问:
How repeat part of function Swift
still learning the basics. I have a function in which there is a block, that needs to be repeated without calling the whole function again. How is this done in Swift? </p>

```<code>func connected(to peripheral: Peripheral) {
    let cwConnection = CWStatusBarNotification()
    cwConnection.display(withMessage: "Ring Connected", forDuration: 3)

    BluejayManager.shared.getHeliosInfo { (success) in
        if success {
            // Go on
        } else {
            // Repeat this block (BluejayManager.shared.getHeliosInfo)
        }
    }
}
</code>```

答:
Hey Riyan it's just simple. Here is the solution to your problem. Just put the block in other small method and when you just need to call that block call that small function.

```<code>func connected(to peripheral: Peripheral) {
    let cwConnection = CWStatusBarNotification()
    cwConnection.display(withMessage: "Ring Connected", forDuration: 3)

    self.callBluejayManagerShared() // Call of block from method
}

func callBluejayManagerShared(){
    BluejayManager.shared.getHeliosInfo { (success) in
        if success {
            // Go on
        } else {
            // Repeat this block (BluejayManager.shared.getHeliosInfo)
            self.callBluejayManagerShared()
        }
    }
}
</code>```

Now when you just want to call block you just need to call self.callBluejayManagerShared() method.
Hope this help you

Title: How repeat part of function Swift

Body:
still learning the basics. I have a function in which there is a block, that needs to be repeated without calling the whole function again. How is this done in Swift?

func connected(to peripheral: Peripheral) {
    let cwConnection = CWStatusBarNotification()
    cwConnection.display(withMessage: "Ring Connected", forDuration: 3)

    BluejayManager.shared.getHeliosInfo { (success) in
        if success {
            // Go on
        } else {
            // Repeat this block (BluejayManager.shared.getHeliosInfo)
        }
    }
}

Body:
Hey Riyan it's just simple. Here is the solution to your problem. Just put the block in other small method and when you just need to call that block call that small function.

func connected(to peripheral: Peripheral) {
    let cwConnection = CWStatusBarNotification()
    cwConnection.display(withMessage: "Ring Connected", forDuration: 3)

    self.callBluejayManagerShared() // Call of block from method
}

func callBluejayManagerShared(){
    BluejayManager.shared.getHeliosInfo { (success) in
        if success {
            // Go on
        } else {
            // Repeat this block (BluejayManager.shared.getHeliosInfo)
            self.callBluejayManagerShared()
        }
    }
}

Now when you just want to call block you just need to call self.callBluejayManagerShared() method.
Hope this help you


来源: stackexchange

问:
Is the traversal category of boost::iterator_adaptor determined by the category of the adapted iterator?
My class inheriting from boost::iterator_adaptor has code like

```<code>private:

using is_bidirectional = std::is_convertible<
  iterator_category, std::bidirectional_iterator_tag>;

typename std::enable_if<is_bidirectional::value>::type
decrement() { ... }
</code>```

and I am wondering if the enable_if part is redundant. As written, the decrement() overload will not be enabled if the adapted iterator is not bidirectional. However I do not know whether boost::iterator_adaptor already uses SFINAE such that I do not need to be concerned about the traversal category in the private overloads. The code compiles and works just fine. I am only asking whether the enable_if part is useful or whether it is redundant.

答:
Yes.

Indeed, the adapter, by default, does mirror the base-iterator's category.

Here's a comprehensive test that works:

Live On Coliru

```<code>#include <boost/iterator_adaptors.hpp>

template <typename BaseIterator>
struct Adapt : boost::iterator_adaptor<Adapt<BaseIterator>, BaseIterator> {
    using base = boost::iterator_adaptor<Adapt<BaseIterator>, BaseIterator>;
    using base::base;
    using base::operator=;
};

#include <iostream>
#include <iterator>
#include <typeinfo>

template <typename It>
std::string cat(It const&) {
    return typeid(typename std::iterator_traits<It>::iterator_category).name();
}

template <typename It, typename OutIt>
void test(std::string caption, It f, It l, OutIt out) {
    Adapt<It> af{f}, al{l};

    std::cout << caption << ", adapts to " << cat(af) << "\t";
    std::copy(af, al, out);
    std::cout << "\n";
}

template <typename Container, typename OutIt>
void test(std::string caption, Container const& c, OutIt out) {
    using BaseIterator = typename Container::const_iterator;
    Adapt<BaseIterator> f{c.begin()}, l{c.end()};

    test(caption, f, l, out);
}

#include <vector>
#include <forward_list>
#include <list>
#include <sstream>

int main() {
    using V = std::vector<int>;
    using L = std::list<int>;
    using FL = std::forward_list<int>;
    using II = std::istream_iterator<int>;
    using OI = std::ostream_iterator<int>;

    static_assert(std::is_same<std::random_access_iterator_tag, std::iterator_traits<V::iterator>::iterator_category>{}, "");
    static_assert(std::is_same<std::bidirectional_iterator_tag, std::iterator_traits<L::iterator>::iterator_category>{}, "");
    static_assert(std::is_same<std::forward_iterator_tag, std::iterator_traits<FL::iterator>::iterator_category>{}, "");
    static_assert(std::is_same<std::input_iterator_tag, std::iterator_traits<II>::iterator_category>{}, "");
    static_assert(std::is_same<std::output_iterator_tag, std::iterator_traits<OI>::iterator_category>{}, "");

    OI out(std::cout, " ");
    test("vector      ", V  { 1,2,3 }, out);
    test("list        ", L  { 4,5,6 }, out);
    test("forward_list", FL { 7,8,9 }, out);
    {
        std::istringstream iss("10 11 12");
        II f(iss), l;
        test("stream input", f, l, out);
    }
}
</code>```

Which prints¹

```<code>vector      , adapts to std::random_access_iterator_tag 1 2 3
list        , adapts to std::bidirectional_iterator_tag 4 5 6
forward_list, adapts to std::forward_iterator_tag   7 8 9
stream input, adapts to std::input_iterator_tag 10 11 12
</code>```

¹ filtered the output through c++filt -t for prettier type info

ContentLicense: CC BY-SA 3.0

Body:
My class inheriting from boost::iterator_adaptor has code like

private:

using is_bidirectional = std::is_convertible<
  iterator_category, std::bidirectional_iterator_tag>;

typename std::enable_if<is_bidirectional::value>::type
decrement() { ... }

and I am wondering if the enable_if part is redundant. As written, the decrement() overload will not be enabled if the adapted iterator is not bidirectional. However I do not know whether boost::iterator_adaptor already uses SFINAE such that I do not need to be concerned about the traversal category in the private overloads. The code compiles and works just fine. I am only asking whether the enable_if part is useful or whether it is redundant.

Body:
Yes.

Indeed, the adapter, by default, does mirror the base-iterator's category.

Here's a comprehensive test that works:

Live On Coliru

#include <boost/iterator_adaptors.hpp>

template <typename BaseIterator>
struct Adapt : boost::iterator_adaptor<Adapt<BaseIterator>, BaseIterator> {
    using base = boost::iterator_adaptor<Adapt<BaseIterator>, BaseIterator>;
    using base::base;
    using base::operator=;
};

#include <iostream>
#include <iterator>
#include <typeinfo>

template <typename It>
std::string cat(It const&) {
    return typeid(typename std::iterator_traits<It>::iterator_category).name();
}

template <typename It, typename OutIt>
void test(std::string caption, It f, It l, OutIt out) {
    Adapt<It> af{f}, al{l};

    std::cout << caption << ", adapts to " << cat(af) << "\t";
    std::copy(af, al, out);
    std::cout << "\n";
}

template <typename Container, typename OutIt>
void test(std::string caption, Container const& c, OutIt out) {
    using BaseIterator = typename Container::const_iterator;
    Adapt<BaseIterator> f{c.begin()}, l{c.end()};

    test(caption, f, l, out);
}

#include <vector>
#include <forward_list>
#include <list>
#include <sstream>

int main() {
    using V = std::vector<int>;
    using L = std::list<int>;
    using FL = std::forward_list<int>;
    using II = std::istream_iterator<int>;
    using OI = std::ostream_iterator<int>;

    static_assert(std::is_same<std::random_access_iterator_tag, std::iterator_traits<V::iterator>::iterator_category>{}, "");
    static_assert(std::is_same<std::bidirectional_iterator_tag, std::iterator_traits<L::iterator>::iterator_category>{}, "");
    static_assert(std::is_same<std::forward_iterator_tag, std::iterator_traits<FL::iterator>::iterator_category>{}, "");
    static_assert(std::is_same<std::input_iterator_tag, std::iterator_traits<II>::iterator_category>{}, "");
    static_assert(std::is_same<std::output_iterator_tag, std::iterator_traits<OI>::iterator_category>{}, "");

    OI out(std::cout, " ");
    test("vector      ", V  { 1,2,3 }, out);
    test("list        ", L  { 4,5,6 }, out);
    test("forward_list", FL { 7,8,9 }, out);
    {
        std::istringstream iss("10 11 12");
        II f(iss), l;
        test("stream input", f, l, out);
    }
}

Which prints¹

vector      , adapts to std::random_access_iterator_tag 1 2 3
list        , adapts to std::bidirectional_iterator_tag 4 5 6
forward_list, adapts to std::forward_iterator_tag   7 8 9
stream input, adapts to std::input_iterator_tag 10 11 12

¹ filtered the output through c++filt -t for prettier type info


问:
How to open an indirect buffer in a new frame in a single call in emacs?
There are a couple of functions to open a buffer in a new frame (display-buffer-other-frame, switch-to-buffer-other-frame), but how do I create an indirect buffer in a new frame (in a single call, that is)?

答:
Is this what you are looking for?

clone-indirect-buffer-other-window is an interactive compiled Lisp
  function in simple.el.

It is bound to C-x 4 c.

(clone-indirect-buffer-other-window NEWNAME DISPLAY-FLAG &optional
  NORECORD)

Like clone-indirect-buffer but display in another window.

Use C-h f clone-indirect-buffer to see details about what that command does.

OK, you want it opened in a separate frame, not just a separate Emacs window.  For that, you can define your own clone-indirect-buffer-other-frame, but just binding pop-up-frames to t around the call to clone-indirect-buffer, the same way that clone-indirect-buffer-other-window binds pop-up-windows.

```<code>(defun clone-indirect-buffer-other-frame (newname display-flag &optional norecord)
  "Like `clone-indirect-buffer' but display in another window."
  (interactive
   (progn
     (if (get major-mode 'no-clone-indirect)
     (error "Cannot indirectly clone a buffer in %s mode" mode-name))
     (list (if current-prefix-arg
           (read-buffer "Name of indirect buffer: " (current-buffer)))
       t)))
  ;; (let ((pop-up-windows t))
  (let ((pop-up-frames t)) ; <==========
    (clone-indirect-buffer newname display-flag norecord)))
</code>```

Body:
Is this what you are looking for?

clone-indirect-buffer-other-window is an interactive compiled Lisp
  function in simple.el.

It is bound to C-x 4 c.

(clone-indirect-buffer-other-window NEWNAME DISPLAY-FLAG &optional
  NORECORD)

Like clone-indirect-buffer but display in another window.

Use C-h f clone-indirect-buffer to see details about what that command does.

OK, you want it opened in a separate frame, not just a separate Emacs window.  For that, you can define your own clone-indirect-buffer-other-frame, but just binding pop-up-frames to t around the call to clone-indirect-buffer, the same way that clone-indirect-buffer-other-window binds pop-up-windows.

(defun clone-indirect-buffer-other-frame (newname display-flag &optional norecord)
  "Like `clone-indirect-buffer' but display in another window."
  (interactive
   (progn
     (if (get major-mode 'no-clone-indirect)
     (error "Cannot indirectly clone a buffer in %s mode" mode-name))
     (list (if current-prefix-arg
           (read-buffer "Name of indirect buffer: " (current-buffer)))
       t)))
  ;; (let ((pop-up-windows t))
  (let ((pop-up-frames t)) ; <==========
    (clone-indirect-buffer newname display-flag norecord)))


问:
How to disable Excel built-in RibbonButton in Ribbon (Visual Designer)?
Is it possible to set an excel 2010 built in RibbonButton to enabled=false from an excel VSTO Add-In?

答:
Here is a sample for Word, using Ribbon XML. I don't think you can use the ribbon designer for this. The same thing should work in Excel as well.

```<code><?xml version="1.0" encoding="UTF-8"?>
<customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui" onLoad="Ribbon_Load">
  <commands>
    <command idMso="Font" enabled="false" />
  </commands>
</customUI>
</code>```

This disables the command, which includes not just the buttons in the ribbon, but also any other way it could be triggered, e.g. through a keyboard shortcut.

If you want to do anything more specific you may have to re-create standard ribbons or ribbon groups. E.g. you can't just disable Font while leaving all other placements enabled. You would have to hide the standard Home tab and re-create it but with your specific changes (disabled, missing, etc.).

Body:
Here is a sample for Word, using Ribbon XML. I don't think you can use the ribbon designer for this. The same thing should work in Excel as well.

<?xml version="1.0" encoding="UTF-8"?>
<customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui" onLoad="Ribbon_Load">
  <commands>
    <command idMso="Font" enabled="false" />
  </commands>
</customUI>

This disables the command, which includes not just the buttons in the ribbon, but also any other way it could be triggered, e.g. through a keyboard shortcut.

If you want to do anything more specific you may have to re-create standard ribbons or ribbon groups. E.g. you can't just disable Font while leaving all other placements enabled. You would have to hide the standard Home tab and re-create it but with your specific changes (disabled, missing, etc.).


答:
This can be done.  Long lines can be broken over multiple lines by wrapping expressions in parentheses.  Here is where it is explained:

http://www.python.org/dev/peps/pep-0008/

ContentLicense: CC BY-SA 2.5

Title: PEP8 - 80 Characters - Big Integers

Body:
This is somehow related to question about big strings and PEP8.

How can I make my script that has the following line PEP8 compliant ("Maximum Line Length" rule)?

pub_key = {
   'e': 3226833362680126101036263622033066816222202666130162062116461326212012222403311326222666622610430466620224662364142L,
   'n': 226421003861041248462826226103022608220328242204422684232640331238220232226321616266146243302342688266846281802662666622213868114632268211186223606846623310006662260110460620201618186828411322260686632603226636226662262862212140221422102106336342228236361106240226122644614266186283436228208626640846820224661642086022346422443282224682686612228404266842316822624342226666622264826123822122031361242246432886612624262663222232331438863220022020826266366016100422L
}


问:
Database level Trigger on table creation to prevent creation of tables without Primary Keys
I'm trying to come up with a way to prevent analysts from creating tables without a Primary key. I know how to create a database level trigger, and I know how to query to find whether or not a table has a primary key, but I was hoping that SQL Server has a 'Created' table, much in the same way it has 'inserted'/'updated' tables used in ON INSERT/ON UPDATE triggers.

Hypothetically, if SQL Server did have this 'Created' table, my trigger would look like this:

```<code>CREATE TRIGGER PKViolations
ON DATABASE
FOR CREATE_TABLE
AS

IF EXISTS (SELECT 1
           FROM Created
           WHERE OBJECTPROPERTY(OBJECT_ID,'TableHasPrimaryKey') = 0)

    BEGIN
        PRINT 'Please include a Primary Key. Transaction has been rolled back.'
        ROLLBACK;
    END
</code>```

Instructing analysts on importance of primary keys has helped, but tables are still being created without PKs, any insight is greatly appreciated!

答:
You can use EVENTDATA() to get the ObjectName. Then you can use your query to examine if there is a primary key.

```<code>SELECT NewTableName = EVENTDATA().value('(/EVENT_INSTANCE/ObjectName)[1]',  'NVARCHAR(255)')
</code>```

You can read more about EVENTDATA here. https://learn.microsoft.com/en-us/sql/t-sql/functions/eventdata-transact-sql

Here is a fully functional example:

```<code>CREATE TRIGGER PKViolations
ON DATABASE
FOR CREATE_TABLE
AS

    declare @NewTableName nvarchar(255)
    SELECT @NewTableName = EVENTDATA().value('(/EVENT_INSTANCE/ObjectName)[1]',  'NVARCHAR(255)')

    IF OBJECTPROPERTY(OBJECT_ID(@NewTableName),'TableHasPrimaryKey') = 0
    BEGIN
        PRINT 'Please include a Primary Key. Transaction has been rolled back.'
        ROLLBACK;
    END

go
</code>```

Body:
I'm trying to come up with a way to prevent analysts from creating tables without a Primary key. I know how to create a database level trigger, and I know how to query to find whether or not a table has a primary key, but I was hoping that SQL Server has a 'Created' table, much in the same way it has 'inserted'/'updated' tables used in ON INSERT/ON UPDATE triggers.

Hypothetically, if SQL Server did have this 'Created' table, my trigger would look like this:

CREATE TRIGGER PKViolations
ON DATABASE
FOR CREATE_TABLE
AS

IF EXISTS (SELECT 1
           FROM Created
           WHERE OBJECTPROPERTY(OBJECT_ID,'TableHasPrimaryKey') = 0)

    BEGIN
        PRINT 'Please include a Primary Key. Transaction has been rolled back.'
        ROLLBACK;
    END

Instructing analysts on importance of primary keys has helped, but tables are still being created without PKs, any insight is greatly appreciated!

Body:
You can use EVENTDATA() to get the ObjectName. Then you can use your query to examine if there is a primary key.

SELECT NewTableName = EVENTDATA().value('(/EVENT_INSTANCE/ObjectName)[1]',  'NVARCHAR(255)')

You can read more about EVENTDATA here. https://learn.microsoft.com/en-us/sql/t-sql/functions/eventdata-transact-sql

Here is a fully functional example:

CREATE TRIGGER PKViolations
ON DATABASE
FOR CREATE_TABLE
AS

    declare @NewTableName nvarchar(255)
    SELECT @NewTableName = EVENTDATA().value('(/EVENT_INSTANCE/ObjectName)[1]',  'NVARCHAR(255)')

    IF OBJECTPROPERTY(OBJECT_ID(@NewTableName),'TableHasPrimaryKey') = 0
    BEGIN
        PRINT 'Please include a Primary Key. Transaction has been rolled back.'
        ROLLBACK;
    END

go


问:
PGP encryption in windows 2012 R2 server using VB.NET program
We have a windows service program written in vb.NET (framework 4). This service will pick up the file from path A, processes it and creates output file(XML file) to path B. This output file is in .IN type.

We want to perform encryption on this .IN file and convert it into .PGP type which is later picked up through FTP.
Previously we were using cryptocx v5 in our code in windows 2003 server and here encryption worked perfectly.
Now we have migrated our application to windows 2012 R2 server (64 bit) and here while performing encryption we are getting an error pop up.

We tried installing cryptocx v5 and V7 software’s, but we are getting same error pop up.

How to perform encryption (.pgp) on our windows 2012 R2 server (.net Framework 4)?

答:
If you just need to encrypt/decrypt/sign using PGP and you're not stuck on using cryptocx I'd suggest you take a look at PGP packages in NuGet.

For example Bouncycastle seems to be pretty popular, and you can find several, helpful resources with a quick search.

I don't know that it's an option, but you might want to consider just encrypting them manually. If you go that route I'd suggest you take a look at gpg4win and pick one of the several user-friendly front ends (I've used kleopatra. It makes things pretty straightforward.)


问:
Convert map to struct
Ok, the title is a little bit misleading. What I'm after is as follows:

```<code>type MyStruct struct {
    id   int
    name string
    age  int
}

func CreateFromMap(m map[string]interface{}) (MyStruct, error) {
    var (
        id   int
        name string
        age  int
        ok   bool
    )
    err := errors.New("Error!")
    id, ok = m["id"].(int)
    if !ok {
        return nil, err
    }
    name, ok = m["name"].(string)
    if !ok {
        return nil, err
    }
    age, ok = m["age"].(int)
    if !ok {
        return nil, err
    }
    return MyStruct{id, name, age}, nil
}
</code>```

Don't ask: Why I'm not using CreateFromMap(int, string, int). That object comes from somewhere else, out of my control.

It's already boring to map each key, value pair in the map to struct properties. But checking if everything is ok or not after each conversion is chaotic.

Is there an easier way of doing this other than reflection?

答:
You can just Marshal/Unmarshal, but property names should match</p>

```<code>func CreateFromMap(m map[string]interface{}) (MyStruct, error) {
    data, _ := json.Marshal(m)
    var result MyStruct
    err := json.Unmarshal(data, &result)
    return result, err
}
</code>```

Title: Convert map to struct

Body:
Ok, the title is a little bit misleading. What I'm after is as follows:

type MyStruct struct {
    id   int
    name string
    age  int
}

func CreateFromMap(m map[string]interface{}) (MyStruct, error) {
    var (
        id   int
        name string
        age  int
        ok   bool
    )
    err := errors.New("Error!")
    id, ok = m["id"].(int)
    if !ok {
        return nil, err
    }
    name, ok = m["name"].(string)
    if !ok {
        return nil, err
    }
    age, ok = m["age"].(int)
    if !ok {
        return nil, err
    }
    return MyStruct{id, name, age}, nil
}

Don't ask: Why I'm not using CreateFromMap(int, string, int). That object comes from somewhere else, out of my control.

It's already boring to map each key, value pair in the map to struct properties. But checking if everything is ok or not after each conversion is chaotic.

Is there an easier way of doing this other than reflection?

Body:
You can just Marshal/Unmarshal, but property names should match

func CreateFromMap(m map[string]interface{}) (MyStruct, error) {
    data, _ := json.Marshal(m)
    var result MyStruct
    err := json.Unmarshal(data, &result)
    return result, err
}


Title: How to Add Serial No in Select Statement in Mysql Join

Body:
There is two table in database.

== tblOrder ==
OrderId
Customer

== tblOrderItem ==
OrderItemId
OrderId
ItemId
Qty
Price

My Query :-

SELECT o.OrderId,o.Customer,oi.ItemId,oi.Qty,oi.Price
FROM tblorder o
JOIN tblorderitem oi ON oi.OrderId=o.OrderId

Result :-

+---------+----------+--------+-----+-------+
| OrderId | Customer | ItemId | Qty | Price |
+---------+----------+--------+-----+-------+
|    1001 | john day |    501 |   1 |    10 |
|    1001 | john day |    502 |   2 |     9 |
|    1002 | amy gill |    201 |   5 |     2 |
|    1003 | hardcaur |    501 |   1 |    10 |
|    1003 | hardcaur |    509 |   2 |     5 |
|    1003 | hardcaur |    201 |   2 |     2 |
+---------+----------+--------+-----+-------+

I want to generate SNO and SNOI(Temp Serial No) in select statement so that result will be like this :-

+------+---------+----------+------+--------+-----+-------+
| SNO  | OrderId | Customer | SNOI | ItemId | Qty | Price |
+------+---------+----------+------+--------+-----+-------+
|    1 |    1001 | john day |    1 |    501 |   1 |    10 |
|    1 |    1001 | john day |    2 |    502 |   2 |     9 |
|    2 |    1002 | amy gill |    1 |    201 |   5 |     2 |
|    3 |    1003 | hardcaur |    1 |    501 |   1 |    10 |
|    3 |    1003 | hardcaur |    2 |    509 |   2 |     5 |
|    3 |    1003 | hardcaur |    3 |    201 |   2 |     2 |

What will be my query?

Body:
You can use variables.

 set @ord ='';
 set @val1 =1;
 set @val2 =0;

select SR_No_1, OrderId, Customer, SR_No_2, ItemId, Qty, Price
from
(
SELECT    t.*,
          @val1 := if(@ord=OrderId, @val1+1, 1) as SR_No_2,
          @val2 := if(@ord=OrderId,@val2, @val2+1) as SR_No_1,
          @ord := OrderId
FROM      table1 t
 ) t
ORDER BY  orderId asc;

Result:

+---------+---------+----------+---------+--------+-----+-------+
| SR_No_1 | OrderId | Customer | SR_No_2 | ItemId | Qty | Price |
+---------+---------+----------+---------+--------+-----+-------+
|       1 |    1001 | john day |       1 |    501 |   1 |    10 |
|       1 |    1001 | john day |       2 |    502 |   2 |     9 |
|       2 |    1002 | amy gill |       1 |    201 |   5 |     2 |
|       3 |    1003 | hardcaur |       1 |    501 |   1 |    10 |
|       3 |    1003 | hardcaur |       2 |    509 |   2 |     5 |
|       3 |    1003 | hardcaur |       3 |    201 |   2 |     2 |
+---------+---------+----------+---------+--------+-----+-------+

DEMO

P.S. Kindly note that for demonstration purpose i have inserted data to one table. you can modify the query by introducing the join between 2 tables


问:
S/4HANA Cloud SDK :com.sap.cloud.sdk.s4hana.datamodel.odata.namespaces does not exist
The build is fails due to lack of resource: class com.sap.cloud.sdk.s4hana.datamodel.odata.services.BusinessPartnerService

Do we need to have/create this model classes in our project structure or will SDK take care of this static import?

Error after executing: mvn clean install

答:
There are likely several things happening in parallel here:

Version 1.3.0 of the SAP S/4HANA Cloud SDK moved the entity classes of a service such as BusinessPartner to their own package, in your case, you now need to import com.sap.cloud.sdk.s4hana.datamodel.odata.namespaces.businesspartner.BusinessPartner;.

Furthermore, BusinessPartnerService is now an interface with a default implementation available with DefaultBusinessPartnerService. You need to replace the static access with new DefaultBusinessPartnerService() (or you could use dependency injection). See the release-notes that Akhil already referenced.

There is no email field on the entity BusinessPartner. You need to use the entity AddressEmailAddress and associate it to the business partner via a BusinessPartnerAddress.


问:
How to assign sequence number for a column with duplicated rows
I have a dataset where I want to assign sequence number to a column with duplicated rows, for example:

```<code>variable_1
   x
   x
   y
   y
   x
   x
   x
   z
   z
   z
</code>```

How do I get the result like this:

```<code>variable_1   sequence
     x          1
     y          2
     x          3
     z          4
</code>```

I tried using unique, but I would miss the sequence number for x showing up the second time.

答:
A solution using dplyr and data.table.

```<code>library(dplyr)
library(data.table)

df2 <- df %>%
  mutate(sequence = rleid(variable_1)) %>%
  distinct()
df2
#   variable_1 sequence
# 1          x        1
# 2          y        2
# 3          x        3
# 4          z        4
</code>```

DATA

```<code>df <- read.table(text = "
variable_1
                x
                x
                y
                y
                x
                x
                x
                z
                z
                z
                ", header = TRUE, stringsAsFactors = FALSE)
</code>```

Body:
I have a dataset where I want to assign sequence number to a column with duplicated rows, for example:

variable_1
   x
   x
   y
   y
   x
   x
   x
   z
   z
   z

How do I get the result like this:

variable_1   sequence
     x          1
     y          2
     x          3
     z          4

I tried using unique, but I would miss the sequence number for x showing up the second time.

Body:
A solution using dplyr and data.table.

library(dplyr)
library(data.table)

df2 <- df %>%
  mutate(sequence = rleid(variable_1)) %>%
  distinct()
df2
#   variable_1 sequence
# 1          x        1
# 2          y        2
# 3          x        3
# 4          z        4

DATA

df <- read.table(text = "
variable_1
                x
                x
                y
                y
                x
                x
                x
                z
                z
                z
                ", header = TRUE, stringsAsFactors = FALSE)


问:
Persist and Retrieve State in Prism for Xamarin Forms
We are considering migrating a UWP app to Xamarin Forms. We need to be able to save the state of complex objects such as an order form when the user navigates away and retrieve that state when the user navigates back. We also need to be able to cancel navigation from a viewmodel.

We use MVVM, so my questions are from that context, but we like to think of ourselves as pragmatic rather than zealous about such things.

In UWP we use the Template10 library to save state in the OnNavigatingFrom event. We retrieve the state in the OnNavigatingTo event. This works even when the app back button is clicked.

Xamarin Forms doesn't seem to have built-in events to handle navigating to and from a viewmodel.

Prism for Xamarin Forms has OnNavigatingTo but does not appear to have OnNavigatingFrom. On some pages we use OnNavigatingFrom to prompt the user to save or discard. OnNavigatingFrom can be cancelled in response to a dialog.

It also appears Prism does not handle navigation using the application back button or the hardware back button. We need to be able to handle navigation to and from viewmodels regardless of how the navigation was initiated.

I've spend a couple of weeks researching these issues and testing scenarios in Xamarin Forms. I assume I have missed something in my ignorance. I understand primitive types can be persisted to application properties, but it would be nice if we didn't have to serialize and deserialize complex hierarchical objects ourselves.

Is there a paradigm/framework in the Xamarin Forms world that will:

handle events navigating to and from a viewmodel

allow navigation from a viewmodel to be cancelled in response to a dialog

allow state to be saved navigating from a viewmodel

allow state to be retrieved navigating to a viewmodel

fire navigation events regardless of how the navigation was initiated?

I understand there are many questions in this one question, but we are not looking for individual solutions, but a paradigm or framework which gives us the tools to solve them all in Xamarin Forms, such as T10 does for UWP.

答:
Not sure how long you spent researching Prism for Xamarin.Forms, but it provides everything you said it didn't.

You should start with this video. It's a little old, but it will get you started.

https://www.youtube.com/watch?v=DYRLcqG2BAY

As far as actually persisting the data, that's for you to decide. Prism will give you the hooks to do it.


问:
Issue with offset in loop cycle.Object required
i'm having an issue in my While cycle with an offset.

There's the code:

```<code>    Sub Voucher()

            Dim rangoCargo, rangoTAG, rangoTipo As Range
            Dim archivo As String
            Dim vFound As Boolean

            Dim subFldr As Object
            Dim subsubFldr As Object

            Worksheets("OC").Visible = True
            Worksheets("OC").Select

            Set rangoTAG = Range("B2")
            Set rangoCargo = Range("C2")
            Set rangoTipo = Range("E2")

            Dim fso As Object
            Set fso = VBA.CreateObject("Scripting.FileSystemObject")

            rutaAño = ActiveWorkbook.Path & "\2017"
            rutaFARFI = rutaAño & "\FAR_FI"
            rutaFARTA = rutaAño & "\FAR_TA"
            rutaFARTN = rutaAño & "\FAR_TN"
            rutaGOPMTI = rutaAño & "\GOPM_TI"

            rutaDocumentos = ActiveWorkbook.Path & "\SGSCM\02_ORDENES_DE_COMPRA\"

            If Dir(ActiveWorkbook.Path & "\2017", vbDirectory) = "" Then 'This checks if a main folder exist, do the procedure, nothing special

                MsgBox "Please, Check if the [2017] Folder Exists"

            Else 'if it exists:

                Do While Not IsEmpty(rangoCargo) 'Starts the cycle

                    If rangoTipo = "C" Then 'If Letter Type is C it loops through a folder until it finds the "C" Like one.

                        rangoCargo = Left(rangoCargo, 6)

                        For Each subFldr In CreateObject("Scripting.FileSystemobject").GetFolder(rutaFARFI).Subfolders
                            For Each subsubFldr In CreateObject("Scripting.FileSystemobject").GetFolder(subFldr).Subfolders
                                Debug.Print subsubFldr

                                vFound = False

                                If subsubFldr Like "*\" & rangoTipo & rangoTAG Then 'If it finds it, copy and move the file from another folder to it.

                                    vFound = True
                                    cFolder = subsubFldr.Path

                                    archivo = Dir(rutaDocumentos & "\" & rangoCargo & "\*.*")
                                    Do Until archivo = ""

                                        Call fso.copyFile(rutaDocumentos & "\" & rangoCargo & "\" & archivo, cFolder & "\" & archivo)
                                        archivo = Dir

                                    Loop

                                End If 'ends subsubFldr

                                If vFound = True Then
                                    Exit For
                                End If

                            Next subsubFldr

                            If vFound = True Then
                                Exit For
                            End If
                        Next subFldr

                    ElseIf rangoTipo = "P" Then

                        archivo = Dir(rutaDocumentos & "\" & rangoCargo & "\*.*")
                        Do Until archivo = ""

                            Call fso.copyFile(rutaDocumentos & "\" & rangoCargo & "\" & archivo, rutaFARFI & "\" & rangoTipo & "\" & rangoTAG & "\" & archivo)
                            archivo = Dir
                        Loop

                    End If

                    Set rangoTAG = rangoTAG.Offset(1, 0)
                    Set rangoTipo = rangoTipo.Offset(1, 0)
                    Set rangoCargo = rangoCargo.Offset(1, 0) 'THIS OFFSET HAS THE PROBLEM
                'When the command Set rangoCargo = rangoCargo.Offset(1, 0) executes it throws the next message: Run Time Error '424' object required

                Loop 'The cycle end when it founds ""

            End If 'End if the folder [2017] doesn't exists

        End Sub
</code>```

Excel Worksheet (OC)

Ok, here goes the problem:

I'm using a Cycle to loop between a Sheet that contains a string of a "Folder" in his cellValue, in this case Document Like. I've done a Left(rangoCargo, 6) to catch the exact number of chars equals to the folder that contains the files to copy them and later move them to the new folder.

As you can see in the Document Like Column the first value is "E-0001-997818". Theres a main folder that contains another sub folders, we will call the Main folder OC. From OC i must get a document and move it to the searched folder (I.E E-001), so, E-001 contains the documents that must be moved to a new folder but, the E-001 is called like that, and in the "Document Like" column they're called like that but a lot of extra numbers (i don't know why, the corporation give the excel file to me and i must work with it without modificating it).
So i did a Left() to get the exactly string of the folder to locate them, and there's is the problem, i don't know how to fix the "It Requires an Object" error.
I'm almost sure that is because of the Offset, but i don't know how to fix it.

So, any help could be very useful.Thank you for your time guys.

答:
Ok, I think I've found your issue.

When you dimension variables like this;

```<code>Dim rangoCargo, rangoTAG, rangoTipo As Range
</code>```

you would think that they are all of type Range, but this is false.  the first two will be of type variant because they are not declared as any type and the last will be the only variable declared as a Range type.

You should change your declarations to either of the following and then your code should work.

```<code>Dim rangoCargo As Range, rangoTAG As Range, rangoTipo As Range
</code>```

or

```<code>Dim rangoCargo As Range
Dim rangoTAG As Range
Dim rangoTipo As Range
</code>```

since rangoCargo was declared as a variant it doesn't know that it's a Range object hence the reason why you're getting the error.  The first time you set the variable to Range("C2") it is not actually setting the range but the value its self.  To test, immediately after the first time you set rangoCargo add this code and it should fail;

```<code>p = rangoCargo.Value
</code>```

It will give you the same error. Run-time error '424': Object required

Hope that helps.  Remember if this fixes your issue to mark as answer. So others can see what to do to fix the issue if they come across it too.

Body:
i'm having an issue in my While cycle with an offset.

There's the code:

    Sub Voucher()

            Dim rangoCargo, rangoTAG, rangoTipo As Range
            Dim archivo As String
            Dim vFound As Boolean

            Dim subFldr As Object
            Dim subsubFldr As Object

            Worksheets("OC").Visible = True
            Worksheets("OC").Select

            Set rangoTAG = Range("B2")
            Set rangoCargo = Range("C2")
            Set rangoTipo = Range("E2")

            Dim fso As Object
            Set fso = VBA.CreateObject("Scripting.FileSystemObject")

            rutaAño = ActiveWorkbook.Path & "\2017"
            rutaFARFI = rutaAño & "\FAR_FI"
            rutaFARTA = rutaAño & "\FAR_TA"
            rutaFARTN = rutaAño & "\FAR_TN"
            rutaGOPMTI = rutaAño & "\GOPM_TI"

            rutaDocumentos = ActiveWorkbook.Path & "\SGSCM\02_ORDENES_DE_COMPRA\"

            If Dir(ActiveWorkbook.Path & "\2017", vbDirectory) = "" Then 'This checks if a main folder exist, do the procedure, nothing special

                MsgBox "Please, Check if the [2017] Folder Exists"

            Else 'if it exists:

                Do While Not IsEmpty(rangoCargo) 'Starts the cycle

                    If rangoTipo = "C" Then 'If Letter Type is C it loops through a folder until it finds the "C" Like one.

                        rangoCargo = Left(rangoCargo, 6)

                        For Each subFldr In CreateObject("Scripting.FileSystemobject").GetFolder(rutaFARFI).Subfolders
                            For Each subsubFldr In CreateObject("Scripting.FileSystemobject").GetFolder(subFldr).Subfolders
                                Debug.Print subsubFldr

                                vFound = False

                                If subsubFldr Like "*\" & rangoTipo & rangoTAG Then 'If it finds it, copy and move the file from another folder to it.

                                    vFound = True
                                    cFolder = subsubFldr.Path

                                    archivo = Dir(rutaDocumentos & "\" & rangoCargo & "\*.*")
                                    Do Until archivo = ""

                                        Call fso.copyFile(rutaDocumentos & "\" & rangoCargo & "\" & archivo, cFolder & "\" & archivo)
                                        archivo = Dir

                                    Loop

                                End If 'ends subsubFldr

                                If vFound = True Then
                                    Exit For
                                End If

                            Next subsubFldr

                            If vFound = True Then
                                Exit For
                            End If
                        Next subFldr

                    ElseIf rangoTipo = "P" Then

                        archivo = Dir(rutaDocumentos & "\" & rangoCargo & "\*.*")
                        Do Until archivo = ""

                            Call fso.copyFile(rutaDocumentos & "\" & rangoCargo & "\" & archivo, rutaFARFI & "\" & rangoTipo & "\" & rangoTAG & "\" & archivo)
                            archivo = Dir
                        Loop

                    End If

                    Set rangoTAG = rangoTAG.Offset(1, 0)
                    Set rangoTipo = rangoTipo.Offset(1, 0)
                    Set rangoCargo = rangoCargo.Offset(1, 0) 'THIS OFFSET HAS THE PROBLEM
                'When the command Set rangoCargo = rangoCargo.Offset(1, 0) executes it throws the next message: Run Time Error '424' object required

                Loop 'The cycle end when it founds ""

            End If 'End if the folder [2017] doesn't exists

        End Sub

Excel Worksheet (OC)

Ok, here goes the problem:

I'm using a Cycle to loop between a Sheet that contains a string of a "Folder" in his cellValue, in this case Document Like. I've done a Left(rangoCargo, 6) to catch the exact number of chars equals to the folder that contains the files to copy them and later move them to the new folder.

As you can see in the Document Like Column the first value is "E-0001-997818". Theres a main folder that contains another sub folders, we will call the Main folder OC. From OC i must get a document and move it to the searched folder (I.E E-001), so, E-001 contains the documents that must be moved to a new folder but, the E-001 is called like that, and in the "Document Like" column they're called like that but a lot of extra numbers (i don't know why, the corporation give the excel file to me and i must work with it without modificating it).
So i did a Left() to get the exactly string of the folder to locate them, and there's is the problem, i don't know how to fix the "It Requires an Object" error.
I'm almost sure that is because of the Offset, but i don't know how to fix it.

So, any help could be very useful.Thank you for your time guys.

Body:
Ok, I think I've found your issue.

When you dimension variables like this;

Dim rangoCargo, rangoTAG, rangoTipo As Range

you would think that they are all of type Range, but this is false.  the first two will be of type variant because they are not declared as any type and the last will be the only variable declared as a Range type.

You should change your declarations to either of the following and then your code should work.

Dim rangoCargo As Range, rangoTAG As Range, rangoTipo As Range

or

Dim rangoCargo As Range
Dim rangoTAG As Range
Dim rangoTipo As Range

since rangoCargo was declared as a variant it doesn't know that it's a Range object hence the reason why you're getting the error.  The first time you set the variable to Range("C2") it is not actually setting the range but the value its self.  To test, immediately after the first time you set rangoCargo add this code and it should fail;

p = rangoCargo.Value

It will give you the same error. Run-time error '424': Object required

Hope that helps.  Remember if this fixes your issue to mark as answer. So others can see what to do to fix the issue if they come across it too.


问:
How to update variable in IO/access variable made in if statement in haskell
I have some code where I create an object at the beginning. Then I want to run various updates on the object depending on different commands.

```<code>main = do
    putStrLn "Enter command, c x y, d x y"
    s <- getLine
    let object = newObject
    if head s == 'c' then
        let object2 = updateObject object s in
        print object
    else if head s == 'd' then
        let object2 = updateObject object s in
        print object
    else do
        print "Error, try again"
        main
    putStrLn "Enter new command"
    c <- getLine
    print $ updateObject object2 c
</code>```

Error:

```<code>Variable not in scope: object2 :: Object
</code>```

How do I make the object "global" for the main function so that changes done to the object inside the if statements can be used later?

How can I do this in a better way?

答:
There are many ways to do that: functions like Object -> Object, monad State, IORef and etc. The way depends on what do you want to do exactly.

The most simplest way (for beginner) is to do that by the function, which generate updated version of your object.

For example:

```<code>updateObject :: Command -> Object -> Maybe Object
updateObject command initialObject = case command of
    'c':_ -> Just $ ... -- update initialObject by the 'c' command
    'd':_ -> Just $ ... -- update initialObject by the 'd' command
    _     -> Nothing    -- invalid command

main = do
    putStrLn "Enter command, c x y, d x y"
    command <- getLine
    case updateObject command newObject of
        Just updatedObject -> print updatedObject
        Nothing -> do
            print "Error, try again"
            main
</code>```

Body:
I have some code where I create an object at the beginning. Then I want to run various updates on the object depending on different commands.

main = do
    putStrLn "Enter command, c x y, d x y"
    s <- getLine
    let object = newObject
    if head s == 'c' then
        let object2 = updateObject object s in
        print object
    else if head s == 'd' then
        let object2 = updateObject object s in
        print object
    else do
        print "Error, try again"
        main
    putStrLn "Enter new command"
    c <- getLine
    print $ updateObject object2 c

Error:

Variable not in scope: object2 :: Object

How do I make the object "global" for the main function so that changes done to the object inside the if statements can be used later?

How can I do this in a better way?

Body:
There are many ways to do that: functions like Object -> Object, monad State, IORef and etc. The way depends on what do you want to do exactly.

The most simplest way (for beginner) is to do that by the function, which generate updated version of your object.

For example:

updateObject :: Command -> Object -> Maybe Object
updateObject command initialObject = case command of
    'c':_ -> Just $ ... -- update initialObject by the 'c' command
    'd':_ -> Just $ ... -- update initialObject by the 'd' command
    _     -> Nothing    -- invalid command

main = do
    putStrLn "Enter command, c x y, d x y"
    command <- getLine
    case updateObject command newObject of
        Just updatedObject -> print updatedObject
        Nothing -> do
            print "Error, try again"
            main


问:
Deserializing json in Angular 2/4 using HttpClientModule
So I'm getting the following JSON structure from my asp.net core api:

```<code>{
  "contentType": null,
  "serializerSettings": null,
  "statusCode": null,
  "value": {
     "productName": "Test",
     "shortDescription": "Test 123",
     "imageUri": "https://bla.com/bla",
     "productCode": null,
     "continuationToken": null
  }
}
</code>```

I have the following typescript function that invokes the API to get the above response:

```<code>public externalProduct: ProductVM;

getProductExternal(code: string): Observable<ProductVM> {
    return this.http.get("api/product?productCode=" + code)
        .map((data: ProductVM) => {
            this.externalProduct = data; //not working...
            console.log("DATA: " + data);
            console.log("DATA: " + data['value']);
            return data;
        });
}
</code>```

ProductVM:

```<code>export interface ProductVM {

    productName: string;
    shortDescription: string;
    imageUri: string;
    productCode: string;
    continuationToken: string;
}
</code>```

My problem is that I can't deserialize it to ProductVM. The console logs just produce [object Object]

How can I actually map the contents of the value in my json response to a ProductVM object?

Is it wrong to say that data is a ProductVM in the map function? I have tried lots of different combinations but I cannot get it to work!

I'm unsure whether I can somehow automatically tell angular to map the value array in the json response to a ProductVM object or if I should provide a constructor to the ProductVM class (it's an interface right now), and extract the specific values in the json manually?

答:
Have you tried to replace

```<code>this.externalProduct = data;
</code>```

with

```<code>this.externalProduct = data.json();
</code>```

Hope it helps

Body:
So I'm getting the following JSON structure from my asp.net core api:

{
  "contentType": null,
  "serializerSettings": null,
  "statusCode": null,
  "value": {
     "productName": "Test",
     "shortDescription": "Test 123",
     "imageUri": "https://bla.com/bla",
     "productCode": null,
     "continuationToken": null
  }
}

I have the following typescript function that invokes the API to get the above response:

public externalProduct: ProductVM;

getProductExternal(code: string): Observable<ProductVM> {
    return this.http.get("api/product?productCode=" + code)
        .map((data: ProductVM) => {
            this.externalProduct = data; //not working...
            console.log("DATA: " + data);
            console.log("DATA: " + data['value']);
            return data;
        });
}

ProductVM:

export interface ProductVM {

    productName: string;
    shortDescription: string;
    imageUri: string;
    productCode: string;
    continuationToken: string;
}

My problem is that I can't deserialize it to ProductVM. The console logs just produce [object Object]

How can I actually map the contents of the value in my json response to a ProductVM object?

Is it wrong to say that data is a ProductVM in the map function? I have tried lots of different combinations but I cannot get it to work!

I'm unsure whether I can somehow automatically tell angular to map the value array in the json response to a ProductVM object or if I should provide a constructor to the ProductVM class (it's an interface right now), and extract the specific values in the json manually?

Body:
Have you tried to replace

this.externalProduct = data;

with

this.externalProduct = data.json();

Hope it helps


问:
pydev debug python program started by another program
I have a C++ program that starts two instances of a python program in separate processes. I have a problem in the python program which causes it to not to display any logging information. The python program instances communicate with the C++ program via Stdin and Stdout/Stderr. I want to, if possible, to run one instance of the program under the Pydev debugger since the C++ program is complaining about receiving invalid input from both of the python programs. The python program can do nothing without communication to the C++ program so running the python program in isolation does not help.

Because Stdin and Stdout are used for inter-process communication so I cannot use print() statements but must use python logging but the program seems to be crashing before anything can reach the log file. The python program was working before my last changes so the architecture is functioning OK.

Any suggestions?

答:
My suggestion for debugging the Python program launched from the C++ program would be using the remote debugger feature:

http://www.pydev.org/manual_adv_remote_debugger.html

(that way you can add programatically start the debugger on the python code wherever you'd like without needing to do anything special to launch it).


问:
c# What happens if I use code a .NET 3.5 function on a machine that has .Net 2 installed
Just out of interest, if I built some code using the Enumerable.Distinct function which appeared in .Net 3.5 and then ran it on a machine with .Net 2.0 on it, what would happen?</p>

答:
.NET 3.5 is essentially .NET 2.0 + some extra assemblies.

If those extra assemblies aren't installed, ie. .NET 3.5 isn't installed, then your program will fail to load those assemblies when needed.

If you have somehow managed to steer clear of using those assemblies, then presumably your program will function just fine, but I'd say that would be the exception to the rule. For your specific example, at the point where your program uses .NET 3.5 code for the first time, you would get an exception.

In short, make sure .NET 3.5 (SP1) is installed on the target machines.


问:
Python - Table not found error when using SQlite3 with Daemonize
I have a slack bot that accesses an SQlite database. When I run the bot in the foreground, everything works but when I run it as a daemon, it seems to connect to my database but then returns "table not found" on every query that I run.

The thing is, this used to work until my latest version and I can't find what changed, so I made a stripped down version as a test but I still have the same problem. See below:

```<code>import syslog
import sqlite3
import os
from daemonize import Daemonize
from slackclient import SlackClient
from qatoken import token

#Slack vars
nickname = "NetBot-QA"
dump = "#net-dump-qa"
channel = "#net-alerts-qa"
avatar = ":loader:"

#Daemonize vars
pid = "/tmp/netbot-qa.pid"
app = "net-bot-qa"
syslog.openlog('netbot', 0, syslog.LOG_LOCAL4 )

###################################################### MAIN
def main():

    sc = SlackClient(token)
    sc.api_call("chat.postMessage", username=nickname, channel=dump, text="{0}/net-alerts-test.db".format(os.path.dirname(__file__)), icon_emoji=avatar)

    try:
        conn = sqlite3.connect("{0}/net-alerts-test.db".format(os.path.dirname(__file__)))
        c = conn.cursor()
        c.execute("SELECT * from maint_calendar")
        sc.api_call("chat.postMessage", username=nickname, channel=dump, text="made it!", icon_emoji=avatar)
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception, e:
        sc.api_call("chat.postMessage", username=nickname, channel=dump, text="The bot crashed", icon_emoji=avatar)
        syslog.syslog("error: {0}".format(e))

########################################################################################
#main()
########################################################################################
#main()
daemon = Daemonize(app=app, pid=pid, action=main)
daemon.start()
</code>```

If I run main(), I get the slack message "Made it!", but if I comment it out and run daemon.start() instead, I get "The bot crashed".

When I cat /var/log/messages, this is what I see:

```<code>Nov 16 09:47:37 server1 netbot: error: no such table: maint_calendar

[root@server1 net-alerts]# pwd
/opt/bots/net-alerts

[root@server1 net-alerts]# sqlite3 net-alerts-test.db
SQLite version 3.7.17 2013-05-20 00:56:22
sqlite> .schema
CREATE TABLE maint_calendar (start time, finish time, summary text, dc_tag text, provider text, CONSTRAINT start_sum PRIMARY KEY (start, summary));
</code>```

I've also tried running this with a static path to the db but os.path.dirname has worked very well with every other script I use. I found another post saying you have to make the DB connection inside the Daemon context (main()) but I've been doing this from the start. I'm running out of ideas.

答:
It seems to me, that this line:

```<code>conn = sqlite3.connect("{0}/net-alerts-test.db".format(os.path.dirname(__file__)))
</code>```

Is actually connecting to two different sources, depending if you daemonize or just run main().

Just save the file to db in a global variable, which you use later. E.g.:

```<code>DB_PATH = "{0}/net-alerts-test.db".format(os.path.dirname(__file__))
...
def main():

    sc = SlackClient(token)
    sc.api_call("chat.postMessage", username=nickname, channel=dump, text="{0}/net-alerts-test.db".format(os.path.dirname(__file__)), icon_emoji=avatar)

    try:
        conn = sqlite3.connect(DB_PATH)
</code>```

Body:
I have a slack bot that accesses an SQlite database. When I run the bot in the foreground, everything works but when I run it as a daemon, it seems to connect to my database but then returns "table not found" on every query that I run.

The thing is, this used to work until my latest version and I can't find what changed, so I made a stripped down version as a test but I still have the same problem. See below:

import syslog
import sqlite3
import os
from daemonize import Daemonize
from slackclient import SlackClient
from qatoken import token

#Slack vars
nickname = "NetBot-QA"
dump = "#net-dump-qa"
channel = "#net-alerts-qa"
avatar = ":loader:"

#Daemonize vars
pid = "/tmp/netbot-qa.pid"
app = "net-bot-qa"
syslog.openlog('netbot', 0, syslog.LOG_LOCAL4 )

###################################################### MAIN
def main():

    sc = SlackClient(token)
    sc.api_call("chat.postMessage", username=nickname, channel=dump, text="{0}/net-alerts-test.db".format(os.path.dirname(__file__)), icon_emoji=avatar)

    try:
        conn = sqlite3.connect("{0}/net-alerts-test.db".format(os.path.dirname(__file__)))
        c = conn.cursor()
        c.execute("SELECT * from maint_calendar")
        sc.api_call("chat.postMessage", username=nickname, channel=dump, text="made it!", icon_emoji=avatar)
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception, e:
        sc.api_call("chat.postMessage", username=nickname, channel=dump, text="The bot crashed", icon_emoji=avatar)
        syslog.syslog("error: {0}".format(e))

########################################################################################
#main()
########################################################################################
#main()
daemon = Daemonize(app=app, pid=pid, action=main)
daemon.start()

If I run main(), I get the slack message "Made it!", but if I comment it out and run daemon.start() instead, I get "The bot crashed".

When I cat /var/log/messages, this is what I see:

Nov 16 09:47:37 server1 netbot: error: no such table: maint_calendar

[root@server1 net-alerts]# pwd
/opt/bots/net-alerts

[root@server1 net-alerts]# sqlite3 net-alerts-test.db
SQLite version 3.7.17 2013-05-20 00:56:22
sqlite> .schema
CREATE TABLE maint_calendar (start time, finish time, summary text, dc_tag text, provider text, CONSTRAINT start_sum PRIMARY KEY (start, summary));

I've also tried running this with a static path to the db but os.path.dirname has worked very well with every other script I use. I found another post saying you have to make the DB connection inside the Daemon context (main()) but I've been doing this from the start. I'm running out of ideas.

Body:
It seems to me, that this line:

conn = sqlite3.connect("{0}/net-alerts-test.db".format(os.path.dirname(__file__)))

Is actually connecting to two different sources, depending if you daemonize or just run main().

Just save the file to db in a global variable, which you use later. E.g.:

DB_PATH = "{0}/net-alerts-test.db".format(os.path.dirname(__file__))
...
def main():

    sc = SlackClient(token)
    sc.api_call("chat.postMessage", username=nickname, channel=dump, text="{0}/net-alerts-test.db".format(os.path.dirname(__file__)), icon_emoji=avatar)

    try:
        conn = sqlite3.connect(DB_PATH)


问:
protobuf gradle plugin does not compile
I'm trying to compile protobuf files using the gradle plugin, but I get the following error:

```<code>java.io.IOException: Can't write [/Users/elavi/dev/sdk3/android/showcaseapp/build/intermediates/multi-dex/debug/componentClasses.jar]
(Can't read [/Users/elavi/.gradle/caches/modules-2/files-2.1/com.google.protobuf/protobuf-java/3.0.0/6d325aa7c921661d84577c0a93d82da4df9fa4c8/protobuf-java-3.0.0.jar(;;;;;;**.class)]
(Duplicate zip entry [protobuf-java-3.0.0.jar:com/google/protobuf/ExperimentalApi.class]))
</code>```

Not sure why this happens...
The protobuf files are generated correctly, as expected, but then the final step fails with this weird error.

This is my gradle file:

```<code>apply plugin: 'com.android.library'
apply plugin: 'com.google.protobuf'
apply plugin: 'idea'

group = GROUP
version = VERSION_NAME

apply from: 'versioning.gradle'

buildscript {
  repositories {
    mavenCentral()
  }
}

android {
  compileSdkVersion 26
  buildToolsVersion '26.0.2'
  flavorDimensions "default"

  defaultConfig {
    minSdkVersion 15
    targetSdkVersion 26
    versionCode buildVersionCode()
    versionName VERSION_NAME
    consumerProguardFiles 'tangram-proguard-rules.txt'
  }

  // Add proto files location to be used with the protobuf plugin
  sourceSets {
    main {
      proto {
        srcDir '../../common/vendored/proto'
      }
    }
  }
}

dependencies {
  compile 'com.google.protobuf:protobuf-lite:3.0.0'
  compile 'io.grpc:grpc-stub:1.6.1'
  compile 'io.grpc:grpc-protobuf:1.0.0-pre2'
  compile 'javax.annotation:javax.annotation-api:1.2'

  compile 'com.squareup.okhttp3:okhttp:3.9.0'
  compile 'com.android.support:support-annotations:27.0.0'

  implementation project(':core')
}

// Protobuf configuration. Taken from the documentation: https://github.com/google/protobuf-gradle-plugin
protobuf {

  protoc {
    artifact = 'com.google.protobuf:protoc:3.0.0'   }   plugins {
    javalite {
      artifact = 'com.google.protobuf:protoc-gen-javalite:3.0.0'
    }
    grpc {
      artifact = 'io.grpc:protoc-gen-grpc-java:1.0.0-pre2'
    }   }   generateProtoTasks {
    all().each { task ->
      task.builtins {
        remove java
      }
      task.plugins {
        javalite { }
        grpc {
          option 'lite'
        }
      }
    }   }   generatedFilesBaseDir = "$projectDir/build/gen" }

clean {   delete protobuf.generatedFilesBaseDir }

idea {   module {
    sourceDirs += file("${protobuf.generatedFilesBaseDir}/main/java");
    sourceDirs += file("${protobuf.generatedFilesBaseDir}/main/grpc");   } }

//apply from: file('gradle-mvn-push.gradle')
</code>```

I simply added what's written in the protobuf readme (https://github.com/google/protobuf-gradle-plugin), didn't do any fancy stuff...

答:
maybe you should remove compile 'com.google.protobuf:protobuf-lite:3.0.0' entry on dependencies section, also you have duplicated entries and some config on last versions are missing. For other side maybe the path for proto sources have issues, my protos are src/main/proto but I only declared proto alone.  My brief config is next:

app build.gradle:

```<code>apply plugin: 'com.google.protobuf'

android {
    ...
    sourceSets {
        main {
          proto {
          }
        }
    }
    ...
    configurations.all {
      resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')

    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'io.grpc:grpc-okhttp:1.10.0'
    implementation 'io.grpc:grpc-protobuf-lite:1.10.0'
    implementation 'io.grpc:grpc-stub:1.10.0'
    implementation 'javax.annotation:javax.annotation-api:1.2'
    // full protobuf (optional)
    // protobuf 'com.google.protobuf:protobuf-java:3.4.0'
    ...

}

protobuf {
    protoc {
        artifact = "com.google.protobuf:protoc:3.0.2"
    }
    plugins {
        grpc {
            artifact = 'io.grpc:protoc-gen-grpc-java:1.1.2'
        }
        javalite {
            artifact = "com.google.protobuf:protoc-gen-javalite:3.0.0"
        }
    }
    generateProtoTasks {
        all().each { task ->
            task.plugins {
                javalite {}
                grpc {
                    // Options added to --grpc_out
                    option 'lite'
                }
            }
        }
    }
    generatedFilesBaseDir = "$projectDir/build/generated"
}
</code>```

main project build.gradle:

```<code>buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath "com.google.protobuf:protobuf-gradle-plugin:0.8.2"
        ...
    }
}
</code>```

Title: protobuf gradle plugin does not compile

Body:
I'm trying to compile protobuf files using the gradle plugin, but I get the following error:

java.io.IOException: Can't write [/Users/elavi/dev/sdk3/android/showcaseapp/build/intermediates/multi-dex/debug/componentClasses.jar]
(Can't read [/Users/elavi/.gradle/caches/modules-2/files-2.1/com.google.protobuf/protobuf-java/3.0.0/6d325aa7c921661d84577c0a93d82da4df9fa4c8/protobuf-java-3.0.0.jar(;;;;;;**.class)]
(Duplicate zip entry [protobuf-java-3.0.0.jar:com/google/protobuf/ExperimentalApi.class]))

Not sure why this happens...
The protobuf files are generated correctly, as expected, but then the final step fails with this weird error.

This is my gradle file:

apply plugin: 'com.android.library'
apply plugin: 'com.google.protobuf'
apply plugin: 'idea'

group = GROUP
version = VERSION_NAME

apply from: 'versioning.gradle'

buildscript {
  repositories {
    mavenCentral()
  }
}

android {
  compileSdkVersion 26
  buildToolsVersion '26.0.2'
  flavorDimensions "default"

  defaultConfig {
    minSdkVersion 15
    targetSdkVersion 26
    versionCode buildVersionCode()
    versionName VERSION_NAME
    consumerProguardFiles 'tangram-proguard-rules.txt'
  }

  // Add proto files location to be used with the protobuf plugin
  sourceSets {
    main {
      proto {
        srcDir '../../common/vendored/proto'
      }
    }
  }
}

dependencies {
  compile 'com.google.protobuf:protobuf-lite:3.0.0'
  compile 'io.grpc:grpc-stub:1.6.1'
  compile 'io.grpc:grpc-protobuf:1.0.0-pre2'
  compile 'javax.annotation:javax.annotation-api:1.2'

  compile 'com.squareup.okhttp3:okhttp:3.9.0'
  compile 'com.android.support:support-annotations:27.0.0'

  implementation project(':core')
}

// Protobuf configuration. Taken from the documentation: https://github.com/google/protobuf-gradle-plugin
protobuf {

  protoc {
    artifact = 'com.google.protobuf:protoc:3.0.0'   }   plugins {
    javalite {
      artifact = 'com.google.protobuf:protoc-gen-javalite:3.0.0'
    }
    grpc {
      artifact = 'io.grpc:protoc-gen-grpc-java:1.0.0-pre2'
    }   }   generateProtoTasks {
    all().each { task ->
      task.builtins {
        remove java
      }
      task.plugins {
        javalite { }
        grpc {
          option 'lite'
        }
      }
    }   }   generatedFilesBaseDir = "$projectDir/build/gen" }

clean {   delete protobuf.generatedFilesBaseDir }

idea {   module {
    sourceDirs += file("${protobuf.generatedFilesBaseDir}/main/java");
    sourceDirs += file("${protobuf.generatedFilesBaseDir}/main/grpc");   } }

//apply from: file('gradle-mvn-push.gradle')

I simply added what's written in the protobuf readme (https://github.com/google/protobuf-gradle-plugin), didn't do any fancy stuff...

Body:
maybe you should remove compile 'com.google.protobuf:protobuf-lite:3.0.0' entry on dependencies section, also you have duplicated entries and some config on last versions are missing. For other side maybe the path for proto sources have issues, my protos are src/main/proto but I only declared proto alone.  My brief config is next:

app build.gradle:

apply plugin: 'com.google.protobuf'

android {
    ...
    sourceSets {
        main {
          proto {
          }
        }
    }
    ...
    configurations.all {
      resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')

    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'io.grpc:grpc-okhttp:1.10.0'
    implementation 'io.grpc:grpc-protobuf-lite:1.10.0'
    implementation 'io.grpc:grpc-stub:1.10.0'
    implementation 'javax.annotation:javax.annotation-api:1.2'
    // full protobuf (optional)
    // protobuf 'com.google.protobuf:protobuf-java:3.4.0'
    ...

}

protobuf {
    protoc {
        artifact = "com.google.protobuf:protoc:3.0.2"
    }
    plugins {
        grpc {
            artifact = 'io.grpc:protoc-gen-grpc-java:1.1.2'
        }
        javalite {
            artifact = "com.google.protobuf:protoc-gen-javalite:3.0.0"
        }
    }
    generateProtoTasks {
        all().each { task ->
            task.plugins {
                javalite {}
                grpc {
                    // Options added to --grpc_out
                    option 'lite'
                }
            }
        }
    }
    generatedFilesBaseDir = "$projectDir/build/generated"
}

main project build.gradle:

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath "com.google.protobuf:protobuf-gradle-plugin:0.8.2"
        ...
    }
}

ContentLicense: CC BY-SA 4.0


问:
PugiXML extracting data from recursive xml_tree_walker
I'm trying to extract data from an XML that looks as shown in the image below using pugiXML traverse function. i'm able to print out all the data from the XML file using this function, however im not able to extract and store these into my variables. The main issue is that im not able to get node.name() and node.value() at the same time. node.name() comes in 1 iteration node.value() comes in the iteration after.

```<code>    const char* node_types[] =
{
    "null","Element", "Name", "InstancePath", "InstancePathDepth", "FieldAmount", "DataType", "TypeName", "DataSize", "ArrayTypeName", "LowerBound", "UpperBound", "BitPosition", "IsArray", "IsElementary", "IsProgram", "IsResource", "IsString", "IsStruct", "IsTask"
};

    // tag::impl[]
    struct simple_walker : pugi::xml_tree_walker
    {
        virtual bool for_each(pugi::xml_node& node)
        {

            for (int i = 0; i < depth(); ++i) std::cout << "  "; // indentation

                std::cout << node.name()<<" "<< node.value() << "\n";

            return true; // continue traversal
        }
    };
</code>```

The output is great, same as in the XML file.

答:
You can skip elements that aren't of type node_element and use node.child_value() roughly like this:

```<code>    virtual bool for_each(pugi::xml_node& node)
    {
        if (node.type() != pugi::node_element)
            return true;

        for (int i = 0; i < depth(); ++i) std::cout << "  "; // indentation

        std::cout << node.name()<<" "<< node.child_value() << "\n";

        return true; // continue traversal
    }
</code>```

This is necessary because text (PCDATA) nodes are separate from element nodes: https://pugixml.org/docs/manual.html#node_pcdata

Body:
I'm trying to extract data from an XML that looks as shown in the image below using pugiXML traverse function. i'm able to print out all the data from the XML file using this function, however im not able to extract and store these into my variables. The main issue is that im not able to get node.name() and node.value() at the same time. node.name() comes in 1 iteration node.value() comes in the iteration after.

    const char* node_types[] =
{
    "null","Element", "Name", "InstancePath", "InstancePathDepth", "FieldAmount", "DataType", "TypeName", "DataSize", "ArrayTypeName", "LowerBound", "UpperBound", "BitPosition", "IsArray", "IsElementary", "IsProgram", "IsResource", "IsString", "IsStruct", "IsTask"
};

    // tag::impl[]
    struct simple_walker : pugi::xml_tree_walker
    {
        virtual bool for_each(pugi::xml_node& node)
        {

            for (int i = 0; i < depth(); ++i) std::cout << "  "; // indentation

                std::cout << node.name()<<" "<< node.value() << "\n";

            return true; // continue traversal
        }
    };

The output is great, same as in the XML file.

Body:
You can skip elements that aren't of type node_element and use node.child_value() roughly like this:

    virtual bool for_each(pugi::xml_node& node)
    {
        if (node.type() != pugi::node_element)
            return true;

        for (int i = 0; i < depth(); ++i) std::cout << "  "; // indentation

        std::cout << node.name()<<" "<< node.child_value() << "\n";

        return true; // continue traversal
    }

This is necessary because text (PCDATA) nodes are separate from element nodes: https://pugixml.org/docs/manual.html#node_pcdata


问:
VBA code to search for string then a second string and return lines of data from a text file
I am trying to search through large log files to find a string of text, then if that string is present to find another string of text and then return the next 5 lines of data. I have managed to search the text file for the string and return the 5 lines after however I cannot seem to get the macro to search for both lines of text before returning the 5 lines.

For example if the text file looked like this:

17:42:56: Log File Closed
17:42:56: PrintInvoice: 2
17:42:56: copyReportData:
17:42:56: getNextRptDataID:
17:42:58: CalcDelCharge:
17:42:58:    Sub Total: 3.80
17:42:58:    Del Total: 0.00
17:42:58:    Disc Total: 0.00
17:42:58:    Vat Total: 0.00
17:42:58:    Inv Total: 3.80
18:33:00: CalculateAmtDue:
18:33:00: CalculateChange:
18:33:00: UpdateDelCharge:
18:33:00: UpdateTotals
18:42:58: CalcDelCharge:
18:42:58:    Sub Total: 5.80
18:42:58:    Del Total: 0.00
18:42:58:    Disc Total: 0.00
18:42:58:    Vat Total: 0.00
18:42:58:    Inv Total: 5.80

I want to extract the 5 lines after the first 'CalcDelCharge' as it is follows 'PrintInvoice: 2', which is one of the strings I am also wanting to search for.

The text file contains 'CalcDelCharge' throughout, however I am only interested in the instances when it comes after 'PrintInvoice: 2', which appears much less frequently.

Here is what I have so far

```<code>Dim fn As String, txt As String, delim As String, a() As String
Dim i As Long, ii As Long, iii As Long, x, y
fn = "C:\Documents\tilllogfile.log"
delim = vbTab
temp = CreateObject("Scripting.FileSystemObject").OpenTextFile(fn).ReadAll
x = Split(temp, vbCrLf)
ReDim a(1 To UBound(x) + 1, 1 To 100)
For i = 0 To UBound(x)
    If InStr(1, x(i), "CalcDelCharge", 1) Then
    For ii = 0 To 5
        n = n + 1: y = Split(x(i + ii), delim)
        For iii = 0 To UBound(y)
            a(n, iii + 1) = y(iii)
        Next
    Next
End If
</code>```

This will extract 5 lines after all 'CalcDelCharge' and put it into a spreadsheet for me, I have not been able to narrow it down to the instances when it follows 'PrintInvoice: 2'.

Any help would be greatly appreciated.

Thanks.

答:
You can use Regex, had to use 2 Regexs, however, it might be possible with just one.

```<code>Dim str1 As Variant, str2 As Variant
ReDim str1(0 To 100)
ReDim str2(0 To 100)
Dim objMatches As Object
Dim j As Long, k As Long
j = 0
k = 0
Set objRegExp = CreateObject("VBScript.RegExp") 'New regexp
objRegExp.Pattern = "(?:PrintInvoice: 2)[\s\S]*?(?:\s*(?:\d+:)+\s*[\w\s]*:\s\d.*)+" 'https://regex101.com/r/ChRr4w/1/
objRegExp.Global = True
Set objMatches = objRegExp.Execute(temp)
If objMatches.Count <> 0 Then
    For Each m In objMatches
        str1(j) = m.Value
        j = j + 1
    Next
    ReDim Preserve str1(0 To j - 1)
    For j = LBound(str1) To UBound(str1)
    txt = txt & str1(j) & vbCrLf
    Next j
End If
objRegExp.Pattern = "(?:\d+:)+\s*([\w\s]*:\s\d.*)" 'https://regex101.com/r/CLAL9i/1/
Set objMatches = objRegExp.Execute(txt)
  If objMatches.Count <> 0 Then
    For Each m In objMatches
        str2(k) = m.Submatches(0)
        k = k + 1
    Next
    ReDim Preserve str2(0 To k - 1)
    For k = LBound(str2) To UBound(str2)
    result = result & str2(k) & vbCrLf
    Next k
End If
Debug.Print result
</code>```

Result

Body:
I am trying to search through large log files to find a string of text, then if that string is present to find another string of text and then return the next 5 lines of data. I have managed to search the text file for the string and return the 5 lines after however I cannot seem to get the macro to search for both lines of text before returning the 5 lines.

For example if the text file looked like this:

17:42:56: Log File Closed
17:42:56: PrintInvoice: 2
17:42:56: copyReportData:
17:42:56: getNextRptDataID:
17:42:58: CalcDelCharge:
17:42:58:    Sub Total: 3.80
17:42:58:    Del Total: 0.00
17:42:58:    Disc Total: 0.00
17:42:58:    Vat Total: 0.00
17:42:58:    Inv Total: 3.80
18:33:00: CalculateAmtDue:
18:33:00: CalculateChange:
18:33:00: UpdateDelCharge:
18:33:00: UpdateTotals
18:42:58: CalcDelCharge:
18:42:58:    Sub Total: 5.80
18:42:58:    Del Total: 0.00
18:42:58:    Disc Total: 0.00
18:42:58:    Vat Total: 0.00
18:42:58:    Inv Total: 5.80

I want to extract the 5 lines after the first 'CalcDelCharge' as it is follows 'PrintInvoice: 2', which is one of the strings I am also wanting to search for.

The text file contains 'CalcDelCharge' throughout, however I am only interested in the instances when it comes after 'PrintInvoice: 2', which appears much less frequently.

Here is what I have so far

Dim fn As String, txt As String, delim As String, a() As String
Dim i As Long, ii As Long, iii As Long, x, y
fn = "C:\Documents\tilllogfile.log"
delim = vbTab
temp = CreateObject("Scripting.FileSystemObject").OpenTextFile(fn).ReadAll
x = Split(temp, vbCrLf)
ReDim a(1 To UBound(x) + 1, 1 To 100)
For i = 0 To UBound(x)
    If InStr(1, x(i), "CalcDelCharge", 1) Then
    For ii = 0 To 5
        n = n + 1: y = Split(x(i + ii), delim)
        For iii = 0 To UBound(y)
            a(n, iii + 1) = y(iii)
        Next
    Next
End If

This will extract 5 lines after all 'CalcDelCharge' and put it into a spreadsheet for me, I have not been able to narrow it down to the instances when it follows 'PrintInvoice: 2'.

Any help would be greatly appreciated.

Thanks.

Body:
You can use Regex, had to use 2 Regexs, however, it might be possible with just one.

Dim str1 As Variant, str2 As Variant
ReDim str1(0 To 100)
ReDim str2(0 To 100)
Dim objMatches As Object
Dim j As Long, k As Long
j = 0
k = 0
Set objRegExp = CreateObject("VBScript.RegExp") 'New regexp
objRegExp.Pattern = "(?:PrintInvoice: 2)[\s\S]*?(?:\s*(?:\d+:)+\s*[\w\s]*:\s\d.*)+" 'https://regex101.com/r/ChRr4w/1/
objRegExp.Global = True
Set objMatches = objRegExp.Execute(temp)
If objMatches.Count <> 0 Then
    For Each m In objMatches
        str1(j) = m.Value
        j = j + 1
    Next
    ReDim Preserve str1(0 To j - 1)
    For j = LBound(str1) To UBound(str1)
    txt = txt & str1(j) & vbCrLf
    Next j
End If
objRegExp.Pattern = "(?:\d+:)+\s*([\w\s]*:\s\d.*)" 'https://regex101.com/r/CLAL9i/1/
Set objMatches = objRegExp.Execute(txt)
  If objMatches.Count <> 0 Then
    For Each m In objMatches
        str2(k) = m.Submatches(0)
        k = k + 1
    Next
    ReDim Preserve str2(0 To k - 1)
    For k = LBound(str2) To UBound(str2)
    result = result & str2(k) & vbCrLf
    Next k
End If
Debug.Print result

Result


问:
How to transpose two-dimension arrays in PostgreSQL
A table

```<code>create table matrices(
 matrix text[][] not null);
</code>```

It's value:

```<code> insert into Matrices values
    (array[ ['1','2','3'],
            ['4','5','6'] ]),
    (array[ ['a','b','c'],
            ['d','e','f'] ]);
</code>```

How Could I write SQL to transpose each array, so that the result looks like:

```<code>   matrix
-------------
{{1,4},{2,5},{3,6}}
{{a,d},{b,e},{c,d}}
(2 rows)
</code>```

答:
Simplifying this a little:</p>

```<code>create or replace function array_transpose(arr anyarray)
returns anyarray as
$f$
    select array_agg(
            (select array_agg(arr[i][j] order by i)
                from generate_subscripts(arr, 1) as i)
            order by j
           )
        from generate_subscripts(arr, 2) as j
$f$
language sql immutable;
</code>```

Body:
A table

create table matrices(
 matrix text[][] not null);

It's value:

 insert into Matrices values
    (array[ ['1','2','3'],
            ['4','5','6'] ]),
    (array[ ['a','b','c'],
            ['d','e','f'] ]);

How Could I write SQL to transpose each array, so that the result looks like:

   matrix
-------------
{{1,4},{2,5},{3,6}}
{{a,d},{b,e},{c,d}}
(2 rows)

Body:
Simplifying this a little:

create or replace function array_transpose(arr anyarray)
returns anyarray as
$f$
    select array_agg(
            (select array_agg(arr[i][j] order by i)
                from generate_subscripts(arr, 1) as i)
            order by j
           )
        from generate_subscripts(arr, 2) as j
$f$
language sql immutable;


问:
What FHIR API would enable one to write notes to patient chart - specifically in Epic
I'm looking for a way to write notes into patient chart in Epic. Couldn't find any current FHIR specs about writing notes , but I didn't find this proposal http://wiki.hl7.org/index.php?title=ClinicalNote_FHIR_Resource_Proposal

Are there any other options ?

答:
Great question. I work on the FHIR team at Epic and from a FHIR perspective we are having a similar problem identifying the appropriate place in FHIR to return notes. The proposal you have linked is a starting artifact in defining a new resource for that purpose. Until we determine in the FHIR community if a new spec should be created or an existing FHIR resource should be used, we do not have a FHIR specification to develop support against.

Outside of FHIR, today there are multiple ways to get notes into Epic such as HL7 v2, document based exchange, or something more Epic defined (these are just the ones I'm aware of). Without knowing more about your use case, it is hard to say what option may or may not meet your needs. I recommend you reach out through the contact us at https://open.epic.com/. From this email group they can dive into what integrations would meet your specific scenario and you will have input from a full gamut of integration experts.

And if you are interested in the standards side of things and getting notes in the FHIR specification, I'd encourage you to get involved on chat.fhir.org or any of the HL7 FHIR meetings to provide input on the specification!

*Edited to point to website instead of email.


问:
Object is not subscripable networkx
```<code>import itertools
import copy
import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt
#--
edgelist = pd.read_csv('https://gist.githubusercontent.com/brooksandrew    /e570c38bcc72a8d102422f2af836513b/raw/89c76b2563dbc0e88384719a35cba0dfc04cd522/edgelist_sleeping_giant.csv')
edgelist.head(10)
#--
nodelist = pd.read_csv('https://gist.githubusercontent.com/brooksandrew/f989e10af17fb4c85b11409fea47895b/raw/a3a8da0fa5b094f1ca9d82e1642b384889ae16e8/nodelist_sleeping_giant.csv')
nodelist.head(5)
#--
g = nx.Graph()
#--
for i, elrow in edgelist.iterrows():
g.add_edge(elrow[0], elrow[1], attr_dict=elrow[2:].to_dict())
#--
#print(elrow[0])
#print(elrow[1])
#print(elrow[2:].to_dict())
#--
g.edges(data=True)[0:5]
g.nodes(data=True)[0:10]
#--
print(format(g.number_of_edges()))
print(format(g.number_of_nodes()))
</code>```

Gets me the following error:

```<code>Traceback (most recent call last):
  File "C:/Users/####/Main.py", line 22, in <module>
    g.edges(data=True)[0:5]
TypeError: 'EdgeDataView' object is not subscriptable
</code>```

I have read a couple of other threads but nada.
From my simple understanding the error is caused by [0:5] but im most likely wrong.

I'm a fairly basic coder and am trying to follow this tutorial and i get the error above.

答:
The tutorial is based on a previous version of networkx where g.edges() or g.edges(Data=True) would give you a list of tuples. Lists are subscriptable.

The version you are running has a different output, g.edges gives you an EdgeView property, and g.edges(data=True) an EdgeDataView object which are not subscriptable. To answer your question, you can do:

```<code>list(g.edges(data=True))[0:5]
</code>```

Note: the same is true for g.nodes(): before it was a list now it's a NodeView property not subscriptable. So don't forget to transform it to a list object before trying to add subscripts ([x:x]).

Title: Object is not subscripable networkx

Body:
import itertools
import copy
import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt
#--
edgelist = pd.read_csv('https://gist.githubusercontent.com/brooksandrew    /e570c38bcc72a8d102422f2af836513b/raw/89c76b2563dbc0e88384719a35cba0dfc04cd522/edgelist_sleeping_giant.csv')
edgelist.head(10)
#--
nodelist = pd.read_csv('https://gist.githubusercontent.com/brooksandrew/f989e10af17fb4c85b11409fea47895b/raw/a3a8da0fa5b094f1ca9d82e1642b384889ae16e8/nodelist_sleeping_giant.csv')
nodelist.head(5)
#--
g = nx.Graph()
#--
for i, elrow in edgelist.iterrows():
g.add_edge(elrow[0], elrow[1], attr_dict=elrow[2:].to_dict())
#--
#print(elrow[0])
#print(elrow[1])
#print(elrow[2:].to_dict())
#--
g.edges(data=True)[0:5]
g.nodes(data=True)[0:10]
#--
print(format(g.number_of_edges()))
print(format(g.number_of_nodes()))

Gets me the following error:

Traceback (most recent call last):
  File "C:/Users/####/Main.py", line 22, in <module>
    g.edges(data=True)[0:5]
TypeError: 'EdgeDataView' object is not subscriptable

I have read a couple of other threads but nada.
From my simple understanding the error is caused by [0:5] but im most likely wrong.

I'm a fairly basic coder and am trying to follow this tutorial and i get the error above.

Body:
The tutorial is based on a previous version of networkx where g.edges() or g.edges(Data=True) would give you a list of tuples. Lists are subscriptable.

The version you are running has a different output, g.edges gives you an EdgeView property, and g.edges(data=True) an EdgeDataView object which are not subscriptable. To answer your question, you can do:

list(g.edges(data=True))[0:5]

Note: the same is true for g.nodes(): before it was a list now it's a NodeView property not subscriptable. So don't forget to transform it to a list object before trying to add subscripts ([x:x]).


问:
How to make use of a DataSource via JNDI works?
there's some things I definitely don't understand while using JNDI.

This should simplify our Java developers' life, but this promise sounds false.

The simplest way tu use a database from within an application seems to build each time you need it (so, once per application) a datasource class giving you a connection or session you will use.
It's a tool class written in a few minutes where you have to declare the driver, url, login and password. And it's done.

The recommanded way is to rely on the server resources management, JNDI and all resources such as directory, etc.
But is it really usefull and simple ??

With Tomcat, you have to have to fully describe the datasource in server.xml, then declare it as a resource in context.xml.

server.xml

```<code><GlobalNamingResources>
   <Resource auth="Container" driverClassName="org.postgresql.Driver" maxIdle="30" maxTotal="100" maxWaitMillis="10000" name="jdbc/dsTriasEmployees" password="pwd" type="javax.sql.DataSource" url="jdbc:postgresql://localhost:5432/trias_employees" username="login"/>
</GlobalNamingResources>
</code>```

context.xml

```<code><ResourceLink name="jdbc/dsTriasEmployees" global="jdbc/dsTriasEmployees"
        type="javax.sql.DataSource" />
</code>```

Java side, you should be able to inject it thanks to a Context Lookup code ou a @Resource(mappedBy...) annotation.

```<code>DataSource datasource;

    public Connection connectJNDI() {
        try {
            Context initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup("java:/comp/env");
            datasource = (DataSource) envContext.lookup("jdbc/trias_employees");
            Connection con = datasource.getConnection();
            genericLogger.info("JNDI LOOKUP -> " + con);
            return con;
        } catch (Exception ex) {
            genericLogger.error("JNDI LOOKUP -> " + ex);

        return null;
    }
</code>```

But after doing that, you still have to deal with error messages telling you that it's not enough just like this one :

```<code>javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
</code>```

I have read somewhere that I now should add a JNDI properties file and a declaration in the web.xml file like this :

web.xml

```<code><resource-ref>
      <description>
        DB PostgreSQL
      </description>
      <res-ref-name>
        jdbc/trias_employees
      </res-ref-name>
      <res-type>
        javax.sql.DataSource
      </res-type>
      <res-auth>
        Container
      </res-auth>
</resource-ref>
</code>```

But when I wanna test with jUnit, my web.xml is not usefull...

How many XML and properties files should I write just to respect the best practice that want me to delegate access to the datasource to the server ?
How many times will I have to duplicate all the informations related to url, pool connection, etc. ??

I've read 2 or 3 books on Java EE, 50 posts on StackOverFlow and dozens of forums and all the JNDI Resources HOW-TO on the Tomcat website.
But it still does not work...

Is there somewhere the full description of all I have to do to connect to my database using the JNDI process ?

Help me please, or I'll kill a kitten for each more minute I'm losing just to do my job in "the recommanded way".

Thanx by advance.

答:
To test classes dependent on a DataSource or any other object provided by Tomcat via JNDI outside of Tomcat you could rely on TomcatJNDI. Point it to your server.xml and context.xml and it will initialize a JNDI environment with all the objects configured in the files.

```<code>TomcatJNDI tomcatJNDI = new TomcatJNDI();
tomcatJNDI.processServerXml(serverXmlFile)
tomcatJNDI.processContextXml(contextXmlFile);
tomcatJNDI.start();
</code>```

Then lookup the datasource

```<code>DataSource ds = (DataSource) InitialContext.doLookup("java:comp/env/jdbc/trias_employee")
</code>```

You can find out more about TomcatJNDI here.

Body:
there's some things I definitely don't understand while using JNDI.

This should simplify our Java developers' life, but this promise sounds false.

The simplest way tu use a database from within an application seems to build each time you need it (so, once per application) a datasource class giving you a connection or session you will use.
It's a tool class written in a few minutes where you have to declare the driver, url, login and password. And it's done.

The recommanded way is to rely on the server resources management, JNDI and all resources such as directory, etc.
But is it really usefull and simple ??

With Tomcat, you have to have to fully describe the datasource in server.xml, then declare it as a resource in context.xml.

server.xml

<GlobalNamingResources>
   <Resource auth="Container" driverClassName="org.postgresql.Driver" maxIdle="30" maxTotal="100" maxWaitMillis="10000" name="jdbc/dsTriasEmployees" password="pwd" type="javax.sql.DataSource" url="jdbc:postgresql://localhost:5432/trias_employees" username="login"/>
</GlobalNamingResources>

context.xml

<ResourceLink name="jdbc/dsTriasEmployees" global="jdbc/dsTriasEmployees"
        type="javax.sql.DataSource" />

Java side, you should be able to inject it thanks to a Context Lookup code ou a @Resource(mappedBy...) annotation.

DataSource datasource;

    public Connection connectJNDI() {
        try {
            Context initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup("java:/comp/env");
            datasource = (DataSource) envContext.lookup("jdbc/trias_employees");
            Connection con = datasource.getConnection();
            genericLogger.info("JNDI LOOKUP -> " + con);
            return con;
        } catch (Exception ex) {
            genericLogger.error("JNDI LOOKUP -> " + ex);

        return null;
    }

But after doing that, you still have to deal with error messages telling you that it's not enough just like this one :

javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial

I have read somewhere that I now should add a JNDI properties file and a declaration in the web.xml file like this :

web.xml

<resource-ref>
      <description>
        DB PostgreSQL
      </description>
      <res-ref-name>
        jdbc/trias_employees
      </res-ref-name>
      <res-type>
        javax.sql.DataSource
      </res-type>
      <res-auth>
        Container
      </res-auth>
</resource-ref>

But when I wanna test with jUnit, my web.xml is not usefull...

How many XML and properties files should I write just to respect the best practice that want me to delegate access to the datasource to the server ?
How many times will I have to duplicate all the informations related to url, pool connection, etc. ??

I've read 2 or 3 books on Java EE, 50 posts on StackOverFlow and dozens of forums and all the JNDI Resources HOW-TO on the Tomcat website.
But it still does not work...

Is there somewhere the full description of all I have to do to connect to my database using the JNDI process ?

Help me please, or I'll kill a kitten for each more minute I'm losing just to do my job in "the recommanded way".

Thanx by advance.

Body:
To test classes dependent on a DataSource or any other object provided by Tomcat via JNDI outside of Tomcat you could rely on TomcatJNDI. Point it to your server.xml and context.xml and it will initialize a JNDI environment with all the objects configured in the files.

TomcatJNDI tomcatJNDI = new TomcatJNDI();
tomcatJNDI.processServerXml(serverXmlFile)
tomcatJNDI.processContextXml(contextXmlFile);
tomcatJNDI.start();

Then lookup the datasource

DataSource ds = (DataSource) InitialContext.doLookup("java:comp/env/jdbc/trias_employee")

You can find out more about TomcatJNDI here.


问:
addChildEventListener with firebase rules Confusion
My firebase database has a child which is name is Messages and it has children user_id and also it has children which are title and timestamp such as:

my firebase database

Messages

user_uid_1

Title

timestamp

user_uid_2

user_uid_3

...

I want to add a addChildEventListener for Messages to determine if there are any change in Messages. this is very easy with this code:

```<code>myRef.child("Messages").addChildEventListener(new ChildEventListener()...
</code>```

how about firebase rules. if I made it public it works. but if I do like that child listener NOT working what should I add to my rules

```<code>{
  "rules": {
   "Messages":{
       "$uid":{
            ".read": "data.child('timestamp').val() > (now - 18000000)",
            ".write": "auth != null"
   }
  },
   "$other":{
     ".read": true,
     ".write": "auth != null"
   }
}
}
</code>```

I want to read only messages from the last 30 minutes can be read so that I've added ".read": "data.child('timestamp').val() > (now - 18000000)",.

I think I should add something between "Messages" and "$uid" to addchild listener correctly.
thnks!

答:
Firebase security rules are enforced when you attach the listener. If you're allowing reads on /Messages/$uid, then a listener on /Messages will be rejected since you have no read permission on that level.

This is known as rules are not filters in the Firebase documentation, and means that you cannot use security rules to filter data. It has been covered quite a bit here on Stack Overflow already, so I suggest you check out some of the previous questions. The oldest answer I can find is this one.

Body:
My firebase database has a child which is name is Messages and it has children user_id and also it has children which are title and timestamp such as:

my firebase database

Messages

user_uid_1

Title

timestamp

user_uid_2

user_uid_3

...

I want to add a addChildEventListener for Messages to determine if there are any change in Messages. this is very easy with this code:

myRef.child("Messages").addChildEventListener(new ChildEventListener()...

how about firebase rules. if I made it public it works. but if I do like that child listener NOT working what should I add to my rules

{
  "rules": {
   "Messages":{
       "$uid":{
            ".read": "data.child('timestamp').val() > (now - 18000000)",
            ".write": "auth != null"
   }
  },
   "$other":{
     ".read": true,
     ".write": "auth != null"
   }
}
}

I want to read only messages from the last 30 minutes can be read so that I've added ".read": "data.child('timestamp').val() > (now - 18000000)",.

I think I should add something between "Messages" and "$uid" to addchild listener correctly.
thnks!