问:
Error not raising from BULK INSERT IN try block
hi i have written the below code inside a try block but does not raising error to catch block . but stand alone bulk insert generating error messages.</p>

```<code>BEGIN TRY

SET @sql =
                '
                    BULK INSERT dbo.vw_Data_Import_ISO_CSP_OPMHC_Premium--<-- table view
                    FROM ''' + @SourceFilePath + '''
                    WITH ( FIRSTROW = 2, FIELDTERMINATOR = ''|'', ROWTERMINATOR = ''\n'' );
                '

EXECUTE (@sql)

END TRY
BEGIN CATCH

        SELECT
            @error_number = ERROR_NUMBER(),
            @error_message = ERROR_MESSAGE(),
            @error_line = ERROR_LINE()
        SELECT @error_description = 'T-SQL error number ' + CAST(@error_number AS VARCHAR(10))  + ' on line ' + CAST(@error_line AS VARCHAR(10)) + '.'

END CATCH
</code>```

答:
You are not raising an error in the CATCH block, only assigning a variable value. Try adding RAISERROR:

```<code>BEGIN TRY
    SET @sql = ' BULK INSERT dbo.vw_Data_Import_ISO_CSP_OPMHC_Premium --<-- table view
FROM ''' + @SourceFilePath + ''' WITH ( FIRSTROW = 2, FIELDTERMINATOR = ''|'', ROWTERMINATOR = ''\n'', MAXERRORS = 0 );'
    EXECUTE (@sql);
END TRY BEGIN CATCH
    SELECT
        @error_number = ERROR_NUMBER(),
        @error_message = ERROR_MESSAGE(),
        @error_line = ERROR_LINE();
    SELECT @error_description = 'T-SQL error number ' + CAST(@error_number AS VARCHAR(10))  + ' on line ' + CAST(@error_line AS VARCHAR(10)) + '.';
    RAISERROR(@error_description, 16, 1);
END CATCH;
</code>```

In SQL Server 2012 and later, the CATCH block can be simplified using THROW:

```<code>BEGIN CATCH
    IF @@TRANCOUNT > 0 ROLLBACK;
    THROW;
END CATCH;
</code>```

EDIT:

As suggested in the comments, a non-zero MAXERRORS specification is useful in situations where some records in the source cannot be parsed and may be skipped. The default is 10 if not specified.

Body:
hi i have written the below code inside a try block but does not raising error to catch block . but stand alone bulk insert generating error messages.

BEGIN TRY

SET @sql =
                '
                    BULK INSERT dbo.vw_Data_Import_ISO_CSP_OPMHC_Premium--<-- table view
                    FROM ''' + @SourceFilePath + '''
                    WITH ( FIRSTROW = 2, FIELDTERMINATOR = ''|'', ROWTERMINATOR = ''\n'' );
                '

EXECUTE (@sql)

END TRY
BEGIN CATCH

        SELECT
            @error_number = ERROR_NUMBER(),
            @error_message = ERROR_MESSAGE(),
            @error_line = ERROR_LINE()
        SELECT @error_description = 'T-SQL error number ' + CAST(@error_number AS VARCHAR(10))  + ' on line ' + CAST(@error_line AS VARCHAR(10)) + '.'

END CATCH

Body:
You are not raising an error in the CATCH block, only assigning a variable value. Try adding RAISERROR:

BEGIN TRY
    SET @sql = ' BULK INSERT dbo.vw_Data_Import_ISO_CSP_OPMHC_Premium --<-- table view
FROM ''' + @SourceFilePath + ''' WITH ( FIRSTROW = 2, FIELDTERMINATOR = ''|'', ROWTERMINATOR = ''\n'', MAXERRORS = 0 );'
    EXECUTE (@sql);
END TRY BEGIN CATCH
    SELECT
        @error_number = ERROR_NUMBER(),
        @error_message = ERROR_MESSAGE(),
        @error_line = ERROR_LINE();
    SELECT @error_description = 'T-SQL error number ' + CAST(@error_number AS VARCHAR(10))  + ' on line ' + CAST(@error_line AS VARCHAR(10)) + '.';
    RAISERROR(@error_description, 16, 1);
END CATCH;

In SQL Server 2012 and later, the CATCH block can be simplified using THROW:

BEGIN CATCH
    IF @@TRANCOUNT > 0 ROLLBACK;
    THROW;
END CATCH;

EDIT:

As suggested in the comments, a non-zero MAXERRORS specification is useful in situations where some records in the source cannot be parsed and may be skipped. The default is 10 if not specified.


来源: stackexchange

问:
Activity Indicator Stuck while Navigating in xamarin forms
Im using xamarin forms 2.3.4.247 shared project. In my login page im navigating my page to another. while this page is rendering im showing a Activity Indicator in Main Page. But unfortunately Activity Indicator Stucks And After A couple of seconds the second page loads.ive tried these codes below and i got nothing.All of these codes are running into an async command.im testing my app in actual device on android platform.

1

```<code>activityIndicator.IsRunnig=true;
    new System.Threading.Thread(new System.Threading.ThreadStart(() =>
                        {
                            Navigation.PushAsync(new DeviceLoginView());
                        })).Start();
</code>```

2

```<code>activityIndicator.IsRunnig=true;
Device.BeginInvokeOnMainThread(async () =>
                {
                    await Navigation.PushAsync(new DeviceLoginView());
                });
</code>```

3

```<code> activityIndicator.IsRunnig=true;
 await Navigation.PushAsync(new DeviceLoginView());
</code>```

答:
i Finally was able to make this issue right.
you can do all your asynchronous jobs in a Task.Run() method to run all of them in a new thread and NOT in the UI thread</p>

ContentLicense: CC BY-SA 3.0

Body:
Im using xamarin forms 2.3.4.247 shared project. In my login page im navigating my page to another. while this page is rendering im showing a Activity Indicator in Main Page. But unfortunately Activity Indicator Stucks And After A couple of seconds the second page loads.ive tried these codes below and i got nothing.All of these codes are running into an async command.im testing my app in actual device on android platform.

1

activityIndicator.IsRunnig=true;
    new System.Threading.Thread(new System.Threading.ThreadStart(() =>
                        {
                            Navigation.PushAsync(new DeviceLoginView());
                        })).Start();

2

activityIndicator.IsRunnig=true;
Device.BeginInvokeOnMainThread(async () =>
                {
                    await Navigation.PushAsync(new DeviceLoginView());
                });

3

 activityIndicator.IsRunnig=true;
 await Navigation.PushAsync(new DeviceLoginView());


问:
How can I build the 64-bit version of the Crypto++ dll?
I'm currently working on implementing the crypto++ libs into a c# app. It's all working fine in 32 bit.
However when I tried to build the c++ DLL in 64 bit, I got this error:

Error 1 error PRJ0019: A tool returned an error code from "Performing Custom Build Step" cryptopp cryptopp

I then changed the project settings to build in Unicode from the default multibyte, and got it to build with no errors. However, it will then fail the safety check when using the GetPowerUpSelfTestStatus().

I've googled the heck out of this, and apparently this is not an uncommon problem. However no one seems to have found a solution, or at least hasn't shared it.

What can I do?

答: The problem was with the custom build step options under the project preferences. Just change the leading output directory folder from 'Win32' to 'x64' with x64 as your target platform. =/</p>

ContentLicense: CC BY-SA 2.5


问:
How to determine pid of process started via os.system
I want to start several subprocesses with a programm, i.e. a module foo.py starts several instances of bar.py.

Since I sometimes have to terminate the process manually, I need the process id to perform a kill command.

Even though the whole setup is pretty “dirty”, is there a good pythonic way to obtain a process’ pid, if the process is started via os.system?

foo.py:

```<code>import os
import time
os.system("python bar.py \"{0}\ &".format(str(argument)))
time.sleep(3)
pid = ???
os.system("kill -9 {0}".format(pid))
</code>```

bar.py:

```<code>import time
print("bla")
time.sleep(10) % within this time, the process should be killed
print("blubb")
</code>```

答:
Sharing my solution in case it can help others:

I took the info from this page to run a fortran exe in the background. I tried to use os.forkpty to get the pid of it, but it didnt give the pid of my process. I cant use subprocess, because I didnt find out how it would let me run my process on the background.

With help of a colleague I found this:

```<code>exec_cmd = 'nohup ./FPEXE & echo $! > /tmp/pid'

os.system(exec_cmd)
</code>```

In case of wanting to append pids to the same file, use double arrow.

Body:
I want to start several subprocesses with a programm, i.e. a module foo.py starts several instances of bar.py.

Since I sometimes have to terminate the process manually, I need the process id to perform a kill command.

Even though the whole setup is pretty “dirty”, is there a good pythonic way to obtain a process’ pid, if the process is started via os.system?

foo.py:

import os
import time
os.system("python bar.py \"{0}\ &".format(str(argument)))
time.sleep(3)
pid = ???
os.system("kill -9 {0}".format(pid))

bar.py:

import time
print("bla")
time.sleep(10) % within this time, the process should be killed
print("blubb")

Body:
Sharing my solution in case it can help others:

I took the info from this page to run a fortran exe in the background. I tried to use os.forkpty to get the pid of it, but it didnt give the pid of my process. I cant use subprocess, because I didnt find out how it would let me run my process on the background.

With help of a colleague I found this:

exec_cmd = 'nohup ./FPEXE & echo $! > /tmp/pid'

os.system(exec_cmd)

In case of wanting to append pids to the same file, use double arrow.


问:
How to read this from file and get each value alone
I have this text file and I need to extract it to a Java program to determine array sizes and its values I can read each line alone but I can't get the value for lines that contains many numbers. Plus, how to count element in the third line.( 0 2 ) </p>

```<code>4
5
0 2

0 1 0.6
0 2 0.2
0 3 0.5
1 3 0.8
2 3 0.3
</code>```

<p>this code that I'm using: </p>

```<code> List<Integer> list = new ArrayList<Integer>();
        File file = new File("D:\\ALGORTHIMS\\MASTER LEVEL\\dr. khaled\\assignment 1\\text.txt");
        BufferedReader reader = null;
         List<Double> ints = new ArrayList<Double>();

        try {
            reader = new BufferedReader(new FileReader(file));
            String text = null;

            while ((text = reader.readLine()) != null) {
                if (text.length() == 1) {
                    list.add(Integer.parseInt(text));
                } else {

                    String[] strs = text.trim().split("\\s+");

                    for (int i = 0; i < strs.length; i++) {
                        ints.add(Double.parseDouble(strs[i]));
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {

            }
        }

//print out the list
        System.out.println(list);

        System.out.println(ints);
</code>```

答:
I think that using Scanner is optimal solution.
E.g. in case we have file

```<code>4 5

 0  1  2  3.1
 4  5  6  7.2
 8  9 10 11.3
12 13 14 15.4
16 17 18 19.5
</code>```

where we define an array with 4 row and 5 columns. Then to get it in int[][] arr we could use following approach:

```<code>public static void main(String... args) throws FileNotFoundException {
    double[][] arr = null;

    try (Scanner scan = new Scanner(new FileInputStream(new File("text.txt")))) {
        scan.useLocale(Locale.US);  // to use '.' as separator
        int rows = scan.nextInt();
        int columns = scan.nextInt();
        scan.nextLine();

        arr = new double[rows][columns];

        for (int i = 0; i < rows; i++)
            for (int j = 0; j < columns; j++)
                arr[i][j] = scan.nextDouble();
    }

    System.out.println(Arrays.toString(arr));
}
</code>```

Body:
I have this text file and I need to extract it to a Java program to determine array sizes and its values I can read each line alone but I can't get the value for lines that contains many numbers. Plus, how to count element in the third line.( 0 2 )

4
5
0 2

0 1 0.6
0 2 0.2
0 3 0.5
1 3 0.8
2 3 0.3

this code that I'm using:

 List<Integer> list = new ArrayList<Integer>();
        File file = new File("D:\\ALGORTHIMS\\MASTER LEVEL\\dr. khaled\\assignment 1\\text.txt");
        BufferedReader reader = null;
         List<Double> ints = new ArrayList<Double>();

        try {
            reader = new BufferedReader(new FileReader(file));
            String text = null;

            while ((text = reader.readLine()) != null) {
                if (text.length() == 1) {
                    list.add(Integer.parseInt(text));
                } else {

                    String[] strs = text.trim().split("\\s+");

                    for (int i = 0; i < strs.length; i++) {
                        ints.add(Double.parseDouble(strs[i]));
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {

            }
        }

//print out the list
        System.out.println(list);

        System.out.println(ints);

Body:
I think that using Scanner is optimal solution.
E.g. in case we have file

4 5

 0  1  2  3.1
 4  5  6  7.2
 8  9 10 11.3
12 13 14 15.4
16 17 18 19.5

where we define an array with 4 row and 5 columns. Then to get it in int[][] arr we could use following approach:

public static void main(String... args) throws FileNotFoundException {
    double[][] arr = null;

    try (Scanner scan = new Scanner(new FileInputStream(new File("text.txt")))) {
        scan.useLocale(Locale.US);  // to use '.' as separator
        int rows = scan.nextInt();
        int columns = scan.nextInt();
        scan.nextLine();

        arr = new double[rows][columns];

        for (int i = 0; i < rows; i++)
            for (int j = 0; j < columns; j++)
                arr[i][j] = scan.nextDouble();
    }

    System.out.println(Arrays.toString(arr));
}


问:
Selendroid program not connecting with Appium, can't do automated testing
I have used Selendroid to write a JAVA program to automate testing in android app, but there is an error coming constantly, I have included selendroid-standalone-0.17.0-with-dependencies.jar,  java-client-5.0.4.jar. java-client-5.0.4-sources.jar, java-client-5.0.4-javadoc.jar files in library, still the error is occuring. Please Help, in great need.

Error :
Exception in thread "main" org.openqa.selenium.WebDriverException: Returned value cannot be converted to WebElement: {ELEMENT=1}
Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
System info: host: 'Kapil-PC', ip: '192.168.43.212', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_92'
Driver info: driver.version: AndroidDriver
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:360)
    at io.appium.java_client.DefaultGenericMobileDriver.findElement(DefaultGenericMobileDriver.java:62)
    at io.appium.java_client.AppiumDriver.findElement(AppiumDriver.java:1)
    at io.appium.java_client.android.AndroidDriver.findElement(AndroidDriver.java:1)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:403)
    at io.appium.java_client.DefaultGenericMobileDriver.findElementById(DefaultGenericMobileDriver.java:70)
    at io.appium.java_client.AppiumDriver.findElementById(AppiumDriver.java:1)
    at io.appium.java_client.android.AndroidDriver.findElementById(AndroidDriver.java:1)
    at org.openqa.selenium.By$ById.findElement(By.java:218)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:345)
    at io.appium.java_client.DefaultGenericMobileDriver.findElement(DefaultGenericMobileDriver.java:58)
    at io.appium.java_client.AppiumDriver.findElement(AppiumDriver.java:1)
    at io.appium.java_client.android.AndroidDriver.findElement(AndroidDriver.java:1)
    at inventorytest.InventoryTest.main(InventoryTest.java:85)
Caused by: java.lang.ClassCastException: java.util.HashMap cannot be cast to org.openqa.selenium.WebElement
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:358)
    ... 13 more
C:\Users\Kapil\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 10 seconds)

And Code :

```<code>package inventorytest;
import io.appium.java_client.android.AndroidDriver;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.CapabilityType;
 import org.openqa.selenium.remote.DesiredCapabilities;
public class InventoryTest {

 private static AndroidDriver driver;
public static void main(String[] args) throws MalformedURLException,
InterruptedException
{

DesiredCapabilities capabilities = new DesiredCapabilities();

capabilities.setCapability(CapabilityType.BROWSER_NAME, "hih");

capabilities.setCapability("deviceName", "My New Phone");

capabilities.setCapability("platformVersion", "6.0");

capabilities.setCapability("platformName", "Android");

capabilities.setCapability("appPackage", "com.example.kapil.inventory");

capabilities.setCapability("appActivity", ".add_new_item");

driver = new AndroidDriver(new URL("http://0.0.0.0:4723/wd/hub"), capabilities);

driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

 driver.findElement(By.id("editText5")).sendKeys("Hello");

Thread.sleep(10000);
 driver.quit();

            }

}
</code>```

答:
Take a look how Appium contributors write Selendroid tests:

```<code>DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator");
capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath());
capabilities.setCapability(AndroidMobileCapabilityType.SELENDROID_PORT, SELENDROID_PORT);
capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.SELENDROID);
driver = new AndroidDriver<>(service.getUrl(), capabilities);
driver.context("NATIVE_APP");
</code>```

Check element searching strategies and make sure you use the right one.

Body:
I have used Selendroid to write a JAVA program to automate testing in android app, but there is an error coming constantly, I have included selendroid-standalone-0.17.0-with-dependencies.jar,  java-client-5.0.4.jar. java-client-5.0.4-sources.jar, java-client-5.0.4-javadoc.jar files in library, still the error is occuring. Please Help, in great need.

Error :
Exception in thread "main" org.openqa.selenium.WebDriverException: Returned value cannot be converted to WebElement: {ELEMENT=1}
Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
System info: host: 'Kapil-PC', ip: '192.168.43.212', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_92'
Driver info: driver.version: AndroidDriver
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:360)
    at io.appium.java_client.DefaultGenericMobileDriver.findElement(DefaultGenericMobileDriver.java:62)
    at io.appium.java_client.AppiumDriver.findElement(AppiumDriver.java:1)
    at io.appium.java_client.android.AndroidDriver.findElement(AndroidDriver.java:1)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:403)
    at io.appium.java_client.DefaultGenericMobileDriver.findElementById(DefaultGenericMobileDriver.java:70)
    at io.appium.java_client.AppiumDriver.findElementById(AppiumDriver.java:1)
    at io.appium.java_client.android.AndroidDriver.findElementById(AndroidDriver.java:1)
    at org.openqa.selenium.By$ById.findElement(By.java:218)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:345)
    at io.appium.java_client.DefaultGenericMobileDriver.findElement(DefaultGenericMobileDriver.java:58)
    at io.appium.java_client.AppiumDriver.findElement(AppiumDriver.java:1)
    at io.appium.java_client.android.AndroidDriver.findElement(AndroidDriver.java:1)
    at inventorytest.InventoryTest.main(InventoryTest.java:85)
Caused by: java.lang.ClassCastException: java.util.HashMap cannot be cast to org.openqa.selenium.WebElement
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:358)
    ... 13 more
C:\Users\Kapil\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 10 seconds)

And Code :

package inventorytest;
import io.appium.java_client.android.AndroidDriver;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.CapabilityType;
 import org.openqa.selenium.remote.DesiredCapabilities;
public class InventoryTest {

 private static AndroidDriver driver;
public static void main(String[] args) throws MalformedURLException,
InterruptedException
{

DesiredCapabilities capabilities = new DesiredCapabilities();

capabilities.setCapability(CapabilityType.BROWSER_NAME, "hih");

capabilities.setCapability("deviceName", "My New Phone");

capabilities.setCapability("platformVersion", "6.0");

capabilities.setCapability("platformName", "Android");

capabilities.setCapability("appPackage", "com.example.kapil.inventory");

capabilities.setCapability("appActivity", ".add_new_item");

driver = new AndroidDriver(new URL("http://0.0.0.0:4723/wd/hub"), capabilities);

driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

 driver.findElement(By.id("editText5")).sendKeys("Hello");

Thread.sleep(10000);
 driver.quit();

            }

}

Body:
Take a look how Appium contributors write Selendroid tests:

DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator");
capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath());
capabilities.setCapability(AndroidMobileCapabilityType.SELENDROID_PORT, SELENDROID_PORT);
capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.SELENDROID);
driver = new AndroidDriver<>(service.getUrl(), capabilities);
driver.context("NATIVE_APP");

Check element searching strategies and make sure you use the right one.


问:
How to configure Spring Batch RetryPolicy in workflow.xml file?
I am working on introducing a customize retry policy in my Spring Batch job. Following is my sample step define in the workflow. But i am not getting where to define/configure the "retry-policy"?

Please help.

```<code><job id="job1" job-repository="jobRepository">
      <step id="step1">
         <tasklet transaction-manager="jobRepository-transactionManager"  >
             <b:bean parent="tasklet1" scope="step">
                    <b:property name="scriptFile" value="script"/>
             </b:bean>
            </tasklet>
            <next on="COMPLETED" to="step2"/>
            <next on="FAILED" to="error"/>
        </step>
</job>
</code>```

答:
Here is an example on official site on how to configure Spring Batch RetryPolicy for chunks.

```<code><step id="step1">
   <tasklet>
      <chunk reader="itemReader" writer="itemWriter"
             commit-interval="2" retry-limit="3">
         <retryable-exception-classes>
            <include class="org.springframework.dao.DeadlockLoserDataAccessException"/>
         </retryable-exception-classes>
      </chunk>
   </tasklet>
</step>
</code>```

step1 is configured with a limit for the number of times an individual item can be retried, and a list of exceptions that are 'retryable'.

you can take a look for more details on how retry works Retry.

Here is another example spring-batch-retrytemplate-example

Body:
I am working on introducing a customize retry policy in my Spring Batch job. Following is my sample step define in the workflow. But i am not getting where to define/configure the "retry-policy"?

Please help.

<job id="job1" job-repository="jobRepository">
      <step id="step1">
         <tasklet transaction-manager="jobRepository-transactionManager"  >

            </tasklet>
            <next on="COMPLETED" to="step2"/>
            <next on="FAILED" to="error"/>
        </step>
</job>

Body:
Here is an example on official site on how to configure Spring Batch RetryPolicy for chunks.

<step id="step1">
   <tasklet>
      <chunk reader="itemReader" writer="itemWriter"
             commit-interval="2" retry-limit="3">
         <retryable-exception-classes>
            <include class="org.springframework.dao.DeadlockLoserDataAccessException"/>
         </retryable-exception-classes>
      </chunk>
   </tasklet>
</step>

step1 is configured with a limit for the number of times an individual item can be retried, and a list of exceptions that are 'retryable'.

you can take a look for more details on how retry works Retry.

Here is another example spring-batch-retrytemplate-example


问:
Select from mysql table unique records according to a Field
I have a table in MySQL which I store registrations info.

I need to select all rows but only the latest according to email field and ID field

My table:

and I need

答:
Thanks for the replies.

Using

```<code>SELECT t1.*
FROM yourTable t1
INNER JOIN
(
    SELECT email, MAX(name) AS max_name
    FROM yourTable
    GROUP BY email
) t2
    ON t1.email = t2.email AND
       t1.name  = t2.max_name;
</code>```

Worked fine.

Thanks

Body:
Thanks for the replies.

Using

SELECT t1.*
FROM yourTable t1
INNER JOIN
(
    SELECT email, MAX(name) AS max_name
    FROM yourTable
    GROUP BY email
) t2
    ON t1.email = t2.email AND
       t1.name  = t2.max_name;

Worked fine.

Thanks


问:
Google API Error RefererNotAllowedMapError
Im trying to create an application using the Google maps api. While running on my localhost the following code, it displays me in the console the following message:

```<code>"Google Maps API error: RefererNotAllowedMapError https://developers.google.com/maps/documentation/javascript/error-messages#referer-not-allowed-map-error
Your site URL to be authorized: http://localhost:8888/fintechjobs.ie/fintechmap.php"

<!DOCTYPE html>
<html>

<body>

<div id="map" style="width:100%;height:500px"></div>

<script>
function myMap() {
  var myCenter = new google.maps.LatLng(51.508742,-0.120850);
  var mapCanvas = document.getElementById("map");
  var mapOptions = {center: myCenter, zoom: 5};
  var map = new google.maps.Map(mapCanvas, mapOptions);
  var marker = new google.maps.Marker({position:myCenter});
  marker.setMap(map);
}
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=xxxxxxxxxxxxxxxx&callback=myMap"></script>

</body>
</html>
</code>```

Can someone guide on where is this error coming from?
Thank you!

答:
You must allow urls in your Api google map interface : https://console.cloud.google.com/apis/dashboard

Click on the hamburger left then choose "Api and services".

Then click on "credentials" section on the left panel then click on your Google Map Api Key. You can then enter your url (localhost) under the keys api section.
Do not forget to enter the port.

Body:
Im trying to create an application using the Google maps api. While running on my localhost the following code, it displays me in the console the following message:

"Google Maps API error: RefererNotAllowedMapError https://developers.google.com/maps/documentation/javascript/error-messages#referer-not-allowed-map-error
Your site URL to be authorized: http://localhost:8888/fintechjobs.ie/fintechmap.php"

<!DOCTYPE html>

Can someone guide on where is this error coming from?
Thank you!


问:
How can the foreign field shows the name instead of its id?
In my models.py, there are two model, the AvailableArea has a foreign field refer to AddressRegion:

```<code>class AddressRegion(models.Model):
    name = models.CharField(max_length=8)

    def __str__(self):
        return self.name
    def __unicode__(self):
        return self.name

class AvailableArea(models.Model):
    name = models.CharField(max_length=8)
    addressregion = models.ForeignKey(AddressRegion, default=1, related_name='availableareas', on_delete=models.CASCADE)

    def __str__(self):
        return self.name
    def __unicode__(self):
        return self.name
</code>```

In the serializers.py, I serialize all the fields:

```<code>class AvailableAreaSerializer(ModelSerializer):
    """
    region
    """
    class Meta:
        model = AvailableArea
        fields = "__all__"
</code>```

In the views.py:

```<code>class AddressRegionListAPIView(ListAPIView):
    serializer_class = AddressRegionSerializer
    permission_classes = []
    queryset = AddressRegion.objects.all()
</code>```

The rest framework data is like this:

```<code>[
    {
        "id": 13,
        "name": "st-01",
        "addressregion": 3
    },
    {
        "id": 14,
        "name": "tg-02",
        "addressregion": 4
    },
    {
        "id": 15,
        "name": "sx-01",
        "addressregion": 3
    }
]
</code>```

I want the addressregion not shows the addressregion's id, but shows the addressregion's name.

答:
Your serializer should be like this:

```<code>class AvailableAreaSerializer(ModelSerializer):
"""
可用地区
"""
class Meta:
    model = AvailableArea
    fields = ('id', 'name', 'addressregion__name')
</code>```

and queryset in View should be:

```<code>queryset = AddressRegion.objects.all().select_related('addressregion')
</code>```

select_related will fetch the result by joining both the table. For more info read this

ContentLicense: CC BY-SA 4.0

Body:
In my models.py, there are two model, the AvailableArea has a foreign field refer to AddressRegion:

class AddressRegion(models.Model):
    name = models.CharField(max_length=8)

    def __str__(self):
        return self.name
    def __unicode__(self):
        return self.name

class AvailableArea(models.Model):
    name = models.CharField(max_length=8)
    addressregion = models.ForeignKey(AddressRegion, default=1, related_name='availableareas', on_delete=models.CASCADE)

    def __str__(self):
        return self.name
    def __unicode__(self):
        return self.name

In the serializers.py, I serialize all the fields:

class AvailableAreaSerializer(ModelSerializer):
    """
    region
    """
    class Meta:
        model = AvailableArea
        fields = "__all__"

In the views.py:

class AddressRegionListAPIView(ListAPIView):
    serializer_class = AddressRegionSerializer
    permission_classes = []
    queryset = AddressRegion.objects.all()

The rest framework data is like this:

[
    {
        "id": 13,
        "name": "st-01",
        "addressregion": 3
    },
    {
        "id": 14,
        "name": "tg-02",
        "addressregion": 4
    },
    {
        "id": 15,
        "name": "sx-01",
        "addressregion": 3
    }
]

I want the addressregion not shows the addressregion's id, but shows the addressregion's name.

Body:
Your serializer should be like this:

class AvailableAreaSerializer(ModelSerializer):
"""
可用地区
"""
class Meta:
    model = AvailableArea
    fields = ('id', 'name', 'addressregion__name')

and queryset in View should be:

queryset = AddressRegion.objects.all().select_related('addressregion')

select_related will fetch the result by joining both the table. For more info read this


问:
How do you set up 'image sets' to match launchImage files for all devices?
NOTE: This question is NOT related to launch image storyboards.

INFO: BG Buddy is a landscape only app. The launch screen uses images in a launchImage.xcassets file.

The launch image transitions to a UIViewController containing a full screen  UIImageView with the same BG Buddy Background image as used in the launch image, and some textual UIButtons. This gives the impression that the buttons appear on top of the background image after a short time when the app has loaded.

Here is how the BG Buddy Background image set has been set up since the app’s release. Transitions from Launch Image to UIViewController work perfectly on iPad, iPhones 5,6,7,8 and 6,7,8 Plus.

The iPhone X and the iPhone Plus both seem to use the iPhone 3x image slot but both have very different dimensions.  I’ve opened up the other size classes slots and tried to find a place with much confusion and no success. NOTE: All iPhones apart from the iPhone Plus use compact width/compact height size classes when in landscape. The iPhone Plus uses regular width/ compact height in landscape orientation.

So how do you set up 'image set' files to match launchImage files  for all devices?

At the moment I can either have a good iPhone X transition or a good iPhone Plus transition but not both.

Is my only option to try to detect if it’s an iPhone X (or iPhone Plus) and swap the images programatically?

答:
So here's the solution for a landscape only app. Hopefully it will help a little for portrait orientations too. Landscape bespoke launch images should be placed as shown with these width/height class settings.

Use the launchImage.xcassets screenshot at the top of the question to set up your launchImage.xcassets.


问:
When might Application_EndRequest not be called?
We have an ASMX web service hosted in IIS 6, and are seeing some strange behaviour with one of our WebMethods. After an iisreset, the first call to a particular method fails to return to the client, which times out after 60 seconds.

I've introduced logging into Application_BeginRequest and Application_EndRequest in the Global.asax.cs file. The logging shows that for that one call, EndRequest is not called. A try-finally block in the method itself shows that it is running to completion.

There are other requests to different methods before, during and after this one that show no problems. TcpTrace shows that no reply is ever returned for that first request to the method.

The logs also show that the thread that serviced the request starts serving other requests after the finally block has completed.

I'm wondering what might cause such behaviour, and how I might debug this further.

答:
Assuming this is entirely repeatable, I would start by changing the method.  Namely I would remove stuff until it works as expected.

It sounds like there is some odd secondary behavior caused by the web method itself.  I'm guessing it's a bit more complex than just adding two numbers together and returning a result.

Also I'd pay close attention to what the method is doing.  For example, is it instantiating unmanaged resources?  Do you have any http handlers or modules involved which might be cratering on the first execution for this method?

By eliminating code until it works you'll figure out exactly what's causing this.


问:
Have Maven fail with a message if a certain profile is used
Let's say I have a profile "dostuff" defined in a pom.xml that uses a plugin to do some stuff when the user runs mvn -P dostuff:

```<code><profiles>
    <profile>
        <id>dostuff</id>
        <build>
            <plugins>
                <plugin>
                    ...
                </plugin>
            <plugins>
        </build>
    </profile>
<profiles>
</code>```

The task the profile performs have been replaced by a new non-maven command entirely.

Of course I can just remove the profile, but that has two problems:

It doesn't fail the build, it just produces a warning:

[WARNING] The requested profile "dostuff" could not be activated because
  it does not exist.

It doesn't give the user any information that they should use the new command instead.

So, I would like any use of the profile "dostuff" to produce an error with a message telling them to use the new non-maven command instead.

Is that even possible? It's a plus if the solution doesn't require a plugin.

答: Just put the profile in your pom and use it to show a message and throw an exception. You could e.g. use the Antrun plugin to echo a message.</p>

Body:
Let's say I have a profile "dostuff" defined in a pom.xml that uses a plugin to do some stuff when the user runs mvn -P dostuff:

<profiles>
    <profile>
        <id>dostuff</id>
        <build>
            <plugins>
                <plugin>
                    ...
                </plugin>
            <plugins>
        </build>
    </profile>
<profiles>

The task the profile performs have been replaced by a new non-maven command entirely.

Of course I can just remove the profile, but that has two problems:

It doesn't fail the build, it just produces a warning:

[WARNING] The requested profile "dostuff" could not be activated because
  it does not exist.

It doesn't give the user any information that they should use the new command instead.

So, I would like any use of the profile "dostuff" to produce an error with a message telling them to use the new non-maven command instead.

Is that even possible? It's a plus if the solution doesn't require a plugin.


问:
Creating a new variable in elements of List using R
I am new to R language. I have a list of 64 elements(1 Element contains 72 observations) and trying to create a new variable with its range using lapply function. Any leads would be highly appreciated

eg:

```<code>$x
Var1 Var2
abc   345
def   678
ghi   891

$x2
Var1 Var2
abc   345
def   678
ghi   891
.
.
.
.
64 elements

required o/p:
$x2
Var1 Var2 var3
abc   345  1
def   678  2
ghi   891  3
.
.
64elements
</code>```

答:
We can use lapply to apply a function though out the data frames in the list.

```<code># Create an example list
dt <- data.frame(Var1 = c("abc", "def", "ghi"),
                 Var2 = c(345, 678, 891),
                 stringsAsFactors = FALSE)

dt_list <- list(dt, dt)
names(dt_list) <- c("x", "x2")

# Add one new column using lapply
dt_list2 <- lapply(dt_list, function(x){
  x[, "Var3"] <- 1:nrow(x)
  return(x)
})
dt_list2
# $x
#   Var1 Var2 Var3
# 1  abc  345    1
# 2  def  678    2
# 3  ghi  891    3
#
# $x2
#   Var1 Var2 Var3
# 1  abc  345    1
# 2  def  678    2
# 3  ghi  891    3
</code>```

Body:
I am new to R language. I have a list of 64 elements(1 Element contains 72 observations) and trying to create a new variable with its range using lapply function. Any leads would be highly appreciated

eg:

$x
Var1 Var2
abc   345
def   678
ghi   891

$x2
Var1 Var2
abc   345
def   678
ghi   891
.
.
.
.
64 elements

required o/p:
$x2
Var1 Var2 var3
abc   345  1
def   678  2
ghi   891  3
.
.
64elements

Body:
We can use lapply to apply a function though out the data frames in the list.

# Create an example list
dt <- data.frame(Var1 = c("abc", "def", "ghi"),
                 Var2 = c(345, 678, 891),
                 stringsAsFactors = FALSE)

dt_list <- list(dt, dt)
names(dt_list) <- c("x", "x2")

# Add one new column using lapply
dt_list2 <- lapply(dt_list, function(x){
  x[, "Var3"] <- 1:nrow(x)
  return(x)
})
dt_list2
# $x
#   Var1 Var2 Var3
# 1  abc  345    1
# 2  def  678    2
# 3  ghi  891    3
#
# $x2
#   Var1 Var2 Var3
# 1  abc  345    1
# 2  def  678    2
# 3  ghi  891    3


问:
absolute css not working as expected
I'm trying to apply absolute positioning on class car. I expect it to be placed in top-left corner inside rectangle. The current behavior is being placed in top-left corner of the page which I don't want. As far as I know absolute element must be positioned inside its ancestor.

body {
  padding: 25px;
}

.car {
  position: absolute;
}

#rectangle {
  /* display: inline-block;
            position: absolute;
            top: 150px;
            left:25px; */
  width: 3324px;
  height: 5112px;
  background-color: #00b3ee;
}

#intro {
  /* position: absolute;
            top: 800px;
            left:25px; */
  border: solid 1px;
  padding: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

  <div id="intro">
    <p>
      Floor <b><i>{{ $title }}</i></b> setup successfully finished!
      Return to floors.
    </p>
  </div>

  <div id="rectangle">
    <img src="{{ url($map_image_path) }}">

      <img id="dynamic" src="http://localhost/ParkingMinis/public/images/icons/car/reza1.png">

  </div>

</body></code>```

答:
Here you go buddy.

 body
        {
            padding: 25px;
        }

        .car
        {
            position: absolute;
            top: 0 ;
            left:0;
            padding: 25px;
        }

        #rectangle
        {
          position:relative;
            width: 3324px;
            height: 5112px;
            background-color: #00b3ee;
        }

        #rectangle img{
          height: 50px;
        }

        #intro
        {
            /* position: absolute;
            top: 800px;
            left:25px; */
            border: solid 1px;
            padding: 10px;
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="intro">
     <p>
        Floor <b><i>{{ $title }}</i></b> setup successfully finished!
        Return to floors.
    </p>
</div>

<div id="rectangle">
    <img src="{{ url($map_image_path) }}" >

        <img id="dynamic" src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png?v=9c558ec15d8a">

</div></code>```

Title: absolute css not working as expected

Body:
I'm trying to apply absolute positioning on class car. I expect it to be placed in top-left corner inside rectangle. The current behavior is being placed in top-left corner of the page which I don't want. As far as I know absolute element must be positioned inside its ancestor.

body {
  padding: 25px;
}

.car {
  position: absolute;
}

#rectangle {
  /* display: inline-block;
            position: absolute;
            top: 150px;
            left:25px; */
  width: 3324px;
  height: 5112px;
  background-color: #00b3ee;
}

#intro {
  /* position: absolute;
            top: 800px;
            left:25px; */
  border: solid 1px;
  padding: 10px;
}

      Floor {{ $title }} setup successfully finished!
      Return to floors.

Body:
Here you go buddy.

 body
        {
            padding: 25px;
        }

        .car
        {
            position: absolute;
            top: 0 ;
            left:0;
            padding: 25px;
        }

        #rectangle
        {
          position:relative;
            width: 3324px;
            height: 5112px;
            background-color: #00b3ee;
        }

        #rectangle img{
          height: 50px;
        }

        #intro
        {
            /* position: absolute;
            top: 800px;
            left:25px; */
            border: solid 1px;
            padding: 10px;
        }

<div id="intro">
     <p>
        Floor <b><i>{{ $title }}</i></b> setup successfully finished!
        <a href="{{ url('/admin/floors') }}" class="alert-link">Return to floors.</a>
    </p>
</div>

<div id="rectangle">
    <img src="{{ url($map_image_path) }}" >
    <a href="#" class="car" style="position: absolute; top: 0px; left: 0px;">
        <img id="dynamic" src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png?v=9c558ec15d8a">
    </a>
</div>


问:
Multiple display file handling
I have a subfile program that displays records in the below format:

Subfile initial display

There are two options that can be taken on the records ( 5 or 7). Option 5 checks for record existence in a table and if no records are found, the below screen is displayed with a window display file indicating that records were not found:

Display with information window

the issue here is that when a combination of options are taken on the records, for example, if option 5 is taken on one record followed by option 7 on the next and then option 5 again on the next record, the display seems to get distorted.

Option 7 calls a program which displays another display file and when the control comes back to the initial display it appears like this:

Distorted display

How can I display this correctly (with the window appearing with a proper background?) I know that correct usage of keywords like KEEP or ASSUME will do this but not sure how to use this in which display file or on what record formats.

答:
When you are creating the display file, it should be created with keyword RSTDSP(*YES). When a second display file is opened, the display file on the screen is suspended. By default, the first display file is not re-displayed when the second display file is closed. That is when you get wacky screens like the one you showed.

From the knowledge center

Restore display (RSTDSP)

Specifies whether data being shown at a display device by this display file is saved at the time the file is suspended (made temporarily inactive) so that another display file can show different data on the same device. If the data for this file is saved, it is restored to the display of the device when the file is used again.

*NO
  The data being shown by this file is not saved when the file is suspended.

*YES
  The data being shown when this file is suspended is saved, and it is restored to the device display when the file is used again.

Title: Multiple display file handling


问:
How to set cursor position to the top-left edge of input
Let I've an input field like the following:

How can I set cursor postition to the top-left edge of this input field?

答:
Simple solution for me was within the HTML code for my ASP:TextBox was at the end of my tagline put "...TextMode="MultiLine" /> as below:</p>

```<code> <asp:TextBox ID="txtPermissionSearch" runat="server" Width="150px" Height ="150px" TextMode="MultiLine" />
</code>```

Body:
Simple solution for me was within the HTML code for my ASP:TextBox was at the end of my tagline put "...TextMode="MultiLine" /> as below:

 <asp:TextBox ID="txtPermissionSearch" runat="server" Width="150px" Height ="150px" TextMode="MultiLine" />


问:
Typing Casting in Python Question
Im a AS3 developer, currently learning Python

In AS3 Id quite often do this:

```<code>for ( var foo in fooArray ) {
   trace(FooObject(foo).name);
}
</code>```

Typing casting the objects in the array, so that I get code hinting in my IDE

How would I do this in Python?

答:
Types are determined at runtime in Python.  Thus, there is typically less "code hinting" (I assume you mean completion, navigation, and so forth) in IDEs.  There is still some.

Related: a commonly used IDE for Python development with some hinting is Eclipse (or Aptana) with pydev.  Some installation instructions.

Title: Typing Casting in Python Question

Body:
Im a AS3 developer, currently learning Python

In AS3 Id quite often do this:

for ( var foo in fooArray ) {
   trace(FooObject(foo).name);
}

Typing casting the objects in the array, so that I get code hinting in my IDE

How would I do this in Python?


问:
Angular2 show two decimals in input
I have an angular2 app that needs to show ALWAYS two decimals in inputs after some calculations. But although in the component I force to have two decimals, in the input it shows it with zero decinmal, one decimal or the decimals that the number has but what I need is to show always two.

In the controller I force to have two decimals in this way

```<code>return +(this.getCost() * this.getQuantity()).toFixed(2);
</code>```

But when I show that, the result can have different decimals size

```<code><input name="number" pattern="^[0-9]+(\.[0-9]{1,2})?" step="0.01" formControlName="number" type="button" class="form-control" id="number" >
</code>```

Adding that I;m using TypeScript and the field type is number (which I think is causing the rounded)

答:
In angular 2 have DecimalPipe this will helpful to your requirement.Please Use it.
Sample:</p>

```<code>Use format '3.2-5' :

minIntegerDigits = 3
minFractionDigits = 2
maxFractionDigits = 5

num = 12.324324

{{num1 | number:'3.2-5'}}

012.63847
</code>```

Title: Angular2 show two decimals in input

Body:
I have an angular2 app that needs to show ALWAYS two decimals in inputs after some calculations. But although in the component I force to have two decimals, in the input it shows it with zero decinmal, one decimal or the decimals that the number has but what I need is to show always two.

In the controller I force to have two decimals in this way

return +(this.getCost() * this.getQuantity()).toFixed(2);

But when I show that, the result can have different decimals size

<input name="number" pattern="^[0-9]+(\.[0-9]{1,2})?" step="0.01" formControlName="number" type="button" class="form-control" id="number" >

Adding that I;m using TypeScript and the field type is number (which I think is causing the rounded)

Body:
In angular 2 have DecimalPipe this will helpful to your requirement.Please Use it.
Sample:

Use format '3.2-5' :

minIntegerDigits = 3
minFractionDigits = 2
maxFractionDigits = 5

num = 12.324324

{{num1 | number:'3.2-5'}}

012.63847


答:
You can use java.util.scanner to parse various data types from a stream relatively painlessly.

For example, suppose you wanted to parse the following:

```<code>1 2 3.0
4.0 5 6
</code>```

You could use the following snippet:

```<code>Scanner scan = new Scanner(System.in);
int one = scan.nextInt();
int two = scan.nextInt();
double three = scan.nextDouble();
// Defaultly, it will continue past the line break
double four = scan.nextDouble();

// We can also do this
double five = scan.nextDouble();
long six = scan.nextLong();
</code>```

An important note is that java.util.Scanner will suppress IOExceptions (although, exceptions from converting text, e.g. NumberFormatExceptions, will still be raised). You can check ioException to see if one has been suppressed.

Title: How to read this from file and get each value alone

Body:
I have this text file and I need to extract it to a Java program to determine array sizes and its values I can read each line alone but I can't get the value for lines that contains many numbers. Plus, how to count element in the third line.( 0 2 )

4
5
0 2

0 1 0.6
0 2 0.2
0 3 0.5
1 3 0.8
2 3 0.3

this code that I'm using:

 List<Integer> list = new ArrayList<Integer>();
        File file = new File("D:\\ALGORTHIMS\\MASTER LEVEL\\dr. khaled\\assignment 1\\text.txt");
        BufferedReader reader = null;
         List<Double> ints = new ArrayList<Double>();

        try {
            reader = new BufferedReader(new FileReader(file));
            String text = null;

            while ((text = reader.readLine()) != null) {
                if (text.length() == 1) {
                    list.add(Integer.parseInt(text));
                } else {

                    String[] strs = text.trim().split("\\s+");

                    for (int i = 0; i < strs.length; i++) {
                        ints.add(Double.parseDouble(strs[i]));
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {

            }
        }

//print out the list
        System.out.println(list);

        System.out.println(ints);

Body:
You can use java.util.scanner to parse various data types from a stream relatively painlessly.

For example, suppose you wanted to parse the following:

1 2 3.0
4.0 5 6

You could use the following snippet:

Scanner scan = new Scanner(System.in);
int one = scan.nextInt();
int two = scan.nextInt();
double three = scan.nextDouble();
// Defaultly, it will continue past the line break
double four = scan.nextDouble();

// We can also do this
double five = scan.nextDouble();
long six = scan.nextLong();

An important note is that java.util.Scanner will suppress IOExceptions (although, exceptions from converting text, e.g. NumberFormatExceptions, will still be raised). You can check ioException to see if one has been suppressed.


问:
delphi Check whether function result value is used
My question is the same as this one here except for the language. I am using Delphi.

Following the link you'll see in Java this seems to be impossible, so I would assume this applies to Delphi as well, but I am not entirely sure

I want to know, whether a function can check, if the calling procedure/function is making use of the return value the function provides.

I've tried this, but it didn't work: (I guess if a solution exists it would behave similar to this)

```<code>  if Assigned(Result) then begin
    showmessage('return value is assigned');
  end else begin
    showmessage('return value is NOT assigned');
  end;
</code>```

It may seem to be useless to check, but my function produces an encrypted file, for which the return value is beeing needed to decrypt this file, so it would be nice to notify the user instead of just producing an useless file and therefore I would like to check the usage of the return value.

Possible workaround:

I've got an Idea, but either don't know whether this is possible nor how to do that: The function could scan the part of RAM, which is occupied by my application and check for the return value (String) to exist after the command Result := 'something like F8975BE8AC0192#2983FE4A#B9DFE25' has been fired. It is soooo unlikeley that the String exists twice, that this simple check would completely fit my purpose.
In general this may not work, because the Result could exist twice, but in my case this is somehow impossible.

So to do this workaround I expand my original question:
How can I search for a String in the part of RAM occupied by the application containing the function, which wants to check this?
As far as I know it would be much harder to check this for an external application, which is not needed here.

答:
What you're trying to do is not possible in Delphi. And it's not a "language issue". But it's also not a problem.

You're really thinking about this back-to-front. I'll try to explain the why; and hopefully you'll abandon this folly.

Summary

Functions should do one thing only. The more things a function tries to do: the more difficult it is to implement correctly, and the more difficult it is for others to reuse.

Any hack you may conceive can easily be bypassed. So you end up with more complexity and the same non- problem.

It's not your responsibility to ensure that callers use your function correctly. That way lies madness and an ever-growing rabbit-warren.

You should only implement your function according to a "contract" and it's the caller's responsibility to use it correctly. If caller doesn't use it correctly, caller has a bug until the calling code is fixed. Simple as that.

Do only one thing

When functions do more than one thing, it becomes impossible (without careful refactoring) to use one feature and not the other. The function is more difficult to test because: more things change during the call, more setup is required, more things should be checked, there are likely more permutations that need to be considered.

The scenario in the Javascript question is even worse because the 2 things have a fundamental difference:

The function-style version can guarantee not to change state.

Whereas the other style is intended to modify state.

This is a concept of mutability vs immutability. And it's extremely beneficial to know when immutability is guaranteed. Bundling both into a single function means you no longer have immutable version.

Hacking a "solution" is pointless

Let's suppose you find some hack to interrogate the call-stack outside the function itself in order to confirm the caller stores the function result to a variable for later use.

Let's also put aside concerns of different OS, CPU architecture, compiler optimisations etc.

Nothing prevents the caller doing the following:

```<code>S := HybridFunction(...);
if (S <> '') then S := '';
</code>```

Yes caller stored the variable, but quite obviously didn't use it. But caller doesn't even have to be so blatant about it. Storing the variable in a class field but never referencing it again has the same effect.

Do not double-check your callers - it is NOT your responsibility

You have enough to worry about ensuring your code behaves correctly without having to worry about what your callers do. If you try to compensate for callers then:

If caller is correct, your special code is pointless.

If caller is wrong, you can't "fix" anything. You cannot know what every possible caller should do.

The effort is better spent working on the caller code and ensuring it is correct!

Also, if you worry about your callers; what about your caller's callers? Or your caller's caller's callers? ... It never ends.

Implement to a contract and be done

You can force your caller to receive a result by using an out parameter. But that still doesn't prevent the caller from not using the out value after the call. So you'd sacrifice clean function-style calling convention for zero benefit.

I assume you have a function along the following lines:

```<code>function EncryptFile(): TKey; { returns the decryption key }
</code>```

There's already a problem here because your function is obviously doing 2 things. Split it into 2 functions and your caller will also be easier to write.

```<code>function GetKey(): TKey;
procedure EncryptFile(AKey: TKey);
</code>```

Then your caller can validate before trying to Encrypt:

```<code>LKey := GetKey();
if Assigned(LKey) then
  EncryptFile(LKey)
else { report the error as you choose }
</code>```

And this is why I say you're going about this back-to-front.

Body:
My question is the same as this one here except for the language. I am using Delphi.

Following the link you'll see in Java this seems to be impossible, so I would assume this applies to Delphi as well, but I am not entirely sure

I want to know, whether a function can check, if the calling procedure/function is making use of the return value the function provides.

I've tried this, but it didn't work: (I guess if a solution exists it would behave similar to this)

  if Assigned(Result) then begin
    showmessage('return value is assigned');
  end else begin
    showmessage('return value is NOT assigned');
  end;

It may seem to be useless to check, but my function produces an encrypted file, for which the return value is beeing needed to decrypt this file, so it would be nice to notify the user instead of just producing an useless file and therefore I would like to check the usage of the return value.

Possible workaround:

I've got an Idea, but either don't know whether this is possible nor how to do that: The function could scan the part of RAM, which is occupied by my application and check for the return value (String) to exist after the command Result := 'something like F8975BE8AC0192#2983FE4A#B9DFE25' has been fired. It is soooo unlikeley that the String exists twice, that this simple check would completely fit my purpose.
In general this may not work, because the Result could exist twice, but in my case this is somehow impossible.

So to do this workaround I expand my original question:
How can I search for a String in the part of RAM occupied by the application containing the function, which wants to check this?
As far as I know it would be much harder to check this for an external application, which is not needed here.

Body:
What you're trying to do is not possible in Delphi. And it's not a "language issue". But it's also not a problem.

You're really thinking about this back-to-front. I'll try to explain the why; and hopefully you'll abandon this folly.

Summary

Functions should do one thing only. The more things a function tries to do: the more difficult it is to implement correctly, and the more difficult it is for others to reuse.

Any hack you may conceive can easily be bypassed. So you end up with more complexity and the same non- problem.

It's not your responsibility to ensure that callers use your function correctly. That way lies madness and an ever-growing rabbit-warren.

You should only implement your function according to a "contract" and it's the caller's responsibility to use it correctly. If caller doesn't use it correctly, caller has a bug until the calling code is fixed. Simple as that.

Do only one thing

When functions do more than one thing, it becomes impossible (without careful refactoring) to use one feature and not the other. The function is more difficult to test because: more things change during the call, more setup is required, more things should be checked, there are likely more permutations that need to be considered.

The scenario in the Javascript question is even worse because the 2 things have a fundamental difference:

The function-style version can guarantee not to change state.

Whereas the other style is intended to modify state.

This is a concept of mutability vs immutability. And it's extremely beneficial to know when immutability is guaranteed. Bundling both into a single function means you no longer have immutable version.

Hacking a "solution" is pointless

Let's suppose you find some hack to interrogate the call-stack outside the function itself in order to confirm the caller stores the function result to a variable for later use.

Let's also put aside concerns of different OS, CPU architecture, compiler optimisations etc.

Nothing prevents the caller doing the following:

S := HybridFunction(...);
if (S <> '') then S := '';

Yes caller stored the variable, but quite obviously didn't use it. But caller doesn't even have to be so blatant about it. Storing the variable in a class field but never referencing it again has the same effect.

Do not double-check your callers - it is NOT your responsibility

You have enough to worry about ensuring your code behaves correctly without having to worry about what your callers do. If you try to compensate for callers then:

If caller is correct, your special code is pointless.

If caller is wrong, you can't "fix" anything. You cannot know what every possible caller should do.

The effort is better spent working on the caller code and ensuring it is correct!

Also, if you worry about your callers; what about your caller's callers? Or your caller's caller's callers? ... It never ends.

Implement to a contract and be done

You can force your caller to receive a result by using an out parameter. But that still doesn't prevent the caller from not using the out value after the call. So you'd sacrifice clean function-style calling convention for zero benefit.

I assume you have a function along the following lines:

function EncryptFile(): TKey; { returns the decryption key }

There's already a problem here because your function is obviously doing 2 things. Split it into 2 functions and your caller will also be easier to write.

function GetKey(): TKey;
procedure EncryptFile(AKey: TKey);

Then your caller can validate before trying to Encrypt:

LKey := GetKey();
if Assigned(LKey) then
  EncryptFile(LKey)
else { report the error as you choose }

And this is why I say you're going about this back-to-front.


问:
Creating objects during runtime in Python
I have a problem grasping the OOP concept when it comes to creating objects during runtime. All the educational code that I have looked into yet defines specific variables e.g. 'Bob' and assigns them to a new object instance. Bob = Person()

What I have trouble understanding now is how I would design a model that creates a new object during runtime? I'm aware that my phrasing is probably faulty since all objects are generated during runtime but what I mean is that if I were to start my application in a terminal or UI how would I create new objects and manage them. I can't really define new variable names on the fly right?

An example application where I run into this design issue would be a database storing people. The user gets a terminal menu which allows him to create a new user and assign a name, salary, position. How would you instantiate that object and later call it if you want to manage it, call functions, etc.? What's the design pattern here?

Please excuse my poor understanding of the OPP model. I'm currently reading up on classes and OOP but I feel like I need to understand what my error is here before moving on. Please let me know if there is anything I should clarify.

答:
Things like lists or dictionaries are great for storing dynamically generated sets of values/objects:</p>

```<code>class Person(object):
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        print "A person named %s" % self.name

people = {}
while True:
    print "Enter a name:",
    a_name = raw_input()

    if a_name == 'done':
        break

    people[a_name] = Person(a_name)

    print "I made a new Person object. The person's name is %s." % a_name

print repr(people)
</code>```

Body:
Things like lists or dictionaries are great for storing dynamically generated sets of values/objects:

class Person(object):
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        print "A person named %s" % self.name

people = {}
while True:
    print "Enter a name:",
    a_name = raw_input()

    if a_name == 'done':
        break

    people[a_name] = Person(a_name)

    print "I made a new Person object. The person's name is %s." % a_name

print repr(people)


问:
Trying to create an empty grid
```<code>class WorldMap (object):
def __init__ (self, width, height):
    self.width = width
    self.height = height
    world = []
    for i in range(self.width):
        world.append(None)
        for j in range(self.height):
                                world[i].append(None)

class WorldMap(object):
def __init__(self, width, height):
    self.width = width
    self.height = height
    self.map = [[None for x in range(self.width)] for y in range(self.height)]
</code>```

The second successfully creates a grid. I don't understand why the first code doesn't work.

to create an empty grid with lists, I tried using None and '' in the first code, but neither work. Why are both '' and None as used in the first code not correct ?

答:
Let's assume the grid size will be:

size = 4

Now, we're making an empty grid:

grid = []

for y in range(size):
   grid = grid + [[]]
   for x in range(size):
      grid[y] = grid[y] + [0]

When you now call your grid you should get:
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

Title: Trying to create an empty grid

Body:
class WorldMap (object):
def __init__ (self, width, height):
    self.width = width
    self.height = height
    world = []
    for i in range(self.width):
        world.append(None)
        for j in range(self.height):
                                world[i].append(None)

class WorldMap(object):
def __init__(self, width, height):
    self.width = width
    self.height = height
    self.map = [[None for x in range(self.width)] for y in range(self.height)]

The second successfully creates a grid. I don't understand why the first code doesn't work.

to create an empty grid with lists, I tried using None and '' in the first code, but neither work. Why are both '' and None as used in the first code not correct ?


问:
Spark DataFrame from pandas Series
I have a Pandas Series object

```<code>dates = pd.Series(pd.date_range(start_date,end_date))/
.dt.strftime('%y%m%d')/
.astype(int)/
</code>```

And i would like to create a Spark DF directly from the Series object, without intermediate Pandas dataframe

```<code>    _schema = StructType([
     StructField("date_id", IntegerType(), True),
])

    dates_rdd = sc.parallelize(dates)
    self.date_table = spark.createDataFrame(dates_rdd, _schema)
</code>```

Error:

```<code>Error: raise TypeError("StructType can not accept object %r in type %s" %
(obj, type(obj)))
TypeError: StructType can not accept object 160101 in type <class
'numpy.int64'>
</code>```

If i change the Series object as:

```<code>    dates = pd.Series(pd.date_range(start_date,end_date))/
    .dt.strftime('%y%m%d')/
    .astype(int).values.tolist()
</code>```

Error becomes:

```<code> raise TypeError("StructType can not accept object %r in type %s" % (obj,
 type(obj)))
 TypeError: StructType can not accept object 160101 in type <class 'int'>
</code>```

How can i properly map the Int values contained in the dates list/rdd to Python native integer that is accepted from Spark Dataframes?

答:
Believe,you have missed to create a tuple for each series value,</p>

```<code>>>> dates = pd.Series(pd.date_range(start='1/1/1980', end='1/11/1980')).dt.strftime('%y%m%d').astype(int).values.tolist()
>>> rdd = sc.parallelize(dates).map(lambda x:(x,))
>>> _schema = StructType([StructField("date_id", IntegerType(), True),])
>>> df = spark.createDataFrame(rdd,schema=_schema)
>>> df.show()
+-------+
|date_id|
+-------+
| 800101|
| 800102|
| 800103|
| 800104|
| 800105|
| 800106|
| 800107|
| 800108|
| 800109|
| 800110|
| 800111|
+-------+

>>> df.printSchema()
root
 |-- date_id: integer (nullable = true)
</code>```

Title: Spark DataFrame from pandas Series

Body:
I have a Pandas Series object

dates = pd.Series(pd.date_range(start_date,end_date))/
.dt.strftime('%y%m%d')/
.astype(int)/

And i would like to create a Spark DF directly from the Series object, without intermediate Pandas dataframe

    _schema = StructType([
     StructField("date_id", IntegerType(), True),
])

    dates_rdd = sc.parallelize(dates)
    self.date_table = spark.createDataFrame(dates_rdd, _schema)

Error:

Error: raise TypeError("StructType can not accept object %r in type %s" %
(obj, type(obj)))
TypeError: StructType can not accept object 160101 in type <class
'numpy.int64'>

If i change the Series object as:

    dates = pd.Series(pd.date_range(start_date,end_date))/
    .dt.strftime('%y%m%d')/
    .astype(int).values.tolist()

Error becomes:

 raise TypeError("StructType can not accept object %r in type %s" % (obj,
 type(obj)))
 TypeError: StructType can not accept object 160101 in type <class 'int'>

How can i properly map the Int values contained in the dates list/rdd to Python native integer that is accepted from Spark Dataframes?

Body:
Believe,you have missed to create a tuple for each series value,

>>> dates = pd.Series(pd.date_range(start='1/1/1980', end='1/11/1980')).dt.strftime('%y%m%d').astype(int).values.tolist()
>>> rdd = sc.parallelize(dates).map(lambda x:(x,))
>>> _schema = StructType([StructField("date_id", IntegerType(), True),])
>>> df = spark.createDataFrame(rdd,schema=_schema)
>>> df.show()
+-------+
|date_id|
+-------+
| 800101|
| 800102|
| 800103|
| 800104|
| 800105|
| 800106|
| 800107|
| 800108|
| 800109|
| 800110|
| 800111|
+-------+

>>> df.printSchema()
root
 |-- date_id: integer (nullable = true)


问:
Python: List merging method
I have a question:

I have 2 lists:

```<code>list_1 = [1, 2, 3]
list_2 = [4, 5, 6]
</code>```

And I want to merge them in order to have the following result:

```<code>mergedlist = [1, 4, 2, 5, 3, 6]
</code>```

How can I do that?

答:
Like this:

```<code>mergedlist = list_1 + list_2
</code>```

If you want that specific order in mergedlist:

```<code>mergedlist = []
for i, entry in enumerate(list_1):
    mergedlist.extend([entry, list_2[i]])
</code>```

Title: Python: List merging method

Body:
I have a question:

I have 2 lists:

list_1 = [1, 2, 3]
list_2 = [4, 5, 6]

And I want to merge them in order to have the following result:

mergedlist = [1, 4, 2, 5, 3, 6]

How can I do that?

Body:
Like this:

mergedlist = list_1 + list_2

If you want that specific order in mergedlist:

mergedlist = []
for i, entry in enumerate(list_1):
    mergedlist.extend([entry, list_2[i]])


问:
Sentry for Python: Add "git blame" like prefix to each source code line
It would be really great if exceptions in sentry would contain info like git blame does.

If every line of source code which I see in an exception in sentry would have a prefix like git blame (date, commit hash, author) you could find the relevant commit faster.

AFAIK sentry can't do this out of the box. Where and how could I hook into sentry to get this?

Please leave a comment why you down-vote this question. I am curious and willing to learn.

Just for the records. The sentry team is working on something like this. Not exactly, but it does solve the same use case: https://github.com/getsentry/sentry/issues/6547

答:
A traceback consists of multiple lines of code. You can extract info from git blame for each of these lines using the GitPython library:

```<code>import sys
import traceback

from git import Repo

def commit_info(file_path, line_number):
    for commit, lines in Repo().blame('HEAD', file_path):
        line_number -= len(lines)
        if line_number <= 0:
            return commit.hexsha, commit.committed_datetime, commit.author.name

try:
    raise Exception('error')
except Exception:
    for filename, line_number, _, _ in traceback.extract_tb(sys.exc_info()[2]):
        print filename, line_number, commit_info(filename, line_number)
</code>```

Then, it's up to you how you want to send this information to Sentry. One of the possible solutions is choosing one commit of the list above and using the extra keyword and let your logger do the job for you:

```<code>try:
    raise Exception
except Exception:
    commit = choose_one_commit()
    logger.exception('Error', extra={'author': author.name, 'sha': commit.hexsha})
</code>```

Also, you can use your own logger which would add this extra parameter to all .exception(), .error() and .critical() calls.

Overall, it's quite vague what behaviour do you want to achieve, and everything is possible. But calling git blame is expensive and may hurt the performance of your application a lot.

Body:
A traceback consists of multiple lines of code. You can extract info from git blame for each of these lines using the GitPython library:

import sys
import traceback

from git import Repo

def commit_info(file_path, line_number):
    for commit, lines in Repo().blame('HEAD', file_path):
        line_number -= len(lines)
        if line_number <= 0:
            return commit.hexsha, commit.committed_datetime, commit.author.name

try:
    raise Exception('error')
except Exception:
    for filename, line_number, _, _ in traceback.extract_tb(sys.exc_info()[2]):
        print filename, line_number, commit_info(filename, line_number)

Then, it's up to you how you want to send this information to Sentry. One of the possible solutions is choosing one commit of the list above and using the extra keyword and let your logger do the job for you:

try:
    raise Exception
except Exception:
    commit = choose_one_commit()
    logger.exception('Error', extra={'author': author.name, 'sha': commit.hexsha})

Also, you can use your own logger which would add this extra parameter to all .exception(), .error() and .critical() calls.

Overall, it's quite vague what behaviour do you want to achieve, and everything is possible. But calling git blame is expensive and may hurt the performance of your application a lot.


问:
Is the purpose of an interface to hide information?
Given that interfaces are also used to help hide information, giving the user only a subset of the possible methods they are allowed to use, and, let's say, I have a Person class and interface IPerson.

Now in main, I'm allowed to do

```<code>IPerson testy = new Person();
</code>```

or

```<code>Person testy = new Person();
</code>```

So really I'm not restricted from using Person still. So how does the interface truly hide data?

答:
The fundamental can't-do-any-other-way purpose of interfaces in .net is to provide a limited form of multiple inheritance.  Having a class inherit from another class serves two orthogonal purposes:

It means that fields, methods, and properties of the base class which will adequately serve the needs of the derived class can be used by the derived class without having to be respecified.

It means that code which expects methods of the base class can automatically work with methods of the derived class.

It is not possible for a class in .net to implicitly make use of the members of more than base class, but it is possible for a class to implement many interfaces, and be substitutable for any of them.  For example, a Dictionary and a linked list don't have much in common, but they can both be enumerated.  A serial port and a ListBox don't have much in common, but they can both be Disposed.

Almost everything interfaces can do, can be done just as well or better with abstract base classes.  The one thing interfaces can do which base classes cannot is allow for a limited form of multiple inheritance.

Body:
Given that interfaces are also used to help hide information, giving the user only a subset of the possible methods they are allowed to use, and, let's say, I have a Person class and interface IPerson.

Now in main, I'm allowed to do

IPerson testy = new Person();

or

Person testy = new Person();

So really I'm not restricted from using Person still. So how does the interface truly hide data?


问:
Spring boot: configure it to find the webapp folder
By default, Spring Boot looks in my src/main/webapp folder to find my html files. Where can I change the settings for Spring Boot if I use another folder to put the html files?

Later, the files will be wrapped in jars for deployment. Are there other things I need to worry about?

答:
AS mentioned above, jar packaging ignores webapp content. If you still want to include the contents inside webapp folder, you need to specify this  explicitly in maven POM.xml configuration as below -

```<code><build>
        <resources>
            <resource>
                <directory>src/main/webapp</directory>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources> ...
</code>```

Body:
AS mentioned above, jar packaging ignores webapp content. If you still want to include the contents inside webapp folder, you need to specify this  explicitly in maven POM.xml configuration as below -

<build>
        <resources>
            <resource>
                <directory>src/main/webapp</directory>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources> ...


问:
Rerurn null if subquery hasn't value sql
If this query hasn't B values, but has A values, can I have null where there are no values?

```<code>SELECT A, B
FROM
(SELECT title as A
 FROM TABLE1
 INNER JOIN TABLE2 ON TABLE1_TABLE2_ID = TABLE2_ID
 INNER JOIN TABLE3 ON TABLE1_TABLE3_ID = TABLE3_ID
 WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'A'),

(SELECT title as B
 FROM TABLE1
 INNER JOIN TABLE2 ON TABLE1_TABLE2_ID = TABLE2_ID
 INNER JOIN TABLE3 ON TABLE1_TABLE3_ID = TABLE3_ID
 WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'B')
</code>```

For example, this table must be show

```<code>  A        B
---------------
Computer  null
</code>```

But now it show the values only if Id has Type A and Type B

答:
It is unclear what data you have but you can use PIVOT, and avoid a self-join, when you are expecting zero-or-one row per TABLE_TYP:

SQL Fiddle

Oracle 11g R2 Schema Setup:

```<code>CREATE TABLE TABLE1 ( table1_table2_id, table1_table3_ID ) AS
SELECT 1, 2008 FROM DUAL;

CREATE TABLE TABLE2 ( table2_ID, table_typ ) AS
SELECT 1, 'A' FROM DUAL;

CREATE TABLE TABLE3 ( table3_ID, title ) AS
SELECT 2008, 'Computer' FROM DUAL;
</code>```

Query 1:

```<code>SELECT *
FROM   (
  SELECT title,
         table_typ
  FROM   TABLE1
         INNER JOIN TABLE2 ON TABLE1_TABLE2_ID = TABLE2_ID
         INNER JOIN TABLE3 ON TABLE1_TABLE3_ID = TABLE3_ID
  WHERE  TABLE1_TABLE3_ID = 2008
  AND    TABLE_TYP IN ( 'A', 'B' )
)
PIVOT ( MAX( title ) FOR Table_Typ IN ( 'A' AS A, 'B' AS B ) )
</code>```

Results:

```<code>|        A |      B |
|----------|--------|
| Computer | (null) |
</code>```

If your sub-queries are expecting to return multiple rows then you would not be able to use this exact method (but still may be able to use PIVOT, and avoid the self-join, depending on your requirements).

Body:
If this query hasn't B values, but has A values, can I have null where there are no values?

SELECT A, B
FROM
(SELECT title as A
 FROM TABLE1
 INNER JOIN TABLE2 ON TABLE1_TABLE2_ID = TABLE2_ID
 INNER JOIN TABLE3 ON TABLE1_TABLE3_ID = TABLE3_ID
 WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'A'),

(SELECT title as B
 FROM TABLE1
 INNER JOIN TABLE2 ON TABLE1_TABLE2_ID = TABLE2_ID
 INNER JOIN TABLE3 ON TABLE1_TABLE3_ID = TABLE3_ID
 WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'B')

For example, this table must be show

  A        B
---------------
Computer  null

But now it show the values only if Id has Type A and Type B

Body:
It is unclear what data you have but you can use PIVOT, and avoid a self-join, when you are expecting zero-or-one row per TABLE_TYP:

SQL Fiddle

Oracle 11g R2 Schema Setup:

CREATE TABLE TABLE1 ( table1_table2_id, table1_table3_ID ) AS
SELECT 1, 2008 FROM DUAL;

CREATE TABLE TABLE2 ( table2_ID, table_typ ) AS
SELECT 1, 'A' FROM DUAL;

CREATE TABLE TABLE3 ( table3_ID, title ) AS
SELECT 2008, 'Computer' FROM DUAL;

Query 1:

SELECT *
FROM   (
  SELECT title,
         table_typ
  FROM   TABLE1
         INNER JOIN TABLE2 ON TABLE1_TABLE2_ID = TABLE2_ID
         INNER JOIN TABLE3 ON TABLE1_TABLE3_ID = TABLE3_ID
  WHERE  TABLE1_TABLE3_ID = 2008
  AND    TABLE_TYP IN ( 'A', 'B' )
)
PIVOT ( MAX( title ) FOR Table_Typ IN ( 'A' AS A, 'B' AS B ) )

Results:

|        A |      B |
|----------|--------|
| Computer | (null) |

If your sub-queries are expecting to return multiple rows then you would not be able to use this exact method (but still may be able to use PIVOT, and avoid the self-join, depending on your requirements).


答:
This will work:

```<code>dates_rdd = sc.parallelize(dates).map(lambda x: tuple([int(x)]))
date_table = spark.createDataFrame(dates_rdd, _schema)
</code>```

The purpose of the additional map in defining dates_rdd is to make the format of the rdd match the schema

Title: Spark DataFrame from pandas Series

Body:
This will work:

dates_rdd = sc.parallelize(dates).map(lambda x: tuple([int(x)]))
date_table = spark.createDataFrame(dates_rdd, _schema)

The purpose of the additional map in defining dates_rdd is to make the format of the rdd match the schema


问:
ColdFusion - Connect to LDAP Server
I am using cfldap (ColdFusion 2016) to connect to an LDAP server but the server starts with LDAPS://. ColdFusion throws an error that it is an invalid name. When I try to connect without LDAPS,  it throws "An error has occured while executing the query. Below is the full tag I am using.

```<code><cftry>
     <cfldap server="#servername#"
             username="#username#"
             password="#password#"
             port="636" action="query"
             name="qryName"
             start="#start#"
             attributes="#attributes#"
             filter="#filter#"
             scope="SUBTREE"
             secure="cfssl_basic">

    <cfcatch type="any">
          <cfdump var="#cfcatch#">
    </cfcatch>

</cftry>
</code>```

Is there anything missing?

答:
You may need to import the ldap server's certificate or if it is Active Directory the domain's CA certificate into the java keystore.

https://helpx.adobe.com/coldfusion/kb/import-certificates-certificate-stores-coldfusion.html

Also, here is an example os authenticating via Active Directory.

```<code>cfldap(
    server = "ServerName",
    port = 636,
    action = "QUERY",
    name = "qLDAPLookup",
    secure = "CFSSL_BASIC",
    username = "MYDOMAIN\#arguments.username#",
    password = arguments.password,
    start = "dc=MYDOMAIN,dc=MYTLD",
    attributes = "cn,userPrincipalName,title,mail",
    timeout = "10",
    filter = "(sAMAccountName=#arguments.username#)"
);

if (qLDAPLookup.recordCount) {
    userAuthenticated = true;
}
</code>```

Title: ColdFusion - Connect to LDAP Server

Body:
I am using cfldap (ColdFusion 2016) to connect to an LDAP server but the server starts with LDAPS://. ColdFusion throws an error that it is an invalid name. When I try to connect without LDAPS,  it throws "An error has occured while executing the query. Below is the full tag I am using.

<cftry>
     <cfldap server="#servername#"
             username="#username#"
             password="#password#"
             port="636" action="query"
             name="qryName"
             start="#start#"
             attributes="#attributes#"
             filter="#filter#"
             scope="SUBTREE"
             secure="cfssl_basic">

    <cfcatch type="any">
          <cfdump var="#cfcatch#">
    </cfcatch>

</cftry>

Is there anything missing?

Body:
You may need to import the ldap server's certificate or if it is Active Directory the domain's CA certificate into the java keystore.

https://helpx.adobe.com/coldfusion/kb/import-certificates-certificate-stores-coldfusion.html

Also, here is an example os authenticating via Active Directory.

cfldap(
    server = "ServerName",
    port = 636,
    action = "QUERY",
    name = "qLDAPLookup",
    secure = "CFSSL_BASIC",
    username = "MYDOMAIN\#arguments.username#",
    password = arguments.password,
    start = "dc=MYDOMAIN,dc=MYTLD",
    attributes = "cn,userPrincipalName,title,mail",
    timeout = "10",
    filter = "(sAMAccountName=#arguments.username#)"
);

if (qLDAPLookup.recordCount) {
    userAuthenticated = true;
}


问:
How to POST request to Google Shortener API with Google API Java Client and parse a JSON response?
I want to use the Google Shortener API. I want to use the google api java client library to post a request and parse the JSON response.

Next, I post the code I have tried:

```<code>import java.io.IOException;
import net.sf.json.JSONObject;
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.GoogleTransport;
import com.google.api.client.googleapis.json.JsonCParser;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonHttpContent;
import com.google.api.client.util.GenericData;

public class GoogleShortener {
public static final String GOOGL_URL = "https://www.googleapis.com/urlshortener/v1/url";

    public static void main(String[] args) {
        // setup up the HTTP transport
        HttpTransport transport = GoogleTransport.create();
        // add default headers
        GoogleHeaders defaultHeaders = new GoogleHeaders();
        transport.defaultHeaders = defaultHeaders;
        transport.defaultHeaders.put("Content-Type", "application/json");
        transport.addParser(new JsonCParser());
        // build the HTTP GET request and URL

        GenericData data = new GenericData();
        data.put("longUrl", "http://www.google.com/");

        JsonHttpContent content = new JsonHttpContent();
        content.data = data;

        HttpRequest request = transport.buildPostRequest();
        request.content = content;
        request.setUrl(GOOGL_URL);
        HttpResponse response;
        try {
            JSONObject json = request.execute().parseAs(JSONObject.class);
        } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
        }
    }
}
</code>```

When I execute the above code, I get the next output:

```<code>Exception in thread "main" java.lang.IllegalArgumentException: data key not found
    at com.google.api.client.googleapis.json.JsonCParser.parserForResponse(JsonCParser.java:77)
    at com.google.api.client.googleapis.json.JsonCParser.parse(JsonCParser.java:47)
    at com.google.api.client.http.HttpResponse.parseAs(HttpResponse.java:261)
    at GoogleShortener.main(GoogleShortener.java:43)
</code>```

Any idea how to set the JsonCParser properly?

ERROR PATH

In the beginning I was not setting properly the request content. As pointed by @dwb, the request content should be set:

```<code>GenericData data = new GenericData();
data.put("longUrl", "http://www.google.com/");

JsonHttpContent content = new JsonHttpContent();
content.data = data;

request.content = content;
</code>```

If you do not set the content properly, you will get the next error

com.google.api.client.http.HttpResponseException:
  411 Length Required   at
  com.google.api.client.http.HttpRequest.execute(HttpRequest.java:209)
    at
  GoogleShortener.main(GoogleShortener.java:32)

答:
You need to add JSON content to the request body like this:

```<code>GenericData data = new GenericData();
data.put("longUrl", "http://www.google.com/");
JsonHttpContent content = new JsonHttpContent();
content.data = data;
request.content = content;
</code>```

For the response, try using the JsonHttpParser instead of JsonCParser. You'll need to create a subclass of GenericJson that contains fields with a @Key annotation for every JSON property you want to retrieve. You can use response.parseAsString() to see all of the properties available.

Here's a full working example:

```<code>import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.GoogleTransport;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonHttpContent;
import com.google.api.client.json.JsonHttpParser;
import com.google.api.client.util.GenericData;
import com.google.api.client.util.Key;

public class Shortener {

    public static final String GOOGL_URL = "https://www.googleapis.com/urlshortener/v1/url";

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        // setup up the HTTP transport
        HttpTransport transport = GoogleTransport.create();
        // add default headers
        GoogleHeaders defaultHeaders = new GoogleHeaders();
        transport.defaultHeaders = defaultHeaders;
        transport.defaultHeaders.put("Content-Type", "application/json");
        transport.addParser(new JsonHttpParser());

        // build the HTTP GET request and URL
        HttpRequest request = transport.buildPostRequest();
        request.setUrl(GOOGL_URL);
        GenericData data = new GenericData();
        data.put("longUrl", "http://www.google.com/");
        JsonHttpContent content = new JsonHttpContent();
        content.data = data;
        request.content = content;

        HttpResponse response = request.execute();
        Result result = response.parseAs(Result.class);

        System.out.println(result.shortUrl);
    }

    public static class Result extends GenericJson {
        @Key("id")
        public String shortUrl;
    }
}
</code>```

Body:
I want to use the Google Shortener API. I want to use the google api java client library to post a request and parse the JSON response.

Next, I post the code I have tried:

import java.io.IOException;
import net.sf.json.JSONObject;
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.GoogleTransport;
import com.google.api.client.googleapis.json.JsonCParser;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonHttpContent;
import com.google.api.client.util.GenericData;

public class GoogleShortener {
public static final String GOOGL_URL = "https://www.googleapis.com/urlshortener/v1/url";

    public static void main(String[] args) {
        // setup up the HTTP transport
        HttpTransport transport = GoogleTransport.create();
        // add default headers
        GoogleHeaders defaultHeaders = new GoogleHeaders();
        transport.defaultHeaders = defaultHeaders;
        transport.defaultHeaders.put("Content-Type", "application/json");
        transport.addParser(new JsonCParser());
        // build the HTTP GET request and URL

        GenericData data = new GenericData();
        data.put("longUrl", "http://www.google.com/");

        JsonHttpContent content = new JsonHttpContent();
        content.data = data;

        HttpRequest request = transport.buildPostRequest();
        request.content = content;
        request.setUrl(GOOGL_URL);
        HttpResponse response;
        try {
            JSONObject json = request.execute().parseAs(JSONObject.class);
        } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
        }
    }
}

When I execute the above code, I get the next output:

Exception in thread "main" java.lang.IllegalArgumentException: data key not found
    at com.google.api.client.googleapis.json.JsonCParser.parserForResponse(JsonCParser.java:77)
    at com.google.api.client.googleapis.json.JsonCParser.parse(JsonCParser.java:47)
    at com.google.api.client.http.HttpResponse.parseAs(HttpResponse.java:261)
    at GoogleShortener.main(GoogleShortener.java:43)

Any idea how to set the JsonCParser properly?

ERROR PATH

In the beginning I was not setting properly the request content. As pointed by @dwb, the request content should be set:

GenericData data = new GenericData();
data.put("longUrl", "http://www.google.com/");

JsonHttpContent content = new JsonHttpContent();
content.data = data;

request.content = content;

If you do not set the content properly, you will get the next error

com.google.api.client.http.HttpResponseException:
  411 Length Required   at
  com.google.api.client.http.HttpRequest.execute(HttpRequest.java:209)
    at
  GoogleShortener.main(GoogleShortener.java:32)

Body:
You need to add JSON content to the request body like this:

GenericData data = new GenericData();
data.put("longUrl", "http://www.google.com/");
JsonHttpContent content = new JsonHttpContent();
content.data = data;
request.content = content;

For the response, try using the JsonHttpParser instead of JsonCParser. You'll need to create a subclass of GenericJson that contains fields with a @Key annotation for every JSON property you want to retrieve. You can use response.parseAsString() to see all of the properties available.

Here's a full working example:

import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.GoogleTransport;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonHttpContent;
import com.google.api.client.json.JsonHttpParser;
import com.google.api.client.util.GenericData;
import com.google.api.client.util.Key;

public class Shortener {

    public static final String GOOGL_URL = "https://www.googleapis.com/urlshortener/v1/url";

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        // setup up the HTTP transport
        HttpTransport transport = GoogleTransport.create();
        // add default headers
        GoogleHeaders defaultHeaders = new GoogleHeaders();
        transport.defaultHeaders = defaultHeaders;
        transport.defaultHeaders.put("Content-Type", "application/json");
        transport.addParser(new JsonHttpParser());

        // build the HTTP GET request and URL
        HttpRequest request = transport.buildPostRequest();
        request.setUrl(GOOGL_URL);
        GenericData data = new GenericData();
        data.put("longUrl", "http://www.google.com/");
        JsonHttpContent content = new JsonHttpContent();
        content.data = data;
        request.content = content;

        HttpResponse response = request.execute();
        Result result = response.parseAs(Result.class);

        System.out.println(result.shortUrl);
    }

    public static class Result extends GenericJson {
        @Key("id")
        public String shortUrl;
    }
}