问:
Docker : Hyper-V was unable to find a virtual switch with name "DockerNAT"
I updated my docker for desktop app (Version 2.0.0.3) on Windows 10 pro.But since then my docker is not starting and throwing following error.

```<code>Hyper-V\Get-VMNetworkAdapter : Hyper-V was unable to find a virtual switch with name "DockerNAT".
At C:\Program Files\Docker\Docker\resources\MobyLinux.ps1:121 char:25
+ ... etAdapter = Hyper-V\Get-VMNetworkAdapter -ManagementOS -SwitchName $S ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (DockerNAT:String) [Get-VMNetworkAdapter], VirtualizationException
    + FullyQualifiedErrorId : InvalidParameter,Microsoft.HyperV.PowerShell.Commands.GetVMNetworkAdapter
</code>```

I followed the steps mentioned in the link (Docker on windows 10 can't startup after deleting MobyLinuxVM in Hyper-V manually ) , but it did not fix the issue.

I have also tried disabling --> restarting --> and then enabling Hyper V and containers option using "Turn windows feature on or off" present at "Control Panel\Programs\Programs and Features"

My network connection has following information

But still I am not being able to start my windows Docker app, which keeps throwing

```<code>Hyper-V was unable to find a virtual switch with name "DockerNAT".
at New-Switch, <No file>: line 121
at <ScriptBlock>, <No file>: line 411
</code>```

答:
Running the MOFCOMP command and a reboot fixed this problem for me.

Running this command: (Command Prompt as administrator)
MOFCOMP %SYSTEMROOT%\System32\WindowsVirtualization.V2.mof

Then restart

(https://community.spiceworks.com/how_to/122307-fix-error-managing-hyper-v-server-2012-r2-from-windows-10)

Body:
I updated my docker for desktop app (Version 2.0.0.3) on Windows 10 pro.But since then my docker is not starting and throwing following error.

Hyper-V\Get-VMNetworkAdapter : Hyper-V was unable to find a virtual switch with name "DockerNAT".
At C:\Program Files\Docker\Docker\resources\MobyLinux.ps1:121 char:25
+ ... etAdapter = Hyper-V\Get-VMNetworkAdapter -ManagementOS -SwitchName $S ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (DockerNAT:String) [Get-VMNetworkAdapter], VirtualizationException
    + FullyQualifiedErrorId : InvalidParameter,Microsoft.HyperV.PowerShell.Commands.GetVMNetworkAdapter

I followed the steps mentioned in the link (Docker on windows 10 can't startup after deleting MobyLinuxVM in Hyper-V manually ) , but it did not fix the issue.

I have also tried disabling --> restarting --> and then enabling Hyper V and containers option using "Turn windows feature on or off" present at "Control Panel\Programs\Programs and Features"

My network connection has following information

But still I am not being able to start my windows Docker app, which keeps throwing

Hyper-V was unable to find a virtual switch with name "DockerNAT".
at New-Switch, <No file>: line 121
at


来源: stackexchange

问:
Generating Indivdiual Dot Plot in R with Multipe Factors
I'm trying to generate an individual dot plot with multiple factors in R that's similar to the one produced by minitab.

I've been able to produce the individual dot plot in R but I can't figure out how to add grouping to the x-axis. For example I have a Color and a Type that I'd like to display on the x-axis, each Type has two colors and I'd like this put on the same graph but can't figure it out for a dot plot.

The result should look similar to this grouping but a dot plot instead and only have 1 graph, I'm just trying to illustrate the grouping.

http://ajpendo.physiology.org/content/280/5/E804/F6.small.gif

sorry can't post the image, too much of a noob to stack :)

I've scoured the web but can't find much help.

Any ideas?

答:
You can do this in a number of ways in R.

The first is to use the lattice package:

```<code>library(lattice)
xyplot(lat ~ long | cut(depth, 3),
        data = quakes,
        aspect = "iso",
        pch = ".",
        cex = 2,
        type = c("p", "g"),
        xlab = "Longitude",
        ylab = "Latitude",
        strip = strip.custom(strip.names = TRUE, var.name = "Depth"))
</code>```

And the second is in ggplot:

```<code>library(ggplot2)
df <- quakes
df$cut_depth <- cut(quakes$depth, 3)
ggplot(quakes, aes(x=long, y=lat)) + geom_point() + facet_grid(.~cut_depth)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can do this in a number of ways in R.

The first is to use the lattice package:

library(lattice)
xyplot(lat ~ long | cut(depth, 3),
        data = quakes,
        aspect = "iso",
        pch = ".",
        cex = 2,
        type = c("p", "g"),
        xlab = "Longitude",
        ylab = "Latitude",
        strip = strip.custom(strip.names = TRUE, var.name = "Depth"))

And the second is in ggplot:

library(ggplot2)
df <- quakes
df$cut_depth <- cut(quakes$depth, 3)
ggplot(quakes, aes(x=long, y=lat)) + geom_point() + facet_grid(.~cut_depth)


问:
Findopenssl.cmake fails to find OpenSSL, compiling restbed, C++
I'm trying to use cmake 3.7.2 on Debian 9.7 to compile restbed, a C++ framework for web services.

I follow the readme instructions. they're straight forward.

```<code>git clone --recursive https://github.com/corvusoft/restbed.git
mkdir restbed/build
cd restbed/build
cmake [-DBUILD_SSL=NO] ..
make install
make test
</code>```

But i get the following error when running cmake:

```<code>-- Found ASIO include at: /home/ben/Workspaces/C_Experiments/restbed/dependency/asio/asio/include
-- Found Catch include at: /home/ben/Workspaces/C_Experiments/restbed/dependency/catch/single_include
CMake Error at cmake/Findopenssl.cmake:23 (message):
  Failed to locate OpenSSL dependency.  see restbed/dependency/openssl;
  ./config shared; make all
Call Stack (most recent call first):
  CMakeLists.txt:47 (find_package)
</code>```

So I check Findopenssl.cmake, and find that it's looking in a number of places for the libraries.

```<code>find_library( ssl_LIBRARY_STATIC libssl.a  ssleay32.lib HINTS "${PROJECT_SOURCE_DIR}/dependency/openssl/out32dll" "${PROJECT_SOURCE_DIR}/dependency/openssl" "/usr/local/opt/openssl/lib" "/usr/lib" "/usr/local/lib" "/opt/local/lib" )
find_library( crypto_LIBRARY_STATIC libcrypto.a libeay32.lib HINTS "${PROJECT_SOURCE_DIR}/dependency/openssl/out32dll" "${PROJECT_SOURCE_DIR}/dependency/openssl" "/usr/local/opt/openssl/lib" "/usr/lib" "/usr/local/lib" "/opt/local/lib" )

find_library( ssl_LIBRARY_SHARED libssl.so libssl.dylib ssleay32.dll HINTS "${PROJECT_SOURCE_DIR}/dependency/openssl/out32dll" "${PROJECT_SOURCE_DIR}/dependency/openssl" "/usr/local/opt/openssl/lib" "/usr/lib" "/usr/local/lib" "/opt/local/lib" )
find_library( crypto_LIBRARY_SHARED libcrypto.so libcrypto.dylib libeay32.dll HINTS "${PROJECT_SOURCE_DIR}/dependency/openssl/out32dll" "${PROJECT_SOURCE_DIR}/dependency/openssl" "/usr/local/opt/openssl/lib" "/usr/lib" "/usr/local/lib" "/opt/local/lib" )

find_path( ssl_INCLUDE openssl/ssl.h HINTS "${PROJECT_SOURCE_DIR}/dependency/openssl/inc32" "${PROJECT_SOURCE_DIR}/dependency/openssl/include" "/usr/local/opt/openssl/include" "/usr/include" "/usr/local/include" "/opt/local/include" )

if ( ssl_LIBRARY_STATIC AND ssl_LIBRARY_SHARED AND crypto_LIBRARY_STATIC AND crypto_LIBRARY_SHARED )
    set( OPENSSL_FOUND TRUE )
    add_definitions( -DBUILD_SSL=TRUE )

    if ( APPLE AND BUILD_SSL )
        set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-deprecated-declarations" )
    endif( )

    message( STATUS "Found OpenSSL include at: ${ssl_INCLUDE}" )
    message( STATUS "Found OpenSSL library at: ${ssl_LIBRARY_STATIC}" )
    message( STATUS "Found OpenSSL library at: ${ssl_LIBRARY_SHARED}" )
    message( STATUS "Found Crypto library at: ${crypto_LIBRARY_STATIC}" )
    message( STATUS "Found Crypto library at: ${crypto_LIBRARY_SHARED}" )
else ( )
    message( FATAL_ERROR "Failed to locate OpenSSL dependency. see restbed/dependency/openssl; ./config shared; make all" )
endif ( )
</code>```

I can't find these file either. I have openssl installed, version 1.1.0

What obvious thing am I missing here?

Thanks

答: Brady Dean was correct, I had only openssl installed, not libssl-dev. </p>

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to use cmake 3.7.2 on Debian 9.7 to compile restbed, a C++ framework for web services.

I follow the readme instructions. they're straight forward.

git clone --recursive https://github.com/corvusoft/restbed.git
mkdir restbed/build
cd restbed/build
cmake [-DBUILD_SSL=NO] ..
make install
make test

But i get the following error when running cmake:

-- Found ASIO include at: /home/ben/Workspaces/C_Experiments/restbed/dependency/asio/asio/include
-- Found Catch include at: /home/ben/Workspaces/C_Experiments/restbed/dependency/catch/single_include
CMake Error at cmake/Findopenssl.cmake:23 (message):
  Failed to locate OpenSSL dependency.  see restbed/dependency/openssl;
  ./config shared; make all
Call Stack (most recent call first):
  CMakeLists.txt:47 (find_package)

So I check Findopenssl.cmake, and find that it's looking in a number of places for the libraries.

find_library( ssl_LIBRARY_STATIC libssl.a  ssleay32.lib HINTS "${PROJECT_SOURCE_DIR}/dependency/openssl/out32dll" "${PROJECT_SOURCE_DIR}/dependency/openssl" "/usr/local/opt/openssl/lib" "/usr/lib" "/usr/local/lib" "/opt/local/lib" )
find_library( crypto_LIBRARY_STATIC libcrypto.a libeay32.lib HINTS "${PROJECT_SOURCE_DIR}/dependency/openssl/out32dll" "${PROJECT_SOURCE_DIR}/dependency/openssl" "/usr/local/opt/openssl/lib" "/usr/lib" "/usr/local/lib" "/opt/local/lib" )

find_library( ssl_LIBRARY_SHARED libssl.so libssl.dylib ssleay32.dll HINTS "${PROJECT_SOURCE_DIR}/dependency/openssl/out32dll" "${PROJECT_SOURCE_DIR}/dependency/openssl" "/usr/local/opt/openssl/lib" "/usr/lib" "/usr/local/lib" "/opt/local/lib" )
find_library( crypto_LIBRARY_SHARED libcrypto.so libcrypto.dylib libeay32.dll HINTS "${PROJECT_SOURCE_DIR}/dependency/openssl/out32dll" "${PROJECT_SOURCE_DIR}/dependency/openssl" "/usr/local/opt/openssl/lib" "/usr/lib" "/usr/local/lib" "/opt/local/lib" )

find_path( ssl_INCLUDE openssl/ssl.h HINTS "${PROJECT_SOURCE_DIR}/dependency/openssl/inc32" "${PROJECT_SOURCE_DIR}/dependency/openssl/include" "/usr/local/opt/openssl/include" "/usr/include" "/usr/local/include" "/opt/local/include" )

if ( ssl_LIBRARY_STATIC AND ssl_LIBRARY_SHARED AND crypto_LIBRARY_STATIC AND crypto_LIBRARY_SHARED )
    set( OPENSSL_FOUND TRUE )
    add_definitions( -DBUILD_SSL=TRUE )

    if ( APPLE AND BUILD_SSL )
        set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-deprecated-declarations" )
    endif( )

    message( STATUS "Found OpenSSL include at: ${ssl_INCLUDE}" )
    message( STATUS "Found OpenSSL library at: ${ssl_LIBRARY_STATIC}" )
    message( STATUS "Found OpenSSL library at: ${ssl_LIBRARY_SHARED}" )
    message( STATUS "Found Crypto library at: ${crypto_LIBRARY_STATIC}" )
    message( STATUS "Found Crypto library at: ${crypto_LIBRARY_SHARED}" )
else ( )
    message( FATAL_ERROR "Failed to locate OpenSSL dependency. see restbed/dependency/openssl; ./config shared; make all" )
endif ( )

I can't find these file either. I have openssl installed, version 1.1.0

What obvious thing am I missing here?

Thanks


问:
textAlign justify property not working in react native
I have try to use textAlign: 'justify' property in react native.TextAlign justify doesn't work on Android.
React native version: "react-native": "0.59.5"</p>

```<code>import React from 'react';
import { Image, View } from 'react-native';
import { Text, Button } from 'native-base';
import { connect } from 'react-redux';
import EStyleSheet from 'react-native-extended-stylesheet';
import { colors } from '../styles';

class Login extends React.Component {
  render() {
    return (
        <View style={styles.container}>
            <View style={styles.contentCenter}>
                <Text style={[styles.titleContent,styles.fontBold]}>Simple Secure</Text>
                <Text style={[styles.titleContent,styles.fontBold]}>Reliable Messaging</Text>
            </View>
        </View>
    );
  }
}

const styles = EStyleSheet.create({
    titleContent: {
        color:'#62778c',
        fontSize: '1.4rem',
        textAlign: 'justify',
      }
});

const mapStateToProps = (state) => {
  return {};
};

export default connect(mapStateToProps)(Login);
</code>```

答:
checkout the offical document:

textAlign: enum('auto', 'left', 'right', 'center', 'justify')

Specifies text alignment. The value 'justify' is only supported on iOS and fallbacks to left on Android.

Body:
I have try to use textAlign: 'justify' property in react native.TextAlign justify doesn't work on Android.
React native version: "react-native": "0.59.5"

import React from 'react';
import { Image, View } from 'react-native';
import { Text, Button } from 'native-base';
import { connect } from 'react-redux';
import EStyleSheet from 'react-native-extended-stylesheet';
import { colors } from '../styles';

class Login extends React.Component {
  render() {
    return (
        <View style={styles.container}>
            <View style={styles.contentCenter}>
                <Text style={[styles.titleContent,styles.fontBold]}>Simple Secure</Text>
                <Text style={[styles.titleContent,styles.fontBold]}>Reliable Messaging</Text>
            </View>
        </View>
    );
  }
}

const styles = EStyleSheet.create({
    titleContent: {
        color:'#62778c',
        fontSize: '1.4rem',
        textAlign: 'justify',
      }
});

const mapStateToProps = (state) => {
  return {};
};

export default connect(mapStateToProps)(Login);


问:
How can I determine if the query is working?
I can't see if there's an error because the application is not prompting anything. I want to get a value from the database and put it inside a variable to be displayed later when I need it.

I'm fairly new to programming, I've tried to watch tutorials, but I just can't seem to get how some things are properly done since tutors have their own approach on doing stuff.

public void selectQuery(String input) throws SQLException {
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");

        String USERNAME = "root";
        String PASSWORD = "root";
        String CONN_STRING =
            "jdbc:mysql://localhost:3306/javaddy?serverTimezone=UTC";
        Connection connection =
            DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);

        try {
            String q = "SELECT Inquiry_answer,Inquiry_question FROM inquiries WHERE Inquiry_question = '" + input + "'";
            Statement stmt = connection.createStatement();
            ResultSet res = stmt.executeQuery(q);
            String answer;
            answer = res.getString("Inquiry_answer");
            // /* there is no value returned here (I think) because after passing to
            // bot method, it doesn't print anything */
            bot(answer);
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }

    } catch (ClassNotFoundException e) {
        System.out.println("Could not find the database driver " + e.getMessage());
    } catch (SQLException e) {
        System.out.println("Could not connect to the database " + e.getMessage());
    }
}
```

I expect to receive a value from the database but there is none returned.

答:
Basically, this is a pretty clear-cut case of when you should be using a debugger. I don't know what programming environment you are using, but all of the big ones (IntelliJ, Eclipse, Netbeans) have support for debugging built in. In this case, you should just set a breakpoint on the bot(answer); line, that way, you can determine whether there is any data there, check if the bot function is working correctly etc.

Also, as pointed above, if you're not getting a stacktrace, then the code is returning a value correctly. Maybe the relevant fields in the database are empty? Again, using a debugger can help you here.

Here's a sample tutorial for debugging Java programs in Eclipse in case you need one: https://www.vogella.com/tutorials/EclipseDebugging/article.html

Body:
I can't see if there's an error because the application is not prompting anything. I want to get a value from the database and put it inside a variable to be displayed later when I need it.

I'm fairly new to programming, I've tried to watch tutorials, but I just can't seem to get how some things are properly done since tutors have their own approach on doing stuff.

public void selectQuery(String input) throws SQLException {
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");

        String USERNAME = "root";
        String PASSWORD = "root";
        String CONN_STRING =
            "jdbc:mysql://localhost:3306/javaddy?serverTimezone=UTC";
        Connection connection =
            DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);

        try {
            String q = "SELECT Inquiry_answer,Inquiry_question FROM inquiries WHERE Inquiry_question = '" + input + "'";
            Statement stmt = connection.createStatement();
            ResultSet res = stmt.executeQuery(q);
            String answer;
            answer = res.getString("Inquiry_answer");
            // /* there is no value returned here (I think) because after passing to
            // bot method, it doesn't print anything */
            bot(answer);
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }

    } catch (ClassNotFoundException e) {
        System.out.println("Could not find the database driver " + e.getMessage());
    } catch (SQLException e) {
        System.out.println("Could not connect to the database " + e.getMessage());
    }
}

I expect to receive a value from the database but there is none returned.


问:
How to disable manual input in a Telerik RadDatePicker
I am using a Telerik RadDatePicker, and I want to disable input by the user, but they should be able to select from the calender.

```<code><telerik:RadDatePicker Culture="{Binding GetLanguage}" x:Name="startDate"
                       Margin="0,5,0,5" HorizontalAlignment="Left"
                       VerticalAlignment="Center" Grid.Column="1" TabIndex="2"
                       MinWidth="120" Width="120" Height="Auto" MaxHeight="25"
                       KeyDown="filterDate_KeyDown" >
</telerik:RadDatePicker>
</code>```

I have used KeyDown but it did not help.

答:
There is an easy solution to this problem.

Adding the property EnableTyping="false" prevents the user from typing.

```<code><telerik:RadDatePicker runat="server" ID="rdpPreviousDay" EnableTyping="false"></telerik:RadDatePicker>
</code>```

Body:
I am using a Telerik RadDatePicker, and I want to disable input by the user, but they should be able to select from the calender.

<telerik:RadDatePicker Culture="{Binding GetLanguage}" x:Name="startDate"
                       Margin="0,5,0,5" HorizontalAlignment="Left"
                       VerticalAlignment="Center" Grid.Column="1" TabIndex="2"
                       MinWidth="120" Width="120" Height="Auto" MaxHeight="25"
                       KeyDown="filterDate_KeyDown" >
</telerik:RadDatePicker>

I have used KeyDown but it did not help.

Body:
There is an easy solution to this problem.

Adding the property EnableTyping="false" prevents the user from typing.

<telerik:RadDatePicker runat="server" ID="rdpPreviousDay" EnableTyping="false"></telerik:RadDatePicker>


问:
how to make a 2 level array to asimple array
I have an array like this:

```<code>[12601] => Array (
        ['docUpload'] => html dom.txt
)

[12602] => Array (
        ['docUpload'] => PYTHON AND DJANGO ARE HUGE IN FINTECH.txt
)
[12603] => Array (
        ['docUpload'] =>
)
</code>```

How to get it like this:

```<code>12601 => html dom.txt
12602 => PYTHON AND DJANGO ARE HUGE IN FINTECH.txt
</code>```

can you help me please?

答:
You can loop over the array by foreach()

Steps:

1) Take a new blank array. We are appending our results into this.

2) If the array is not empty, loop over the array by foreach

3) Use key value pairs. Key is the id in required array.

4) Value is an array with key docUpload to be the document name.

5) Append new element with id and value (docUpload).

6) Resulting array will be a single dimensional array.

Final Code:

```<code>$arr = [];
$arr[12401] = ['docUpload' => ''];
$arr[12601] = ['docUpload' => 'html dom.txt'];
$arr[12602] = ['docUpload' => 'PYTHON AND DJANGO ARE HUGE IN FINTECH.txt'];
$arr[12603] = ['docUpload' => ''];
$newArr = [];
if (! empty($arr)) {
 foreach ($arr as $id => $docArr) {
  $newArr[$id] = $docArr['docUpload'];
 }
}
echo '```';print_r($newArr);echo '```';
</code>```

Output:

```<code>Array
(
    [12401] =>
    [12601] => html dom.txt
    [12602] => PYTHON AND DJANGO ARE HUGE IN FINTECH.txt
    [12603] =>
)
</code>```

Working Link:

Body:
I have an array like this:

[12601] => Array (
        ['docUpload'] => html dom.txt
)

[12602] => Array (
        ['docUpload'] => PYTHON AND DJANGO ARE HUGE IN FINTECH.txt
)
[12603] => Array (
        ['docUpload'] =>
)

How to get it like this:

12601 => html dom.txt
12602 => PYTHON AND DJANGO ARE HUGE IN FINTECH.txt

can you help me please?

Body:
You can loop over the array by foreach()

Steps:

1) Take a new blank array. We are appending our results into this.

2) If the array is not empty, loop over the array by foreach

3) Use key value pairs. Key is the id in required array.

4) Value is an array with key docUpload to be the document name.

5) Append new element with id and value (docUpload).

6) Resulting array will be a single dimensional array.

Final Code:

$arr = [];
$arr[12401] = ['docUpload' => ''];
$arr[12601] = ['docUpload' => 'html dom.txt'];
$arr[12602] = ['docUpload' => 'PYTHON AND DJANGO ARE HUGE IN FINTECH.txt'];
$arr[12603] = ['docUpload' => ''];
$newArr = [];
if (! empty($arr)) {
 foreach ($arr as $id => $docArr) {
  $newArr[$id] = $docArr['docUpload'];
 }
}
echo '<pre>';print_r($newArr);echo '</pre>';

Output:

Array
(
    [12401] =>
    [12601] => html dom.txt
    [12602] => PYTHON AND DJANGO ARE HUGE IN FINTECH.txt
    [12603] =>
)

Working Link:


问:
write python script to run the shell script?
I run the svn status got the modified files :

```<code>  svn status
  ?       .settings
  ?       .buildpath
  ?       .directory
  A       A.php
  M       B.php
  D       html/C.html
  M       html/D.fr
  M       api/E.api
  M       F.php
  ..
</code>```

After I want to keep all of these files

zcvf MY.tar.gz all files that svn stat display
(not include ? just M,A,D)

My idea is to create the python script can run the shell,because right now to do this I just copy the file name one by one.

zcvf MY.tar.gz all the files that we run svn stat

Anybody could guide how to do this or some related tutorial? But if you think it difficult than copy && paste I will ignore my trying?

thanks

答:
You could use check_output() and check_call() functions:

```<code>#!/usr/bin/env python
from subprocess import check_call, check_output as qx

filenames = [line[8:] # extract filename
             for line in qx(['svn', 'status']).splitlines()
             if not line.startswith('?')] # exclude files that are not under VC
check_call(['tar', 'cvfz', 'MY.tar.gz'] + filenames)
</code>```

On Python < 2.7 see check_output() recipe.

Body:
I run the svn status got the modified files :

  svn status
  ?       .settings
  ?       .buildpath
  ?       .directory
  A       A.php
  M       B.php
  D       html/C.html
  M       html/D.fr
  M       api/E.api
  M       F.php
  ..

After I want to keep all of these files

zcvf MY.tar.gz all files that svn stat display
(not include ? just M,A,D)

My idea is to create the python script can run the shell,because right now to do this I just copy the file name one by one.

zcvf MY.tar.gz all the files that we run svn stat

Anybody could guide how to do this or some related tutorial? But if you think it difficult than copy && paste I will ignore my trying?

thanks

Body:
You could use check_output() and check_call() functions:

#!/usr/bin/env python
from subprocess import check_call, check_output as qx

filenames = [line[8:] # extract filename
             for line in qx(['svn', 'status']).splitlines()
             if not line.startswith('?')] # exclude files that are not under VC
check_call(['tar', 'cvfz', 'MY.tar.gz'] + filenames)

On Python < 2.7 see check_output() recipe.


问:
merge list elements which are different dimensions r
I have a df:

```<code>df= data.frame(year=c(rep(2018,4),rep(2017,3)),Area=c(1:4,1:3),P=1:7,N=1:7)
</code>```

I want to split it by years, and then merge everything together again so I can see years as columns for each area. In order to do this, I am splitting and merging:

```<code>s=split(df,df$year)
m=merge(s[[1]][,2:4],[s[[2]][,2:4],by='Area',all=1)
colnames(m)=c('area','P2018','C2018','P2017','C2017')
</code>```

I am sure there is a more efficient way, expecially as the possibility for errors is very high once I include data from other years.

Any suggestions?

答:
We can gather data to long form excluding year and Area column, unite the year and then spread it to wide format.

```<code>library(dplyr)
library(tidyr)

df %>%
  gather(key, value, -year, -Area) %>%
  unite(key, key, year, sep = "") %>%
  spread(key, value)

#  Area N2017 N2018 P2017 P2018
#1    1     5     1     5     1
#2    2     6     2     6     2
#3    3     7     3     7     3
#4    4    NA     4    NA     4
</code>```

Body:
I have a df:

df= data.frame(year=c(rep(2018,4),rep(2017,3)),Area=c(1:4,1:3),P=1:7,N=1:7)

I want to split it by years, and then merge everything together again so I can see years as columns for each area. In order to do this, I am splitting and merging:

s=split(df,df$year)
m=merge(s[[1]][,2:4],[s[[2]][,2:4],by='Area',all=1)
colnames(m)=c('area','P2018','C2018','P2017','C2017')

I am sure there is a more efficient way, expecially as the possibility for errors is very high once I include data from other years.

Any suggestions?

Body:
We can gather data to long form excluding year and Area column, unite the year and then spread it to wide format.

library(dplyr)
library(tidyr)

df %>%
  gather(key, value, -year, -Area) %>%
  unite(key, key, year, sep = "") %>%
  spread(key, value)

#  Area N2017 N2018 P2017 P2018
#1    1     5     1     5     1
#2    2     6     2     6     2
#3    3     7     3     7     3
#4    4    NA     4    NA     4


问:
Angular 6 update a component from the service
I'm using angular 6 and I need to update the component when I call a service method. I have a variable agentthat keep the selected agent from html so I get this variable from several component and I can delete this agent from a specific button.

When I call deleteAgent I have to update the interface so I need a way to "tell" to the component that the agent was deleted.

```<code>export class ComponentService {
  private agent : Agent
  constructor() { }

   /************ AGENT MANAGEMENT *****************/
   get getAgent(){
     return this.agent;
   }

   setAgent(agent: Agent){
     this.agent = agent;
   }

   deleteAgent(){
     this.agent = null;
     //inform the component about the change
   }
}
</code>```

I read about ReplaySubject but I don't know if it is the correct way and how to remove element. Can you help me? Thanks

答:
I resolved with this code, I don't know if it is the best code:

```<code>export class ComponentService {
  private agent: Agent;
  // Observable navItem source
  agentChange = new ReplaySubject<Agent>(1);

  constructor() { }

   /************ AGENT MANAGEMENT *****************/
   get getAgent(){
     return this.agent;
   }

   setAgent(agent: Agent){
     this.agent = agent;
   }

   deleteAgent(){
     this.agentChange.next(this.agent);
     this.agent = null;
   }
}
</code>```

then in the custroctor of component I have the subscribe and the unsubscribe into destroy method:

```<code>this.componentService.agentChange.subscribe((agent:Agent)=>{
     //on success instruction
    })

ngOnDestroy() {
    this.componentService.agentChange.unsubscribe();
  }
</code>```

Body:
I'm using angular 6 and I need to update the component when I call a service method. I have a variable agentthat keep the selected agent from html so I get this variable from several component and I can delete this agent from a specific button.

When I call deleteAgent I have to update the interface so I need a way to "tell" to the component that the agent was deleted.

export class ComponentService {
  private agent : Agent
  constructor() { }

   /************ AGENT MANAGEMENT *****************/
   get getAgent(){
     return this.agent;
   }

   setAgent(agent: Agent){
     this.agent = agent;
   }

   deleteAgent(){
     this.agent = null;
     //inform the component about the change
   }
}

I read about ReplaySubject but I don't know if it is the correct way and how to remove element. Can you help me? Thanks

Body:
I resolved with this code, I don't know if it is the best code:

export class ComponentService {
  private agent: Agent;
  // Observable navItem source
  agentChange = new ReplaySubject<Agent>(1);

  constructor() { }

   /************ AGENT MANAGEMENT *****************/
   get getAgent(){
     return this.agent;
   }

   setAgent(agent: Agent){
     this.agent = agent;
   }

   deleteAgent(){
     this.agentChange.next(this.agent);
     this.agent = null;
   }
}

then in the custroctor of component I have the subscribe and the unsubscribe into destroy method:

this.componentService.agentChange.subscribe((agent:Agent)=>{
     //on success instruction
    })

ngOnDestroy() {
    this.componentService.agentChange.unsubscribe();
  }


问:
Run all Python scripts in a folder - from Python
How can I write a Python program that runs all Python scripts in the current folder? The program should run in Linux, Windows and any other OS in which python  is installed.

Here is what I tried:

```<code>import glob, importlib

for file in glob.iglob("*.py"):
    importlib.import_module(file)
</code>```

This returns an error: ModuleNotFoundError: No module named 'agents.py'; 'agents' is not a package
(here agents.py is one of the files in the folder; it is indeed not a package and not intended to be a package - it is just a script).

If I change the last line to:

```<code>    importlib.import_module(file.replace(".py",""))
</code>```

then I get no error, but also the scripts do not run.

Another attempt:

```<code>import glob, os

for file in glob.iglob("*.py"):
    os.system(file)
</code>```

This does not work on Windows - it tries to open each file in Notepad.

答:
You need to specify that you are running the script through the command line. To do this you need to add python3 plus the name of the file that you are running. The following code should work

```<code>import os
import glob

for file in glob.iglob("*.py"):
    os.system("python3 " + file)
</code>```

If you are using a version other than python3, just change the argument from python3 to python

Body:
How can I write a Python program that runs all Python scripts in the current folder? The program should run in Linux, Windows and any other OS in which python  is installed.

Here is what I tried:

import glob, importlib

for file in glob.iglob("*.py"):
    importlib.import_module(file)

This returns an error: ModuleNotFoundError: No module named 'agents.py'; 'agents' is not a package
(here agents.py is one of the files in the folder; it is indeed not a package and not intended to be a package - it is just a script).

If I change the last line to:

    importlib.import_module(file.replace(".py",""))

then I get no error, but also the scripts do not run.

Another attempt:

import glob, os

for file in glob.iglob("*.py"):
    os.system(file)

This does not work on Windows - it tries to open each file in Notepad.

Body:
You need to specify that you are running the script through the command line. To do this you need to add python3 plus the name of the file that you are running. The following code should work

import os
import glob

for file in glob.iglob("*.py"):
    os.system("python3 " + file)

If you are using a version other than python3, just change the argument from python3 to python


问:
How to change the property class for row in data blocks using oracle form builder?
I want to make the row change color when clicking on it. I want to change it using property pallete.</p>

答:
If your mean to paint an individual row of a Database Block with "Number of Records Displayed" >0 ;

open up Property Palette,

go to Records node,

and toggle "Current Record Visual Attribute Group" then set as a
Visual Attribute as you wish as previously created.


问:
Help writing a stored procedure / SQL Query error
I have table tblcategory with columns categoryid , shopid , title, logicalcode.

I have a second table tblproduct with columns productid, shopid, producttitle ,price ,logicalcode , available.

I have a third table categoryproduct with columns categoryproductid, categoryid, productid

I have a grid view for displaying products in a given category with columns producttitle and logicalcode.

I have written a stored procedure with input parameter as categoryid (mandatory) to get the list of products in that category:

```<code>@categoryid int
AS
BEGIN
  SELECT P.Title, P.LogicalCode
  FROM tblProduct AS P
  JOIN  tblCategory AS C
  WHERE P.LogicalCode=C.LogicalCode AND
  WHERE C.CategoryID=@categoryid
END
</code>```

But I got the error near to "WHERE" condition

Would anyone please help me out?

答:
You have two WHERE clauses. It should be:

WHERE P.LogicalCode=C.LogicalCode AND
      C.CategoryID=@categoryid

EDIT

OK, try

```<code>SELECT P.Title,P.LogicalCode
FROM tblProduct P
JOIN tblCategory C
ON P.LogicalCode=C.LogicalCode
WHERE C.CategoryID=@categoryid
</code>```

Body:
I have table tblcategory with columns categoryid , shopid , title, logicalcode.

I have a second table tblproduct with columns productid, shopid, producttitle ,price ,logicalcode , available.

I have a third table categoryproduct with columns categoryproductid, categoryid, productid

I have a grid view for displaying products in a given category with columns producttitle and logicalcode.

I have written a stored procedure with input parameter as categoryid (mandatory) to get the list of products in that category:

@categoryid int
AS
BEGIN
  SELECT P.Title, P.LogicalCode
  FROM tblProduct AS P
  JOIN  tblCategory AS C
  WHERE P.LogicalCode=C.LogicalCode AND
  WHERE C.CategoryID=@categoryid
END

But I got the error near to "WHERE" condition

Would anyone please help me out?

Body:
You have two WHERE clauses. It should be:

WHERE P.LogicalCode=C.LogicalCode AND
      C.CategoryID=@categoryid

EDIT

OK, try

SELECT P.Title,P.LogicalCode
FROM tblProduct P
JOIN tblCategory C
ON P.LogicalCode=C.LogicalCode
WHERE C.CategoryID=@categoryid


问:
Decimal to Binary converstion (fixed length) and reversing the order
I am writing a perl script which will generate string output of 0s and 1s.

I have numbers from 2 to 27. I want to convert them to binary number of fixed length 5 and then reverse the order.

For example, if I convert 2 to binary, it will be 00010 (fixed length of 5) and then I would like to get it reversed such that output is 01000.

I am iterating the numbers through a for loop in perl.

What will be a sweet one liner or 2 to do this. Any bash or perl one liner or 2 that I can use in my perl script.

I am able to do it in 2 lines though but still looking for any one liner in bash.

```<code>for (my $i=02; $i <= 27; $i++) {
    my $j = sprintf ("%05b\n", $i);
    my $k = reverse $j;
}
</code>```

Body:
I am writing a perl script which will generate string output of 0s and 1s.

I have numbers from 2 to 27. I want to convert them to binary number of fixed length 5 and then reverse the order.

For example, if I convert 2 to binary, it will be 00010 (fixed length of 5) and then I would like to get it reversed such that output is 01000.

I am iterating the numbers through a for loop in perl.

What will be a sweet one liner or 2 to do this. Any bash or perl one liner or 2 that I can use in my perl script.

I am able to do it in 2 lines though but still looking for any one liner in bash.

for (my $i=02; $i <= 27; $i++) {
    my $j = sprintf ("%05b\n", $i);
    my $k = reverse $j;
}

Body:
Try this:

say for map { scalar reverse sprintf "%05b", $_ } 2..27;

Output:

01000
11000
00100
10100
01100
11100
00010
10010
01010
11010
00110
10110
01110
11110
00001
10001
01001
11001
00101
10101
01101
11101
00011
10011
01011
11011


问:
How to update value inside object from inputText
Sorry guys i'am still learning react native and i want update value of each qty(quantity) item from input, so i have this state,

```<code>this.state={
 selectedObject={
   otherAttributes:'',
   items:[
     {name:'a',qty:''},
     {name:'b',qty:''},
   ],
  },

}
</code>```

then i have this function to render the TextInput,

```<code>renderPage(){
 return this.state.selectedObject.items.map(item ,i)=>
   <View style={{margin:15}}>
     <Text>Name: {item.name}</Text>
     <TextInput style={styles.input} keyboardType='numeric' maxLength={10}
       value={?}
       onChangeText={?}
      }}/>
   </View>
  )
}
</code>```

and i dont know what to do inside the value and onchangeText,

This is what i tried, in the TextInput

```<code>renderPage(){
  const itemqty = this.state.selectedObject.items;
  return itemqty.map((item,i)=>
    <View style={{margin:15}}>
      <Text>Name: {item.name}</Text>
      <TextInput style={styles.input} keyboardType='numeric'
         value={itemqty[i].qty}
         onChangeText={(qty)=>{
         this.setState({items[i].qty: qty});
     }}/>
  </View>
  )
}
</code>```

after trying this i'am aware that value can't have '[i]' aswell as in the setState. Because i was trying so that the value qty will go to the respected items qty as well when setState it.

So what i expect is i can change the value of the quantity of the items from the input that are available in this case there are 2, but later on it can be 3,4,5,6 items with qty in each one and set it to the respected state.

Thank you

答:
Try to avoid state mutation, by not updating the array directly.

```<code>hanldeChange = (value, index) => {
  const items = [
    ...this.state.selectedObject.items.slice(0, index),
    Object.assign({}, this.state.selectedObject.items[index], { qty: value }),
    ...this.state.selectedObject.items.slice(index + 1),
  ];

  this.setState(prevState => ({
    selectedObject: {
      ...prevState.selectedObject,
      items: items,
    },
  }));
};
</code>```

In your input do

```<code><TextInput
  style={styles.input}
  keyboardType="numeric"
  value={this.state.selectedObject.items[i].qty}
  onChangeText={qty => this.hanldeChange(qty, i)}
/>
</code>```

Body:
Sorry guys i'am still learning react native and i want update value of each qty(quantity) item from input, so i have this state,

this.state={
 selectedObject={
   otherAttributes:'',
   items:[
     {name:'a',qty:''},
     {name:'b',qty:''},
   ],
  },

}

then i have this function to render the TextInput,

renderPage(){
 return this.state.selectedObject.items.map(item ,i)=>
   <View style={{margin:15}}>
     <Text>Name: {item.name}</Text>
     <TextInput style={styles.input} keyboardType='numeric' maxLength={10}
       value={?}
       onChangeText={?}
      }}/>
   </View>
  )
}

and i dont know what to do inside the value and onchangeText,

This is what i tried, in the TextInput

renderPage(){
  const itemqty = this.state.selectedObject.items;
  return itemqty.map((item,i)=>
    <View style={{margin:15}}>
      <Text>Name: {item.name}</Text>
      <TextInput style={styles.input} keyboardType='numeric'
         value={itemqty[i].qty}
         onChangeText={(qty)=>{
         this.setState({items[i].qty: qty});
     }}/>
  </View>
  )
}

after trying this i'am aware that value can't have '[i]' aswell as in the setState. Because i was trying so that the value qty will go to the respected items qty as well when setState it.

So what i expect is i can change the value of the quantity of the items from the input that are available in this case there are 2, but later on it can be 3,4,5,6 items with qty in each one and set it to the respected state.

Thank you

Body:
Try to avoid state mutation, by not updating the array directly.

hanldeChange = (value, index) => {
  const items = [
    ...this.state.selectedObject.items.slice(0, index),
    Object.assign({}, this.state.selectedObject.items[index], { qty: value }),
    ...this.state.selectedObject.items.slice(index + 1),
  ];

  this.setState(prevState => ({
    selectedObject: {
      ...prevState.selectedObject,
      items: items,
    },
  }));
};

In your input do

<TextInput
  style={styles.input}
  keyboardType="numeric"
  value={this.state.selectedObject.items[i].qty}
  onChangeText={qty => this.hanldeChange(qty, i)}
/>


问:
Efficiently selecting distinct (a, b) from big table
I have a table with around 54 million rows in a Postgres 9.6 DB and would like to find all distinct pairs of two columns (there are around 4 million such values). I have an index over the two columns of interest:

```<code>create index ab_index on tbl (a, b)
</code>```

What is the most efficient way to get such pairs? I have tried:

```<code>select a,b
from tbl
where a>$previouslargesta
group by a,b
order by a,b
limit 1000
</code>```

And also:

```<code>select distinct(a,b)
from tbl
where a>previouslargesta
order by a,b
limit 1000
</code>```

Also this recursive query:

```<code>with recursive t AS (
  select min(a) AS a from tbl
  union all
  select (select min(a) from tickets where a > t.a)
  FROM t)
select a FROM t
</code>```

But all are slooooooow.

Is there a faster way to get this information?

答:
I cannot guarantee for performance at Postgres, but this is a technique i had used on sql server in a similar case and proven faster than others:

get distinct A into a temp a

get distinct B into a temp b

cross a and b temps to Cartesian into a temp abALL

rank the abALL (optionally)

create a view myview as select top 1 a,b from tbl (your_main_table)

join temp abALL with myview into a temp abCLEAN

rank abCLEAN here if you havent rank above

Body:
I have a table with around 54 million rows in a Postgres 9.6 DB and would like to find all distinct pairs of two columns (there are around 4 million such values). I have an index over the two columns of interest:

create index ab_index on tbl (a, b)

What is the most efficient way to get such pairs? I have tried:

select a,b
from tbl
where a>$previouslargesta
group by a,b
order by a,b
limit 1000

And also:

select distinct(a,b)
from tbl
where a>previouslargesta
order by a,b
limit 1000

Also this recursive query:

with recursive t AS (
  select min(a) AS a from tbl
  union all
  select (select min(a) from tickets where a > t.a)
  FROM t)
select a FROM t

But all are slooooooow.

Is there a faster way to get this information?


问:
using getFragmentSupport Manager inside PreferenceFragment
I found this library that I want to use inside my PreferenceFragment extended class, my problem is that the getSupportFragmentManager can not be resolved.
My question is how do I show the fragment when it extends a PreferenceFragment

I tried changing to getFragmentManager but won't work

```<code>public class PreferencesFragment extends PreferenceFragment {

 final Preference currencyPreference = findPreference(getResources().getString(R.string.setting_category_currency_key));
        currencyPreference.setOnPreferenceClickListener(preference -> {
            //selectCurrencyDialog = new SelectCurrencyFragment();
            //selectCurrencyDialog.show(((SettingsActivity) getActivity()).getSupportFragmentManager(), "SelectCurrency");

            CurrencyPicker picker = CurrencyPicker.newInstance("Select Currency");  // dialog title
            picker.setListener((name, code, symbol, flagDrawableResID) -> {
                // Implement your code here
            });
            picker.show(getSupportFragmentManager(), "CURRENCY_PICKER");

            return false;
        });

}
</code>```

The error is on this Line

getSupportFragmentManager()

```<code>picker.show(getSupportFragmentManager(), "CURRENCY_PICKER");
</code>```

答:
have you tried replacing getSupportFragmentManager() with PreferencesFragment.this.getActivity().getSupportFragmentManager()?

This works by returning the parent activity of your PreferencesFragment and obtaining it's fragment manager. You would want to use PreferencesFragment.this.getActivity().getFragmentManager() instead, if your parent activity extends an activity from the support library.

Body:
I found this library that I want to use inside my PreferenceFragment extended class, my problem is that the getSupportFragmentManager can not be resolved.
My question is how do I show the fragment when it extends a PreferenceFragment

I tried changing to getFragmentManager but won't work

public class PreferencesFragment extends PreferenceFragment {

 final Preference currencyPreference = findPreference(getResources().getString(R.string.setting_category_currency_key));
        currencyPreference.setOnPreferenceClickListener(preference -> {
            //selectCurrencyDialog = new SelectCurrencyFragment();
            //selectCurrencyDialog.show(((SettingsActivity) getActivity()).getSupportFragmentManager(), "SelectCurrency");

            CurrencyPicker picker = CurrencyPicker.newInstance("Select Currency");  // dialog title
            picker.setListener((name, code, symbol, flagDrawableResID) -> {
                // Implement your code here
            });
            picker.show(getSupportFragmentManager(), "CURRENCY_PICKER");

            return false;
        });

}

The error is on this Line

getSupportFragmentManager()

picker.show(getSupportFragmentManager(), "CURRENCY_PICKER");


问:
Best possible ways to copy link
I'm looking for a suitable way to copy URL (link) to the clipboard.

Can someone tell me how this can be achieved?

function copyURL() {
  var elem = document.createElement("textarea");
  document.body.appendChild(elem);
  elem.value = google.com;
  elem.select();
  document.execCommand("copy");
  document.body.removeChild(elem);
  document.write("Copied to clipboard!");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Copy URL</code>```

答:
You can use window.location.href and .execCommand on a hidden textarea:

var url = document.getElementById('url')
url.value = location.href
url.select()
document.execCommand("copy");```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Not hidden for example:<br>
<textarea id="url"></textarea></code>```

Title: Best possible ways to copy link

Body:
I'm looking for a suitable way to copy URL (link) to the clipboard.

Can someone tell me how this can be achieved?

function copyURL() {
  var elem = document.createElement("textarea");
  document.body.appendChild(elem);
  elem.value = google.com;
  elem.select();
  document.execCommand("copy");
  document.body.removeChild(elem);
  document.write("Copied to clipboard!");
}

Copy URL

Body:
You can use window.location.href and .execCommand on a hidden textarea:

var url = document.getElementById('url')
url.value = location.href
url.select()
document.execCommand("copy");

Not hidden for example:<br>
<textarea id="url"></textarea>


问:
Neo4j Cypher Client Create Dynamic Objects
At the moment I have to specify what class is needed during the return, is there a way to get all properties and and create a dynamic/anonymous object.</p>

```<code>public IEnumerable<Node> GetNodes()
    {
        Console.WriteLine($"Retrieving All Nodes from DB...");
        try
        {
            return graphClient.Cypher
               .Match($"(n:Node)")
               .Return(t => new Node
               {
                   Latitude = Return.As<double>("n.lat"),
                   Longitude = Return.As<double>("n.lon"),
                   Id = Return.As<string>("n.id"),
                   ValA = Return.As<long>("n.valA")
               }).Results;
        }
        catch (Exception ex)
        {
            string error = $"ERROR (Get Node): {ex.ToString()}";
            Console.WriteLine(error);
        }

        return null;
    }
</code>```

答:
Try with the Neo4J official C# driver and JSON.NET like:

```<code>public static void Main()
{
    string neo4jHostname = string.Empty, neo4jUsername = string.Empty, neo4jPassword = string.Empty;
    IDriver driver = GraphDatabase.Driver(neo4jHostname, AuthTokens.Basic(neo4jUsername, neo4jPassword));

    using (ISession session = driver.Session())
    {
        string query = "MATCH (n) RETURN n";
        IStatementResult resultCursor = session.Run(query);
        List<IRecord> res = resultCursor.ToList();
        string values = JsonConvert.SerializeObject(res.Select(x => x.Values), Formatting.Indented);
        List<JObject> nodes = JsonConvert.DeserializeObject<List<JObject>>(values);
    }
}
</code>```

Body:
At the moment I have to specify what class is needed during the return, is there a way to get all properties and and create a dynamic/anonymous object.

public IEnumerable<Node> GetNodes()
    {
        Console.WriteLine($"Retrieving All Nodes from DB...");
        try
        {
            return graphClient.Cypher
               .Match($"(n:Node)")
               .Return(t => new Node
               {
                   Latitude = Return.As<double>("n.lat"),
                   Longitude = Return.As<double>("n.lon"),
                   Id = Return.As<string>("n.id"),
                   ValA = Return.As<long>("n.valA")
               }).Results;
        }
        catch (Exception ex)
        {
            string error = $"ERROR (Get Node): {ex.ToString()}";
            Console.WriteLine(error);
        }

        return null;
    }

Body:
Try with the Neo4J official C# driver and JSON.NET like:

public static void Main()
{
    string neo4jHostname = string.Empty, neo4jUsername = string.Empty, neo4jPassword = string.Empty;
    IDriver driver = GraphDatabase.Driver(neo4jHostname, AuthTokens.Basic(neo4jUsername, neo4jPassword));

    using (ISession session = driver.Session())
    {
        string query = "MATCH (n) RETURN n";
        IStatementResult resultCursor = session.Run(query);
        List<IRecord> res = resultCursor.ToList();
        string values = JsonConvert.SerializeObject(res.Select(x => x.Values), Formatting.Indented);
        List<JObject> nodes = JsonConvert.DeserializeObject<List<JObject>>(values);
    }
}


问:
Wordpress woocommerce -> in which PHP file
 is generated?
Woocommerce, Which PHP file inside /plugins/woocommerce/ ...... generates the code (?) :

```<code><div class="content-area  container">
  <div class="row">
    <main id="main" class="site-main  col-xs-12  col-md-9" role="main">
</code>```

???????????????????

Look at this picture for more details https://i.postimg.cc/bpw42mDf/mega.png

I searched both in:

```<code>/wp-content/plugins/woocommerce/templates/content-single-product.php
</code>```

and

```<code>/wp-content/themes/bolts-pt/page.php
</code>```

...but in neigher can I find this code which I posted above.

I can even erase the whole page.php in bolts-pt theme and it does not affect the woocommerce product page so that code can't be in page.php file in themes/bolts-pt/ folder

答:
Please check this path

```<code>/wp-content/plugins/woocommerce/includes/theme-support/class-wc-twenty-nineteen.php

public static function output_content_wrapper() {
    echo '<section id="primary" class="content-area balasaheb">';
    echo '<main id="main" class="site-main">';
}
</code>```

OR Please check hooks

```<code>woocommerce_before_main_content
</code>```

Title: Wordpress woocommerce -> in which PHP file <div class="content-area container"> is generated?

Body:
Woocommerce, Which PHP file inside /plugins/woocommerce/ ...... generates the code (?) :

???????????????????

Look at this picture for more details https://i.postimg.cc/bpw42mDf/mega.png

I searched both in:

/wp-content/plugins/woocommerce/templates/content-single-product.php

and

/wp-content/themes/bolts-pt/page.php

...but in neigher can I find this code which I posted above.

I can even erase the whole page.php in bolts-pt theme and it does not affect the woocommerce product page so that code can't be in page.php file in themes/bolts-pt/ folder

Body:
Please check this path

/wp-content/plugins/woocommerce/includes/theme-support/class-wc-twenty-nineteen.php

public static function output_content_wrapper() {
    echo '<section id="primary" class="content-area balasaheb">';
    echo '<main id="main" class="site-main">';
}

OR Please check hooks

woocommerce_before_main_content


答:
Try making a dummy input, copying it, then removing it.

function copyURL() {
  var elem = document.createElement("textarea");
  document.body.appendChild(elem);
  elem.value = location.href;
  elem.select();
  document.execCommand("copy");
  document.body.removeChild(elem);
  document.write("Copied to clipboard!");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="copyURL()">Copy URL</button></code>```

Title: Best possible ways to copy link

Body:
Try making a dummy input, copying it, then removing it.

function copyURL() {
  var elem = document.createElement("textarea");
  document.body.appendChild(elem);
  elem.value = location.href;
  elem.select();
  document.execCommand("copy");
  document.body.removeChild(elem);
  document.write("Copied to clipboard!");
}

<button onclick="copyURL()">Copy URL</button>


问:
Question about DateAdd function and information
I'm currently writing some SQL and have come upon an odd issue.

The code i'm using is:

```<code>select * from #table1
where datefield = DATEADD(day, -2, getdate())
</code>```

The issue i'm running into is it won't pull any information like this. If I add a '>' to the '=' it pulls information. If I put an exact date into teh query instead of the 'dateadd' piece it pulls the correct records.

I've tested the date parameters and there are matching records for 4/10/2011. But for some reason it just does not like the '= dateadd' in this instance.

I have also attempted to use the 'current_timestamp' string instead of 'getdate' as well with the same results.

Any suggestions?

答:
Getdate() returns a Datetime, which includes a time portion.  I'm guessing you are matching against just a date.  Try:

where datefield = CAST(DATEADD(day, -2, getdate())) as DATE)

Body:
I'm currently writing some SQL and have come upon an odd issue.

The code i'm using is:

select * from #table1
where datefield = DATEADD(day, -2, getdate())

The issue i'm running into is it won't pull any information like this. If I add a '>' to the '=' it pulls information. If I put an exact date into teh query instead of the 'dateadd' piece it pulls the correct records.

I've tested the date parameters and there are matching records for 4/10/2011. But for some reason it just does not like the '= dateadd' in this instance.

I have also attempted to use the 'current_timestamp' string instead of 'getdate' as well with the same results.

Any suggestions?


问:
how to narrow the type for SVG Element union
I am using react to set a reference to an svg element that might be a <rect>, <polygon> or <ellipse>.

I have this declaration:

```<code>const shapeRef = useRef<SVGPolygonElement | SVGEllipseElement | SVGRectElement>(null);
</code>```

But when I try and set this on an <ellipse> element like this:

```<code><ellipse
  cx={width / 8}
  cy={-sideDimension(y) / 8}
  rx={width}
  ry={height}
  ref={shapeRef}
/>
</code>```

I get this error:

Type 'RefObject' is not assignable to type 'string | ((instance:
  SVGEllipseElement | null) => void) | RefObject |
  null | undefined'.   Type 'RefObject' is not assignable to type
  'RefObject'.
      Type 'SVGPolygonElement | SVGEllipseElement | SVGRectElement' is not assignable to type 'SVGEllipseElement'.
        Type 'SVGPolygonElement' is missing the following properties from type 'SVGEllipseElement': cx, cy, rx, ryts(2322)

My understanding from this is that I somehow need to narrow the type in order for this to work or else every object that uses this ref must have all properties of the union.

答:
You are correct. Typescript gives you that error because it doesn't know which one of the types it should account the shapreRef as.

The best solution IMO is using a Type Guards. A Type Guard is the typescript way to check if a variable is of a certain type. For union types, that gives typescript the understanding that something is of a specific type.

For example, in your case, it can be something like this:

interface IEllipse {
  attr1: string;
  attr2: string;
}

interface IRect {
  attr3: string;
  attr4: string;
}

type SvgShape = IEllipse | IRect | IPolygon;

function isEllipse(shape: SvgShape): shape is IEllipse {
    return (shape as IEllipse).attr1 !== undefined;
}

```

<p>Notice that the return type is <code>shape is IEllipse</code>. This means that typescript will interpret a truthy return value here as if <code>shape</code> <strong>is an <code>IEllipse</code></strong>.</p>

<p>Then, wherever you want to use a <code>SvgShape</code>, you can check which type of <code>SvgShape</code> it is and typescript should know the type based on that:</p>

<pre class="lang-ts prettyprint-override"><code>// ...
render() {
  const shape: SvgShape = this.getCurrentShape();

  if (isEllipse(shape)) {
    // typescript should KNOW that this is an ellipse inside this if
    // it will accept all of Ellipse's attribute and reject other attributes
    // that appear in other shapes

    return <ellipse .../>;
  } else if (isRect(shape)) {
    // typescript should interpet this shape as a Rect inside the `if`

    return <rect ... />;
  } else {
    // typescript will know only one subtype left (IPolygon)

    return <polygon points="..." />;
  }
}
// ...
</code>```

Why not just an Intersection type?

Well... Intersection types are more for cases where every one of the types (Rect, Polygon, etc) have the exact same attributes in the new item.
For example:

type Inter = IRect & IPolygon & IEllipse;
```

<p>Means that an <code>Inter</code> type is <code>IRect</code> and <code>IPolygon</code> and <code>IEllipse</code>. That means an object of this type will have all members of all three types.
So, trying to access the attribute <code>points</code> (which exists on <code>IPolygon</code>) on a shape that is actually an <code>IRect</code>, will act as if that attribute exists there (which we don't want)</p>

<p>You will mostly see intersection types used for mixins and other concepts that don’t fit in the classic object-oriented mold.</p>

<h3>how to use with useRef?</h3>

<pre class="lang-ts prettyprint-override"><code>type SvgShape = SVGPolygonElement | SVGEllipseElement | SVGRectElement;

const shapeRef = useRef<SvgShape>(null);

function isEllipseRef(shapeRef: MutableRefObject<SvgShape>): shapeRef is MutableRefObject<IEllipse> {
  const shape: SvgShape = shapeRef.current;
  return (shape as IEllipse).attr1 !== undefined;
}
</code>```

Body:
I am using react to set a reference to an svg element that might be a <rect>, <polygon> or <ellipse>.

I have this declaration:

const shapeRef = useRef<SVGPolygonElement | SVGEllipseElement | SVGRectElement>(null);

But when I try and set this on an <ellipse> element like this:

<ellipse
  cx={width / 8}
  cy={-sideDimension(y) / 8}
  rx={width}
  ry={height}
  ref={shapeRef}
/>

I get this error:

Type 'RefObject' is not assignable to type 'string | ((instance:
  SVGEllipseElement | null) => void) | RefObject |
  null | undefined'.   Type 'RefObject' is not assignable to type
  'RefObject'.
      Type 'SVGPolygonElement | SVGEllipseElement | SVGRectElement' is not assignable to type 'SVGEllipseElement'.
        Type 'SVGPolygonElement' is missing the following properties from type 'SVGEllipseElement': cx, cy, rx, ryts(2322)

My understanding from this is that I somehow need to narrow the type in order for this to work or else every object that uses this ref must have all properties of the union.

Body:
You are correct. Typescript gives you that error because it doesn't know which one of the types it should account the shapreRef as.

The best solution IMO is using a Type Guards. A Type Guard is the typescript way to check if a variable is of a certain type. For union types, that gives typescript the understanding that something is of a specific type.

For example, in your case, it can be something like this:

interface IEllipse {
  attr1: string;
  attr2: string;
}

interface IRect {
  attr3: string;
  attr4: string;
}

type SvgShape = IEllipse | IRect | IPolygon;

function isEllipse(shape: SvgShape): shape is IEllipse {
    return (shape as IEllipse).attr1 !== undefined;
}

Notice that the return type is shape is IEllipse. This means that typescript will interpret a truthy return value here as if shape is an IEllipse.

Then, wherever you want to use a SvgShape, you can check which type of SvgShape it is and typescript should know the type based on that:

// ...
render() {
  const shape: SvgShape = this.getCurrentShape();

  if (isEllipse(shape)) {
    // typescript should KNOW that this is an ellipse inside this if
    // it will accept all of Ellipse's attribute and reject other attributes
    // that appear in other shapes

    return <ellipse .../>;
  } else if (isRect(shape)) {
    // typescript should interpet this shape as a Rect inside the `if`

    return <rect ... />;
  } else {
    // typescript will know only one subtype left (IPolygon)

    return <polygon points="..." />;
  }
}
// ...

Why not just an Intersection type?

Well... Intersection types are more for cases where every one of the types (Rect, Polygon, etc) have the exact same attributes in the new item.
For example:

type Inter = IRect & IPolygon & IEllipse;

Means that an Inter type is IRect and IPolygon and IEllipse. That means an object of this type will have all members of all three types.
So, trying to access the attribute points (which exists on IPolygon) on a shape that is actually an IRect, will act as if that attribute exists there (which we don't want)

You will mostly see intersection types used for mixins and other concepts that don’t fit in the classic object-oriented mold.

how to use with useRef?

type SvgShape = SVGPolygonElement | SVGEllipseElement | SVGRectElement;

const shapeRef = useRef<SvgShape>(null);

function isEllipseRef(shapeRef: MutableRefObject<SvgShape>): shapeRef is MutableRefObject<IEllipse> {
  const shape: SvgShape = shapeRef.current;
  return (shape as IEllipse).attr1 !== undefined;
}


问:
Getting Undefined
I am working on LoopBack and Angular project.
I have JSON object but I getting output null when accessing the JSON object.

I storing the object like this var file =   res.result.files.file;
where res has the JSON object
And Accessing the Object like this
var filename = file.name;
which is returning Undefined,

how can I get the name form the JSON Object
here is the output of the file

```<code>[{ container: 'Images',
    name: '1559211341196.jpg',
    type: 'multipart/form-data',
    field: 'file',
    size: 3577522,
    providerResponse: undefined }]
</code>```

form this i want to access the 'name:' Parameter, I tried this file. name, but I am getting an output as null,

how can I access the name parameter and store it in a variable?

Here is the code:

```<code>{
    'use strict';
    module.exports = function (Picture) {
        Picture.afterRemote('upload', function (ctx, res, next) {
            var http = require('request');
            var file = res.result.files.file;
            console.log(file);
            console.log(JSON.stringify(file.container + file.name + file.size));
            var i = http.get('http://192.168.1.11:3000/api/Pictures/Images/files/1559211341196.jpg', { json: true }, (body) => {
            });
            console.log(i.uri.href);
            next();
        })
    };
}
</code>```

答:
Your response looks like an array of objects, so you will have to get it like this:

var file = res.result.files.file[0]; or res.result.files[0], it depends...

Maybe you could have several files, not just one? in that case i'd recomend to map them instead, something like...

var files = res.result.files.reduce((l, i) => ({...l, [i.name]: i}),{})

So you can have a map of files and access them with files.file1, files['187263871623.jpg'] etc

EDIT1: I'd move that require('http') out od the export, it's a module, you can share it between calls and if you have it inside the export it'll probably be called more than once.

Title: Getting Undefined

Body:
I am working on LoopBack and Angular project.
I have JSON object but I getting output null when accessing the JSON object.

I storing the object like this var file =   res.result.files.file;
where res has the JSON object
And Accessing the Object like this
var filename = file.name;
which is returning Undefined,

how can I get the name form the JSON Object
here is the output of the file

[{ container: 'Images',
    name: '1559211341196.jpg',
    type: 'multipart/form-data',
    field: 'file',
    size: 3577522,
    providerResponse: undefined }]

form this i want to access the 'name:' Parameter, I tried this file. name, but I am getting an output as null,

how can I access the name parameter and store it in a variable?

Here is the code:

{
    'use strict';
    module.exports = function (Picture) {
        Picture.afterRemote('upload', function (ctx, res, next) {
            var http = require('request');
            var file = res.result.files.file;
            console.log(file);
            console.log(JSON.stringify(file.container + file.name + file.size));
            var i = http.get('http://192.168.1.11:3000/api/Pictures/Images/files/1559211341196.jpg', { json: true }, (body) => {
            });
            console.log(i.uri.href);
            next();
        })
    };
}


Title: Why does `unix_timestamp` behave differently on Spark 2.3.x/2.0.x?

Body:
Trying to do a simple transformation using unix_timestamp behave differently from Spark 2.0.2 and 2.3.x.

At first, I was thinking it could be a Spark environment related issue, like timezone differences.
But all the settings are the same.

The example below shows the described behavior.

import org.apache.spark.sql.types.{TimestampType}

case class Dummy(mts:String, sts:String)

val testData = Seq(Dummy("2018-05-09-06.57.53.013768", "2018-05-09-06.57.53.013198"), Dummy("2018-11-21-04.30.03.804441", "2018-11-21-04.30.03.802212")).toDF

val result = testData
      .withColumn("time1", unix_timestamp(col("sts"), "yyyy-MM-dd-HH.mm.ss.SSSSSS").cast(TimestampType))
      .withColumn("time2", unix_timestamp(col("sts"), "yyyy-MM-dd-HH.mm.ss.SSSSSS").cast(TimestampType))

result.select($"time1", $"time2", $"sts", $"mts").show(false)

scala> spark.version
res25: String = 2.3.1.3.0.1.0-187

scala> result.select("time1", "time2", "sts", "mts").show(false)
+-----+-----+--------------------------+--------------------------+
|time1|time2|sts                      |mts                      |
+-----+-----+--------------------------+--------------------------+
|null |null |2018-05-09-06.57.53.013198|2018-05-09-06.57.53.013768|
|null |null |2018-11-21-04.30.03.802212|2018-11-21-04.30.03.804441|
+-----+-----+--------------------------+--------------------------+

scala>

scala> spark.version
   def version: String

scala> spark.version
res4: String = 2.0.2

scala> result.select("time1", "time2", "sts", "mts").show(false)
+---------------------+---------------------+--------------------------+--------------------------+
|time1                |time2                |sts                      |mts                      |
+---------------------+---------------------+--------------------------+--------------------------+
|2018-05-09 06:58:06.0|2018-05-09 06:58:06.0|2018-05-09-06.57.53.013198|2018-05-09-06.57.53.013768|
|2018-11-21 04:43:25.0|2018-11-21 04:43:27.0|2018-11-21-04.30.03.802212|2018-11-21-04.30.03.804441|
+---------------------+---------------------+--------------------------+--------------------------+

Is there any particular reason for this behavior?

Body:
The problem you have is related to the function unix_timestamp.

It converts a string to Unix timestamp in seconds. So anything after seconds is ignored.
Spark 2.0.2 was quite forgiving and substituted the SSSSSS part of your pattern with a 0.

However, somewhere between Spark 2.0.2 and 2.3.x, the implementation changed and it, and you have a null to call your attention to it.

How to solve it? Just remove the .SSSSSS and it looks like this:

val result = testData
  .withColumn("time1", unix_timestamp(col("sts"), "yyyy-MM-dd-HH.mm.ss").cast(TimestampType))
  .withColumn("time2", unix_timestamp(col("sts"), "yyyy-MM-dd-HH.mm.ss").cast(TimestampType))

result.select("time1", "time2", "sts", "mts").show(false)

+-------------------+-------------------+--------------------------+--------------------------+
|time1              |time2              |sts                       |mts                       |
+-------------------+-------------------+--------------------------+--------------------------+
|2018-05-09 06:57:53|2018-05-09 06:57:53|2018-05-09-06.57.53.013198|2018-05-09-06.57.53.013768|
|2018-11-21 04:30:03|2018-11-21 04:30:03|2018-11-21-04.30.03.802212|2018-11-21-04.30.03.804441|
+-------------------+-------------------+--------------------------+--------------------------+


问:
What does "listPointer->leftPointer->rightPointer = newNodePtr;" do?
It is my first time encountering this type of pointer. It points then points again, what does this imply? I encountered this on a doubly linked list program.</p>

```<code>listPointer->leftPointer->rightPointer = newNodePtr;
</code>```

答:
It probably is part of inserting a new element. If you do it correctly, you only need to know about the element after where you wish to insert it, and the element you are inserting. The other element can be gotten by following the links.

Starting from

```<code>             listPtr
                |
                v
----------  ----------
|        |->|        |
| Node L |  |  Node  |
|        |<-|        |
----------  ----------

newNodePtr
   |
   v
----------
|        |
| Node N |
|        |
----------
</code>```

First do

```<code>listPointer->leftPointer->rightPointer = newNodePtr;
</code>```

So that the preceding element points to the new element

```<code>               newNodePtr    listPtr
                  |             |
                  v             v
----------    ----------    ----------
|        |--->|        |    |        |
| Node L |    | Node N |    |  Node  |
|        |<-| |        |  |-|        |
----------  | ----------  | ----------
            |             |
            |-------------|
</code>```

Then do

```<code>newNodePtr->leftPointer = listPointer->leftPointer;
</code>```

So that the new element points to the preceding element

```<code>               newNodePtr    listPtr
                  |             |
                  v             v
----------    ----------    ----------
|        |--->|        |    |        |
| Node L |<---| Node N |    |  Node  |
|        |<-| |        |  |-|        |
----------  | ----------  | ----------
            |             |
            |-------------|
</code>```

Then do

```<code>listPointer->leftPointer = newNodePtr;
</code>```

So that the following element points back to the new element

```<code>             newNodePtr  listPtr
                |           |
                v           v
----------  ----------  ----------
|        |->|        |  |        |
| Node L |  | Node N |  |  Node  |
|        |<-|        |<-|        |
----------  ----------  ----------
</code>```

Then finally

```<code>newNodePtr->rightPointer = listPointer;
</code>```

So that the new element points at the following element

```<code>             newNodePtr  listPtr
                |           |
                v           v
----------  ----------  ----------
|        |->|        |->|        |
| Node L |  | Node N |  |  Node  |
|        |<-|        |<-|        |
----------  ----------  ----------
</code>```

Body:
It is my first time encountering this type of pointer. It points then points again, what does this imply? I encountered this on a doubly linked list program.

listPointer->leftPointer->rightPointer = newNodePtr;

Body:
It probably is part of inserting a new element. If you do it correctly, you only need to know about the element after where you wish to insert it, and the element you are inserting. The other element can be gotten by following the links.

Starting from

             listPtr
                |
                v
----------  ----------
|        |->|        |
| Node L |  |  Node  |
|        |<-|        |
----------  ----------

newNodePtr
   |
   v
----------
|        |
| Node N |
|        |
----------

First do

listPointer->leftPointer->rightPointer = newNodePtr;

So that the preceding element points to the new element

               newNodePtr    listPtr
                  |             |
                  v             v
----------    ----------    ----------
|        |--->|        |    |        |
| Node L |    | Node N |    |  Node  |
|        |<-| |        |  |-|        |
----------  | ----------  | ----------
            |             |
            |-------------|

Then do

newNodePtr->leftPointer = listPointer->leftPointer;

So that the new element points to the preceding element

               newNodePtr    listPtr
                  |             |
                  v             v
----------    ----------    ----------
|        |--->|        |    |        |
| Node L |<---| Node N |    |  Node  |
|        |<-| |        |  |-|        |
----------  | ----------  | ----------
            |             |
            |-------------|

Then do

listPointer->leftPointer = newNodePtr;

So that the following element points back to the new element

             newNodePtr  listPtr
                |           |
                v           v
----------  ----------  ----------
|        |->|        |  |        |
| Node L |  | Node N |  |  Node  |
|        |<-|        |<-|        |
----------  ----------  ----------

Then finally

newNodePtr->rightPointer = listPointer;

So that the new element points at the following element

             newNodePtr  listPtr
                |           |
                v           v
----------  ----------  ----------
|        |->|        |->|        |
| Node L |  | Node N |  |  Node  |
|        |<-|        |<-|        |
----------  ----------  ----------


问:
how to make a 2 level array to asimple array
I have an array like this:

```<code>[12601] => Array (
        ['docUpload'] => html dom.txt
)

[12602] => Array (
        ['docUpload'] => PYTHON AND DJANGO ARE HUGE IN FINTECH.txt
)
[12603] => Array (
        ['docUpload'] =>
)
</code>```

How to get it like this:

```<code>12601 => html dom.txt
12602 => PYTHON AND DJANGO ARE HUGE IN FINTECH.txt
</code>```

can you help me please?

答:
You need to do as follows:

```<code>foreach ($arrayData as &$value) {
    $value = isset($value['docUpload']) ? $value['docUpload'] : '';
}
</code>```

It will result in following array:

```<code>[docUpload] => [
    [12601] => html dom.txt
    [12602] => PYTHON AND DJANGO ARE HUGE IN FINTECH.txt
];
</code>```

Body:
I have an array like this:

[12601] => Array (
        ['docUpload'] => html dom.txt
)

[12602] => Array (
        ['docUpload'] => PYTHON AND DJANGO ARE HUGE IN FINTECH.txt
)
[12603] => Array (
        ['docUpload'] =>
)

How to get it like this:

12601 => html dom.txt
12602 => PYTHON AND DJANGO ARE HUGE IN FINTECH.txt

can you help me please?

Body:
You need to do as follows:

foreach ($arrayData as &$value) {
    $value = isset($value['docUpload']) ? $value['docUpload'] : '';
}

It will result in following array:

[docUpload] => [
    [12601] => html dom.txt
    [12602] => PYTHON AND DJANGO ARE HUGE IN FINTECH.txt
];


问:
Converting Swift code to Objective-C errors
Im try to convert from swift to Objective-C, but have errors

```<code>func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {

    print(url)

    let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true)

    let host = urlComponents?.host ?? ""

    print(host)

    return true
}
</code>```

In object try:

```<code>  - (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {

    printf("%s", url);

    NSURLComponents * const urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true);

    NSString * const host = urlComponents.host ?? ""

    printf(host);
    return true;
    }
</code>```

But have error

Implicit declaration of function 'URLComponents' is invalid in C99

答:
Try this., It will work without error... </p>

```<code>- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
   NSLog(@"%@", url);
   NSURLComponents * const urlComponents = [[NSURLComponents alloc] initWithURL:url resolvingAgainstBaseURL:true];
   NSString * const host = urlComponents.host;
   NSLog(@"%@", host);
   return true;
}
</code>```

Body:
Im try to convert from swift to Objective-C, but have errors

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {

    print(url)

    let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true)

    let host = urlComponents?.host ?? ""

    print(host)

    return true
}

In object try:

  - (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {

    printf("%s", url);

    NSURLComponents * const urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true);

    NSString * const host = urlComponents.host ?? ""

    printf(host);
    return true;
    }

But have error

Implicit declaration of function 'URLComponents' is invalid in C99

Body:
Try this., It will work without error...

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
   NSLog(@"%@", url);
   NSURLComponents * const urlComponents = [[NSURLComponents alloc] initWithURL:url resolvingAgainstBaseURL:true];
   NSString * const host = urlComponents.host;
   NSLog(@"%@", host);
   return true;
}


问:
Not able to get path from URI in android
I am trying to upload an image from the camera. I'm using file provider for this, but the thing is when I try to create PATH from image URI it's not working. I tried almost everything but it's not working. I am not able to get path from URI.

Manifest.xml:

```<code>      <provider
        android:authorities="${applicationId}.provider"
        android:name="android.support.v4.content.FileProvider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths"/>
           </provider>
</code>```

file_paths.xml:

```<code>    <?xml version="1.0" encoding="utf-8"?>
       <paths>
          <files-path name="image_picked" path="picked/" />
          <external-path name="*" path="."/>
       </paths>
</code>```

Image uploading code:

```<code>   private void openCameraIntent() {

    if (MarshMallowPermissionUtils.checkPermissionForCamera(this)) {
        Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (pictureIntent.resolveActivity(getPackageManager()) != null) {

            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
            photoUri = FileProvider.getUriForFile(this, getPackageName() + ".provider", photoFile);
            pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
            startActivityForResult(pictureIntent, REQUEST_IMAGE);
        }
    }
    else {
        MarshMallowPermissionUtils.requestPermissionForCamera(this);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (requestCode == REQUEST_PERMISSION && grantResults.length > 0) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "Thanks for granting Permission", Toast.LENGTH_SHORT).show();
        }
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_IMAGE) {
        if (resultCode == RESULT_OK) {
            imageView.setImageURI(Uri.parse(imageFilePath));
        } else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(this, "You cancelled the operation", Toast.LENGTH_SHORT).show();
        }
    }
}

private File createImageFile() throws IOException {

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
    String imageFileName = "deep_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(imageFileName, ".jpg", storageDir);
    imageFilePath = image.getAbsolutePath();

    return image;
}

  public String getRealPathFromURI(Context context, Uri contentUri)
 {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri,  proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
 } finally {
   if (cursor != null) {
  cursor.close();
  }
  }
  }
</code>```

Path from URI:

```<code>     private void getPathFromUri(){

    String path = getRealPathFromURI(DemoCam.this,photoUri);
    if (path != null) {
        File file = new File(path);

        String contentType = file.toURL().openConnection().getContentType();
        fileBody = RequestBody.create(MediaType.parse(contentType), file);
        String filename = "file_" + System.currentTimeMillis() / 1000L;
    }
    }
</code>```

Uploading Code:

```<code>        private void execMultipartPost() throws Exception {

    String path = getRealPathFromURI(DemoCam.this,photoUri);

    RequestBody requestBody;

    if (path != null) {

        File file = new File(path);
        String contentType = file.toURL().openConnection().getContentType();
        fileBody = RequestBody.create(MediaType.parse(contentType), file);
        String filename = "file_" + System.currentTimeMillis() / 1000L;

        requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image_file", filename + ".jpg", fileBody)
                .addFormDataPart("name", "eere")
                .addFormDataPart("user_id", "346")
                .addFormDataPart("email", "a@gmail.com")
                .addFormDataPart("postal_code", "121001")
                .addFormDataPart("phone", "7503366400")
                .addFormDataPart("type", "S")
                .addFormDataPart("address", "fefrfrf")
                .addFormDataPart("gender", "M")
                .addFormDataPart("skype_id", "hde.jfjf")
                .build();
   }

    okhttp3.Request request = new okhttp3.Request.Builder()
            .url(Constants.EDIT_PROFILE_DATA)
            .post(requestBody)
            .addHeader("Authorization", "Bearer " + api_token)
            .build();

    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(150, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build();

    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, final IOException e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    Toast.makeText(DemoCam.this, e.toString(), Toast.LENGTH_SHORT).show();
                    Log.e("TAG", "run:error " + e.toString());
                    e.printStackTrace();
                }
            });
        }

        @Override
        public void onResponse(Call call, final okhttp3.Response response) throws IOException {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {

                        ResponseBody responseBody = response.body();
                        String content = responseBody.string();

                        Log.e("TAG", "advisor profile content: " + content);

                    } catch (Exception e) {

                        Toast.makeText(DemoCam.this, e.toString(), Toast.LENGTH_SHORT).show();

                        //pBar.setVisibility(View.GONE);

                        e.printStackTrace();

                    }

                }
            });
        }

    });
}
</code>```

答:
i have faced similar problem in my app and i have used below code to get path from uri

follow these steps:

call Camera Intent:

please add this line in camera intent

Uri  mPhotoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new ContentValues());

intent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);

```<code> /*for getting image using camera*/
    private void cameraIntent() {
      Uri  mPhotoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new ContentValues());
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);
        startActivityForResult(intent, GlobalString.REQUEST_CAMERA);
    }
</code>```

OnActivityResult

```<code>@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("data===", "" + data);
        // creating method gallery camera and file
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == GlobalString.SELECT_GALLERY) {
                onSelectFromGalleryResult(data);
            }
            else if (requestCode == GlobalString.REQUEST_CAMERA) {
                onCaptureImageResult(data);
            }
        }
    }

/* this method use camera*/
    private void onCaptureImageResult(Intent data) {

        String path = null;
        Log.i(TAG, "check capture image uri---" + mPhotoUri);
        try {
            Log.i(TAG,"check image path:--"+getRealPathFromURI(mPhotoUri));
      path =getRealPathFromURI(mPhotoUri);
    }Catch(Exception e)
       {
        Log.e(TAG,"Exception--"+e);
        }
       }
</code>```

getRealPathFromURI()

```<code>private String getRealPathFromURI(Uri contentURI) {
        String filePath;
        Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
        if (cursor == null) {
            filePath = contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            filePath = cursor.getString(idx);
            cursor.close();
        }
        return filePath;
    }
</code>```

Try this code to get image path from URI. its work for me

Body:
I am trying to upload an image from the camera. I'm using file provider for this, but the thing is when I try to create PATH from image URI it's not working. I tried almost everything but it's not working. I am not able to get path from URI.

Manifest.xml:

      <provider
        android:authorities="${applicationId}.provider"
        android:name="android.support.v4.content.FileProvider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths"/>
           </provider>

file_paths.xml:

    <?xml version="1.0" encoding="utf-8"?>
       <paths>
          <files-path name="image_picked" path="picked/" />
          <external-path name="*" path="."/>
       </paths>

Image uploading code:

   private void openCameraIntent() {

    if (MarshMallowPermissionUtils.checkPermissionForCamera(this)) {
        Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (pictureIntent.resolveActivity(getPackageManager()) != null) {

            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
            photoUri = FileProvider.getUriForFile(this, getPackageName() + ".provider", photoFile);
            pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
            startActivityForResult(pictureIntent, REQUEST_IMAGE);
        }
    }
    else {
        MarshMallowPermissionUtils.requestPermissionForCamera(this);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (requestCode == REQUEST_PERMISSION && grantResults.length > 0) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "Thanks for granting Permission", Toast.LENGTH_SHORT).show();
        }
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_IMAGE) {
        if (resultCode == RESULT_OK) {
            imageView.setImageURI(Uri.parse(imageFilePath));
        } else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(this, "You cancelled the operation", Toast.LENGTH_SHORT).show();
        }
    }
}

private File createImageFile() throws IOException {

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
    String imageFileName = "deep_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(imageFileName, ".jpg", storageDir);
    imageFilePath = image.getAbsolutePath();

    return image;
}

  public String getRealPathFromURI(Context context, Uri contentUri)
 {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri,  proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
 } finally {
   if (cursor != null) {
  cursor.close();
  }
  }
  }

Path from URI:

     private void getPathFromUri(){

    String path = getRealPathFromURI(DemoCam.this,photoUri);
    if (path != null) {
        File file = new File(path);

        String contentType = file.toURL().openConnection().getContentType();
        fileBody = RequestBody.create(MediaType.parse(contentType), file);
        String filename = "file_" + System.currentTimeMillis() / 1000L;
    }
    }

Uploading Code:

        private void execMultipartPost() throws Exception {

    String path = getRealPathFromURI(DemoCam.this,photoUri);

    RequestBody requestBody;

    if (path != null) {

        File file = new File(path);
        String contentType = file.toURL().openConnection().getContentType();
        fileBody = RequestBody.create(MediaType.parse(contentType), file);
        String filename = "file_" + System.currentTimeMillis() / 1000L;

        requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image_file", filename + ".jpg", fileBody)
                .addFormDataPart("name", "eere")
                .addFormDataPart("user_id", "346")
                .addFormDataPart("email", "a@gmail.com")
                .addFormDataPart("postal_code", "121001")
                .addFormDataPart("phone", "7503366400")
                .addFormDataPart("type", "S")
                .addFormDataPart("address", "fefrfrf")
                .addFormDataPart("gender", "M")
                .addFormDataPart("skype_id", "hde.jfjf")
                .build();
   }

    okhttp3.Request request = new okhttp3.Request.Builder()
            .url(Constants.EDIT_PROFILE_DATA)
            .post(requestBody)
            .addHeader("Authorization", "Bearer " + api_token)
            .build();

    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(150, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build();

    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, final IOException e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    Toast.makeText(DemoCam.this, e.toString(), Toast.LENGTH_SHORT).show();
                    Log.e("TAG", "run:error " + e.toString());
                    e.printStackTrace();
                }
            });
        }

        @Override
        public void onResponse(Call call, final okhttp3.Response response) throws IOException {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {

                        ResponseBody responseBody = response.body();
                        String content = responseBody.string();

                        Log.e("TAG", "advisor profile content: " + content);

                    } catch (Exception e) {

                        Toast.makeText(DemoCam.this, e.toString(), Toast.LENGTH_SHORT).show();

                        //pBar.setVisibility(View.GONE);

                        e.printStackTrace();

                    }

                }
            });
        }

    });
}

Body:
i have faced similar problem in my app and i have used below code to get path from uri

follow these steps:

call Camera Intent:

please add this line in camera intent

Uri  mPhotoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new ContentValues());

intent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);

 /*for getting image using camera*/
    private void cameraIntent() {
      Uri  mPhotoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new ContentValues());
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);
        startActivityForResult(intent, GlobalString.REQUEST_CAMERA);
    }

OnActivityResult

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("data===", "" + data);
        // creating method gallery camera and file
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == GlobalString.SELECT_GALLERY) {
                onSelectFromGalleryResult(data);
            }
            else if (requestCode == GlobalString.REQUEST_CAMERA) {
                onCaptureImageResult(data);
            }
        }
    }

/* this method use camera*/
    private void onCaptureImageResult(Intent data) {

        String path = null;
        Log.i(TAG, "check capture image uri---" + mPhotoUri);
        try {
            Log.i(TAG,"check image path:--"+getRealPathFromURI(mPhotoUri));
      path =getRealPathFromURI(mPhotoUri);
    }Catch(Exception e)
       {
        Log.e(TAG,"Exception--"+e);
        }
       }

getRealPathFromURI()

private String getRealPathFromURI(Uri contentURI) {
        String filePath;
        Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
        if (cursor == null) {
            filePath = contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            filePath = cursor.getString(idx);
            cursor.close();
        }
        return filePath;
    }

Try this code to get image path from URI. its work for me


问:
Is it possible to create an optional literal in Swift?
I have explained my query in the code snippet below. I am looking for this type of syntax for Obj-C interoperability. Specifically I see a difference in behaviour of aCoder.encode(count, forKey: "count") API when count is Int (non-optional) vs Int? (optional)

```<code>import Foundation

let num = 5
// Swift's type system will infer this as Int (non-optional)
print(type(of: num))
// Prints: Int

let optNum: Int? = 5
// This is explicitly typed as an optional Int
print(type(of: optNum))
// Prints Optional<Int>
</code>```

Is it possible to use a literal to implicitly type a var/let to optional?

```<code>// let imlicitOptional = 5?
// print(type(of: imlicitOptional))
// The above line should print: Optional<Int>

// or

// let imlicitOptional = num?
// print(type(of: imlicitOptional))
// The above line should print: Optional<Int>
</code>```

答:
Optional is a plain enum not any specific magic type. So, you can create a value using Optional:

```<code>let implicitOptional = Optional(5)
print(type(of: implicitOptional)) // Optional<Int>
</code>```

Body:
I have explained my query in the code snippet below. I am looking for this type of syntax for Obj-C interoperability. Specifically I see a difference in behaviour of aCoder.encode(count, forKey: "count") API when count is Int (non-optional) vs Int? (optional)

import Foundation

let num = 5
// Swift's type system will infer this as Int (non-optional)
print(type(of: num))
// Prints: Int

let optNum: Int? = 5
// This is explicitly typed as an optional Int
print(type(of: optNum))
// Prints Optional<Int>

Is it possible to use a literal to implicitly type a var/let to optional?

// let imlicitOptional = 5?
// print(type(of: imlicitOptional))
// The above line should print: Optional<Int>

// or

// let imlicitOptional = num?
// print(type(of: imlicitOptional))
// The above line should print: Optional<Int>

Body:
Optional is a plain enum not any specific magic type. So, you can create a value using Optional:

let implicitOptional = Optional(5)
print(type(of: implicitOptional)) // Optional<Int>