问:
How to make link, phone number clickable (Same behaviour as in textview) in a custom view where i draw text?
I made a view and draw text on it and i want that if any text contains link(Hyperlink) or Phone Number It would be clickable (Same Behaviour As in Text View) So how to Achieve it   ?

Code For View In which i am Drawing Text :-

```<code>class DrawRectCellView: UIView {

    var text: NSAttributedString?

    override init(frame: CGRect) {
        super.init(frame: frame)

    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // Only override drawRect: if you perform custom drawing.

    override func draw(_ rect: CGRect)
    {
        UIColor.white.setFill()
        UIGraphicsGetCurrentContext()?.fill(rect)

        // Drawing code

        if let attributedText = text {
            attributedText.draw(in: rect)
        }
    }

}
</code>```

Code For TableCell :-

```<code>class DrawRectCell: UITableViewCell {

    var cellView: DrawRectCellView?

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        // Initialization code
        cellView = DrawRectCellView(frame: self.frame)

        if let cell = cellView {
            cell.autoresizingMask = UIViewAutoresizing(rawValue: UIViewAutoresizing.RawValue(UInt8(UIViewAutoresizing.flexibleWidth.rawValue) | UInt8(UIViewAutoresizing.flexibleHeight.rawValue)))
            cell.contentMode = UIViewContentMode.redraw
        }

        self.contentView.addSubview(cellView!)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setTextString(_ text: NSAttributedString) {
        if let view = cellView {
            view.text = text
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}
</code>```

i am Setting Text like = www.google.com or any phone number its showing as normal text only (Not Showing Like In textview (it makes it clickable))

答:
To highlight certain text within the TextView:

Let's say you have your textView textView, then you can use this code to highlight URLs, phone numbers, etc.:

```<code>textView.dataDetectorTypes = [] // doesn't work if textfield isEditable is set to true
textView.linkTextAttributes = [NSForegroundColorAttributeName: UIColor.blue] // the default is blue anyway
</code>```

If you want to only include some specific data types to be detected, add them to the array like so:

```<code>textView.dataDetectorTypes = [.link]
</code>```

Here's a list of types:

https://developer.apple.com/documentation/uikit/uidatadetectortypes

To make an entire view tappable:

You can add a UITapGestureRecognizer to the view (or not if it does not contain a phone number or hyperlink) like so:

https://stackoverflow.com/a/28675664/7270113

This answer may not be using the Swift version you are using. If so the compiler will tell you how to change it, so it will work.

If you don't like using Selectors, I recommend using the library Closures
https://github.com/vhesener/Closures, specifically with this https://vhesener.github.io/Closures/Extensions/UITapGestureRecognizer.html

Body:
I made a view and draw text on it and i want that if any text contains link(Hyperlink) or Phone Number It would be clickable (Same Behaviour As in Text View) So how to Achieve it   ?

Code For View In which i am Drawing Text :-

class DrawRectCellView: UIView {

    var text: NSAttributedString?

    override init(frame: CGRect) {
        super.init(frame: frame)

    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // Only override drawRect: if you perform custom drawing.

    override func draw(_ rect: CGRect)
    {
        UIColor.white.setFill()
        UIGraphicsGetCurrentContext()?.fill(rect)

        // Drawing code

        if let attributedText = text {
            attributedText.draw(in: rect)
        }
    }

}

Code For TableCell :-

class DrawRectCell: UITableViewCell {

    var cellView: DrawRectCellView?

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        // Initialization code
        cellView = DrawRectCellView(frame: self.frame)

        if let cell = cellView {
            cell.autoresizingMask = UIViewAutoresizing(rawValue: UIViewAutoresizing.RawValue(UInt8(UIViewAutoresizing.flexibleWidth.rawValue) | UInt8(UIViewAutoresizing.flexibleHeight.rawValue)))
            cell.contentMode = UIViewContentMode.redraw
        }

        self.contentView.addSubview(cellView!)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setTextString(_ text: NSAttributedString) {
        if let view = cellView {
            view.text = text
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}

i am Setting Text like = www.google.com or any phone number its showing as normal text only (Not Showing Like In textview (it makes it clickable))

Body:
To highlight certain text within the TextView:

Let's say you have your textView textView, then you can use this code to highlight URLs, phone numbers, etc.:

textView.dataDetectorTypes = [] // doesn't work if textfield isEditable is set to true
textView.linkTextAttributes = [NSForegroundColorAttributeName: UIColor.blue] // the default is blue anyway

If you want to only include some specific data types to be detected, add them to the array like so:

textView.dataDetectorTypes = [.link]

Here's a list of types:

https://developer.apple.com/documentation/uikit/uidatadetectortypes

To make an entire view tappable:

You can add a UITapGestureRecognizer to the view (or not if it does not contain a phone number or hyperlink) like so:

https://stackoverflow.com/a/28675664/7270113

This answer may not be using the Swift version you are using. If so the compiler will tell you how to change it, so it will work.

If you don't like using Selectors, I recommend using the library Closures
https://github.com/vhesener/Closures, specifically with this https://vhesener.github.io/Closures/Extensions/UITapGestureRecognizer.html


来源: stackexchange

问:
how to write if else under return react native
hope you are doing well.

I am stuck in little problem is i want to pass a  tag only if my condition goes true.

for ex:

```<code>render(
   return(
     <View>
         {
          if(data==='test')
            {
              <Text>Hello this is Test Execution </Text>
            }
         }
     </View>
   )
)
</code>```

i want to do exactly like above example.

i get some errors i can't understand what to do so please help me.

Thank you

答:
You could try this:

```<code>render(
   return(
     <View>
         { (data==='test') && <Text>Hello this is Test Execution </Text>}
     </View>
   )
)
</code>```

But I'd suggest the following syntax:

```<code>render(
  if (data === 'test') {
     return (
        <View>
          <Text>Hello this is Test Execution </Text>
        <View>
     )
  }

  return null;
)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
hope you are doing well.

I am stuck in little problem is i want to pass a  tag only if my condition goes true.

for ex:

render(
   return(
     <View>
         {
          if(data==='test')
            {
              <Text>Hello this is Test Execution </Text>
            }
         }
     </View>
   )
)

i want to do exactly like above example.

i get some errors i can't understand what to do so please help me.

Thank you

Body:
You could try this:

render(
   return(
     <View>
         { (data==='test') && <Text>Hello this is Test Execution </Text>}
     </View>
   )
)

But I'd suggest the following syntax:

render(
  if (data === 'test') {
     return (
        <View>
          <Text>Hello this is Test Execution </Text>
        <View>
     )
  }

  return null;
)


问:
Print the values in an array using batch
The following code lists all the folders in a directory sorted by date and prints the latest folder in %a%

```<code>FOR /F "delims=" %%i IN ('dir "directory" /b /ad-h /t:c /od') DO SET a=%%i
echo Most recent subfolder: %a%
</code>```

How do i print the second recent one? I tried using %a[1]% but it did not work.

答:
Here is another method that show you how to populate array dynamically using a counter.

You can for example populate two arrays with names and full paths dynamically while we increment the counter into a loop forindo

@echo off
Title Print the values in an array using batch
Set "MasterFolder=C:\FRST"
Set "RecentFolder="
set /a "count=0"
Setlocal EnableDelayedExpansion
Rem Populate two arrays with names and full paths dynamically while we increment the counter
@FOR /F "delims=" %%a IN ('dir "%MasterFolder%" /b /ad-h /t:c /o-d') DO (
    if not defined RecentFolder (
        set /a "Count+=1"
        set "RecentFolderName[!Count!]=%%~na"
        set "RecentFolderPath[!count!]=%%~fa"
    )
)

Rem Display numbered Folders Names and full paths
color 0A & Mode 90,30 & cls & echo(
@for /L %%i in (1,1,%Count%) do (
   set "RecentName=[%%i] - !RecentFolderName[%%i]!"
   set "RecentFullPath=FullPath - "!RecentFolderPath[%%i]!""
   echo !RecentName!
   echo !RecentFullPath!
   echo --------------------------------------------------
)
Pause
```

Body:
The following code lists all the folders in a directory sorted by date and prints the latest folder in %a%

FOR /F "delims=" %%i IN ('dir "directory" /b /ad-h /t:c /od') DO SET a=%%i
echo Most recent subfolder: %a%

How do i print the second recent one? I tried using %a[1]% but it did not work.


问:
'if' v.s. `while` to a `functools.partial.func`
In Django documentation django.conf.urls | Django documentation | Django

There's such codes:

```<code>class RegexURLPattern(LocaleRegexProvider):
    ...
    def lookup_str(self)
        callback = self.callback
        # Python 3.5 collapses nested partials, so can change "while" to "if"
        # when it's the minimum supported version.
        while isinstance(callback, functools.partial):
            callback = callback.func
        ...
</code>```

The code is to callback the argument of funtion 'view' and execute it.

Why while is better than if excluding 'Python 3.5'?
There is only one callback argument passed in from django.conf.urls.url,which seen in:

```<code>def url(regex, view, kwargs=None, name=None):
    elif callable(view):
        return RegexURLPattern(regex, view, kwargs, name)
</code>```

It seems if is more readable than while.

答:
It's not about number of arguments but about the depth of how many times a callback was wrapped in another callback.

For one iteration, while is the same as if so that doesn't really matter. However, if someone called lookup_str with callback which was itself a callback, while would still just keep on to work.

Body:
In Django documentation django.conf.urls | Django documentation | Django

There's such codes:

class RegexURLPattern(LocaleRegexProvider):
    ...
    def lookup_str(self)
        callback = self.callback
        # Python 3.5 collapses nested partials, so can change "while" to "if"
        # when it's the minimum supported version.
        while isinstance(callback, functools.partial):
            callback = callback.func
        ...

The code is to callback the argument of funtion 'view' and execute it.

Why while is better than if excluding 'Python 3.5'?
There is only one callback argument passed in from django.conf.urls.url,which seen in:

def url(regex, view, kwargs=None, name=None):
    elif callable(view):
        return RegexURLPattern(regex, view, kwargs, name)

It seems if is more readable than while.


问:
How to ad something every third post django
how to put one banner in every third post by one

views

```<code>def all_ads(request):
all_ads = CreateNewAdvert.objects.filter(is_active=True)
all_ads_list = list()
banner = Banners.objects.all()
counter = 0
for i in all_ads:
    if len(all_ads_list) % 3 == 0:
            all_ads_list.append(i)
            all_ads_list = list()
            all_ads_list.append(banner[counter])
    print i
paginator = Paginator(all_ads, 10)  # Show 25 contacts per page
page = request.GET.get('page')
try:
    all_ads_paginated = paginator.page(page)
except PageNotAnInteger:
    # If page is not an integer, deliver first page.
    all_ads_paginated = paginator.page(1)
except EmptyPage:
    # If page is out of range (e.g. 9999), deliver last page of results.
    all_ads_paginated = paginator.page(paginator.num_pages)

context = {
    'all_ads': all_ads_paginated,
}
return context
</code>```

need to get this:
post 1,
post 2,
post 3,
banner 1, post 4,
post 5,
post 6,
banner 2

答:
```<code>def all_ads(request):
all_ads = CreateNewAdvert.objects.filter(is_active=True)

paginator = Paginator(sort_adds(all_ads), 10)  # Show 25 contacts per page
page = request.GET.get('page')
try:
    all_ads_paginated = paginator.page(page)
except PageNotAnInteger:
    # If page is not an integer, deliver first page.
    all_ads_paginated = paginator.page(1)
except EmptyPage:
    # If page is out of range (e.g. 9999), deliver last page of results.
    all_ads_paginated = paginator.page(paginator.num_pages)

context = {
    'all_ads': all_ads_paginated,
}
return context
</code>```

<p>result </p>

```<code>def sort_adds(obj):
sell_adds_list = list()
banner = Banners.objects.all()
counter = 0
adds_counter = 0
for i in obj:
    sell_adds_list.append(i)
    adds_counter += 1
    if adds_counter % 3 == 0:
        if not counter > len(banner):
            sell_adds_list.append(banner[counter])
            counter += 1
        else:
            pass
return sell_adds_list
</code>```

Body:
how to put one banner in every third post by one

views

def all_ads(request):
all_ads = CreateNewAdvert.objects.filter(is_active=True)
all_ads_list = list()
banner = Banners.objects.all()
counter = 0
for i in all_ads:
    if len(all_ads_list) % 3 == 0:
            all_ads_list.append(i)
            all_ads_list = list()
            all_ads_list.append(banner[counter])
    print i
paginator = Paginator(all_ads, 10)  # Show 25 contacts per page
page = request.GET.get('page')
try:
    all_ads_paginated = paginator.page(page)
except PageNotAnInteger:
    # If page is not an integer, deliver first page.
    all_ads_paginated = paginator.page(1)
except EmptyPage:
    # If page is out of range (e.g. 9999), deliver last page of results.
    all_ads_paginated = paginator.page(paginator.num_pages)

context = {
    'all_ads': all_ads_paginated,
}
return context

need to get this:
post 1,
post 2,
post 3,
banner 1, post 4,
post 5,
post 6,
banner 2

Body:
def all_ads(request):
all_ads = CreateNewAdvert.objects.filter(is_active=True)

paginator = Paginator(sort_adds(all_ads), 10)  # Show 25 contacts per page
page = request.GET.get('page')
try:
    all_ads_paginated = paginator.page(page)
except PageNotAnInteger:
    # If page is not an integer, deliver first page.
    all_ads_paginated = paginator.page(1)
except EmptyPage:
    # If page is out of range (e.g. 9999), deliver last page of results.
    all_ads_paginated = paginator.page(paginator.num_pages)

context = {
    'all_ads': all_ads_paginated,
}
return context

result

def sort_adds(obj):
sell_adds_list = list()
banner = Banners.objects.all()
counter = 0
adds_counter = 0
for i in obj:
    sell_adds_list.append(i)
    adds_counter += 1
    if adds_counter % 3 == 0:
        if not counter > len(banner):
            sell_adds_list.append(banner[counter])
            counter += 1
        else:
            pass
return sell_adds_list


问:
Issue with HTTP Handlers and IIS7
I've been developing a custom HTTP handler. Using the new web.config <httphandlers> section for ASP.NET 4.0 and IIS7, this works great on my development machine.

However, when I upload the code to my shared-hosting account, I get a 500 server error. I called my hosting company and they said the server was reporting an error about a web.config setting being detected that does not apply to integrated pipeline mode.

When he switched IIS from integrated to classic mode, the home page then loads okay but my routed pages all report a 403 server error.

I'm pretty sure I need integrated mode in order for the <httphandlers> section to work, but I am definitely not an IIS/admin guy. Does anyone have any idea what the problem might be or what I can try next?

EDIT: The bulk of my updated web.config:

```<code><?xml version="1.0"?>
<configuration>
    <connectionStrings>
        [...]
    </connectionStrings>
    <appSettings>
        [...]
    </appSettings>
    <system.web>
        <httpHandlers>
            <add verb="*" path="*.zip" type="BlackBelt.ZipHttpHandler"/>
        </httpHandlers>
        <compilation debug="false" targetFramework="4.0"/>
    </system.web>
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
        <handlers>
            <add verb="*" path="BlackBelt.ZipHttpHandler" name="BlackBelt.ZipHttpHandler" type="BlackBelt.ZipHttpHandler"/>
        </handlers>
        <!-- Redirect domain.com to www.domain.com -->
        <rewrite>
            <rules>
                <clear/>
                <rule name="WWW Rewrite" enabled="true">
                    <match url="(.*)"/>
                    <conditions>
                        <add input="{HTTP_HOST}" negate="true" pattern="^www\.([.a-zA-Z0-9]+)$"/>
                    </conditions>
                    <action type="Redirect" url="http://www.{HTTP_HOST}/{R:0}" appendQueryString="true" redirectType="Permanent"/>
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>
</code>```

答:
Thanks to Pauli, I was able to figure this out. Although <system.web><httpHandlers> is the section I must change to get it to work when running from Visual Studio, <system.webServer><handlers> is the section I must modify to get it to work when running on the server, which is running IIS7.

I've received email asking exactly how I resolved this. I've written an article that describes the exact steps and presents my code. If anyone wants to see this article, it is available at http://www.blackbeltcoder.com/Articles/asp/writing-a-custom-http-handler-in-asp-net.

ContentLicense: CC BY-SA 2.5

Title: Issue with HTTP Handlers and IIS7

Body:
I've been developing a custom HTTP handler. Using the new web.config <httphandlers> section for ASP.NET 4.0 and IIS7, this works great on my development machine.

However, when I upload the code to my shared-hosting account, I get a 500 server error. I called my hosting company and they said the server was reporting an error about a web.config setting being detected that does not apply to integrated pipeline mode.

When he switched IIS from integrated to classic mode, the home page then loads okay but my routed pages all report a 403 server error.

I'm pretty sure I need integrated mode in order for the <httphandlers> section to work, but I am definitely not an IIS/admin guy. Does anyone have any idea what the problem might be or what I can try next?

EDIT: The bulk of my updated web.config:

<?xml version="1.0"?>
<configuration>
    <connectionStrings>
        [...]
    </connectionStrings>
    <appSettings>
        [...]
    </appSettings>
    <system.web>
        <httpHandlers>
            <add verb="*" path="*.zip" type="BlackBelt.ZipHttpHandler"/>
        </httpHandlers>
        <compilation debug="false" targetFramework="4.0"/>
    </system.web>
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
        <handlers>
            <add verb="*" path="BlackBelt.ZipHttpHandler" name="BlackBelt.ZipHttpHandler" type="BlackBelt.ZipHttpHandler"/>
        </handlers>

        <rewrite>
            <rules>
                <clear/>
                <rule name="WWW Rewrite" enabled="true">
                    <match url="(.*)"/>
                    <conditions>
                        <add input="{HTTP_HOST}" negate="true" pattern="^www\.([.a-zA-Z0-9]+)$"/>
                    </conditions>
                    <action type="Redirect" url="http://www.{HTTP_HOST}/{R:0}" appendQueryString="true" redirectType="Permanent"/>
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>


答:
You can do like this</p>

```<code>return(){
    <View>
    {data === 'test' && <Text>Hello this is Test Execution </Text>}
    </View>
}
</code>```

Title: how to write if else under return react native

Body:
You can do like this

return(){
    <View>
    {data === 'test' && <Text>Hello this is Test Execution </Text>}
    </View>
}


答:
You can try like

```<code>{(data === 'test')  && <Text>Hello this is Test Execution</Text>}
</code>```

Hope this will help.

Body:
You can try like

{(data === 'test')  && <Text>Hello this is Test Execution</Text>}

Hope this will help.


问:
Avoid loading a transitively dependent module
I am compiling my legacy source code using JDK 9.0.1 as follows:

```<code>javac --add-modules=java.base,java.xml.ws -cp lib\jsr305.jar;lib\javax.annotation-api-1.2.jar TestJava.java
</code>```

It gives an error because the annotations defined in jsr305.jar are not visible due to split module issue. The error is as follows:

```<code>TestJava.java:3: error: cannot find symbol
import javax.annotation.Nonnull;
                       ^
  symbol:   class Nonnull
  location: package javax.annotation
</code>```

Here the module java.xml.ws.annotation is getting loaded since it is required for java.xml.ws. So it is ignoring the types in jsr305.jar. I don't want this module to be loaded but refer all its annotation types from javax.annotation-api-1.2.jar. I don't want to do --patch-module either because it would break in future releases.

If I use --limit-module=java.xml.ws.annotation it gives the same error. If I remove java.xml.ws from -add-modules, it compiles successfully but I need to export few APIs from it so can't remove it. Is there any way I can load module java.xml.ws but not java.xml.ws.annotation?

EDIT : I think I have added some confusion by giving an example of split between java.xml.ws.annotaion and jsr305.jar. Though it's my actual problem, I am more interested in knowing - can I avoid loading a transitively dependent module, say loading java.xml.ws without loading java.xml.ws.annotation? As per my understanding in JEP 261 it says,

--limit-modules <module>(,<module>)*

where <module> is a module name. The effect of this option is to limit
  the observable modules to those in the transitive closure of the named
  modules plus the main module, if any, plus any further modules
  specified via the --add-modules option.

So, why isn't --limit-module preventing java.xml.ws.annotation from loading?

答:
I know of no way to prevent resolution of a transitive dependency.

Short-term fix

You should be able to make it work by patching the module with --patch-module java.xml.ws=lib\jsr305.jar:lib\javax.annotation-api-1.2.jar. My opinion: If you just want to get your build working on Java 9, that is a good choice. It's a little dubious but still acceptable if you want to use it in production.

If you're worried about long-term compatibility:

I don't think --patch-module will disappear any time soon - do you have a source for that?

I'm pretty sure java.xml.ws will be removed quite soon - it is already deprecated for removal.

In your place I'd worry about the module more than about patching it.

Long-term solution

So for a long-term solution you should remove your dependency on java.xml.ws. JDK-8189188 has a section on this (with lots of links that I was too lazy to copy):

The Reference Implementations (RIs) of JAX-WS and JAXB are a good starting point because they are complete replacements for the java.xml.ws and java.xml.bind modules in JDK 9. The RIs are available as Maven artifacts: (note that they must be deployed on the classpath)

com.sun.xml.ws : jaxws-ri (JAX-WS, plus SAAJ and Web Services Metadata)

com.sun.xml.bind : jaxb-ri (JAXB)

The tools for JAX-WS and JAXB are also available as Maven artifacts:

wsgen and wsimport: com.sun.xml.ws : jaxws-tools, plus tool scripts

schemagen and xjc: com.sun.xml.bind : jaxb-jxc and com.sun.xml.bind : jaxb-xjc, plus tool scripts

There are also Maven artifacts that contain just the APIs of the Java EE technologies:

javax.xml.ws : jaxws-api (JAX-WS, plus javax.xml.soap : javax.xml.soap-api for SAAJ and javax.xml : webservices-api for Web Services Metadata)

javax.xml.bind : jaxb-api (JAXB)

javax.activation : javax.activation-api (JAF)

javax.annotation : javax.annotation-api (Common Annotations)

Adding either the API JARs or the reference implementations to your class path together with all other javax.annotation-related JARs will work because all class path content ends up in the same module (the unnamed one) and thus split packages are no problem there.

Body:
I am compiling my legacy source code using JDK 9.0.1 as follows:

javac --add-modules=java.base,java.xml.ws -cp lib\jsr305.jar;lib\javax.annotation-api-1.2.jar TestJava.java

It gives an error because the annotations defined in jsr305.jar are not visible due to split module issue. The error is as follows:

TestJava.java:3: error: cannot find symbol
import javax.annotation.Nonnull;
                       ^
  symbol:   class Nonnull
  location: package javax.annotation

Here the module java.xml.ws.annotation is getting loaded since it is required for java.xml.ws. So it is ignoring the types in jsr305.jar. I don't want this module to be loaded but refer all its annotation types from javax.annotation-api-1.2.jar. I don't want to do --patch-module either because it would break in future releases.

If I use --limit-module=java.xml.ws.annotation it gives the same error. If I remove java.xml.ws from -add-modules, it compiles successfully but I need to export few APIs from it so can't remove it. Is there any way I can load module java.xml.ws but not java.xml.ws.annotation?

EDIT : I think I have added some confusion by giving an example of split between java.xml.ws.annotaion and jsr305.jar. Though it's my actual problem, I am more interested in knowing - can I avoid loading a transitively dependent module, say loading java.xml.ws without loading java.xml.ws.annotation? As per my understanding in JEP 261 it says,

--limit-modules <module>(,<module>)*

where <module> is a module name. The effect of this option is to limit
  the observable modules to those in the transitive closure of the named
  modules plus the main module, if any, plus any further modules
  specified via the --add-modules option.

So, why isn't --limit-module preventing java.xml.ws.annotation from loading?


问:
Falling object with acceleration in canvas like in gravity environment?
I have a canvas with border inside

```<code><Canvas x:Name="mainCanvas" ManipulationMode="None" Margin="0,12,0,0" MinHeight="400">
     <Border x:Name="manipulateMe" Background="LightGray" Height="200" Width="200"  ManipulationMode="All"/>
</Canvas>
</code>```

I already implemented manipulation function on it. Then I need it always falling down like things on air. Is there any simple way?

Beside, I also want handle the animation when it touch the ground : bounce, rolling ... base on its shape. Do I need a game engine, framework or some thing like that?

答:
Then I need it always falling down like things on air.

If you just want a falling down effect, you could animate the element with TranslateTransform to along Y coordinate. For example:

```<code><StackPanel Margin="15">
   <StackPanel.Resources>
       <Storyboard x:Name="myStoryboard">
           <DoubleAnimation
               RepeatBehavior="Forever"
               Storyboard.TargetName="myTranslateTransform"
               Storyboard.TargetProperty="Y"
               From="0"
               To="360"
               Duration="0:0:5" />
       </Storyboard>
   </StackPanel.Resources>
   <Rectangle
       Width="50"
       Height="50"
       Fill="RoyalBlue"
       PointerPressed="StartAnimation">
       <Rectangle.RenderTransform>
           <TranslateTransform x:Name="myTranslateTransform"  />
       </Rectangle.RenderTransform>
   </Rectangle>
</StackPanel>

private void StartAnimation(object sender, PointerRoutedEventArgs e)
{
    myStoryboard.Begin();
}
</code>```

More details about transform please reference this article.

Beside, I also want handle the animation when it touch the ground : bounce, rolling ... base on its shape.

For bounce effects you could use BounceEase, one of the Easing functions. For rolling you could use RotateTransform combine with TranslateTransform. For how to combine two animations please reference this article.

For a conclusion, you can find many animations you want in UWP animation library. Please reference Animations overview. If this cannot meet your requirements, you may consider to use Composition animations. For samples you can reference WindowsUIDevLabs.

Body:
I have a canvas with border inside

<Canvas x:Name="mainCanvas" ManipulationMode="None" Margin="0,12,0,0" MinHeight="400">
     <Border x:Name="manipulateMe" Background="LightGray" Height="200" Width="200"  ManipulationMode="All"/>
</Canvas>

I already implemented manipulation function on it. Then I need it always falling down like things on air. Is there any simple way?

Beside, I also want handle the animation when it touch the ground : bounce, rolling ... base on its shape. Do I need a game engine, framework or some thing like that?

Body:
Then I need it always falling down like things on air.

If you just want a falling down effect, you could animate the element with TranslateTransform to along Y coordinate. For example:

<StackPanel Margin="15">
   <StackPanel.Resources>
       <Storyboard x:Name="myStoryboard">
           <DoubleAnimation
               RepeatBehavior="Forever"
               Storyboard.TargetName="myTranslateTransform"
               Storyboard.TargetProperty="Y"
               From="0"
               To="360"
               Duration="0:0:5" />
       </Storyboard>
   </StackPanel.Resources>
   <Rectangle
       Width="50"
       Height="50"
       Fill="RoyalBlue"
       PointerPressed="StartAnimation">
       <Rectangle.RenderTransform>
           <TranslateTransform x:Name="myTranslateTransform"  />
       </Rectangle.RenderTransform>
   </Rectangle>
</StackPanel>

private void StartAnimation(object sender, PointerRoutedEventArgs e)
{
    myStoryboard.Begin();
}

More details about transform please reference this article.

Beside, I also want handle the animation when it touch the ground : bounce, rolling ... base on its shape.

For bounce effects you could use BounceEase, one of the Easing functions. For rolling you could use RotateTransform combine with TranslateTransform. For how to combine two animations please reference this article.

For a conclusion, you can find many animations you want in UWP animation library. Please reference Animations overview. If this cannot meet your requirements, you may consider to use Composition animations. For samples you can reference WindowsUIDevLabs.


问:
PHP Session Across Subdomains
I have a PHP 7 app running on Azure where clients move between multiple subdomains on the app but access the same web site. The subdomains differentiate companies, with one user associated with multiple companies. The user's info is tracked across those domains using a cookie.

My issue is, despite having the same cookie ID present on both subdomains, if I store info in the cookie on a.example.com, and then load the same page and cookie on b.example.com, it doesn't show that information. Inline with previous answers on SO, I am setting the cookie to be valid for / on .example.com.

I did having instance scaling turned on for my application, and thinking perhaps that was causing issues, I turned it off. But even with one instance, Azure still has two different hosts serving requests for different domains - although the same instance and thus should be the same shared session.

I'm using the code below on as a page I access on both subdomains that should be printing out all the subdomains I've visited with the cookie, but it only shows the current domain.

```<code>$currentCookieParams = session_get_cookie_params();

$serverParts = explode('.', $_SERVER['HTTP_HOST']);
$serverPartsCount = sizeof($serverParts);

session_set_cookie_params(
    time() + 315360000, //(10 * 365 * 24 * 60 * 60),
    '/',
    '.'.$serverParts[$serverPartsCount-2].'.'.$serverParts[$serverPartsCount-1], //equates to '.mydomain.com'
    TRUE,
    $currentCookieParams["httponly"]
);

session_start();

//use an array to track every subdomain we visit with this cookie
if (!isset($_SESSION['visitedDomains']))
{
    $_SESSION['visitedDomains'] = [];
}
$_SESSION['visitedDomains'][$_SERVER['HTTP_HOST']] = 'visited';

//show the cookie id
var_dump(session_id());
echo '<br><br>';

//the hostname of the machine serving this request
var_dump(gethostname());
echo '<br><br>';

//what should be a list of all domains visited using this cookie
var_dump($_SESSION['visitedDomains']);
echo '<br><br>';

//cookie params
var_dump(session_get_cookie_params());
</code>```

答:
You'd need to set session.cookie_secure to FLASE. Make it like so:

```<code>session_set_cookie_params(
    time() + 315360000, //(10 * 365 * 24 * 60 * 60),
    '/',
    '.'.$serverParts[$serverPartsCount-2].'.'.$serverParts[$serverPartsCount-1], //equates to '.mydomain.com'
    FLASE,
    $currentCookieParams["httponly"]
);
</code>```

It works fine for me:

I'm using the code below:

```<code><?php

$currentCookieParams = session_get_cookie_params();

$serverParts = explode('.', $_SERVER['HTTP_HOST']);
$serverPartsCount = sizeof($serverParts);

echo '.'.$serverParts[$serverPartsCount-2].'.'.$serverParts[$serverPartsCount-1];
echo '<br><br>';

session_set_cookie_params(
    time() + 315360000, //(10 * 365 * 24 * 60 * 60),
    '/',
    '.'.$serverParts[$serverPartsCount-2].'.'.$serverParts[$serverPartsCount-1], //equates to '.mydomain.com'
    FALSE,
    $currentCookieParams["httponly"]
);

session_start();

//use an array to track every subdomain we visit with this cookie
if (!isset($_SESSION['visitedDomains']))
{
    $_SESSION['visitedDomains'] = [];
}

$_SESSION['visitedDomains'][$_SERVER['HTTP_HOST']] = 'visited';

//show the cookie id
var_dump(session_id());
echo '<br><br>';

//the hostname of the machine serving this request
var_dump(gethostname());
echo '<br><br>';

//what should be a list of all domains visited using this cookie
var_dump($_SESSION['visitedDomains']);
echo '<br><br>';

//cookie params
var_dump(session_get_cookie_params());
</code>```

Title: PHP Session Across Subdomains

Body:
I have a PHP 7 app running on Azure where clients move between multiple subdomains on the app but access the same web site. The subdomains differentiate companies, with one user associated with multiple companies. The user's info is tracked across those domains using a cookie.

My issue is, despite having the same cookie ID present on both subdomains, if I store info in the cookie on a.example.com, and then load the same page and cookie on b.example.com, it doesn't show that information. Inline with previous answers on SO, I am setting the cookie to be valid for / on .example.com.

I did having instance scaling turned on for my application, and thinking perhaps that was causing issues, I turned it off. But even with one instance, Azure still has two different hosts serving requests for different domains - although the same instance and thus should be the same shared session.

I'm using the code below on as a page I access on both subdomains that should be printing out all the subdomains I've visited with the cookie, but it only shows the current domain.

$currentCookieParams = session_get_cookie_params();

$serverParts = explode('.', $_SERVER['HTTP_HOST']);
$serverPartsCount = sizeof($serverParts);

session_set_cookie_params(
    time() + 315360000, //(10 * 365 * 24 * 60 * 60),
    '/',
    '.'.$serverParts[$serverPartsCount-2].'.'.$serverParts[$serverPartsCount-1], //equates to '.mydomain.com'
    TRUE,
    $currentCookieParams["httponly"]
);

session_start();

//use an array to track every subdomain we visit with this cookie
if (!isset($_SESSION['visitedDomains']))
{
    $_SESSION['visitedDomains'] = [];
}
$_SESSION['visitedDomains'][$_SERVER['HTTP_HOST']] = 'visited';

//show the cookie id
var_dump(session_id());
echo '

';

//the hostname of the machine serving this request
var_dump(gethostname());
echo '

';

//what should be a list of all domains visited using this cookie
var_dump($_SESSION['visitedDomains']);
echo '

';

//cookie params
var_dump(session_get_cookie_params());

Body:
You'd need to set session.cookie_secure to FLASE. Make it like so:

session_set_cookie_params(
    time() + 315360000, //(10 * 365 * 24 * 60 * 60),
    '/',
    '.'.$serverParts[$serverPartsCount-2].'.'.$serverParts[$serverPartsCount-1], //equates to '.mydomain.com'
    FLASE,
    $currentCookieParams["httponly"]
);

It works fine for me:

I'm using the code below:

<?php

$currentCookieParams = session_get_cookie_params();

$serverParts = explode('.', $_SERVER['HTTP_HOST']);
$serverPartsCount = sizeof($serverParts);

echo '.'.$serverParts[$serverPartsCount-2].'.'.$serverParts[$serverPartsCount-1];
echo '<br><br>';

session_set_cookie_params(
    time() + 315360000, //(10 * 365 * 24 * 60 * 60),
    '/',
    '.'.$serverParts[$serverPartsCount-2].'.'.$serverParts[$serverPartsCount-1], //equates to '.mydomain.com'
    FALSE,
    $currentCookieParams["httponly"]
);

session_start();

//use an array to track every subdomain we visit with this cookie
if (!isset($_SESSION['visitedDomains']))
{
    $_SESSION['visitedDomains'] = [];
}

$_SESSION['visitedDomains'][$_SERVER['HTTP_HOST']] = 'visited';

//show the cookie id
var_dump(session_id());
echo '<br><br>';

//the hostname of the machine serving this request
var_dump(gethostname());
echo '<br><br>';

//what should be a list of all domains visited using this cookie
var_dump($_SESSION['visitedDomains']);
echo '<br><br>';

//cookie params
var_dump(session_get_cookie_params());


问:
Map in Dart is replacing the values of previous keys with the last updated value
I am actually working with maps in Dart and I couldn't figure out why the map variable in my example is behaving strangely or I am doing something wrong in my code.

Please can someone help me to debug the code, I have posted the code to reproduce the issue.

example.dart

```<code>void main() {
  var data2 = {};
  var data1 = {};

  var floorDetails = new Map();
  floorDetails.clear();
  for (int i = 0; i < 2; i++) {
    data2.clear();
    data1.clear();
    for (int j = 0; j < 2; j++) {
      data1 = {
        'flat${(i + 1) * 100 + (j + 1)}': {'flattype': "flat"},
      };
      data2.addAll(data1);
    }
    print('data2=$data2');

    floorDetails['floor${(i+1)}'] = data2;

    print('floorDetails = $floorDetails');
  }

  print(floorDetails.keys);
}
</code>```

The output from the code is:

```<code>floorDetails = {
  floor1: {
    flat201: {flattype: flat},
    flat202: {flattype: flat}
  },
  floor2: {
    flat201: {flattype: flat},
    flat202: {flattype: flat}
  }
}
</code>```

Actually I was expecting the output to be:

```<code>floorDetails = {
  floor1: {
    flat101: {flattype: flat},
    flat102: {flattype: flat}
  },
  floor2: {
    flat201: {flattype: flat},
    flat202: {flattype: flat}
  }
}
</code>```

this is actually overwriting the values of all the keys inside the map floorDetails as per documentation for Map.addAll() method

```<code>void addAll(
  Map<K, V> other
)
</code>```

Adds all key-value pairs of other to this map.

If a key of other is already in this map, its value is overwritten.

The operation is equivalent to doing this[key] = value for each key and associated value in other. It iterates over other, which must therefore not change during the iteration.

although in the given example the keys are different but it is still overwriting the values.

Please, any help would be much appreciated.
Many Thanks,
Mahi

答:
In the first iteration, here you assign data2

```<code>floorDetails['floor${(i+1)}'] = data2;
</code>```

but the first line in the next iteration is

```<code>data2.clear();
</code>```

which clears data2. This also clears the content of floorDetails['floor1']`, because it references the same map.

Either you create a new map, instead of clearing it by changing

```<code>data2.clear();
data1.clear();
</code>```

to

```<code>data2 = {}; // or new Map()
data1 = {};
</code>```

or create a copy of the map before assigning it

```<code>floorDetails['floor${(i+1)}'] = new Map.from(data2);
</code>```

Map is an object and copied by reference. Only primitive types like bool, double, int, and String are copied by value.

ContentLicense: CC BY-SA 4.0

Body:
I am actually working with maps in Dart and I couldn't figure out why the map variable in my example is behaving strangely or I am doing something wrong in my code.

Please can someone help me to debug the code, I have posted the code to reproduce the issue.

example.dart

void main() {
  var data2 = {};
  var data1 = {};

  var floorDetails = new Map();
  floorDetails.clear();
  for (int i = 0; i < 2; i++) {
    data2.clear();
    data1.clear();
    for (int j = 0; j < 2; j++) {
      data1 = {
        'flat${(i + 1) * 100 + (j + 1)}': {'flattype': "flat"},
      };
      data2.addAll(data1);
    }
    print('data2=$data2');

    floorDetails['floor${(i+1)}'] = data2;

    print('floorDetails = $floorDetails');
  }

  print(floorDetails.keys);
}

The output from the code is:

floorDetails = {
  floor1: {
    flat201: {flattype: flat},
    flat202: {flattype: flat}
  },
  floor2: {
    flat201: {flattype: flat},
    flat202: {flattype: flat}
  }
}

Actually I was expecting the output to be:

floorDetails = {
  floor1: {
    flat101: {flattype: flat},
    flat102: {flattype: flat}
  },
  floor2: {
    flat201: {flattype: flat},
    flat202: {flattype: flat}
  }
}

this is actually overwriting the values of all the keys inside the map floorDetails as per documentation for Map.addAll() method

void addAll(
  Map<K, V> other
)

Adds all key-value pairs of other to this map.

If a key of other is already in this map, its value is overwritten.

The operation is equivalent to doing this[key] = value for each key and associated value in other. It iterates over other, which must therefore not change during the iteration.

although in the given example the keys are different but it is still overwriting the values.

Please, any help would be much appreciated.
Many Thanks,
Mahi

Body:
In the first iteration, here you assign data2

floorDetails['floor${(i+1)}'] = data2;

but the first line in the next iteration is

data2.clear();

which clears data2. This also clears the content of floorDetails['floor1']`, because it references the same map.

Either you create a new map, instead of clearing it by changing

data2.clear();
data1.clear();

to

data2 = {}; // or new Map()
data1 = {};

or create a copy of the map before assigning it

floorDetails['floor${(i+1)}'] = new Map.from(data2);

Map is an object and copied by reference. Only primitive types like bool, double, int, and String are copied by value.


问:
How to incrementally increase all tuples within the same dictionary
I have a dictionary which generates a "map"
e.g. tuple (x, y) : mapTile

```<code>mapGenCode = {(1, 1): 0, (2, 1): 1, (3, 1): 0, (1, 2): 0, (2, 2): 2, (3, 2): 1}
</code>```

What I'm trying to achieve is when an keyboard arrow is pushed all the x/y values within the same dictionary are incremented by +1/-1

```<code>if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            x_loc = x_loc-1
            x_map -1

mapRefresh(x_map, y_map)

def mapRefresh(x, y):

    if x == -1:
        for (key1, key2), value in mapGenCode.iteritems():
            newkeyX = key1 -1
            mapGenCode[newKey1, key2] = value
</code>```

I have previously run into this error

```<code>runtimeerror: dictionary changed size during iteration
</code>```

答:
Instead of "for key, value in dic", you can consider following code</p>

```<code>while key in dic:
    func()
    key += 1
</code>```

Body:
I have a dictionary which generates a "map"
e.g. tuple (x, y) : mapTile

mapGenCode = {(1, 1): 0, (2, 1): 1, (3, 1): 0, (1, 2): 0, (2, 2): 2, (3, 2): 1}

What I'm trying to achieve is when an keyboard arrow is pushed all the x/y values within the same dictionary are incremented by +1/-1

if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            x_loc = x_loc-1
            x_map -1

mapRefresh(x_map, y_map)

def mapRefresh(x, y):

    if x == -1:
        for (key1, key2), value in mapGenCode.iteritems():
            newkeyX = key1 -1
            mapGenCode[newKey1, key2] = value

I have previously run into this error

runtimeerror: dictionary changed size during iteration

Body:
Instead of "for key, value in dic", you can consider following code

while key in dic:
    func()
    key += 1


问:
Fetching multiple rows by foreign key column
I have an Address table that contains multiple addresses

```<code>Address:
| Id   |   details   | ... |
 - - - - - - - - -  - - - - - - -
| 1    |  details |    ...        |
| 2    |  details |    ...        |
| 3    |  details |    ...        |
| 4    |  details |    ...        |
</code>```

Then i have a site table, that contains address.id as FK to represent Billing or Shipping address,

```<code>Site:
| Id   |   details   | Ship_Address_id  |  Bill_Address_id | ... |
 - - - - - - - - -  - - - - - - -
| 1    |  details |          1           |        2          |     |
| 2    |  details |          1           |        3          |     |
| 3    |  details |          4           |        4          |     |
| 4    |  details |          2           |        3          |     |
</code>```

is there a way to join both the tables so that single row from site table may fetch two rows of address table, even in the case of same address of both columns.
i was expecting to use multiple join of site with address but that is not working:

This is what i tried:

```<code>SELECT CASE
        WHEN ship.CRM_Address_Internal_Id_Ship IS NOT NULL THEN 'Ship'
        WHEN bill.CRM_Address_Internal_Id_Ship IS NOT NULL THEN 'Bill'
        ELSE '' END
FROM Address as Adr
LEFT JOIN Site ship ON ship.Ship_Address_id = Adr.id
LEFT JOIN Site bill ON bill.Bill_Address_id = Adr.id
</code>```

Even if i don't use the CASE it does not fetch two rows for each address with respect to site.

Please advise.

EDIT
Here is the desired output table:
as in Site table we have two different ids of address table (Ship/Bill) so the result table should display two rows for each site.id

for example i'm fetching records for site.id 1 and 3 then

```<code>Result_Table:
| Address.ID | Address Details | TYPE | ... |
--------------------------------------------
| 1         | Other Details    | Ship | ... |
| 2         | Other Details    | Bill | ... |
| 4         | Other Details    | Ship | ... |
| 4         | Other Details    | Bill | ... |
</code>```

答:
There are various ways to do this. This is an example that I implemented by UNPIVOT, you can take a look as references:

```<code>declare @address table(id int, details nvarchar(100))
declare @site table(id int, details nvarchar(100), ship_address_id int, bill_address_id int)

insert into @address values(1,'details 1')
insert into @address values(2,'details 2')
insert into @address values(3,'details 3')
insert into @address values(4,'details 4')

insert into @site values(1,'details 1',1,2)
insert into @site values(2,'details 1',1,3)
insert into @site values(3,'details 1',4,4)
insert into @site values(4,'details 1',2,5)

SELECT *
FROM (
    SELECT s.id as site_id, s.bill_address_id, s.ship_address_id
    FROM @Site AS s
    INNER JOIN @Address AS sa ON s.Ship_Address_id = sa.Id
    INNER JOIN @Address AS ba ON s.Bill_Address_id = ba.Id
    WHERE s.id in (1,3)) p
UNPIVOT
     (address_id FOR address_type IN
      (Ship_Address_id, Bill_Address_id)
) AS unpvt
</code>```

Output

```<code>site_id     address_id  address_type
1           1           ship_address_id
1           2           bill_address_id
3           4           ship_address_id
3           4           bill_address_id
</code>```

Body:
I have an Address table that contains multiple addresses

Address:
| Id   |   details   | ... |
 - - - - - - - - -  - - - - - - -
| 1    |  details |    ...        |
| 2    |  details |    ...        |
| 3    |  details |    ...        |
| 4    |  details |    ...        |

Then i have a site table, that contains address.id as FK to represent Billing or Shipping address,

Site:
| Id   |   details   | Ship_Address_id  |  Bill_Address_id | ... |
 - - - - - - - - -  - - - - - - -
| 1    |  details |          1           |        2          |     |
| 2    |  details |          1           |        3          |     |
| 3    |  details |          4           |        4          |     |
| 4    |  details |          2           |        3          |     |

is there a way to join both the tables so that single row from site table may fetch two rows of address table, even in the case of same address of both columns.
i was expecting to use multiple join of site with address but that is not working:

This is what i tried:

SELECT CASE
        WHEN ship.CRM_Address_Internal_Id_Ship IS NOT NULL THEN 'Ship'
        WHEN bill.CRM_Address_Internal_Id_Ship IS NOT NULL THEN 'Bill'
        ELSE '' END
FROM Address as Adr
LEFT JOIN Site ship ON ship.Ship_Address_id = Adr.id
LEFT JOIN Site bill ON bill.Bill_Address_id = Adr.id

Even if i don't use the CASE it does not fetch two rows for each address with respect to site.

Please advise.

EDIT
Here is the desired output table:
as in Site table we have two different ids of address table (Ship/Bill) so the result table should display two rows for each site.id

for example i'm fetching records for site.id 1 and 3 then

Result_Table:
| Address.ID | Address Details | TYPE | ... |
--------------------------------------------
| 1         | Other Details    | Ship | ... |
| 2         | Other Details    | Bill | ... |
| 4         | Other Details    | Ship | ... |
| 4         | Other Details    | Bill | ... |

Body:
There are various ways to do this. This is an example that I implemented by UNPIVOT, you can take a look as references:

declare @address table(id int, details nvarchar(100))
declare @site table(id int, details nvarchar(100), ship_address_id int, bill_address_id int)

insert into @address values(1,'details 1')
insert into @address values(2,'details 2')
insert into @address values(3,'details 3')
insert into @address values(4,'details 4')

insert into @site values(1,'details 1',1,2)
insert into @site values(2,'details 1',1,3)
insert into @site values(3,'details 1',4,4)
insert into @site values(4,'details 1',2,5)

SELECT *
FROM (
    SELECT s.id as site_id, s.bill_address_id, s.ship_address_id
    FROM @Site AS s
    INNER JOIN @Address AS sa ON s.Ship_Address_id = sa.Id
    INNER JOIN @Address AS ba ON s.Bill_Address_id = ba.Id
    WHERE s.id in (1,3)) p
UNPIVOT
     (address_id FOR address_type IN
      (Ship_Address_id, Bill_Address_id)
) AS unpvt

Output

site_id     address_id  address_type
1           1           ship_address_id
1           2           bill_address_id
3           4           ship_address_id
3           4           bill_address_id


问:
mvc download file outside the app folder
im trying to get a file outside of my application folder to download...

```<code>public FilePathResult DownloadFile(Guid id, string dateiname)
    {
        string pfad = @"D:\wwwroot\portal_Daten\";

        return File(pfad + dateiname, "application/pdf", dateiname);
    }
</code>```

Errormessage: is a D:\wwwroot\portal_Daten\8/0/6/a/e/974-aaca-426c-b7fc-e6af6c0fb52e/oeffentlich is a physical path, but it was a virtual path expected.

Why can't this work with a physical path? How can i make this to a virtual path?

Regards,
float

答:
The way I have handled this in the path is to use a custom file download http handler (for an asp.net webforms application) and you could use the same here. You could even construct a new sub-class of ActionResult which might net you the same result.

The way I did this was to create an implementation of IHttpHandler, handle the request and return the file. This way you're not restricted to using virtual paths and, as long as your web server security configuration allows, you will be able to access any file on your system and return that to the browser.

Something like:

```<code>public class MyFileHandler : IHttpHandler
{
  public bool IsReusable
  {
    get { return true; }
  }

  public void ProcessRequest(HttpContext context)
  {
    string filePath = Path.Combine(@"d:\wwwroot\portal_daten", context.Request.QueryString["dateiname"]);

    context.Response.ContentType = "application/pdf";
    context.Response.WriteFile(filePath);
  }
}
</code>```

A stripped down example with no checking, but that's for you to fill in. Then register the handler in your web.config:

```<code><handlers>
  <add name="MyFileHandler" path="file.axd" type="MvcApplication4.Models.MyFileHandler" verb="GET" />
</handlers>
</code>```

You will of course have to rename classes/namespaces to suit yourself. The actual web link to the file then becomes:

```<code>http://[domain]/file.axd?dateiname=mypdf.pdf
</code>```

Where [domain] is your domain name/localhost or whatever you're using.

Body:
im trying to get a file outside of my application folder to download...

public FilePathResult DownloadFile(Guid id, string dateiname)
    {
        string pfad = @"D:\wwwroot\portal_Daten\";

        return File(pfad + dateiname, "application/pdf", dateiname);
    }

Errormessage: is a D:\wwwroot\portal_Daten\8/0/6/a/e/974-aaca-426c-b7fc-e6af6c0fb52e/oeffentlich is a physical path, but it was a virtual path expected.

Why can't this work with a physical path? How can i make this to a virtual path?

Regards,
float

Body:
The way I have handled this in the path is to use a custom file download http handler (for an asp.net webforms application) and you could use the same here. You could even construct a new sub-class of ActionResult which might net you the same result.

The way I did this was to create an implementation of IHttpHandler, handle the request and return the file. This way you're not restricted to using virtual paths and, as long as your web server security configuration allows, you will be able to access any file on your system and return that to the browser.

Something like:

public class MyFileHandler : IHttpHandler
{
  public bool IsReusable
  {
    get { return true; }
  }

  public void ProcessRequest(HttpContext context)
  {
    string filePath = Path.Combine(@"d:\wwwroot\portal_daten", context.Request.QueryString["dateiname"]);

    context.Response.ContentType = "application/pdf";
    context.Response.WriteFile(filePath);
  }
}

A stripped down example with no checking, but that's for you to fill in. Then register the handler in your web.config:

<handlers>
  <add name="MyFileHandler" path="file.axd" type="MvcApplication4.Models.MyFileHandler" verb="GET" />
</handlers>

You will of course have to rename classes/namespaces to suit yourself. The actual web link to the file then becomes:

http://[domain]/file.axd?dateiname=mypdf.pdf

Where [domain] is your domain name/localhost or whatever you're using.


问:
Can we use bootstrap modal backdrop as a standalone component
my question is that can i use bootstrap's modal plugin's backdrop as a separate standalone component, if i have to use backdrop for some other purpose.
If possible then how to use it.
Thanks in advance</p>

答:
You can't use bootstrap backdrop as a standalone component.

I have written the following js function, inherited from bootstrap, for using backdrop.

The function use jquery like bootstrap.

```<code>    var backdrop = function () {
        var that = this
        var animate = 'fade'
        that.$body = $(document.body)
        that.__TRANSITION_DURATION = 300
        that.__BACKDROP_TRANSITION_DURATION = 150

        this.show = function (callback) {
            var doAnimate = $.support.transition && animate

            that.$backdrop = $(document.createElement('div'))
              .addClass('modal-backdrop ' + animate)
              .appendTo(that.$body)

            if (doAnimate) that.$backdrop[0].offsetWidth // force reflow

            that.$backdrop.addClass('in')

            if (!callback) return

            doAnimate ?
              that.$backdrop
                .one('bsTransitionEnd', callback)
                .emulateTransitionEnd(that.__BACKDROP_TRANSITION_DURATION) :
              callback()
        }

        this.hide = function (callback) {

            if (that.$backdrop) {
                var callbackRemove = function () {
                    that.$backdrop && that.$backdrop.remove()
                    that.$backdrop = null
                    callback && callback()
                }

                $.support.transition ?
                    that.$backdrop
                    .one('bsTransitionEnd', callbackRemove)
                    .emulateTransitionEnd(that.__BACKDROP_TRANSITION_DURATION) :
                    callbackRemove()
            }
        }

        return this
    }
</code>```

and this is the code for using it:

```<code>      function showBackdrop() {

            var bd = new backdrop()
            bd.show(function () { })
            setTimeout(function () { bd.hide() }, 2000)
        }
</code>```

in both functions show and hide You have a callback for doing custom actions, exactly like bootstrap.

Note. You must set the show callback function for backdrop taking effect. For hide function it's no required.

Body:
You can't use bootstrap backdrop as a standalone component.

I have written the following js function, inherited from bootstrap, for using backdrop.

The function use jquery like bootstrap.

    var backdrop = function () {
        var that = this
        var animate = 'fade'
        that.$body = $(document.body)
        that.__TRANSITION_DURATION = 300
        that.__BACKDROP_TRANSITION_DURATION = 150

        this.show = function (callback) {
            var doAnimate = $.support.transition && animate

            that.$backdrop = $(document.createElement('div'))
              .addClass('modal-backdrop ' + animate)
              .appendTo(that.$body)

            if (doAnimate) that.$backdrop[0].offsetWidth // force reflow

            that.$backdrop.addClass('in')

            if (!callback) return

            doAnimate ?
              that.$backdrop
                .one('bsTransitionEnd', callback)
                .emulateTransitionEnd(that.__BACKDROP_TRANSITION_DURATION) :
              callback()
        }

        this.hide = function (callback) {

            if (that.$backdrop) {
                var callbackRemove = function () {
                    that.$backdrop && that.$backdrop.remove()
                    that.$backdrop = null
                    callback && callback()
                }

                $.support.transition ?
                    that.$backdrop
                    .one('bsTransitionEnd', callbackRemove)
                    .emulateTransitionEnd(that.__BACKDROP_TRANSITION_DURATION) :
                    callbackRemove()
            }
        }

        return this
    }

and this is the code for using it:

      function showBackdrop() {

            var bd = new backdrop()
            bd.show(function () { })
            setTimeout(function () { bd.hide() }, 2000)
        }

in both functions show and hide You have a callback for doing custom actions, exactly like bootstrap.

Note. You must set the show callback function for backdrop taking effect. For hide function it's no required.


问:
How to create new column from existing column value in R dynamically
i have data frame called df,how to create new column from existing list column data frame.

my data frame.

```<code>Policy             Item

Checked           list(Processed = "Valid", Gmail = "yy@gmail", Information = list(list(Descrption = "T1, R1", VID = "YUY")))

Sample            list(Processed = "Valid", Gmail = "tt@gmail", Information = list(list(Descrption = "D3, Y3", VID = "RT")))

Processed         list(Processed = "Valid", Gmail = "pp@gmail", Information = list(list(Descrption = "Y2, LE", VID = "UIU")))
</code>```

my expected data frame.

```<code>Policy          Processed    Gmail        Descrption  VID

Checked           Valid      yy@gmail       "T1,R1"  "YUY"

Sample            Valid      tt@gmail       "D3,Y3"  "RT"

Processed         Valid      pp@gmail       "Y2,LE"  "UIU"
</code>```

i'm using below code to get my expected dataframe .

```<code>na_if_null <- function(x) if (is.null(x)) NA else x

new_cols <- lapply(
  Filter(is.list, df),
  function(list_col) {
    names_ <- setNames(nm = unique(do.call(c, lapply(list_col, names))))
    lapply(names_, function(name) sapply(list_col, function(x)
      trimws(na_if_null(as.list(x)[[name]]))))
  }
)

res <- do.call(
  data.frame,
  c(
    list(df, check.names = FALSE, stringsAsFactors = FALSE),
    do.call(c, new_cols)
  )
)
</code>```

But i'm getting below Data frame.please help me to done my post.

```<code>Policy       Item                                                                                Item.Processed    Item.Gmail     Item.Information

Checked      list(Processed = "Valid", Gmail = "yy@gmail", Information = list(list(Descrption = "T1, R1", VID = "YUY")))    Processed        yy@gmail      list(Descrption = "T1, R1", VID = "YUY")

Sample       list(Processed = "Valid", Gmail = "tt@gmail", Information = list(list(Descrption = "D3, Y3", VID = "RT")))     Processed        tt@gmail      list(Descrption = "D3, Y3", VID = "RT")

Processed    list(Processed = "Valid", Gmail = "pp@gmail", Information = list(list(Descrption = "Y2, LE", VID = "UIU")))    Processed        pp@gmail      list(Descrption = "Y2, LE", VID = "UIU")
</code>```

dput

```<code>    structure(list(Policy = c("Checked", "Sample", "Processed"), Item = list(
    structure(list(Processed = "Valid", Gmail = "yy@gmail", Information = list(
        structure(list(Descrption = "T1, R1", VID = "YUY"), .Names = c("Descrption",
        "VID"), class = "data.frame", row.names = 1L))), .Names = c("Processed",
    "Gmail", "Information"), class = "data.frame", row.names = 1L),
    structure(list(Processed = "Valid", Gmail = "tt@gmail", Information = list(
        structure(list(Descrption = "D3, Y3", VID = "RT"), .Names = c("Descrption",
        "VID"), class = "data.frame", row.names = 1L))), .Names = c("Processed",
    "Gmail", "Information"), class = "data.frame", row.names = 1L),
    structure(list(Processed = "Valid", Gmail = "pp@gmail", Information = list(
        structure(list(Descrption = "Y2, LE", VID = "UIU"), .Names = c("Descrption",
        "VID"), class = "data.frame", row.names = 1L))), .Names = c("Processed",
    "Gmail", "Information"), class = "data.frame", row.names = 1L))), row.names = c(NA,
3L), class = "data.frame", .Names = c("Policy", "Item"))
</code>```

Sample data frame

```<code>Policy             colval                                 Item

Checked         list(PID="4",Bdetail ="ui,89")      list(Processed = "Valid", Gmail = "yy@gmail", Information = list(list(Descrption = "T1, R1", VID = "YUY")))

Sample          list(PID="7",Bdetail ="ju,78")      list(Processed = "Valid", Gmail = "tt@gmail", Information = list(list(Descrption = "D3, Y3", VID = "RT")))

Processed       list(PID ="8",Bdetail ="nj,45")     list(Processed = "Valid", Gmail = "pp@gmail", Information = list(list(Descrption = "Y2, LE", VID = "UIU")))
</code>```

答:
Here a solution in base R:

```<code>dd <-
cbind(
  dx$Policy,
  do.call(rbind,
          lapply(seq_len(nrow(dx)), function(i)unlist(dx$Item[i]))
  )
)

colnames(dd) <- c("Policy","Processed","Gmail","Descrption","VID")

dd

#       Policy      Processed Gmail      Descrption VID
# [1,] "Checked"   "Valid"   "yy@gmail" "T1, R1"   "YUY"
# [2,] "Sample"    "Valid"   "tt@gmail" "D3, Y3"   "RT"
# [3,] "Processed" "Valid"   "pp@gmail" "Y2, LE"   "UIU"
</code>```

Basically I am using unlist for each item. and Then joining them using the classic d.call(rbind,llist).

edit

in case you want tu use the same names as the original sub lists you can do something like :

```<code>colnames(dd) <- c("Policy",gsub(".*[.]","",colnames(dd)[-1]))
</code>```

data.table solution

```<code>library(data.table)
setDT(dx)
dx[, rbindlist(lapply(.SD,function(x)data.table(t(unlist(x))))),Policy]
</code>```

Body:
i have data frame called df,how to create new column from existing list column data frame.

my data frame.

Policy             Item

Checked           list(Processed = "Valid", Gmail = "yy@gmail", Information = list(list(Descrption = "T1, R1", VID = "YUY")))

Sample            list(Processed = "Valid", Gmail = "tt@gmail", Information = list(list(Descrption = "D3, Y3", VID = "RT")))

Processed         list(Processed = "Valid", Gmail = "pp@gmail", Information = list(list(Descrption = "Y2, LE", VID = "UIU")))

my expected data frame.

Policy          Processed    Gmail        Descrption  VID

Checked           Valid      yy@gmail       "T1,R1"  "YUY"

Sample            Valid      tt@gmail       "D3,Y3"  "RT"

Processed         Valid      pp@gmail       "Y2,LE"  "UIU"

i'm using below code to get my expected dataframe .

na_if_null <- function(x) if (is.null(x)) NA else x

new_cols <- lapply(
  Filter(is.list, df),
  function(list_col) {
    names_ <- setNames(nm = unique(do.call(c, lapply(list_col, names))))
    lapply(names_, function(name) sapply(list_col, function(x)
      trimws(na_if_null(as.list(x)[[name]]))))
  }
)

res <- do.call(
  data.frame,
  c(
    list(df, check.names = FALSE, stringsAsFactors = FALSE),
    do.call(c, new_cols)
  )
)

But i'm getting below Data frame.please help me to done my post.

Policy       Item                                                                                Item.Processed    Item.Gmail     Item.Information

Checked      list(Processed = "Valid", Gmail = "yy@gmail", Information = list(list(Descrption = "T1, R1", VID = "YUY")))    Processed        yy@gmail      list(Descrption = "T1, R1", VID = "YUY")

Sample       list(Processed = "Valid", Gmail = "tt@gmail", Information = list(list(Descrption = "D3, Y3", VID = "RT")))     Processed        tt@gmail      list(Descrption = "D3, Y3", VID = "RT")

Processed    list(Processed = "Valid", Gmail = "pp@gmail", Information = list(list(Descrption = "Y2, LE", VID = "UIU")))    Processed        pp@gmail      list(Descrption = "Y2, LE", VID = "UIU")

dput

    structure(list(Policy = c("Checked", "Sample", "Processed"), Item = list(
    structure(list(Processed = "Valid", Gmail = "yy@gmail", Information = list(
        structure(list(Descrption = "T1, R1", VID = "YUY"), .Names = c("Descrption",
        "VID"), class = "data.frame", row.names = 1L))), .Names = c("Processed",
    "Gmail", "Information"), class = "data.frame", row.names = 1L),
    structure(list(Processed = "Valid", Gmail = "tt@gmail", Information = list(
        structure(list(Descrption = "D3, Y3", VID = "RT"), .Names = c("Descrption",
        "VID"), class = "data.frame", row.names = 1L))), .Names = c("Processed",
    "Gmail", "Information"), class = "data.frame", row.names = 1L),
    structure(list(Processed = "Valid", Gmail = "pp@gmail", Information = list(
        structure(list(Descrption = "Y2, LE", VID = "UIU"), .Names = c("Descrption",
        "VID"), class = "data.frame", row.names = 1L))), .Names = c("Processed",
    "Gmail", "Information"), class = "data.frame", row.names = 1L))), row.names = c(NA,
3L), class = "data.frame", .Names = c("Policy", "Item"))

Sample data frame

Policy             colval                                 Item

Checked         list(PID="4",Bdetail ="ui,89")      list(Processed = "Valid", Gmail = "yy@gmail", Information = list(list(Descrption = "T1, R1", VID = "YUY")))

Sample          list(PID="7",Bdetail ="ju,78")      list(Processed = "Valid", Gmail = "tt@gmail", Information = list(list(Descrption = "D3, Y3", VID = "RT")))

Processed       list(PID ="8",Bdetail ="nj,45")     list(Processed = "Valid", Gmail = "pp@gmail", Information = list(list(Descrption = "Y2, LE", VID = "UIU")))

Body:
Here a solution in base R:

dd <-
cbind(
  dx$Policy,
  do.call(rbind,
          lapply(seq_len(nrow(dx)), function(i)unlist(dx$Item[i]))
  )
)

colnames(dd) <- c("Policy","Processed","Gmail","Descrption","VID")

dd

#       Policy      Processed Gmail      Descrption VID
# [1,] "Checked"   "Valid"   "yy@gmail" "T1, R1"   "YUY"
# [2,] "Sample"    "Valid"   "tt@gmail" "D3, Y3"   "RT"
# [3,] "Processed" "Valid"   "pp@gmail" "Y2, LE"   "UIU"

Basically I am using unlist for each item. and Then joining them using the classic d.call(rbind,llist).

edit

in case you want tu use the same names as the original sub lists you can do something like :

colnames(dd) <- c("Policy",gsub(".*[.]","",colnames(dd)[-1]))

data.table solution

library(data.table)
setDT(dx)
dx[, rbindlist(lapply(.SD,function(x)data.table(t(unlist(x))))),Policy]


问:
Error with for_each, map and lambda when passing by non-auto non-const lvalue reference
In the following code, the first for_each statement gives me errors with GCC 7.2, some of which says:

cannot bind non-const lvalue reference of type 'std::pair&' to an rvalue of type 'std::pair'

```<code>#include <algorithm>
#include <iostream>
#include <map>

int main() {
  std::map<int, double> m = { {1, 1.0}, {2, 2.0}, {3, 3.0} };

  std::for_each(std::begin(m), std::end(m),
                [](std::pair<int, double>& e){ e.second += 1.0; }); // ERROR

  std::for_each(std::begin(m), std::end(m),
                [](auto& e){ e.second += 1.0; }); // OK

  for (auto iter = std::begin(m); iter != std::end(m); ++iter)
    iter->second += 1.0;

  for (auto & e : m)
    e.second += 1.0;

  for (auto & [ key, value ] : m)
    value += 1.0;

  std::cout << m[1] << ", " << m[2] << ", " << m[3] << std::endl;
}
</code>```

What causes this error? How's that it works with auto, i.e., in the second for_each statement?

According to this answers: https://stackoverflow.com/a/14037863/580083 the first for_each should work (and I've also found another answer that said the very same).

Online code: https://wandbox.org/permlink/mOUS1NMjKooetnN1

答:
You can't modify key of a std::map, so you should use

```<code>  std::for_each(std::begin(m), std::end(m),
            [](std::pair<const int, double>& e){ e.second += 1.0; });
</code>```

Body:
In the following code, the first for_each statement gives me errors with GCC 7.2, some of which says:

cannot bind non-const lvalue reference of type 'std::pair&' to an rvalue of type 'std::pair'

#include <algorithm>
#include <iostream>
#include <map>

int main() {
  std::map<int, double> m = { {1, 1.0}, {2, 2.0}, {3, 3.0} };

  std::for_each(std::begin(m), std::end(m),
                [](std::pair<int, double>& e){ e.second += 1.0; }); // ERROR

  std::for_each(std::begin(m), std::end(m),
                [](auto& e){ e.second += 1.0; }); // OK

  for (auto iter = std::begin(m); iter != std::end(m); ++iter)
    iter->second += 1.0;

  for (auto & e : m)
    e.second += 1.0;

  for (auto & [ key, value ] : m)
    value += 1.0;

  std::cout << m[1] << ", " << m[2] << ", " << m[3] << std::endl;
}

What causes this error? How's that it works with auto, i.e., in the second for_each statement?

According to this answers: https://stackoverflow.com/a/14037863/580083 the first for_each should work (and I've also found another answer that said the very same).

Online code: https://wandbox.org/permlink/mOUS1NMjKooetnN1

Body:
You can't modify key of a std::map, so you should use

  std::for_each(std::begin(m), std::end(m),
            [](std::pair<const int, double>& e){ e.second += 1.0; });


问:
How to use global variable in onCreate method of Android
I am very much new to Android world. I was just trying to check how a global variable can be used in onCreate() method in Android, whenever i tried doing so, it closed abruptly. When I displayed some random text in the code, it was displayed successfully.

Here's my code:

```<code>public class MyActivity extends AppCompatActivity
{
    public static int num_i=0;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_beer);
        TextView tv = findViewById(R.id.textView);
        tv.setText(num_i);
        num_i++;
    }
}
</code>```

Please help me in this.

答:
setText(CharSequence text)

Sets the text to be displayed. it takes String as a parameter not a number

Sample : tv.setText("PREM");

setText(int resid)

Sets the text to be displayed using a string resource identifier.

Sample : tv.setText(R.string.app_name);

first you have to convert your int value in to a String

Try this use

```<code>tv.setText(String.valueOf(num_i));
</code>```

or

```<code>tv.setText(num_i+"");
</code>```

instead of this

```<code> tv.setText(num_i);
</code>```

Body:
I am very much new to Android world. I was just trying to check how a global variable can be used in onCreate() method in Android, whenever i tried doing so, it closed abruptly. When I displayed some random text in the code, it was displayed successfully.

Here's my code:

public class MyActivity extends AppCompatActivity
{
    public static int num_i=0;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_beer);
        TextView tv = findViewById(R.id.textView);
        tv.setText(num_i);
        num_i++;
    }
}

Please help me in this.

Body:
setText(CharSequence text)

Sets the text to be displayed. it takes String as a parameter not a number

Sample : tv.setText("PREM");

setText(int resid)

Sets the text to be displayed using a string resource identifier.

Sample : tv.setText(R.string.app_name);

first you have to convert your int value in to a String

Try this use

tv.setText(String.valueOf(num_i));

or

tv.setText(num_i+"");

instead of this

 tv.setText(num_i);


问:
Remove duplicates within Spark array column
I have a given DataSet :

```<code>+-------------------+--------------------+
|               date|            products|
+-------------------+--------------------+
|2017-08-31 22:00:00|[361, 361, 361, 3...|
|2017-09-22 22:00:00|[361, 362, 362, 3...|
|2017-09-21 22:00:00|[361, 361, 361, 3...|
|2017-09-28 22:00:00|[360, 361, 361, 3...|
</code>```

where products column is an array of strings with possible duplicated items.

I would like to remove this duplication (within one row)

What I did is basically write an UDF function like that

```<code> val removeDuplicates: WrappedArray[String] => WrappedArray[String] = _.distinct
 val udfremoveDuplicates = udf(removeDuplicates)
</code>```

This solution gives me a proper results :

```<code>+-------------------+--------------------+--------------------+
|               date|            products|       rm_duplicates|
+-------------------+--------------------+--------------------+
|2017-08-31 22:00:00|[361, 361, 361, 3...|[361, 362, 363, 3...|
|2017-09-22 22:00:00|[361, 362, 362, 3...|[361, 362, 363, 3...|
</code>```

My questions are  :

Do Spark provides a better/more efficient way of getting this result ?

I was thinking about using a map - but how to get desired column as a List to be able to use 'distinct' method  like in my removeDuplicates lambda ?

Edit: I marked this topic with java tag, because it does not matter to me in which language (scala or java) I will get an answear :)
Edit2: typos

答:
The approach presented in the question--using a UDF--is the best approach as spark-sql has no built-in primitive to uniquify arrays.

If you are dealing with massive amounts of data and/or the array values have unique properties then it's worth thinking about the implementation of the UDF.

WrappedArray.distinct builds a mutable.HashSet behind the scenes and then traverses it to build the array of distinct elements. There are two possible problems with this from a performance standpoint:

Scala's mutable collections are not wonderfully efficient, which is why in the guts of Spark you'll find a lot of Java collections and while loops. If you are in need of extreme performance, you can implement your own generic distinct using faster data structures.

A generic implementation of distinct does not take advantage of any properties of your data. For example, if the arrays will be small on average then a simple implementation that builds directly into an array and does a linear search for duplicates may perform much better than code that builds a complex data structure, despite it's theoretical O(n^2) complexity. For another example, if the values can only be numbers in a small range, or strings from a small set, you can implement uniquification via a bit set.

Again, these strategies should only be considered if you have ridiculous amounts of data. Your simple implementation is perfectly suitable for almost every situation.

Body:
I have a given DataSet :

+-------------------+--------------------+
|               date|            products|
+-------------------+--------------------+
|2017-08-31 22:00:00|[361, 361, 361, 3...|
|2017-09-22 22:00:00|[361, 362, 362, 3...|
|2017-09-21 22:00:00|[361, 361, 361, 3...|
|2017-09-28 22:00:00|[360, 361, 361, 3...|

where products column is an array of strings with possible duplicated items.

I would like to remove this duplication (within one row)

What I did is basically write an UDF function like that

 val removeDuplicates: WrappedArray[String] => WrappedArray[String] = _.distinct
 val udfremoveDuplicates = udf(removeDuplicates)

This solution gives me a proper results :

+-------------------+--------------------+--------------------+
|               date|            products|       rm_duplicates|
+-------------------+--------------------+--------------------+
|2017-08-31 22:00:00|[361, 361, 361, 3...|[361, 362, 363, 3...|
|2017-09-22 22:00:00|[361, 362, 362, 3...|[361, 362, 363, 3...|

My questions are  :

Do Spark provides a better/more efficient way of getting this result ?

I was thinking about using a map - but how to get desired column as a List to be able to use 'distinct' method  like in my removeDuplicates lambda ?

Edit: I marked this topic with java tag, because it does not matter to me in which language (scala or java) I will get an answear :)
Edit2: typos


问:
aliasing fields in mongodb projections
In mongo projections, you can either include or exclude fields in the output:

```<code>{
   IncludetField: 1,
   ExcludedField: 0
}
</code>```

These projections are easy to create in c#, using the ProjectionDefinitionBuilder<> methods Include and Exclude.

MongoDb also allows for aliasing fields:

```<code>{
   alias: "$IncludedField"
}
</code>```

but I havnen't found a good way of doing this without falling back to strings:

```<code>_collection.Aggregate()
   .Match(...)
   .Project("{alias: '$IncludedField'}");
</code>```

This can soon become quite messy. Add a $filter in that projection, and you soon end up with quite a complicated string with no help from the compiler at all.

Have I overlooked something? Or is this just the way it is?

答:
This should work:</p>

```<code>_collection.Aggregate()
   .Match(...)
   .Project(x => new { alias = x.IncludedField });
</code>```

Title: aliasing fields in mongodb projections

Body:
In mongo projections, you can either include or exclude fields in the output:

{
   IncludetField: 1,
   ExcludedField: 0
}

These projections are easy to create in c#, using the ProjectionDefinitionBuilder<> methods Include and Exclude.

MongoDb also allows for aliasing fields:

{
   alias: "$IncludedField"
}

but I havnen't found a good way of doing this without falling back to strings:

_collection.Aggregate()
   .Match(...)
   .Project("{alias: '$IncludedField'}");

This can soon become quite messy. Add a $filter in that projection, and you soon end up with quite a complicated string with no help from the compiler at all.

Have I overlooked something? Or is this just the way it is?

Body:
This should work:

_collection.Aggregate()
   .Match(...)
   .Project(x => new { alias = x.IncludedField });


问:
Assign image to PHP variable
I would like to assign an image to a variable in a PHP script so that I can make the image appear when I want to it to, by declaring the variable. </p>

```<code>$FoodList = array_unique($FoodList);
if (!empty($FoodList)) {
    foreach ($FoodList as $key => $value) {
        // The variable would go here, so that image would appear
        //next to each variable
        echo "<li>" . $value . "<li>";
    }
    echo "</ul>";
}
</code>```

答:
please insert a space before your image name :-
Example:-

```<code>$image_name="myphoto.jpg";

$image_path="./upload/ ".$image_name;
</code>```

here I add a space after "./upload/(space)"

Store the image path into your MySql database.

call it from your HTML page as:-

```<code><img src= '<?php echo  $image_path;?>'width="200" height="200" alt=""/>
</code>```

Title: Assign image to PHP variable

Body:
I would like to assign an image to a variable in a PHP script so that I can make the image appear when I want to it to, by declaring the variable.

$FoodList = array_unique($FoodList);
if (!empty($FoodList)) {
    foreach ($FoodList as $key => $value) {
        // The variable would go here, so that image would appear
        //next to each variable
        echo "
" . $value . "
";
    }
    echo "
";
}

Body:
please insert a space before your image name :-
Example:-

$image_name="myphoto.jpg";

$image_path="./upload/ ".$image_name;

here I add a space after "./upload/(space)"

Store the image path into your MySql database.

call it from your HTML page as:-

<img src= '<?php echo  $image_path;?>'width="200" height="200" alt=""/>


问:
Disable winston logging when running unit tests?
Can Winston logging be selectively disabled when executing unit tests of a node module?

Ideally, I'd like to have logging for informational and debug purposes when the application is running, but be suppressed as to not clutter the presentation unit test results when I run my tests.

My use of winston is internal to my module, something like this:

```<code>// MyModule.js
var logger = require('winston');
module.exports = function() {
  // does some stuff
  // and logs some stuff like so:
  logger.log('an informational message');
}

// MyModuleTest.js
describe('MyModule', fucntion() {
  it('should do some stuff', function() {
     var myModuleUnderTest = require('MyModule');
     // some tests
  }
}
</code>```

答:
What I do is a bit ugly, but allows me to keep using Jest's --silent option normally. I just set Winston's silent to process.argv.indexOf("--silent") >= 0. For example:

```<code>const logger = new winston.Logger({
  …,
  transports: [
    new winston.transports.Console({
      …,
      silent: process.argv.indexOf("--silent") >= 0,
    }),
  ],
});
</code>```

Body:
Can Winston logging be selectively disabled when executing unit tests of a node module?

Ideally, I'd like to have logging for informational and debug purposes when the application is running, but be suppressed as to not clutter the presentation unit test results when I run my tests.

My use of winston is internal to my module, something like this:

// MyModule.js
var logger = require('winston');
module.exports = function() {
  // does some stuff
  // and logs some stuff like so:
  logger.log('an informational message');
}

// MyModuleTest.js
describe('MyModule', fucntion() {
  it('should do some stuff', function() {
     var myModuleUnderTest = require('MyModule');
     // some tests
  }
}

Body:
What I do is a bit ugly, but allows me to keep using Jest's --silent option normally. I just set Winston's silent to process.argv.indexOf("--silent") >= 0. For example:

const logger = new winston.Logger({
  …,
  transports: [
    new winston.transports.Console({
      …,
      silent: process.argv.indexOf("--silent") >= 0,
    }),
  ],
});


问:
Selectize not showing data from ajax call
I'm using selectize js to have a search functionality and lets the user select multiple items based on the search. My problem is that the data is being retrieved properly but the data is not being shown by the control. Here's how I'm doing it.

The control:

```<code><label>Skills Required</label>
<select id="skills-ddl"  class="form-control" placeholder="Search skills.." multiple ></select>
</code>```

Js:

```<code>$(function () {
    var $select = $('#skills-ddl').selectize({
        valueField: 'Id',
        labelField: 'Name',
        load: function (query, callback) {
            $.ajax({
                url: '/ClientProjects/GetSkills?keyword=' + encodeURIComponent(query),
                success: function (response) { console.log(response); $select.options = response; callback(response); }
            });
        }
    });

    var selectize = $select[0].selectize;

});
</code>```

Here's a screenshot the data is there:

When I press backspace to make the search text box empty, the previous result is being displayed.

EDIT:

Here's how my response data looks like:

答:
I think you are missing searchField attribute due to which it is not able to understand which attribute it has to show in your dropdown when you type in it.

Try adding searchField: 'Name' after labelField: 'Name', which will give the filter names in the dropdown.

Your js code should look like below. Hope it will work for you

```<code>$(function () {
    var $select = $('#skills-ddl').selectize({
        valueField: 'Id',
        labelField: 'Name',
        searchField: 'Name',
        load: function (query, callback) {
            $.ajax({
                url: '/ClientProjects/GetSkills?keyword=' + encodeURIComponent(query),
                success: function (response) { console.log(response); $select.options = response; callback(response); }
            });
        }
    });

    var selectize = $select[0].selectize;

});
</code>```

Body:
I'm using selectize js to have a search functionality and lets the user select multiple items based on the search. My problem is that the data is being retrieved properly but the data is not being shown by the control. Here's how I'm doing it.

The control:

Skills Required
<select id="skills-ddl"  class="form-control" placeholder="Search skills.." multiple ></select>

Js:

$(function () {
    var $select = $('#skills-ddl').selectize({
        valueField: 'Id',
        labelField: 'Name',
        load: function (query, callback) {
            $.ajax({
                url: '/ClientProjects/GetSkills?keyword=' + encodeURIComponent(query),
                success: function (response) { console.log(response); $select.options = response; callback(response); }
            });
        }
    });

    var selectize = $select[0].selectize;

});

Here's a screenshot the data is there:

When I press backspace to make the search text box empty, the previous result is being displayed.

EDIT:

Here's how my response data looks like:

Body:
I think you are missing searchField attribute due to which it is not able to understand which attribute it has to show in your dropdown when you type in it.

Try adding searchField: 'Name' after labelField: 'Name', which will give the filter names in the dropdown.

Your js code should look like below. Hope it will work for you

$(function () {
    var $select = $('#skills-ddl').selectize({
        valueField: 'Id',
        labelField: 'Name',
        searchField: 'Name',
        load: function (query, callback) {
            $.ajax({
                url: '/ClientProjects/GetSkills?keyword=' + encodeURIComponent(query),
                success: function (response) { console.log(response); $select.options = response; callback(response); }
            });
        }
    });

    var selectize = $select[0].selectize;

});


问:
Toggle switch to call url but not open it
I have a toggle switch on my html which i would like to enable/disable a relay in arduino with.

On: call http://192.168.1.144:8000/1234!Q02=0$
Off: call http://192.168.1.144:8000/1234!Q02=1$

I don't want the url to be opened, i just want it to be called.

```<code>function getValue1() {
   var isChecked = document.getElementById("button1").checked;

   if(isChecked){
     alert("button1 is checked");
   } else {
     alert("button1 is NOT checked");
   }
}
</code>```

My javascript code is working, but i dont know how to call the url.

Thanks.

答:
Button: </p>

```<code>$(document).ready(function() {
    $("#btnCall").click(function(){
        var isChecked = document.getElementById("button1").checked;
        if(isChecked){
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "http://192.168.1.144:8000/1234!Q02=0$",
                data: JSON.stringify(data), //yourData
                success: function (data) {
                    console.log(data);
                },
                dataType: "json"
           });
        } else {
            $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "http://192.168.1.144:8000/1234!Q02=1$",
            data: JSON.stringify(data), //yourData
            success: function (data) {
                console.log(data);
            },
            dataType: "json"
        });
        }
    });
});
</code>```

Body:
I have a toggle switch on my html which i would like to enable/disable a relay in arduino with.

On: call http://192.168.1.144:8000/1234!Q02=0$
Off: call http://192.168.1.144:8000/1234!Q02=1$

I don't want the url to be opened, i just want it to be called.

function getValue1() {
   var isChecked = document.getElementById("button1").checked;

   if(isChecked){
     alert("button1 is checked");
   } else {
     alert("button1 is NOT checked");
   }
}

My javascript code is working, but i dont know how to call the url.

Thanks.

Body:
Button:

$(document).ready(function() {
    $("#btnCall").click(function(){
        var isChecked = document.getElementById("button1").checked;
        if(isChecked){
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "http://192.168.1.144:8000/1234!Q02=0$",
                data: JSON.stringify(data), //yourData
                success: function (data) {
                    console.log(data);
                },
                dataType: "json"
           });
        } else {
            $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "http://192.168.1.144:8000/1234!Q02=1$",
            data: JSON.stringify(data), //yourData
            success: function (data) {
                console.log(data);
            },
            dataType: "json"
        });
        }
    });
});


问:
My bubble sorting algorithm in Java never stops sorting and doesnt return anything
I'm trying to make a bubble sorting algorithm in Java however my code just keeps going when It's supposed to sort without returning anything. When the program is run it gets as far as printing the array before the sorting however after that nothing happens but the program doesnt stop it keeps running</p>

```<code>package src;
import java.util.Scanner;
import java.util.Random;
import java.util.ArrayList;
import java.util.List;

public class bubbleSort {

    public static void main(String[] args) {

        int length = getLength();

        List<Integer> randomList = createList(length);

        System.out.println("The list before sorting:\n" + randomList);

        List<Integer> newList = sortList(randomList, length);

        System.out.println("The list after sorting:\n" + newList);

    }

    public static int getLength() {
        System.out.println("Please enter how long you want the array to be");

        Scanner reader = new Scanner(System.in);

        int length = Integer.parseInt(reader.nextLine());

        return length;
    }

    public static List<Integer> createList(int length) {
        Random rand = new Random();

        List<Integer> randomList = new ArrayList<Integer>();

        for(int x = 0 ; x < length ; x++){
            int randomnumber = rand.nextInt((100 - 1) + 1) + 1;
            randomList.add(randomnumber);
        }

        return randomList;
    }

    public static List<Integer> sortList(List<Integer> randomList, int length){
        boolean sorted = false;

        while(sorted == false){
            sorted = true;

            for(int x = 0 ; x < (length - 1) ; x++) {
                if(randomList.get(x) > randomList.get(x + 1)) {
                    sorted = false;
                    int temp = randomList.get(x + 1);
                    randomList.set((x + 1), (x));
                    randomList.set((x + 1), temp);
                }
            }
        }

        return randomList;
    }

}
</code>```

答:
you made a couple of mistakes

this:

```<code>randomList.set((x + 1), (x));
randomList.set((x + 1), temp);
</code>```

should be:

```<code>randomList.set((x + 1), randomList.get(x));
randomList.set((x), temp);
</code>```

full method:

```<code>public static List<Integer> sortList(List<Integer> randomList, int length){
    boolean sorted = false;

    while(sorted == false){
        sorted = true;

        for(int x = 0 ; x < (length - 1) ; x++) {
            if(randomList.get(x) > randomList.get(x + 1)) {
                sorted = false;
                int temp = randomList.get(x + 1);
                randomList.set((x + 1), randomList.get(x));
                randomList.set((x), temp);
            }
        }
    }

    return randomList;
}
</code>```

Body:
I'm trying to make a bubble sorting algorithm in Java however my code just keeps going when It's supposed to sort without returning anything. When the program is run it gets as far as printing the array before the sorting however after that nothing happens but the program doesnt stop it keeps running

package src;
import java.util.Scanner;
import java.util.Random;
import java.util.ArrayList;
import java.util.List;

public class bubbleSort {

    public static void main(String[] args) {

        int length = getLength();

        List<Integer> randomList = createList(length);

        System.out.println("The list before sorting:\n" + randomList);

        List<Integer> newList = sortList(randomList, length);

        System.out.println("The list after sorting:\n" + newList);

    }

    public static int getLength() {
        System.out.println("Please enter how long you want the array to be");

        Scanner reader = new Scanner(System.in);

        int length = Integer.parseInt(reader.nextLine());

        return length;
    }

    public static List<Integer> createList(int length) {
        Random rand = new Random();

        List<Integer> randomList = new ArrayList<Integer>();

        for(int x = 0 ; x < length ; x++){
            int randomnumber = rand.nextInt((100 - 1) + 1) + 1;
            randomList.add(randomnumber);
        }

        return randomList;
    }

    public static List<Integer> sortList(List<Integer> randomList, int length){
        boolean sorted = false;

        while(sorted == false){
            sorted = true;

            for(int x = 0 ; x < (length - 1) ; x++) {
                if(randomList.get(x) > randomList.get(x + 1)) {
                    sorted = false;
                    int temp = randomList.get(x + 1);
                    randomList.set((x + 1), (x));
                    randomList.set((x + 1), temp);
                }
            }
        }

        return randomList;
    }

}

Body:
you made a couple of mistakes

this:

randomList.set((x + 1), (x));
randomList.set((x + 1), temp);

should be:

randomList.set((x + 1), randomList.get(x));
randomList.set((x), temp);

full method:

public static List<Integer> sortList(List<Integer> randomList, int length){
    boolean sorted = false;

    while(sorted == false){
        sorted = true;

        for(int x = 0 ; x < (length - 1) ; x++) {
            if(randomList.get(x) > randomList.get(x + 1)) {
                sorted = false;
                int temp = randomList.get(x + 1);
                randomList.set((x + 1), randomList.get(x));
                randomList.set((x), temp);
            }
        }
    }

    return randomList;
}