问:
Trouble incrementing and decrementing a malloced array of multiple data types in C
In my Computer Science course, we have been taught a method of storing a value in the 0th element of a malloced array, then incrementing the array so that things such as the size of the array can be stored in that element and retrieved later. I have tried using a modified version of this method to store various datatypes in these incremented elements.

Here is an example of how such an array is created:

```<code>int *array;
array = malloc(sizeof(int) + sizeof(double) + (n * sizeof(int)))
*(array) = n;
array++;
(double*)array++;
return array;
</code>```

In this example, the sizeof(int) and sizeof(double) in the malloc statement are the elements that will store things, such as the size of the array in the int element, and in the double element we can store something like the average of all the numbers in the array (excluding these two elements of course)

(n * sizeof(int)) is for creating the rest of the elements in the array, where n is the number of elements, and sizeof(int) is the desired data type for these elements, and in theory this should work for an array of any data type.

Now, here is the trouble I am having:

I have created another function to retrieve the size of the array, but I am having trouble decrementing and incrementing the array. Here is my code:

```<code>getArraySize(void* array){
(double*)array--;//Decrement past the double element
(int*)array--;//Decrement past the int element

int size = *((int*)array);//Acquire size of the array

(int*)array++;//Increment past int element
(double*)array++;//Increment past the double element

return size;}
</code>```

This function fails to get the size of the array, and I have realized it is because the compiler first increments the array then type casts it. However, when i try to fix such increment/decrement statements as follows:

```<code>((int*)array)++;
</code>```

I get an error that says lvalue required as increment operand. I do not know how to fix this notation in such a way that it will increment and decrement correctly. Any suggestions would be much appreciated.

答:
In my Computer Science course, we have been taught a method of storing a value in the 0th element of a malloced array, then incrementing the array so that things such as the size of the array can be stored in that element and retrieved later.

Sorry to hear that, since this is utter nonsense. Use struct instead.

What's worse than the task being nonsense however, is that it also invokes undefined behavior (see the C standard 6.5.6). You cannot do pointer arithmetic with that are not pointing to an array with the same type as the pointer itself.

In addition, this may lead to misaligned access. Depending on CPU, misalignment could cause needlessly slow code or instruction traps leading to a program crash. Misaligned access is also undefined behavior.

Also, storing the result of various operations on a data type, such as average, inside the data type itself doesn't make any sense at all. They would have to be updated as soon as a value changes, which causes needless bloat and ineffective code.

Forget about all this nonsense immediately. Your program cannot get fixed or repaired, since the very idea behind it is fundamentally wrong. Do like this instead:

```<code>typedef struct
{
  int i;
  double d;
  int array[];
} something;

something* s = malloc(sizeof(something) + sizeof(int[n]));
s->i = ...;
s->d = ...;
for(int i=0; i<n; i++)
  s->array[i] = ...;

...
free(s);
</code>```

Specifically, your code invokes undefined behavior per C17 6.5.6 §7 and §8:

For the purposes of these operators, a pointer to an object that is not an element of an
  array behaves the same as a pointer to the first element of an array of length one with the
  type of the object as its element type.

When an expression that has integer type is added to or subtracted from a pointer, the
  result has the type of the pointer operand. /--/
  If both the pointer operand and the result point to elements of the same array object... /--/ ...otherwise, the
  behavior is undefined.

There is also the issue of pointer aliasing, but (by luck?) it doesn't apply in this case, since data allocated on the heap doesn't have an "effective type" until written to. Long as you write to a specific address with the same pointer type, it is not undefined behavior.

Relevant parts regarding misalignment is C17 6.3.2.3/7:

A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned for the referenced type, the behavior is undefined.

Body:
In my Computer Science course, we have been taught a method of storing a value in the 0th element of a malloced array, then incrementing the array so that things such as the size of the array can be stored in that element and retrieved later. I have tried using a modified version of this method to store various datatypes in these incremented elements.

Here is an example of how such an array is created:

int *array;
array = malloc(sizeof(int) + sizeof(double) + (n * sizeof(int)))
*(array) = n;
array++;
(double*)array++;
return array;

In this example, the sizeof(int) and sizeof(double) in the malloc statement are the elements that will store things, such as the size of the array in the int element, and in the double element we can store something like the average of all the numbers in the array (excluding these two elements of course)

(n * sizeof(int)) is for creating the rest of the elements in the array, where n is the number of elements, and sizeof(int) is the desired data type for these elements, and in theory this should work for an array of any data type.

Now, here is the trouble I am having:

I have created another function to retrieve the size of the array, but I am having trouble decrementing and incrementing the array. Here is my code:

getArraySize(void* array){
(double*)array--;//Decrement past the double element
(int*)array--;//Decrement past the int element

int size = *((int*)array);//Acquire size of the array

(int*)array++;//Increment past int element
(double*)array++;//Increment past the double element

return size;}

This function fails to get the size of the array, and I have realized it is because the compiler first increments the array then type casts it. However, when i try to fix such increment/decrement statements as follows:

((int*)array)++;

I get an error that says lvalue required as increment operand. I do not know how to fix this notation in such a way that it will increment and decrement correctly. Any suggestions would be much appreciated.

Body:
In my Computer Science course, we have been taught a method of storing a value in the 0th element of a malloced array, then incrementing the array so that things such as the size of the array can be stored in that element and retrieved later.

Sorry to hear that, since this is utter nonsense. Use struct instead.

What's worse than the task being nonsense however, is that it also invokes undefined behavior (see the C standard 6.5.6). You cannot do pointer arithmetic with that are not pointing to an array with the same type as the pointer itself.

In addition, this may lead to misaligned access. Depending on CPU, misalignment could cause needlessly slow code or instruction traps leading to a program crash. Misaligned access is also undefined behavior.

Also, storing the result of various operations on a data type, such as average, inside the data type itself doesn't make any sense at all. They would have to be updated as soon as a value changes, which causes needless bloat and ineffective code.

Forget about all this nonsense immediately. Your program cannot get fixed or repaired, since the very idea behind it is fundamentally wrong. Do like this instead:

typedef struct
{
  int i;
  double d;
  int array[];
} something;

something* s = malloc(sizeof(something) + sizeof(int[n]));
s->i = ...;
s->d = ...;
for(int i=0; i<n; i++)
  s->array[i] = ...;

...
free(s);

Specifically, your code invokes undefined behavior per C17 6.5.6 §7 and §8:

For the purposes of these operators, a pointer to an object that is not an element of an
  array behaves the same as a pointer to the first element of an array of length one with the
  type of the object as its element type.

When an expression that has integer type is added to or subtracted from a pointer, the
  result has the type of the pointer operand. /--/
  If both the pointer operand and the result point to elements of the same array object... /--/ ...otherwise, the
  behavior is undefined.

There is also the issue of pointer aliasing, but (by luck?) it doesn't apply in this case, since data allocated on the heap doesn't have an "effective type" until written to. Long as you write to a specific address with the same pointer type, it is not undefined behavior.

Relevant parts regarding misalignment is C17 6.3.2.3/7:

A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned for the referenced type, the behavior is undefined.


来源: stackexchange

问:
HTTPS redirect in .htaccess is causing infinite redirect loop
I'm trying to redirect all HTTP urls to HTTPS using the following in .htaccess:

```<code>RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</code>```

However it just causes an infinite redirect loop.  There is a valid SSL certificate and the website is written in asp.net in case it matters.  Google chrome automatically redirects to https, but firefox and edge do not so I need to add this rule.  The only way I can get the site to load in https is if I explicitly type https:// in the address.  What's the possible cause here?

答:
IIS does not support .htaccess file.so I suggest you use iis URL rewrite module and add a rule using that.

for that, you need to install the URL rewrite module by using the web platform installer or from this below link.

https://www.iis.net/downloads/microsoft/url-rewrite

than add below code in your config file:

```<code><configuration>
 <system.webServer>
 <rewrite>
 <rules>
 <rule name="HTTP to HTTPS" enabled="true" stopProcessing="true">
 <match url="(.*)" />
 <conditions>
 <add input="{HTTPS}" pattern="off" />
 </conditions>
 <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent"/>
 </rule>
 </rules>
 </rewrite>
 </system.webServer>
</configuration>
</code>```

for more detail you could refer this below link:

https://stackoverflow.com/a/55531655/11147346

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to redirect all HTTP urls to HTTPS using the following in .htaccess:

RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

However it just causes an infinite redirect loop.  There is a valid SSL certificate and the website is written in asp.net in case it matters.  Google chrome automatically redirects to https, but firefox and edge do not so I need to add this rule.  The only way I can get the site to load in https is if I explicitly type https:// in the address.  What's the possible cause here?

Body:
IIS does not support .htaccess file.so I suggest you use iis URL rewrite module and add a rule using that.

for that, you need to install the URL rewrite module by using the web platform installer or from this below link.

https://www.iis.net/downloads/microsoft/url-rewrite

than add below code in your config file:

<configuration>
 <system.webServer>
 <rewrite>
 <rules>
 <rule name="HTTP to HTTPS" enabled="true" stopProcessing="true">
 <match url="(.*)" />
 <conditions>
 <add input="{HTTPS}" pattern="off" />
 </conditions>
 <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent"/>
 </rule>
 </rules>
 </rewrite>
 </system.webServer>
</configuration>

for more detail you could refer this below link:

https://stackoverflow.com/a/55531655/11147346


问:
Is there a way to query multiple tables at once based on common table name in Oracle through SQL or PL/SQL
I have a requirement to fetch data from all the tables based on common table name pattern every week.Basically my requirement is to merge all the data to form a single lookup table.

Example:

Table Names:

```<code>Department_20190101
Department_20190109
Department_20190122
Department_20190129
</code>```

I have to fetch data from all the tables and have to create a single lookup table. Is there a simple way to do this other than by going through iteration in PL/SQL by getting the table names with the help of ALL_TABLES

Note:The Date part is not consistent.If i can achieve this requirement once then i can easily start inserting the data from the new table to the existing lookup(n+1)

Please share your suggestions.

Regards,
Scott

答: Check here:  Execute For Each Table in PLSQL  there is nice example to resolve Your problem using pl/sql (pl/sql help You dinamicly grow up sql-query) .</p>

Body:
I have a requirement to fetch data from all the tables based on common table name pattern every week.Basically my requirement is to merge all the data to form a single lookup table.

Example:

Table Names:

Department_20190101
Department_20190109
Department_20190122
Department_20190129

I have to fetch data from all the tables and have to create a single lookup table. Is there a simple way to do this other than by going through iteration in PL/SQL by getting the table names with the help of ALL_TABLES

Note:The Date part is not consistent.If i can achieve this requirement once then i can easily start inserting the data from the new table to the existing lookup(n+1)

Please share your suggestions.

Regards,
Scott


问:
Inline form elements in Angular / Material
I'm trying to design an form that has an input field and right beside it, a button. However, I'm getting the button on top of the input field.

```<code><mat-form-field>
  <input matInput placeholder="Select Spec Folder">
  <button mat-raised-button >Select Folder</button>
</mat-form-field>
</code>```

Is there a way to have both elements on the same line one after the other?

Thanks

答:
I did something like this

```<code>    <form #form="ngForm">
      <mat-form-field>
        <input matInput placeholder="Name" maxlength="8" minlength="5" required
               #name>
      </mat-form-field>
      <button mat-icon-button type="submit" color="accent" aria-label="Save name">
        <mat-icon>check</mat-icon>
      </button>
    </form>
</code>```

And added below scss to keep the input field and save button inline

```<code>form {
 display: flex;

 mat-form-field {
  width: 80%;
  padding: 5px;
 }

 button {
  width: 25px;
  margin: auto;
 }
}
</code>```

In my case, I only had one input and a button. If you have multiple form fields group them inside a div and add flex to it and set the width to the child elements similar to what I did above with form and its child elements

Body:
I'm trying to design an form that has an input field and right beside it, a button. However, I'm getting the button on top of the input field.

<mat-form-field>
  <input matInput placeholder="Select Spec Folder">
  <button mat-raised-button >Select Folder</button>
</mat-form-field>

Is there a way to have both elements on the same line one after the other?

Thanks

Body:
I did something like this

    <form #form="ngForm">
      <mat-form-field>
        <input matInput placeholder="Name" maxlength="8" minlength="5" required
               #name>
      </mat-form-field>
      <button mat-icon-button type="submit" color="accent" aria-label="Save name">
        <mat-icon>check</mat-icon>
      </button>
    </form>

And added below scss to keep the input field and save button inline

form {
 display: flex;

 mat-form-field {
  width: 80%;
  padding: 5px;
 }

 button {
  width: 25px;
  margin: auto;
 }
}

In my case, I only had one input and a button. If you have multiple form fields group them inside a div and add flex to it and set the width to the child elements similar to what I did above with form and its child elements


问:
Graceful shutdown of windows service on server reboot
Is there a way to let a windows service - Tomcat in my case - gracefully shutdown when the machine or VM shuts down?

I have a schedule on a VM to shut down every night and it just kills the Tomcat process, resulting in a lot of session errors on my client.

On a graceful shutdown the clients are properly exited by the software

答:
Schedule a task in windows to shutdown your service first then shutdown your server.

You can just make a batch file the schedule it as a task

```<code>net stop <service name>
 shutdown /s
</code>```

Body:
Schedule a task in windows to shutdown your service first then shutdown your server.

You can just make a batch file the schedule it as a task

net stop <service name>
 shutdown /s


问:
Start Hadoop cluster using sbin/start-dfs.sh
I want to start Hadoop daemons with PHP instead of terminal.

When i do start-dfs.sh, it works well.

The PHP code I'm using is

```<code><?php
    echo shell_exec('/usr/local/hadoop3/sbin/stop-dfs.sh');
?>
</code>```

the output of the above code is

Starting namenodes on [localhost] starting datanodes. Starting
  secondary namenodes [chbpc-VirtualBox] .

but when i type the url http://localhost:9870/dfshealth.html#tab-overview in the browser (to check the status of my Hadoop), it actually did not start despite having the output above.

答:
Answer

```<code><?php
    echo shell_exec('/usr/local/hadoop3/sbin/stop-dfs.sh > /dev/null &');
?>
</code>```

Description

When you run the daemon process with shell_exec, you should detach from this process for finished your shell_exec command, but you should stay daemon process in progress state.

& - provide doing this.

Also instead /dev/null you may be using your custom log file and all info from stop-dfs.sh will redirect to this file.

My test for this solution

Copy this snippet to your bash console:

cat <<EOT > daemon.sh
while true; do date; sleep 1; done

EOT

chmod +x daemon.sh

cat <<EOT > daemon-runner.php
<?php
    echo shell_exec(__DIR__ . '/daemon.sh > daemon-log &');

EOT

touch daemon-log

php daemon-runner.php

tail -f daemon-log

```

PS

You using stop-dfs.sh script name for start your hadoop, also maybe you mixed up script name with start.sh?

Body:
I want to start Hadoop daemons with PHP instead of terminal.

When i do start-dfs.sh, it works well.

The PHP code I'm using is

<?php
    echo shell_exec('/usr/local/hadoop3/sbin/stop-dfs.sh');
?>

the output of the above code is

Starting namenodes on [localhost] starting datanodes. Starting
  secondary namenodes [chbpc-VirtualBox] .

but when i type the url http://localhost:9870/dfshealth.html#tab-overview in the browser (to check the status of my Hadoop), it actually did not start despite having the output above.

Body:
Answer

<?php
    echo shell_exec('/usr/local/hadoop3/sbin/stop-dfs.sh > /dev/null &');
?>

Description

When you run the daemon process with shell_exec, you should detach from this process for finished your shell_exec command, but you should stay daemon process in progress state.

& - provide doing this.

Also instead /dev/null you may be using your custom log file and all info from stop-dfs.sh will redirect to this file.

My test for this solution

Copy this snippet to your bash console:

cat <<EOT > daemon.sh
while true; do date; sleep 1; done

EOT

chmod +x daemon.sh

cat <<EOT > daemon-runner.php
<?php
    echo shell_exec(__DIR__ . '/daemon.sh > daemon-log &');

EOT

touch daemon-log

php daemon-runner.php

tail -f daemon-log

PS

You using stop-dfs.sh script name for start your hadoop, also maybe you mixed up script name with start.sh?


问:
mysql query prints data of different rows in one row
I am using MySQL version 8.0 and popSQL as the editor.

Table:

```<code>create table account (no int, salary int);

insert into account values
(901,25000),
(902,30000),
(903,21000),
(904,40000),
(905,27000);
</code>```

Now, I want no and salary of person with highest salary.
Highest salary is 40000 and corresponding no is 904.
But, this query is giving me different output.

```<code>-- no and salary of max salary
select no, max(salary)
from account ;
</code>```

The output is:
no  max(salary)
901 40000

It is printing the first no and the max salary.
i.e. data of different rows are shown in a same row.
How to fix this???

Same type of problem for my next query.

```<code>-- no and salary of second highest salary.
select no, max(salary)
from account
where salary not in
(select max(salary) from account);
</code>```

The output is:
no  max(salary)
901 30000

Whereas expected is 902,30000.

I searched through the stack overflow for issue where data of different rows are shown in one but didn't get any help.

Thanking you in advance.

答:
For Highest Salary

```<code>select no, salary from (
    select no, salary, ROW_NUMBER() OVER (partition by salary order by salary desc) as rn
    from account
) as a
where rn = 1 limit 1
</code>```

For Second highest salary

```<code>select no, salary from (
    select no, salary, ROW_NUMBER() OVER (partition by salary order by salary desc) as rn
    from account
) as a
where rn = 2 limit 1
</code>```

Body:
I am using MySQL version 8.0 and popSQL as the editor.

Table:

create table account (no int, salary int);

insert into account values
(901,25000),
(902,30000),
(903,21000),
(904,40000),
(905,27000);

Now, I want no and salary of person with highest salary.
Highest salary is 40000 and corresponding no is 904.
But, this query is giving me different output.

-- no and salary of max salary
select no, max(salary)
from account ;

The output is:
no  max(salary)
901 40000

It is printing the first no and the max salary.
i.e. data of different rows are shown in a same row.
How to fix this???

Same type of problem for my next query.

-- no and salary of second highest salary.
select no, max(salary)
from account
where salary not in
(select max(salary) from account);

The output is:
no  max(salary)
901 30000

Whereas expected is 902,30000.

I searched through the stack overflow for issue where data of different rows are shown in one but didn't get any help.

Thanking you in advance.

Body:
For Highest Salary

select no, salary from (
    select no, salary, ROW_NUMBER() OVER (partition by salary order by salary desc) as rn
    from account
) as a
where rn = 1 limit 1

For Second highest salary

select no, salary from (
    select no, salary, ROW_NUMBER() OVER (partition by salary order by salary desc) as rn
    from account
) as a
where rn = 2 limit 1


问:
Webdriver disable enhanced protected mode
I am using webdriver on IE11. And per selenium there are a set of required setting to run in IE11 one of them is to disabled "enhanced protected mode" in Internet Option > Advanced > Security (not the same as the enabled protected mode in Internet Option > Security)

The problem is, my group policy's has those field disabled, meaning I cannot turn them off without requesting for a group policy change. I was wondering if there is a IE capability or option out there that can work around this issue like the caps['ignoreProtectedModeSettings'] = True for the Internet Option > Security Enable Protection Mode setting

https://github.com/SeleniumHQ/selenium/wiki/InternetExplorerDriver

答:
Please try to use the InternetExplorerOptions object and set the  IntroduceInstabilityByIgnoringProtectedModeSettings property to true in C# application, code as below:

```<code>   private const string URL = @"https://www.bing.com/";
    private const string IE_DRIVER_PATH = @"E:\webdriver\IEDriverServer_x64_3.14.0";  // where the Selenium IE webdriver EXE is.
    static void Main(string[] args)
    {
        InternetExplorerOptions opts = new InternetExplorerOptions() {
            IntroduceInstabilityByIgnoringProtectedModeSettings = true,
            IgnoreZoomLevel = true,
        };
        using (var driver = new InternetExplorerDriver(IE_DRIVER_PATH, opts))
        {
            driver.Navigate().GoToUrl("https://www.bing.com/");

            //someTextbox.SendKeys("abc123");
            var element = driver.FindElementById("sb_form_q");
            var script = "document.getElementById('sb_form_q').value = 'webdriver';";

            IJavaScriptExecutor jse = (IJavaScriptExecutor)driver;
            jse.ExecuteScript(script, element);

            //element.SendKeys("webdriver");
            element.SendKeys(Keys.Enter);
        }
    }
</code>```

If you application is a Java application, try to use the following code:

```<code>DesiredCapabilities cap = DesiredCapabilities.internetExplorer();
cap.setCapability("nativeEvents", false);
cap.setCapability("unexpectedAlertBehaviour", "accept");
cap.setCapability("ignoreProtectedModeSettings", true);
cap.setCapability("disable-popup-blocking", true);
cap.setCapability("enablePersistentHover", true);
cap.setCapability("ignoreZoomSetting", true);
cap.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
InternetExplorerOptions options = new InternetExplorerOptions();
options.merge(cap);
WebDriver driver = new InternetExplorerDriver(options);
</code>```

Code from this link.

Body:
Please try to use the InternetExplorerOptions object and set the  IntroduceInstabilityByIgnoringProtectedModeSettings property to true in C# application, code as below:

   private const string URL = @"https://www.bing.com/";
    private const string IE_DRIVER_PATH = @"E:\webdriver\IEDriverServer_x64_3.14.0";  // where the Selenium IE webdriver EXE is.
    static void Main(string[] args)
    {
        InternetExplorerOptions opts = new InternetExplorerOptions() {
            IntroduceInstabilityByIgnoringProtectedModeSettings = true,
            IgnoreZoomLevel = true,
        };
        using (var driver = new InternetExplorerDriver(IE_DRIVER_PATH, opts))
        {
            driver.Navigate().GoToUrl("https://www.bing.com/");

            //someTextbox.SendKeys("abc123");
            var element = driver.FindElementById("sb_form_q");
            var script = "document.getElementById('sb_form_q').value = 'webdriver';";

            IJavaScriptExecutor jse = (IJavaScriptExecutor)driver;
            jse.ExecuteScript(script, element);

            //element.SendKeys("webdriver");
            element.SendKeys(Keys.Enter);
        }
    }

If you application is a Java application, try to use the following code:

DesiredCapabilities cap = DesiredCapabilities.internetExplorer();
cap.setCapability("nativeEvents", false);
cap.setCapability("unexpectedAlertBehaviour", "accept");
cap.setCapability("ignoreProtectedModeSettings", true);
cap.setCapability("disable-popup-blocking", true);
cap.setCapability("enablePersistentHover", true);
cap.setCapability("ignoreZoomSetting", true);
cap.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
InternetExplorerOptions options = new InternetExplorerOptions();
options.merge(cap);
WebDriver driver = new InternetExplorerDriver(options);

Code from this link.


问:
Escape white space in column name in Hive
I want to write a script to query data from Hive using ODBC. However, the column that I have to make a condition on happen to have a white space in it. As a result, it returned only column names but no result. So, I'd like to know how I can escape the white space in column name, "item id", so that I can get the result I desire returned.

Here is the example of code I used.

```<code>import pyodbc
import pandas as pd

query = "SELECT * FROM tableA " \
    "WHERE 'item id' RLIKE 'AB001.*' LIMIT 2 "

with pyodbc.connect("DSN=HIVE_ODBC", autocommit=True) as conn:
    df = pd.read_sql(query, conn)

df
</code>```

Thank you in advance

答:
Try the following:

```<code> query = "SELECT * FROM tableA " \
 "WHERE `item id` RLIKE 'AB001.*' LIMIT 2 "
</code>```

e.i., instead single-quote use `.

Body:
I want to write a script to query data from Hive using ODBC. However, the column that I have to make a condition on happen to have a white space in it. As a result, it returned only column names but no result. So, I'd like to know how I can escape the white space in column name, "item id", so that I can get the result I desire returned.

Here is the example of code I used.

import pyodbc
import pandas as pd

query = "SELECT * FROM tableA " \
    "WHERE 'item id' RLIKE 'AB001.*' LIMIT 2 "

with pyodbc.connect("DSN=HIVE_ODBC", autocommit=True) as conn:
    df = pd.read_sql(query, conn)

df

Thank you in advance

Body:
Try the following:

 query = "SELECT * FROM tableA " \
 "WHERE `item id` RLIKE 'AB001.*' LIMIT 2 "

e.i., instead single-quote use `.


问:
Get cookies from website with requests in python
i try to get all cookies (include cookies that set by javascript) from a website using python. At the moment i try that with the requests module.

The http cookies are not the problem. I can catch them with:

```<code>response = requests.get("http://example.com")
http_cookies = response.cookies
</code>```

The cookies that are set by javascript is a little bit tricky.
I search the content from all  tags and the integrated javascripts sources

答:
As Chris said, it is not possible to search for cookies using that regex because cookies can be set in a multitude of ways not just limited to document.cookie.

I would suggest using Selenium, which imitates a browser, where you can get the cookies by using the following:

```<code>import pickle
import selenium.webdriver

driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))
</code>```

Body:
i try to get all cookies (include cookies that set by javascript) from a website using python. At the moment i try that with the requests module.

The http cookies are not the problem. I can catch them with:

response = requests.get("http://example.com")
http_cookies = response.cookies

The cookies that are set by javascript is a little bit tricky.
I search the content from all  tags and the integrated javascripts sources

Body:
As Chris said, it is not possible to search for cookies using that regex because cookies can be set in a multitude of ways not just limited to document.cookie.

I would suggest using Selenium, which imitates a browser, where you can get the cookies by using the following:

import pickle
import selenium.webdriver

driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))


问:
How can I generate random number in specific range in Android?
I want to generate random number in a specific range. (Ex. Range Between 65 to 80)

I try as per below code, but it is not very use full. It also returns the value greater then max. value(greater then 80).

```<code>Random r = new Random();
int i1 = (r.nextInt(80) + 65);
</code>```

How can I generate random number between a range?

答:
```<code>int min = 65;
int max = 80;

Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;
</code>```

Note that nextInt(int max) returns an int between 0 inclusive and max exclusive. Hence the +1.

Body:
I want to generate random number in a specific range. (Ex. Range Between 65 to 80)

I try as per below code, but it is not very use full. It also returns the value greater then max. value(greater then 80).

Random r = new Random();
int i1 = (r.nextInt(80) + 65);

How can I generate random number between a range?

Body:
int min = 65;
int max = 80;

Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;

Note that nextInt(int max) returns an int between 0 inclusive and max exclusive. Hence the +1.

ContentLicense: CC BY-SA 3.0


问:
DolphinDB pivot table
I have a table something looking like this:

```<code>id CompanyName ProductID productName
-- ----------- --------- -----------
1  c1          1         p1
2  c1          2         p2
3  c2          2         p2
4  c2          3         p3
5  c3          3         p3
6  c4          3         p3
7  c5          4         p4
8  c6          4         p4
9  c6          5         p5
</code>```

Is it possible to run a DolphinDB query to get output like this:

```<code>companyName p1  p2  p3  p4  p5
------------------------------
c1          1   1   0   0   0
c2          0   1   1   0   0
c3          0   0   1   0   0
c4          0   0   1   0   0
c5          0   0   0   1   0
c6          0   0   0   1   1

</code>```

The value in the above table is the number of each product in each company.I get it by the query:

```<code>select count(*) from t group by companyName,productName
</code>```

答:
```<code>t1=select count(ProductID) from t pivot by CompanyName, productName
nullFill!(t1,0)
</code>```

Title: DolphinDB pivot table

Body:
I have a table something looking like this:

id CompanyName ProductID productName
-- ----------- --------- -----------
1  c1          1         p1
2  c1          2         p2
3  c2          2         p2
4  c2          3         p3
5  c3          3         p3
6  c4          3         p3
7  c5          4         p4
8  c6          4         p4
9  c6          5         p5

Is it possible to run a DolphinDB query to get output like this:

companyName p1  p2  p3  p4  p5
------------------------------
c1          1   1   0   0   0
c2          0   1   1   0   0
c3          0   0   1   0   0
c4          0   0   1   0   0
c5          0   0   0   1   0
c6          0   0   0   1   1

The value in the above table is the number of each product in each company.I get it by the query:

select count(*) from t group by companyName,productName


问:
Azure SQL is not letting me create a SQL User
I have a Database server created in Azure [not a managed instance] and a Server Admin user was created, many SQL users were added and they were able to login without any issues. Now all of a sudden, SQL users  I newly create can't login. It's giving Login failed message with Error# 18456

Here are the SQL commands I am using to create the user [after logging in as Server Admin]:

CREATE LOGIN reportslogin WITH password='' - this in "master" database

CREATE USER reportsuser from LOGIN reportslogin - this is in MyDatabase

ALTER ROLE db_datareader ADD MEMBER reportsuser - this again is in MyDatabase

Now I disconnect the server and when I try reconnecting to the server using the reportsuser, I get this:

What am I doing wrong?

答:
Actually, the error is caused by you database login name.

You should using the Login reportslogin to login the database, not the username reportsuser !

We must using the login name to access the Azure SQL database, not the username.

A login is a simple credential for accessing SQL Server. For example,

SQL Login is for Authentication and SQL Server User is for Authorization. Authentication can decide if we have permissions to access the server or not and Authorization decides what are different operations we can do in a database. Login are created at the SQL Server instance level and User is created at SQL Server database level.

Please reference:

Login and SQL User

Difference between a User and a Login in SQL Server

Suggestions:

create the login and user with the same name:

USE master
CREATE LOGIN reportslogin  WITH password='Xunmi110'

USE user_database
CREATE USER reportsuser  FOR LOGIN  reportslogin
ALTER ROLE db_datareader ADD MEMBER reportsuser

One login for one user.

Hope this helps.


问:
Subclassing Uint8Array in Javascript
I try to use Uint8Array to simulate a byte[] or uint8[].

TypedArray.subarray creating a new view on the existing buffer,changes to the new object's contents will impact the original object and vice versa.

I always use it like this:

let u = new Uint8Array(8) //'u' is 8 bytes
let a = u.subarray(4) //'a' is 4 bytes
console.log(a) // show [0,0,0,0], it is ok ```
</div>
</div>
</p>

<p>but when I try to subclassing Uint8Array, subarray goes strange.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class bytes extends Uint8Array {
  constructor(arg) {
    super(arg)
  }
}

let b = new bytes(8) //'b' is 8 bytes
let c = b.subarray(4) //'c' should be 4 bytes, but is 8 bytes
console.log(c) // show [0,0,0,0,0,0,0,0], ??????</code>```

I want to know what happened and how to fix it.

答:
It has to do with how arguments are interpreted by the overloaded constructor.

This works correctly:

class bytes extends Uint8Array {
  constructor(...args) {
    super(...args);
  }
}

let b = new bytes(8);
let c = b.subarray(4);
console.log(c);```

Title: Subclassing Uint8Array in Javascript

Body:
I try to use Uint8Array to simulate a byte[] or uint8[].

TypedArray.subarray creating a new view on the existing buffer,changes to the new object's contents will impact the original object and vice versa.

I always use it like this:

let u = new Uint8Array(8) //'u' is 8 bytes
let a = u.subarray(4) //'a' is 4 bytes
console.log(a) // show [0,0,0,0], it is ok

but when I try to subclassing Uint8Array, subarray goes strange.

class bytes extends Uint8Array {
  constructor(arg) {
    super(arg)
  }
}

let b = new bytes(8) //'b' is 8 bytes
let c = b.subarray(4) //'c' should be 4 bytes, but is 8 bytes
console.log(c) // show [0,0,0,0,0,0,0,0], ??????

I want to know what happened and how to fix it.


问:
Delete images and pdf when the session is over
I want to develop a healthcare app in android. the doctor will be authenticate for a specific time to access patient's medical reports and download them to the application (reports will be in a block-chain or a db). when the session is over all of those downloaded data (reports) should be permanently deleted from the doctors mobile. what is the best approach to delete these data?

答: Well, when the doctor will be authenticated you should start some type of a timer (for how long will he be authenticated to use patient's records) and save the paths to these files in DB. After the timer hits the 0 or the max value, you should have a listener or observer that just deletes the files from his mobile (using the paths saved in the database).  You can delete files using File class.


答:
```<code>Random r = new Random();
int i1 = r.nextInt(80 - 65) + 65;
</code>```

This gives a random integer between 65 (inclusive) and 80 (exclusive), one of 65,66,...,78,79.

Title: How can I generate random number in specific range in Android?

Body:
Random r = new Random();
int i1 = r.nextInt(80 - 65) + 65;

This gives a random integer between 65 (inclusive) and 80 (exclusive), one of 65,66,...,78,79.


问:
timber lint: ClassNotFound: com/android/tools/lint/detector/api/Detector$JavaPsiScanner
The Timber (V 4.5.0) lint checks only work via Gradle (but not via the lint command and also not in Android Studio Version 2.3 Beta2).

Summary

When I run lint directly on the command line I get an error.

```<code>lint --show TimberArgCount

Could not load custom rule jar file /home/tmtron/.android/lint/timber-lint.jar
java.lang.NoClassDefFoundError: com/android/tools/lint/detector/api/Detector$JavaPsiScanner
</code>```

but it works when I invoke it via gradle:

```<code>./gradlew lint

MainActivity.java:15: Error: Wrong argument count,
format string %s.%s requires 2 but format call supplies 1 [TimberArgCount]
        Timber.d("%s.%s", "onCreate");
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</code>```

Detailed description

I've made a small sample project on GitHub: TimberLintTest

Basically I did this:

created a simple Android project in Android Studio

added Timber

activated stdout output for lint errors

android {
    lintOptions {
        textReport true
        textOutput "stdout"
    }
}

In the MainActivity I use an erronous log-statement like this:

```<code>Timber.d("%s.%s", "onCreate");
</code>```

When I execute lint via the Gradle-wrapper from the command line it works as expected - stripped output:

```<code>MainActivity.java:15: Error: Wrong argument count,
format string %s.%s requires 2 but format call supplies 1 [TimberArgCount]
        Timber.d("%s.%s", "onCreate");
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</code>```

But the checks don't work in Android Studio and also not when I start lint directly.

Some sources in the internet indicate that we must copy the lint.jar file to ~/.android/lint. I did that for the lint.jar (from timber-4.5.0) and renamed it to timber-lint.jar, so that I end up with this file:

```<code>~/.android/lint/timber-lint.jar
</code>```

So the problem is that this JavaPsiScanner interface is not found.

I have checked the Timber source code and it depends on the lint-api-25.0.2 where the Detector contains this inner interface. But in my local SDK code (Android/Sdk/tools/lib/lint-api.jar) this inner class does not exist (I guess this is what the lint command line tool and Android Studio use).

So I think it's just a version mismatch. But I am not sure how to resolve this.

How can I even know for sure, which version of lint-api.jar my current android tools have?

When start the sdk manager and it shows that the Android SDK Tools version is 25.2.5 (I've updated to the most recent version). So is this the version of the lint-api.jar (or is it the SDK platform-tools, SDK build-tools, ..)?

答:
defaultPublishConfig/flavor should not be 'debug' when running lint.
For running lint on Debug variant use

gradlew lintDebug

Refer to Improve your code with lint checks

Body:
The Timber (V 4.5.0) lint checks only work via Gradle (but not via the lint command and also not in Android Studio Version 2.3 Beta2).

Summary

When I run lint directly on the command line I get an error.

lint --show TimberArgCount

Could not load custom rule jar file /home/tmtron/.android/lint/timber-lint.jar
java.lang.NoClassDefFoundError: com/android/tools/lint/detector/api/Detector$JavaPsiScanner

but it works when I invoke it via gradle:

./gradlew lint

MainActivity.java:15: Error: Wrong argument count,
format string %s.%s requires 2 but format call supplies 1 [TimberArgCount]
        Timber.d("%s.%s", "onCreate");
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Detailed description

I've made a small sample project on GitHub: TimberLintTest

Basically I did this:

created a simple Android project in Android Studio

added Timber

activated stdout output for lint errors

android {
    lintOptions {
        textReport true
        textOutput "stdout"
    }
}

In the MainActivity I use an erronous log-statement like this:

Timber.d("%s.%s", "onCreate");

When I execute lint via the Gradle-wrapper from the command line it works as expected - stripped output:

MainActivity.java:15: Error: Wrong argument count,
format string %s.%s requires 2 but format call supplies 1 [TimberArgCount]
        Timber.d("%s.%s", "onCreate");
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

But the checks don't work in Android Studio and also not when I start lint directly.

Some sources in the internet indicate that we must copy the lint.jar file to ~/.android/lint. I did that for the lint.jar (from timber-4.5.0) and renamed it to timber-lint.jar, so that I end up with this file:

~/.android/lint/timber-lint.jar

So the problem is that this JavaPsiScanner interface is not found.

I have checked the Timber source code and it depends on the lint-api-25.0.2 where the Detector contains this inner interface. But in my local SDK code (Android/Sdk/tools/lib/lint-api.jar) this inner class does not exist (I guess this is what the lint command line tool and Android Studio use).

So I think it's just a version mismatch. But I am not sure how to resolve this.

How can I even know for sure, which version of lint-api.jar my current android tools have?

When start the sdk manager and it shows that the Android SDK Tools version is 25.2.5 (I've updated to the most recent version). So is this the version of the lint-api.jar (or is it the SDK platform-tools, SDK build-tools, ..)?


问:
Unable to multiply two variables in Smarty on Prestashop
In my prestashop store, I have two variables per_sqft_price and per_box_price. per_sqft_price is having currency ($) sign before. I am trying to print the multiplied value of those 2 variables. But it is always printing 0.

```<code>{assign var = per_sqft_price value = $product.price}
{assign var = per_box_price value = $product.features[0].value}

<meta itemprop="per_sqft_price" content="{$per_sqft_price|replace:'$':''}"/>
{math equation = "x * y" x = $per_sqft_price  y = $per_box_price }
</code>```

Please help me how can i solve this. Thanks in advance

答:
Use $product.price_amount instead of $product.price, it gives numeric price output without currency sign. And be sure that $product.features[0].value is numeric as well, because it may be a string and may contain just a text. Also, you can use intval for your variables like:

```<code>{math equation = "x * y" x = $per_sqft_price|intval  y = $per_box_price|intval }
</code>```

Body:
In my prestashop store, I have two variables per_sqft_price and per_box_price. per_sqft_price is having currency ($) sign before. I am trying to print the multiplied value of those 2 variables. But it is always printing 0.

{assign var = per_sqft_price value = $product.price}
{assign var = per_box_price value = $product.features[0].value}

<meta itemprop="per_sqft_price" content="{$per_sqft_price|replace:'$':''}"/>
{math equation = "x * y" x = $per_sqft_price  y = $per_box_price }

Please help me how can i solve this. Thanks in advance

Body:
Use $product.price_amount instead of $product.price, it gives numeric price output without currency sign. And be sure that $product.features[0].value is numeric as well, because it may be a string and may contain just a text. Also, you can use intval for your variables like:

{math equation = "x * y" x = $per_sqft_price|intval  y = $per_box_price|intval }


问:
Send all bytes from richTextBox
I have a richTextBox and byte array.

```<code>byte[] message = Encoding.Default.GetBytes(richTextBox1.Text);

byte[] bytesToSend = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (MESSAGE SHOULD BE HERE), 0x00 };
</code>```

How can i do that?

答:
<pre class="lang-cs prettyprint-override"><code>    static byte[] SomeMethod(string value, Encoding encoding)
    {
        // create an array with the space needed for the value and the zeros
        var bytes = new byte[encoding.GetByteCount(value) + 9];
        // encode the data into the array starting at position 8
        encoding.GetBytes(value, 0, value.Length, bytes, 8);
        // and we're done
        return bytes;
    }
    var bytesToSend = SomeMethod(richTextBox1.Text, Encoding.Default);
    // (but probably not Encoding.Default - that is almost always wrong)
</code>```

Title: Send all bytes from richTextBox

Body:
I have a richTextBox and byte array.

byte[] message = Encoding.Default.GetBytes(richTextBox1.Text);

byte[] bytesToSend = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (MESSAGE SHOULD BE HERE), 0x00 };

How can i do that?


问:
docker build with pip install overwrites existing packages
This is my Dockerfile:

```<code>FROM docker_with_pre_installed_packages:1.0
ADD requirements.txt .
RUN pip install -r requirements.txt
ADD app app
WORKDIR /
</code>```

docker_with_pre_installed_packages has:

```<code>/usr/local/lib/python2.7/site-packages/my_packages/db
/usr/local/lib/python2.7/site-packages/my_packages/config
/usr/local/lib/python2.7/site-packages/my_packages/logging
</code>```

requirements.txt:

```<code>my_package.redis-db
my_package.common.utils
</code>```

after running

```<code>docker build -t test:1.0 .
docker run -it test:1.0 bash
cd /usr/local/lib/python2.7/site-packages/my_packages/
ls
__init__.py redis_db common
</code>```

pip freeze still shows the old packages
and I can still see the dist-info directory
but when trying to run python and import something from the pre installed packages I getting:

```<code>ImportError: No module named my_package.config
</code>```

Thanks!

答:
Did you try to install python in your docker_with_pre_installed_packages or just copied some files? Looks like python was not properly installed.
By the way, Python 2.7 is not supported since this year, highly recommend to use Python 3.
Try to use python docker image and install dependencies and compare.</p>

```<code>FROM python:3
ADD requirements.txt /
ADD app app
RUN pip install -r requirements.txt
CMD [ "python", "./my_script.py" ]
</code>```

Body:
This is my Dockerfile:

FROM docker_with_pre_installed_packages:1.0
ADD requirements.txt .
RUN pip install -r requirements.txt
ADD app app
WORKDIR /

docker_with_pre_installed_packages has:

/usr/local/lib/python2.7/site-packages/my_packages/db
/usr/local/lib/python2.7/site-packages/my_packages/config
/usr/local/lib/python2.7/site-packages/my_packages/logging

requirements.txt:

my_package.redis-db
my_package.common.utils

after running

docker build -t test:1.0 .
docker run -it test:1.0 bash
cd /usr/local/lib/python2.7/site-packages/my_packages/
ls
__init__.py redis_db common

pip freeze still shows the old packages
and I can still see the dist-info directory
but when trying to run python and import something from the pre installed packages I getting:

ImportError: No module named my_package.config

Thanks!

Body:
Did you try to install python in your docker_with_pre_installed_packages or just copied some files? Looks like python was not properly installed.
By the way, Python 2.7 is not supported since this year, highly recommend to use Python 3.
Try to use python docker image and install dependencies and compare.

FROM python:3
ADD requirements.txt /
ADD app app
RUN pip install -r requirements.txt
CMD [ "python", "./my_script.py" ]


问:
how to add tablet resolution support in Android Studio
Using ConstraintLayout I saw this problem: on phones, the resolution of my widgets is normal and takes up almost all of the
screen space:

But when I switch to the resolution of the tablets, all the widgets become small and cannot be viewed on the screen:

How to make the resolution of widgets look normal on all resolutions and devices?

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TableLayout
        android:id="@+id/table_l"
        android:layout_width="297dp"
        android:layout_height="329dp"
        android:layout_weight="1"
        android:layout_x="57dp"
        android:layout_y="202dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1" />

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1" />

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1">

        </TableRow>
    </TableLayout>

    <Button
        android:id="@+id/st"
        android:layout_width="178dp"
        android:layout_height="wrap_content"
        android:layout_x="120dp"
        android:layout_y="112dp"
        android:text="start"
        app:layout_constraintBottom_toTopOf="@+id/table_l"
        app:layout_constraintEnd_toEndOf="@+id/table_l"
        app:layout_constraintHorizontal_bias="0.495"
        app:layout_constraintStart_toStartOf="@+id/table_l"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_weight="1"
        app:layout_constraintVertical_bias="0.647" />

    <TextView
        android:id="@+id/X_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="48dp"
        android:layout_x="118dp"
        android:layout_y="608dp"
        android:text="x:"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/O_text"
        app:layout_constraintStart_toStartOf="@+id/O_text"
        app:layout_constraintTop_toBottomOf="@+id/O_text" />

    <TextView
        android:id="@+id/O_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="36dp"
        android:layout_x="116dp"
        android:layout_y="661dp"
        android:text="o:"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/table_l"
        app:layout_constraintHorizontal_bias="0.153"
        app:layout_constraintStart_toStartOf="@+id/table_l"
        app:layout_constraintTop_toBottomOf="@+id/table_l"
        app:layout_constraintVertical_bias="0.0" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="27dp"
        android:layout_height="47dp"
        android:layout_marginTop="36dp"
        android:textSize="36sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.139"
        app:layout_constraintStart_toEndOf="@+id/O_text"
        app:layout_constraintTop_toBottomOf="@+id/table_l"
        app:layout_constraintVertical_bias="0.0" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="25dp"
        android:layout_height="45dp"
        android:layout_marginBottom="52dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.151"
        app:layout_constraintStart_toEndOf="@+id/X_text"
        app:layout_constraintTop_toBottomOf="@+id/textView3"
        app:layout_constraintVertical_bias="0.571" />

</androidx.constraintlayout.widget.ConstraintLayout>```

答:
You should create layout xml files for different screen size. For example; If your app running in Tablet(7 inch), you must create new layout as a layout-sw600dp.

Look at this link for more details.


问:
How to match new-line character using regex
I'm trying to match the special characters and the breaks using a regex to cleanse the string so that I'm left with only the following string 'All release related activities' extracted from the following line:

```<code>{"Well":"\n\n\t\n\t\n\n\t\n\tAll release related activities\n\n\t"}
</code>```

I've tried the regex ^{.Well":" and I'm able to match till  the first colon appears. How do I match the \n characters in the string?

答:
I am not quite sure about the prefix of "well:" So I am basically providing you with a basic regex:

```<code>^\{[^}]*?(?:\\[ntr])+([^}]+)\}
</code>```

and replace by:

```<code>\1
</code>```

Example

Body:
I'm trying to match the special characters and the breaks using a regex to cleanse the string so that I'm left with only the following string 'All release related activities' extracted from the following line:

{"Well":"\n\n\t\n\t\n\n\t\n\tAll release related activities\n\n\t"}

I've tried the regex ^{.Well":" and I'm able to match till  the first colon appears. How do I match the \n characters in the string?

Body:
I am not quite sure about the prefix of "well:" So I am basically providing you with a basic regex:

^\{[^}]*?(?:\\[ntr])+([^}]+)\}

and replace by:

\1

Example


问:
How to make a portable program in C# Visual Studio 2015?
Portable means the program runs immediately and doesn't ask to be added in "Programs and Features" of Windows.

I only know in Visual Studio C# 2015 to press Build->Publish, and publish the program to a setup.exe file with a folder near, and when I run setup.exe it adds itself to Programs and Features...

The program is a Windows Forms Application program.

答: It should work too if you just give the .exe file from the release folder to the user.</p>


问:
Putting a list into a class c#
Is it possible to put a list into a class? So for example if I have a class of Person and their properties are Name, Age, Valuables can the Valuables property be a list that holds a Valuable class with properties like ItemName, Cost, Quantity?</p>

答:
```<code>public class Person
{
     public string Name {get;set;}
     public int Age {get;set;}
     public List<ValuablesDTO> Valuables {get;set;}

     public  class ValuablesDTO
     {
          public string ItemName {get;set;}
          public decimal Quantity {get;set;}
          public decimal Cost {get;set;}
      }
}
</code>```

Title: Putting a list into a class c#


问:
Heroku 403 Forbidden - Laravel 5
I have a Laravel 5.8 site

https://boss-security-2.herokuapp.com/

I deployed to Heorku to test with this script that I created

```<code>appName='boss-security-2'
echo 'appName =' $appName

# heroku apps
# heroku apps:destroy appName --confirm appName
# ----------------------

echo web: vendor/bin/heroku-php-apache2 public/ > Procfile
git init
git status
git add -A
git commit -m "Initial commit"

heroku create $appName
heroku git:remote -a $appName
heroku buildpacks:set heroku/php
heroku config:set APP_KEY=9O7AegDFJhVC16jLfNNepT7TEQ7FyFZc

git push heroku master

heroku apps:info
heroku open
echo "done"
#
</code>```

I kept getting

Forbidden

>

You don't have permission to access this resource

Anything wrong in my script ?

Composer.json

```<code>{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.1.3",
        "fideloper/proxy": "^4.0",
        "guzzlehttp/guzzle": "~6.0",
        "laravel/framework": "5.8.*",
        "laravel/tinker": "^1.0",
        "laravelcollective/html": "~5.0",
        "nesbot/carbon": "^2.19",
        "pusher/pusher-php-server": "^3.4"
    },
    "require-dev": {
        "beyondcode/laravel-dump-server": "^1.0",
        "filp/whoops": "^2.0",
        "fzaninotto/faker": "^1.4",
        "mockery/mockery": "^1.0",
        "nunomaduro/collision": "^2.0",
        "phpunit/phpunit": "^7.5"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ],
        "post-install-cmd": [
            "php artisan clear-compiled",
            "chmod -R 777 public/"
        ]
    },

}
</code>```

Update 1

I checked the log, I saw this

Cannot serve directory /app/: No matching DirectoryIndex (index.php,index.html,index.htm) found, and server-generated directory index forbidden by Options directive

Update 2

I have no idea why my composer.json in my dyno doesn't seem to have my latest code. I SSHed in and check.

heroku ps:exec

Is this has something to do with my composer.lock ?

答:
Probably You Pushed The Directories with wrong Permissions in your
  remote git repository

Goto Your local code

Update the Permissions

and push back the code

take a pull from the Heroku app

Title: Heroku 403 Forbidden - Laravel 5

Body:
I have a Laravel 5.8 site

https://boss-security-2.herokuapp.com/

I deployed to Heorku to test with this script that I created

appName='boss-security-2'
echo 'appName =' $appName

# heroku apps
# heroku apps:destroy appName --confirm appName
# ----------------------

echo web: vendor/bin/heroku-php-apache2 public/ > Procfile
git init
git status
git add -A
git commit -m "Initial commit"

heroku create $appName
heroku git:remote -a $appName
heroku buildpacks:set heroku/php
heroku config:set APP_KEY=9O7AegDFJhVC16jLfNNepT7TEQ7FyFZc

git push heroku master

heroku apps:info
heroku open
echo "done"
#

I kept getting

Forbidden

>

You don't have permission to access this resource

Anything wrong in my script ?

Composer.json

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.1.3",
        "fideloper/proxy": "^4.0",
        "guzzlehttp/guzzle": "~6.0",
        "laravel/framework": "5.8.*",
        "laravel/tinker": "^1.0",
        "laravelcollective/html": "~5.0",
        "nesbot/carbon": "^2.19",
        "pusher/pusher-php-server": "^3.4"
    },
    "require-dev": {
        "beyondcode/laravel-dump-server": "^1.0",
        "filp/whoops": "^2.0",
        "fzaninotto/faker": "^1.4",
        "mockery/mockery": "^1.0",
        "nunomaduro/collision": "^2.0",
        "phpunit/phpunit": "^7.5"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ],
        "post-install-cmd": [
            "php artisan clear-compiled",
            "chmod -R 777 public/"
        ]
    },

}

Update 1

I checked the log, I saw this

Cannot serve directory /app/: No matching DirectoryIndex (index.php,index.html,index.htm) found, and server-generated directory index forbidden by Options directive

Update 2

I have no idea why my composer.json in my dyno doesn't seem to have my latest code. I SSHed in and check.

heroku ps:exec

Is this has something to do with my composer.lock ?


问:
Class function inside a component while running ngFor gives Error (not a function)
I'm trying to show a list of topics where every list entry is a custom component.
I will describe my problem as a simple example of my code.

Using the current (02/2020) Version of Angular, MongoDB and Chrome

Topic class:

export class Topic {
    constructor(
        public title: string,
        public solutionID: number[] = [],
        private rating: number = 0,
        private votes: number = 0
    ) { }

    currentRating(): number {
        return this.rating / this.votes;
    }

    vote(stars: number) {
        this.votes++;
        this.rating += stars;
    }

    lastEditDate(): Date {
        console.log('test');
        return this.ts_worker[this.ts_worker.length - 1];
    }
}
```

<p><strong>main-view.component.html</strong> This is the "frame" where the list is shown</p>

<pre class="lang-html prettyprint-override"><code><div class="content-wrapper">
    <app-topic-view *ngFor="let tp of topics" [topic]="tp"></app-topic-view>
</div>
</code>```

main-view.component.ts This is where my topics come from (GET from Server)

import { Component, OnInit, Input } from '@angular/core';
import { TopicsService } from 'src/app/services/topics.service';
import { Topic } from 'src/app/classes/class_Topic';

@Component({
  selector: 'app-main-view',
  templateUrl: './main-view.component.html',
  styleUrls: ['./main-view.component.scss']
})

export class MainViewComponent implements OnInit {

  @Input() topics: Topic[];

  constructor(private topicService: TopicsService) { }

  ngOnInit() {
    this.topicService.getAllTopics().subscribe((topics: Topic[]) => {
      this.topics = topics;
    })
  }

}
```

<p><strong>topic-view.component.html</strong></p>

<pre class="lang-html prettyprint-override"><code><div class="topicElement">
    <!-- Some code hidden here -->
    <div class="back-group">
        <div class="solutionCount">Solutions: {{(topic.ts_worker[topic.ts_worker.length - 1])}}</div>
        <div class="solutionCount">Solutions: {{(topic.lastEditDate())}}</div>
    </div>
</div>
</code>```

The error is found in {{(topic.lastEditDate()}}.

The line above that works just fine. Only the function call doesn't work.

Error

Goal

What am I missing here

In the end I would like to use the functions of my class. I'm used to do this in other languages.
Is this possible in Angular?

EDIT: Typo fixed

答:
your "topics" are not class Topic when return of the http because when it's traspile to javaScript, you only has an object, you need create as

```<code> this.topicService.getAllTopics().subscribe((topics: Topic[]) => {
      this.topics=x.map(x=>new Topic(x.title,x.solutionID,x.rating,x.votes))
    })
</code>```

Others idea is that Topic was

```<code>export class Topic {
  public title;
  public solutionID;
  private rating;
  private votes;
  constructor({ title, solutionID, rating, votes }) {
    this.title = title;
    this.solutionID = solutionID;
    this.rating = rating;
    this.votes = votes;
  }
  ..your methods...
}
</code>```

And write

```<code>this.topicService.getAllTopics().subscribe((topics: Topic[]) => {
      this.topics=x.map(x=>new Topic(x))
    })
</code>```

And another idea are that in your app-topic-view you has

```<code>private _topic:Topic
@Input() set topic(value)
{
  this._topic=new Topic(value.title,value.solutionID,value.rating,value.votes)
  //or if you change the constructor
  // this._topic=new Topic(value);
}

get topic()
{
     return this._topic;
}
</code>```

Body:
I'm trying to show a list of topics where every list entry is a custom component.
I will describe my problem as a simple example of my code.

Using the current (02/2020) Version of Angular, MongoDB and Chrome

Topic class:

export class Topic {
    constructor(
        public title: string,
        public solutionID: number[] = [],
        private rating: number = 0,
        private votes: number = 0
    ) { }

    currentRating(): number {
        return this.rating / this.votes;
    }

    vote(stars: number) {
        this.votes++;
        this.rating += stars;
    }

    lastEditDate(): Date {
        console.log('test');
        return this.ts_worker[this.ts_worker.length - 1];
    }
}

main-view.component.html This is the "frame" where the list is shown

    <app-topic-view *ngFor="let tp of topics" [topic]="tp"></app-topic-view>

main-view.component.ts This is where my topics come from (GET from Server)

import { Component, OnInit, Input } from '@angular/core';
import { TopicsService } from 'src/app/services/topics.service';
import { Topic } from 'src/app/classes/class_Topic';

@Component({
  selector: 'app-main-view',
  templateUrl: './main-view.component.html',
  styleUrls: ['./main-view.component.scss']
})

export class MainViewComponent implements OnInit {

  @Input() topics: Topic[];

  constructor(private topicService: TopicsService) { }

  ngOnInit() {
    this.topicService.getAllTopics().subscribe((topics: Topic[]) => {
      this.topics = topics;
    })
  }

}

topic-view.component.html

Solutions: {{(topic.ts_worker[topic.ts_worker.length - 1])}}

Solutions: {{(topic.lastEditDate())}}

The error is found in {{(topic.lastEditDate()}}.

The line above that works just fine. Only the function call doesn't work.

Error

Goal

What am I missing here

In the end I would like to use the functions of my class. I'm used to do this in other languages.
Is this possible in Angular?

EDIT: Typo fixed

Body:
your "topics" are not class Topic when return of the http because when it's traspile to javaScript, you only has an object, you need create as

 this.topicService.getAllTopics().subscribe((topics: Topic[]) => {
      this.topics=x.map(x=>new Topic(x.title,x.solutionID,x.rating,x.votes))
    })

Others idea is that Topic was

export class Topic {
  public title;
  public solutionID;
  private rating;
  private votes;
  constructor({ title, solutionID, rating, votes }) {
    this.title = title;
    this.solutionID = solutionID;
    this.rating = rating;
    this.votes = votes;
  }
  ..your methods...
}

And write

this.topicService.getAllTopics().subscribe((topics: Topic[]) => {
      this.topics=x.map(x=>new Topic(x))
    })

And another idea are that in your app-topic-view you has

private _topic:Topic
@Input() set topic(value)
{
  this._topic=new Topic(value.title,value.solutionID,value.rating,value.votes)
  //or if you change the constructor
  // this._topic=new Topic(value);
}

get topic()
{
     return this._topic;
}


问:
DocuSign API - How to get callback response after user authentication?
I'm trying to implement the Implicit Grant REST API of DocuSign. I'm confused as to what needs to happen right after the user logs in. This is a stand-alone native Windows desktop application, not a web service or page.

I got as far as to open an embedded browser window, navigating to the correct URI for login, and the user is able to successfully login. I further have an HTTP server running in this application as well which is to receive the callback. In fact, the callback does work, I do get an incoming HTTP GET command. However, there is nothing usable in this callback response. No special headers, parameters, body, nothing.

Before I tried the Implicit Grant API, I first tried the JWT Grant method, before realizing it wasn't the right approach. But my point is, at least I had a code parameter in the callback command. But after shifting over to use the Implicit Grant method, this response is empty.

According to the documentation:

After consent has been granted, the Authentication Service verifies that the client application is valid and has access to the requested scope. If so, it redirects the access token to the provided callback URI in a hash fragment.

The response contains the following hash fragment parameters:

.......

It even shows an example response:

```<code>http://localhost/#access_token=eyJ0eXAi.....9LyiFrUqvdw&expires_in=28800&token_type=bearer&state=a39fh23hnf23
</code>```

But, as mentioned, the callback response I receive has nothing of notable value. It's essentially just empty.

What am I missing here? What's the correct approach to complete the authentication process and proceed to actually using the API?

NOTE: I'm using Delphi, so none of the examples provided by DocuSign are compatible.

答:
Updated answer
Use Implict Grant when you do not have a backend server as part of the authentication flow. Implicit Grant is for anytime the client id's secret / RSA private key can't be protected--anytime there isn't a secure server in the application's architecture. This includes mobile apps (since the app can be reverse engineered, single page apps (React, Angular, etc) and desktop/thick client apps (eg Delphi apps).

I use Implicit Grant for my DocuSign applications I write in React.

In your case, you're writing a "thick client app" that runs entirely on the desktop.

Since DocuSign's OAuth2 Implicit Grant flow matches the standard, a good place to start is the framework's examples for authenticating with other OAuth2 identity providers.

For Delphi, see their example for Accessing Facebook API. While not exactly the same as DocuSign's Implicit Grant flow, it is close enough. In particular, note how Facebook also returns the access token in the URL fragment when response_type=token is requested (as is done in the Delphi example).

Quote from Facebook authentication docs:

response_type = token. Response data is included as a URL fragment and contains an access token. Desktop apps must use this setting for response_type. This is most useful when the client will be handling the token.

[Emphasis added]

Bottom line: use/modify the Delphi example of authenticating with Facebook since DocuSign is similar. If you can't get it to work, ask Delphi customer service for help, referencing the Facebook authentication example.

PS Once you've solved the problem, please provide your own answer that includes the code you use--to help others in the future. Thanks!

Body:
I'm trying to implement the Implicit Grant REST API of DocuSign. I'm confused as to what needs to happen right after the user logs in. This is a stand-alone native Windows desktop application, not a web service or page.

I got as far as to open an embedded browser window, navigating to the correct URI for login, and the user is able to successfully login. I further have an HTTP server running in this application as well which is to receive the callback. In fact, the callback does work, I do get an incoming HTTP GET command. However, there is nothing usable in this callback response. No special headers, parameters, body, nothing.

Before I tried the Implicit Grant API, I first tried the JWT Grant method, before realizing it wasn't the right approach. But my point is, at least I had a code parameter in the callback command. But after shifting over to use the Implicit Grant method, this response is empty.

According to the documentation:

After consent has been granted, the Authentication Service verifies that the client application is valid and has access to the requested scope. If so, it redirects the access token to the provided callback URI in a hash fragment.

The response contains the following hash fragment parameters:

.......

It even shows an example response:

http://localhost/#access_token=eyJ0eXAi.....9LyiFrUqvdw&expires_in=28800&token_type=bearer&state=a39fh23hnf23

But, as mentioned, the callback response I receive has nothing of notable value. It's essentially just empty.

What am I missing here? What's the correct approach to complete the authentication process and proceed to actually using the API?

NOTE: I'm using Delphi, so none of the examples provided by DocuSign are compatible.


问:
How to eliminate (or suppress from console) Interactive Brokers error when downloading data with Python API
I wrote the code below to read information from my accounts at Interactive Brokers:

```<code># Interactive Brokers functions to import data

def read_positions(): #read all accounts positions and return DataFrame with information

    from ibapi.client import EClient
    from ibapi.wrapper import EWrapper
    from ibapi.common import TickerId
    import pandas as pd

    class ib_class(EWrapper, EClient):
        def __init__(self):
            EClient.__init__(self, self)
            self.all_positions = pd.DataFrame([], columns = ['Account','Symbol', 'Quantity', 'Average Cost'])

        def position(self, account, contract, pos, avgCost):
            index = str(account)+str(contract.symbol)
            self.all_positions.loc[index]=account,contract.symbol,pos,avgCost

        def error(self, reqId:TickerId, errorCode:int, errorString:str):
            if reqId > -1:
                print("Error. Id: " , reqId, " Code: " , errorCode , " Msg: " , errorString)

        def positionEnd(self):
            super().positionEnd()
            self.disconnect()

    ib_api = ib_class()
    ib_api.connect("127.0.0.1", 7496, 0)
    ib_api.reqPositions()
    current_positions = ib_api.all_positions
    ib_api.run()

    return(current_positions)

def read_navs(): #read all accounts NAVs

    from ibapi.client import EClient
    from ibapi.wrapper import EWrapper
    from ibapi.common import TickerId
    import pandas as pd

    class ib_class(EWrapper, EClient):
        def __init__(self):
            EClient.__init__(self, self)
            self.all_accounts = pd.DataFrame([], columns = ['reqId','Account', 'Tag', 'Value' , 'Currency'])

        def accountSummary(self, reqId, account, tag, value, currency):
            if tag == 'NetLiquidationByCurrency':
                index = str(account)
                self.all_accounts.loc[index]=reqId, account, tag, value, currency

        def error(self, reqId:TickerId, errorCode:int, errorString:str):
            if reqId > -1:
                print("Error. Id: " , reqId, " Code: " , errorCode , " Msg: " , errorString)

        def accountSummaryEnd(self, reqId:int):
                super().accountSummaryEnd(reqId)
                self.disconnect()

    ib_api = ib_class()
    ib_api.connect("127.0.0.1", 7496, 0)
    ib_api.reqAccountSummary(9001,"All","$LEDGER")
    current_nav = ib_api.all_accounts
    ib_api.run()

    return(current_nav)
</code>```

If I call the two functions read_positions() or read_navs() I get the results I want, on DataFrame variables. However, I get an error message (on the console) that reads:

"OSError: [WinError 10038] An operation was attempted on something
  that is not a socket".

Before the error message itself, I get a lot of error-related messages:

unhandled exception in EReader thread Traceback (most recent call
  last):   File
  "C:\Users\xxxxx\Anaconda3\lib\site-packages\ibapi-9.76.1-py3.7.egg\ibapi\reader.py",
  line 34, in run
      data = self.conn.recvMsg()   File "C:\Users\xxxxx\Anaconda3\lib\site-packages\ibapi-9.76.1-py3.7.egg\ibapi\connection.py",
  line 99, in recvMsg
      buf = self._recvAllMsg()   File "C:\Users\xxxxx\Anaconda3\lib\site-packages\ibapi-9.76.1-py3.7.egg\ibapi\connection.py",
  line 119, in _recvAllMsg
      buf = self.socket.recv(4096)

The helpdesk from IB refuses to answer my question: how do I either avoid this error message or suppress it? I don't know if it is something I'm doing wrong or if this is a bug on their API. As long as I can avoid this junk printed on my console, I will be OK. Any guidance is much appreciated.

答:
So instead of downgrading, I found a quick fix to suppressing the error message. Go to the script where its messing up at, it should be connection.py and at line 119 at the very bottom. This is what I did to catch the error and it worked.</p>

```<code>while cont and self.socket is not None:
            try:
                buf = self.socket.recv(4096)
                allbuf += buf
                logger.debug("len %d raw:%s|", len(buf), buf)

                if len(buf) < 4096:
                    cont = False
            except OSError:
                pass
</code>```

Body:
I wrote the code below to read information from my accounts at Interactive Brokers:

# Interactive Brokers functions to import data

def read_positions(): #read all accounts positions and return DataFrame with information

    from ibapi.client import EClient
    from ibapi.wrapper import EWrapper
    from ibapi.common import TickerId
    import pandas as pd

    class ib_class(EWrapper, EClient):
        def __init__(self):
            EClient.__init__(self, self)
            self.all_positions = pd.DataFrame([], columns = ['Account','Symbol', 'Quantity', 'Average Cost'])

        def position(self, account, contract, pos, avgCost):
            index = str(account)+str(contract.symbol)
            self.all_positions.loc[index]=account,contract.symbol,pos,avgCost

        def error(self, reqId:TickerId, errorCode:int, errorString:str):
            if reqId > -1:
                print("Error. Id: " , reqId, " Code: " , errorCode , " Msg: " , errorString)

        def positionEnd(self):
            super().positionEnd()
            self.disconnect()

    ib_api = ib_class()
    ib_api.connect("127.0.0.1", 7496, 0)
    ib_api.reqPositions()
    current_positions = ib_api.all_positions
    ib_api.run()

    return(current_positions)

def read_navs(): #read all accounts NAVs

    from ibapi.client import EClient
    from ibapi.wrapper import EWrapper
    from ibapi.common import TickerId
    import pandas as pd

    class ib_class(EWrapper, EClient):
        def __init__(self):
            EClient.__init__(self, self)
            self.all_accounts = pd.DataFrame([], columns = ['reqId','Account', 'Tag', 'Value' , 'Currency'])

        def accountSummary(self, reqId, account, tag, value, currency):
            if tag == 'NetLiquidationByCurrency':
                index = str(account)
                self.all_accounts.loc[index]=reqId, account, tag, value, currency

        def error(self, reqId:TickerId, errorCode:int, errorString:str):
            if reqId > -1:
                print("Error. Id: " , reqId, " Code: " , errorCode , " Msg: " , errorString)

        def accountSummaryEnd(self, reqId:int):
                super().accountSummaryEnd(reqId)
                self.disconnect()

    ib_api = ib_class()
    ib_api.connect("127.0.0.1", 7496, 0)
    ib_api.reqAccountSummary(9001,"All","$LEDGER")
    current_nav = ib_api.all_accounts
    ib_api.run()

    return(current_nav)

If I call the two functions read_positions() or read_navs() I get the results I want, on DataFrame variables. However, I get an error message (on the console) that reads:

"OSError: [WinError 10038] An operation was attempted on something
  that is not a socket".

Before the error message itself, I get a lot of error-related messages:

unhandled exception in EReader thread Traceback (most recent call
  last):   File
  "C:\Users\xxxxx\Anaconda3\lib\site-packages\ibapi-9.76.1-py3.7.egg\ibapi\reader.py",
  line 34, in run
      data = self.conn.recvMsg()   File "C:\Users\xxxxx\Anaconda3\lib\site-packages\ibapi-9.76.1-py3.7.egg\ibapi\connection.py",
  line 99, in recvMsg
      buf = self._recvAllMsg()   File "C:\Users\xxxxx\Anaconda3\lib\site-packages\ibapi-9.76.1-py3.7.egg\ibapi\connection.py",
  line 119, in _recvAllMsg
      buf = self.socket.recv(4096)

The helpdesk from IB refuses to answer my question: how do I either avoid this error message or suppress it? I don't know if it is something I'm doing wrong or if this is a bug on their API. As long as I can avoid this junk printed on my console, I will be OK. Any guidance is much appreciated.

Body:
So instead of downgrading, I found a quick fix to suppressing the error message. Go to the script where its messing up at, it should be connection.py and at line 119 at the very bottom. This is what I did to catch the error and it worked.

while cont and self.socket is not None:
            try:
                buf = self.socket.recv(4096)
                allbuf += buf
                logger.debug("len %d raw:%s|", len(buf), buf)

                if len(buf) < 4096:
                    cont = False
            except OSError:
                pass


问:
How to disable an eventListener in RCP?
I've an EventListener dedicated to listen to the focusLost() event of a Text in my view  in Eclipse RCP. The Listener's working fine. But at some point of the execution I want to disable this Listener from Listening to the Text and Later I wish it to be activated.
How can it be deactivated or activated as per our needs programatically ?</p>

答:
You can use the removeListener() method of SWT Widget. You will need a reference to the Listener to do this.

This reference can be obtained using the getListeners(int eventType) method.

The event types are defined as constants in the SWT class. It could look like this, I'm not sure about the actual event type though

```<code>Listener[] focusOutListeners = myWidget.getListeners(SWT.FocusOut);

for(int i = 0 ; i< focusOutListeners; i++){
    myWidget.removeListener(SWT.FocusOut, focusOutListeners[i]);
}

// ... do stuff the listeners will not know about ...//

for(int i = 0 ; i< focusOutListeners; i++){
    myWidget.addListener(SWT.FocusOut, focusOutListeners[i]);
}
</code>```

AFAIK there is no other means in SWT to disable a Listener, but as your Listener just implements the according interface, you can implement custom disable/enable methods. Then your code could look like this:
Listener[] focusOutListeners = myWidget.getListeners(SWT.FocusOut);

```<code>for(int i = 0 ; i< focusOutListeners; i++){
    CustomListener listener = (CustomListener)focusOutListeners[i]);
    listener.disable();
}

// ... do stuff the listeners will not know about ...//

for(int i = 0 ; i< focusOutListeners; i++){
    CustomListener listener = (CustomListener)focusOutListeners[i]);
    listener.enable();
}
</code>```

The action under the hood is described nicely in Paul Webster's answer.

Title: How to disable an eventListener in RCP?

Body:
You can use the removeListener() method of SWT Widget. You will need a reference to the Listener to do this.

This reference can be obtained using the getListeners(int eventType) method.

The event types are defined as constants in the SWT class. It could look like this, I'm not sure about the actual event type though

Listener[] focusOutListeners = myWidget.getListeners(SWT.FocusOut);

for(int i = 0 ; i< focusOutListeners; i++){
    myWidget.removeListener(SWT.FocusOut, focusOutListeners[i]);
}

// ... do stuff the listeners will not know about ...//

for(int i = 0 ; i< focusOutListeners; i++){
    myWidget.addListener(SWT.FocusOut, focusOutListeners[i]);
}

AFAIK there is no other means in SWT to disable a Listener, but as your Listener just implements the according interface, you can implement custom disable/enable methods. Then your code could look like this:
Listener[] focusOutListeners = myWidget.getListeners(SWT.FocusOut);

for(int i = 0 ; i< focusOutListeners; i++){
    CustomListener listener = (CustomListener)focusOutListeners[i]);
    listener.disable();
}

// ... do stuff the listeners will not know about ...//

for(int i = 0 ; i< focusOutListeners; i++){
    CustomListener listener = (CustomListener)focusOutListeners[i]);
    listener.enable();
}

The action under the hood is described nicely in Paul Webster's answer.


问:
Merge the json objects with same key value pair in a file using python
I have a file with objects in it like below.

Eg: Input.txt

```<code>1. {"Cp": "1000", "Af": "CBS", "Bp": "150", "Vt": "channel", "Ti": "Q2", "Cs": "K11HE-D", "Tg": "BROADCAST<>LOCAL<>HD", "Fd": "dish#K11HE-D", "Pi": "CHAF2", "Gi": "RV1688668060"}

2. {"Cp": "1000", "Af": "CBS", "Bp": "150", "Vt": "channel", "Ti": "Q2", "Cs": "K08JV-D", "Tg": "BROADCAST<>LOCAL<>HD", "Fd": "dish#K08JV-D", "Pi": "CHAF2", "Gi": "RV1714277379"}

3. {"Cp": "1000", "Af": "CBS", "Bp": "150", "Vt": "channel", "Ti": "ABCD", "Cs": "K20LT-D", "Tg": "BROADCAST<>LOCAL<>HD", "Fd": "dish#K20LT-D", "Pi": "CHAF2", "Gi": "RV1714278093"}

4. {"Cp": "1000", "Af": "CBS", "Bp": "150", "Vt": "channel", "Ti": "Q2", "Cs": "K08OW-D", "Tg": "BROADCAST<>LOCAL<>HD", "Fd": "dish#K08OW-D", "Pi": "CHAF2", "Gi": "RV1714277380"}
</code>```

The file contains thousands of rows.

I want to group all those json objects in the file, which has the same value for the key " Ti ".

Below is an example to elaborate more on my requirement.

You can see from the sample file above, there are 3 lines with the same value of for key "Ti". That is line 1, 2 and 4. They have all the value for "Ti" as "Q2".

I need a way to join those JSON objects, and I want to create an output file, that looks like below.

Eg: Output.txt

```<code>1. {"Cp": "[1000, 1000, 1000]", "Af": "['CBS', 'CBS', 'CBS']", "Bp": "[150, 150, 150]", "Vt": "['channel', 'channel', 'channel']", "Ti": "['Q2', 'Q2', 'Q2']", "Cs": "['K11HE-D', 'K08JV-D', 'K08OW-D' ]", "Tg": "['BROADCAST<>LOCAL<>HD', 'BROADCAST<>LOCAL<>HD, 'BROADCAST<>LOCAL<>HD]", "Fd": "['dish#K11HE-D', 'dish#K08JV-D', 'dish#K08OW-D']", "Pi": "['CHAF2','CHAF2','CHAF2']", "Gi": "['RV1688668060', 'RV1714277379', 'RV1714277380']"}

2. {"Cp": "[1000, 1000, 1000]", "Af": "['CBS', 'CBS', 'CBS']", "Bp": "[150, 150, 150]", "Vt": "['channel', 'channel', 'channel']", "Ti": "['Q2', 'Q2', 'Q2']", "Cs": "['K11HE-D', 'K08JV-D', 'K08OW-D' ]", "Tg": "['BROADCAST<>LOCAL<>HD', 'BROADCAST<>LOCAL<>HD, 'BROADCAST<>LOCAL<>HD]", "Fd": "['dish#K11HE-D', 'dish#K08JV-D', 'dish#K08OW-D']", "Pi": "['CHAF2','CHAF2','CHAF2']", "Gi": "['RV1688668060', 'RV1714277379', 'RV1714277380']"}

3. {"Cp": "1000", "Af": "CBS", "Bp": "150", "Vt": "channel", "Ti": "ABCD", "Cs": "K20LT-D", "Tg": "BROADCAST<>LOCAL<>HD", "Fd": "dish#K20LT-D", "Pi": "CHAF2", "Gi": "RV1714278093"}

4. {"Cp": "[1000, 1000, 1000]", "Af": "['CBS', 'CBS', 'CBS']", "Bp": "[150, 150, 150]", "Vt": "['channel', 'channel', 'channel']", "Ti": "['Q2', 'Q2', 'Q2']", "Cs": "['K11HE-D', 'K08JV-D', 'K08OW-D' ]", "Tg": "['BROADCAST<>LOCAL<>HD', 'BROADCAST<>LOCAL<>HD, 'BROADCAST<>LOCAL<>HD]", "Fd": "['dish#K11HE-D', 'dish#K08JV-D', 'dish#K08OW-D']", "Pi": "['CHAF2','CHAF2','CHAF2']", "Gi": "['RV1688668060', 'RV1714277379', 'RV1714277380']"}
</code>```

Please let me know, how can I achieve this.

答:
You need to:

convert string into dictionary

collect Ti values

loop over dictionary elements and collect data based on Ti

```<code>import re

raw_data = open('test.txt', 'r')

data_list = raw_data.read().splitlines()
data_list = list(filter(None, data_list))

# create list of Ti values
ti_list = []
for item in data_list:
    number = re.search('\d+\.', item).group(0)
    row = re.sub('\d+\. ', '', item)
    row_dictionary = eval(row)
    ti_list.append(row_dictionary.get('Ti'))

# collect data into new dictionary
data = {}
i = 1
for ti in ti_list:
    raw = {}
    for item in data_list:
        number = re.search('\d+\.', item).group(0)
        row = re.sub('\d+\. ', '', item)
        row_dictionary = eval(row)

        if row_dictionary.get('Ti') == ti:
            for key, value in row_dictionary.items():
                raw.setdefault(key, []).append(value)

    data[str(i)+'.'] = raw
    i += 1
</code>```

Output:

```<code>1. {'Cp': ['1000', '1000', '1000'], 'Af': ['CBS', 'CBS', 'CBS'], 'Bp': ['150', '150', '150'], 'Vt': ['channel', 'channel', 'channel'], 'Ti': ['Q2', 'Q2', 'Q2'], 'Cs': ['K11HE-D', 'K08JV-D', 'K08OW-D'], 'Tg': ['BROADCAST<>LOCAL<>HD', 'BROADCAST<>LOCAL<>HD', 'BROADCAST<>LOCAL<>HD'], 'Fd': ['dish#K11HE-D', 'dish#K08JV-D', 'dish#K08OW-D'], 'Pi': ['CHAF2', 'CHAF2', 'CHAF2'], 'Gi': ['RV1688668060', 'RV1714277379', 'RV1714277380']}
2. {'Cp': ['1000', '1000', '1000'], 'Af': ['CBS', 'CBS', 'CBS'], 'Bp': ['150', '150', '150'], 'Vt': ['channel', 'channel', 'channel'], 'Ti': ['Q2', 'Q2', 'Q2'], 'Cs': ['K11HE-D', 'K08JV-D', 'K08OW-D'], 'Tg': ['BROADCAST<>LOCAL<>HD', 'BROADCAST<>LOCAL<>HD', 'BROADCAST<>LOCAL<>HD'], 'Fd': ['dish#K11HE-D', 'dish#K08JV-D', 'dish#K08OW-D'], 'Pi': ['CHAF2', 'CHAF2', 'CHAF2'], 'Gi': ['RV1688668060', 'RV1714277379', 'RV1714277380']}
3. {'Cp': ['1000'], 'Af': ['CBS'], 'Bp': ['150'], 'Vt': ['channel'], 'Ti': ['ABCD'], 'Cs': ['K20LT-D'], 'Tg': ['BROADCAST<>LOCAL<>HD'], 'Fd': ['dish#K20LT-D'], 'Pi': ['CHAF2'], 'Gi': ['RV1714278093']}
4. {'Cp': ['1000', '1000', '1000'], 'Af': ['CBS', 'CBS', 'CBS'], 'Bp': ['150', '150', '150'], 'Vt': ['channel', 'channel', 'channel'], 'Ti': ['Q2', 'Q2', 'Q2'], 'Cs': ['K11HE-D', 'K08JV-D', 'K08OW-D'], 'Tg': ['BROADCAST<>LOCAL<>HD', 'BROADCAST<>LOCAL<>HD', 'BROADCAST<>LOCAL<>HD'], 'Fd': ['dish#K11HE-D', 'dish#K08JV-D', 'dish#K08OW-D'], 'Pi': ['CHAF2', 'CHAF2', 'CHAF2'], 'Gi': ['RV1688668060', 'RV1714277379', 'RV1714277380']}
</code>```

Body:
I have a file with objects in it like below.

Eg: Input.txt

1. {"Cp": "1000", "Af": "CBS", "Bp": "150", "Vt": "channel", "Ti": "Q2", "Cs": "K11HE-D", "Tg": "BROADCAST<>LOCAL<>HD", "Fd": "dish#K11HE-D", "Pi": "CHAF2", "Gi": "RV1688668060"}

2. {"Cp": "1000", "Af": "CBS", "Bp": "150", "Vt": "channel", "Ti": "Q2", "Cs": "K08JV-D", "Tg": "BROADCAST<>LOCAL<>HD", "Fd": "dish#K08JV-D", "Pi": "CHAF2", "Gi": "RV1714277379"}

3. {"Cp": "1000", "Af": "CBS", "Bp": "150", "Vt": "channel", "Ti": "ABCD", "Cs": "K20LT-D", "Tg": "BROADCAST<>LOCAL<>HD", "Fd": "dish#K20LT-D", "Pi": "CHAF2", "Gi": "RV1714278093"}

4. {"Cp": "1000", "Af": "CBS", "Bp": "150", "Vt": "channel", "Ti": "Q2", "Cs": "K08OW-D", "Tg": "BROADCAST<>LOCAL<>HD", "Fd": "dish#K08OW-D", "Pi": "CHAF2", "Gi": "RV1714277380"}

The file contains thousands of rows.

I want to group all those json objects in the file, which has the same value for the key " Ti ".

Below is an example to elaborate more on my requirement.

You can see from the sample file above, there are 3 lines with the same value of for key "Ti". That is line 1, 2 and 4. They have all the value for "Ti" as "Q2".

I need a way to join those JSON objects, and I want to create an output file, that looks like below.

Eg: Output.txt

1. {"Cp": "[1000, 1000, 1000]", "Af": "['CBS', 'CBS', 'CBS']", "Bp": "[150, 150, 150]", "Vt": "['channel', 'channel', 'channel']", "Ti": "['Q2', 'Q2', 'Q2']", "Cs": "['K11HE-D', 'K08JV-D', 'K08OW-D' ]", "Tg": "['BROADCAST<>LOCAL<>HD', 'BROADCAST<>LOCAL<>HD, 'BROADCAST<>LOCAL<>HD]", "Fd": "['dish#K11HE-D', 'dish#K08JV-D', 'dish#K08OW-D']", "Pi": "['CHAF2','CHAF2','CHAF2']", "Gi": "['RV1688668060', 'RV1714277379', 'RV1714277380']"}

2. {"Cp": "[1000, 1000, 1000]", "Af": "['CBS', 'CBS', 'CBS']", "Bp": "[150, 150, 150]", "Vt": "['channel', 'channel', 'channel']", "Ti": "['Q2', 'Q2', 'Q2']", "Cs": "['K11HE-D', 'K08JV-D', 'K08OW-D' ]", "Tg": "['BROADCAST<>LOCAL<>HD', 'BROADCAST<>LOCAL<>HD, 'BROADCAST<>LOCAL<>HD]", "Fd": "['dish#K11HE-D', 'dish#K08JV-D', 'dish#K08OW-D']", "Pi": "['CHAF2','CHAF2','CHAF2']", "Gi": "['RV1688668060', 'RV1714277379', 'RV1714277380']"}

3. {"Cp": "1000", "Af": "CBS", "Bp": "150", "Vt": "channel", "Ti": "ABCD", "Cs": "K20LT-D", "Tg": "BROADCAST<>LOCAL<>HD", "Fd": "dish#K20LT-D", "Pi": "CHAF2", "Gi": "RV1714278093"}

4. {"Cp": "[1000, 1000, 1000]", "Af": "['CBS', 'CBS', 'CBS']", "Bp": "[150, 150, 150]", "Vt": "['channel', 'channel', 'channel']", "Ti": "['Q2', 'Q2', 'Q2']", "Cs": "['K11HE-D', 'K08JV-D', 'K08OW-D' ]", "Tg": "['BROADCAST<>LOCAL<>HD', 'BROADCAST<>LOCAL<>HD, 'BROADCAST<>LOCAL<>HD]", "Fd": "['dish#K11HE-D', 'dish#K08JV-D', 'dish#K08OW-D']", "Pi": "['CHAF2','CHAF2','CHAF2']", "Gi": "['RV1688668060', 'RV1714277379', 'RV1714277380']"}

Please let me know, how can I achieve this.

Body:
You need to:

convert string into dictionary

collect Ti values

loop over dictionary elements and collect data based on Ti

import re

raw_data = open('test.txt', 'r')

data_list = raw_data.read().splitlines()
data_list = list(filter(None, data_list))

# create list of Ti values
ti_list = []
for item in data_list:
    number = re.search('\d+\.', item).group(0)
    row = re.sub('\d+\. ', '', item)
    row_dictionary = eval(row)
    ti_list.append(row_dictionary.get('Ti'))

# collect data into new dictionary
data = {}
i = 1
for ti in ti_list:
    raw = {}
    for item in data_list:
        number = re.search('\d+\.', item).group(0)
        row = re.sub('\d+\. ', '', item)
        row_dictionary = eval(row)

        if row_dictionary.get('Ti') == ti:
            for key, value in row_dictionary.items():
                raw.setdefault(key, []).append(value)

    data[str(i)+'.'] = raw
    i += 1

Output:

1. {'Cp': ['1000', '1000', '1000'], 'Af': ['CBS', 'CBS', 'CBS'], 'Bp': ['150', '150', '150'], 'Vt': ['channel', 'channel', 'channel'], 'Ti': ['Q2', 'Q2', 'Q2'], 'Cs': ['K11HE-D', 'K08JV-D', 'K08OW-D'], 'Tg': ['BROADCAST<>LOCAL<>HD', 'BROADCAST<>LOCAL<>HD', 'BROADCAST<>LOCAL<>HD'], 'Fd': ['dish#K11HE-D', 'dish#K08JV-D', 'dish#K08OW-D'], 'Pi': ['CHAF2', 'CHAF2', 'CHAF2'], 'Gi': ['RV1688668060', 'RV1714277379', 'RV1714277380']}
2. {'Cp': ['1000', '1000', '1000'], 'Af': ['CBS', 'CBS', 'CBS'], 'Bp': ['150', '150', '150'], 'Vt': ['channel', 'channel', 'channel'], 'Ti': ['Q2', 'Q2', 'Q2'], 'Cs': ['K11HE-D', 'K08JV-D', 'K08OW-D'], 'Tg': ['BROADCAST<>LOCAL<>HD', 'BROADCAST<>LOCAL<>HD', 'BROADCAST<>LOCAL<>HD'], 'Fd': ['dish#K11HE-D', 'dish#K08JV-D', 'dish#K08OW-D'], 'Pi': ['CHAF2', 'CHAF2', 'CHAF2'], 'Gi': ['RV1688668060', 'RV1714277379', 'RV1714277380']}
3. {'Cp': ['1000'], 'Af': ['CBS'], 'Bp': ['150'], 'Vt': ['channel'], 'Ti': ['ABCD'], 'Cs': ['K20LT-D'], 'Tg': ['BROADCAST<>LOCAL<>HD'], 'Fd': ['dish#K20LT-D'], 'Pi': ['CHAF2'], 'Gi': ['RV1714278093']}
4. {'Cp': ['1000', '1000', '1000'], 'Af': ['CBS', 'CBS', 'CBS'], 'Bp': ['150', '150', '150'], 'Vt': ['channel', 'channel', 'channel'], 'Ti': ['Q2', 'Q2', 'Q2'], 'Cs': ['K11HE-D', 'K08JV-D', 'K08OW-D'], 'Tg': ['BROADCAST<>LOCAL<>HD', 'BROADCAST<>LOCAL<>HD', 'BROADCAST<>LOCAL<>HD'], 'Fd': ['dish#K11HE-D', 'dish#K08JV-D', 'dish#K08OW-D'], 'Pi': ['CHAF2', 'CHAF2', 'CHAF2'], 'Gi': ['RV1688668060', 'RV1714277379', 'RV1714277380']}