问:
Python: 'object in list' checks and '__cmp__' overflow
this is my first time at stack overflow so I'm sorry if the format doesn't fit quite right with the site.
I just recently started learning programming, almost 2 weeks have passed since.  I'm learning python from http://openbookproject.net/thinkcs/python/english3e/index.html  and everything had been quite nice until now, where I just got stuck for hours.
I googled a lot but couldn't find a proper solution to my problem so here I am.

I'm trying to get the OldMaidGame() run without problems as explained on CH17. http://openbookproject.net/thinkcs/python/english3e/ch17.html
- Most of the code also comes from the previous chapter.

What I've found out is I can't get the Deck.remove, Hand.remove_matches, or any other kind of remove function to work.  After some debugging I found out
that the problem occurs when the program checks if the given card is present in the deck/hand/etc.  It can't ever make a match.  Then after some looking back on
the chapter, (in ch16), I found out that 'if card in deck/hand/etc: remove(card)' etc looks up the .cmp() of the object to determine if the card actually exists in the deck/hand/etc.  This is my version of the cmp after doing the additions for 'ace's on the given code from the e-book.

```<code>def __cmp__(self, other):
    """ Compares cards, returns 1 if greater, -1 if lesser, 0 if equal """
    # check the suits
    if self.suit > other.suit: return 1
    if self.suit < other.suit: return -1
    # suits are the same... check ranks
    # check for aces first.
    if self.rank == 1 and other.rank == 1: return 0
    if self.rank == 1 and other.rank != 1: return 1
    if self.rank != 1 and other.rank == 1: return -1
    # check for non-aces.
    if self.rank > other.rank: return 1
    if self.rank < other.rank: return -1
    # ranks are the same... it's a tie
    return 0
</code>```

The cmp itself seems fine afaik, ofc I could use some tips on how to make it better (like with ace checks).
So I have no idea why the card in deck/hand checks always return false.
This was the given remove function:

```<code>class Deck:
    ...
    def remove(self, card):
        if card in self.cards:
            self.cards.remove(card)
            return True
        else:
            return False
</code>```

Desperately trying to get it to work, I came up with this:

```<code>class Deck:
    ...
    def remove(self, card):
        """ Removes the card from the deck, returns true if successful """
        for lol in self.cards:
            if lol.__cmp__(card) == 0:
                self.cards.remove(lol)
                return True
        return False
</code>```

Seemed to work fine, until I moved on to the other non-working remove functions:

```<code>class OldMaidHand(Hand):
    def remove_matches(self):
        count = 0
        original_cards = self.cards[:]
        for card in original_cards:
            match = Card(3 - card.suit, card.rank)
            if match in self.cards:
                self.cards.remove(card)
                self.cards.remove(match)
                print("Hand {0}: {1} matches {2}".format(self.name, card, match))
                count = count + 1
        return count
</code>```

I again made some adjustments:

```<code>class OldMaidHand(Hand):
    def remove_matches(self):
        count = 0
        original_cards = self.cards[:]
        for card in original_cards:
            match = Card(3 - card.suit, card.rank)
            for lol in self.cards:
                if lol.__cmp__(match) == 0:
                    self.cards.remove(card)
                    self.cards.remove(match)
                    print("Hand {0}: {1} matches {2}".format(self.name, card, match))
                    count = count + 1
        return count
</code>```

The removing worked fine for the card, but it would give an error (x not in list) when I tried to remove match.  Another our or so, I might've been able to make that work too, but since it already feels like I'm on the wrong road since I can't fix the original 'card in deck/hand/etc' etc, I came here looking for some answers/tips.

Thanks for reading and I greatly appreciate any help you can give :)

--------------------- EDIT 1 *>

This is my current code:
http://pastebin.com/g77Y4Tjr

--------------------- EDIT 2 *>

I've tried every single cmp advised here, and I still can't get it to find a card with 'in'.

```<code>>>> a = Card(0, 5)
>>> b = Card(0, 1)
>>> c = Card(3, 1)
>>> hand = Hand('Baris')
>>> hand.add(a)
>>> hand.add(b)
>>> hand.add(c)
>>> d = Card(3, 1)
>>> print(hand)
Hand Baris contains
5 of Clubs
 Ace of Clubs
  Ace of Spades
>>> d in hand.cards
False
>>>
</code>```

I've also tried the card.py @DSM has used successfully, and I get errors there too, like at the sort function it says it cant compare the two card objects.

So I was wondering, maybe it is a problem with Python 3.2, or maybe the syntax has changed somewhere?

答:
I also can't reproduce the error. It works fine for me. My only suggestion would be that you probably shouldn't be modifying a list while you're iterating over it (ie, calling self.cards.remove within a loop over self.cards). That can't explain why the versions using "in" wouldn't work for you.

Your cmp function can be written somewhat more succinctly (and IMHO more simply) as:

```<code>def __cmp__(self, other):
    """ Compares cards, returns 1 if greater, -1 if lesser, 0 if equal """
    return cmp((self.suit,  self.rank == 1,  self.rank),
              (other.suit, other.rank == 1, other.rank))
</code>```

or if you prefer:

```<code>    return (cmp(self.suit, other.suit) or
            cmp(self.rank == 1, other.rank == 1) or
            cmp(self.rank, other.rank))
</code>```

Body:
this is my first time at stack overflow so I'm sorry if the format doesn't fit quite right with the site.
I just recently started learning programming, almost 2 weeks have passed since.  I'm learning python from http://openbookproject.net/thinkcs/python/english3e/index.html  and everything had been quite nice until now, where I just got stuck for hours.
I googled a lot but couldn't find a proper solution to my problem so here I am.

I'm trying to get the OldMaidGame() run without problems as explained on CH17. http://openbookproject.net/thinkcs/python/english3e/ch17.html
- Most of the code also comes from the previous chapter.

What I've found out is I can't get the Deck.remove, Hand.remove_matches, or any other kind of remove function to work.  After some debugging I found out
that the problem occurs when the program checks if the given card is present in the deck/hand/etc.  It can't ever make a match.  Then after some looking back on
the chapter, (in ch16), I found out that 'if card in deck/hand/etc: remove(card)' etc looks up the .cmp() of the object to determine if the card actually exists in the deck/hand/etc.  This is my version of the cmp after doing the additions for 'ace's on the given code from the e-book.

def __cmp__(self, other):
    """ Compares cards, returns 1 if greater, -1 if lesser, 0 if equal """
    # check the suits
    if self.suit > other.suit: return 1
    if self.suit < other.suit: return -1
    # suits are the same... check ranks
    # check for aces first.
    if self.rank == 1 and other.rank == 1: return 0
    if self.rank == 1 and other.rank != 1: return 1
    if self.rank != 1 and other.rank == 1: return -1
    # check for non-aces.
    if self.rank > other.rank: return 1
    if self.rank < other.rank: return -1
    # ranks are the same... it's a tie
    return 0

The cmp itself seems fine afaik, ofc I could use some tips on how to make it better (like with ace checks).
So I have no idea why the card in deck/hand checks always return false.
This was the given remove function:

class Deck:
    ...
    def remove(self, card):
        if card in self.cards:
            self.cards.remove(card)
            return True
        else:
            return False

Desperately trying to get it to work, I came up with this:

class Deck:
    ...
    def remove(self, card):
        """ Removes the card from the deck, returns true if successful """
        for lol in self.cards:
            if lol.__cmp__(card) == 0:
                self.cards.remove(lol)
                return True
        return False

Seemed to work fine, until I moved on to the other non-working remove functions:

class OldMaidHand(Hand):
    def remove_matches(self):
        count = 0
        original_cards = self.cards[:]
        for card in original_cards:
            match = Card(3 - card.suit, card.rank)
            if match in self.cards:
                self.cards.remove(card)
                self.cards.remove(match)
                print("Hand {0}: {1} matches {2}".format(self.name, card, match))
                count = count + 1
        return count

I again made some adjustments:

class OldMaidHand(Hand):
    def remove_matches(self):
        count = 0
        original_cards = self.cards[:]
        for card in original_cards:
            match = Card(3 - card.suit, card.rank)
            for lol in self.cards:
                if lol.__cmp__(match) == 0:
                    self.cards.remove(card)
                    self.cards.remove(match)
                    print("Hand {0}: {1} matches {2}".format(self.name, card, match))
                    count = count + 1
        return count

The removing worked fine for the card, but it would give an error (x not in list) when I tried to remove match.  Another our or so, I might've been able to make that work too, but since it already feels like I'm on the wrong road since I can't fix the original 'card in deck/hand/etc' etc, I came here looking for some answers/tips.

Thanks for reading and I greatly appreciate any help you can give :)

--------------------- EDIT 1 *>

This is my current code:
http://pastebin.com/g77Y4Tjr

--------------------- EDIT 2 *>

I've tried every single cmp advised here, and I still can't get it to find a card with 'in'.

>>> a = Card(0, 5)
>>> b = Card(0, 1)
>>> c = Card(3, 1)
>>> hand = Hand('Baris')
>>> hand.add(a)
>>> hand.add(b)
>>> hand.add(c)
>>> d = Card(3, 1)
>>> print(hand)
Hand Baris contains
5 of Clubs
 Ace of Clubs
  Ace of Spades
>>> d in hand.cards
False
>>>

I've also tried the card.py @DSM has used successfully, and I get errors there too, like at the sort function it says it cant compare the two card objects.

So I was wondering, maybe it is a problem with Python 3.2, or maybe the syntax has changed somewhere?

Body:
I also can't reproduce the error. It works fine for me. My only suggestion would be that you probably shouldn't be modifying a list while you're iterating over it (ie, calling self.cards.remove within a loop over self.cards). That can't explain why the versions using "in" wouldn't work for you.

Your cmp function can be written somewhat more succinctly (and IMHO more simply) as:

def __cmp__(self, other):
    """ Compares cards, returns 1 if greater, -1 if lesser, 0 if equal """
    return cmp((self.suit,  self.rank == 1,  self.rank),
              (other.suit, other.rank == 1, other.rank))

or if you prefer:

    return (cmp(self.suit, other.suit) or
            cmp(self.rank == 1, other.rank == 1) or
            cmp(self.rank, other.rank))


来源: stackexchange

问:
Getting Build Compilation Error when Integrating Firebase without Cocoapods [Obj-C]
I want to integrate Firebase without cocoapods in my iOS application which is in Obj-C. I had downloaded the firebase zip file containing all the xcframeworks and frameworks files. I am trying to implement Firebase Analytics with my application.

I had gone through the Readme.md file and followed the steps to integrate the Firebase with by project.

I had added all the required .xcframework and .framework files which are mentioned under the "Firebase Analytics" and made sure that I had tick marked the "Copy items if needed" and the "target" for my project is selected.

After this I added the "Firebase.h" header file in the same manner and also included the "-ObjC" tag under the "Build Settings -> Linking -> Other Linker Flags" but even doing all these steps when I am building my application I am getting the following error:

```<code>ld: warning: Could not find or use auto-linked framework 'FBLPromises'
Undefined symbols for architecture arm64:
  "_OBJC_CLASS_$_SKProductsRequest", referenced from:
      objc-class-ref in GoogleAppMeasurement(APMProductsRequest_9ec051498f83cad93a58cf3f308ab9b6.o)
  "_sqlite3_errmsg", referenced from:
      -[APMSqliteStore lastErrorMessage] in GoogleAppMeasurement(APMSqliteStore_4b93d70f10ae469a3a03d3a4cf33073f.o)
  "_sqlite3_bind_blob", referenced from:
      ___47-[APMSqliteStore bindValues:toStatement:error:]_block_invoke in GoogleAppMeasurement(APMSqliteStore_4b93d70f10ae469a3a03d3a4cf33073f.o)
  "_sqlite3_bind_double", referenced from:
      ___47-[APMSqliteStore bindValues:toStatement:error:]_block_invoke in GoogleAppMeasurement(APMSqliteStore_4b93d70f10ae469a3a03d3a4cf33073f.o)
  "_sqlite3_bind_text", referenced from:
      ___47-[APMSqliteStore bindValues:toStatement:error:]_block_invoke in GoogleAppMeasurement(APMSqliteStore_4b93d70f10ae469a3a03d3a4cf33073f.o)
  "_sqlite3_bind_int64", referenced from:
      ___47-[APMSqliteStore bindValues:toStatement:error:]_block_invoke in GoogleAppMeasurement(APMSqliteStore_4b93d70f10ae469a3a03d3a4cf33073f.o)
  "_sqlite3_column_int64", referenced from:
      -[APMSqliteStore valueAtColumn:forStatement:] in GoogleAppMeasurement(APMSqliteStore_4b93d70f10ae469a3a03d3a4cf33073f.o)
  "_sqlite3_column_double", referenced from:
      -[APMSqliteStore valueAtColumn:forStatement:] in GoogleAppMeasurement(APMSqliteStore_4b93d70f10ae469a3a03d3a4cf33073f.o)
  "_sqlite3_column_bytes", referenced from:
      -[APMSqliteStore valueAtColumn:forStatement:] in GoogleAppMeasurement(APMSqliteStore_4b93d70f10ae469a3a03d3a4cf33073f.o)
  "_sqlite3_prepare_v2", referenced from:
      -[APMSqliteStore prepareSQL:error:] in GoogleAppMeasurement(APMSqliteStore_4b93d70f10ae469a3a03d3a4cf33073f.o)
  "_sqlite3_changes", referenced from:
      -[APMSqliteStore deleteRecordsFromTableWithName:condition:parameterValues:error:] in GoogleAppMeasurement(APMSqliteStore_4b93d70f10ae469a3a03d3a4cf33073f.o)

</code>```

Here is my System Configuration :

```<code>1.  Mac OS: MacOS Mojave[10.14.6]
2.  Xcode Version: 11.3.1
3.  Deployment Target: 11.3
</code>```

Can anyone help me what I am missing here in the configuration that is needed to be done to successfully run it ?

答:
Depending on where you got your dependency from it should also include a PromisesObjc.framework file inside it. You need to simply drag this framework into your Frameworks, Libraries & Embedded Content part of Xcode and it will compile. If you don't have this, you'll need to download the FBLPromises framework and embed it yourself.

If you chose to use Carthage or CocoaPods it will gather this dependency for you but it may be in the list of your dependencies you mentioned.

ContentLicense: CC BY-SA 4.0

Body:
I want to integrate Firebase without cocoapods in my iOS application which is in Obj-C. I had downloaded the firebase zip file containing all the xcframeworks and frameworks files. I am trying to implement Firebase Analytics with my application.

I had gone through the Readme.md file and followed the steps to integrate the Firebase with by project.

I had added all the required .xcframework and .framework files which are mentioned under the "Firebase Analytics" and made sure that I had tick marked the "Copy items if needed" and the "target" for my project is selected.

After this I added the "Firebase.h" header file in the same manner and also included the "-ObjC" tag under the "Build Settings -> Linking -> Other Linker Flags" but even doing all these steps when I am building my application I am getting the following error:

ld: warning: Could not find or use auto-linked framework 'FBLPromises'
Undefined symbols for architecture arm64:
  "_OBJC_CLASS_$_SKProductsRequest", referenced from:
      objc-class-ref in GoogleAppMeasurement(APMProductsRequest_9ec051498f83cad93a58cf3f308ab9b6.o)
  "_sqlite3_errmsg", referenced from:
      -[APMSqliteStore lastErrorMessage] in GoogleAppMeasurement(APMSqliteStore_4b93d70f10ae469a3a03d3a4cf33073f.o)
  "_sqlite3_bind_blob", referenced from:
      ___47-[APMSqliteStore bindValues:toStatement:error:]_block_invoke in GoogleAppMeasurement(APMSqliteStore_4b93d70f10ae469a3a03d3a4cf33073f.o)
  "_sqlite3_bind_double", referenced from:
      ___47-[APMSqliteStore bindValues:toStatement:error:]_block_invoke in GoogleAppMeasurement(APMSqliteStore_4b93d70f10ae469a3a03d3a4cf33073f.o)
  "_sqlite3_bind_text", referenced from:
      ___47-[APMSqliteStore bindValues:toStatement:error:]_block_invoke in GoogleAppMeasurement(APMSqliteStore_4b93d70f10ae469a3a03d3a4cf33073f.o)
  "_sqlite3_bind_int64", referenced from:
      ___47-[APMSqliteStore bindValues:toStatement:error:]_block_invoke in GoogleAppMeasurement(APMSqliteStore_4b93d70f10ae469a3a03d3a4cf33073f.o)
  "_sqlite3_column_int64", referenced from:
      -[APMSqliteStore valueAtColumn:forStatement:] in GoogleAppMeasurement(APMSqliteStore_4b93d70f10ae469a3a03d3a4cf33073f.o)
  "_sqlite3_column_double", referenced from:
      -[APMSqliteStore valueAtColumn:forStatement:] in GoogleAppMeasurement(APMSqliteStore_4b93d70f10ae469a3a03d3a4cf33073f.o)
  "_sqlite3_column_bytes", referenced from:
      -[APMSqliteStore valueAtColumn:forStatement:] in GoogleAppMeasurement(APMSqliteStore_4b93d70f10ae469a3a03d3a4cf33073f.o)
  "_sqlite3_prepare_v2", referenced from:
      -[APMSqliteStore prepareSQL:error:] in GoogleAppMeasurement(APMSqliteStore_4b93d70f10ae469a3a03d3a4cf33073f.o)
  "_sqlite3_changes", referenced from:
      -[APMSqliteStore deleteRecordsFromTableWithName:condition:parameterValues:error:] in GoogleAppMeasurement(APMSqliteStore_4b93d70f10ae469a3a03d3a4cf33073f.o)

Here is my System Configuration :

1.  Mac OS: MacOS Mojave[10.14.6]
2.  Xcode Version: 11.3.1
3.  Deployment Target: 11.3

Can anyone help me what I am missing here in the configuration that is needed to be done to successfully run it ?


问:
How do I fix my variables on my code as it does not appear
So when I ran this code below, I noticed that my variables myName and myAge didn't function at all. An I getting something wrong here?

This program says hello and asks for my name.

print ('Hello world!')

print ('What is your name?') # ask for their name

myName = input('Michael')

print ('It is good to meet you, ' + myName)

print('The length of your name is:')

print (len(myName))

print ('What is your age?') # ask for their age

myAge = input('16')

print('You will be " + str(int(myAge) + 1) + ' in a year.')
```

答:
Thanks so much, guys...... It really helped learnt my mistake.... This is the correction:

print ('Hello world!')

print ('What is your name?') # ask for their name

myName = input('Michael')

myName = 'Michael'

print ('It is good to meet you, ' + myName)

print('The length of your name is:')

print (len(myName))

print ('What is your age?') # ask for their age

myAge = input('16')

myAge = 16

print('You will be ' + str(int(myAge) + 1) + ' in a year.')


问:
AttributeError: module 'cv2' has no attribute 'imread'
(i'm on mac os 10.8.5)

I'm using Python 3 (through jupyter notebook) and trying to import cv2

I did import cv2  succefully, but when I type im_g = cv2.imread("smallgray.png", 0)  I get this error:

```<code>---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-7-5eb2880672d2> in <module>()
----> 1 im_g = cv2.imread("smallgray.png", 0)

AttributeError: module 'cv2' has no attribute 'imread'
</code>```

I also checked dir(cv2)  and I get:

```<code>['__doc__', '__loader__', '__name__', '__package__', '__path__', '__spec__'
</code>```

I guess a lot of functions are missing...
Is it due to a wrong opencv installation ?
Actually I struggled a lot to get opencv and I guess I installed it 'too many times' and different ways via Terminal. (brew, pip)

Should I uninstall opencv and start over ? How can I do this properly ?

Thx in advance

答: I had this problem, the reason was that my script was named 'cv2.py', let's try to rename to something else.</p>

ContentLicense: CC BY-SA 3.0

Body:
(i'm on mac os 10.8.5)

I'm using Python 3 (through jupyter notebook) and trying to import cv2

I did import cv2  succefully, but when I type im_g = cv2.imread("smallgray.png", 0)  I get this error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-7-5eb2880672d2> in <module>()
----> 1 im_g = cv2.imread("smallgray.png", 0)

AttributeError: module 'cv2' has no attribute 'imread'

I also checked dir(cv2)  and I get:

['__doc__', '__loader__', '__name__', '__package__', '__path__', '__spec__'

I guess a lot of functions are missing...
Is it due to a wrong opencv installation ?
Actually I struggled a lot to get opencv and I guess I installed it 'too many times' and different ways via Terminal. (brew, pip)

Should I uninstall opencv and start over ? How can I do this properly ?

Thx in advance


问:
How to save info such as a user name to the device?
I'd like to provide a "Remember Me" for my flutter app's login screen. Can someone point me in the right direction of how I can read and write some info to the device such as the user name.</p>

答:
Have you looked into shared preferences?
https://pub.dev/packages/shared_preferences</p>


问:
GraphDB 9.3.0 (Win-Desktop) not starting
I'm having troubles starting GraphDB Free 9.3 as a Windows desktop installation. When double clicking the .exe nothing happens. I don't even see any logs.

Please note that I previously had v8, which I deinstalled before installing v9. I also just tried to run the standalone server version and this works. What could be the problem with the desktop version?

My Java-Version:

openjdk 14 2020-03-17

OpenJDK Runtime Environment (build 14+36-1461)

OpenJDK 64-Bit Server VM (build 14+36-1461, mixed mode, sharing)

答: A possible problem could be the Java version - the supported versions are up to JDK 11. Try changing the JDK or if this doesn't help take a look for any errors in  Event Viewer -> Windows Logs -> Application. Also you could check for leftovers from the previous installation in \Users\your_user\AppData\Local\GraphDB Free</p>


问:
python mysql connector multi=true Continue even if an SQL error occurs
I am using mysql connector python to connect to mysql and run multiple queries by setting multi=True. I am getting results. If there is sql error in any of the statements, the queries after the error are ignored. How do I use "--force" and continue even if an SQL error occurs

```<code>conn = MYSQL.MySQLConnection(user=sql_username,password=sql_password,host='127.0.0.1',database=sql_main_database,port=3306)
cursor = conn.cursor(buffered=True)
try:
    results=cursor.execute("select now();SELECT UNIX_TIMESTAMP(now());select 'test';SELECT UTC_TIMESTAMP();select 'aravinth';select yuu;show processlist;select 1",multi=True)
except Exception as e:
    print(e)

count = 1

for result in results:
    if result.with_rows:

        print("Rows produced by statement '{}':".format(
        result.statement))
        print(result.fetchall())

    else:
         print("Number of rows affected by statement '{}': {}".format(
         result.statement, result.rowcount))

except Exception as e:
    print(e)
</code>```

My output is

```<code>Rows produced by statement 'select now()':
[(datetime.datetime(2020, 6, 3, 13, 4, 54),)]
Rows produced by statement 'SELECT UNIX_TIMESTAMP(now())':
[(1591169694,)]
Rows produced by statement 'select 'test'':
[('test',)]
Rows produced by statement 'SELECT UTC_TIMESTAMP()':
[(datetime.datetime(2020, 6, 3, 7, 34, 54),)]
Rows produced by statement 'select 'aravinth'':
[('aravinth',)]
1054 (42S22): Unknown column 'yuu' in 'field list'
end
</code>```

I would like to continue executing all the queries even if any of the middle query fails.

答:
Because one of the intermediate queries throws an Exception, you cannot force the try block to continue executing from that point. What you can rather do is:

Declare  results = []

Run each query individually within its own try-catch block.

Append the result of each query to results.

Use results henceforth.

A sample code could be:

# assume that queries is a list containing all queries
results = []
for query in queries:
    try:
        result = cursor.execute(query)
        results.append(result)
    except Exception as e:
        print(e)

for result in results:
    if result.with_rows:

        print("Rows produced by statement '{}':".format(
        result.statement))
        print(result.fetchall())
```

Body:
I am using mysql connector python to connect to mysql and run multiple queries by setting multi=True. I am getting results. If there is sql error in any of the statements, the queries after the error are ignored. How do I use "--force" and continue even if an SQL error occurs

conn = MYSQL.MySQLConnection(user=sql_username,password=sql_password,host='127.0.0.1',database=sql_main_database,port=3306)
cursor = conn.cursor(buffered=True)
try:
    results=cursor.execute("select now();SELECT UNIX_TIMESTAMP(now());select 'test';SELECT UTC_TIMESTAMP();select 'aravinth';select yuu;show processlist;select 1",multi=True)
except Exception as e:
    print(e)

count = 1

for result in results:
    if result.with_rows:

        print("Rows produced by statement '{}':".format(
        result.statement))
        print(result.fetchall())

    else:
         print("Number of rows affected by statement '{}': {}".format(
         result.statement, result.rowcount))

except Exception as e:
    print(e)

My output is

Rows produced by statement 'select now()':
[(datetime.datetime(2020, 6, 3, 13, 4, 54),)]
Rows produced by statement 'SELECT UNIX_TIMESTAMP(now())':
[(1591169694,)]
Rows produced by statement 'select 'test'':
[('test',)]
Rows produced by statement 'SELECT UTC_TIMESTAMP()':
[(datetime.datetime(2020, 6, 3, 7, 34, 54),)]
Rows produced by statement 'select 'aravinth'':
[('aravinth',)]
1054 (42S22): Unknown column 'yuu' in 'field list'
end

I would like to continue executing all the queries even if any of the middle query fails.


问:
Is there any guide for iOS runloop mechanism?
I'm learning socket communication on iPhone, and its guide said something about CFRunloop(it is a guide for CFNetwork, can this be used on iOS?)
Where can I learn about runloop on iOS?API reference is not enough.

答:
Have a look at these articles in the Apple docs:

Main event loop

Run Loops

For sample code on how to run asynchronous connections via the run loop:

SimpleURLConnections (although this one uses the NSURLConnection API)


问:
pandas filter by multiple conditions without chaining
I want to filter a pandas dataframe by multiple condiitons that have to hold together.

```<code>d = {'price': [1, 2, 0 ,0,1], 'description': ['a', 'a','b','c','e']}
df = pd.DataFrame(data=d)
li = ['a','b']
df = df[(df['price']!=0) & (~df['description'].isin(li))]
</code>```

The problem is, that it removes all prices that are 0 and then removes everything thats in li.
I want it to remove rows in the dataframe that hold both conditions together and not only one of it.

expected output would be:

```<code>   price description
      1           a
      2           a
      0           c
      1           e
</code>```

but instead it is:

```<code>   price description
      1           e
</code>```

答:
Your current code selects all rows that meet the following criteria:

df['price']!=0: price different than zero

Returns:

```<code>0 True
1 True
2 False
3 False
4 True
</code>```

~df['description'].isin(li): description not in li

Returns:

```<code>0 False
1 False
2 False
3 True
4 True
</code>```

The combination of these two boolean arrays leads to:

```<code>(df['price']!=0) & (~df['description'].isin(li))
>> 0    False
>> 1    False
>> 2    False
>> 3    False
>> 4     True
</code>```

That is, only the last row of your dataframe (price = 1, description = e) meets both criteria.

From your description, you might want to use an "OR" operator, |:

```<code>(df['price']!=0) | (~df['description'].isin(li))
>> 0 True
>> 1 True
>> 2 False
>> 3 True
>> 4 True
</code>```

Which will remove only the row with (price = 0, description = b).

Hope it helps!
Cheers,
T

Body:
I want to filter a pandas dataframe by multiple condiitons that have to hold together.

d = {'price': [1, 2, 0 ,0,1], 'description': ['a', 'a','b','c','e']}
df = pd.DataFrame(data=d)
li = ['a','b']
df = df[(df['price']!=0) & (~df['description'].isin(li))]

The problem is, that it removes all prices that are 0 and then removes everything thats in li.
I want it to remove rows in the dataframe that hold both conditions together and not only one of it.

expected output would be:

   price description
      1           a
      2           a
      0           c
      1           e

but instead it is:

   price description
      1           e

Body:
Your current code selects all rows that meet the following criteria:

df['price']!=0: price different than zero

Returns:

0 True
1 True
2 False
3 False
4 True

~df['description'].isin(li): description not in li

Returns:

0 False
1 False
2 False
3 True
4 True

The combination of these two boolean arrays leads to:

(df['price']!=0) & (~df['description'].isin(li))
>> 0    False
>> 1    False
>> 2    False
>> 3    False
>> 4     True

That is, only the last row of your dataframe (price = 1, description = e) meets both criteria.

From your description, you might want to use an "OR" operator, |:

(df['price']!=0) | (~df['description'].isin(li))
>> 0 True
>> 1 True
>> 2 False
>> 3 True
>> 4 True

Which will remove only the row with (price = 0, description = b).

Hope it helps!
Cheers,
T


问:
In App Purchase - Options after payment is successful
I have successfully implemented IAP in one of my apps.

At the moment I am using NotificationCenter to notify my UIViewController when the item is purchased, which works:

```<code>func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
    for transaction in transactions {
        print(transaction.transactionState.status(), transaction.payment.productIdentifier)
        switch transaction.transactionState {
        case .purchasing: break
        case .purchased:
            print("purhcsed")
            NotificationCenter.default.post(name: Notification.Name(rawValue: "Cvpurchased"), object: nil, userInfo: nil)
            queue.finishTransaction(transaction)
        default:
            print("updatedTransactions")
            queue.finishTransaction(transaction)
        }
    }
}
</code>```

The problem is that I would like to wait that the user push "OK" on the "You're all set" alert before performing the next action.

I was looking for a delegate method but I can't find anything in the apple documentation.

答:
You can do it via using applicationState of UIApplication as workaround.

When purchase is completed, if applicationState is inactive, wait until state is changed to active (Ok button is tapped), then do your stuff.

You can use applicationDidBecomeActive(_ application: UIApplication) delegate or UIApplicationDidBecomeActive notification to handle state change.

Body:
I have successfully implemented IAP in one of my apps.

At the moment I am using NotificationCenter to notify my UIViewController when the item is purchased, which works:

func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
    for transaction in transactions {
        print(transaction.transactionState.status(), transaction.payment.productIdentifier)
        switch transaction.transactionState {
        case .purchasing: break
        case .purchased:
            print("purhcsed")
            NotificationCenter.default.post(name: Notification.Name(rawValue: "Cvpurchased"), object: nil, userInfo: nil)
            queue.finishTransaction(transaction)
        default:
            print("updatedTransactions")
            queue.finishTransaction(transaction)
        }
    }
}

The problem is that I would like to wait that the user push "OK" on the "You're all set" alert before performing the next action.

I was looking for a delegate method but I can't find anything in the apple documentation.


问:
How to send a SOAP request with an authentication header in PHP
I have created a request using SoapClient towards a wsdl. I have managed to get through and get a list of functions using __getFunctions(), so I can confirm my URL is working.

The issue lies when calling a function, I receive a Could not connect to host error message. I should also mention I use Laravel and the error message does not give me any more information.

I personally believe it is an authentication based issue, as I need to parse a username and password through the header and I might have gotten some syntax wrong.

My PHP function:

```<code>try {
            $wsdlUrl = 'https://myurl.com/Service.svc?wsdl';
            $context = [
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true,
                'cache_wsdl' => WSDL_CACHE_NONE,
            ];
            $client = new SoapClient($wsdlUrl, array('stream_context' => $context));

            $authentication = array(
                'Username' => env('USERNAME'),
                'Password' => env('PASSWORD')
            );

            //Soap Header
            $header = new SoapHeader(
                'https://myurl.com/',
                'Credentials',
                $authentication,
                false
            );
            $client->__setSoapHeaders($header);

            return $client->GetElement(['ID' => '462493']);

        } catch (\Exception $e) {
            \Log::error($e->getMessage());
    }
</code>```

and the xml I'm trying to match:

```<code>  <soapenv:Header>
    <Credentials>
      <Password>Password</Password>
      <Username>Brugernavn</Username>
    </Credentials>
  </soapenv:Header>
  <soapenv:Body>
    <GetElementRequestType>
      <ID>4624393</ID>
    </GetElementRequestType>
  </soapenv:Body>
</code>```

答:
There are a few elementary things wrong in your code. Let us go through the different things you have to do right, when dealing with soap requests and responses with PHP.

Try/catch blocks with soap

When dealing with soap, there 's always thrown a SoapFault. The SoapFault class inherits directly from Exception. With this in mind you have to catch a SoapFault and not an ErrorException.

```<code>try {
    // doing some soap stuff here
} catch (SoapFault $fault) {
    Log::error($fault->getMessage());
}
</code>```

Optionally you can catch different exceptions with different catch blocks if you are awaiting some other throwable stuff.

```<code>try {

} catch (SoapFault $fault) {
    // catches soap faults
} catch (ErrorException $e) {
    // catches error exceptions
} finally {
    // final catch of everything else
}
</code>```

The finally statement will always be executed no matter what kind of throwable was thrown before.

The client options

As long as you 're not dealing with any certificates you do not have to create an context. You can, but it would work without that context. In your case, as you 're just dealing with username and password credentials, the context is just another possible source of error.
For development the options of the SoapClient class should look as follows.

```<code>try {
    $wsdl = 'https://www.domain.tld/service?wsdl';
    $options = [
        'cache_wsdl' => WSDL_CACHE_NONE,
        'exceptions' => true,
        'trace' => true,
    ];

    $client = new SoapClient($wsdl, $options);
} catch (SoapFault $fault) {
    if ($client) {
        // get the last sent request
        var_dump($client->__getLastRequest());

        // get the last response
        var_dump($client->__getLastResponse());
    }

    var_dump($fault);
}
</code>```

With the trace option you enable the functions for getting the last request and response. This can be quite helpful during development. The exception option forces the client to throw exceptions in any case. If this is no set the client can be calm in an error case.

Data models with soap

Just assume that the PHP Soap extension is strictly object oriented. So you have to deal with value objects and elements, that are directly described in the wsdl file. You can view the definitions mostly by calling the wsdl url directy in the broser. All complex and simple types and function calls are described there.

So when we look at your soap header, we see  credentials object (complex type) with the properties username and password. We can directy use that in php as a class.

```<code>class Credentials
{
    protected string $Password;
    protected string $Username;

    public function getPassword(): string
    {
        return $this->Password;
    }

    public function setPassword(string $password): self
    {
        $this->Password = $password;
        return $this;
    }

    public function getUsername(): string
    {
        return $this->Username;
    }

    public function setUsername(string $username): self
    {
        $this->Username = $username;
        return $this;
    }
}
</code>```

As you can see this is a simple data model of the credentials. You now have to initialize it and force it as a soap header.

```<code>$credentials = (new Credentials())
    ->setPassword('bla')
    ->setUsername('blubb');

$header = new SoapHeader(
    'http://www.domain.tld/namespace',
    'Credentials',
    new SoapVar($credentials, SOAP_ENC_OBJECT, '', '', 'Credentials', '')
);

$client->__setSoapHeaders($header);
$response = $client->GetElement([ 'ID' => 1234 ]);
</code>```

If this is not working, remember the trace function. In case of a soap fault try to have a look at the last sent request. In most cases you can see, that there 's something wrong with the request xml structure.

Body:
I have created a request using SoapClient towards a wsdl. I have managed to get through and get a list of functions using __getFunctions(), so I can confirm my URL is working.

The issue lies when calling a function, I receive a Could not connect to host error message. I should also mention I use Laravel and the error message does not give me any more information.

I personally believe it is an authentication based issue, as I need to parse a username and password through the header and I might have gotten some syntax wrong.

My PHP function:

try {
            $wsdlUrl = 'https://myurl.com/Service.svc?wsdl';
            $context = [
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true,
                'cache_wsdl' => WSDL_CACHE_NONE,
            ];
            $client = new SoapClient($wsdlUrl, array('stream_context' => $context));

            $authentication = array(
                'Username' => env('USERNAME'),
                'Password' => env('PASSWORD')
            );

            //Soap Header
            $header = new SoapHeader(
                'https://myurl.com/',
                'Credentials',
                $authentication,
                false
            );
            $client->__setSoapHeaders($header);

            return $client->GetElement(['ID' => '462493']);

        } catch (\Exception $e) {
            \Log::error($e->getMessage());
    }

and the xml I'm trying to match:

  <soapenv:Header>
    <Credentials>
      <Password>Password</Password>
      <Username>Brugernavn</Username>
    </Credentials>
  </soapenv:Header>
  <soapenv:Body>
    <GetElementRequestType>
      <ID>4624393</ID>
    </GetElementRequestType>
  </soapenv:Body>

Body:
There are a few elementary things wrong in your code. Let us go through the different things you have to do right, when dealing with soap requests and responses with PHP.

Try/catch blocks with soap

When dealing with soap, there 's always thrown a SoapFault. The SoapFault class inherits directly from Exception. With this in mind you have to catch a SoapFault and not an ErrorException.

try {
    // doing some soap stuff here
} catch (SoapFault $fault) {
    Log::error($fault->getMessage());
}

Optionally you can catch different exceptions with different catch blocks if you are awaiting some other throwable stuff.

try {

} catch (SoapFault $fault) {
    // catches soap faults
} catch (ErrorException $e) {
    // catches error exceptions
} finally {
    // final catch of everything else
}

The finally statement will always be executed no matter what kind of throwable was thrown before.

The client options

As long as you 're not dealing with any certificates you do not have to create an context. You can, but it would work without that context. In your case, as you 're just dealing with username and password credentials, the context is just another possible source of error.
For development the options of the SoapClient class should look as follows.

try {
    $wsdl = 'https://www.domain.tld/service?wsdl';
    $options = [
        'cache_wsdl' => WSDL_CACHE_NONE,
        'exceptions' => true,
        'trace' => true,
    ];

    $client = new SoapClient($wsdl, $options);
} catch (SoapFault $fault) {
    if ($client) {
        // get the last sent request
        var_dump($client->__getLastRequest());

        // get the last response
        var_dump($client->__getLastResponse());
    }

    var_dump($fault);
}

With the trace option you enable the functions for getting the last request and response. This can be quite helpful during development. The exception option forces the client to throw exceptions in any case. If this is no set the client can be calm in an error case.

Data models with soap

Just assume that the PHP Soap extension is strictly object oriented. So you have to deal with value objects and elements, that are directly described in the wsdl file. You can view the definitions mostly by calling the wsdl url directy in the broser. All complex and simple types and function calls are described there.

So when we look at your soap header, we see  credentials object (complex type) with the properties username and password. We can directy use that in php as a class.

class Credentials
{
    protected string $Password;
    protected string $Username;

    public function getPassword(): string
    {
        return $this->Password;
    }

    public function setPassword(string $password): self
    {
        $this->Password = $password;
        return $this;
    }

    public function getUsername(): string
    {
        return $this->Username;
    }

    public function setUsername(string $username): self
    {
        $this->Username = $username;
        return $this;
    }
}

As you can see this is a simple data model of the credentials. You now have to initialize it and force it as a soap header.

$credentials = (new Credentials())
    ->setPassword('bla')
    ->setUsername('blubb');

$header = new SoapHeader(
    'http://www.domain.tld/namespace',
    'Credentials',
    new SoapVar($credentials, SOAP_ENC_OBJECT, '', '', 'Credentials', '')
);

$client->__setSoapHeaders($header);
$response = $client->GetElement([ 'ID' => 1234 ]);

If this is not working, remember the trace function. In case of a soap fault try to have a look at the last sent request. In most cases you can see, that there 's something wrong with the request xml structure.


问:
How to make a 3D histogram of a 2D vector distribution in python / plotly
So, basically I have a list of 2D vectors in python, and I want to make a 3d visualization of the distribution of this vector, like a surface curve, through plotly. I'll leave a sample of the first 4 components of my vector

[[0.35431211986827776, 0.21438054570807566], [0.35431211986827776, 0.21438054570807566], [0.35431211986827776, 0.21438054570807566], [0.35431211986827776, 0.21438054570807566],

so I used the seaborn.kdeplot() to visualize, giving only the 2D visualization of the KDE:

But i wanted a 3D result, like in this bivariate normal distribution plot, where de X and Y axis are a 2d matrix and the z axis the pdf:

I think I just need to find a good pdf estimate for each vector in my list. Is there a way to fit a KDE to my data, in order to obtain this approximated distribution of each vector an then plot the surface?

Many thanks

答:
Here's a way to do that:

```<code>x = np.random.normal(5, 10, 100000)
y = np.random.normal(10, 3, 100000)
h = np.histogram2d(x, y, bins=50)

def bin_centers(bins):
    centers = (bins + (bins[1]-bins[0])/2) [:-1]
    return centers

x_bins_centers = bin_centers(h[1])
y_bins_centers = bin_centers(h[2])

df = pd.DataFrame(h[0], index=x_bins_centers, columns=y_bins_centers)
fig = go.Figure(data=[go.Surface(z=df)])
fig.show()
</code>```

The result is:

Body:
Here's a way to do that:

x = np.random.normal(5, 10, 100000)
y = np.random.normal(10, 3, 100000)
h = np.histogram2d(x, y, bins=50)

def bin_centers(bins):
    centers = (bins + (bins[1]-bins[0])/2) [:-1]
    return centers

x_bins_centers = bin_centers(h[1])
y_bins_centers = bin_centers(h[2])

df = pd.DataFrame(h[0], index=x_bins_centers, columns=y_bins_centers)
fig = go.Figure(data=[go.Surface(z=df)])
fig.show()

The result is:


问:
javascript Cannot pass variables between 2 functions
I am wondering how to pass a variable between 2 functions.

I have looked on Stackoverflow but all examples I tried did not work for me.

I have function, which calculates an array: arrR.

Now, I would like to call this variable somewhere else:

```<code>function my_function(arrR) {
    return(arrR[1]);
}

function onRefresh(chart) {
    chart.config.data.datasets.forEach(function(dataset) {
        dataset.data.push({
            x: Date.now(),
            y: myfunction(arrR)
        });
    });
}
</code>```

But y: myfunction(arrR) gives notting. I have checked that if I put some number say y: 1 this works.

Any clue ?

Many thanks

答:
Can you get the value of the variable arrR?

If the scope of the variable arrR is different from onRefresh one level or higher. You can't get arrR across domains. You need to understand the scope of JavaScript

Body:
I am wondering how to pass a variable between 2 functions.

I have looked on Stackoverflow but all examples I tried did not work for me.

I have function, which calculates an array: arrR.

Now, I would like to call this variable somewhere else:

function my_function(arrR) {
    return(arrR[1]);
}

function onRefresh(chart) {
    chart.config.data.datasets.forEach(function(dataset) {
        dataset.data.push({
            x: Date.now(),
            y: myfunction(arrR)
        });
    });
}

But y: myfunction(arrR) gives notting. I have checked that if I put some number say y: 1 this works.

Any clue ?

Many thanks


问:
Finding parameters values of growth function?
```<code> Number of days before vaccination  (x)     bacteria count (1000 pieces) (y)
            1                                        112
            2                                        148
            3                                        241
            4                                        363
            5                                        585

</code>```

I Need to find 2 things
first calculate with growth function third day count and I have been counted.
=GROWTH(I3:I4;H3:H4;H5)

But I need to calculate parameters of growth function( =.^)

So how to calculate a and b? I tried to use excel solver but i didn't solve

答: You are dealing with an exponentional growth, you want to describe. The basic way to handle this, is to take the logarythm of the whole thing, and apply linear regression on that, using the Linest() function.

Body:
 Number of days before vaccination  (x)     bacteria count (1000 pieces) (y)
            1                                        112
            2                                        148
            3                                        241
            4                                        363
            5                                        585

I Need to find 2 things
first calculate with growth function third day count and I have been counted.
=GROWTH(I3:I4;H3:H4;H5)

But I need to calculate parameters of growth function( =.^)

So how to calculate a and b? I tried to use excel solver but i didn't solve


问:
Wix + uninstall from control panel + Application running
I have a Wix solution to install an application. When attempting to uninstall the application from control panel while it is running, a popup is appearing to close the application before continue.

The issues is the message showing in that popup which is suppose to be an uninstall message instead of install message.

The message is "The following application is running which is need to be close before continuing the install"

can we customize this default popup and change our message?

答:
You can modify this default message. Edit FilesInUse and MsiRMFilesInUse dialogs. You can edit them directly in the .wsx file or use a GUI editor. (The dialogs that you need to edit can be defined either in your .wsx file or come from a predefined WiX UI.)

Using WixEdit, you can use a visual designer.

You would better change the part of the string to come from a property.

The following application is running which is need to be close before continuing the [CURRENT_ACTION]

You will set the value of the CURRENT_ACTION depending on the mode of installation. You can find an example of doing it in the default WiX dialog set, the maintenance dialog: when user selects the mode (Modify, Repair, Remove), a property value is set which is then used on the progress page.


问:
Open txt file through Tkinter GUI
I'm wondering how to open a file through a Tkinter GUI, example having a button in your interface that opens a .txt file. It doesn't matter if it loads into a textbox or if it opens in the text-editor just want it to open. Preferably to open in the text-editor.

```<code>def openInstruktion():
    f= open("instruktioner.txt")

instruktionBtn = Button(root, text='Spelinstruktioner', command=openInstruktion)
instruktionBtn.grid(row=6, column=0)
</code>```

I've searched the web for some answer but most people use the menubar. I want it to open through the button posted above.

答:
```<code>def help():
    readme = "F:\\yourpath\\readme.txt"
    os.startfile(readme)
</code>```

just use this function , but first do import os at the top..

Title: Open txt file through Tkinter GUI

Body:
I'm wondering how to open a file through a Tkinter GUI, example having a button in your interface that opens a .txt file. It doesn't matter if it loads into a textbox or if it opens in the text-editor just want it to open. Preferably to open in the text-editor.

def openInstruktion():
    f= open("instruktioner.txt")

instruktionBtn = Button(root, text='Spelinstruktioner', command=openInstruktion)
instruktionBtn.grid(row=6, column=0)

I've searched the web for some answer but most people use the menubar. I want it to open through the button posted above.

Body:
def help():
    readme = "F:\\yourpath\\readme.txt"
    os.startfile(readme)

just use this function , but first do import os at the top..


问:
Binding Image-Source to position of piece C#
Situation: I'am developing a chess game where the user can move the pieces on the board.

The board contains 8x8 fields (=64) just like a normal one.

The board: The board is a dynamically created Grid with 8 rows and 8 columns. Each "field" contains another Grid that contains a Rectangle (=the color of the field using the fill property) and an Image (=the image of the piece on the field [piece or empty]).

What I want to do: I want to bind the source property of the images to the position of any piece.

Example: When the position of any piece changes, the image automatically removes the old source (because the piece moved away) & the field where the piece is located now, updates the image source.

To be clear: I have a pawn at (1,1)||(A,1) and move it to (1,2)||(A,2). Now the image-source of the old position (1,1)||(A,1) should be set to empty because the piece moved, and the image-soruce of the new position-field should be set to "pawn.png".

How it works now: At the moment I have a click event on the image. When a first click event is registered, I save the clicked image (=ref) and wait for a second click. When a second click is registered, I set the source of the second clicked image equals the source of the first clicked image and the source of the first clicked image to an empty source... But this isn't a good solution...

Question: How can I do a binding to the 64 image-sources so that every position change of the 32 pieces gets notified to the UI?

Here the class ChessField:

```<code>    public class ChessField : INotifyPropertyChanged
{
    public int X { get; protected set; }
    public int Y { get; protected set; }

    public bool Recheable
    {
        get;
        set;
    }

    private readonly SolidColorBrush _defaultFieldColor;

    public ChessField(int X, int Y, SolidColorBrush fieldColor)
    {
        this.X = X;
        this.Y = Y;
        ColorProperty = fieldColor;
        _defaultFieldColor = fieldColor;
        Recheable = false;
    }

    public void SetToDefault()
    {
        ColorProperty = _defaultFieldColor;
        Recheable = false;
    }

    private SolidColorBrush colorProperty;

    public SolidColorBrush ColorProperty
    {
        get
        {
            return colorProperty;
        }

        set
        {
            if (colorProperty == value) return;

            colorProperty = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
</code>```

PiecePos is a struct and looks like this:

```<code>public struct PiecePos
{
    public int X { get; set; }
    public int Y { get; set; }

    public PiecePos(int X, int Y)
    {
        this.X = X;
        this.Y = Y;
    }

    public override bool Equals(object obj)
    {
        if (!(obj is PiecePos))
        {
            return false;
        }

        PiecePos toCompare = (PiecePos)obj;
        return (this.X == toCompare.X) && (this.Y == toCompare.Y);
    }
}
</code>```

Any help would be appreciated ! Thanks

答:
After some work I solved the problem...

Solution:

Add a ImageSource property to the ChessField-Class

Add a default value to the ChessField-Class constructor

Do the binding where you dynamically create the Images

The ChessField should look like this:

```<code>public class ChessField : INotifyPropertyChanged
{
    public int X { get; protected set; }
    public int Y { get; protected set; }

    public bool Recheable
    {
        get;
        set;
    }

    private readonly SolidColorBrush _defaultFieldColor;

    public ChessField(int X, int Y, SolidColorBrush fieldColor, ImageSource imageSource)
    {
        this.X = X;
        this.Y = Y;
        ColorProperty = fieldColor;
        _defaultFieldColor = fieldColor;
        this.ImageSource = imageSource;
        Recheable = false;
    }

    public void SetToDefault()
    {
        ColorProperty = _defaultFieldColor;
        Recheable = false;
    }

    private SolidColorBrush colorProperty;

    public SolidColorBrush ColorProperty
    {
        get
        {
            return colorProperty;
        }

        set
        {
            if (colorProperty == value) return;

            colorProperty = value;
            OnPropertyChanged();
        }
    }

    private ImageSource imageSource;

    public ImageSource ImageSource
    {
        get { return imageSource; }
        set
        {
            if (imageSource == value) return;

            imageSource = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
</code>```

Here how to dynamically create the Images and add them to the UI:

```<code>private void CreateImages()
    {
        ChessField chessField = new ChessField(X, Y, defaultColor, startImage); //Create field

        //Each field is a single grid
        Grid fieldGrid = new Grid();
        fieldGrid.SetValue(Grid.RowProperty, Helper.BoardSize - Y);
        fieldGrid.SetValue(Grid.ColumnProperty, X - 1);

        Image imageField = new Image();
        imageField.MouseDown += ImageClickEvent; //Click event
        imageField.HorizontalAlignment = HorizontalAlignment.Stretch;
        imageField.VerticalAlignment = VerticalAlignment.Stretch;
        imageField.Tag = x + "," + y; //Set the image tag (needed for the click event)

        imageField.DataContext = chessField;
        imageField.SetBinding(Image.SourceProperty, "ImageSource"); //Binding

        _chessFields.Add(chessField); //Add to list --> so we can access the field on the click event

        fieldGrid.Children.Add(imageField);
        BoardGrid.Children.Add(fieldGrid); //Add field-grid to the main-grid in the XAML
    }
</code>```

Image click event:

```<code>private void ImageClickEvent()
    {
        //Move to
        var pieceToMove = Board.PiecesOnTheBoard
            .FirstOrDefault(piece => piece.Position.X == _lastSelectedField.X && piece.Position.Y == _lastSelectedField.Y && piece.IsAlive);

        var oldField = _chessFields.FirstOrDefault(field =>
            field.X == pieceToMove.Position.X && field.Y == pieceToMove.Position.Y);

        pieceToMove?.Move(new PiecePos(clickedChessField.X, clickedChessField.Y)); //Move

        var newField = _chessFields.FirstOrDefault(field =>
            field.X == pieceToMove?.Position.X && field.Y == pieceToMove.Position.Y);

        if (oldField != null)
        {
            oldField.ImageSource = Helper.EmptyImage; //Use binding to change image
        }

        if (newField != null)
        {
            newField.ImageSource = pieceToMove?.GetImage(); //Use binding to change image
        }
    }
</code>```

Body:
Situation: I'am developing a chess game where the user can move the pieces on the board.

The board contains 8x8 fields (=64) just like a normal one.

The board: The board is a dynamically created Grid with 8 rows and 8 columns. Each "field" contains another Grid that contains a Rectangle (=the color of the field using the fill property) and an Image (=the image of the piece on the field [piece or empty]).

What I want to do: I want to bind the source property of the images to the position of any piece.

Example: When the position of any piece changes, the image automatically removes the old source (because the piece moved away) & the field where the piece is located now, updates the image source.

To be clear: I have a pawn at (1,1)||(A,1) and move it to (1,2)||(A,2). Now the image-source of the old position (1,1)||(A,1) should be set to empty because the piece moved, and the image-soruce of the new position-field should be set to "pawn.png".

How it works now: At the moment I have a click event on the image. When a first click event is registered, I save the clicked image (=ref) and wait for a second click. When a second click is registered, I set the source of the second clicked image equals the source of the first clicked image and the source of the first clicked image to an empty source... But this isn't a good solution...

Question: How can I do a binding to the 64 image-sources so that every position change of the 32 pieces gets notified to the UI?

Here the class ChessField:

    public class ChessField : INotifyPropertyChanged
{
    public int X { get; protected set; }
    public int Y { get; protected set; }

    public bool Recheable
    {
        get;
        set;
    }

    private readonly SolidColorBrush _defaultFieldColor;

    public ChessField(int X, int Y, SolidColorBrush fieldColor)
    {
        this.X = X;
        this.Y = Y;
        ColorProperty = fieldColor;
        _defaultFieldColor = fieldColor;
        Recheable = false;
    }

    public void SetToDefault()
    {
        ColorProperty = _defaultFieldColor;
        Recheable = false;
    }

    private SolidColorBrush colorProperty;

    public SolidColorBrush ColorProperty
    {
        get
        {
            return colorProperty;
        }

        set
        {
            if (colorProperty == value) return;

            colorProperty = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

PiecePos is a struct and looks like this:

public struct PiecePos
{
    public int X { get; set; }
    public int Y { get; set; }

    public PiecePos(int X, int Y)
    {
        this.X = X;
        this.Y = Y;
    }

    public override bool Equals(object obj)
    {
        if (!(obj is PiecePos))
        {
            return false;
        }

        PiecePos toCompare = (PiecePos)obj;
        return (this.X == toCompare.X) && (this.Y == toCompare.Y);
    }
}

Any help would be appreciated ! Thanks

Body:
After some work I solved the problem...

Solution:

Add a ImageSource property to the ChessField-Class

Add a default value to the ChessField-Class constructor

Do the binding where you dynamically create the Images

The ChessField should look like this:

public class ChessField : INotifyPropertyChanged
{
    public int X { get; protected set; }
    public int Y { get; protected set; }

    public bool Recheable
    {
        get;
        set;
    }

    private readonly SolidColorBrush _defaultFieldColor;

    public ChessField(int X, int Y, SolidColorBrush fieldColor, ImageSource imageSource)
    {
        this.X = X;
        this.Y = Y;
        ColorProperty = fieldColor;
        _defaultFieldColor = fieldColor;
        this.ImageSource = imageSource;
        Recheable = false;
    }

    public void SetToDefault()
    {
        ColorProperty = _defaultFieldColor;
        Recheable = false;
    }

    private SolidColorBrush colorProperty;

    public SolidColorBrush ColorProperty
    {
        get
        {
            return colorProperty;
        }

        set
        {
            if (colorProperty == value) return;

            colorProperty = value;
            OnPropertyChanged();
        }
    }

    private ImageSource imageSource;

    public ImageSource ImageSource
    {
        get { return imageSource; }
        set
        {
            if (imageSource == value) return;

            imageSource = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Here how to dynamically create the Images and add them to the UI:

private void CreateImages()
    {
        ChessField chessField = new ChessField(X, Y, defaultColor, startImage); //Create field

        //Each field is a single grid
        Grid fieldGrid = new Grid();
        fieldGrid.SetValue(Grid.RowProperty, Helper.BoardSize - Y);
        fieldGrid.SetValue(Grid.ColumnProperty, X - 1);

        Image imageField = new Image();
        imageField.MouseDown += ImageClickEvent; //Click event
        imageField.HorizontalAlignment = HorizontalAlignment.Stretch;
        imageField.VerticalAlignment = VerticalAlignment.Stretch;
        imageField.Tag = x + "," + y; //Set the image tag (needed for the click event)

        imageField.DataContext = chessField;
        imageField.SetBinding(Image.SourceProperty, "ImageSource"); //Binding

        _chessFields.Add(chessField); //Add to list --> so we can access the field on the click event

        fieldGrid.Children.Add(imageField);
        BoardGrid.Children.Add(fieldGrid); //Add field-grid to the main-grid in the XAML
    }

Image click event:

private void ImageClickEvent()
    {
        //Move to
        var pieceToMove = Board.PiecesOnTheBoard
            .FirstOrDefault(piece => piece.Position.X == _lastSelectedField.X && piece.Position.Y == _lastSelectedField.Y && piece.IsAlive);

        var oldField = _chessFields.FirstOrDefault(field =>
            field.X == pieceToMove.Position.X && field.Y == pieceToMove.Position.Y);

        pieceToMove?.Move(new PiecePos(clickedChessField.X, clickedChessField.Y)); //Move

        var newField = _chessFields.FirstOrDefault(field =>
            field.X == pieceToMove?.Position.X && field.Y == pieceToMove.Position.Y);

        if (oldField != null)
        {
            oldField.ImageSource = Helper.EmptyImage; //Use binding to change image
        }

        if (newField != null)
        {
            newField.ImageSource = pieceToMove?.GetImage(); //Use binding to change image
        }
    }


问:
Getting Error TypeError: Cannot read property 'rows' of null
I am fairly new to react and I am trying add a row in my react app on the click of a button. I followed this link How to add and remove table rows Dynamically in React.js

to do so but I am not able to translate it to my code.

My code here:
KPIDetails.js
Here I am rendering the view in KPI Details.js file.

```<code><MuiThemeProvider>
    <React.Fragment>
        <Grid container>
            <Grid item xs={6} direction="row" alignItems="center">
                <table
                    className="table table-bordered table-hover"
                    id="tab_logic"
                >
                    <thead>
                    <tr>
                        <th className="text-center"> KPI</th>
                        <th className="text-center"> UOM</th>
                        <th className="text-center"> Base</th>
                        <th className="text-center"> Target</th>
                        <th className="text-center"> Target Date</th>
                    </tr>
                    </thead>
                    <tbody>
                    {this.state.rows.map((item, idx) => (
                        <tr id="addr0" key={idx}>
                            <td>{idx}</td>
                            <td>
                                <input
                                    type="text"
                                    name="Kpi_Before"
                                    value={this.state.rows[idx].Kpi_Before}
                                    onChange={this.handleChangeRows(idx)}
                                    className="form-control"
                                />
                            </td>
                            <td>
                                <input
                                    type="text"
                                    name="UOM_Before"
                                    value={this.state.rows[idx].UOM_Before}
                                    onChange={this.handleChangeRows(idx)}
                                    className="form-control"
                                />
                            </td>
                            <td>
                                <input
                                    type="text"
                                    name="Base_Before"
                                    value={this.state.rows[idx].Base_Before}
                                    onChange={this.handleChangeRows(idx)}
                                    className="form-control"
                                />
                            </td>
                            <td>
                                <input
                                    type="text"
                                    name="Target_Before"
                                    value={this.state.rows[idx].Target_Before}
                                    onChange={this.handleChangeRows(idx)}
                                    className="form-control"
                                />
                            </td>
                            <td>
                                <input
                                    type="text"
                                    name="Target_Before"
                                    value={this.state.rows[idx].dateTime}
                                    onChange={this.handleChangeRows(idx)}
                                    className="form-control"
                                />
                            </td>
                        </tr>
                    ))}
                    </tbody>
                </table>
                <button
                    onClick={this.handleRemoveRow}
                    className="pull-right btn btn-default"
                >
                    Delete Row
                </button>
                <Button
                    variant="outlined"
                    color="primary"
                    onClick={this.handleAddRow}
                    size="small"
                    style={styles.button}
                >
                    +
                </Button>
            </Grid>
        </Grid>
        < /React.Fragment>
</MuiThemeProvider>
</code>```

This is the js file where I call all the functions

User Form.js

```<code>export class UserForm extends Component {
    state = {
        step: 1,
        Title: "",
        Details: "",
        What: "",
        Why: "",
        How: "",
        Status: "",
        Cost: "",
        Benefits: "",
        Kpi_Before: "",
        Kpi_After: "",
        Time: "",
        UOM_Before: "",
        Base_Before: "",
        Target_Before: "",
        dateTime: null,
        rows: ["row1"]
    };

    //1
    handleChangeRows = idx => e => {
        const {Kpi_Before, value} = e.target;
        const rows = [...this.state.rows];
        rows[idx] = {
            [Kpi_Before]: value
        };
        this.setState({
            rows
        });
    };

    //2
    handleAddRow = () => {
        const item = {
            KPI_Before: "",
            UOM_Before: "",
            Base_Before: "",
            Target_Before: "",
            dateTime: ""
        };
        this.setState({
            rows: [...this.state.rows, item]
        });
    };

    //3
    handleRemoveRow = () => {
        this.setState({
            rows: this.state.rows.slice(0, -1)
        });
    };
}
</code>```

What am I doing wrong. Is there any other way to do it?

答:
I have added:

```<code>state = {
    rows: []
  };
</code>```

in the component and it solved the issue

Body:
I am fairly new to react and I am trying add a row in my react app on the click of a button. I followed this link How to add and remove table rows Dynamically in React.js

to do so but I am not able to translate it to my code.

My code here:
KPIDetails.js
Here I am rendering the view in KPI Details.js file.

<MuiThemeProvider>
    <React.Fragment>
        <Grid container>
            <Grid item xs={6} direction="row" alignItems="center">

                         KPI
                         UOM
                         Base
                         Target
                         Target Date

                    {this.state.rows.map((item, idx) => (

                            {idx}

                                <input
                                    type="text"
                                    name="Kpi_Before"
                                    value={this.state.rows[idx].Kpi_Before}
                                    onChange={this.handleChangeRows(idx)}
                                    className="form-control"
                                />

                                <input
                                    type="text"
                                    name="UOM_Before"
                                    value={this.state.rows[idx].UOM_Before}
                                    onChange={this.handleChangeRows(idx)}
                                    className="form-control"
                                />

                                <input
                                    type="text"
                                    name="Base_Before"
                                    value={this.state.rows[idx].Base_Before}
                                    onChange={this.handleChangeRows(idx)}
                                    className="form-control"
                                />

                                <input
                                    type="text"
                                    name="Target_Before"
                                    value={this.state.rows[idx].Target_Before}
                                    onChange={this.handleChangeRows(idx)}
                                    className="form-control"
                                />

                                <input
                                    type="text"
                                    name="Target_Before"
                                    value={this.state.rows[idx].dateTime}
                                    onChange={this.handleChangeRows(idx)}
                                    className="form-control"
                                />

                    ))}

                <button
                    onClick={this.handleRemoveRow}
                    className="pull-right btn btn-default"
                >
                    Delete Row
                </button>
                <Button
                    variant="outlined"
                    color="primary"
                    onClick={this.handleAddRow}
                    size="small"
                    style={styles.button}
                >
                    +
                </Button>
            </Grid>
        </Grid>
        < /React.Fragment>
</MuiThemeProvider>

This is the js file where I call all the functions

User Form.js

export class UserForm extends Component {
    state = {
        step: 1,
        Title: "",
        Details: "",
        What: "",
        Why: "",
        How: "",
        Status: "",
        Cost: "",
        Benefits: "",
        Kpi_Before: "",
        Kpi_After: "",
        Time: "",
        UOM_Before: "",
        Base_Before: "",
        Target_Before: "",
        dateTime: null,
        rows: ["row1"]
    };

    //1
    handleChangeRows = idx => e => {
        const {Kpi_Before, value} = e.target;
        const rows = [...this.state.rows];
        rows[idx] = {
            [Kpi_Before]: value
        };
        this.setState({
            rows
        });
    };

    //2
    handleAddRow = () => {
        const item = {
            KPI_Before: "",
            UOM_Before: "",
            Base_Before: "",
            Target_Before: "",
            dateTime: ""
        };
        this.setState({
            rows: [...this.state.rows, item]
        });
    };

    //3
    handleRemoveRow = () => {
        this.setState({
            rows: this.state.rows.slice(0, -1)
        });
    };
}

What am I doing wrong. Is there any other way to do it?

Body:
I have added:

state = {
    rows: []
  };

in the component and it solved the issue


问:
GeoDjango on Windows: "Could not find the GDAL library" / "OSError: [WinError 126] The specified module could not be found"
I've been trying to setup my windows computer such that I can have a local postgreSQL with PostGIS extension. With this installed I hope to be able to create a project with geodjango locally before putting it in the cloud. I have been working with Django for a little while now on my local machine with the SQLite DB, but since the next project will partly be based on coordinate based data I wanted to setup the right environment.

Import note: I've installed mini-conda to run in a seperate environment. I do activate this environment "development" when I work though

I've tried to follow most of the geodjango information/tutorials online, but can't get it to work. What I've done (mostly followed this: https://docs.djangoproject.com/en/2.0/ref/contrib/gis/install/#windows):

Download and install the latest (10.3) PostgreSQL setup from https://www.enterprisedb.com/downloads/postgres-postgresql-downloads

After installation I also installed used the Application Stack Builder to install PostGis

I've installed OSGeo4W from https://trac.osgeo.org/osgeo4w/

I've created a batch script as described on the geodjango website (https://docs.djangoproject.com/en/2.0/ref/contrib/gis/install/#windows) and ran it as administrator (except for the part where it sets the path to python, cause python was already in there since I've been using python for a while now)

I've tried some command in psql shell and I think I've created a database with name: geodjango, username: **** and pass: ****.

I don't know if I have given the geodjango user all priveleges, but I suspect so.

After all of this I created a new django project and in settings.py I've added some parts:

```<code>INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'nameOfMyApp',
]
</code>```

I've also got this in settings.py:

```<code>DATABASES = {
'default': {
    'ENGINE': 'django.contrib.gis.db.backends.postgis',
    'NAME': 'geodjango',
    'USER': '****',
    'PASSWORD': '****',
    'HOST': 'localhost',
}
}

# FOR GEODJANGO
POSTGIS_VERSION = (2, 4, 3)
</code>```

When I try to set up the database in django I run (in the right folder):

```<code>python manage.py makemigrations
</code>```

I get the following error:

```<code>django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal202", "gdal201", "gdal20", "gdal111", "gdal110", "gdal19"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings.
</code>```

I've tried to fix that, but nothing seems to work.
Can anybody give me some help in setting this all up locally?

Update 7-3-2018:

I've tried installing GDAL manually myself, (from: http://www.gisinternals.com/query.html?content=filelist&file=release-1911-x64-gdal-2-2-3-mapserver-7-0-7.zip the generic core components)

I've installed (what I assume are) the python bindings from https://www.lfd.uci.edu/~gohlke/pythonlibs/. Still I get the same error.

I've also tried setting the GDAL_LIBRARY_PATH to the GDAL directory or the gdal-data directory (which resides in the GDAL directory).

Now I get the following error:

```<code>OSError: [WinError 126] The specified module could not be found
</code>```

(while the .dll is there...)

答:
I had the same error "The specified module could not be found," even though gdal204.dll was present at the expected location, with the right architecture (which I verified by adding asserts in the Python code and loading the DLL from a C program).

It turned out to be an issue with the Python 3.7 app from the Microsoft Store, the one that automatically installs the first time you type python on the command line.
This version of Python refuses to load the GDAL DLL; I don't know if it's a bug or a security feature.

I fixed the issue by:

uninstalling the Python app

removing the app execution aliases (as explained in the app description)

installing the regular Python package from python.org

Body:
I've been trying to setup my windows computer such that I can have a local postgreSQL with PostGIS extension. With this installed I hope to be able to create a project with geodjango locally before putting it in the cloud. I have been working with Django for a little while now on my local machine with the SQLite DB, but since the next project will partly be based on coordinate based data I wanted to setup the right environment.

Import note: I've installed mini-conda to run in a seperate environment. I do activate this environment "development" when I work though

I've tried to follow most of the geodjango information/tutorials online, but can't get it to work. What I've done (mostly followed this: https://docs.djangoproject.com/en/2.0/ref/contrib/gis/install/#windows):

Download and install the latest (10.3) PostgreSQL setup from https://www.enterprisedb.com/downloads/postgres-postgresql-downloads

After installation I also installed used the Application Stack Builder to install PostGis

I've installed OSGeo4W from https://trac.osgeo.org/osgeo4w/

I've created a batch script as described on the geodjango website (https://docs.djangoproject.com/en/2.0/ref/contrib/gis/install/#windows) and ran it as administrator (except for the part where it sets the path to python, cause python was already in there since I've been using python for a while now)

I've tried some command in psql shell and I think I've created a database with name: geodjango, username: **** and pass: ****.

I don't know if I have given the geodjango user all priveleges, but I suspect so.

After all of this I created a new django project and in settings.py I've added some parts:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'nameOfMyApp',
]

I've also got this in settings.py:

DATABASES = {
'default': {
    'ENGINE': 'django.contrib.gis.db.backends.postgis',
    'NAME': 'geodjango',
    'USER': '****',
    'PASSWORD': '****',
    'HOST': 'localhost',
}
}

# FOR GEODJANGO
POSTGIS_VERSION = (2, 4, 3)

When I try to set up the database in django I run (in the right folder):

python manage.py makemigrations

I get the following error:

django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal202", "gdal201", "gdal20", "gdal111", "gdal110", "gdal19"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings.

I've tried to fix that, but nothing seems to work.
Can anybody give me some help in setting this all up locally?

Update 7-3-2018:

I've tried installing GDAL manually myself, (from: http://www.gisinternals.com/query.html?content=filelist&file=release-1911-x64-gdal-2-2-3-mapserver-7-0-7.zip the generic core components)

I've installed (what I assume are) the python bindings from https://www.lfd.uci.edu/~gohlke/pythonlibs/. Still I get the same error.

I've also tried setting the GDAL_LIBRARY_PATH to the GDAL directory or the gdal-data directory (which resides in the GDAL directory).

Now I get the following error:

OSError: [WinError 126] The specified module could not be found

(while the .dll is there...)


问:
Compiling Java program in terminal causes log error
I am trying to compile a Java program in the terminal:

Long version containing all the imports:

```<code>javac -classpath bin:$OSPL_HOME/jar/dcpssaj5.jar:$OSPL_HOME/jar/dcpssaj5-sources.jar:$OSPL_HOME/jar/dcpssaj-osgi-bundle.jar:$OSPL_HOME/jar/dcpssaj-sources.jar:$OSPL_HOME/jar/dcpssaj.jar:$OSPL_HOME/jar/osplconf.jar:$OSPL_HOME/jar/tooling_common.jar:$OSPL_HOME/jar/dcpsprotobuf.jar:$OSPL_HOME/jar/cmdataadapter.jar:$OSPL_HOME/jar/cmapi.jar:$OSPL_HOME/jar/ddsface.jar:Libraries/httpclient-4.5.12.jar:Libraries/jersey-client-1.19.4.jar:Libraries/jersey-client-1.19.jar:Libraries/jersey-core-1.19.4.jar:Libraries/json-simple-1.1.1.jar:Libraries/json-simple-3.1.0.jar:Libraries/jsr311-api-1.1.1.jar:Libraries/mqtt-client-0.0.6.jar:Libraries/paho-mqtt-client-1.13.0.jar -sourcepath src/ src/afarcloud/Main/afarcloud_main.java
</code>```

Without all the imports:

```<code>javac -classpath bin:(jar_files) -sourcepath src/ src/afarcloud/Main/afarcloud_main.java
</code>```

I have added what I thought would be all the necessaries jars, however I get the following error related to a logger when I try to run the code on my Ubuntu computer:

```<code>src/afarcloud/Log/UtilLog.java:3: error: package org.apache.log4j does not exist
import org.apache.log4j.Logger;
                       ^
src/afarcloud/Log/UtilLog.java:7: error: cannot find symbol
    private static Logger log = Logger.getLogger(UtilLog.class);
                   ^
  symbol:   class Logger
  location: class UtilLog
src/afarcloud/Log/UtilLog.java:7: error: cannot find symbol
    private static Logger log = Logger.getLogger(UtilLog.class);
                                ^
  symbol:   variable Logger
  location: class UtilLog
src/afarcloud/Log/UtilLog.java:10: error: cannot find symbol
        log = Logger.getLogger(clase);
              ^
  symbol:   variable Logger
  location: class UtilLog
4 errors
</code>```

What confuses me is that there is no folder called "Log" under src/afarcloud, so I am pretty confused about how to proceed... Any help is highly appreciated, thank you.

答:
Instead of mentioning the jar files of a directory individually, you should use wildcard character * to specify all jars of the directory e.g.

```<code>javac -d bin -cp .:$OSPL_HOME/jar/*:Libraries/*:lib/* -sourcepath src src/afarcloud/Main/afarcloud_main.java
</code>```

where

-d bin specifies the directory where the compiled class will be put.

. with -cp or -classpath includes the current directory in the classpath.

: specifies the separator to use multiple locations in the classpath.

$OSPL_HOME/jar/* specifies all the files in the directory, $OSPL_HOME/jar. Alternatively, you can use $OSPL_HOME/jar/*.jar to specify just jar files.

Note: Make sure you also specify the location of the apache-logging-log4j.jar in your command because the error shows that you have missed to include this jar.

Body:
I am trying to compile a Java program in the terminal:

Long version containing all the imports:

javac -classpath bin:$OSPL_HOME/jar/dcpssaj5.jar:$OSPL_HOME/jar/dcpssaj5-sources.jar:$OSPL_HOME/jar/dcpssaj-osgi-bundle.jar:$OSPL_HOME/jar/dcpssaj-sources.jar:$OSPL_HOME/jar/dcpssaj.jar:$OSPL_HOME/jar/osplconf.jar:$OSPL_HOME/jar/tooling_common.jar:$OSPL_HOME/jar/dcpsprotobuf.jar:$OSPL_HOME/jar/cmdataadapter.jar:$OSPL_HOME/jar/cmapi.jar:$OSPL_HOME/jar/ddsface.jar:Libraries/httpclient-4.5.12.jar:Libraries/jersey-client-1.19.4.jar:Libraries/jersey-client-1.19.jar:Libraries/jersey-core-1.19.4.jar:Libraries/json-simple-1.1.1.jar:Libraries/json-simple-3.1.0.jar:Libraries/jsr311-api-1.1.1.jar:Libraries/mqtt-client-0.0.6.jar:Libraries/paho-mqtt-client-1.13.0.jar -sourcepath src/ src/afarcloud/Main/afarcloud_main.java

Without all the imports:

javac -classpath bin:(jar_files) -sourcepath src/ src/afarcloud/Main/afarcloud_main.java

I have added what I thought would be all the necessaries jars, however I get the following error related to a logger when I try to run the code on my Ubuntu computer:

src/afarcloud/Log/UtilLog.java:3: error: package org.apache.log4j does not exist
import org.apache.log4j.Logger;
                       ^
src/afarcloud/Log/UtilLog.java:7: error: cannot find symbol
    private static Logger log = Logger.getLogger(UtilLog.class);
                   ^
  symbol:   class Logger
  location: class UtilLog
src/afarcloud/Log/UtilLog.java:7: error: cannot find symbol
    private static Logger log = Logger.getLogger(UtilLog.class);
                                ^
  symbol:   variable Logger
  location: class UtilLog
src/afarcloud/Log/UtilLog.java:10: error: cannot find symbol
        log = Logger.getLogger(clase);
              ^
  symbol:   variable Logger
  location: class UtilLog
4 errors

What confuses me is that there is no folder called "Log" under src/afarcloud, so I am pretty confused about how to proceed... Any help is highly appreciated, thank you.

Body:
Instead of mentioning the jar files of a directory individually, you should use wildcard character * to specify all jars of the directory e.g.

javac -d bin -cp .:$OSPL_HOME/jar/*:Libraries/*:lib/* -sourcepath src src/afarcloud/Main/afarcloud_main.java

where

-d bin specifies the directory where the compiled class will be put.

. with -cp or -classpath includes the current directory in the classpath.

: specifies the separator to use multiple locations in the classpath.

$OSPL_HOME/jar/* specifies all the files in the directory, $OSPL_HOME/jar. Alternatively, you can use $OSPL_HOME/jar/*.jar to specify just jar files.

Note: Make sure you also specify the location of the apache-logging-log4j.jar in your command because the error shows that you have missed to include this jar.


问:
How to declare string in C# without having to escape special characters?
Is there a way to declare strings in C# without having to escape special characters?

I have searched for answers and found some string literal syntaxes that I thought would achieve what I wanted, but did not.

```<code>string lit = ""<?xml version="1.0" encoding="utf-8"?""
string lit = @"<?xml version="1.0" encoding="utf-8"?"

error CS1525: Invalid expression term '?'
</code>```

答:
inside the string literal if we need to use double quote we will still need to escape it in verbatim string too like:

```<code>string lit = @"<?xml version=""1.0"" encoding=""utf-8""?";
</code>```

the value in variable will be :

```<code><?xml version="1.0" encoding="utf-8"?
</code>```

Body:
Is there a way to declare strings in C# without having to escape special characters?

I have searched for answers and found some string literal syntaxes that I thought would achieve what I wanted, but did not.

string lit = ""<?xml version="1.0" encoding="utf-8"?""
string lit = @"<?xml version="1.0" encoding="utf-8"?"

error CS1525: Invalid expression term '?'

Body:
inside the string literal if we need to use double quote we will still need to escape it in verbatim string too like:

string lit = @"<?xml version=""1.0"" encoding=""utf-8""?";

the value in variable will be :

<?xml version="1.0" encoding="utf-8"?


答:
Is there a way to declare strings in C# without having to escape special characters?

When considering " as a special character, the answer is no.

Verbatim string literals (@"foo") avoid you having to escape backslashes and line breaks, but you still need to escape double quotes. The correct escaping for your examples would be:

string lit = "<?xml version=\"1.0\" encoding=\"utf-8\"?";
string lit = @"<?xml version=""1.0"" encoding=""utf-8""?";
```

<p>I often find that for JSON and XML, in test code at least, it's simplest to use single quotes and then replace them:</p>

<pre class="lang-cs prettyprint-override"><code>string lit = "<?xml version='1.0' encoding='utf-8'?".Replace('\'', '"');
</code>```

Or for XML you could just use single quotes for attributes anyway.

Title: How to declare string in C# without having to escape special characters?

Body:
Is there a way to declare strings in C# without having to escape special characters?

When considering " as a special character, the answer is no.

Verbatim string literals (@"foo") avoid you having to escape backslashes and line breaks, but you still need to escape double quotes. The correct escaping for your examples would be:

string lit = "<?xml version=\"1.0\" encoding=\"utf-8\"?";
string lit = @"<?xml version=""1.0"" encoding=""utf-8""?";

I often find that for JSON and XML, in test code at least, it's simplest to use single quotes and then replace them:

string lit = "<?xml version='1.0' encoding='utf-8'?".Replace('\'', '"');

Or for XML you could just use single quotes for attributes anyway.


问:
Monkey patch getUserMedia in a WebExtension?

What I'm trying to do:

First question here, sorry for any mistakes.

Basically what I want to do is implement filters for the webcam so that everyone you are in a video conference/call/meeting with can see it if you have webcam on. My first thought was to use CSS filters, which was stupid in hindsight, since it won't be seen by everybody.

Then I did some research(say, googling) and found out about a similar WebExtension, ZomboCam,(whose source I saw with crxviewer) which, basically intercepts the mediaStream, edits it, and sets the edited mediaStream as source of your webcam. I looked at its source, and found out that it Monkey Patches (or is it monkeypatches) the getUserMedia() function. In the source,

```<code>var originalMediaDevicesGetUserMedia = navigator.mediaDevices.getUserMedia;
if (navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices.getUserMedia = function getUserMedia(constraints) {
          return new Promise(function (resolve, reject) {
            originalMediaDevicesGetUserMedia.bind(navigator.mediaDevices)(constraints).then(function (stream) {
              return resolve(enhance(stream));
            }).catch(reject);
          });
        };
      }
</code>```

The enhance() function works on a mediaStream passed to it as parameter.

What I tried:

I did the monkeypatching code in the content script of the WebExtension, if that helps.

I tried monkeypatching like this, in a webpage with a video element to display the webcam. It reached the Video devices found!, but not any further.

change() will be my function to work on mediaStream(any helpful tips for that?),  and it doesn't do anything as of now.

```<code>const OGgum =  navigator.mediaDevices.getUserMedia;
    if(navigator.mediaDevices.getUserMedia){
        console.log('Video devices found!');
        navigator.mediaDevices.getUserMedia = (constraints) => {
            OGgum(constraints).then((stream)=> {
              console.log('gum Patched');
              video.srcObject = change(stream);
            })
            .catch((error)=>{
              console.log('This Went wrong: '+error);
            })
          }
    }
    const change = (st) => {
      return st;
    }
</code>```

Now with the disappointment of that not working, I tried monkey patching console.log() in the content script of the webextension to add some text in front of every log, like this:

```<code>const OGlog = console.log;
console.log = (params) => {
  OGlog(' PATCHING: '+params);
}

console.log('Testing');
</code>```

Outputs:

```<code> PATCHING: Testing
</code>```

which WORKED but ONLY for console.log() INSIDE the content script. How do I make it work for every page? Meaning, suppose I do a console.log(), I expect it to have  PATCHING in front.

I supposed if I manage to get console.log() to work, I can probably work on the getUserMedia() myself.

Relevant Reading

What am I missing here? Also if you have alternatives for this task, please share them. Thanks!

答:
In Firefox you should use wrappedJSObject to access the page context and exportFunction to expose your code into the page context. More info on MDN: Sharing objects with page scripts.

```<code>const pWindow = window.wrappedJSObject;
const pMediaDevices = pWindow.navigator.mediaDevices;
const pGUM = pMediaDevices.getUserMedia;
const myGUM = (...args) =>
  pGUM.apply(pMediaDevices, args).then(stream => {
    // .........
    return stream;
  });
pMediaDevices.getUserMedia = exportFunction(myGUM, pWindow);
</code>```

If you thought it's complicated, in Chrome/Chromium browsers it's even worse.

Body:
What I'm trying to do:

First question here, sorry for any mistakes.

Basically what I want to do is implement filters for the webcam so that everyone you are in a video conference/call/meeting with can see it if you have webcam on. My first thought was to use CSS filters, which was stupid in hindsight, since it won't be seen by everybody.

Then I did some research(say, googling) and found out about a similar WebExtension, ZomboCam,(whose source I saw with crxviewer) which, basically intercepts the mediaStream, edits it, and sets the edited mediaStream as source of your webcam. I looked at its source, and found out that it Monkey Patches (or is it monkeypatches) the getUserMedia() function. In the source,

var originalMediaDevicesGetUserMedia = navigator.mediaDevices.getUserMedia;
if (navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices.getUserMedia = function getUserMedia(constraints) {
          return new Promise(function (resolve, reject) {
            originalMediaDevicesGetUserMedia.bind(navigator.mediaDevices)(constraints).then(function (stream) {
              return resolve(enhance(stream));
            }).catch(reject);
          });
        };
      }

The enhance() function works on a mediaStream passed to it as parameter.

What I tried:

I did the monkeypatching code in the content script of the WebExtension, if that helps.

I tried monkeypatching like this, in a webpage with a video element to display the webcam. It reached the Video devices found!, but not any further.

change() will be my function to work on mediaStream(any helpful tips for that?),  and it doesn't do anything as of now.

const OGgum =  navigator.mediaDevices.getUserMedia;
    if(navigator.mediaDevices.getUserMedia){
        console.log('Video devices found!');
        navigator.mediaDevices.getUserMedia = (constraints) => {
            OGgum(constraints).then((stream)=> {
              console.log('gum Patched');
              video.srcObject = change(stream);
            })
            .catch((error)=>{
              console.log('This Went wrong: '+error);
            })
          }
    }
    const change = (st) => {
      return st;
    }

Now with the disappointment of that not working, I tried monkey patching console.log() in the content script of the webextension to add some text in front of every log, like this:

const OGlog = console.log;
console.log = (params) => {
  OGlog(' PATCHING: '+params);
}

console.log('Testing');

Outputs:

 PATCHING: Testing

which WORKED but ONLY for console.log() INSIDE the content script. How do I make it work for every page? Meaning, suppose I do a console.log(), I expect it to have  PATCHING in front.

I supposed if I manage to get console.log() to work, I can probably work on the getUserMedia() myself.

Relevant Reading

What am I missing here? Also if you have alternatives for this task, please share them. Thanks!

Body:
In Firefox you should use wrappedJSObject to access the page context and exportFunction to expose your code into the page context. More info on MDN: Sharing objects with page scripts.

const pWindow = window.wrappedJSObject;
const pMediaDevices = pWindow.navigator.mediaDevices;
const pGUM = pMediaDevices.getUserMedia;
const myGUM = (...args) =>
  pGUM.apply(pMediaDevices, args).then(stream => {
    // .........
    return stream;
  });
pMediaDevices.getUserMedia = exportFunction(myGUM, pWindow);

If you thought it's complicated, in Chrome/Chromium browsers it's even worse.