问:
How to implement a Lock with a timeout in Python 2.7
Is there a way to implement a lock in Python for multithreading purposes whose acquire method can have an arbitrary timeout? The only working solutions I found so far use polling, which

I find inelegant and inefficient

Doesn't preserve the bounded waiting / progress guarantee of the lock as a solution to the critical section problem

Is there a better way to implement this?

答:
Based on the already accepted answer and this idea for context hybrid manager/decorators I implemented a timeout lock (works in Python 2.7) that has both a context manager and a decorator interface. Additionally, when used as a context manager it supports named locks, so tasks can wait for a lock of a given name, rather than using a single global lock:</p>

```<code>import logging
import threading
import time
from functools import wraps
import sys

logger = logging.getLogger(__name__)
# use a global condition for safe manipulating of the LOCKS and
# LOCK_CONDITIONS dictionary in non-atomic operations
GLOBAL_COND = threading.Condition(threading.Lock())
LOCKS = {}
LOCK_CONDITIONS = {}

class ContextDecorator(object):
    def __enter__(self):
        return self

    def __exit__(self, typ, val, traceback):
        pass

    def __call__(self, f):
        @wraps(f)
        def wrapper(*args, **kw):
            with self as acquired:
                if acquired:
                    return f(*args, **kw)
        return wrapper

class TimeoutLock(ContextDecorator):
    def __init__(self, timeout, name=None):
        self.name = name
        self.timeout = timeout

    def __enter__(self):
        with GLOBAL_COND:
            self.cond = LOCK_CONDITIONS.get(self.name, None)
            if self.cond is None:
                self.cond = threading.Condition(threading.Lock())
                LOCK_CONDITIONS[self.name] = self.cond
                LOCKS[self.name] = threading.Lock()
            self.lock = LOCKS[self.name]

        self.cond.acquire()
        current_time = start_time = time.time()
        while current_time < start_time + self.timeout:
            if self.lock.acquire(False):
                self.cond.release()
                return True
            else:
                logger.debug('Waiting')
                self.cond.wait(
                    self.timeout - current_time + start_time)
                logger.debug('Woke up')
                current_time = time.time()
        logger.info('Timed out')
        self.cond.release()
        return False

    def __exit__(self, typ, val, traceback):
        if self.lock.locked():
            self.lock.release()
            with self.cond:
                self.cond.notify_all()

############################# DEMO ###############################
timeout = 4
sleep_interval = 1

handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter(
    fmt=('[%(asctime)s] %(name)s '
         '(%(threadName)s): %(message)s'),
    datefmt='%d/%b/%Y %H:%M:%S'))
logger.addHandler(handler)
logger.setLevel(logging.INFO)

def ascontext(i, name):
    with TimeoutLock(timeout, name=name) as acquired:
        if acquired:
            task()

# this will use a single lock, None
@TimeoutLock(timeout)
def asdecorator(i, name):
    task()

def task():
    logger.info('Acquired')
    time.sleep(sleep_interval)
    logger.info('Released')

def run(target):
    threads = []
    for i, name in enumerate(
            ['foo', 'bar', 'foo', 'baz', 'bar', 'foo']):
        thread = threading.Thread(
            target=target,
            name='{}.{}'.format(name, i),
            args=(i, name))
        threads.append(thread)
        thread.start()
    for i, t in enumerate(threads):
        t.join()

print('---- As context manager ----')
# foo, bar and baz can run concurrently
run(ascontext)
print('---- As decorator ----')
run(asdecorator)
</code>```

Body:
Based on the already accepted answer and this idea for context hybrid manager/decorators I implemented a timeout lock (works in Python 2.7) that has both a context manager and a decorator interface. Additionally, when used as a context manager it supports named locks, so tasks can wait for a lock of a given name, rather than using a single global lock:

import logging
import threading
import time
from functools import wraps
import sys

logger = logging.getLogger(__name__)
# use a global condition for safe manipulating of the LOCKS and
# LOCK_CONDITIONS dictionary in non-atomic operations
GLOBAL_COND = threading.Condition(threading.Lock())
LOCKS = {}
LOCK_CONDITIONS = {}

class ContextDecorator(object):
    def __enter__(self):
        return self

    def __exit__(self, typ, val, traceback):
        pass

    def __call__(self, f):
        @wraps(f)
        def wrapper(*args, **kw):
            with self as acquired:
                if acquired:
                    return f(*args, **kw)
        return wrapper

class TimeoutLock(ContextDecorator):
    def __init__(self, timeout, name=None):
        self.name = name
        self.timeout = timeout

    def __enter__(self):
        with GLOBAL_COND:
            self.cond = LOCK_CONDITIONS.get(self.name, None)
            if self.cond is None:
                self.cond = threading.Condition(threading.Lock())
                LOCK_CONDITIONS[self.name] = self.cond
                LOCKS[self.name] = threading.Lock()
            self.lock = LOCKS[self.name]

        self.cond.acquire()
        current_time = start_time = time.time()
        while current_time < start_time + self.timeout:
            if self.lock.acquire(False):
                self.cond.release()
                return True
            else:
                logger.debug('Waiting')
                self.cond.wait(
                    self.timeout - current_time + start_time)
                logger.debug('Woke up')
                current_time = time.time()
        logger.info('Timed out')
        self.cond.release()
        return False

    def __exit__(self, typ, val, traceback):
        if self.lock.locked():
            self.lock.release()
            with self.cond:
                self.cond.notify_all()

############################# DEMO ###############################
timeout = 4
sleep_interval = 1

handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter(
    fmt=('[%(asctime)s] %(name)s '
         '(%(threadName)s): %(message)s'),
    datefmt='%d/%b/%Y %H:%M:%S'))
logger.addHandler(handler)
logger.setLevel(logging.INFO)

def ascontext(i, name):
    with TimeoutLock(timeout, name=name) as acquired:
        if acquired:
            task()

# this will use a single lock, None
@TimeoutLock(timeout)
def asdecorator(i, name):
    task()

def task():
    logger.info('Acquired')
    time.sleep(sleep_interval)
    logger.info('Released')

def run(target):
    threads = []
    for i, name in enumerate(
            ['foo', 'bar', 'foo', 'baz', 'bar', 'foo']):
        thread = threading.Thread(
            target=target,
            name='{}.{}'.format(name, i),
            args=(i, name))
        threads.append(thread)
        thread.start()
    for i, t in enumerate(threads):
        t.join()

print('---- As context manager ----')
# foo, bar and baz can run concurrently
run(ascontext)
print('---- As decorator ----')
run(asdecorator)


来源: stackexchange

问:
Correct way to implement "yarn install" in shake-build?
My question might be a duplicate of Shake depending on on node_modules directory

I'm new to shake-build and got stumped with the very first thing that I wanted to do. Basically, I want to run yarn install whenever the yarn.lock OR package.json file changes.

I tried the following first, but it ended up running always:

want ["foo"]

phony "foo" $ do
  need ["yarn.lock", "package.json"]
  cmd_ ["yarn", "install"]
```

<p>Then I tried the following:</p>

<pre class="lang-hs prettyprint-override"><code>  want ["yarn.lock"]

  "yarn.lock" %> \out -> do
    need ["package.json"]
    cmd_ ["yarn", "install"]
</code>```

And it seems to work, but not quite. It re-runs only when yarn.lock or package.json changes, but fails to run after an rm -rf node_modules (sadly, a very common occurence, btw!)

Is Shake depending on on node_modules directory the correct way to set this up? Does one have to resort to these fake files for all such cases? Shouldn't this be automagically handled somehow by the shake database?

Edit: As an extension to this question, what's the right way to setup a common rule that can do a yarn install in any given directory?

答:
For the first snippet, a phony rule is always rerun, so there's no point doing a need within it (unless it needs those outputs to do its job) - which explains why it was always rerun.

For the second snippet, you have said to build yarn.lock depend on package.json. It has no idea that the contents of node_modules are the important ones. To capture that, and be tolerant to node_modules being deleted, the stamp file approach works well.

The reason stamp files are necessary is that directories aren't really a tracked concept in Shake - they don't have identity, a good modification time, they don't have contents, they come and go freely in the build system. Adding a dependency on a directory always goes wrong sooner or later (Shake actually used to allow it).

For a common reusable rule, one approach is to encode the directory name in the stamp file (which I've named .yarn_stamp). For example:

```<code>"*.yarn_stamp" *> \out -> do
    let name = dropDirectory out
    need ["package.lock", name </> "package.json"]
    cmd_ "yarn install" (Cwd name)
    writeFile' out ""
</code>```

As to whether this could be handled for you by Shake, very little goes deep into the Shake database - even the notion of files themselves are wrapped at a higher level. I looked at whether we could wrap the directory creation pattern, and it seems we're one simple function away from doing it - see https://github.com/ndmitchell/shake/issues/759 for that feature request (and please weigh in on the ticket if it seems useful for you).

ContentLicense: CC BY-SA 4.0

Body:
My question might be a duplicate of Shake depending on on node_modules directory

I'm new to shake-build and got stumped with the very first thing that I wanted to do. Basically, I want to run yarn install whenever the yarn.lock OR package.json file changes.

I tried the following first, but it ended up running always:

want ["foo"]

phony "foo" $ do
  need ["yarn.lock", "package.json"]
  cmd_ ["yarn", "install"]

Then I tried the following:

  want ["yarn.lock"]

  "yarn.lock" %> \out -> do
    need ["package.json"]
    cmd_ ["yarn", "install"]

And it seems to work, but not quite. It re-runs only when yarn.lock or package.json changes, but fails to run after an rm -rf node_modules (sadly, a very common occurence, btw!)

Is Shake depending on on node_modules directory the correct way to set this up? Does one have to resort to these fake files for all such cases? Shouldn't this be automagically handled somehow by the shake database?

Edit: As an extension to this question, what's the right way to setup a common rule that can do a yarn install in any given directory?

Body:
For the first snippet, a phony rule is always rerun, so there's no point doing a need within it (unless it needs those outputs to do its job) - which explains why it was always rerun.

For the second snippet, you have said to build yarn.lock depend on package.json. It has no idea that the contents of node_modules are the important ones. To capture that, and be tolerant to node_modules being deleted, the stamp file approach works well.

The reason stamp files are necessary is that directories aren't really a tracked concept in Shake - they don't have identity, a good modification time, they don't have contents, they come and go freely in the build system. Adding a dependency on a directory always goes wrong sooner or later (Shake actually used to allow it).

For a common reusable rule, one approach is to encode the directory name in the stamp file (which I've named .yarn_stamp). For example:

"*.yarn_stamp" *> \out -> do
    let name = dropDirectory out
    need ["package.lock", name </> "package.json"]
    cmd_ "yarn install" (Cwd name)
    writeFile' out ""

As to whether this could be handled for you by Shake, very little goes deep into the Shake database - even the notion of files themselves are wrapped at a higher level. I looked at whether we could wrap the directory creation pattern, and it seems we're one simple function away from doing it - see https://github.com/ndmitchell/shake/issues/759 for that feature request (and please weigh in on the ticket if it seems useful for you).


问:
Find the average of similar dataframe columns
I have a python dataframe and some columns refer to repeated samples as below:

In [3]: df = pd.DataFrame(
   ...:     [[89, 89, 12, 34, 32],
   ...:      [788, 25, 55, 65, 55],
   ...:      [588, 23, 58, 8, 55],
   ...:      [25, 14, 45, 123, 58]],
   ...:     columns = ['sample1','sample2.1','sample2.2','sample3','sample4'],
   ...: )
In [4]: df
   sample1  sample2.1  sample2.2  sample3  sample4
0       89         89         12       34       32
1      788         25         55       65       55
2      588         23         58        8       55
3       25         14         45      123       58
```

<p>for the repeated samples, <code>sample2.1</code> and <code>sample2.2</code>, I want to remain with an average of the two, i.e</p>

<pre class="lang-py prettyprint-override"><code>   sample1  sample2_averaged  sample3  sample4
0       89              50.5       34       32
1      788              40.0       65       55
2      588              40.5        8       55
3       25              29.5      123       58
</code>```

I am thinking of using regex but I have never used them on python dataframes

答:
You can group by columns if you provide axis=1, e.g.:

>>> df.groupby(df.columns.str.replace(r'\..+', ''), axis=1).mean()
    sample1 sample2 sample3 sample4
0   89.0    50.5    34.0    32.0
1   788.0   40.0    65.0    55.0
2   588.0   40.5    8.0 55.0
3   25.0    29.5    123.0   58.0
```

Pandas columns and indices can use the pandas.Series.str string accessor methods, including regex.

Body:
I have a python dataframe and some columns refer to repeated samples as below:

In [3]: df = pd.DataFrame(
   ...:     [[89, 89, 12, 34, 32],
   ...:      [788, 25, 55, 65, 55],
   ...:      [588, 23, 58, 8, 55],
   ...:      [25, 14, 45, 123, 58]],
   ...:     columns = ['sample1','sample2.1','sample2.2','sample3','sample4'],
   ...: )
In [4]: df
   sample1  sample2.1  sample2.2  sample3  sample4
0       89         89         12       34       32
1      788         25         55       65       55
2      588         23         58        8       55
3       25         14         45      123       58

for the repeated samples, sample2.1 and sample2.2, I want to remain with an average of the two, i.e

   sample1  sample2_averaged  sample3  sample4
0       89              50.5       34       32
1      788              40.0       65       55
2      588              40.5        8       55
3       25              29.5      123       58

I am thinking of using regex but I have never used them on python dataframes

Body:
You can group by columns if you provide axis=1, e.g.:

>>> df.groupby(df.columns.str.replace(r'\..+', ''), axis=1).mean()
    sample1 sample2 sample3 sample4
0   89.0    50.5    34.0    32.0
1   788.0   40.0    65.0    55.0
2   588.0   40.5    8.0 55.0
3   25.0    29.5    123.0   58.0

Pandas columns and indices can use the pandas.Series.str string accessor methods, including regex.


问:
Getting max value from rows and joining to another table
Sorry if this is being stupid, I am really a newbie trying to nail this.

```<code>Table A:
ID  Rank Name
1   100  Name1
1    45  Name2
2    60  Name3
2    42  Name4
2    88 Name5

Table B:
ID FileName
1  fn1
2  fn2
</code>```

What I want is

```<code>1 fn1 name1
2 fn2 name5
</code>```

This is what my query looks like, but it gives me multiple rows of results (instead of max) when i do the join

```<code>select B.Id B.FileName,A.Name
FRom B
JOIN (
select A.Id, MAX(A.Rank)as ExpertRank
from A
group by A.Id
) as NewA on A.Id = B.ID
join B on A.Rank = NewA.Rank
</code>```

Sub-query works fine, I get the problem on doing th join.

How do I fix this?

Thanks.

I have sql server 2008 R2

Last one is what I missed.

```<code>select B.Id B.FileName,A.Name
FRom B
JOIN (
select A.Id, MAX(A.Rank)as ExpertRank
from A
group by A.Id
) as NewA on A.Id = B.ID
join B on A.Rank = NewA.Rank
and A.Id = newA.Id
</code>```

答:
personally, i like the below.  just cleaner imo (though not sure about performace)</p>

```<code>select *
from a
inner join b on a.id=b.id and b.rank=(select max(rank) rnk from b where id=id)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Sorry if this is being stupid, I am really a newbie trying to nail this.

Table A:
ID  Rank Name
1   100  Name1
1    45  Name2
2    60  Name3
2    42  Name4
2    88 Name5

Table B:
ID FileName
1  fn1
2  fn2

What I want is

1 fn1 name1
2 fn2 name5

This is what my query looks like, but it gives me multiple rows of results (instead of max) when i do the join

select B.Id B.FileName,A.Name
FRom B
JOIN (
select A.Id, MAX(A.Rank)as ExpertRank
from A
group by A.Id
) as NewA on A.Id = B.ID
join B on A.Rank = NewA.Rank

Sub-query works fine, I get the problem on doing th join.

How do I fix this?

Thanks.

I have sql server 2008 R2

Last one is what I missed.

select B.Id B.FileName,A.Name
FRom B
JOIN (
select A.Id, MAX(A.Rank)as ExpertRank
from A
group by A.Id
) as NewA on A.Id = B.ID
join B on A.Rank = NewA.Rank
and A.Id = newA.Id

Body:
personally, i like the below.  just cleaner imo (though not sure about performace)

select *
from a
inner join b on a.id=b.id and b.rank=(select max(rank) rnk from b where id=id)


问:
atomic create file if not exists from bash script
In system call open(), if I open with O_CREAT | O_EXCL, the system call ensures that the file will only be created if it does not exist. The atomicity is guaranteed by the system call. Is there a similar way to create a file in an atomic fashion from a bash script?

UPDATE:
I found two different atomic ways

Use  set -o noclobber. Then you can use > operator atomically.

Just use mkdir. Mkdir is atomic

答:
Another way to do this is to use umask to try to create the file and open it for writing, without creating it with write permissions, like this:

```<code>LOCK_FILE=only_one_at_a_time_please
UMASK=$(umask)
umask 777
echo "$$" > "$LOCK_FILE"
umask "$UMASK"
trap "rm '$LOCK_FILE'" EXIT
</code>```

If the file is missing, the script will succeed at creating and opening it for writing, despite the file being created without writing permissions. If it already exists, the script won't be able to open the file for writing. It would be possible to use exec to open the file and keep the file descriptor around.

rm requires you to have write permissions to the directory itself, without regards to file permissions.

Body:
Another way to do this is to use umask to try to create the file and open it for writing, without creating it with write permissions, like this:

LOCK_FILE=only_one_at_a_time_please
UMASK=$(umask)
umask 777
echo "$$" > "$LOCK_FILE"
umask "$UMASK"
trap "rm '$LOCK_FILE'" EXIT

If the file is missing, the script will succeed at creating and opening it for writing, despite the file being created without writing permissions. If it already exists, the script won't be able to open the file for writing. It would be possible to use exec to open the file and keep the file descriptor around.

rm requires you to have write permissions to the directory itself, without regards to file permissions.


问:
SQL injection login bypass
I am preparing SQL injection vulnerable page to test skills, here is my code:

```<code><?php
    echo "<center><h1>Login Bypass</h1></center>";
    include 'config.php';
    mysql_connect($host, $user, $password) or die(mysql_error());
    mysql_select_db($database) or die(mysql_error());

    $name = $_REQUEST['name'];
    $passwd = $_REQUEST['passwd'];
    $query_string = "SELECT * FROM users WHERE username = '$name' AND password = '$passwd'";
    echo "<center>".$query_string."</center><br/>";
    $query = mysql_query($query_string) or die(mysql_error());
    $row = mysql_fetch_array($query);
    if(mysql_num_rows($query)>0)
        echo "<center>SUCCESS</center><br/>";
    else echo "<center>ACCESS DENIED</center><br/>";
    echo "<center>".$row['email']."</center><br/>";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
    <title>Login Bypass</title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <meta name="generator" content="Geany 0.19.1" />
</head>

<body>
    <center>
    <form action="login_bypass.php" method="get">
        Login: <input name="name">
        Password: <input name="passwd" >
        <input type="submit" value="CHECK">
    </form>
    </center>
</body>

</html>
</code>```

I have also table users where I have username='agajan' and password='12345' email='torayeff@gmail.com'.
I know that this query is vulnerable:

```<code>$query_string = "SELECT * FROM users WHERE username = '$name' AND password = '$passwd'";
</code>```

But when I insert instead of username the following "agajan' /*" and leave password field empty I  get:

```<code>SELECT * FROM users WHERE username = 'agajan' /* ' AND password = ' '
</code>```

...but It gives me mysql error.  Can anyone explain me why I can not inject sql?

答:
This is not a valid comment because you use the inline comment which requires a closing */ as well..

Use -- or # comments instead, so you need to pass agajan' -- or agajan' #.

MySql comment syntax : http://dev.mysql.com/doc/refman/5.1/en/comments.html

Title: SQL injection login bypass

Body:
I am preparing SQL injection vulnerable page to test skills, here is my code:

<?php
    echo "
Login Bypass
";
    include 'config.php';
    mysql_connect($host, $user, $password) or die(mysql_error());
    mysql_select_db($database) or die(mysql_error());

    $name = $_REQUEST['name'];
    $passwd = $_REQUEST['passwd'];
    $query_string = "SELECT * FROM users WHERE username = '$name' AND password = '$passwd'";
    echo "".$query_string."
";
    $query = mysql_query($query_string) or die(mysql_error());
    $row = mysql_fetch_array($query);
    if(mysql_num_rows($query)>0)
        echo "SUCCESS
";
    else echo "ACCESS DENIED
";
    echo "".$row['email']."
";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title>Login Bypass</title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <meta name="generator" content="Geany 0.19.1" />

    <form action="login_bypass.php" method="get">
        Login: <input name="name">
        Password: <input name="passwd" >
        <input type="submit" value="CHECK">
    </form>

I have also table users where I have username='agajan' and password='12345' email='torayeff@gmail.com'.
I know that this query is vulnerable:

$query_string = "SELECT * FROM users WHERE username = '$name' AND password = '$passwd'";

But when I insert instead of username the following "agajan' /*" and leave password field empty I  get:

SELECT * FROM users WHERE username = 'agajan' /* ' AND password = ' '

...but It gives me mysql error.  Can anyone explain me why I can not inject sql?


问:
Is there a way to control dry/wet balance of AKOperationEffect?
In an attempt to smooth out crackling/zippering when changing parameters on an AKDelay, I switched to using AKOperationEffect. However, unlike AKDelay, AKOperationEffect has no dry/wet mix parameter. How do I change it?</p>

答:
I wound up composing a wrapper class with an optional AKDryWetMixer node that I just use for cases where the effect needs an additional dry/wet mixer (as is the case with AKOperationEffect). Seems fine.

Obviously, if there's a "proper" solution, or something obvious I'm missing, I'd appreciate a heads-up.


问:
How to concatenate BLOB fields (Oracle)?
IS it possible to concatenate A1 and A2 from the particular table (for example):

```<code>CREATE TABLE MY_SCHEME.CONC_BLOB
(
  A1       BLOB,
  A1_SORT  NUMBER(20),
  T_TYPE   VARCHAR2(9 BYTE),
  A2       BLOB,
  A2_SORT  NUMBER(20),
  A3       VARCHAR2(32 BYTE),
  A4       BLOB,
  A5       VARCHAR2(8 BYTE)
)
</code>```

?
How?

答:
Here is my solution for joining any number of BLOBs into single BLOB using helper table type and stored function:

```<code>create or replace type blobs as table of blob;

create or replace function concat_blobs(parts in blobs) return blob
is
    temp blob;
begin
    if parts is null or parts.count = 0 then
       return null;
    end if;
    dbms_lob.createtemporary(temp, false, dbms_lob.CALL);
    for i in parts.first .. parts.last
    loop
        dbms_lob.append(temp, parts(i));
    end loop;
    return temp;
end;

-- usage example:
select concat_blobs(blobs(to_blob(hextoraw('CAFE')), to_blob(hextoraw('BABE')))) from dual;

-- bonus
create or replace type raws as table of raw(2000);

create or replace function raws_to_blobs(arg in raws) return blobs
is
    res blobs;
begin
    select to_blob(column_value) bulk collect into res from table(arg);
    return res;
end;

-- usage example:
select concat_blobs(raws_to_blobs(raws(hextoraw('CAFE'), hextoraw('BABE'))) from dual;
</code>```

See also multiple RAWs concatenation in  Oracle 10: Using HEXTORAW to fill in blob data.

Body:
IS it possible to concatenate A1 and A2 from the particular table (for example):

CREATE TABLE MY_SCHEME.CONC_BLOB
(
  A1       BLOB,
  A1_SORT  NUMBER(20),
  T_TYPE   VARCHAR2(9 BYTE),
  A2       BLOB,
  A2_SORT  NUMBER(20),
  A3       VARCHAR2(32 BYTE),
  A4       BLOB,
  A5       VARCHAR2(8 BYTE)
)

?
How?

Body:
Here is my solution for joining any number of BLOBs into single BLOB using helper table type and stored function:

create or replace type blobs as table of blob;

create or replace function concat_blobs(parts in blobs) return blob
is
    temp blob;
begin
    if parts is null or parts.count = 0 then
       return null;
    end if;
    dbms_lob.createtemporary(temp, false, dbms_lob.CALL);
    for i in parts.first .. parts.last
    loop
        dbms_lob.append(temp, parts(i));
    end loop;
    return temp;
end;

-- usage example:
select concat_blobs(blobs(to_blob(hextoraw('CAFE')), to_blob(hextoraw('BABE')))) from dual;

-- bonus
create or replace type raws as table of raw(2000);

create or replace function raws_to_blobs(arg in raws) return blobs
is
    res blobs;
begin
    select to_blob(column_value) bulk collect into res from table(arg);
    return res;
end;

-- usage example:
select concat_blobs(raws_to_blobs(raws(hextoraw('CAFE'), hextoraw('BABE'))) from dual;

See also multiple RAWs concatenation in  Oracle 10: Using HEXTORAW to fill in blob data.


问:
regex for matching programming language like block
I'm trying to make a small scripting language using c#
currently doing a block parser
im stuck at making regex for block.
Blocks can have ∞ times of sub blocks

This is what i need to catch

```<code>{
    naber();
}
{
    int x = 5;
    x = 2;
    if (x == 5) {
        x = 5;
    }
}

</code>```

I tried this but not working

```<code>\{[^{}]*|(\{[^\{\}]\})*\}
</code>```

This is my first post please have mercy on me

答:
Regex will not help you for this. If you are designing a scripting language, possibly to be executed, that has blocks and sub-blocks, you need context-free grammar as opposed to regular grammar which can be expressed through regular expressions.

To interpret a context-free language you need the following steps (simplified):

Convert the code string to a list of tokens/symbols. This process is done by a component usually called Lexer.

Convert the tokens into a structured tree (AST - Abstract Syntax Tree) based on grammar rules (things like operator precedence, nested code blocks, etc). This is done by a component usually called Parser.

From here several options arise, either you translate the AST into native code, or intermediate code (like bytecode) or transpile it into another language; Or you can run it directly in memory, the most simple approach and probably what you want/need.

These should already be plenty of concepts to search for, but all of this can be achieved easily with tools like ANTLR. There might be alternatives to ANTLR obviously, I just don’t recall any just now.

Body:
I'm trying to make a small scripting language using c#
currently doing a block parser
im stuck at making regex for block.
Blocks can have ∞ times of sub blocks

This is what i need to catch

{
    naber();
}
{
    int x = 5;
    x = 2;
    if (x == 5) {
        x = 5;
    }
}

I tried this but not working

\{[^{}]*|(\{[^\{\}]\})*\}

This is my first post please have mercy on me


问:
Why second channel not receiving data from previous channel
I'm doing my first steps with go channels, and tried to write the below code, where I want to do the following with goroutine that is reading from a given csv file, emit the read record to another channel which is adding the same record to another csv file:

package main

import (
    "encoding/csv"
    "encoding/json"
    "fmt"
    "log"
    "os"
)

func failOnError(err error) {
    if err != nil {
        log.Fatal("Error:", err)
        panic(err)
    }
}
func main() {
    read := make(chan Data)
    go func(input_file string) {
        var data Data

        fr, err := os.Open(input_file)
        failOnError(err)
        defer fr.Close()
        r := csv.NewReader(fr)
        rows, err := r.ReadAll()
        failOnError(err)
        data.header = rows[0]
        for _, row := range rows[1:] {
            data.lines = append(data.lines, Person{
                Firstname: row[0],
                Lastname:  row[1],
                Address: &Address{
                    City:  row[2],
                    State: row[3],
                },
            })
        }

        peopleJson, _ := json.Marshal(data.lines)
        fmt.Println(string(peopleJson))   // This is working smoothly

        read <- data
    }("people.csv")

    csvOut, err := os.Create("resultsfile.csv")
    if err != nil {
        log.Fatal("Unable to open output")
    }

    out := make(chan int)
    select {
    case data := <-read:
        go func(data Data) {
            println("data received")     // <-- Not show up
            w := csv.NewWriter(csvOut)
            defer csvOut.Close()
            // handle header
            data.header = append(data.header, "score")
            if err = w.Write(data.header); err != nil {
                log.Fatal(err)
            }
            /*
                hanlde data
            */
            w.Flush()
            out <- 0
        }(data)
    case _ = <-out:
        println("done")
    }

}

type Person struct {
    Firstname string   `json:"firstname"` // JSON annotation will allow for easy printing to JSON after it had been loaded
    Lastname  string   `json:"lastname"`
    Address   *Address `json:"address,omitempty"`
}

type Address struct {
    City  string `json:"city"`
    State string `json:"state"`
}

type Data struct {
    header []string
    lines  []Person
}
```

<p>my code failed, with no error and did not show the <code>data received</code>  note</p>

<p><code>people.csv</code> file is:</p>

```First,Last,City,State
Nic,Raboy,San Francisco,CA
Maria,Raboy,Dublin,CA
Hasan,yousef, Jordan, ZA
```

<p>And the output i got is:</p>

<pre class="lang-sh prettyprint-override"><code>[Running] go run "d:\goplay\csv.go"
[{"firstname":"Nic","lastname":"Raboy","address":{"city":"San Francisco","state":"CA"}},{"firstname":"Maria","lastname":"Raboy","address":{"city":"Dublin","state":"CA"}},{"firstname":"Hasan","lastname":"yousef","address":{"city":" Jordan","state":" ZA"}}]

[Done] exited with code=0 in 1.233 seconds
</code>```

答:
Tthe problem is this:

```<code>    select {
    case data := <-read:
        go func(data Data) {
</code>```

The select is the last thing in the main function.   When it reads data from read, it starts a goroutine in the background to process it.  The main function then ends and, thus, the program exits.

Go does not automatically wait for goroutines.  It's up to you to use "done" channels or whatever to synchronize between them.

You essentially have a pipeline that conceptually looks something like this:

```<code>                                         ----> process -> write to `out`
                                        /
start --> main file waits  data on `read` *or* wait for `out` -> done
       \
        ---> CSV reads all lines and outputs data to `read`
</code>```

Because you actually only send one message over the channel, you don't really need a select, or a loop.  You just neeed to wait for the data, process it , and have main wait for the completion:

package main

import (
    "encoding/csv"
    "encoding/json"
    "fmt"
    "log"
    "os"
)

func failOnError(err error) {
    if err != nil {
        log.Fatal("Error:", err)
        panic(err)
    }
}
func main() {
    read := make(chan Data)
    go func(input_file string) {
        var data Data

        fr, err := os.Open(input_file)
        failOnError(err)
        defer fr.Close()
        r := csv.NewReader(fr)
        rows, err := r.ReadAll()
        failOnError(err)
        data.header = rows[0]
        for _, row := range rows[1:] {
            data.lines = append(data.lines, Person{
                Firstname: row[0],
                Lastname:  row[1],
                Address: &Address{
                    City:  row[2],
                    State: row[3],
                },
            })
        }

        peopleJson, _ := json.Marshal(data.lines)
        fmt.Println(string(peopleJson)) // This is working smoothly

        read <- data
    }("people.csv")

    csvOut, err := os.Create("resultsfile.csv")
    if err != nil {
        log.Fatal("Unable to open output")
    }

    out := make(chan int)
    go func() {
        data := <-read
        println("data received") // <-- Not show up
        w := csv.NewWriter(csvOut)
        defer csvOut.Close()
        // handle header
        data.header = append(data.header, "score")
        if err = w.Write(data.header); err != nil {
            log.Fatal(err)
        }
        /*
           hanlde data
        */
        w.Flush()
        out <- 0
    }()

    <-out
    println("done")
}

type Person struct {
    Firstname string   `json:"firstname"` // JSON annotation will allow for easy printing to JSON after it had been loaded
    Lastname  string   `json:"lastname"`
    Address   *Address `json:"address,omitempty"`
}

type Address struct {
    City  string `json:"city"`
    State string `json:"state"`
}

type Data struct {
    header []string
    lines  []Person
}
```

<p>The OP asks, </p>

<blockquote>
  <p>Is there a way to receive input from previous channels without select and at same time ensure the program is not exit before finishing what is required? – Hasan A Yousef 1 min ago</p>
</blockquote>

<p>All of your channels as written pass exactly one message, which means that once you read the channel <em>once</em>, you can assume the writer is complete.  So with your use of the <code>out</code> channel, you already achieve this.  </p>

<p>If you had an <em>unknown</em> number of sends to the channel, you could use the builtin <code>close</code> functionality to achieve this:</p>

<pre class="lang-golang prettyprint-override"><code>package main

import (
  "fmt"
)

func main() {
  send := make(chan int)
  result := make(chan int)
  go func() {
    sum := 0
    for i := range send {
      sum += i
    }
    result <- sum
  }()
  for _, x := range []int{1,2,3}  {
    send <- x
  }
  close(send)
  fmt.Println("Sum is: ", <-result)
}
</code>```

Body:
I'm doing my first steps with go channels, and tried to write the below code, where I want to do the following with goroutine that is reading from a given csv file, emit the read record to another channel which is adding the same record to another csv file:

package main

import (
    "encoding/csv"
    "encoding/json"
    "fmt"
    "log"
    "os"
)

func failOnError(err error) {
    if err != nil {
        log.Fatal("Error:", err)
        panic(err)
    }
}
func main() {
    read := make(chan Data)
    go func(input_file string) {
        var data Data

        fr, err := os.Open(input_file)
        failOnError(err)
        defer fr.Close()
        r := csv.NewReader(fr)
        rows, err := r.ReadAll()
        failOnError(err)
        data.header = rows[0]
        for _, row := range rows[1:] {
            data.lines = append(data.lines, Person{
                Firstname: row[0],
                Lastname:  row[1],
                Address: &Address{
                    City:  row[2],
                    State: row[3],
                },
            })
        }

        peopleJson, _ := json.Marshal(data.lines)
        fmt.Println(string(peopleJson))   // This is working smoothly

        read <- data
    }("people.csv")

    csvOut, err := os.Create("resultsfile.csv")
    if err != nil {
        log.Fatal("Unable to open output")
    }

    out := make(chan int)
    select {
    case data := <-read:
        go func(data Data) {
            println("data received")     // <-- Not show up
            w := csv.NewWriter(csvOut)
            defer csvOut.Close()
            // handle header
            data.header = append(data.header, "score")
            if err = w.Write(data.header); err != nil {
                log.Fatal(err)
            }
            /*
                hanlde data
            */
            w.Flush()
            out <- 0
        }(data)
    case _ = <-out:
        println("done")
    }

}

type Person struct {
    Firstname string   `json:"firstname"` // JSON annotation will allow for easy printing to JSON after it had been loaded
    Lastname  string   `json:"lastname"`
    Address   *Address `json:"address,omitempty"`
}

type Address struct {
    City  string `json:"city"`
    State string `json:"state"`
}

type Data struct {
    header []string
    lines  []Person
}

my code failed, with no error and did not show the data received  note

people.csv file is:

First,Last,City,State
Nic,Raboy,San Francisco,CA
Maria,Raboy,Dublin,CA
Hasan,yousef, Jordan, ZA

And the output i got is:

[Running] go run "d:\goplay\csv.go"
[{"firstname":"Nic","lastname":"Raboy","address":{"city":"San Francisco","state":"CA"}},{"firstname":"Maria","lastname":"Raboy","address":{"city":"Dublin","state":"CA"}},{"firstname":"Hasan","lastname":"yousef","address":{"city":" Jordan","state":" ZA"}}]

[Done] exited with code=0 in 1.233 seconds

Body:
Tthe problem is this:

    select {
    case data := <-read:
        go func(data Data) {

The select is the last thing in the main function.   When it reads data from read, it starts a goroutine in the background to process it.  The main function then ends and, thus, the program exits.

Go does not automatically wait for goroutines.  It's up to you to use "done" channels or whatever to synchronize between them.

You essentially have a pipeline that conceptually looks something like this:

                                         ----> process -> write to `out`
                                        /
start --> main file waits  data on `read` *or* wait for `out` -> done
       \
        ---> CSV reads all lines and outputs data to `read`

Because you actually only send one message over the channel, you don't really need a select, or a loop.  You just neeed to wait for the data, process it , and have main wait for the completion:

package main

import (
    "encoding/csv"
    "encoding/json"
    "fmt"
    "log"
    "os"
)

func failOnError(err error) {
    if err != nil {
        log.Fatal("Error:", err)
        panic(err)
    }
}
func main() {
    read := make(chan Data)
    go func(input_file string) {
        var data Data

        fr, err := os.Open(input_file)
        failOnError(err)
        defer fr.Close()
        r := csv.NewReader(fr)
        rows, err := r.ReadAll()
        failOnError(err)
        data.header = rows[0]
        for _, row := range rows[1:] {
            data.lines = append(data.lines, Person{
                Firstname: row[0],
                Lastname:  row[1],
                Address: &Address{
                    City:  row[2],
                    State: row[3],
                },
            })
        }

        peopleJson, _ := json.Marshal(data.lines)
        fmt.Println(string(peopleJson)) // This is working smoothly

        read <- data
    }("people.csv")

    csvOut, err := os.Create("resultsfile.csv")
    if err != nil {
        log.Fatal("Unable to open output")
    }

    out := make(chan int)
    go func() {
        data := <-read
        println("data received") // <-- Not show up
        w := csv.NewWriter(csvOut)
        defer csvOut.Close()
        // handle header
        data.header = append(data.header, "score")
        if err = w.Write(data.header); err != nil {
            log.Fatal(err)
        }
        /*
           hanlde data
        */
        w.Flush()
        out <- 0
    }()

    <-out
    println("done")
}

type Person struct {
    Firstname string   `json:"firstname"` // JSON annotation will allow for easy printing to JSON after it had been loaded
    Lastname  string   `json:"lastname"`
    Address   *Address `json:"address,omitempty"`
}

type Address struct {
    City  string `json:"city"`
    State string `json:"state"`
}

type Data struct {
    header []string
    lines  []Person
}

The OP asks,

Is there a way to receive input from previous channels without select and at same time ensure the program is not exit before finishing what is required? – Hasan A Yousef 1 min ago

All of your channels as written pass exactly one message, which means that once you read the channel once, you can assume the writer is complete.  So with your use of the out channel, you already achieve this.

If you had an unknown number of sends to the channel, you could use the builtin close functionality to achieve this:

package main

import (
  "fmt"
)

func main() {
  send := make(chan int)
  result := make(chan int)
  go func() {
    sum := 0
    for i := range send {
      sum += i
    }
    result <- sum
  }()
  for _, x := range []int{1,2,3}  {
    send <- x
  }
  close(send)
  fmt.Println("Sum is: ", <-result)
}


问:
Android and FireTv UI customization using RowsSupportFragment
I am new to Android TV development and would like to know a few things. I saw that using Leanback we can achieve this. The key components being BrowseSupportFragment, RowsSupportFragment etc.

What I want is.
Currently, in BrowseSupportFragment I am using PageRow such that I can have a custom fragment (extending RowsSupportFragment) for each row. What I want is this, the custom Fragment to be a regular Fragment (extending Fragment) and have some FrameLayouts in that and for that FrameLayouts I can call different Fragments (RowsSupportFragment). So just to summarize I want something like BrowseSupportFragment --> Fragment --> RowsSupportFragment for each frameLayout in this way I can customize the UI as I want.

Can someone help me with this?

答:
I couldn't get around this situation. So I ended up having normal fragments and some key important points in case any one else needs the same.

android:background="?android:attr/selectableItemBackground" this to the parent layout to get the current view selected effect.

Direction should be handled by onKeyListener with these events.

a. keyCode == KeyEvent.KEYCODE_DPAD_UP

b. keyCode == KeyEvent.KEYCODE_DPAD_DOWN

c. keyCode == KeyEvent.KEYCODE_DPAD_LEFT

d. keyCode == KeyEvent.KEYCODE_DPAD_RIGHT

e. keyCode == KeyEvent.KEYCODE_DPAD_ENTER

( when you press enter key on the keyboard)
Make sure to check event.getAction() == KeyEvent.ACTION_DOWN otherwise you will run into the problem of skipping the views in between.

If anyone gets the correct implementation of the about question please update till then this is my solution.


问:
pandas read_csv function reading values as NaN even though there are values in cells
I have a file that I am trying to read in a pandas dataframe. However, some of the cells, are coming up as NaN even though there are values in there. The cells that are showing up as float value. The cells that are not showing up were copied pasted in the cells. Not sure why that would make a difference. Can anyone help? I have included the file as a link at this location: https://www.dropbox.com/s/30rxw07eaza29df/manhattan_hs_gps.csv?dl=0

答:
Tried this and it worked fine, both encoding='unicode-escape' and encoding='latin-1' work:

```<code>df = pd.read_csv('manhattan_hs_gps.csv', encoding='unicode-escape', header=None)
print(df)

       0                                                  1          2          3
0      0              A. Philip Randolph Campus High School  40.818500 -73.950000
1      1                                       Aaron School  40.744800 -73.983700
2      2                      Abraham Joshua Heschel School  40.772300 -73.989700
3      3  Academy of Environmental Science Secondary Hig...  40.785200 -73.942200
4      4  Academy for Social Action: A College Board School  40.815400 -73.955300
..   ...                                                ...        ...        ...
162  164                                 Xavier High School  40.737900 -73.994600
163  165            Yeshiva University High School for Boys  40.851749 -73.928695
164  166                            York Preparatory School  40.774100 -73.979400
165  167                    Young Women's Leadership School  40.792900 -73.947200
166  168   Washington Heights Expeditionary Learning School  40.774100 -73.979400
</code>```

Body:
Tried this and it worked fine, both encoding='unicode-escape' and encoding='latin-1' work:

df = pd.read_csv('manhattan_hs_gps.csv', encoding='unicode-escape', header=None)
print(df)

       0                                                  1          2          3
0      0              A. Philip Randolph Campus High School  40.818500 -73.950000
1      1                                       Aaron School  40.744800 -73.983700
2      2                      Abraham Joshua Heschel School  40.772300 -73.989700
3      3  Academy of Environmental Science Secondary Hig...  40.785200 -73.942200
4      4  Academy for Social Action: A College Board School  40.815400 -73.955300
..   ...                                                ...        ...        ...
162  164                                 Xavier High School  40.737900 -73.994600
163  165            Yeshiva University High School for Boys  40.851749 -73.928695
164  166                            York Preparatory School  40.774100 -73.979400
165  167                    Young Women's Leadership School  40.792900 -73.947200
166  168   Washington Heights Expeditionary Learning School  40.774100 -73.979400


问:
Namespaces in C
Is there a way to (ab)use the C preprocessor to emulate namespaces in C?

I'm thinking something along these lines:

```<code>#define NAMESPACE name_of_ns
some_function() {
    some_other_function();
}
</code>```

This would get translated to:

```<code>name_of_ns_some_function() {
    name_of_ns_some_other_function();
}
</code>```

答:
You can use a helper #define macro:

```<code>#include <stdio.h>

#define ns(x) gargantua_ ## x

struct ns(stats) {
    int size;
};

int ns(get_size)(struct ns(stats) *st) {
    return st->size;
}

void ns(set_size)(struct ns(stats) *st, int sz) {
    st->size = sz;
}

int main(void) {
    struct ns(stats) stats = {0};

    ns(set_size)(&stats, 3);
    printf("size=%d\n", ns(get_size)(&stats));
    return 0;
}
</code>```

Running it through the preprocessor gives you:

```<code>struct gargantua_stats {
    int size;
};

int gargantua_get_size(struct gargantua_stats *st) {
    return st->size;
}

void gargantua_set_size(struct gargantua_stats *st, int sz) {
    st->size = sz;
}

int main(void) {
    struct gargantua_stats stats = {0};

    gargantua_set_size(&stats, 3);
    printf("size=%d\n", gargantua_get_size(&stats));
    return 0;
}
</code>```

OwnerDisplayName: Kim

Title: Namespaces in C

Body:
Is there a way to (ab)use the C preprocessor to emulate namespaces in C?

I'm thinking something along these lines:

#define NAMESPACE name_of_ns
some_function() {
    some_other_function();
}

This would get translated to:

name_of_ns_some_function() {
    name_of_ns_some_other_function();
}

Body:
You can use a helper #define macro:

#include <stdio.h>

#define ns(x) gargantua_ ## x

struct ns(stats) {
    int size;
};

int ns(get_size)(struct ns(stats) *st) {
    return st->size;
}

void ns(set_size)(struct ns(stats) *st, int sz) {
    st->size = sz;
}

int main(void) {
    struct ns(stats) stats = {0};

    ns(set_size)(&stats, 3);
    printf("size=%d\n", ns(get_size)(&stats));
    return 0;
}

Running it through the preprocessor gives you:

struct gargantua_stats {
    int size;
};

int gargantua_get_size(struct gargantua_stats *st) {
    return st->size;
}

void gargantua_set_size(struct gargantua_stats *st, int sz) {
    st->size = sz;
}

int main(void) {
    struct gargantua_stats stats = {0};

    gargantua_set_size(&stats, 3);
    printf("size=%d\n", gargantua_get_size(&stats));
    return 0;
}


问:
Web App on Azure loaded slow after applying custom domain
I just started hosting my website on Azure. Initially when uploading and hosting the website on xxxx.azurewebsites.net, the performance and response was great. After adding a custom domain (Bought from Godaddy), the performance became worst and it would take 1 min for a page to load.

xxxx.azurewebsites.net -> loaded in few seconds

xxxx.com -> loaded in almost a minute

Is there anything im missing here? In General Configuration, I have enabled Always On but the performance is still the same for custom domains.

Custom Domains set up :

In Chrome Network tools, I can see that the connection is stalled for at least 1 minutes. Not sure what causing this.

答:
If the performance is (very) bad only with the custom domain, chances are DNS is either not setup correctly, or hosted on a (very) slow DNS host. Of course, it might be something else altogether.

Here's a few things that can help you determine the issue:

Check if there's any logic in your web app that might be retried or waiting for a response it is not getting when you're connecting to it through the domain name.

Check the speed of your DNS, for instance by using Ultratools' DNS Speed Test.

The DNS hosting speed tool will give you valuable DNS performance information for each level in the DNS tree to assist with performance evaluations and performance troubleshooting.

Run this from a command line and see information about how to get to your domain:

```<code>nslookup
> set debug
<your-domain-name>
</code>```

Consider adding a service like Cloudflare to your website.

Protect and accelerate your websites, apps, and teams.

Run webhint (or any other tool that gives you insight) on your custom domain.

It does more than just performance:

webhint is a customizable linting tool that helps you improve your site's accessibility, speed, cross-browser compatibility, and more by checking your code for best practices and common errors.

Body:
If the performance is (very) bad only with the custom domain, chances are DNS is either not setup correctly, or hosted on a (very) slow DNS host. Of course, it might be something else altogether.

Here's a few things that can help you determine the issue:

Check if there's any logic in your web app that might be retried or waiting for a response it is not getting when you're connecting to it through the domain name.

Check the speed of your DNS, for instance by using Ultratools' DNS Speed Test.

The DNS hosting speed tool will give you valuable DNS performance information for each level in the DNS tree to assist with performance evaluations and performance troubleshooting.

Run this from a command line and see information about how to get to your domain:

nslookup
> set debug
<your-domain-name>

Consider adding a service like Cloudflare to your website.

Protect and accelerate your websites, apps, and teams.

Run webhint (or any other tool that gives you insight) on your custom domain.

It does more than just performance:

webhint is a customizable linting tool that helps you improve your site's accessibility, speed, cross-browser compatibility, and more by checking your code for best practices and common errors.


问:
Chainlink job not returning value
I have an oracle and JobID I’d like to submit to an oracle to get ETH price data. I have funded the node, and am following the documentation. However, every time I request the price, my BTC value will not update. The contract seems to be funded with LINK and I’m not getting gas errors, but for some reason the number will not change. What is going on?</p>

```<code>solidity
pragma solidity ^0.6.0;
import "github.com/smartcontractkit/chainlink/evm-contracts/src/v0.6/ChainlinkClient.sol";
contract testingData is ChainlinkClient {
  address public owner;
  uint256 public btc;
  address ORACLE =  0xB36d3709e22F7c708348E225b20b13eA546E6D9c;
  bytes32 constant JOB = "f9528decb5c64044b6b4de54ca7ea63e";
  uint256 constant private ORACLE_PAYMENT = 1 * LINK;
  constructor() public {
    setPublicChainlinkToken();
    owner = msg.sender;
  }
  function getBTCPrice()
    public
    onlyOwner
  {
    Chainlink.Request memory req = buildChainlinkRequest(JOB, address(this), this.fulfill.selector);
    req.add("get", "https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=BTC&to_currency=USD&apikey=xxxx");
    string[] memory copyPath = new string[](2);
    copyPath[0] = "Realtime Currency Exchange Rate";
    copyPath[1] = "5. Exchange Rate";
    sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);
  }
  function fulfill(bytes32 _requestId, uint256 _price)
    public
    recordChainlinkFulfillment(_requestId)
  {
    btc = _price;
  }
  modifier onlyOwner() {
    require(msg.sender == owner);
    _;
  }
}
</code>```

答:
For this particular issue, do:

You need to add a multiply adapter to your job. In your getBTCPrice(), add a line:

```<code>run.addInt("times", 100000000);
</code>```

There is a full example code below, however here are some tips on what might be going on.

The node address isn't funded with ETH - you'd have to contact the node operator.

Fund the Ethereum address that your Chainlink node uses. You can find the address in the node Operator GUI under the Keys tab. The address of the node is the Regular type. You can obtain test ETH from several faucets.

The jobid or oracle address is wrong - double check.

The node is currently down - ask the node operator.

You are blacklisted, or not whitelisted. Contact the node operator.

In solidity, decimals don't work, so whenever you're getting a number with decimals from an oracle, you need to add a multiply adapter so that it can understand.

Whole code below:

```<code>solidity
pragma solidity ^0.6.0;
import "github.com/smartcontractkit/chainlink/evm-contracts/src/v0.6/ChainlinkClient.sol";
contract testingData is ChainlinkClient {
  address public owner;
  uint256 public btc;
  address ORACLE =  0xB36d3709e22F7c708348E225b20b13eA546E6D9c;
  bytes32 constant JOB = "f9528decb5c64044b6b4de54ca7ea63e";
  uint256 constant private ORACLE_PAYMENT = 1 * LINK;
  constructor() public {
    setPublicChainlinkToken();
    owner = msg.sender;
  }
  function getBTCPrice()
    public
    onlyOwner
  {
    Chainlink.Request memory req = buildChainlinkRequest(JOB, address(this), this.fulfill.selector);
    req.add("get", "https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=BTC&to_currency=USD&apikey=xxxx");
    string[] memory copyPath = new string[](2);
    copyPath[0] = "Realtime Currency Exchange Rate";
    copyPath[1] = "5. Exchange Rate";
    sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);
  }
  function fulfill(bytes32 _requestId, uint256 _price)
    public
    recordChainlinkFulfillment(_requestId)
  {
    btc = _price;
  }
  modifier onlyOwner() {
    require(msg.sender == owner);
    _;
  }
}
</code>```

Title: Chainlink job not returning value

Body:
I have an oracle and JobID I’d like to submit to an oracle to get ETH price data. I have funded the node, and am following the documentation. However, every time I request the price, my BTC value will not update. The contract seems to be funded with LINK and I’m not getting gas errors, but for some reason the number will not change. What is going on?

solidity
pragma solidity ^0.6.0;
import "github.com/smartcontractkit/chainlink/evm-contracts/src/v0.6/ChainlinkClient.sol";
contract testingData is ChainlinkClient {
  address public owner;
  uint256 public btc;
  address ORACLE =  0xB36d3709e22F7c708348E225b20b13eA546E6D9c;
  bytes32 constant JOB = "f9528decb5c64044b6b4de54ca7ea63e";
  uint256 constant private ORACLE_PAYMENT = 1 * LINK;
  constructor() public {
    setPublicChainlinkToken();
    owner = msg.sender;
  }
  function getBTCPrice()
    public
    onlyOwner
  {
    Chainlink.Request memory req = buildChainlinkRequest(JOB, address(this), this.fulfill.selector);
    req.add("get", "https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=BTC&to_currency=USD&apikey=xxxx");
    string[] memory copyPath = new string[](2);
    copyPath[0] = "Realtime Currency Exchange Rate";
    copyPath[1] = "5. Exchange Rate";
    sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);
  }
  function fulfill(bytes32 _requestId, uint256 _price)
    public
    recordChainlinkFulfillment(_requestId)
  {
    btc = _price;
  }
  modifier onlyOwner() {
    require(msg.sender == owner);
    _;
  }
}

Body:
For this particular issue, do:

You need to add a multiply adapter to your job. In your getBTCPrice(), add a line:

run.addInt("times", 100000000);

There is a full example code below, however here are some tips on what might be going on.

The node address isn't funded with ETH - you'd have to contact the node operator.

Fund the Ethereum address that your Chainlink node uses. You can find the address in the node Operator GUI under the Keys tab. The address of the node is the Regular type. You can obtain test ETH from several faucets.

The jobid or oracle address is wrong - double check.

The node is currently down - ask the node operator.

You are blacklisted, or not whitelisted. Contact the node operator.

In solidity, decimals don't work, so whenever you're getting a number with decimals from an oracle, you need to add a multiply adapter so that it can understand.

Whole code below:

solidity
pragma solidity ^0.6.0;
import "github.com/smartcontractkit/chainlink/evm-contracts/src/v0.6/ChainlinkClient.sol";
contract testingData is ChainlinkClient {
  address public owner;
  uint256 public btc;
  address ORACLE =  0xB36d3709e22F7c708348E225b20b13eA546E6D9c;
  bytes32 constant JOB = "f9528decb5c64044b6b4de54ca7ea63e";
  uint256 constant private ORACLE_PAYMENT = 1 * LINK;
  constructor() public {
    setPublicChainlinkToken();
    owner = msg.sender;
  }
  function getBTCPrice()
    public
    onlyOwner
  {
    Chainlink.Request memory req = buildChainlinkRequest(JOB, address(this), this.fulfill.selector);
    req.add("get", "https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=BTC&to_currency=USD&apikey=xxxx");
    string[] memory copyPath = new string[](2);
    copyPath[0] = "Realtime Currency Exchange Rate";
    copyPath[1] = "5. Exchange Rate";
    sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);
  }
  function fulfill(bytes32 _requestId, uint256 _price)
    public
    recordChainlinkFulfillment(_requestId)
  {
    btc = _price;
  }
  modifier onlyOwner() {
    require(msg.sender == owner);
    _;
  }
}


问:
Adding numbers to marker in mapbox android
I'm trying to figure out how to add numbers to markers programmatically in mapbox to get the result of the image below

MARKERS WITH NUMBERS

Here is the code of the map that displays some markers

```<code>public class DepartMissionFragment extends Fragment {
    private MapView mapView;

    private static final String TAG = "DirectionsActivity";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        Mapbox.getInstance(requireActivity(), getString(R.string.access_token));
        View view  = inflater.inflate(R.layout.fragment_mission_depart, container, false);

        mapView = view.findViewById(R.id.mapView20);
        mapView.onCreate(savedInstanceState);
        mapView.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(@NonNull MapboxMap mapboxMap) {

                mapboxMap.addMarker(new MarkerOptions()
                        .position(new LatLng(33.589886, -7.603869))
                        .title("marker one"));
// It is possible to use .setIcon() to get a custom icon from ressources

                mapboxMap.addMarker(new MarkerOptions()
                        .position(new LatLng(33.589790, -7.603989))
                        .title("marker two"));

                mapboxMap.addMarker(new MarkerOptions()
                        .position(new LatLng(33.589190, -7.603089))
                        .title("marker three"));

                mapboxMap.addMarker(new MarkerOptions()
                        .position(new LatLng(33.588790, -7.603289))
                        .title("etc.."));

                mapboxMap.addMarker(new MarkerOptions()
                        .position(new LatLng(33.580790, -7.603989))
                        .title("etc...."));
                mapboxMap.setStyle(getString(R.string.navigation_guidance_day), new Style.OnStyleLoaded() {

                    @Override
                    public void onStyleLoaded(@NonNull Style style) {

                    }
                });

            }
        });
        return view;
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
    }

    @Override
    public void onStart() {
        super.onStart();
        mapView.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        mapView.onStop();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }
}
</code>```

I'm searching for a way to give numbers to the markers, a proper way for me would be to add custom marker from drawable.

Any other method is welcomed.

答:
Rather than displaying markers with the MapboxMap#addMarker method and depending on a drawable resource, you could add icons from coordinates stored as GeoJSON features using a symbol layer, as shown in this example for the Mapbox Maps SDK for Android.

When adding each Feature representing a coordinate to the a GeoJSON object, you could add a property to each Feature's properties object containing the number to display on the marker for this coordinate. Then, in addition to the iconImage added with SymbolLayer#setProperties as shown in the example, you could also add a textField for each symbol populated by the property added to the GeoJSON. This symbol layer clustering example shows a similar workflow applied to a clustering use case. The difference between the clustering example and your implementation will mainly be that, rather than obtaining the number to display from a clustered count, you will be obtaining it from a GeoJSON property which you specified for the coordinate.

Body:
I'm trying to figure out how to add numbers to markers programmatically in mapbox to get the result of the image below

MARKERS WITH NUMBERS

Here is the code of the map that displays some markers

public class DepartMissionFragment extends Fragment {
    private MapView mapView;

    private static final String TAG = "DirectionsActivity";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        Mapbox.getInstance(requireActivity(), getString(R.string.access_token));
        View view  = inflater.inflate(R.layout.fragment_mission_depart, container, false);

        mapView = view.findViewById(R.id.mapView20);
        mapView.onCreate(savedInstanceState);
        mapView.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(@NonNull MapboxMap mapboxMap) {

                mapboxMap.addMarker(new MarkerOptions()
                        .position(new LatLng(33.589886, -7.603869))
                        .title("marker one"));
// It is possible to use .setIcon() to get a custom icon from ressources

                mapboxMap.addMarker(new MarkerOptions()
                        .position(new LatLng(33.589790, -7.603989))
                        .title("marker two"));

                mapboxMap.addMarker(new MarkerOptions()
                        .position(new LatLng(33.589190, -7.603089))
                        .title("marker three"));

                mapboxMap.addMarker(new MarkerOptions()
                        .position(new LatLng(33.588790, -7.603289))
                        .title("etc.."));

                mapboxMap.addMarker(new MarkerOptions()
                        .position(new LatLng(33.580790, -7.603989))
                        .title("etc...."));
                mapboxMap.setStyle(getString(R.string.navigation_guidance_day), new Style.OnStyleLoaded() {

                    @Override
                    public void onStyleLoaded(@NonNull Style style) {

                    }
                });

            }
        });
        return view;
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
    }

    @Override
    public void onStart() {
        super.onStart();
        mapView.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        mapView.onStop();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }
}

I'm searching for a way to give numbers to the markers, a proper way for me would be to add custom marker from drawable.

Any other method is welcomed.


问:
How to sort tuple with python by using specific rules
I have this tuple:

```<code>[('site-nfv01-swsto01',), ('site-nfv01-swsto01V',),('site-nfv01-swsto02',),('site-nfv02-swsto02',), ('site-nfv02-swsto01',) , ('site-nfv02-swsto01V',)]
</code>```

I would like to classify it in this order:

```<code>site-nfv01-swsto01V
site-nfv01-swsto01
site-nfv01-swsto02
site-nfv02-swsto01V
site-nfv02-swsto01
site-nfv02-swsto02
</code>```

To have: [('site-nfv01-swsto01V',), ('site-nfv01-swsto01',),('site-nfv01-swsto02',),('site-nfv02-swsto01V',), ('site-nfv02-swsto01',) , ('site-nfv02-swsto02',)]

574 idea is to first classify the NFV part in ascending order ,after that, we classify the SWSTO in increasing order too but by putting the SWSTO which ends with 'V' first

How can I do that?

答:
Note that Python already sorts tuples naturally, first sorting on the first element, then the second element, etc. That means that if we can create a tuple which reflects the appropriate ranking of your elements, we can simply sort using that tuple as a key.

To convert your sorting pattern to a tuple, treat the presence of 'V' as negative infinity, and otherwise use the number.

Last, we can use conveniences of Python like zip and re to reduce the lines of code to get there.

import re
from math import inf
def sorted_tuples(string_list):
    def rank(chunk):
        if 'V' in chunk:
            return -inf
        return int(re.findall(r"\d+", chunk)[0])

    items = [(word, word.split('-')) for (word,) in string_list]
    keys = [(word, rank(chunks[1]), rank(chunks[2])) for (word, chunks) in items]
    keys.sort(key=lambda x: (x[1], x[2]))
    return list(zip(*keys))[0]

print(sorted_tuples([
     ('site-nfv01-swsto01V',),
     ('site-nfv01-swsto01',),
     ('site-nfv01-swsto02',),
     ('site-nfv02-swsto01V',),
     ('site-nfv02-swsto01',) ,
     ('site-nfv02-swsto02',)]))

# Outputs:
# ('site-nfv01-swsto01V',
#     'site-nfv01-swsto01',
#     'site-nfv01-swsto02',
#     'site-nfv02-swsto01V',
#     'site-nfv02-swsto01',
#     'site-nfv02-swsto02'
# )

```

<p>Or, for a one-liner (don't do this!):</p>

<pre class="lang-py prettyprint-override"><code>lambda string_list: list(zip(*sorted([(word, list(map(lambda x: -inf \
     if 'V' in x else int(re.findall(r"\d+", x)[0]), word.split('-') \
     [1:]))) for (word,) in string_list], key=lambda x: x[1])))[0]
</code>```

Body:
I have this tuple:

[('site-nfv01-swsto01',), ('site-nfv01-swsto01V',),('site-nfv01-swsto02',),('site-nfv02-swsto02',), ('site-nfv02-swsto01',) , ('site-nfv02-swsto01V',)]

I would like to classify it in this order:

site-nfv01-swsto01V
site-nfv01-swsto01
site-nfv01-swsto02
site-nfv02-swsto01V
site-nfv02-swsto01
site-nfv02-swsto02

To have: [('site-nfv01-swsto01V',), ('site-nfv01-swsto01',),('site-nfv01-swsto02',),('site-nfv02-swsto01V',), ('site-nfv02-swsto01',) , ('site-nfv02-swsto02',)]

574 idea is to first classify the NFV part in ascending order ,after that, we classify the SWSTO in increasing order too but by putting the SWSTO which ends with 'V' first

How can I do that?

Body:
Note that Python already sorts tuples naturally, first sorting on the first element, then the second element, etc. That means that if we can create a tuple which reflects the appropriate ranking of your elements, we can simply sort using that tuple as a key.

To convert your sorting pattern to a tuple, treat the presence of 'V' as negative infinity, and otherwise use the number.

Last, we can use conveniences of Python like zip and re to reduce the lines of code to get there.

import re
from math import inf
def sorted_tuples(string_list):
    def rank(chunk):
        if 'V' in chunk:
            return -inf
        return int(re.findall(r"\d+", chunk)[0])

    items = [(word, word.split('-')) for (word,) in string_list]
    keys = [(word, rank(chunks[1]), rank(chunks[2])) for (word, chunks) in items]
    keys.sort(key=lambda x: (x[1], x[2]))
    return list(zip(*keys))[0]

print(sorted_tuples([
     ('site-nfv01-swsto01V',),
     ('site-nfv01-swsto01',),
     ('site-nfv01-swsto02',),
     ('site-nfv02-swsto01V',),
     ('site-nfv02-swsto01',) ,
     ('site-nfv02-swsto02',)]))

# Outputs:
# ('site-nfv01-swsto01V',
#     'site-nfv01-swsto01',
#     'site-nfv01-swsto02',
#     'site-nfv02-swsto01V',
#     'site-nfv02-swsto01',
#     'site-nfv02-swsto02'
# )

Or, for a one-liner (don't do this!):

lambda string_list: list(zip(*sorted([(word, list(map(lambda x: -inf \
     if 'V' in x else int(re.findall(r"\d+", x)[0]), word.split('-') \
     [1:]))) for (word,) in string_list], key=lambda x: x[1])))[0]


问:
Codemirror can't use variable to get or set Value
Hello everybody I am using the Codemirror editor and have a standard code added inside the html textarea tag then I create the Codemirror element in jQuery but when I want to set the elements value from outside with setValue or getValue that doesn't work because the variable I defined codemirror to is undefined. The only workaround I found was to save the codemirror instance to a global variable using the change instance of codemirror but then the problem arises how do I trigger the change method on creation? Even better would be if the codemirror assigned variable wouldn't be undefined any suggestions?

```<code><textarea name="mediaopt" rows="8" cols="80">/*===== MEDIA OPTIMIZATION =====*/
</textarea>
</code>```

```<code>editor2 = CodeMirror.fromTextArea($('textarea[name="mediaopt"]')[0], {
                         lineNumbers: true,
                         lineWrapping: true,
                         smartIndent: true,
                         mode: "text/css",
                         extraKeys: {"Shift-Space": "autocomplete"},
                         autoCloseBrackets: true,
                         matchBrackets: true,
                         closeTags: true,
                         theme: "monokai",
                 }).on('change', editor => {
                        cssmediaopt = editor.getValue();
                        globaleditor = editor;
                });
</code>```

In this case editor2 is always undefined editor inside the change function is the codemirror instance which only works once the change method has been triggered and therefore globaleditor is undefined until the change thats what I want to change :)

答:
I would suggest wrapping each textarea in a div with a unique id / class. This way you can specify which codemirror instance you want to have the change event.

Use change, where I prefer using keyup, on the .CodeMirror class.

You can set your variables directly after an editor has been intialized.

```<code>var editor2 = CodeMirror.fromTextArea($('textarea[name="mediaopt"]')[0], {
    lineNumbers: true,
    lineWrapping: true,
    smartIndent: true,
    mode: "text/css",
    extraKeys: {"Shift-Space": "autocomplete"},
    autoCloseBrackets: true,
    matchBrackets: true,
    closeTags: true,
    theme: "monokai",
}
var cssmediaopt = editor.getValue();
var globaleditor = editor;

$(document).on('change', '.Editor_2 .CodeMirror', function() {
    cssmediaopt = editor.getValue();
    globaleditor = editor;
});
</code>```

Body:
Hello everybody I am using the Codemirror editor and have a standard code added inside the html textarea tag then I create the Codemirror element in jQuery but when I want to set the elements value from outside with setValue or getValue that doesn't work because the variable I defined codemirror to is undefined. The only workaround I found was to save the codemirror instance to a global variable using the change instance of codemirror but then the problem arises how do I trigger the change method on creation? Even better would be if the codemirror assigned variable wouldn't be undefined any suggestions?

<textarea name="mediaopt" rows="8" cols="80">/*===== MEDIA OPTIMIZATION =====*/
</textarea>

editor2 = CodeMirror.fromTextArea($('textarea[name="mediaopt"]')[0], {
                         lineNumbers: true,
                         lineWrapping: true,
                         smartIndent: true,
                         mode: "text/css",
                         extraKeys: {"Shift-Space": "autocomplete"},
                         autoCloseBrackets: true,
                         matchBrackets: true,
                         closeTags: true,
                         theme: "monokai",
                 }).on('change', editor => {
                        cssmediaopt = editor.getValue();
                        globaleditor = editor;
                });

In this case editor2 is always undefined editor inside the change function is the codemirror instance which only works once the change method has been triggered and therefore globaleditor is undefined until the change thats what I want to change :)

Body:
I would suggest wrapping each textarea in a div with a unique id / class. This way you can specify which codemirror instance you want to have the change event.

Use change, where I prefer using keyup, on the .CodeMirror class.

You can set your variables directly after an editor has been intialized.

var editor2 = CodeMirror.fromTextArea($('textarea[name="mediaopt"]')[0], {
    lineNumbers: true,
    lineWrapping: true,
    smartIndent: true,
    mode: "text/css",
    extraKeys: {"Shift-Space": "autocomplete"},
    autoCloseBrackets: true,
    matchBrackets: true,
    closeTags: true,
    theme: "monokai",
}
var cssmediaopt = editor.getValue();
var globaleditor = editor;

$(document).on('change', '.Editor_2 .CodeMirror', function() {
    cssmediaopt = editor.getValue();
    globaleditor = editor;
});


问:
How to select newly inserted record(s) in MSSQL stored procedure in case of execution of dynamic insert script?
I want to select newly inserted record in my sql server database.

I know that the right solution for me is this:

```<code>DECLARE @OutputTbl TABLE (ID INT)

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')
</code>```

But my question is about create insert script and execute it in specific stored procedure.

I wrote these two lines at the end of my stored procedure to insert my data to any table I need.

```<code>SET @sqlQuery = 'INSERT INTO ' + @tblName + '(' + @param_Collection + ') ' + 'OUTPUT INSERTED.' + @IDENT_Field + ' values('+ @value_Collection +')';
EXEC sys.sp_executesql @sqlQuery;
</code>```

All variables declared before.

I don't know how to access the identity field to select proper newly inserted record(s).

答:
No, you can't.

A table-valued parameter must be declared with the READONLY option. Thus you can't insert into it.

Even if you declare it in the dynamic SQL, you can insert the data into it, but you can't get the data from the table, because the table variable is isolated from the scope of the dynamic SQL.

Body:
I want to select newly inserted record in my sql server database.

I know that the right solution for me is this:

DECLARE @OutputTbl TABLE (ID INT)

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

But my question is about create insert script and execute it in specific stored procedure.

I wrote these two lines at the end of my stored procedure to insert my data to any table I need.

SET @sqlQuery = 'INSERT INTO ' + @tblName + '(' + @param_Collection + ') ' + 'OUTPUT INSERTED.' + @IDENT_Field + ' values('+ @value_Collection +')';
EXEC sys.sp_executesql @sqlQuery;

All variables declared before.

I don't know how to access the identity field to select proper newly inserted record(s).


问:
Deleting all objects(files & folders) from an Amazon S3 bucket folder
I have an Amazon S3 bucket[example-bucket] and a folder[prod] in it, the use case is to delete all the objects[files and folders] of prod folder.

I tried with this:

aws s3 rm s3://example-bucket/ --recursive --exclude="" --include="prod/.*"

it deletes the files but not the folders from /prod folder, which does not solve my problem. I just want to empty this prod folder.

I will appreciate the help provided to empty the folder.

thank you

答:
To empty the prod objects on the prod folder, your command will look like this:

```<code>aws s3 rm s3://example-bucket/prod --recursive
</code>```

Reference:
https://docs.aws.amazon.com/AmazonS3/latest/dev/delete-or-empty-bucket.html#empty-bucket

Body:
To empty the prod objects on the prod folder, your command will look like this:

aws s3 rm s3://example-bucket/prod --recursive

Reference:
https://docs.aws.amazon.com/AmazonS3/latest/dev/delete-or-empty-bucket.html#empty-bucket


问:
Docker MySQL - can't connect from Spring Boot app to MySQL database
What I'm trying to do is, connect from my spring-boot app to mysql database in Docker. Each in their own container.

But I must be having something wrong because I can't do it.

To keep it simple :

application-properties :

```<code># URL for the mysql db
spring.datasource.url=jdbc:mysql://workaround-mysql:3308/workaround?serverTimezone=UTC&max_allowed_packet=15728640
# User name in mysql
spring.datasource.username=springuser
# Password for mysql
spring.datasource.password=admin
#Port at which application runs
server.port=8080
</code>```

docker-compose for MySQL:

```<code>version: '3'
services:
  workaround-mysql:
    container_name: workaround-mysql
    image: mysql
    environment:
      MYSQL_DATABASE: workaround
      MYSQL_USER: springuser
      MYSQL_PASSWORD: admin
      MYSQL_ROOT_PASSWORD: admin
      MYSQL_ROOT_HOST: '%'
    ports:
      - "3308:3306"
    restart: always
</code>```

So pretty simple right ? Database I start with docker-compose up:

All seems to be working fine so far.

Now that I have db started, to the application, this is its docker-compose.yml:

```<code>version: '3'
services:

  workaround:
    restart: always
    # will build ./docker/workaround/Dockerfile
    build: ./docker/workaround
    working_dir: /workaround
    volumes:
      - ./:/workaround
      - ~/.m2:/root/.m2
    expose:
      - "8080"
    command: "mvn clean spring-boot:run"
</code>```

For its Dockerfile I use Linux Alpine and Java.

```<code>FROM alpine:3.9
....add java...
RUN apk update
RUN apk add dos2unix --update-cache --repository http://dl-3.alpinelinux.org/alpine/edge/community/ --allow-untrusted
RUN apk add bash
RUN apk add maven
</code>```

Super simple. Now let's start the application :

Unknown host, so let's try the IP then :

```<code>    docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' workaround-mysql

# URL for the mysql db
spring.datasource.url=jdbc:mysql://172.20.0.2:3308/workaround?serverTimezone=UTC&max_allowed_packet=15728640
</code>```

Now I get timeout:

As you can see I get error. What is wrong with my setup and how to fix
this? Either I have unknown host exception or Refused to connect or connection timeout.

I have tried:

Using ip of a container in my application.properties, didn't work

Different ports for MySQL and application

Different images and versions of MySQL

Having everything in one docker compose with wait

timer for database.

Minimal setup with
https://github.com/hellokoding/hellokoding-courses/tree/master/docker-examples/dockercompose-springboot-mysql-nginx
Also resulted in communication link failure, Site was accessible but I
doubt that db was connected properly.

Notes:

I run this all on one computer I use port 3308 because I have local
MySQL db at 3306.

Here is docker ps -a

@Vusal ANSWER output :

Only thing different from code in answer I did wait for database to be ready 30 seconds

```<code>command: /bin/bash -c "sleep 30;mvn clean spring-boot:run;"
</code>```

答:
Before you try to connect to the Docker container you should stop mysql in your computer then go to the application.properties and type:

```<code>spring.datasource.url=jdbc:mysql://localhost:3306/NAME_OF_YOUR_DB_HERE?useSSL=false&allowPublicKeyRetrieval=true
</code>```

Regarding localhost, you should inspect the mysql container and pick the IP address and use it instead. most likely is 172.17.0.2. If it did not work then use localhost.

Body:
What I'm trying to do is, connect from my spring-boot app to mysql database in Docker. Each in their own container.

But I must be having something wrong because I can't do it.

To keep it simple :

application-properties :

# URL for the mysql db
spring.datasource.url=jdbc:mysql://workaround-mysql:3308/workaround?serverTimezone=UTC&max_allowed_packet=15728640
# User name in mysql
spring.datasource.username=springuser
# Password for mysql
spring.datasource.password=admin
#Port at which application runs
server.port=8080

docker-compose for MySQL:

version: '3'
services:
  workaround-mysql:
    container_name: workaround-mysql
    image: mysql
    environment:
      MYSQL_DATABASE: workaround
      MYSQL_USER: springuser
      MYSQL_PASSWORD: admin
      MYSQL_ROOT_PASSWORD: admin
      MYSQL_ROOT_HOST: '%'
    ports:
      - "3308:3306"
    restart: always

So pretty simple right ? Database I start with docker-compose up:

All seems to be working fine so far.

Now that I have db started, to the application, this is its docker-compose.yml:

version: '3'
services:

  workaround:
    restart: always
    # will build ./docker/workaround/Dockerfile
    build: ./docker/workaround
    working_dir: /workaround
    volumes:
      - ./:/workaround
      - ~/.m2:/root/.m2
    expose:
      - "8080"
    command: "mvn clean spring-boot:run"

For its Dockerfile I use Linux Alpine and Java.

FROM alpine:3.9
....add java...
RUN apk update
RUN apk add dos2unix --update-cache --repository http://dl-3.alpinelinux.org/alpine/edge/community/ --allow-untrusted
RUN apk add bash
RUN apk add maven

Super simple. Now let's start the application :

Unknown host, so let's try the IP then :

    docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' workaround-mysql

# URL for the mysql db
spring.datasource.url=jdbc:mysql://172.20.0.2:3308/workaround?serverTimezone=UTC&max_allowed_packet=15728640

Now I get timeout:

As you can see I get error. What is wrong with my setup and how to fix
this? Either I have unknown host exception or Refused to connect or connection timeout.

I have tried:

Using ip of a container in my application.properties, didn't work

Different ports for MySQL and application

Different images and versions of MySQL

Having everything in one docker compose with wait

timer for database.

Minimal setup with
https://github.com/hellokoding/hellokoding-courses/tree/master/docker-examples/dockercompose-springboot-mysql-nginx
Also resulted in communication link failure, Site was accessible but I
doubt that db was connected properly.

Notes:

I run this all on one computer I use port 3308 because I have local
MySQL db at 3306.

Here is docker ps -a

@Vusal ANSWER output :

Only thing different from code in answer I did wait for database to be ready 30 seconds

command: /bin/bash -c "sleep 30;mvn clean spring-boot:run;"

Body:
Before you try to connect to the Docker container you should stop mysql in your computer then go to the application.properties and type:

spring.datasource.url=jdbc:mysql://localhost:3306/NAME_OF_YOUR_DB_HERE?useSSL=false&allowPublicKeyRetrieval=true

Regarding localhost, you should inspect the mysql container and pick the IP address and use it instead. most likely is 172.17.0.2. If it did not work then use localhost.


问:
how to add a pyside QGraphicsScene to a BoxLayout
I have a PySide2.QtWidgets.QVBoxLayout and a PySide2.QtWidgets.QGraphicsScene and I want to put the GraphicsScene in the layout. Here's a part of my code:

```<code>self.cn_graph = QtWidgets.QGraphicsScene()
[...]
self.ly_bottom = QtWidgets.QVBoxLayout()
[...]
self.ly_bottom.addWidget(self.cn_graph)
</code>```

but I get this error:

```<code>TypeError: 'PySide2.QtWidgets.QBoxLayout.addWidget' called with wrong argument types:
  PySide2.QtWidgets.QBoxLayout.addWidget(QGraphicsScene)
Supported signatures:
  PySide2.QtWidgets.QBoxLayout.addWidget(PySide2.QtWidgets.QWidget, int = 0,
  PySide2.QtCore.Qt.Alignment = Default(Qt.Alignment))
  PySide2.QtWidgets.QBoxLayout.addWidget(PySide2.QtWidgets.QWidget)
</code>```

I don't know if it's even possible to have a graphicsscene in a boxlayout so any idea is welcome.

答:
QGraphicsScene is not a widget, it is not a visual element, but a paint handler, instead you should use the QGraphicsView:</p>

```<code>self.cn_scene_graph = QtWidgets.QGraphicsScene()
self.cn_view_graph = QtWidgets.QGraphicsView(self.cn_scene_graph)
# ...
self.ly_bottom = QtWidgets.QVBoxLayout()
# ...
self.ly_bottom.addWidget(self.cn_view_graph)
</code>```

Body:
I have a PySide2.QtWidgets.QVBoxLayout and a PySide2.QtWidgets.QGraphicsScene and I want to put the GraphicsScene in the layout. Here's a part of my code:

self.cn_graph = QtWidgets.QGraphicsScene()
[...]
self.ly_bottom = QtWidgets.QVBoxLayout()
[...]
self.ly_bottom.addWidget(self.cn_graph)

but I get this error:

TypeError: 'PySide2.QtWidgets.QBoxLayout.addWidget' called with wrong argument types:
  PySide2.QtWidgets.QBoxLayout.addWidget(QGraphicsScene)
Supported signatures:
  PySide2.QtWidgets.QBoxLayout.addWidget(PySide2.QtWidgets.QWidget, int = 0,
  PySide2.QtCore.Qt.Alignment = Default(Qt.Alignment))
  PySide2.QtWidgets.QBoxLayout.addWidget(PySide2.QtWidgets.QWidget)

I don't know if it's even possible to have a graphicsscene in a boxlayout so any idea is welcome.

Body:
QGraphicsScene is not a widget, it is not a visual element, but a paint handler, instead you should use the QGraphicsView:

self.cn_scene_graph = QtWidgets.QGraphicsScene()
self.cn_view_graph = QtWidgets.QGraphicsView(self.cn_scene_graph)
# ...
self.ly_bottom = QtWidgets.QVBoxLayout()
# ...
self.ly_bottom.addWidget(self.cn_view_graph)


问:
"The breakpoint will not currently be hit. The source code is different from the original version." What does this mean?
When debugging in Visual Studio, sometimes I add a breakpoint but it's hollow and VS says "The breakpoint will not currently be hit. The source code is different from the original version." Obviously this prevents me from being able to debug.

What on earth does the message mean? What original version? If I've just opened up the solution and not made any changes whatsoever to the code, how can there be an 'original version'?

答:
I've tried the proposed solutions but it didn't work.

In case you have multiple project, make the one you want to debug as the startup project.


问:
R Reshape Using String
I have this data

```<code>data=data.frame(GROUP=c(1,2), a.q.var=c(5,4), b.w.var=c(7,8),
c.e.var=c(2,3))
</code>```

but I want this data where I reshape by '.var'

```<code>data2=data.frame(VARIABLE=c('a.q.var','b.w.var','c.e.var','a.q.var','b.w.var','c.e.var'),
VALUE=c(5,7,2,4,8,3),
GROUP=c(1,1,1,2,2,2))
</code>```

And what I try is:

```<code>library(reshape2)
data2 = reshape(data, id.var = grep('$.var'))
</code>```

but it does not work

答:
We can use pivot_longer

```<code>library(tidyr)
pivot_longer(data, cols  = -GROUP, names_to = 'VARIABLE', values_to = 'VALUE')
</code>```

Or with data.table

```<code>library(data.table)
melt(setDT(data), id.var = 'GROUP', variable.name = 'VARIABLE', value.name = 'VALUE')
</code>```

Title: R Reshape Using String

Body:
I have this data

data=data.frame(GROUP=c(1,2), a.q.var=c(5,4), b.w.var=c(7,8),
c.e.var=c(2,3))

but I want this data where I reshape by '.var'

data2=data.frame(VARIABLE=c('a.q.var','b.w.var','c.e.var','a.q.var','b.w.var','c.e.var'),
VALUE=c(5,7,2,4,8,3),
GROUP=c(1,1,1,2,2,2))

And what I try is:

library(reshape2)
data2 = reshape(data, id.var = grep('$.var'))

but it does not work

Body:
We can use pivot_longer

library(tidyr)
pivot_longer(data, cols  = -GROUP, names_to = 'VARIABLE', values_to = 'VALUE')

Or with data.table

library(data.table)
melt(setDT(data), id.var = 'GROUP', variable.name = 'VARIABLE', value.name = 'VALUE')


问:
Replicating system libraries for Android from Eclipse to Ant
I have a Android project which I'm building in Ant and I'm stuck on system libraries:  In Eclipse I've defined two system libraries, each consisting of a few jars, which I then include in my projects.  I've tried copying these jar files to the libs dir of the projects which use them and I'm still getting the same errors when compiling with ant.

Is there a difference between using a system library and including jars in the libs folder?  Is there something I'm missing - maybe some way of defining a system library in ant itself?

UPDATE:

It's failing on the following code in main_rules.xml when executing ant compile

```<code>    <!-- Generates the R.java file for this project's resources. -->
<target name="-resource-src" depends="-dirs">
    <if condition="${manifest.hasCode}">
        <then>
            <echo>Generating R.java / Manifest.java from the resources...</echo>
            <aapt executable="${aapt}"
                    command="package"
                    verbose="${verbose}"
                    manifest="AndroidManifest.xml"
                    androidjar="${android.jar}"
                    rfolder="${gen.absolute.dir}">
                <res path="${resource.absolute.dir}" />
            </aapt>
        </then>
        <else>
            <echo>hasCode = false. Skipping...</echo>
        </else>
    </if>
</target>
</code>```

I have added the libraries to the compile target javac task but this also doesn't seem to work.

答:
In Ant, you generally need to put jars on classpath explicitly. They are not automatically added to classpath just by putting them in a lib directory.

Find where javac is done in your Ant buildfile and look at the classpath used. You will need to update this classpath to include each jar.

Body:
I have a Android project which I'm building in Ant and I'm stuck on system libraries:  In Eclipse I've defined two system libraries, each consisting of a few jars, which I then include in my projects.  I've tried copying these jar files to the libs dir of the projects which use them and I'm still getting the same errors when compiling with ant.

Is there a difference between using a system library and including jars in the libs folder?  Is there something I'm missing - maybe some way of defining a system library in ant itself?

UPDATE:

It's failing on the following code in main_rules.xml when executing ant compile

<target name="-resource-src" depends="-dirs">
    <if condition="${manifest.hasCode}">
        <then>
            <echo>Generating R.java / Manifest.java from the resources...</echo>
            <aapt executable="${aapt}"
                    command="package"
                    verbose="${verbose}"
                    manifest="AndroidManifest.xml"
                    androidjar="${android.jar}"
                    rfolder="${gen.absolute.dir}">
                <res path="${resource.absolute.dir}" />
            </aapt>
        </then>
        <else>
            <echo>hasCode = false. Skipping...</echo>
        </else>
    </if>
</target>

I have added the libraries to the compile target javac task but this also doesn't seem to work.


问:
How to find and return a duplicate value in array
arr is array of strings:

```<code>["hello", "world", "stack", "overflow", "hello", "again"]
</code>```

What would be an easy and elegant way to check if arr has duplicates, and if so, return one of them (no matter which)?

Examples:

```<code>["A", "B", "C", "B", "A"]    # => "A" or "B"
["A", "B", "C"]              # => nil
</code>```

答:
This code will return list of duplicated values. Hash keys are used as an efficient way of checking which values have already been seen. Based on whether value has been seen, the original array ary is partitioned into 2 arrays: first containing unique values and second containing duplicates.

```<code>ary = ["hello", "world", "stack", "overflow", "hello", "again"]

hash={}
arr.partition { |v| hash.has_key?(v) ? false : hash[v]=0 }.last.uniq

=> ["hello"]
</code>```

You can further shorten it - albeit at a cost of slightly more complex syntax - to this form:

```<code>hash={}
arr.partition { |v| !hash.has_key?(v) && hash[v]=0 }.last.uniq
</code>```

Body:
arr is array of strings:

["hello", "world", "stack", "overflow", "hello", "again"]

What would be an easy and elegant way to check if arr has duplicates, and if so, return one of them (no matter which)?

Examples:

["A", "B", "C", "B", "A"]    # => "A" or "B"
["A", "B", "C"]              # => nil

Body:
This code will return list of duplicated values. Hash keys are used as an efficient way of checking which values have already been seen. Based on whether value has been seen, the original array ary is partitioned into 2 arrays: first containing unique values and second containing duplicates.

ary = ["hello", "world", "stack", "overflow", "hello", "again"]

hash={}
arr.partition { |v| hash.has_key?(v) ? false : hash[v]=0 }.last.uniq

=> ["hello"]

You can further shorten it - albeit at a cost of slightly more complex syntax - to this form:

hash={}
arr.partition { |v| !hash.has_key?(v) && hash[v]=0 }.last.uniq