问:
Refactoring PL/SQL: many cursors with same rowtype (in theory)
I am writing some PL/SQL and found myself falling into a repeptitive pattern:

```<code>cursor c_curs1 is
   select a, b, c
   from (...) big_subquery_1
   where big_subquery_1.a_ind = 'Y'

cursor c_curs2 is
   select a, b, c
   from (...) big_subquery_2
   where big_subquery_2.b_ind = 'R'

cursor c_curs3 is
   select a, b, c
   from (...) big_subquery_3
   where big_subquery_3.c_ind = 'M'

...
type t_curs1_tab is table of c_curs1;
type t_curs2_tab is table of c_curs2;
type t_curs3_tab is table of c_curs3;
...
v_curs1_results t_curs1_tab := t_curs1_tab();
v_curs2_results t_curs2_tab := t_curs2_tab();
v_curs3_results t_curs3_tab := t_curs3_tab();
</code>```

Then when processing the results, I have code like this:

```<code>    open c_curs1;
    fetch c_curs1 bulk collect into v_curs1_results;
    close c_curs1;

    if v_curs1_results.first is not null and v_curs1_results.last is not null then
       for i in v_curs1_results.first .. v_curs1_results.last loop
           /*Do something with field a in the results
             Do something with field b in the results
             Do something with field c in the results*/
           ....
       end loop;
    end if;
</code>```

The code in the processing loop is the same for all cursors, as all 3 cursors return a,b,c - the only difference being which cursor is referenced. I wanted to refactor this into some sort of generic result-set processor, but I'm stuck here:

```<code>procedure sp_process_collection(in_collection t_curs1_tab) is ...
</code>```

I can only call this with v_curs1_results, I can't call it with v_curs2_results or I get a PLS-00306 wrong number of types or arguments... compiler error. Is there any way to do this generically so I only have to write one collection processing procedure? I have this pattern of cursor (returning the same three columns, always the same types) appears in several other parts of the same package, and the processing loop, while semantically the same is sometimes written with slightly different code. I'd very much like to centralize the processing in one procedure, I just can'd figure out how to do it in PL/SQL. I know PL/SQL doesn't have generics (Which I think would have made a Java/C# solution fairly trivial), but I'm wondering if there's another way to approach this problem that I just haven't thought of.

(using Oracle 10g)

答:
Can you do this with a REF CURSOR?

Something like:

```<code>CREATE PROCEDURE sp_process_cursor(in_cursor SYS_REFCURSOR)

/* you don't need to open the cursor, it's already open */
FETCH in_cursor BULK COLLECT INTO v_cursor_results;
IF v_cursor_results.first is not null and v_cursor_results.last IS NOT NULL THEN
  FOR i in v_cursor_results.FIRST .. v_cursor_results.LAST LOOP
  ...
  END LOOP;
END IF;
</code>```

Your calling code would need to invoke this procedure once per cursor:

```<code>OPEN c_curs1;
sp_process_cursor(c_curs1);
CLOSE c_curs1;

OPEN c_curs2;
sp_process_cursor(c_curs2);
...
</code>```

Body:
I am writing some PL/SQL and found myself falling into a repeptitive pattern:

cursor c_curs1 is
   select a, b, c
   from (...) big_subquery_1
   where big_subquery_1.a_ind = 'Y'

cursor c_curs2 is
   select a, b, c
   from (...) big_subquery_2
   where big_subquery_2.b_ind = 'R'

cursor c_curs3 is
   select a, b, c
   from (...) big_subquery_3
   where big_subquery_3.c_ind = 'M'

...
type t_curs1_tab is table of c_curs1;
type t_curs2_tab is table of c_curs2;
type t_curs3_tab is table of c_curs3;
...
v_curs1_results t_curs1_tab := t_curs1_tab();
v_curs2_results t_curs2_tab := t_curs2_tab();
v_curs3_results t_curs3_tab := t_curs3_tab();

Then when processing the results, I have code like this:

    open c_curs1;
    fetch c_curs1 bulk collect into v_curs1_results;
    close c_curs1;

    if v_curs1_results.first is not null and v_curs1_results.last is not null then
       for i in v_curs1_results.first .. v_curs1_results.last loop
           /*Do something with field a in the results
             Do something with field b in the results
             Do something with field c in the results*/
           ....
       end loop;
    end if;

The code in the processing loop is the same for all cursors, as all 3 cursors return a,b,c - the only difference being which cursor is referenced. I wanted to refactor this into some sort of generic result-set processor, but I'm stuck here:

procedure sp_process_collection(in_collection t_curs1_tab) is ...

I can only call this with v_curs1_results, I can't call it with v_curs2_results or I get a PLS-00306 wrong number of types or arguments... compiler error. Is there any way to do this generically so I only have to write one collection processing procedure? I have this pattern of cursor (returning the same three columns, always the same types) appears in several other parts of the same package, and the processing loop, while semantically the same is sometimes written with slightly different code. I'd very much like to centralize the processing in one procedure, I just can'd figure out how to do it in PL/SQL. I know PL/SQL doesn't have generics (Which I think would have made a Java/C# solution fairly trivial), but I'm wondering if there's another way to approach this problem that I just haven't thought of.

(using Oracle 10g)

Body:
Can you do this with a REF CURSOR?

Something like:

CREATE PROCEDURE sp_process_cursor(in_cursor SYS_REFCURSOR)

/* you don't need to open the cursor, it's already open */
FETCH in_cursor BULK COLLECT INTO v_cursor_results;
IF v_cursor_results.first is not null and v_cursor_results.last IS NOT NULL THEN
  FOR i in v_cursor_results.FIRST .. v_cursor_results.LAST LOOP
  ...
  END LOOP;
END IF;

Your calling code would need to invoke this procedure once per cursor:

OPEN c_curs1;
sp_process_cursor(c_curs1);
CLOSE c_curs1;

OPEN c_curs2;
sp_process_cursor(c_curs2);
...


来源: stackexchange

问:
How render input fields label and text boxes in table format in angular 7?
I need to populate input fields label and text boxes dynamically in html form in table format. Each row consists 3 columns,  should populate 3 text boxes in different cells in my angular7 app.

Eg:

First row -> Label1: textbox1 Label2: textbox2 Labe31: textbox3
Second row ...

答:
Checkout Angular Material Tables! Gives very clean syntax in HTML for defining columns.

https://material.angular.io/components/table/overview

ContentLicense: CC BY-SA 4.0


问:
Filter specific value from Tshark JSON output
I would like to extract the "tls.handshake.certificate_raw" values, but without success so far. The big JSON is killing me.

Here's my JSON file: Download

Thanks in advance!

Body:
The following assumes that if a JSON object in the file has a specific key more than once, then only the last one is relevant. If this assumption is not valid, then one option would be to use jq's streaming parser.

The following shows that a simple application of jq to retrieve the named key requires about 26MB RAM. Is that a problem in this day and age?

/usr/bin/time -lp jq '.. | objects | .["tls.handshake.certificate_raw"] // empty'  Tshark.json

Output:

[
  "308204633082034ba00302010202100182f8098ea2e626b91a3b27841fb9af300d06092a864886f70d01010b0500305a310b300906035504061302494531123010060355040a130942616c74696d6f726531133011060355040b130a43796265725472757374312230200603550403131942616c74696d6f7265204379626572547275737420526f6f74301e170d3135313230383132303530375a170d3235303531303132303030305a3064310b300906035504061302555331153013060355040a130c446967694365727420496e6331193017060355040b13107777772e64696769636572742e636f6d312330210603550403131a44696769436572742042616c74696d6f72652043412d3220473230820122300d06092a864886f70d01010105000382010f003082010a0282010100bbe700fe000173ef9b88f05c0875f05c70731fffb57a1f8d0823fdc7c1133fb12106bd4dccdb2db8871931deda6b0dc15dd251d5b05e72d4f066d484f2911841b50926b2039604699553fa074f3ebe863a432bb259b5abd1baf45940725a67b6cde655fc092ba498b2bfcca91fd4bf878f8225fd4580a9ec9d8cf97490cf1cf86550afcdf845abc82f8d8e361ddeea89cdb252d9e509cd36712bdac6d09bc6f6a45b5b39b61f001f19a4fbd3be0ce6fb8fdd0e80e6a4e75ac4c02f72ee91f38367c9cdcace4ab02081fde472af0918e74f42ec4d27424d07a0ddd50d75f73660cc265498a18837f083f7ad295920cfbb25e1d59ee6f3aec101ebb50689e20a8f0203010001a382011930820115301d0603551d0e04160414c012b22874684667e97025741a00455b067d5c44301f0603551d23041830168014e59d5930824758ccacfa085436867b3ab5044df030120603551d130101ff040830060101ff020100300e0603551d0f0101ff040403020186303406082b0601050507010104283026302406082b060105050730018618687474703a2f2f6f6373702e64696769636572742e636f6d303a0603551d1f04333031302fa02da02b8629687474703a2f2f63726c332e64696769636572742e636f6d2f4f6d6e69726f6f74323032352e63726c303d0603551d200436303430320604551d2000302a302806082b06010505070201161c68747470733a2f2f7777772e64696769636572742e636f6d2f435053300d06092a864886f70d01010b050003820101002fe23766c31acf9155ee2914fa5010be998de228f1741607693b44303df5b949f56836feb7308da9e0074942634652b569c69b49f21a0f57c6f6b7beab758d0da2ab33e462854354ab63940ca353a0ea1de4a6a6ac950e6578ec338cbe943ed870abeac7e178ce3395bbfb2c58e08a40a66d41d8d8d9b3f92f02c51b706be23a857b1d18b0d14b9ac16f171029e80ec3e1549654a5919508208d692c9e2f3f50b42ee5571fafa473d2a124bb0d90fe45131da7a129d8660bc3d16cb34fb42b844c4790ec8be2418913b607467742fdbb1e17faff254b8e5057eb8ecc4e153fb125dd410ca09c626d6fba97078bd9f30610c529d4f7ba1690a8d054e14b49c798",
  1778,
  1127,
  0,
  30
]
real         1.42
user         1.34
sys          0.03
  26693632  maximum resident set size


问:
Accept inputs from the user until 5 unique inputs
How would I do this using a while function. Do we have to use a set somewhere for this?

This is what I have so far

```<code>while True:
    mySet = set(input("Enter a number:"))
    if mySet == 5:
        break
    print(mySet)
</code>```

答:
This maybe another good option, doesn't make use of a set()though, set() can be used as well like shown in the other answers, but here's one by using a list. Hope it helps :)

```<code>x = []
getUnique = []
while True:
   getNum = int(input("Enter a number:"))
   x.append(getNum)
   for num in x:
      if num not in getUnique:
         getUnique.append(num)
   if len(getUnique) == 5:
      print('5 unique numbers in list')
      print(getUnique) #shows only 5 unique numbers from user input.
      break
</code>```

Body:
How would I do this using a while function. Do we have to use a set somewhere for this?

This is what I have so far

while True:
    mySet = set(input("Enter a number:"))
    if mySet == 5:
        break
    print(mySet)

Body:
This maybe another good option, doesn't make use of a set()though, set() can be used as well like shown in the other answers, but here's one by using a list. Hope it helps :)

x = []
getUnique = []
while True:
   getNum = int(input("Enter a number:"))
   x.append(getNum)
   for num in x:
      if num not in getUnique:
         getUnique.append(num)
   if len(getUnique) == 5:
      print('5 unique numbers in list')
      print(getUnique) #shows only 5 unique numbers from user input.
      break


问:
Session can not be sent from backend to frontend
I have the issue that I am not getting a session from the backend. My application works on the live server but not on the localhost. I had the same issue before and I was working on it for about 1 week, then I had realized that the problem has nothing to do with my code. So I have played around with Git and used checkout to switch to previous versions and that worked! Even if I switched back to my current version, it still worked. I have no idea why and how but I was just glad that it worked. So now I have exactly the same problem again. I have tried the same to checkout previous versions but this time it doesn't work anymore. What is here the problem and how can I fix it?

It has definitely nothing to do with my code since the same code works on my server and it also worked on localhost before.

I am working with Angular (WebStorm) and Symfony (PhpStorm).

I am using Sourcetree. Any help would be appreciated!

答: If you are using a watcher (like nodemon node or springloader for ruby) then it is likely to blame. Try restarting your server if you have not already.</p>


问:
Is it possible to save form data through with Vue.js through Controller without Axios or asynchronous call?
I have a function in my controller that is used to store data. I am recreating my front end using Vue.js. As of now, I removed the current Laravel {{ Form: }} with Vue.js. Can I use same synchronous route without api to post the data? APIs are not ready and I cannot wait to validate my forms</p>

答:
Sure you can, all you need to do is to be aware that HTML does not have methods other than GET and POST. So, if you have PUT, DELETE and others, you're going to have to use the _method param trick.So, for example, when using the PUT http verb, you should create your form something like this:

```<code><form method='POST'>
       yourfields...
       <input type="hidden" name="_method" value="PUT">
</form>
</code>```

Other than that, it's pretty much calling the correct endpoints from your Vue application.

Body:
Sure you can, all you need to do is to be aware that HTML does not have methods other than GET and POST. So, if you have PUT, DELETE and others, you're going to have to use the _method param trick.So, for example, when using the PUT http verb, you should create your form something like this:

<form method='POST'>
       yourfields...
       <input type="hidden" name="_method" value="PUT">
</form>

Other than that, it's pretty much calling the correct endpoints from your Vue application.


问:
using boto3 to get file list and download files
I was given this s3 url: s3://file.share.external.bdex.com/Offrs

In this url is a battery of files I need to download.

I have this code:

```<code>import boto3

s3_client = boto3.client('s3',
                      aws_access_key_id='<<ACCESS KEY>>',
                      aws_secret_access_key='<<SECRET_ACCESS_KEY>>'
                      )
object_listing = s3_client.list_objects_v2(Bucket='file.share.external.bdex.com/Offrs',
                                    Prefix='')

print(object_listing)
</code>```

I have tried:

```<code>Bucket='file.share.external.bdex.com', Prefix='Offrs'
Bucket='s3://file.share.external.bdex.com/Offrs/'
Bucket='file.share.external.bdx.com/Offrs', Prefix='Offrs'
</code>```

and several other configurations, all saying I'm not following the regex. due to the slash, or not found.

What am I missing?

Thank you.

答:
```<code>Bucket = 'file.share.external.bdx.com'
Prefix = 'Offrs/'
</code>```

You can test your access permissions via the AWS CLI:

```<code>aws s3 ls s3://file.share.external.bdex.com/Offrs/
</code>```

Body:
I was given this s3 url: s3://file.share.external.bdex.com/Offrs

In this url is a battery of files I need to download.

I have this code:

import boto3

s3_client = boto3.client('s3',
                      aws_access_key_id='<<ACCESS KEY>>',
                      aws_secret_access_key='<<SECRET_ACCESS_KEY>>'
                      )
object_listing = s3_client.list_objects_v2(Bucket='file.share.external.bdex.com/Offrs',
                                    Prefix='')

print(object_listing)

I have tried:

Bucket='file.share.external.bdex.com', Prefix='Offrs'
Bucket='s3://file.share.external.bdex.com/Offrs/'
Bucket='file.share.external.bdx.com/Offrs', Prefix='Offrs'

and several other configurations, all saying I'm not following the regex. due to the slash, or not found.

What am I missing?

Thank you.

Body:
Bucket = 'file.share.external.bdx.com'
Prefix = 'Offrs/'

You can test your access permissions via the AWS CLI:

aws s3 ls s3://file.share.external.bdex.com/Offrs/


问:
Make sure path in Go template always ends with slash
I am writing a Helm chart for a bunch of deployments. I am supplying a value which can be:

my_value: "/opt/my-path"or my_value: "/opt/my-path/"

Now I would want to make sure that there is always a single / at the end of the path.

How do I do this using Go templates?

答:
You can trim the suffix / with trimSuffix function, docs here http://masterminds.github.io/sprig/strings.html, and to add / manually at the end. So regardless the original value you will always get a / at the end.
example

values.yaml:

```<code>path_with_slash: "/my/path/"
path_without_slash: "/my/path"
</code>```

inside a template file:

```<code>{{ $path_with_slash := trimSuffix "/" .Values.path_with_slash }}
{{ $path_without_slash := trimSuffix "/" .Values.path_without_slash }}
path_with_slash: "{{ $path_with_slash }}/"
path_without_slash: "{{ $path_without_slash }}/"
</code>```

rendered file:

```<code>path_with_slash: "/my/path/"
path_without_slash: "/my/path/"
</code>```

Body:
You can trim the suffix / with trimSuffix function, docs here http://masterminds.github.io/sprig/strings.html, and to add / manually at the end. So regardless the original value you will always get a / at the end.
example

values.yaml:

path_with_slash: "/my/path/"
path_without_slash: "/my/path"

inside a template file:

{{ $path_with_slash := trimSuffix "/" .Values.path_with_slash }}
{{ $path_without_slash := trimSuffix "/" .Values.path_without_slash }}
path_with_slash: "{{ $path_with_slash }}/"
path_without_slash: "{{ $path_without_slash }}/"

rendered file:

path_with_slash: "/my/path/"
path_without_slash: "/my/path/"


问:
How to securely create PHP variables with extract
In my previous post i ask how to create variables from an array ( PHP Variables made with foreach ) i got several answers and i was testing extract() but i have seen several against it for security reasons.

Now my question here is how can i use extract in a secure way from a $_POST that has an array that was made using jquery serialized.

With secure i mean that if a user inputs the wrong data, the secure way can take care of that with no problems.

THe PHP Site has a small warning in the extract command the says the following:

Do not use extract() on untrusted
  data, like user input (i.e. $_GET,
  $_FILES, etc.). If you do, for example
  if you want to run old code that
  relies on register_globals
  temporarily, make sure you use one of
  the non-overwriting extract_type
  values such as EXTR_SKIP and be aware
  that you should extract in the same
  order that's defined in
  variables_order within the php.ini.

It warns about the use but does not provide an example at least of how to solve the user of extract in a secure way.

答:
There is nothing wrong with extract if you only use it for partial extraction of known input variables. It's not the nicest syntax but doable with:

```<code>extract(array_intersect_key($_POST,
        array_flip(array("var1", "var2", "var3", "var4"))));
</code>```

This cuts down on the possible $_POST variables and will not extract unexpected stuff. The general benefit is that you can still apply some filter function using array_map for example. In some settings it reduces code clutter in comparison to individual variable copying.

ContentLicense: CC BY-SA 3.0

Body:
There is nothing wrong with extract if you only use it for partial extraction of known input variables. It's not the nicest syntax but doable with:

extract(array_intersect_key($_POST,
        array_flip(array("var1", "var2", "var3", "var4"))));

This cuts down on the possible $_POST variables and will not extract unexpected stuff. The general benefit is that you can still apply some filter function using array_map for example. In some settings it reduces code clutter in comparison to individual variable copying.


问:
How to make visual studio highlight keywords
Here is a picture of how it looks now:

I had to reinstall visual studio and when I started programming I noticed something was off.
For example, GameObject and Vector3 used to be the same color as MouseLook. Update and OnDrawGizmos used to be some other color too.
Does anybody know how to revert that? It is so annoying like this. But it's not the only problem.

When I type Vector3. it ussualy lists me its components, for example Vector3.forward or left, right, zero, one and so on. It doesn't do that now.

Please help me with this :/

Thank you in advance.

答:
Intellisense must not be working properly.

Make sure you have the Visual Studio Tools for Unity setup.


问:
How to change PayPal button locale?
I am having problems with changing the language displated on the PayPal Button:

PayPal Demo

When I add the following code, the language does not change (according to the documentation, it should change):

```<code>paypal.Buttons({
    locale: 'de_DE',
    style: {
       layout: 'vertical',
       color: 'gold',
       shape: 'pill',
       label: 'pay',
       tagline: false,
    },
    ...
})
</code>```

But when I change it in the script, it does change:

```<code><script src="https://www.paypal.com/sdk/js?client-id=sb&currency=USD&locale=de_DE"></script>
</code>```

How can I set the language by using Button configuration object and why it is not working as expected?

答:
according to the documentation, it should change

Which documentation are you reading? Archived documentation for the older checkout.js?

The current PayPal Checkout documentation clearly states that if you need to set the button language to match your website language, locale should be specified on the script/SDK line.

But only do this if your website is in a specific language and you need it to match. Otherwise, the best language can be detected automatically.

Title: How to change PayPal button locale?

Body:
I am having problems with changing the language displated on the PayPal Button:

PayPal Demo

When I add the following code, the language does not change (according to the documentation, it should change):

paypal.Buttons({
    locale: 'de_DE',
    style: {
       layout: 'vertical',
       color: 'gold',
       shape: 'pill',
       label: 'pay',
       tagline: false,
    },
    ...
})

But when I change it in the script, it does change:

How can I set the language by using Button configuration object and why it is not working as expected?


问:
How to create abstract model in Django?
I am new to Django framework and in my project I have a model called Layer.

```<code>class Layer(models.Model):
    name = models.CharField(max_length=255)
</code>```

I would like layer to have a relationship with an abstract model called "Geometry", more specifically, one layer should have one or no Geometry and one Geometry should be owned by one layer.

The problem is that I have for types of Geometries and they all have different properties, so I decided to create multiple geometries:

```<code>class Circle(models.Model):
    radius = models.CharField(max_length=255)

class Rectangle(models.Model):
    height = models.CharField(max_length=255)
    width = models.CharField(max_length=255)

</code>```

I would like to have a data structure where both models are of the same type (Geometry). I would like to call layer.geometry and be able to get either a circle or a rectangle, or a cross and so on. Is that possible? And how is the database shape going to be like? Is Django going to create two different tables or one table with merged properties?

Thanks in advance

答:
Django supports inheritance, although it is not very common. You can thus create a model Geometry, and let Circle and Rectangle inherit from that:

```<code>class <b>Geometry</b>(models.Model):
    pass

class Circle(<b>Geometry</b>):
    radius = models.CharField(max_length=255)

class Rectangle(<b>Geometry</b>):
    height = models.CharField(max_length=255)
    width = models.CharField(max_length=255)</code>```

We can furthermore make a ForeignKey (or another relation) to this Geometry class with:

```<code>class Layer(models.Model):
    name = models.CharField(max_length=255)
    geometry = <b>models.ForeignKey(Geometry, on_delete=models.CASCADE)</b></code>```

Django will make migrations that, for an SQL database create tables for Geometry, Circle and Rectangle. The Circle and Rectangle models will have an implicit OneToOneRelation to the table for the Geometry named geometry_ptr_id, that thus refers to the parent.

For more information, see the section on Multi-table inheritance in the documentation.

Title: How to create abstract model in Django?

Body:
I am new to Django framework and in my project I have a model called Layer.

class Layer(models.Model):
    name = models.CharField(max_length=255)

I would like layer to have a relationship with an abstract model called "Geometry", more specifically, one layer should have one or no Geometry and one Geometry should be owned by one layer.

The problem is that I have for types of Geometries and they all have different properties, so I decided to create multiple geometries:

class Circle(models.Model):
    radius = models.CharField(max_length=255)

class Rectangle(models.Model):
    height = models.CharField(max_length=255)
    width = models.CharField(max_length=255)

I would like to have a data structure where both models are of the same type (Geometry). I would like to call layer.geometry and be able to get either a circle or a rectangle, or a cross and so on. Is that possible? And how is the database shape going to be like? Is Django going to create two different tables or one table with merged properties?

Thanks in advance

Body:
Django supports inheritance, although it is not very common. You can thus create a model Geometry, and let Circle and Rectangle inherit from that:

class Geometry(models.Model):
    pass

class Circle(Geometry):
    radius = models.CharField(max_length=255)

class Rectangle(Geometry):
    height = models.CharField(max_length=255)
    width = models.CharField(max_length=255)

We can furthermore make a ForeignKey (or another relation) to this Geometry class with:

class Layer(models.Model):
    name = models.CharField(max_length=255)
    geometry = models.ForeignKey(Geometry, on_delete=models.CASCADE)

Django will make migrations that, for an SQL database create tables for Geometry, Circle and Rectangle. The Circle and Rectangle models will have an implicit OneToOneRelation to the table for the Geometry named geometry_ptr_id, that thus refers to the parent.

For more information, see the section on Multi-table inheritance in the documentation.


问:
Xcode, SFML error dyld: Library not loaded
I am trying to start a basic C++ project with link to SFML library.
I have unzipped the SFML library to folder /Users/mulperi/cpplib/sfml
and I have added that to Include Search Path and Library Search Path.

My code is simple, I followed a tutorial on Youtube (also tried different ready-made codes):

```<code>#include <iostream>
#include <SFML/Graphics.hpp>
int main() {
    sf::RenderWindow window(sf::VideoMode(640, 480), "First SML Window");
    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            switch (event.type) {
                case sf::Event::Closed:
                    window.close();
                    break;
                default:
                    break;
            }
        }
        window.clear();
        window.display();
    }
    return 0;
}
</code>```

The build succeeds so the paths should be fine. I don't get the window, instead I have these outputs:

Thread 1:

```<code>dyld`__abort_with_payload:
    0x10003b1e0 <+0>:  movl   $0x2000209, %eax          ; imm = 0x2000209
    0x10003b1e5 <+5>:  movq   %rcx, %r10
    0x10003b1e8 <+8>:  syscall
->  0x10003b1ea <+10>: jae    0x10003b1f4               ; <+20>
    0x10003b1ec <+12>: movq   %rax, %rdi
    0x10003b1ef <+15>: jmp    0x10003aa48               ; cerror_nocancel
    0x10003b1f4 <+20>: retq
    0x10003b1f5 <+21>: nop
    0x10003b1f6 <+22>: nop
    0x10003b1f7 <+23>: nop
</code>```

Output:

```<code>dyld: Library not loaded: @rpath/libsfml-system.2.5.dylib
  Referenced from: /Users/mulperi/Library/Developer/Xcode/DerivedData/sfml_1-cgodahbmxiufqnhhglbsyfuzvdvz/Build/Products/Debug/sfml_1
  Reason: image not found
(lldb)
</code>```

I am using Xcode 9.3.1 on High Sierra 10.13.4

Update:
I also tried moving the SFML folder inside the project folder and even tried splitting up include,libs,frameworks,extlibs tu /usr/local like in the SFML tutorial but I always get the same output.

Here are pics of my settings

答:
On Catalina the accepted solution does not seem to work anymore due to errors like:

sfml-audio.framework cannot be opened because the developer cannot be verified

Using homebrew solved it for me:

brew install sfml. Then on Xcode link the libraries installed by homebre by:

Navigating to the section 'Link Binaries With Libraries' on Xcode, drag and drop the sfml libraries from /usr/local/Cellar/sfml/x.x.x/lib directory

Click build and run. Project should now build and run successfully

Body:
I am trying to start a basic C++ project with link to SFML library.
I have unzipped the SFML library to folder /Users/mulperi/cpplib/sfml
and I have added that to Include Search Path and Library Search Path.

My code is simple, I followed a tutorial on Youtube (also tried different ready-made codes):

#include <iostream>
#include <SFML/Graphics.hpp>
int main() {
    sf::RenderWindow window(sf::VideoMode(640, 480), "First SML Window");
    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            switch (event.type) {
                case sf::Event::Closed:
                    window.close();
                    break;
                default:
                    break;
            }
        }
        window.clear();
        window.display();
    }
    return 0;
}

The build succeeds so the paths should be fine. I don't get the window, instead I have these outputs:

Thread 1:

dyld`__abort_with_payload:
    0x10003b1e0 <+0>:  movl   $0x2000209, %eax          ; imm = 0x2000209
    0x10003b1e5 <+5>:  movq   %rcx, %r10
    0x10003b1e8 <+8>:  syscall
->  0x10003b1ea <+10>: jae    0x10003b1f4               ; <+20>
    0x10003b1ec <+12>: movq   %rax, %rdi
    0x10003b1ef <+15>: jmp    0x10003aa48               ; cerror_nocancel
    0x10003b1f4 <+20>: retq
    0x10003b1f5 <+21>: nop
    0x10003b1f6 <+22>: nop
    0x10003b1f7 <+23>: nop

Output:

dyld: Library not loaded: @rpath/libsfml-system.2.5.dylib
  Referenced from: /Users/mulperi/Library/Developer/Xcode/DerivedData/sfml_1-cgodahbmxiufqnhhglbsyfuzvdvz/Build/Products/Debug/sfml_1
  Reason: image not found
(lldb)

I am using Xcode 9.3.1 on High Sierra 10.13.4

Update:
I also tried moving the SFML folder inside the project folder and even tried splitting up include,libs,frameworks,extlibs tu /usr/local like in the SFML tutorial but I always get the same output.

Here are pics of my settings


问:
Can I use static class for my Logger?
Recently I have been told that static class/methods are evil.

Take for example my class Logger:

```<code>class Logger{
   private static $logs = array();
   public static function add($msg){
      self::$logs[]=$msg;
   }

   public static function echo(){
       print_r(self::$logs);
   }
}
</code>```

I can use whenever i want in my appliaction like this:

```<code>Logger::add('My log 1');
</code>```

But reading this developers:

http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/

That Logger class doesn't seem so good.

So: Can I use it statically or I should avoid it at any cost?

答:
Logging classes are the exception.

Since they rarely contain much logic, you don't have the same testing concerns.

Logging is a perfect example of a GOOD place to use static classes.

Think of your alternatives:

A global instance of a logging object?

A singleton logging object?

Pass the logging object around to every single method/class (via in a constructor)?

The above are much worse than using static for logging.

Title: Can I use static class for my Logger?

Body:
Recently I have been told that static class/methods are evil.

Take for example my class Logger:

class Logger{
   private static $logs = array();
   public static function add($msg){
      self::$logs[]=$msg;
   }

   public static function echo(){
       print_r(self::$logs);
   }
}

I can use whenever i want in my appliaction like this:

Logger::add('My log 1');

But reading this developers:

http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/

That Logger class doesn't seem so good.

So: Can I use it statically or I should avoid it at any cost?


问:
JSON Headers is missing in Azure Data Factory (v2)
In the pipeline, I used copy data activity to fetch data from REST API into a .txt file

This is the preview of source data:

However after running the pipeline, I received the following output:

Now where is the column header? Is there something that I might have missed in configuring during creating the copy data activity?

EDIT: Here's the sink configuration:

答:
You have probably missed the option "First row as header" when configuring the sink dataset. Check that you have this enabled in the sink dataset of your copy activity:

Hope this helped!!


问:
How to register a user event defined in a SUB VI(LabVIEW)
I created a SUB VI and defined a user event in it.
Then I created another VI, let's call it MAIN VI.
I put a SUB VI in the MAIN VI,and I want to register the user event created in the SUB VI to the Event Case in the MAIN VI, what should I do?</p>

答:
The Option 2 does not need the Boolean Control (at least with LabVIEW 2018+) - the subVI may use First Call function, and when it returns True, setup everything its caller needs (maybe the event refnum is not the only thing needed - maybe an empty cluster of a type which will be used to pass the data later) and return - the caller gets and processes it all, then invokes the subVI again; then the First Call returns False, and the subVI stays active "forever".

An alternative is to use two subVI-s: subVI_init and subVI_stay - the caller needs to invoke both, wire connections from the first to the second, except the "error out" line which must pass through Register For Events to make sure it will be done before invoking the subVI_stay.

Or - if the main reason for creating user event in the subVI was a sophisticated data structure used by the event, like large and possibly nested cluster (the problem is that creating the event in the caller would need access to an empty structure, and putting this in the caller might make the caller too big) - use a separate subVI_typedef.


问:
QAbstractSeries signal clicked because type is QLineSeries
Is there a way to connect QAbstractSeries to a clicked signal because the type of the QAbstractSeries is a QLineSeries?

I can do the following:

```<code>QlineSeries *series = new QLineSeries();
QChart *chart = new QChart();
series->append(1,1);
chart->addSeries(series);
connect(series, &QLineSeries::clicked, this, &View::myFunction);
</code>```

But if i have defined the series in another class and i can only access the series through

```<code>QList<QAbstractSeries*> seriesList = chart->series();
</code>```

I cannot connect a series through

```<code>connect(seriesList[0], &QAbstractSeries::clicked, this, &View::myFunction);
</code>```

because QAbstractSeries has not a signal "clicked". But i can access the type through

```<code>seriesList[0].type();
</code>```

But now i don't know how to handle the connection with this information. Or is there another way to get the series out of my chart as a QLineSeries?

答:
The clicked signal is associated with the objects of the class QXYSeries and their derivatives such as QLineSeries so the solution is to make a casting to filter the series:

for(QAbstractSeries* series: chart->series()){
    if(QXYSeries* xyseries = qobject_cast<QXYSeries *>(series)){
        connect(xyseries, &QXYSeries::clicked, this, &View::myFunction);
    }
}
```

<p>With the previous code they will be applied to the classes derived from QXYSeries such as QLineSeries and QScatterSeries, but if you only want to apply to QLineSeries then you must do the following:</p>

<pre class="lang-cpp prettyprint-override"><code>for(QAbstractSeries* series: chart->series()){
    if(QLineSeries* lineseries = qobject_cast<QLineSeries *>(series)){
        connect(lineseries, &QLineSeries::clicked, this, &View::myFunction);
    }
}
</code>```

Body:
Is there a way to connect QAbstractSeries to a clicked signal because the type of the QAbstractSeries is a QLineSeries?

I can do the following:

QlineSeries *series = new QLineSeries();
QChart *chart = new QChart();
series->append(1,1);
chart->addSeries(series);
connect(series, &QLineSeries::clicked, this, &View::myFunction);

But if i have defined the series in another class and i can only access the series through

QList<QAbstractSeries*> seriesList = chart->series();

I cannot connect a series through

connect(seriesList[0], &QAbstractSeries::clicked, this, &View::myFunction);

because QAbstractSeries has not a signal "clicked". But i can access the type through

seriesList[0].type();

But now i don't know how to handle the connection with this information. Or is there another way to get the series out of my chart as a QLineSeries?

Body:
The clicked signal is associated with the objects of the class QXYSeries and their derivatives such as QLineSeries so the solution is to make a casting to filter the series:

for(QAbstractSeries* series: chart->series()){
    if(QXYSeries* xyseries = qobject_cast<QXYSeries *>(series)){
        connect(xyseries, &QXYSeries::clicked, this, &View::myFunction);
    }
}

With the previous code they will be applied to the classes derived from QXYSeries such as QLineSeries and QScatterSeries, but if you only want to apply to QLineSeries then you must do the following:

for(QAbstractSeries* series: chart->series()){
    if(QLineSeries* lineseries = qobject_cast<QLineSeries *>(series)){
        connect(lineseries, &QLineSeries::clicked, this, &View::myFunction);
    }
}


问:
Passing anonymous functions as parameters for later use
I'm having issues with a script that I made for use in HTML5.
Here is the function

```<code>function loadImage(loc,after,para){
        var img = new Image();
        img.src = loc;
        if(typeof(after) != "undefined" && typeof(para) != "undefined"){
            img.onloadeddata  = after(img,para);
        }else if(typeof(after) != "undefined"){
            img.onloadeddata  = after(img);
        }
        return img;
}
</code>```

and here is what is calling it

```<code>window.globalFriends[i][2]=loadImage('http://graph.facebook.com/'+window.globalFriends[i][0]+'/picture', function (a){
    updateLoaders();
    loadingDrawPerson(a);});
</code>```

What I'm trying to do is send a function as a parameter for it then to be called.
It kinda of works but it a weird way. For example; All the images do get loaded but the onloadeddata either fires the function way to early or the function is getting executed before it gets to the loadImage function.

What are your ideas on my malfunctioning script?

Thank-you for reading
Paul

答:
A line like this:

```<code>img.onloadeddata  = after(img,para);
</code>```

Means "call the after function with arguments img and para" and assign the result to onloadeddata."  If, instead, you're wanting to assign the function to onloadeddata, do this:

```<code>img.onloadeddata = function() { after(img, para); };
</code>```

Body:
I'm having issues with a script that I made for use in HTML5.
Here is the function

function loadImage(loc,after,para){
        var img = new Image();
        img.src = loc;
        if(typeof(after) != "undefined" && typeof(para) != "undefined"){
            img.onloadeddata  = after(img,para);
        }else if(typeof(after) != "undefined"){
            img.onloadeddata  = after(img);
        }
        return img;
}

and here is what is calling it

window.globalFriends[i][2]=loadImage('http://graph.facebook.com/'+window.globalFriends[i][0]+'/picture', function (a){
    updateLoaders();
    loadingDrawPerson(a);});

What I'm trying to do is send a function as a parameter for it then to be called.
It kinda of works but it a weird way. For example; All the images do get loaded but the onloadeddata either fires the function way to early or the function is getting executed before it gets to the loadImage function.

What are your ideas on my malfunctioning script?

Thank-you for reading
Paul

Body:
A line like this:

img.onloadeddata  = after(img,para);

Means "call the after function with arguments img and para" and assign the result to onloadeddata."  If, instead, you're wanting to assign the function to onloadeddata, do this:

img.onloadeddata = function() { after(img, para); };


问:
How do properly divide in a for loop? And how do I control the size of the result?
```<code>    printf("Enter the number of gallons used for tank#1: ");
    scanf("%.f", &number);
    while ((c = getchar() != '\n') && c != EOF);
    printf("Enter the number of miles driven:");
    scanf("%.f", &y);
    while ((c = getchar() != '\n') && c != EOF);
    div = number / y;
    printf("***The miles per gallon for this tank is %d\n\n", number, y, div);
</code>```

I am using a for loop here, the only problem I have with this section is the division of number and y.

Every time I try to do so the result isn't calculated, it'll give me a random number or an extremely long number.

答:
There are multiple problems in your code:

you did not post the definition of number, y or div. Given the computation you want to perform and the scanf() conversion, they should be defined as float or double.

the scanf() conversion format is invalid: there should ve not . in %.f. Either use %f if the variables have type float or %lf if they have type double.

You pass 3 variables to the last printf but only one format is present %d, which is incorrect for a floating point number, leading to undefined behavior, for example a meaningless sequence of digits.

The division computes gallons per mile, not miles per gallon. Naming your variables with meaningful names is advisable.

Here is a modified version:

```<code>int compute_mileage(void) {
    double gallons, miles, mph;

    printf("Enter the number of gallons used for tank#1: ");
    if (scanf("%lf", &gallons) != 1)
        return 1;
    while ((c = getchar() != EOF) && c != '\n')
        continue;
    printf("Enter the number of miles driven: ");
    if (scanf("%lf", &miles) != 1)
        return 1;
    while ((c = getchar() != EOF) && c != '\n')
        continue;
    mph = miles / gallons;
    printf("***The miles per gallon for this tank is %f\n\n", mph);
    return 0;
}
</code>```

Body:
    printf("Enter the number of gallons used for tank#1: ");
    scanf("%.f", &number);
    while ((c = getchar() != '\n') && c != EOF);
    printf("Enter the number of miles driven:");
    scanf("%.f", &y);
    while ((c = getchar() != '\n') && c != EOF);
    div = number / y;
    printf("***The miles per gallon for this tank is %d\n\n", number, y, div);

I am using a for loop here, the only problem I have with this section is the division of number and y.

Every time I try to do so the result isn't calculated, it'll give me a random number or an extremely long number.

Body:
There are multiple problems in your code:

you did not post the definition of number, y or div. Given the computation you want to perform and the scanf() conversion, they should be defined as float or double.

the scanf() conversion format is invalid: there should ve not . in %.f. Either use %f if the variables have type float or %lf if they have type double.

You pass 3 variables to the last printf but only one format is present %d, which is incorrect for a floating point number, leading to undefined behavior, for example a meaningless sequence of digits.

The division computes gallons per mile, not miles per gallon. Naming your variables with meaningful names is advisable.

Here is a modified version:

int compute_mileage(void) {
    double gallons, miles, mph;

    printf("Enter the number of gallons used for tank#1: ");
    if (scanf("%lf", &gallons) != 1)
        return 1;
    while ((c = getchar() != EOF) && c != '\n')
        continue;
    printf("Enter the number of miles driven: ");
    if (scanf("%lf", &miles) != 1)
        return 1;
    while ((c = getchar() != EOF) && c != '\n')
        continue;
    mph = miles / gallons;
    printf("***The miles per gallon for this tank is %f\n\n", mph);
    return 0;
}


问:
List in Ruby gem cli
I am making a ruby cli that outputs a list of game deals scraped from a site.

The list prints out promptly using

```<code>def games_sales
  Deal.all.each_with_index do |deal, index|
    puts "#{index + 1}.  #{deal.title}"
  end

  puts "What game do you want to see?"
  input = gets.strip

  game_selection(input.to_i)
end
</code>```

My problem comes when asking the user to select an item from the list.

```<code>def game_selection(input)
  deal = Deal.find_by_index(input)
  #binding.pry
  deal.each do |deal|
    puts "#{deal.index}"
    puts " Name: #{deal.title}"
    puts " Price: #{deal.price}"
    puts " Store: #{deal.store}"
    puts " Expiration: #{deal.expiration}"
  end
  deal
end
</code>```

It returns the int input but only the first item on the list every time.

I forgot my find_by_index method:

```<code>def self.find_by_index(input)
  all.select do |deal|

  end
end
</code>```

which is incomplete

答:
Not 100% sure if I got your question right and if you're using Rails, but Deals.all let me think of this.

I had to replace Deals.all with DEALS for testing as I haven't got a rails app running. So I used an Array of OpenStructs to fake your Model result.

```<code># this fakes Deals.all
require 'ostruct'
DEALS = [
    # add any more properties the same way as title, separated by comma
    OpenStruct.new(title: 123),
    OpenStruct.new(title: 456)
]

def games_sales
  DEALS.each_with_index do |deal, index|
    puts "#{index + 1}.  #{deal.title}"
  end

  puts "What game do you want to see?"
  input = gets.strip

  game_selection(input.to_i)
end

def game_selection(input)
  deal = DEALS.at(input-1)
  p deal[:title]
end

def self.find_by_index(input)
  all.select do |deal|
    deal.index == input
  end
end

games_sales
</code>```

Result when choosing 1 is 123, choosing 2 you'll get 456, due to p deal[:title] above in the code.

I think your find_by_index need to get the right index and in my example I had to use at(index) as at(input-1) in order to get the right result.

I really hope this helps somehow and I suggest that you add the expected result to your question, in case my answer does not help you.

Title: List in Ruby gem cli

Body:
I am making a ruby cli that outputs a list of game deals scraped from a site.

The list prints out promptly using

def games_sales
  Deal.all.each_with_index do |deal, index|
    puts "#{index + 1}.  #{deal.title}"
  end

  puts "What game do you want to see?"
  input = gets.strip

  game_selection(input.to_i)
end

My problem comes when asking the user to select an item from the list.

def game_selection(input)
  deal = Deal.find_by_index(input)
  #binding.pry
  deal.each do |deal|
    puts "#{deal.index}"
    puts " Name: #{deal.title}"
    puts " Price: #{deal.price}"
    puts " Store: #{deal.store}"
    puts " Expiration: #{deal.expiration}"
  end
  deal
end

It returns the int input but only the first item on the list every time.

I forgot my find_by_index method:

def self.find_by_index(input)
  all.select do |deal|

  end
end

which is incomplete

Body:
Not 100% sure if I got your question right and if you're using Rails, but Deals.all let me think of this.

I had to replace Deals.all with DEALS for testing as I haven't got a rails app running. So I used an Array of OpenStructs to fake your Model result.

# this fakes Deals.all
require 'ostruct'
DEALS = [
    # add any more properties the same way as title, separated by comma
    OpenStruct.new(title: 123),
    OpenStruct.new(title: 456)
]

def games_sales
  DEALS.each_with_index do |deal, index|
    puts "#{index + 1}.  #{deal.title}"
  end

  puts "What game do you want to see?"
  input = gets.strip

  game_selection(input.to_i)
end

def game_selection(input)
  deal = DEALS.at(input-1)
  p deal[:title]
end

def self.find_by_index(input)
  all.select do |deal|
    deal.index == input
  end
end

games_sales

Result when choosing 1 is 123, choosing 2 you'll get 456, due to p deal[:title] above in the code.

I think your find_by_index need to get the right index and in my example I had to use at(index) as at(input-1) in order to get the right result.

I really hope this helps somehow and I suggest that you add the expected result to your question, in case my answer does not help you.


答:
Honestly I would not use SQL for the column layout task.

Just fetch the results for all names with a simple SQL query:

```<code>$stmt = $pdo->query("SELECT name FROM MyTable ORDER BY id");
$names = $stmt->fetchAll(PDO::FETCH_OBJ);
</code>```

Then output your tabular format using PHP code:

```<code>$numColumns = 3;
$rowCount = $stmt->rowCount();
$numRows = ceil($rowCount / $numColumns);
for ($row = 0; $row < $numRows; $row++) {
  for ($col = 0; $col < $numColumns; $col++) {
    $i = $row + $numRows * $col;
    if ($i >= $rowCount) break;
    print $names[$i]->name;
    print "\t";
  }
  print "\n";
}
</code>```

Output in my test:

```<code>Name1   Name4   Name7
Name2   Name5   Name8
Name3   Name6   Name9
</code>```

I added another row for Name10, and this is the output:

```<code>Name1   Name5   Name9
Name2   Name6   Name10
Name3   Name7
Name4   Name8
</code>```

Title: Create grouping rows by foreach and mysql in PHP

Body:
This is my table structure :

----------------------
 # |  name  | active |
---|--------|--------|
 1 |  Name1 |   1    |
---|--------|--------|
 2 |  Name2 |   1    |
---|--------|--------|
 3 |  Name3 |   1    |
---|--------|--------|
 4 |  Name4 |   1    |
---|--------|--------|
 5 |  Name5 |   1    |
---|--------|--------|
 6 |  Name6 |   1    |
---|--------|--------|
 7 |  Name7 |   1    |
---|--------|--------|
 8 |  Name8 |   1    |
---|--------|--------|
 9 |  Name9 |   1    |
---|--------|--------|

I want to grouping (groups of three) rows by foreach and mysql, like the following:

--------------------------------
 Group 1 |  Group 2  | Group 3 |
---------|-----------|---------|
  Name1  |   Name4   |  Name7  |
---------|-----------|---------|
  Name2  |   Name5   |  Name8  |
---------|-----------|---------|
  Name3  |   Name6   |  Name9  |
---------|-----------|---------|

How do I do this?

Body:
Honestly I would not use SQL for the column layout task.

Just fetch the results for all names with a simple SQL query:

$stmt = $pdo->query("SELECT name FROM MyTable ORDER BY id");
$names = $stmt->fetchAll(PDO::FETCH_OBJ);

Then output your tabular format using PHP code:

$numColumns = 3;
$rowCount = $stmt->rowCount();
$numRows = ceil($rowCount / $numColumns);
for ($row = 0; $row < $numRows; $row++) {
  for ($col = 0; $col < $numColumns; $col++) {
    $i = $row + $numRows * $col;
    if ($i >= $rowCount) break;
    print $names[$i]->name;
    print "\t";
  }
  print "\n";
}

Output in my test:

Name1   Name4   Name7
Name2   Name5   Name8
Name3   Name6   Name9

I added another row for Name10, and this is the output:

Name1   Name5   Name9
Name2   Name6   Name10
Name3   Name7
Name4   Name8


问:
How can I match an exact pattern with sed -n
I have a file test.txt

```<code>---
kind: ClusterRole
metadata:
kind: ClusterRoleBinding
metadata:
subjects:
roleRef:
  kind: ClusterRole
  name: bla
</code>```

And need this output with sed (just the line that matches the exact pattern)

```<code>kind: ClusterRole
metadata:
</code>```

sed -n '/kind: ClusterRole/,/metadata/p' test.txt

```<code>kind: ClusterRole
metadata:
kind: ClusterRoleBinding
metadata:
  kind: ClusterRole
  name: bla
</code>```

is showing ClusterRole, ClusterRoleBinding and additional indented ClusterRole

```<code>sed -n '/kind: ClusterRole\b/,/metadata/p' test.txt
sed -n '/\<kind: ClusterRole\>/,/metadata/p' test.txt
</code>```

Both of the above output to nothing what am I doing wrong?
just so it's clear and I'm not getting any grep -B 2 suggestions ;-) this is an example file, the original file is a lot bigger and has hundreds of ClusterRoles so I need to figure out how to match the exact pattern.

Thank you!

lema

答: You should include start-of-line (^) and end-of-line ($) in your pattern.

Body:
I have a file test.txt

---
kind: ClusterRole
metadata:
kind: ClusterRoleBinding
metadata:
subjects:
roleRef:
  kind: ClusterRole
  name: bla

And need this output with sed (just the line that matches the exact pattern)

kind: ClusterRole
metadata:

sed -n '/kind: ClusterRole/,/metadata/p' test.txt

kind: ClusterRole
metadata:
kind: ClusterRoleBinding
metadata:
  kind: ClusterRole
  name: bla

is showing ClusterRole, ClusterRoleBinding and additional indented ClusterRole

sed -n '/kind: ClusterRole\b/,/metadata/p' test.txt
sed -n '/\<kind: ClusterRole\>/,/metadata/p' test.txt

Both of the above output to nothing what am I doing wrong?
just so it's clear and I'm not getting any grep -B 2 suggestions ;-) this is an example file, the original file is a lot bigger and has hundreds of ClusterRoles so I need to figure out how to match the exact pattern.

Thank you!

lema


问:
Failing to run external Bash program — /usr/bin/bash: bad interpreter: No such file or directory
I'm trying to run a CLI tool in Linux (Mint) which allows me to edit subtitles. It is named subedit: github link. In order to run it, I've added executable permission with chmod +x and added it to the path in bash. However, when I run it, I get the following error message:

```<code>bash: /home/main/Documents/shellTools/subedit/subedit: /usr/bin/bash: bad interpreter: No such file or directory
</code>```

I'm not very experienced with external bash programs and forgot to do something that would be obvious in hindsight.

When I do echo $PATH this is the output:

```<code>/home/main/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/main/Documents/shellTools/subedit/
</code>```

Could somebody please help?

答:
It seems that you don't have bash installed, you can verify that by running

```<code>which bash
</code>```

if the above command returns "bash not found", then you need to install it.
In case the above command returns a path, you can use the below command to add a symlink to the expected path

```<code>ln -s $(path from the above command) /usr/bin/bash
</code>```

Body:
I'm trying to run a CLI tool in Linux (Mint) which allows me to edit subtitles. It is named subedit: github link. In order to run it, I've added executable permission with chmod +x and added it to the path in bash. However, when I run it, I get the following error message:

bash: /home/main/Documents/shellTools/subedit/subedit: /usr/bin/bash: bad interpreter: No such file or directory

I'm not very experienced with external bash programs and forgot to do something that would be obvious in hindsight.

When I do echo $PATH this is the output:

/home/main/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/main/Documents/shellTools/subedit/

Could somebody please help?

Body:
It seems that you don't have bash installed, you can verify that by running

which bash

if the above command returns "bash not found", then you need to install it.
In case the above command returns a path, you can use the below command to add a symlink to the expected path

ln -s $(path from the above command) /usr/bin/bash


问:
re-sequencing a column of numbers based on a set value, R
I have a column of numbers that need to be re sequenced starting from 1, for example:
 column with numbers: 226 227 227 227 228 228 229 229 ...... so on

I would like to re sequence so that: 226 changes 1, 227 changes 2, 227 = 2, 227 = 2, 228 = 3, 228 = 3,
 229 = 4, 229 = 4  ....... and so on

    Current
    Desired

    226
    99

    227
    100

     227
    100

    227
    100

    228
    101

    228
    101

    229
    102

    229
    102

    229
    102

```

答:
We can subtract the minimum or the first element of 'Current' and then add 99 to it

```<code>df1$Desired <- df1$Current - df1$Current[1] + 99
df1$Desired
#[1]  99 100 100 100 101 101 102 102 102
</code>```

Or if it needs to be resequenced from 1

```<code>df1$Current - df1$Current[1] + 1
</code>```

Or use match

```<code>match(df1$Current, unique(df1$Current))
</code>```

data

```<code>df1 <- data.frame(Current = c(226, 227, 227, 227, 228, 228, 229, 229, 229))
</code>```

Body:
We can subtract the minimum or the first element of 'Current' and then add 99 to it

df1$Desired <- df1$Current - df1$Current[1] + 99
df1$Desired
#[1]  99 100 100 100 101 101 102 102 102

Or if it needs to be resequenced from 1

df1$Current - df1$Current[1] + 1

Or use match

match(df1$Current, unique(df1$Current))

data

df1 <- data.frame(Current = c(226, 227, 227, 227, 228, 228, 229, 229, 229))


问:
Artificial Intelligence A Modern Approach - Probabilistic Reasoning over Time
I'm currently reading Peter Norvig's Artificial Intelligence A Modern Approach Chapter 15 Probabilistic Reasoning over Time and I'm not able to follow the derivation for filtering and prediction (page 572).

Given the result of filtering up to time t, the agent needs to compute
  the result for t + 1  from the new evidence et+1,

P(Xt+1|e1:t+1) = f(et+1, P(Xt|e1:t)),

for some function f. This is called recursive estimation. We
  can view the calculation as being composed of two parts: first, the
  current state distribution is projected forward from t to t + 1; then
  it is updated using the new evidence et+1. This
  two-part process emerges quite simply when the formula is rearranged:

P(Xt+1|e1:t+1) = P(Xt+1|e1:t, et+1)     (dividing up the evidence)

  = α P(et+1|Xt+1, e1:t) P(Xt+1|e1:t)     (using Bayes' rule)

How does using Bayes' rule result in the last forumla? Shouldn't it be

α P(e1:t, et+1|Xt+1) P(Xt+1)

答:
They are both correct, except that the α is not identical between the two. The trick is that in Norvig's application of Bayes', the conditioning on e1:t is kept constant throughout. Just imagine that it wasn't there to begin with. You would still have all the identities. Then apply that conditioning to every part of the equation, and all the identities will hold.

Alternatively, the derivation can also be done without explicitly using Bayes', but instead, just using the definitions of joint and conditional probability (i.e., P(A|B)P(B)=P(A,B)=P(B|A)P(A)).

P(Xt+1|e1:t, et+1) P(et+1,e1:t) = P(e1:t, et+1|Xt+1) P(Xt+1)

Expanding the joint probabilities on both sides gives

P(Xt+1|e1:t, et+1) P(et+1|e1:t) P(e1:t) = P(et+1|Xt+1,e1:t) P(e1:t|Xt+1) P(Xt+1)

The last two terms on the RHS can be rewritten as

P(Xt+1|e1:t, et+1) P(et+1|e1:t) P(e1:t) = P(et+1|Xt+1,e1:t) P(Xt+1|e1:t) P(e1:t)

Now the P(e1:t) cancels (assuming nonzero), and we have

P(Xt+1|e1:t, et+1) = α P(et+1|Xt+1,e1:t) P(Xt+1|e1:t)

where α = 1 / P(et+1|e1:t).


问:
How can I execute a python script directly (without prefixing by the python command) from bash?
I am just starting to use terminal for my programming needs. In a lot of Django tutorials I see people say, for example, I should type this in terminal:

```<code>manage.py runserver
</code>```

However when I do this it says:

```<code>bash: manage.py: command not found
</code>```

I get it to work when I do: python manage.py runserver, however I would like to understand why this works and the other method doesn't. I guess these are some very basic things but I thought I'd ask here.

答:
It is because your manage.py is not an executable script.

First put this line at the top of manage.py (assuming your python is in /usr/bin/python):

```<code>#!/usr/bin/python
</code>```

Then make your script executable:

```<code>chmod +x manage.py
</code>```

Then try to execute your script ./manage.py runserver.

Read this link for more info: http://effbot.org/pyfaq/how-do-i-make-a-python-script-executable-on-unix.htm

Body:
I am just starting to use terminal for my programming needs. In a lot of Django tutorials I see people say, for example, I should type this in terminal:

manage.py runserver

However when I do this it says:

bash: manage.py: command not found

I get it to work when I do: python manage.py runserver, however I would like to understand why this works and the other method doesn't. I guess these are some very basic things but I thought I'd ask here.

Body:
It is because your manage.py is not an executable script.

First put this line at the top of manage.py (assuming your python is in /usr/bin/python):

#!/usr/bin/python

Then make your script executable:

chmod +x manage.py

Then try to execute your script ./manage.py runserver.

Read this link for more info: http://effbot.org/pyfaq/how-do-i-make-a-python-script-executable-on-unix.htm


问:
Reading csv file and want to skip first two columns
I am trying to read a CSV file in Python. Further I want to read my whole file but just don't want first two columns. Also I don't have columns name so that I can easily drop or skip it.

What code do I need to read the file without reading first two columns?

I have tried below code:

```<code>with open("data2.csv", "r") as file:
    lines = [line.split() for line in file]
    for i, x in enumerate(lines):
        print("line {0} = {1}".format(i,x))
</code>```

I am just reading file line by line from above code. But how to skip first two columns and then read the file? I don't have names of the columns.

答:
You should use the csv module in the standard library. You might need to pass additional kwargs (keyword arguments) depending on the format of your csv file.

```<code>import csv

with open('my_csv_file', 'r') as fin:
    reader = csv.reader(fin)
    for line in reader:
        print(line[2:])
        # do something with rest of columns...
</code>```

Body:
I am trying to read a CSV file in Python. Further I want to read my whole file but just don't want first two columns. Also I don't have columns name so that I can easily drop or skip it.

What code do I need to read the file without reading first two columns?

I have tried below code:

with open("data2.csv", "r") as file:
    lines = [line.split() for line in file]
    for i, x in enumerate(lines):
        print("line {0} = {1}".format(i,x))

I am just reading file line by line from above code. But how to skip first two columns and then read the file? I don't have names of the columns.

Body:
You should use the csv module in the standard library. You might need to pass additional kwargs (keyword arguments) depending on the format of your csv file.

import csv

with open('my_csv_file', 'r') as fin:
    reader = csv.reader(fin)
    for line in reader:
        print(line[2:])
        # do something with rest of columns...


问:
Error: Export of name 'ngModel' not found
After building my angular project i get the error:
 Error: Export of name 'ngModel' not found!

I have my UI running in a docker container

not even sure where to look for this. Its working fine in dev. (ng serve)

Any ideas

答:
I had the same error (though in dev), it turns out that I had not added the FormsModule module to the app.module.ts file. See below:

It is also stated here along with a few more problems and their corresponding solutions


问:
Error on starting the ruby server, specifically SystemStackError
May be this is just a simple error but since I am Rails noobie any help to my problem will be greatly appreciated.
I have been facing the following error everytime I start the rails server.
I am using Ruby 2.6 and Rails 4.2</p>

```<code>C:/Ruby26-x64/lib/ruby/gems/2.6.0/gems/activesupport-4.2.0/lib/active_support/core_ext/object/duplicable.rb:85: warning: BigDecimal.new is deprecated; use BigDecimal() method instead.
=> Booting WEBrick
=> Rails 4.2.0 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
C:/Ruby26-x64/lib/ruby/gems/2.6.0/gems/activesupport-4.2.0/lib/active_support/core_ext/numeric/conversions.rb:121: warning: constant ::Fixnum is deprecated
C:/Ruby26-x64/lib/ruby/gems/2.6.0/gems/activesupport-4.2.0/lib/active_support/core_ext/numeric/conversions.rb:121: warning: constant ::Bignum is deprecated
Exiting
Traceback (most recent call last):
bin/rails: stack level too deep (SystemStackError)
</code>```

答:
Rails 4.2 does not support Ruby 2.6. You should be using Ruby 2.4 for Rails 4.2, as support for Ruby 2.4 was explicitly added in Rails 4.2.8.

If you wish to use Ruby 2.6 you'll want to use Rails 6. Upgrading from Rails 4.2 to 5 to 6 is a complex process so you'll most likely to have an easier time downgrading Ruby rather than upgrading Rails. Running Ruby 2.4 on Windows is an exercise left up to the reader, though.

You can read more about the compatibility between Ruby and Rails versions in this answer.

Body:
May be this is just a simple error but since I am Rails noobie any help to my problem will be greatly appreciated.
I have been facing the following error everytime I start the rails server.
I am using Ruby 2.6 and Rails 4.2

C:/Ruby26-x64/lib/ruby/gems/2.6.0/gems/activesupport-4.2.0/lib/active_support/core_ext/object/duplicable.rb:85: warning: BigDecimal.new is deprecated; use BigDecimal() method instead.
=> Booting WEBrick
=> Rails 4.2.0 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
C:/Ruby26-x64/lib/ruby/gems/2.6.0/gems/activesupport-4.2.0/lib/active_support/core_ext/numeric/conversions.rb:121: warning: constant ::Fixnum is deprecated
C:/Ruby26-x64/lib/ruby/gems/2.6.0/gems/activesupport-4.2.0/lib/active_support/core_ext/numeric/conversions.rb:121: warning: constant ::Bignum is deprecated
Exiting
Traceback (most recent call last):
bin/rails: stack level too deep (SystemStackError)


答:
replot does not act as you may think it does.  It does not reproduce the previous plot; it creates a new plot by re-using the previous command.  So the sequence of commands

```<code>j = j0
plot foo(j)
j = j+1
replot, foo(j)
j = j+1
replot, foo(j)
</code>```

results in 3 copies of the same plot foo(j0+2)

If you want to compose a plot with successive values of k do not use replot. Instead do something like

```<code> plot for [j = j0 : j0+2] foo(j)
</code>```

Title: Plotting multiple graphs using index to data from array

Body:
Using Version 5.2 patchlevel 2, I tried the following plot:

gnuplot> set xdata time
gnuplot> set timefmt "%s"
gnuplot> array lr_a[100];array lr_b[100]
gnuplot> plot "free.dat" using 2:(i=stringcolumn(0)+1,lr_a[i]=$13,lr_b[i]=$14,$10) with linesp title columnheader(1)
gnuplot> print i
13
gnuplot> print lr_a
[-452057.0,-178648.0,9568.53,10688.5,11016.6,11142.9,11137.5,12296.8,12467.0,-147009.0,-18170.2,-17176.1,-6493.16,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,]
gnuplot> print lr_b
[0.000292381,0.000119527,5.32936e-07,-1.75101e-07,-3.82532e-07,-4.62388e-07,-4.58968e-07,-1.19192e-06,-1.29956e-06,9.95245e-05,1.80699e-05,1.74415e-05,1.06875e-05,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,]

Now I want to add plots using those arrays:

j=1
gnuplot> replot "free.dat" using 2:(lr_a[j]+lr_b[j]*$2) with linesp title "LR#".j

It worked, however when I try to add more plots like this

gnuplot> j=j+1;replot "free.dat" using 2:(lr_a[j]+lr_b[j]*$2) with linesp title "LR#".j
gnuplot> j=j+1;replot "free.dat" using 2:(lr_a[j]+lr_b[j]*$2) with linesp title "LR#".j
gnuplot> print j
3

The plots are all the same, labeled LR#3.

Why is that so?

For reference, here's (a rather useless) free.dat:

/home   1581728983       51175       51175           0       51175           0           1       51175     10411.5     10411.5           0     10411.5           0           1     10411.5
/home   1581729050       51175       51175           0       51175           0           1       51175     10411.5     10411.5  0.00976562     -452057  0.000292381    1.00299     10411.5
/home   1581729142       51175       51175           0       51175           0           1       51175     10411.5     10411.5  0.00920748     -178648  0.000119527    0.83085     10411.5
/home   1581730106       51175       51175           0       51175           0           1       51175     10411.5     10411.5  0.00799351     9568.53  5.32936e-07  0.0304721     10411.5
/home   1581730231       51175       51175           0       51175           0           1       51175     10411.5     10411.5  0.00715961     10688.5  -1.75101e-07    -0.0133904     10411.5
/home   1581730248       51175       51175           0       51175           0           1       51175     10411.5     10411.5  0.00654339     11016.6  -3.82532e-07     -0.033421     10411.5
/home   1581730649       51175       51175           0       51175           0           1       51175     10411.5     10411.5  0.00606222     11142.9  -4.62388e-07    -0.0487386     10411.5
/home   1581730988       51175       51175           0       51175           0           1       51175     10411.5     10411.5  0.00567332     11137.5  -4.58968e-07    -0.0582907     10411.5
/home   1581732515       51175       51175           0       51175           0           1       51175     10411.5     10411.5  0.00552427     12296.8  -1.19192e-06     -0.228729     10411.5
/home   1581732849       51175       51175           0       51175           0           1       51175     10411.5     10411.5  0.00537109       12467  -1.29956e-06      -0.30963     10411.5
/home   1581733526       51175       51175           0       51175           0           1       51175     10412.4     10411.6    0.258446     -147009  9.95245e-05   0.578522     10411.8
/home   1581797054       51175       51175           0       51175           0           1       51175     10412.7     10411.7    0.406035    -18170.2  1.80699e-05   0.818011     10412.8
/home   1581799764       51175       51175           0       51175           0           1       51175     10412.7     10411.7    0.482222    -17176.1  1.74415e-05   0.884514     10412.8
/home   1581802740       51175       51175           0       51175           0           1       51175     10411.5     10411.7    0.469488    -6493.16  1.06875e-05   0.646611     10412.3

Body:
replot does not act as you may think it does.  It does not reproduce the previous plot; it creates a new plot by re-using the previous command.  So the sequence of commands

j = j0
plot foo(j)
j = j+1
replot, foo(j)
j = j+1
replot, foo(j)

results in 3 copies of the same plot foo(j0+2)

If you want to compose a plot with successive values of k do not use replot. Instead do something like

 plot for [j = j0 : j0+2] foo(j)


问:
Git merge file content outside of a repo (--no-index)
The git diff command (with the --no-index flag) works incredibly well to diff two files, irrespective of whether or not these two files are contained in a Git repo or not.

Example

```<code>$ git diff --no-index -- filea fileb
// shows diff between filea and fileb
</code>```

Question

Is it also possible to use Git to selectively "merge" (i.e. git add) content from one file to another if they are not part of a Git repo? Basically like a git add -p but not from the working directory to the index, but from fileb to filea.

I feel like all the basic building blocks (plumbing commands) should be available. Possibly something involving format-patch and/or apply?

```<code>$ <command> filea fileb
// wanted: interactively choose patches/hunks from fileb and apply them to filea
</code>```

答:
git diff --no-index is pretty much just an ordinary diff, if you want to apply change hunks across arbitrary files, use an ordinary merge tool like vimdiff -- which is even harder to distinguish from vimdiff used as a Git mergetool because it's the same exact thing.

git add is for adding content to the repo, you're not working on two paths from the work tree, you're working on a single path from the work tree and whatever content is indexed at that path.  In particular, you don't get the option to have two different names.

But Git itself finds its work tree (and repo, and objects, and index…) only if
you don't explicitly tell it where they are.  If you've got a snapshot of filea somewhere, say at /path/to/filea, you can

```<code>git --work-tree /path/to add -p filea`
</code>```

and git will obligingly do a patch-add from the filea at that path to the filea content registered in the index.

Body:
The git diff command (with the --no-index flag) works incredibly well to diff two files, irrespective of whether or not these two files are contained in a Git repo or not.

Example

$ git diff --no-index -- filea fileb
// shows diff between filea and fileb

Question

Is it also possible to use Git to selectively "merge" (i.e. git add) content from one file to another if they are not part of a Git repo? Basically like a git add -p but not from the working directory to the index, but from fileb to filea.

I feel like all the basic building blocks (plumbing commands) should be available. Possibly something involving format-patch and/or apply?

$ <command> filea fileb
// wanted: interactively choose patches/hunks from fileb and apply them to filea

Body:
git diff --no-index is pretty much just an ordinary diff, if you want to apply change hunks across arbitrary files, use an ordinary merge tool like vimdiff -- which is even harder to distinguish from vimdiff used as a Git mergetool because it's the same exact thing.

git add is for adding content to the repo, you're not working on two paths from the work tree, you're working on a single path from the work tree and whatever content is indexed at that path.  In particular, you don't get the option to have two different names.

But Git itself finds its work tree (and repo, and objects, and index…) only if
you don't explicitly tell it where they are.  If you've got a snapshot of filea somewhere, say at /path/to/filea, you can

git --work-tree /path/to add -p filea`

and git will obligingly do a patch-add from the filea at that path to the filea content registered in the index.


答:
if the lines list does getting the data you want you can use slicing to get rid of the columns you don't want:

getting rid of first two:
lines[2:]

getting rid of last two:
lines[:-2]

```<code>with open("data2.csv", "r") as file:
    lines = [line.split()[2:] for line in file]
    for i, x in enumerate(lines):
        print("line {0} = {1}".format(i,x))
</code>```

Title: Reading csv file and want to skip first two columns

Body:
if the lines list does getting the data you want you can use slicing to get rid of the columns you don't want:

getting rid of first two:
lines[2:]

getting rid of last two:
lines[:-2]

with open("data2.csv", "r") as file:
    lines = [line.split()[2:] for line in file]
    for i, x in enumerate(lines):
        print("line {0} = {1}".format(i,x))


问:
Emacs switches to old buffers when a stale command is quit
I must be in the habit of leaving the mini-buffer in the middle of a command.  From there I will change buffers and continue working.  Later (sometimes much later) I'll notice that I had a command dangling incomplete in the mini-buffer.  If I go to cancel it with a C-g, Emacs will often swap buffers in my open windows to an earlier state.

I suppose this may be a feature, but in my flow of work I find it rather annoying.  Is there a way to stop this behavior or prevent it from happening, such as a warning that There is an incomplete command?

答:
I think that the answer to another question will help you solve this.  It can be an annoying behavior, but the solution limits some of the flexibility found in Emacs.

The answer is: How can I prevent the mini-buffer from displaying previous commands in Emacs? (I call it stop-using-minibuffer).


问:
How to groupBy one column and count another column with condition in Laravel?
I have a table for students with column remarks which is equal to pass or fail and a column class to determine their group.

Now I want to get a collection using eloquent that goes like:

```<code>Select count(remarks) where 'remarks' equal to pass and
count(remarks) where 'remarks' equal to fail
GROUP BY class
</code>```

What I have tried so far:

```<code>Student::where('remarks', 'pass')
        ->selectRaw('count(remarks) as passRemark')
        ->where('remarks', 'fail')
        ->selectRaw('count(remarks) as failRemark')
        ->groupBy('class')->get();
</code>```

The above code doesn't seem to work and it returns nothing, it does work when using 1 where clause which is not what I intend to do and I tried adding another where, the query breaks.

Can anyone suggest the best approach for this?

答:
To keep this in Eloquent, I would use the built in Laravel withCount() method and a closure function for each type of count.

Something like this would be my preference (I have now successfully tested this: each Student will have a count for both):

```<code>Student::withCount(['remarks as passRemark' => function ($query) {
         $query->where('remarks', 'pass');
}, 'remarks as failRemark' => function ($query) {
         $query->where('remarks', 'fail');
}])->groupBy('class')->get();
</code>```

Body:
I have a table for students with column remarks which is equal to pass or fail and a column class to determine their group.

Now I want to get a collection using eloquent that goes like:

Select count(remarks) where 'remarks' equal to pass and
count(remarks) where 'remarks' equal to fail
GROUP BY class

What I have tried so far:

Student::where('remarks', 'pass')
        ->selectRaw('count(remarks) as passRemark')
        ->where('remarks', 'fail')
        ->selectRaw('count(remarks) as failRemark')
        ->groupBy('class')->get();

The above code doesn't seem to work and it returns nothing, it does work when using 1 where clause which is not what I intend to do and I tried adding another where, the query breaks.

Can anyone suggest the best approach for this?

Body:
To keep this in Eloquent, I would use the built in Laravel withCount() method and a closure function for each type of count.

Something like this would be my preference (I have now successfully tested this: each Student will have a count for both):

Student::withCount(['remarks as passRemark' => function ($query) {
         $query->where('remarks', 'pass');
}, 'remarks as failRemark' => function ($query) {
         $query->where('remarks', 'fail');
}])->groupBy('class')->get();


问:
Python not able to save some CLOB xml into xml file
I have this xml saved as CLOB in my oracle database:

```<code><?xml version="1.0" encoding="UTF-8"?>
<DCResponse>
...
</DCResponse>
</code>```

and with this python code I am able to save content into xml file:

```<code>sql = "select extract(xmltype.createxml(xml), '//DCResponse').getStringVal() from table t where id = 2"
for row in cursor.execute(sql):
    print(row[0])
with open("output.xml", "w") as f:
    f.write(row[0])
</code>```

Instead with this xml

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<PIPEDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:XML-PIPE
PIPEDocument.xsd" ReferenceNumber="567862650" CreationDate="20200115155255" Version="1.0"
xmlns="urn:XML-PIPE">
...
</PIPEDocument>
</code>```

I'm not able to extract the content with python. Write() argument must be str, not None.....is result in Python console running this code:

```<code>sql = "select extract(xmltype.createxml(xml), '//PIPEDocument').getStringVal() from table t where id
= 7"
for row in cursor.execute(sql):
    print(row[0])
with open("output.xml", "w") as f:
    f.write(row[0])
</code>```

In my oracle client the output of the below sql query, used in python, is null:

```<code>select extract(xmltype.createxml(xml), '//PIPEDocument').getStringVal() from table t where id = 7;
</code>```

while the xml content is present in my DB:

```<code>select xml from table where id =7
</code>```

Not sure what is the issue, maybe the keyword '//PIPEDocument' in the select query or different encoding between the 2 XML files, but no idea how to fix this.

Please Help
Best Regards
Giancarlo

答:
For query performance, you might want to fetch the LOB as a String, see the doc.

For general reference, if the database type had been XMLType,  cx_Oracle's recommendation is to use xmltype.getclobval() to avoid limited XML lengths.

Update: The latest version of cx_Oracle, now called python-oracledb has a Thin mode that doesn't have the XML query length limitation.

Body:
I have this xml saved as CLOB in my oracle database:

<?xml version="1.0" encoding="UTF-8"?>
<DCResponse>
...
</DCResponse>

and with this python code I am able to save content into xml file:

sql = "select extract(xmltype.createxml(xml), '//DCResponse').getStringVal() from table t where id = 2"
for row in cursor.execute(sql):
    print(row[0])
with open("output.xml", "w") as f:
    f.write(row[0])

Instead with this xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<PIPEDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:XML-PIPE
PIPEDocument.xsd" ReferenceNumber="567862650" CreationDate="20200115155255" Version="1.0"
xmlns="urn:XML-PIPE">
...
</PIPEDocument>

I'm not able to extract the content with python. Write() argument must be str, not None.....is result in Python console running this code:

sql = "select extract(xmltype.createxml(xml), '//PIPEDocument').getStringVal() from table t where id
= 7"
for row in cursor.execute(sql):
    print(row[0])
with open("output.xml", "w") as f:
    f.write(row[0])

In my oracle client the output of the below sql query, used in python, is null:

select extract(xmltype.createxml(xml), '//PIPEDocument').getStringVal() from table t where id = 7;

while the xml content is present in my DB:

select xml from table where id =7

Not sure what is the issue, maybe the keyword '//PIPEDocument' in the select query or different encoding between the 2 XML files, but no idea how to fix this.

Please Help
Best Regards
Giancarlo


问:
Type error with Either in TypeScript/fp-ts
I'm using fp-ts and I have a function that returns either an HttpError object or a string:

```<code>async getPreferencesForUserId(userId: string): Promise<Either<HttpResponseNotFound, string>> {
    const preferences = await getRepository(Preference).findOne({ userId });
    return preferences ? right(preferences.preferenceMap) : left(new HttpResponseNotFound({ code: 404, message: 'Could not find preferences' }));
  }
</code>```

I would like to call this function in another file like this:

```<code>const preferenceMapAsJsonStringOrError: Either<HttpResponseNotFound, string> = await this.preferenceService.getPreferencesForUserId(userId);

const response: HttpResponseOK | HttpResponseNotFound = pipe(preferenceMapAsJsonStringOrError, fold(
  e => e,
  r => new HttpResponseOK(r)
));
response.setHeader('content-type', 'application/json');

return response;
</code>```

This is basically how I'd do it in Scala. (with the exception that fold is a method on the Either type, not a standalone function - so here I'm using the pipe helper)

The problem is, I'm getting an error from ts-server:

```<code>Type 'HttpResponseOK' is missing the following properties from type 'HttpResponseNotFound': isHttpResponseNotFound, isHttpResponseClientError
</code>```

And

```<code>node_modules/fp-ts/lib/Either.d.ts:129:69
    129 export declare function fold<E, A, B>(onLeft: (e: E) => B, onRight: (a: A) => B): (ma: Either<E, A>) => B;
                                                                            ~~~~~~~~~~~
    The expected type comes from the return type of this signature.
</code>```

I can get around this issue by doing this in a much more imperative way:

```<code>const preferenceMapAsJsonStringOrError: Either<HttpResponseNotFound, string> = await this.preferenceService.getPreferencesForUserId(userId);
if (isLeft(preferenceMapAsJsonStringOrError)) {
  return preferenceMapAsJsonStringOrError.left;
}

const response = new HttpResponseOK(preferenceMapAsJsonStringOrError.right);
response.setHeader('content-type', 'application/json');

return response;
</code>```

But I pretty much lose the benefit of using an Either at that point.

答:
I still get type errors after when trying the 2 methods. What fixed it for me was explicitly specifying the type of the fold.</p>

```<code>fold<HttpResponseNotFound, HttpResponseOK, HttpResponseNotFound | HttpResponseOK>(
  e => e,
  r => new HttpResponseOK(r)
)
</code>```

Body:
I'm using fp-ts and I have a function that returns either an HttpError object or a string:

async getPreferencesForUserId(userId: string): Promise<Either<HttpResponseNotFound, string>> {
    const preferences = await getRepository(Preference).findOne({ userId });
    return preferences ? right(preferences.preferenceMap) : left(new HttpResponseNotFound({ code: 404, message: 'Could not find preferences' }));
  }

I would like to call this function in another file like this:

const preferenceMapAsJsonStringOrError: Either<HttpResponseNotFound, string> = await this.preferenceService.getPreferencesForUserId(userId);

const response: HttpResponseOK | HttpResponseNotFound = pipe(preferenceMapAsJsonStringOrError, fold(
  e => e,
  r => new HttpResponseOK(r)
));
response.setHeader('content-type', 'application/json');

return response;

This is basically how I'd do it in Scala. (with the exception that fold is a method on the Either type, not a standalone function - so here I'm using the pipe helper)

The problem is, I'm getting an error from ts-server:

Type 'HttpResponseOK' is missing the following properties from type 'HttpResponseNotFound': isHttpResponseNotFound, isHttpResponseClientError

And

node_modules/fp-ts/lib/Either.d.ts:129:69
    129 export declare function fold<E, A, B>(onLeft: (e: E) => B, onRight: (a: A) => B): (ma: Either<E, A>) => B;
                                                                            ~~~~~~~~~~~
    The expected type comes from the return type of this signature.

I can get around this issue by doing this in a much more imperative way:

const preferenceMapAsJsonStringOrError: Either<HttpResponseNotFound, string> = await this.preferenceService.getPreferencesForUserId(userId);
if (isLeft(preferenceMapAsJsonStringOrError)) {
  return preferenceMapAsJsonStringOrError.left;
}

const response = new HttpResponseOK(preferenceMapAsJsonStringOrError.right);
response.setHeader('content-type', 'application/json');

return response;

But I pretty much lose the benefit of using an Either at that point.

Body:
I still get type errors after when trying the 2 methods. What fixed it for me was explicitly specifying the type of the fold.

fold<HttpResponseNotFound, HttpResponseOK, HttpResponseNotFound | HttpResponseOK>(
  e => e,
  r => new HttpResponseOK(r)
)


问:
Using Room, how to get the last inserted auto-generated ID , including when the table didn't get anything inserted into it?
Just a solution that someone wrote to me that I think could be useful:

Background

I just wanted to know if the table was ever been modified, so I thought that maybe by getting the last generated ID this could be a way to do it, and since I know this value should be saved somewhere, it should be possible to get it.

My idea :

Using Room, get the last inserted auto-generated ID (even if nothing was ever inserted) , without modifying the table or create any additional table.

The problem

I couldn't find a way to do it, so I requested about this here and asked here.

What I've found

There were some answers over StackOverflow for using "last_insert_rowid", but I failed to use it.

Here's a sample Room Database :

build.gradle

```<code>repositories {
    maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
}
</code>```

...

```<code>apply plugin: 'kotlin-android-extensions'
</code>```

...

```<code>final def room_version = '2.1.0'
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
</code>```

...

DBProvider.kt

```<code>object DBProvider {
    const val DB_NAME = "room.db"
    lateinit var DB: MainDatabase

    fun init(context: Context) {
        //        Log.d("AppLog", "DBProvider init")
        DB = Room.databaseBuilder(context.applicationContext, MainDatabase::class.java, DB_NAME)
            .addCallback(object : RoomDatabase.Callback() {
            }).build()
    }

    @Database(
        entities = [FavoriteSpeedDialDTO::class],
        version = DB_VERSION,
        exportSchema = false
    )
    abstract class MainDatabase : RoomDatabase() {
        abstract fun favoriteSpeedDialDao(): FavoriteSpeedDialDao
        abstract fun dao(): SpecialDao
    }

}
</code>```

FavoriteSpeedDialDao.kt

```<code>@Dao
abstract class FavoriteSpeedDialDao {
    @Query("SELECT * FROM favorite_speed_dial")
    abstract fun getFavoritesList(): MutableList<FavoriteSpeedDialDTO>

    @Insert
    abstract fun insert(item: FavoriteSpeedDialDTO): Long

    @Query("DELETE FROM favorite_speed_dial")
    abstract fun deleteAll(): Int

}
</code>```

FavoriteSpeedDialDTO.kt

```<code>@Entity(tableName = "favorite_speed_dial")
@Parcelize
data class FavoriteSpeedDialDTO(@ColumnInfo(name = COL_ID) @PrimaryKey(autoGenerate = true) var id: Long,
                                @ColumnInfo(name = COL_ASSIGNED_PHONE_NUMBER) var phoneNumber: String) : Parcelable {
    companion object {
        const val COL_ID = BaseColumns._ID
        const val COL_ASSIGNED_PHONE_NUMBER = "assigned_phone_number"
    }
}
</code>```

The question

Using Room, how to get the last generated ID of a table, even if nothing was added to it, ever, and also when it gets emptied?

Since I already found an answer, I posted it, but if you think there is another nice solution, feel free to post it.

答:
And the answer:

SpecialDao.kt

```<code>@Suppress("AndroidUnresolvedRoomSqlReference")
@Dao
abstract class SpecialDao {
    @Query("SELECT seq FROM sqlite_sequence WHERE name = :tableName")
    abstract fun getSequenceNumber(tableName: String): Long?
}
</code>```

Sample to show it works:

MainActivity.kt

```<code>class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        DBProvider.init(this)
        AsyncTask.execute {
            val dao = DBProvider.DB.dao()
            var sequenceNumber = dao.getSequenceNumber("favorite_speed_dial")
            Log.d("AppLog", "id:$sequenceNumber")
            val favoriteSpeedDialDao = DBProvider.DB.favoriteSpeedDialDao()
            var favoritesList = favoriteSpeedDialDao.getFavoritesList()
            Log.d("AppLog", "favoritesList:${favoritesList}")
            Log.d("AppLog", "deleting all and inserting a new item...")
            favoriteSpeedDialDao.deleteAll()
            favoriteSpeedDialDao.insert(FavoriteSpeedDialDTO(0L, "123"))
            favoritesList = favoriteSpeedDialDao.getFavoritesList()
            Log.d("AppLog", "favoritesList:${favoritesList}")
            sequenceNumber = dao.getSequenceNumber("favorite_speed_dial")
            Log.d("AppLog", "id:$sequenceNumber")

        }
    }

    companion object {
        fun toString(collection: Collection<*>?): String {
            if (collection == null)
                return "null"
            val sb = StringBuilder("{")
            var isFirst = true
            for (`object` in collection) {
                if (!isFirst)
                    sb.append(',')
                else
                    isFirst = false
                sb.append(`object`)
            }
            sb.append('}')
            return sb.toString()
        }
    }
}
</code>```

Body:
Just a solution that someone wrote to me that I think could be useful:

Background

I just wanted to know if the table was ever been modified, so I thought that maybe by getting the last generated ID this could be a way to do it, and since I know this value should be saved somewhere, it should be possible to get it.

My idea :

Using Room, get the last inserted auto-generated ID (even if nothing was ever inserted) , without modifying the table or create any additional table.

The problem

I couldn't find a way to do it, so I requested about this here and asked here.

What I've found

There were some answers over StackOverflow for using "last_insert_rowid", but I failed to use it.

Here's a sample Room Database :

build.gradle

repositories {
    maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
}

...

apply plugin: 'kotlin-android-extensions'

...

final def room_version = '2.1.0'
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"

...

DBProvider.kt

object DBProvider {
    const val DB_NAME = "room.db"
    lateinit var DB: MainDatabase

    fun init(context: Context) {
        //        Log.d("AppLog", "DBProvider init")
        DB = Room.databaseBuilder(context.applicationContext, MainDatabase::class.java, DB_NAME)
            .addCallback(object : RoomDatabase.Callback() {
            }).build()
    }

    @Database(
        entities = [FavoriteSpeedDialDTO::class],
        version = DB_VERSION,
        exportSchema = false
    )
    abstract class MainDatabase : RoomDatabase() {
        abstract fun favoriteSpeedDialDao(): FavoriteSpeedDialDao
        abstract fun dao(): SpecialDao
    }

}

FavoriteSpeedDialDao.kt

@Dao
abstract class FavoriteSpeedDialDao {
    @Query("SELECT * FROM favorite_speed_dial")
    abstract fun getFavoritesList(): MutableList<FavoriteSpeedDialDTO>

    @Insert
    abstract fun insert(item: FavoriteSpeedDialDTO): Long

    @Query("DELETE FROM favorite_speed_dial")
    abstract fun deleteAll(): Int

}

FavoriteSpeedDialDTO.kt

@Entity(tableName = "favorite_speed_dial")
@Parcelize
data class FavoriteSpeedDialDTO(@ColumnInfo(name = COL_ID) @PrimaryKey(autoGenerate = true) var id: Long,
                                @ColumnInfo(name = COL_ASSIGNED_PHONE_NUMBER) var phoneNumber: String) : Parcelable {
    companion object {
        const val COL_ID = BaseColumns._ID
        const val COL_ASSIGNED_PHONE_NUMBER = "assigned_phone_number"
    }
}

The question

Using Room, how to get the last generated ID of a table, even if nothing was added to it, ever, and also when it gets emptied?

Since I already found an answer, I posted it, but if you think there is another nice solution, feel free to post it.

Body:
And the answer:

SpecialDao.kt

@Suppress("AndroidUnresolvedRoomSqlReference")
@Dao
abstract class SpecialDao {
    @Query("SELECT seq FROM sqlite_sequence WHERE name = :tableName")
    abstract fun getSequenceNumber(tableName: String): Long?
}

Sample to show it works:

MainActivity.kt

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        DBProvider.init(this)
        AsyncTask.execute {
            val dao = DBProvider.DB.dao()
            var sequenceNumber = dao.getSequenceNumber("favorite_speed_dial")
            Log.d("AppLog", "id:$sequenceNumber")
            val favoriteSpeedDialDao = DBProvider.DB.favoriteSpeedDialDao()
            var favoritesList = favoriteSpeedDialDao.getFavoritesList()
            Log.d("AppLog", "favoritesList:${favoritesList}")
            Log.d("AppLog", "deleting all and inserting a new item...")
            favoriteSpeedDialDao.deleteAll()
            favoriteSpeedDialDao.insert(FavoriteSpeedDialDTO(0L, "123"))
            favoritesList = favoriteSpeedDialDao.getFavoritesList()
            Log.d("AppLog", "favoritesList:${favoritesList}")
            sequenceNumber = dao.getSequenceNumber("favorite_speed_dial")
            Log.d("AppLog", "id:$sequenceNumber")

        }
    }

    companion object {
        fun toString(collection: Collection<*>?): String {
            if (collection == null)
                return "null"
            val sb = StringBuilder("{")
            var isFirst = true
            for (`object` in collection) {
                if (!isFirst)
                    sb.append(',')
                else
                    isFirst = false
                sb.append(`object`)
            }
            sb.append('}')
            return sb.toString()
        }
    }
}