问:
I can't manage to setup the database of a git clone project Ubuntu
Hello everyone,

First of all, I'm an absloute noob in Linux/Ubuntu.

I need to install a company site locally on my pc.

I have Ubuntu running on a VM with    Ruby on Rails installed.

I have git cloned the whole project but I    can not install the
database.

I have a method document on which    there is the method to follow
but despite doing all the steps    carefully, I can't manage to run
"rake db:create/migrate".

I'm    absolutely lost between Postgresql users and  associate
database, the    environment and test file, and the database.yml
file.

I don't know if    it's useful to say but when I gitcloned the
project I had no    database.yml (or even .exemple extension on it)

I have already tried the "bundle exec" prefix.

I re-created an entire VM to avoid conflict between root and non-root
allocations.

I commented code from config/initializers/recaptcha.rb.

I set password in postgresql and try with that password (but I think
I did a bit of anything, I'm lost at this level).

Well, here is what I have

With db:create :

```<code>martin@martin-virtual-machine:~/makerble$ rake db:create
** [Bugsnag] 2019-05-09 15:56:13 +0100: No valid API key has been set, notifications will not be sent
fe_sendauth: no password supplied
Couldn't create database for {"adapter"=>"postgresql", "database"=>"make_dev", "pool"=>5, "timeout"=>50, "host"=>"localhost"}
rake aborted!
PG::ConnectionBad: fe_sendauth: no password supplied

Tasks: TOP => db:create
(See full trace by running task with --trace)
</code>```

With db:migrate :

```<code>martin@martin-virtual-machine:~/makerble$ rake db:migrate
** [Bugsnag] 2019-05-09 15:57:19 +0100: No valid API key has been set, notifications will not be sent
/home/martin/makerble/config/initializers/devise.rb:8: warning: already initialized constant OpenSSL::SSL::VERIFY_PEER
rake aborted!
PG::ConnectionBad: fe_sendauth: no password supplied

Tasks: TOP => db:migrate
(See full trace by running task with --trace)
</code>```

I don't even know what is the expected outpout but here are the file instructions given :

Rails Project Setup

Rails Project Setup (2)

I also have another file containing :

Create a postgresql user and database

Reach your project in your laptop console with 'cd'

sudo apt-get install postgresql postgresql-contrib

sudo adduser postgres_user

sudo su - postgres

psql

CREATE USER postgres_user WITH PASSWORD 'password';

CREATE DATABASE my_postgres_db OWNER postgres_user;

\q

exit

sudo su - postgres_user

psql my_postgres_db

rake db:migrate

Huge thanks for your consideration and help

答:
Fixed it.
I was just running rake commands on the wrong db</p>

Body:
Hello everyone,

First of all, I'm an absloute noob in Linux/Ubuntu.

I need to install a company site locally on my pc.

I have Ubuntu running on a VM with    Ruby on Rails installed.

I have git cloned the whole project but I    can not install the
database.

I have a method document on which    there is the method to follow
but despite doing all the steps    carefully, I can't manage to run
"rake db:create/migrate".

I'm    absolutely lost between Postgresql users and  associate
database, the    environment and test file, and the database.yml
file.

I don't know if    it's useful to say but when I gitcloned the
project I had no    database.yml (or even .exemple extension on it)

I have already tried the "bundle exec" prefix.

I re-created an entire VM to avoid conflict between root and non-root
allocations.

I commented code from config/initializers/recaptcha.rb.

I set password in postgresql and try with that password (but I think
I did a bit of anything, I'm lost at this level).

Well, here is what I have

With db:create :

martin@martin-virtual-machine:~/makerble$ rake db:create
** [Bugsnag] 2019-05-09 15:56:13 +0100: No valid API key has been set, notifications will not be sent
fe_sendauth: no password supplied
Couldn't create database for {"adapter"=>"postgresql", "database"=>"make_dev", "pool"=>5, "timeout"=>50, "host"=>"localhost"}
rake aborted!
PG::ConnectionBad: fe_sendauth: no password supplied

Tasks: TOP => db:create
(See full trace by running task with --trace)

With db:migrate :

martin@martin-virtual-machine:~/makerble$ rake db:migrate
** [Bugsnag] 2019-05-09 15:57:19 +0100: No valid API key has been set, notifications will not be sent
/home/martin/makerble/config/initializers/devise.rb:8: warning: already initialized constant OpenSSL::SSL::VERIFY_PEER
rake aborted!
PG::ConnectionBad: fe_sendauth: no password supplied

Tasks: TOP => db:migrate
(See full trace by running task with --trace)

I don't even know what is the expected outpout but here are the file instructions given :

Rails Project Setup

Rails Project Setup (2)

I also have another file containing :

Create a postgresql user and database

Reach your project in your laptop console with 'cd'

sudo apt-get install postgresql postgresql-contrib

sudo adduser postgres_user

sudo su - postgres

psql

CREATE USER postgres_user WITH PASSWORD 'password';

CREATE DATABASE my_postgres_db OWNER postgres_user;

\q

exit

sudo su - postgres_user

psql my_postgres_db

rake db:migrate

Huge thanks for your consideration and help


来源: stackexchange

问:
Should I encapsulate slice and maps in Go? If so, how to do it?
I want to create a structure which will be accessible in other packages, but I don't want to allow modify this structure. In other languages this is archived by making all fields private and exposing only public getters.

Solution with getters works fine for all data types except slices and maps because returned slices and maps aren't copied by default so they can be modified. The only solution that I managed to figure out is to create new map/slice and assign all items in a loop but this introduce a lot of repetitive and ugly code, especially for large nested structures.

package main

import (
    "fmt"
)

type OtherStruct struct {
    prop string
}

type Struct struct {
    prop map[string]OtherStruct
}

func (s Struct) Prop() map[string]OtherStruct {
    return s.prop
}

func (s Struct) Prop2() map[string]*OtherStruct {
    prop := make(map[string]*OtherStruct, 0)
    for k := range s.prop {
        v := s.prop[k]
        prop[k] = &v
    }

    return prop
}

func main() {
    var s Struct;

    // Simple getter
    s = Struct{make(map[string]OtherStruct, 0)}
    p1 := s.Prop()
    fmt.Println(s) // &{map[]}
    p1["something"] = OtherStruct{"test"}
    fmt.Println(s) // {map[something:{test}]}

    // Getter which copies map
    s = Struct{make(map[string]OtherStruct, 0)}
    p2 := s.Prop2()
    fmt.Println(s) // &{map[]}
    p2["something"] = &OtherStruct{"test"}
    fmt.Println(s) // &{map[]}
}
```

Is there any better way to encapsulate slices/maps in Go? Or maybe I shouldn't use encapsulation at all in Go and use different approach?

答:
Returning slice or map values is idiomatic Go. The user of your package will know how those data structures work in Go.

In your example, the user of Struct should know that adding a new entry into the returned map would reflect for any other user of the same map.

```<code>// Simple getter
s = Struct{make(map[string]OtherStruct, 0)}
p1 := s.Prop()
fmt.Println(s) // &{map[]}
p1["something"] = OtherStruct{"test"}
fmt.Println(s) // {map[something:{test}]}
</code>```

You should worry about such things only in case of concurrency. That is, when multiple goroutines are accessing, and possibly changing, the elements inside your slice or map.

ContentLicense: CC BY-SA 4.0

Body:
I want to create a structure which will be accessible in other packages, but I don't want to allow modify this structure. In other languages this is archived by making all fields private and exposing only public getters.

Solution with getters works fine for all data types except slices and maps because returned slices and maps aren't copied by default so they can be modified. The only solution that I managed to figure out is to create new map/slice and assign all items in a loop but this introduce a lot of repetitive and ugly code, especially for large nested structures.

package main

import (
    "fmt"
)

type OtherStruct struct {
    prop string
}

type Struct struct {
    prop map[string]OtherStruct
}

func (s Struct) Prop() map[string]OtherStruct {
    return s.prop
}

func (s Struct) Prop2() map[string]*OtherStruct {
    prop := make(map[string]*OtherStruct, 0)
    for k := range s.prop {
        v := s.prop[k]
        prop[k] = &v
    }

    return prop
}

func main() {
    var s Struct;

    // Simple getter
    s = Struct{make(map[string]OtherStruct, 0)}
    p1 := s.Prop()
    fmt.Println(s) // &{map[]}
    p1["something"] = OtherStruct{"test"}
    fmt.Println(s) // {map[something:{test}]}

    // Getter which copies map
    s = Struct{make(map[string]OtherStruct, 0)}
    p2 := s.Prop2()
    fmt.Println(s) // &{map[]}
    p2["something"] = &OtherStruct{"test"}
    fmt.Println(s) // &{map[]}
}

Is there any better way to encapsulate slices/maps in Go? Or maybe I shouldn't use encapsulation at all in Go and use different approach?

Body:
Returning slice or map values is idiomatic Go. The user of your package will know how those data structures work in Go.

In your example, the user of Struct should know that adding a new entry into the returned map would reflect for any other user of the same map.

// Simple getter
s = Struct{make(map[string]OtherStruct, 0)}
p1 := s.Prop()
fmt.Println(s) // &{map[]}
p1["something"] = OtherStruct{"test"}
fmt.Println(s) // {map[something:{test}]}

You should worry about such things only in case of concurrency. That is, when multiple goroutines are accessing, and possibly changing, the elements inside your slice or map.


问:
Height of contentView of UIScrollView based on inside content using Storyboard
I'm actually facing difficulties to make my UIScrollView fully responsive using only storyboard constraints.

Here is my hierarchy :

```<code>> - UIViewController
>  - UIView
>   - UIScrollView
>    - contentView
>     - module1View
>     - module2View
>     - module3View
</code>```

All the modules are used to display charts. I want them to be responsive. I want their width to be 100% of the screen and their height is defined by a ratio added using constraint. The modules are displayed next to each other like news in a newsfeed.

My question is : How do you set the contentView height equal to the sum of all the modules (module 1 + 2 + 3) ?

In other word I want to achieve :

Top of contentView = top of module 1

Top of module 2 = bottom of module 1

Top of module 2 = bottom of module 2

Bottom of contentView = bottom of module 3

To managed to do that I follow some tutorial found on internet. Here are the steps I followed :

Setting UIScrollView contraints to define its place and position.

Setting UIScrollView top, bottom, left and right spacing to nearest neighbour to 0.

Setting the constraint between modules to "stack" them one on an
other.

(I'M BLOCKED HERE) Setting the bottom of the contentView to the
bottom of module 3 to allow the UIScrollview to scroll until the end
content.

I tried to force the height of UIScrollView : It works but it's not responsive. As the height of the module is calculated through a ratio, depending on the device, the height "module 1 + 2 + 3" while change.

I tried to add a constraint from module 3 to contentView to set the bottom of module 3 = bottom of contentView. All the constraints turn red with warning everywhere.

Do you have any idea to how to set height of contentView based on a responsive content ? (Like "wrap-content in a way).

Thanks in advance for you help !

答: I got mine working by not setting the content view's height equal to anything.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm actually facing difficulties to make my UIScrollView fully responsive using only storyboard constraints.

Here is my hierarchy :

> - UIViewController
>  - UIView
>   - UIScrollView
>    - contentView
>     - module1View
>     - module2View
>     - module3View

All the modules are used to display charts. I want them to be responsive. I want their width to be 100% of the screen and their height is defined by a ratio added using constraint. The modules are displayed next to each other like news in a newsfeed.

My question is : How do you set the contentView height equal to the sum of all the modules (module 1 + 2 + 3) ?

In other word I want to achieve :

Top of contentView = top of module 1

Top of module 2 = bottom of module 1

Top of module 2 = bottom of module 2

Bottom of contentView = bottom of module 3

To managed to do that I follow some tutorial found on internet. Here are the steps I followed :

Setting UIScrollView contraints to define its place and position.

Setting UIScrollView top, bottom, left and right spacing to nearest neighbour to 0.

Setting the constraint between modules to "stack" them one on an
other.

(I'M BLOCKED HERE) Setting the bottom of the contentView to the
bottom of module 3 to allow the UIScrollview to scroll until the end
content.

I tried to force the height of UIScrollView : It works but it's not responsive. As the height of the module is calculated through a ratio, depending on the device, the height "module 1 + 2 + 3" while change.

I tried to add a constraint from module 3 to contentView to set the bottom of module 3 = bottom of contentView. All the constraints turn red with warning everywhere.

Do you have any idea to how to set height of contentView based on a responsive content ? (Like "wrap-content in a way).

Thanks in advance for you help !


问:
How to build Static Binary for Tesseract?
I am currently building Tesseract 4.0.0 from source (on Ubuntu 14.04 for context), using the instructions found on: https://github.com/tesseract-ocr/tesseract/wiki/Compiling

I am using the following ./configure parameters:

./configure --disable-openmp  --disable-graphics --disable-opencl --enable-static LDFLAGS='-static -static-libgcc -static-libstdc++' --disable-shared

Followed by
make and sudo make install

The compiled binary I am running after is src/api/tesseract, which works as intended. The problem is that when I run ldd on this file, it actually shows dependencies.

Am I looking in the wrong spot for the static binary of Tesseract (I ran a find command in the entire repo and didn't see anything else that looked like an executable), or am I misunderstanding the meaning of a static binary - I am under the impression it is pretty much an executable version of Tesseract that does not require any dependencies to be pre installed.

If there is any problem with the configure options too please let me know. I do not believe that --disable-openmp  --disable-graphics --disable-opencl impacts static vs shared linking but I am using those for my desired tesseract build so I included them for more context.

答:
$ uname -a

Linux vm00 4.15.0-50-generic #54-Ubuntu SMP Mon May 6 18:46:08 UTC
2019 x86_64 x86_64 x86_64 GNU/Linux

$ echo $CFLAGS

-static

$ echo $LDFLAGS

-static -static-libgcc -static-libstdc++

$ ./configure --enable-static LDFLAGS='-static -static-libgcc -static-libstdc++' --disable-shared

...

Configuration is done.

$ make

...

Making all in unittest

...

$ file src/api/tesseract

src/api/tesseract: ELF 64-bit LSB shared object, x86-64, version 1
(GNU/Linux), dynamically linked, interpreter /lib64/l, for
GNU/Linux 3.2.0,
BuildID[sha1]=96afb1f1ff8962b3f9046c40407364ebf26369d1, with
debug_info, not stripped

Not statically linked.


问:
IR transmitter not working on Raspberry Pi
I am trying to turn on my TV using a Raspberry Pi.

I have followed the below instructions and added my remote config file, however, am having no luck! Any suggestions.

When running sudo /etc/init.d/lircd status, I get

```<code>lircd.service - Flexible IR remote input/output application support
   Loaded: loaded (/lib/systemd/system/lircd.service; enabled; vendor preset: enabled)
   Active: active (running) since Sun 2018-11-11 13:27:07 UTC; 5min ago
     Docs: man:lircd(8)
           http://lirc.org/html/configure.html
 Main PID: 334 (lircd)
   CGroup: /system.slice/lircd.service
           └─334 /usr/sbin/lircd --nodaemon

Nov 11 13:32:23 raspberrypi lircd[334]: lircd-0.9.4c[334]: Info: removed client
Nov 11 13:32:23 raspberrypi lircd-0.9.4c[334]: Info: removed client
Nov 11 13:32:42 raspberrypi lircd[334]: lircd-0.9.4c[334]: Notice: accepted new client on /var/run/lirc/lircd
Nov 11 13:32:42 raspberrypi lircd-0.9.4c[334]: Notice: accepted new client on /var/run/lirc/lircd
Nov 11 13:32:42 raspberrypi lircd[334]: lircd-0.9.4c[334]: Info: removed client
Nov 11 13:32:42 raspberrypi lircd-0.9.4c[334]: Info: removed client
Nov 11 13:32:54 raspberrypi lircd[334]: lircd-0.9.4c[334]: Notice: accepted new client on /var/run/lirc/lircd
Nov 11 13:32:54 raspberrypi lircd-0.9.4c[334]: Notice: accepted new client on /var/run/lirc/lircd
Nov 11 13:32:54 raspberrypi lircd[334]: lircd-0.9.4c[334]: Info: removed client
Nov 11 13:32:54 raspberrypi lircd-0.9.4c[334]: Info: removed client
</code>```

Here are the steps I took to set it up.

```<code># Add the following lines to /etc/modules file
lirc_dev
lirc_rpi gpio_in_pin=18 gpio_out_pin=17

# Add the following lines to /etc/lirc/hardware.conf file
LIRCD_ARGS="--uinput --listen"
LOAD_MODULES=true
DRIVER="default"
DEVICE="/dev/lirc0"
MODULES="lirc_rpi"

# Update the following line in /boot/config.txt
dtoverlay=lirc-rpi,gpio_in_pin=18,gpio_out_pin=17

# Update the following lines in /etc/lirc/lirc_options.conf
driver    = default
device    = /dev/lirc0

$ sudo /etc/init.d/lircd stop
$ sudo /etc/init.d/lircd start

# Check status to make lirc is running
$ sudo /etc/init.d/lircd status

# Reboot before testing
$ reboot
</code>```

答:
Just run into the same problem. There are two main parts to it:

Part 1: new LIRC config

With the new version on lirc 0.9.0+, the configuration needed is much less:

The driver is already included in the kernel, no need to edit anything in modules

The new config syntax is much different, there's a shell script provided to change an old config to the new one. Run: sudo /usr/share/lirc/lirc-old2new.sh

To summarise, you only need to change the /etc/lirc/lirc_options.conf. In particular, you need to edit the lines to driver = default AND device = /dev/lirc0.

This should solve part 1.

Part 2: new IR drivers

As you can see in the /boot/overlays/README, the LIRC driver is being outdated. There are new ones provided for IR input and output. The driver for IR output is the new gpio-ir-tx. You need to use that instead of lirc-rpi in your /boot/config.txt.

In summary, change dtoverlay=lirc-rpi,gpio_out_pin=17,gpio_in_pin=13 to

```<code>dtoverlay=gpio-ir-tx,gpio_pin=17
</code>```

NOTE the missing _out in the config. This driver only supports output, so no need for an input one. To handle inputs, use the gpio-ir one.

Body:
I am trying to turn on my TV using a Raspberry Pi.

I have followed the below instructions and added my remote config file, however, am having no luck! Any suggestions.

When running sudo /etc/init.d/lircd status, I get

lircd.service - Flexible IR remote input/output application support
   Loaded: loaded (/lib/systemd/system/lircd.service; enabled; vendor preset: enabled)
   Active: active (running) since Sun 2018-11-11 13:27:07 UTC; 5min ago
     Docs: man:lircd(8)
           http://lirc.org/html/configure.html
 Main PID: 334 (lircd)
   CGroup: /system.slice/lircd.service
           └─334 /usr/sbin/lircd --nodaemon

Nov 11 13:32:23 raspberrypi lircd[334]: lircd-0.9.4c[334]: Info: removed client
Nov 11 13:32:23 raspberrypi lircd-0.9.4c[334]: Info: removed client
Nov 11 13:32:42 raspberrypi lircd[334]: lircd-0.9.4c[334]: Notice: accepted new client on /var/run/lirc/lircd
Nov 11 13:32:42 raspberrypi lircd-0.9.4c[334]: Notice: accepted new client on /var/run/lirc/lircd
Nov 11 13:32:42 raspberrypi lircd[334]: lircd-0.9.4c[334]: Info: removed client
Nov 11 13:32:42 raspberrypi lircd-0.9.4c[334]: Info: removed client
Nov 11 13:32:54 raspberrypi lircd[334]: lircd-0.9.4c[334]: Notice: accepted new client on /var/run/lirc/lircd
Nov 11 13:32:54 raspberrypi lircd-0.9.4c[334]: Notice: accepted new client on /var/run/lirc/lircd
Nov 11 13:32:54 raspberrypi lircd[334]: lircd-0.9.4c[334]: Info: removed client
Nov 11 13:32:54 raspberrypi lircd-0.9.4c[334]: Info: removed client

Here are the steps I took to set it up.

# Add the following lines to /etc/modules file
lirc_dev
lirc_rpi gpio_in_pin=18 gpio_out_pin=17

# Add the following lines to /etc/lirc/hardware.conf file
LIRCD_ARGS="--uinput --listen"
LOAD_MODULES=true
DRIVER="default"
DEVICE="/dev/lirc0"
MODULES="lirc_rpi"

# Update the following line in /boot/config.txt
dtoverlay=lirc-rpi,gpio_in_pin=18,gpio_out_pin=17

# Update the following lines in /etc/lirc/lirc_options.conf
driver    = default
device    = /dev/lirc0

$ sudo /etc/init.d/lircd stop
$ sudo /etc/init.d/lircd start

# Check status to make lirc is running
$ sudo /etc/init.d/lircd status

# Reboot before testing
$ reboot

Body:
Just run into the same problem. There are two main parts to it:

Part 1: new LIRC config

With the new version on lirc 0.9.0+, the configuration needed is much less:

The driver is already included in the kernel, no need to edit anything in modules

The new config syntax is much different, there's a shell script provided to change an old config to the new one. Run: sudo /usr/share/lirc/lirc-old2new.sh

To summarise, you only need to change the /etc/lirc/lirc_options.conf. In particular, you need to edit the lines to driver = default AND device = /dev/lirc0.

This should solve part 1.

Part 2: new IR drivers

As you can see in the /boot/overlays/README, the LIRC driver is being outdated. There are new ones provided for IR input and output. The driver for IR output is the new gpio-ir-tx. You need to use that instead of lirc-rpi in your /boot/config.txt.

In summary, change dtoverlay=lirc-rpi,gpio_out_pin=17,gpio_in_pin=13 to

dtoverlay=gpio-ir-tx,gpio_pin=17

NOTE the missing _out in the config. This driver only supports output, so no need for an input one. To handle inputs, use the gpio-ir one.


问:
How to add external fonts to android application
I was looking for some stylish fonts for my android application. but the problem is how can i make my android application supportable for external fonts.

Thank you.

答:
Create a folder named fonts in the assets folder and add the snippet from the below link.</p>

```<code>Typeface tf = Typeface.createFromAsset(getApplicationContext().getAssets(),"fonts/fontname.ttf");
textview.setTypeface(tf);
</code>```

Body:
Create a folder named fonts in the assets folder and add the snippet from the below link.

Typeface tf = Typeface.createFromAsset(getApplicationContext().getAssets(),"fonts/fontname.ttf");
textview.setTypeface(tf);


问:
Query to find accounts with specified months
I Want to extract those account ids which are present in may and JUNE but not in JULY . I have data for 6 months

i have tried using CONDITION(AND/ NOT)

```<code>SELECT ACCOUNT_ID, DATA_MONTH
FROM DATA1
WHERE DATA_MONTH ='01-MAY-18' AND DATA_MONTH <> '01-JULY-18
GROUP BY DATA_MONTH
</code>```

I am still getting account ids which where in JULY

答:
You can put the conditions you need in a HAVING clause:

```<code>SELECT ACCOUNT_ID
FROM DATA1
GROUP BY ACCOUNT_ID
HAVING
  SUM(CASE WHEN MONTH(DATA_MONTH) = 5 THEN 1 ELSE 0 END) > 0
  AND
  SUM(CASE WHEN MONTH(DATA_MONTH) = 6 THEN 1 ELSE 0 END) > 0
  AND
  SUM(CASE WHEN MONTH(DATA_MONTH) = 7 THEN 1 ELSE 0 END) = 0
</code>```

I assume that in your rdbms there exists a function like MONTH() to extract the month from the date.

If you want to check the year also, you can do it in each condition, so you must change to:

```<code>CASE WHEN MONTH(DATA_MONTH) = 7 AND YEAR(DATA_MONTH) = 2018 THEN 1 ELSE 0
</code>```

Body:
I Want to extract those account ids which are present in may and JUNE but not in JULY . I have data for 6 months

i have tried using CONDITION(AND/ NOT)

SELECT ACCOUNT_ID, DATA_MONTH
FROM DATA1
WHERE DATA_MONTH ='01-MAY-18' AND DATA_MONTH <> '01-JULY-18
GROUP BY DATA_MONTH

I am still getting account ids which where in JULY

Body:
You can put the conditions you need in a HAVING clause:

SELECT ACCOUNT_ID
FROM DATA1
GROUP BY ACCOUNT_ID
HAVING
  SUM(CASE WHEN MONTH(DATA_MONTH) = 5 THEN 1 ELSE 0 END) > 0
  AND
  SUM(CASE WHEN MONTH(DATA_MONTH) = 6 THEN 1 ELSE 0 END) > 0
  AND
  SUM(CASE WHEN MONTH(DATA_MONTH) = 7 THEN 1 ELSE 0 END) = 0

I assume that in your rdbms there exists a function like MONTH() to extract the month from the date.

If you want to check the year also, you can do it in each condition, so you must change to:

CASE WHEN MONTH(DATA_MONTH) = 7 AND YEAR(DATA_MONTH) = 2018 THEN 1 ELSE 0


问:
How to create custom background for UITableView section?
I'm trying to create a custom background for my tableview section. The look I'm going for is this:

How do I customize the tableview section background/layer please, rather than just the individual cells?

Edit: Just to clarify - I'm talking about the white background under 'Latest Transactions'. So the top of the section is rounded (as is bottom) but all the rows are rectangular.

答:
Create UITableViewCell subclass and add a UIView with white color. Add left & right padding for the view to the cell. Add UILabel and other UI elements to this newly added view instead of adding in cell or its contentView. Set cell background color as UIColor.groupTableViewBackground

```<code>class CustomCell: UITableViewCell {

    let bgView = UIView()
    let label = UILabel()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        commonInit()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }
    func commonInit() {

        backgroundColor = .groupTableViewBackground

        bgView.backgroundColor = .white
        bgView.translatesAutoresizingMaskIntoConstraints = false
        addSubview(bgView)

        label.translatesAutoresizingMaskIntoConstraints = false
        bgView.addSubview(label)

        bgView.topAnchor.constraint(equalTo: topAnchor).isActive = true
        bgView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
        bgView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10).isActive = true
        bgView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10).isActive = true

        label.heightAnchor.constraint(equalToConstant: 30).isActive = true
        label.topAnchor.constraint(equalTo: bgView.topAnchor, constant: 5).isActive = true
        label.bottomAnchor.constraint(equalTo: bgView.bottomAnchor, constant: -5).isActive = true
        label.leadingAnchor.constraint(equalTo: bgView.leadingAnchor, constant: 5).isActive = true
        label.trailingAnchor.constraint(equalTo: bgView.trailingAnchor, constant: -5).isActive = true
    }
}
</code>```

Use this cell class in your tableView. And set your view controller background color and tableView background color as UIColor.groupTableViewBackground

In cellForRowAt check if the cell is first or last cell of the section. If it is the first cell of the section, apply corner radius to top left, top right corners. If the cell is the last cell of the section, apply corner radius to bottom left, bottom right corners. If the cell is in the middle remove corner radius.

```<code>class TableViewController: UITableViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.backgroundColor = .groupTableViewBackground
        tableView.register(CustomCell.self, forCellReuseIdentifier: "CustomCell")
        tableView.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 10)
        tableView.tableFooterView = UIView()
    }
    // MARK: - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "Section \(section) Title"
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell") as? CustomCell
            ?? CustomCell(style: .default, reuseIdentifier: "CustomCell")
        if indexPath.row == 0 {//first cell of this section
            cell.bgView.layer.cornerRadius = 15.0
            cell.bgView.layer.masksToBounds = true
            cell.bgView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        } else if indexPath.row == tableView.numberOfRows(inSection: indexPath.section)-1 {//last cell of this section
            cell.bgView.layer.cornerRadius = 15.0
            cell.bgView.layer.masksToBounds = true
            cell.bgView.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
        } else {
            cell.bgView.layer.cornerRadius = 0
        }
        cell.label.text = "Row \(indexPath.row)"
        return cell
    }
}
</code>```

Body:
Create UITableViewCell subclass and add a UIView with white color. Add left & right padding for the view to the cell. Add UILabel and other UI elements to this newly added view instead of adding in cell or its contentView. Set cell background color as UIColor.groupTableViewBackground

class CustomCell: UITableViewCell {

    let bgView = UIView()
    let label = UILabel()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        commonInit()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }
    func commonInit() {

        backgroundColor = .groupTableViewBackground

        bgView.backgroundColor = .white
        bgView.translatesAutoresizingMaskIntoConstraints = false
        addSubview(bgView)

        label.translatesAutoresizingMaskIntoConstraints = false
        bgView.addSubview(label)

        bgView.topAnchor.constraint(equalTo: topAnchor).isActive = true
        bgView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
        bgView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10).isActive = true
        bgView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10).isActive = true

        label.heightAnchor.constraint(equalToConstant: 30).isActive = true
        label.topAnchor.constraint(equalTo: bgView.topAnchor, constant: 5).isActive = true
        label.bottomAnchor.constraint(equalTo: bgView.bottomAnchor, constant: -5).isActive = true
        label.leadingAnchor.constraint(equalTo: bgView.leadingAnchor, constant: 5).isActive = true
        label.trailingAnchor.constraint(equalTo: bgView.trailingAnchor, constant: -5).isActive = true
    }
}

Use this cell class in your tableView. And set your view controller background color and tableView background color as UIColor.groupTableViewBackground

In cellForRowAt check if the cell is first or last cell of the section. If it is the first cell of the section, apply corner radius to top left, top right corners. If the cell is the last cell of the section, apply corner radius to bottom left, bottom right corners. If the cell is in the middle remove corner radius.

class TableViewController: UITableViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.backgroundColor = .groupTableViewBackground
        tableView.register(CustomCell.self, forCellReuseIdentifier: "CustomCell")
        tableView.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 10)
        tableView.tableFooterView = UIView()
    }
    // MARK: - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "Section \(section) Title"
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell") as? CustomCell
            ?? CustomCell(style: .default, reuseIdentifier: "CustomCell")
        if indexPath.row == 0 {//first cell of this section
            cell.bgView.layer.cornerRadius = 15.0
            cell.bgView.layer.masksToBounds = true
            cell.bgView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        } else if indexPath.row == tableView.numberOfRows(inSection: indexPath.section)-1 {//last cell of this section
            cell.bgView.layer.cornerRadius = 15.0
            cell.bgView.layer.masksToBounds = true
            cell.bgView.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
        } else {
            cell.bgView.layer.cornerRadius = 0
        }
        cell.label.text = "Row \(indexPath.row)"
        return cell
    }
}


问:
Embedded dll resources
Is there a clean way of accessing embedded resources (css/js/images etc) inside a dll.

For example, from an aspx page, can something similar to the below be used?

答:
I would suggest to take a look at WebResource.axd and the way how you can access embedded resources, like for example here:

http://weblogs.asp.net/jeff/archive/2005/07/18/419842.aspx

you can get the resource url on server side like this:

```<code>Page.ClientScript.GetWebResourceUrl(typeof(MyNameSpaces.MyControl), "MyNameSpaces.Resources.MyImage.gif")
</code>```

and then render it on page

Title: Embedded dll resources

Body:
I would suggest to take a look at WebResource.axd and the way how you can access embedded resources, like for example here:

http://weblogs.asp.net/jeff/archive/2005/07/18/419842.aspx

you can get the resource url on server side like this:

Page.ClientScript.GetWebResourceUrl(typeof(MyNameSpaces.MyControl), "MyNameSpaces.Resources.MyImage.gif")

and then render it on page


问:
Error when installing packages on AWS EC2 instance
I need to install S3FS package to mount S3 storage onto EC2 instance.

To do this, I executed following commands.

Update

```<code>ubuntu@ip-172-31-28-212:~$ sudo apt-get update
Hit:1 http://us-east-1.ec2.archive.ubuntu.com/ubuntu xenial InRelease
Hit:2 http://us-east-1.ec2.archive.ubuntu.com/ubuntu xenial-updates InRelease
Hit:3 http://us-east-1.ec2.archive.ubuntu.com/ubuntu xenial-backports InRelease
Hit:4 http://security.ubuntu.com/ubuntu xenial-security InRelease
Hit:5 https://nvidia.github.io/libnvidia-container/ubuntu16.04/amd64  InRelease
Hit:6 https://nvidia.github.io/nvidia-container-runtime/ubuntu16.04/amd64  InRelease
Hit:7 https://nvidia.github.io/nvidia-docker/ubuntu16.04/amd64  InRelease
Hit:8 http://ppa.launchpad.net/openjdk-r/ppa/ubuntu xenial InRelease
Reading package lists... Done
</code>```

Install dependency packages

```<code>ubuntu@ip-172-31-28-212:~$ sudo apt-get install automake autotools-dev fuse g++ git libcurl4-gnutls-dev libfuse-dev libssl-dev libxml2-dev make pkg-config
E: Could not get lock /var/lib/dpkg/lock-frontend - open (11: Resource temporarily unavailable)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?
</code>```

Remove /var/lib/dpkg/lock-frontend

```<code>ubuntu@ip-172-31-28-212:~$ sudo rm /var/lib/dpkg/lock-frontend
</code>```

Retry installing packages

```<code>ubuntu@ip-172-31-28-212:~$ sudo apt-get install automake autotools-dev fuse g++ git libcurl4-gnutls-dev libfuse-dev libssl-dev libxml2-dev make pkg-config
E: Could not get lock /var/lib/dpkg/lock - open (11: Resource temporarily unavailable)
E: Unable to lock the administration directory (/var/lib/dpkg/), is another process using it?
</code>```

Remove /var/lib/dpkg/lock

```<code>ubuntu@ip-172-31-28-212:~$ sudo rm /var/lib/dpkg/lock
</code>```

Install packages

```<code>ubuntu@ip-172-31-28-212:~$ sudo apt-get install automake autotools-dev fuse g++ git libcurl4-gnutls-dev libfuse-dev libssl-dev libxml2-dev make pkg-config
E: dpkg was interrupted, you must manually run 'sudo dpkg --configure -a' to correct the problem.
</code>```

sudo dpkg --configure -a

```<code>ubuntu@ip-172-31-28-212:~$ sudo dpkg --configure -a
Setting up libgs9-common (9.26~dfsg+0-0ubuntu0.16.04.5) ...
Setting up libapt-inst2.0:amd64 (1.2.29ubuntu0.1) ...
Processing triggers for ufw (0.35-0ubuntu2) ...
Setting up linux-image-4.4.0-1075-aws (4.4.0-1075.85) ...
Running depmod.
update-initramfs: deferring update (hook will be called later)
Examining /etc/kernel/postinst.d.
run-parts: executing /etc/kernel/postinst.d/apt-auto-removal 4.4.0-1075-aws /boot/vmlinuz-4.4.0-1075-aws
run-parts: executing /etc/kernel/postinst.d/dkms 4.4.0-1075-aws /boot/vmlinuz-4.4.0-1075-aws
run-parts: executing /etc/kernel/postinst.d/initramfs-tools 4.4.0-1075-aws /boot/vmlinuz-4.4.0-1075-aws
update-initramfs: Generating /boot/initrd.img-4.4.0-1075-aws
W: mdadm: /etc/mdadm/mdadm.conf defines no arrays.
run-parts: executing /etc/kernel/postinst.d/unattended-upgrades 4.4.0-1075-aws /boot/vmlinuz-4.4.0-1075-aws
run-parts: executing /etc/kernel/postinst.d/update-notifier 4.4.0-1075-aws /boot/vmlinuz-4.4.0-1075-aws
run-parts: executing /etc/kernel/postinst.d/x-grub-legacy-ec2 4.4.0-1075-aws /boot/vmlinuz-4.4.0-1075-aws
locale: Cannot set LC_ALL to default locale: No such file or directory
Searching for GRUB installation directory ... found: /boot/grub
Searching for default file ... found: /boot/grub/default
Testing for an existing GRUB menu.lst file ... found: /boot/grub/menu.lst
Searching for splash image ... none found, skipping ...
Found kernel: /boot/vmlinuz-4.4.0-1073-aws
Found kernel: /boot/vmlinuz-4.4.0-1072-aws
Found kernel: /boot/vmlinuz-4.4.0-1075-aws
Found kernel: /boot/vmlinuz-4.4.0-1073-aws
Found kernel: /boot/vmlinuz-4.4.0-1072-aws
Replacing config file /run/grub/menu.lst with new version
Updating /boot/grub/menu.lst ... done

run-parts: executing /etc/kernel/postinst.d/zz-update-grub 4.4.0-1075-aws /boot/vmlinuz-4.4.0-1075-aws
Generating grub configuration file ...
Found linux image: /boot/vmlinuz-4.4.0-1075-aws
Found initrd image: /boot/initrd.img-4.4.0-1075-aws
Found linux image: /boot/vmlinuz-4.4.0-1073-aws
Found initrd image: /boot/initrd.img-4.4.0-1073-aws
Found linux image: /boot/vmlinuz-4.4.0-1072-aws
Found initrd image: /boot/initrd.img-4.4.0-1072-aws
done
Setting up libpam-systemd:amd64 (229-4ubuntu21.16) ...
locale: Cannot set LC_ALL to default locale: No such file or directory
Setting up libisc160:amd64 (1:9.10.3.dfsg.P4-8ubuntu1.12) ...
Setting up linux-aws-headers-4.4.0-1075 (4.4.0-1075.85) ...
Setting up libisc-export160 (1:9.10.3.dfsg.P4-8ubuntu1.12) ...
Processing triggers for mime-support (3.59ubuntu1) ...
Processing triggers for ureadahead (0.100.0-19) ...
Setting up libarchive13:amd64 (3.1.2-11ubuntu0.16.04.6) ...
Setting up apt-utils (1.2.29ubuntu0.1) ...
Setting up tzdata (2018i-0ubuntu0.16.04) ...
locale: Cannot set LC_ALL to default locale: No such file or directory

Current default time zone: 'Etc/UTC'
Local time is now:      Sat Feb 23 05:06:41 UTC 2019.
Universal Time is now:  Sat Feb 23 05:06:41 UTC 2019.
Run 'dpkg-reconfigure tzdata' if you wish to change it.

Setting up linux-libc-dev:amd64 (4.4.0-142.168) ...
Setting up libdns-export162 (1:9.10.3.dfsg.P4-8ubuntu1.12) ...
Setting up libtiff5:amd64 (4.0.6-1ubuntu0.5) ...
Setting up libkrb5support0:amd64 (1.13.2+dfsg-5ubuntu2.1) ...
Setting up libisccc140:amd64 (1:9.10.3.dfsg.P4-8ubuntu1.12) ...
Setting up krb5-locales (1.13.2+dfsg-5ubuntu2.1) ...
Processing triggers for libc-bin (2.23-0ubuntu10) ...
Setting up udev (229-4ubuntu21.16) ...
addgroup: The group `input' already exists as a system group. Exiting.
update-initramfs: deferring update (trigger activated)
insserv: warning: script 'K01S100AMI' missing LSB tags and overrides
insserv: warning: script 'S100AMI' missing LSB tags and overrides
Processing triggers for systemd (229-4ubuntu21.16) ...
Setting up liblwres141:amd64 (1:9.10.3.dfsg.P4-8ubuntu1.12) ...
Setting up linux-image-aws (4.4.0.1075.77) ...
dpkg: error processing package unattended-upgrades (--configure):
 package is in a very bad inconsistent state; you should
 reinstall it before attempting configuration
Setting up libtiffxx5:amd64 (4.0.6-1ubuntu0.5) ...
Processing triggers for man-db (2.7.5-1) ...
Setting up linux-headers-4.4.0-1075-aws (4.4.0-1075.85) ...
Examining /etc/kernel/header_postinst.d.
run-parts: executing /etc/kernel/header_postinst.d/dkms 4.4.0-1075-aws /boot/vmlinuz-4.4.0-1075-aws
Setting up binutils (2.26.1-1ubuntu1~16.04.8) ...
Setting up initramfs-tools-bin (0.122ubuntu8.14) ...
Processing triggers for dbus (1.10.6-1ubuntu3.3) ...
Setting up libpoppler58:amd64 (0.41.0-0ubuntu1.12) ...
Processing triggers for hicolor-icon-theme (0.15-0ubuntu1.1) ...
Setting up libgs9:amd64 (9.26~dfsg+0-0ubuntu0.16.04.5) ...
Setting up libpolkit-gobject-1-0:amd64 (0.105-14.1ubuntu0.4) ...
Setting up libavahi-common-data:amd64 (0.6.32~rc+dfsg-1ubuntu2.3) ...
Setting up libk5crypto3:amd64 (1.13.2+dfsg-5ubuntu2.1) ...
Setting up initramfs-tools-core (0.122ubuntu8.14) ...
Setting up libpolkit-agent-1-0:amd64 (0.105-14.1ubuntu0.4) ...
Setting up libtiff5-dev:amd64 (4.0.6-1ubuntu0.5) ...
Setting up libtiff-tools (4.0.6-1ubuntu0.5) ...
Setting up initramfs-tools (0.122ubuntu8.14) ...
update-initramfs: deferring update (trigger activated)
Setting up ghostscript (9.26~dfsg+0-0ubuntu0.16.04.5) ...
Setting up linux-headers-aws (4.4.0.1075.77) ...
Setting up libpolkit-backend-1-0:amd64 (0.105-14.1ubuntu0.4) ...
Setting up linux-aws (4.4.0.1075.77) ...
Setting up libkrb5-3:amd64 (1.13.2+dfsg-5ubuntu2.1) ...
Setting up libavahi-common3:amd64 (0.6.32~rc+dfsg-1ubuntu2.3) ...
Setting up policykit-1 (0.105-14.1ubuntu0.4) ...
Removed symlink /run/systemd/system/polkitd.service.
Setting up libgssapi-krb5-2:amd64 (1.13.2+dfsg-5ubuntu2.1) ...
Setting up libavahi-client3:amd64 (0.6.32~rc+dfsg-1ubuntu2.3) ...
Setting up openssh-client (1:7.2p2-4ubuntu2.7) ...
Setting up libdns162:amd64 (1:9.10.3.dfsg.P4-8ubuntu1.12) ...
Setting up libcurl3:amd64 (7.47.0-1ubuntu2.12) ...
Setting up libcurl3-gnutls:amd64 (7.47.0-1ubuntu2.12) ...
Setting up libisccfg140:amd64 (1:9.10.3.dfsg.P4-8ubuntu1.12) ...
Setting up snapd (2.34.2ubuntu0.1) ...
snapd.snap-repair.service is a disabled or a static unit, not starting it.
Setting up openssh-sftp-server (1:7.2p2-4ubuntu2.7) ...
Setting up ubuntu-core-launcher (2.34.2ubuntu0.1) ...
Setting up libbind9-140:amd64 (1:9.10.3.dfsg.P4-8ubuntu1.12) ...
Setting up libcurl4-openssl-dev:amd64 (7.47.0-1ubuntu2.12) ...
Setting up bind9-host (1:9.10.3.dfsg.P4-8ubuntu1.12) ...
Setting up apt-transport-https (1.2.29ubuntu0.1) ...
Setting up curl (7.47.0-1ubuntu2.12) ...
Setting up dnsutils (1:9.10.3.dfsg.P4-8ubuntu1.12) ...
Setting up openssh-server (1:7.2p2-4ubuntu2.7) ...
locale: Cannot set LC_ALL to default locale: No such file or directory
insserv: warning: script 'K01S100AMI' missing LSB tags and overrides
insserv: warning: script 'S100AMI' missing LSB tags and overrides
Setting up libnss3-nssdb (2:3.28.4-0ubuntu0.16.04.4) ...
Setting up libnss3:amd64 (2:3.28.4-0ubuntu0.16.04.4) ...
Setting up openjdk-8-jre-headless:amd64 (8u191-b12-2ubuntu0.16.04.1) ...
Installing new version of config file /etc/java-8-openjdk/net.properties ...
Setting up openjdk-8-jdk-headless:amd64 (8u191-b12-2ubuntu0.16.04.1) ...
Setting up openjdk-8-jre:amd64 (8u191-b12-2ubuntu0.16.04.1) ...
Setting up openjdk-8-jdk:amd64 (8u191-b12-2ubuntu0.16.04.1) ...
Processing triggers for libc-bin (2.23-0ubuntu10) ...
Processing triggers for initramfs-tools (0.122ubuntu8.14) ...
update-initramfs: Generating /boot/initrd.img-4.4.0-1075-aws
W: mdadm: /etc/mdadm/mdadm.conf defines no arrays.
Errors were encountered while processing:
 unattended-upgrades
ubuntu@ip-172-31-28-212:~$
</code>```

Q1. Why can't I install packages on raw EC2 instance with errors with /var/lib/dpkg/lock-frontend and /var/lib/dpkg/lock

Q2. The other day, I could fix these issue

by removing those directories; /var/lib/dpkg/lock-frontend and /var/lib/dpkg/lock, and followed sudo dpkg --configure -a

But strangely this time, it didn't work. Why didn't it work?

and how to fix this issue?

答:
Is your instance sill initializing?

```<code>aws ec2 describe-instance-status --instance-id i-xxxxxxxxxxx
{
    "InstanceStatuses": [
        {
            "AvailabilityZone": "",
            "InstanceId": "i-xxxxxxxxxxx",
            "InstanceState": {
                "Code": 16,
                "Name": "running"
            },
            "InstanceStatus": {
                "Details": [
                    {
                        "Name": "reachability",
                        "Status": "initializing"
                    }
                ],
                "Status": "initializing"
            },
            "SystemStatus": {
                "Details": [
                    {
                        "Name": "reachability",
                        "Status": "initializing"
                    }
                ],
                "Status": "initializing"
            }
        }
    ]
}
</code>```

the initialization process installs a number of things, probably what keeps holding a lock.

Body:
I need to install S3FS package to mount S3 storage onto EC2 instance.

To do this, I executed following commands.

Update

ubuntu@ip-172-31-28-212:~$ sudo apt-get update
Hit:1 http://us-east-1.ec2.archive.ubuntu.com/ubuntu xenial InRelease
Hit:2 http://us-east-1.ec2.archive.ubuntu.com/ubuntu xenial-updates InRelease
Hit:3 http://us-east-1.ec2.archive.ubuntu.com/ubuntu xenial-backports InRelease
Hit:4 http://security.ubuntu.com/ubuntu xenial-security InRelease
Hit:5 https://nvidia.github.io/libnvidia-container/ubuntu16.04/amd64  InRelease
Hit:6 https://nvidia.github.io/nvidia-container-runtime/ubuntu16.04/amd64  InRelease
Hit:7 https://nvidia.github.io/nvidia-docker/ubuntu16.04/amd64  InRelease
Hit:8 http://ppa.launchpad.net/openjdk-r/ppa/ubuntu xenial InRelease
Reading package lists... Done

Install dependency packages

ubuntu@ip-172-31-28-212:~$ sudo apt-get install automake autotools-dev fuse g++ git libcurl4-gnutls-dev libfuse-dev libssl-dev libxml2-dev make pkg-config
E: Could not get lock /var/lib/dpkg/lock-frontend - open (11: Resource temporarily unavailable)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?

Remove /var/lib/dpkg/lock-frontend

ubuntu@ip-172-31-28-212:~$ sudo rm /var/lib/dpkg/lock-frontend

Retry installing packages

ubuntu@ip-172-31-28-212:~$ sudo apt-get install automake autotools-dev fuse g++ git libcurl4-gnutls-dev libfuse-dev libssl-dev libxml2-dev make pkg-config
E: Could not get lock /var/lib/dpkg/lock - open (11: Resource temporarily unavailable)
E: Unable to lock the administration directory (/var/lib/dpkg/), is another process using it?

Remove /var/lib/dpkg/lock

ubuntu@ip-172-31-28-212:~$ sudo rm /var/lib/dpkg/lock

Install packages

ubuntu@ip-172-31-28-212:~$ sudo apt-get install automake autotools-dev fuse g++ git libcurl4-gnutls-dev libfuse-dev libssl-dev libxml2-dev make pkg-config
E: dpkg was interrupted, you must manually run 'sudo dpkg --configure -a' to correct the problem.

sudo dpkg --configure -a

ubuntu@ip-172-31-28-212:~$ sudo dpkg --configure -a
Setting up libgs9-common (9.26~dfsg+0-0ubuntu0.16.04.5) ...
Setting up libapt-inst2.0:amd64 (1.2.29ubuntu0.1) ...
Processing triggers for ufw (0.35-0ubuntu2) ...
Setting up linux-image-4.4.0-1075-aws (4.4.0-1075.85) ...
Running depmod.
update-initramfs: deferring update (hook will be called later)
Examining /etc/kernel/postinst.d.
run-parts: executing /etc/kernel/postinst.d/apt-auto-removal 4.4.0-1075-aws /boot/vmlinuz-4.4.0-1075-aws
run-parts: executing /etc/kernel/postinst.d/dkms 4.4.0-1075-aws /boot/vmlinuz-4.4.0-1075-aws
run-parts: executing /etc/kernel/postinst.d/initramfs-tools 4.4.0-1075-aws /boot/vmlinuz-4.4.0-1075-aws
update-initramfs: Generating /boot/initrd.img-4.4.0-1075-aws
W: mdadm: /etc/mdadm/mdadm.conf defines no arrays.
run-parts: executing /etc/kernel/postinst.d/unattended-upgrades 4.4.0-1075-aws /boot/vmlinuz-4.4.0-1075-aws
run-parts: executing /etc/kernel/postinst.d/update-notifier 4.4.0-1075-aws /boot/vmlinuz-4.4.0-1075-aws
run-parts: executing /etc/kernel/postinst.d/x-grub-legacy-ec2 4.4.0-1075-aws /boot/vmlinuz-4.4.0-1075-aws
locale: Cannot set LC_ALL to default locale: No such file or directory
Searching for GRUB installation directory ... found: /boot/grub
Searching for default file ... found: /boot/grub/default
Testing for an existing GRUB menu.lst file ... found: /boot/grub/menu.lst
Searching for splash image ... none found, skipping ...
Found kernel: /boot/vmlinuz-4.4.0-1073-aws
Found kernel: /boot/vmlinuz-4.4.0-1072-aws
Found kernel: /boot/vmlinuz-4.4.0-1075-aws
Found kernel: /boot/vmlinuz-4.4.0-1073-aws
Found kernel: /boot/vmlinuz-4.4.0-1072-aws
Replacing config file /run/grub/menu.lst with new version
Updating /boot/grub/menu.lst ... done

run-parts: executing /etc/kernel/postinst.d/zz-update-grub 4.4.0-1075-aws /boot/vmlinuz-4.4.0-1075-aws
Generating grub configuration file ...
Found linux image: /boot/vmlinuz-4.4.0-1075-aws
Found initrd image: /boot/initrd.img-4.4.0-1075-aws
Found linux image: /boot/vmlinuz-4.4.0-1073-aws
Found initrd image: /boot/initrd.img-4.4.0-1073-aws
Found linux image: /boot/vmlinuz-4.4.0-1072-aws
Found initrd image: /boot/initrd.img-4.4.0-1072-aws
done
Setting up libpam-systemd:amd64 (229-4ubuntu21.16) ...
locale: Cannot set LC_ALL to default locale: No such file or directory
Setting up libisc160:amd64 (1:9.10.3.dfsg.P4-8ubuntu1.12) ...
Setting up linux-aws-headers-4.4.0-1075 (4.4.0-1075.85) ...
Setting up libisc-export160 (1:9.10.3.dfsg.P4-8ubuntu1.12) ...
Processing triggers for mime-support (3.59ubuntu1) ...
Processing triggers for ureadahead (0.100.0-19) ...
Setting up libarchive13:amd64 (3.1.2-11ubuntu0.16.04.6) ...
Setting up apt-utils (1.2.29ubuntu0.1) ...
Setting up tzdata (2018i-0ubuntu0.16.04) ...
locale: Cannot set LC_ALL to default locale: No such file or directory

Current default time zone: 'Etc/UTC'
Local time is now:      Sat Feb 23 05:06:41 UTC 2019.
Universal Time is now:  Sat Feb 23 05:06:41 UTC 2019.
Run 'dpkg-reconfigure tzdata' if you wish to change it.

Setting up linux-libc-dev:amd64 (4.4.0-142.168) ...
Setting up libdns-export162 (1:9.10.3.dfsg.P4-8ubuntu1.12) ...
Setting up libtiff5:amd64 (4.0.6-1ubuntu0.5) ...
Setting up libkrb5support0:amd64 (1.13.2+dfsg-5ubuntu2.1) ...
Setting up libisccc140:amd64 (1:9.10.3.dfsg.P4-8ubuntu1.12) ...
Setting up krb5-locales (1.13.2+dfsg-5ubuntu2.1) ...
Processing triggers for libc-bin (2.23-0ubuntu10) ...
Setting up udev (229-4ubuntu21.16) ...
addgroup: The group `input' already exists as a system group. Exiting.
update-initramfs: deferring update (trigger activated)
insserv: warning: script 'K01S100AMI' missing LSB tags and overrides
insserv: warning: script 'S100AMI' missing LSB tags and overrides
Processing triggers for systemd (229-4ubuntu21.16) ...
Setting up liblwres141:amd64 (1:9.10.3.dfsg.P4-8ubuntu1.12) ...
Setting up linux-image-aws (4.4.0.1075.77) ...
dpkg: error processing package unattended-upgrades (--configure):
 package is in a very bad inconsistent state; you should
 reinstall it before attempting configuration
Setting up libtiffxx5:amd64 (4.0.6-1ubuntu0.5) ...
Processing triggers for man-db (2.7.5-1) ...
Setting up linux-headers-4.4.0-1075-aws (4.4.0-1075.85) ...
Examining /etc/kernel/header_postinst.d.
run-parts: executing /etc/kernel/header_postinst.d/dkms 4.4.0-1075-aws /boot/vmlinuz-4.4.0-1075-aws
Setting up binutils (2.26.1-1ubuntu1~16.04.8) ...
Setting up initramfs-tools-bin (0.122ubuntu8.14) ...
Processing triggers for dbus (1.10.6-1ubuntu3.3) ...
Setting up libpoppler58:amd64 (0.41.0-0ubuntu1.12) ...
Processing triggers for hicolor-icon-theme (0.15-0ubuntu1.1) ...
Setting up libgs9:amd64 (9.26~dfsg+0-0ubuntu0.16.04.5) ...
Setting up libpolkit-gobject-1-0:amd64 (0.105-14.1ubuntu0.4) ...
Setting up libavahi-common-data:amd64 (0.6.32~rc+dfsg-1ubuntu2.3) ...
Setting up libk5crypto3:amd64 (1.13.2+dfsg-5ubuntu2.1) ...
Setting up initramfs-tools-core (0.122ubuntu8.14) ...
Setting up libpolkit-agent-1-0:amd64 (0.105-14.1ubuntu0.4) ...
Setting up libtiff5-dev:amd64 (4.0.6-1ubuntu0.5) ...
Setting up libtiff-tools (4.0.6-1ubuntu0.5) ...
Setting up initramfs-tools (0.122ubuntu8.14) ...
update-initramfs: deferring update (trigger activated)
Setting up ghostscript (9.26~dfsg+0-0ubuntu0.16.04.5) ...
Setting up linux-headers-aws (4.4.0.1075.77) ...
Setting up libpolkit-backend-1-0:amd64 (0.105-14.1ubuntu0.4) ...
Setting up linux-aws (4.4.0.1075.77) ...
Setting up libkrb5-3:amd64 (1.13.2+dfsg-5ubuntu2.1) ...
Setting up libavahi-common3:amd64 (0.6.32~rc+dfsg-1ubuntu2.3) ...
Setting up policykit-1 (0.105-14.1ubuntu0.4) ...
Removed symlink /run/systemd/system/polkitd.service.
Setting up libgssapi-krb5-2:amd64 (1.13.2+dfsg-5ubuntu2.1) ...
Setting up libavahi-client3:amd64 (0.6.32~rc+dfsg-1ubuntu2.3) ...
Setting up openssh-client (1:7.2p2-4ubuntu2.7) ...
Setting up libdns162:amd64 (1:9.10.3.dfsg.P4-8ubuntu1.12) ...
Setting up libcurl3:amd64 (7.47.0-1ubuntu2.12) ...
Setting up libcurl3-gnutls:amd64 (7.47.0-1ubuntu2.12) ...
Setting up libisccfg140:amd64 (1:9.10.3.dfsg.P4-8ubuntu1.12) ...
Setting up snapd (2.34.2ubuntu0.1) ...
snapd.snap-repair.service is a disabled or a static unit, not starting it.
Setting up openssh-sftp-server (1:7.2p2-4ubuntu2.7) ...
Setting up ubuntu-core-launcher (2.34.2ubuntu0.1) ...
Setting up libbind9-140:amd64 (1:9.10.3.dfsg.P4-8ubuntu1.12) ...
Setting up libcurl4-openssl-dev:amd64 (7.47.0-1ubuntu2.12) ...
Setting up bind9-host (1:9.10.3.dfsg.P4-8ubuntu1.12) ...
Setting up apt-transport-https (1.2.29ubuntu0.1) ...
Setting up curl (7.47.0-1ubuntu2.12) ...
Setting up dnsutils (1:9.10.3.dfsg.P4-8ubuntu1.12) ...
Setting up openssh-server (1:7.2p2-4ubuntu2.7) ...
locale: Cannot set LC_ALL to default locale: No such file or directory
insserv: warning: script 'K01S100AMI' missing LSB tags and overrides
insserv: warning: script 'S100AMI' missing LSB tags and overrides
Setting up libnss3-nssdb (2:3.28.4-0ubuntu0.16.04.4) ...
Setting up libnss3:amd64 (2:3.28.4-0ubuntu0.16.04.4) ...
Setting up openjdk-8-jre-headless:amd64 (8u191-b12-2ubuntu0.16.04.1) ...
Installing new version of config file /etc/java-8-openjdk/net.properties ...
Setting up openjdk-8-jdk-headless:amd64 (8u191-b12-2ubuntu0.16.04.1) ...
Setting up openjdk-8-jre:amd64 (8u191-b12-2ubuntu0.16.04.1) ...
Setting up openjdk-8-jdk:amd64 (8u191-b12-2ubuntu0.16.04.1) ...
Processing triggers for libc-bin (2.23-0ubuntu10) ...
Processing triggers for initramfs-tools (0.122ubuntu8.14) ...
update-initramfs: Generating /boot/initrd.img-4.4.0-1075-aws
W: mdadm: /etc/mdadm/mdadm.conf defines no arrays.
Errors were encountered while processing:
 unattended-upgrades
ubuntu@ip-172-31-28-212:~$

Q1. Why can't I install packages on raw EC2 instance with errors with /var/lib/dpkg/lock-frontend and /var/lib/dpkg/lock

Q2. The other day, I could fix these issue

by removing those directories; /var/lib/dpkg/lock-frontend and /var/lib/dpkg/lock, and followed sudo dpkg --configure -a

But strangely this time, it didn't work. Why didn't it work?

and how to fix this issue?

Body:
Is your instance sill initializing?

aws ec2 describe-instance-status --instance-id i-xxxxxxxxxxx
{
    "InstanceStatuses": [
        {
            "AvailabilityZone": "",
            "InstanceId": "i-xxxxxxxxxxx",
            "InstanceState": {
                "Code": 16,
                "Name": "running"
            },
            "InstanceStatus": {
                "Details": [
                    {
                        "Name": "reachability",
                        "Status": "initializing"
                    }
                ],
                "Status": "initializing"
            },
            "SystemStatus": {
                "Details": [
                    {
                        "Name": "reachability",
                        "Status": "initializing"
                    }
                ],
                "Status": "initializing"
            }
        }
    ]
}

the initialization process installs a number of things, probably what keeps holding a lock.


问:
How to click a clickablespan using espresso?
I have a textview with multiple clickable spans in it. I want to be able to test clicking these spans.

I tried setting up a custom ViewAction that would find the clickablespans in the TextView and then match their text with the desired text and then click on the xy coordinates of that text. However, it seems the spans added to the TextView aren't of type ClickableSpan and are instead the the fragment that added the span.

Therefore, I am not able to distinguish the link spans. Is there a better way to do this?

Adding the spans:

```<code>Util.addClickableSpan(spannableString, string, linkedString, new      ClickableSpan() {
@Override
public void onClick(View textView) {}
});

tvAcceptTc.setText(spannableString);
tvAcceptTc.setMovementMethod(LinkMovementMethod.getInstance());
</code>```

Utility method:

```<code>public static void addClickableSpan(SpannableString spannableString,
                              String text,
                              String subText,
                              ClickableSpan clickableSpan) {
        int start = text.indexOf(subText);
        int end = text.indexOf(subText) + subText.length();
        int flags = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE;

        spannableString.setSpan(clickableSpan, start, end, flags);
}
</code>```

Defining the ViewAction:

```<code>@Override
        public void perform(UiController uiController, View view) {
            uiController.loopMainThreadUntilIdle();
            if (view instanceof TextView) {

                TextView textView = (TextView) view;
                Layout textViewLayout = textView.getLayout();

                SpannableString fullSpannable = new SpannableString(textView.getText());

                Object[] spans = fullSpannable.getSpans(0, fullSpannable.length(), Object.class);

                ClickableSpan span = null;
                for (Object object : spans) {
                    if (object instanceof BaseFragment) {
                        ClickableSpan foundSpan = (ClickableSpan)object;
                        int spanStart = fullSpannable.getSpanStart(foundSpan);
                        int spanEnd = fullSpannable.getSpanEnd(foundSpan);
                        if (fullSpannable.subSequence(spanStart, spanEnd).equals(aSubstring)) {
                            //Found the correct span!
                            span = foundSpan;
                        }
                    }
                } ... go on to click the xy-coordinates
</code>```

答:
Here is the Kotlin version of accepted answer</p>

```<code>fun clickClickableSpan(textToClick: CharSequence): ViewAction {
    return object : ViewAction {

        override fun getConstraints(): Matcher<View> {
            return Matchers.instanceOf(TextView::class.java)
        }

        override fun getDescription(): String {
            return "clicking on a ClickableSpan";
        }

        override fun perform(uiController: UiController, view: View) {
            val textView = view as TextView
            val spannableString = textView.text as SpannableString

            if (spannableString.isEmpty()) {
                // TextView is empty, nothing to do
                throw NoMatchingViewException.Builder()
                        .includeViewHierarchy(true)
                        .withRootView(textView)
                        .build();
            }

            // Get the links inside the TextView and check if we find textToClick
            val spans = spannableString.getSpans(0, spannableString.length, ClickableSpan::class.java)
            if (spans.isNotEmpty()) {
                var spanCandidate: ClickableSpan
                for (span: ClickableSpan in spans) {
                    spanCandidate = span
                    val start = spannableString.getSpanStart(spanCandidate)
                    val end = spannableString.getSpanEnd(spanCandidate)
                    val sequence = spannableString.subSequence(start, end)
                    if (textToClick.toString().equals(sequence.toString())) {
                        span.onClick(textView)
                        return;
                    }
                }
            }

            // textToClick not found in TextView
            throw NoMatchingViewException.Builder()
                    .includeViewHierarchy(true)
                    .withRootView(textView)
                    .build()

        }
    }
}
</code>```

Body:
I have a textview with multiple clickable spans in it. I want to be able to test clicking these spans.

I tried setting up a custom ViewAction that would find the clickablespans in the TextView and then match their text with the desired text and then click on the xy coordinates of that text. However, it seems the spans added to the TextView aren't of type ClickableSpan and are instead the the fragment that added the span.

Therefore, I am not able to distinguish the link spans. Is there a better way to do this?

Adding the spans:

Util.addClickableSpan(spannableString, string, linkedString, new      ClickableSpan() {
@Override
public void onClick(View textView) {}
});

tvAcceptTc.setText(spannableString);
tvAcceptTc.setMovementMethod(LinkMovementMethod.getInstance());

Utility method:

public static void addClickableSpan(SpannableString spannableString,
                              String text,
                              String subText,
                              ClickableSpan clickableSpan) {
        int start = text.indexOf(subText);
        int end = text.indexOf(subText) + subText.length();
        int flags = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE;

        spannableString.setSpan(clickableSpan, start, end, flags);
}

Defining the ViewAction:

@Override
        public void perform(UiController uiController, View view) {
            uiController.loopMainThreadUntilIdle();
            if (view instanceof TextView) {

                TextView textView = (TextView) view;
                Layout textViewLayout = textView.getLayout();

                SpannableString fullSpannable = new SpannableString(textView.getText());

                Object[] spans = fullSpannable.getSpans(0, fullSpannable.length(), Object.class);

                ClickableSpan span = null;
                for (Object object : spans) {
                    if (object instanceof BaseFragment) {
                        ClickableSpan foundSpan = (ClickableSpan)object;
                        int spanStart = fullSpannable.getSpanStart(foundSpan);
                        int spanEnd = fullSpannable.getSpanEnd(foundSpan);
                        if (fullSpannable.subSequence(spanStart, spanEnd).equals(aSubstring)) {
                            //Found the correct span!
                            span = foundSpan;
                        }
                    }
                } ... go on to click the xy-coordinates

Body:
Here is the Kotlin version of accepted answer

fun clickClickableSpan(textToClick: CharSequence): ViewAction {
    return object : ViewAction {

        override fun getConstraints(): Matcher<View> {
            return Matchers.instanceOf(TextView::class.java)
        }

        override fun getDescription(): String {
            return "clicking on a ClickableSpan";
        }

        override fun perform(uiController: UiController, view: View) {
            val textView = view as TextView
            val spannableString = textView.text as SpannableString

            if (spannableString.isEmpty()) {
                // TextView is empty, nothing to do
                throw NoMatchingViewException.Builder()
                        .includeViewHierarchy(true)
                        .withRootView(textView)
                        .build();
            }

            // Get the links inside the TextView and check if we find textToClick
            val spans = spannableString.getSpans(0, spannableString.length, ClickableSpan::class.java)
            if (spans.isNotEmpty()) {
                var spanCandidate: ClickableSpan
                for (span: ClickableSpan in spans) {
                    spanCandidate = span
                    val start = spannableString.getSpanStart(spanCandidate)
                    val end = spannableString.getSpanEnd(spanCandidate)
                    val sequence = spannableString.subSequence(start, end)
                    if (textToClick.toString().equals(sequence.toString())) {
                        span.onClick(textView)
                        return;
                    }
                }
            }

            // textToClick not found in TextView
            throw NoMatchingViewException.Builder()
                    .includeViewHierarchy(true)
                    .withRootView(textView)
                    .build()

        }
    }
}


问:
How to use Oraclize in solidity to pass arguments to the data source?
My aim is to pass some string to the data source and then process there and get back the result.
Below given code works in solidity

```<code>oraclize_query("URL", "json(https://clever-ape-38.localtunnel.me).a","sfdg");
</code>```

But when i try to fetch some value from blockchain and use it, if fails

```<code>string memory st = arr[msg.sender];
oraclize_query("URL", "json(https://clever-ape-38.localtunnel.me).a",st);
</code>```

everything compiles properly. Even truffle migrate --reset works fine.
I feel that the fetching from blockchain takes some time and oraclize_query() is called before the fetch.

Below there is mentioned the error.

```<code>    [2019-05-28T08:54:50.206Z] INFO new HTTP query created, id: 72e3a263387ed365d97bc97a64c601380a5b4e8bbd1b3740bcc2af1e2bc97b19
[2019-05-28T08:54:50.215Z] INFO checking HTTP query 72e3a263387ed365d97bc97a64c601380a5b4e8bbd1b3740bcc2af1e2bc97b19 status in 0 seconds
[2019-05-28T08:54:50.215Z] INFO checking HTTP query 72e3a263387ed365d97bc97a64c601380a5b4e8bbd1b3740bcc2af1e2bc97b19 status every 5 seconds...
[2019-05-28T08:54:56.634Z] INFO 72e3a263387ed365d97bc97a64c601380a5b4e8bbd1b3740bcc2af1e2bc97b19 HTTP query result:
    {
    "result": {
        "_timestamp": 1559033691,
        "id": "72e3a263387ed365d97bc97a64c601380a5b4e8bbd1b3740bcc2af1e2bc97b19",
        "daterange": [
            1559033689,
            1559035489
        ],
        "_lock": false,
        "id2": "72fdf59adf3ecc92244e3b173ce1657252ab5eb877c3569a393599d34dd2c848",
        "actions": [],
        "interval": 3600,
        "checks": [
            {
                "errors": [
                    "TypeError",
                    "parsing_helper.wrong_path"
                ],
                "success": true,
                "timestamp": 1559033691,
                "results": [
                    ""
                ],
                "proofs": [
                    null
                ],
                "match": true
            }
        ],
        "version": 3,
        "_timestamp_creation": 1559033689,
        "context": {
            "protocol": "eth",
            "relative_timestamp": 1559033687,
            "type": "blockchain",
            "name": "eth_AB65E563DB"
        },
        "active": false,
        "hidden": false,
        "payload": {
            "conditions": [
                {
                    "query": [
                        "json(https://purple-squid-54.localtunnel.me).a",
                        "28189689"
                    ],
                    "proof_type": 0,
                    "check_op": "tautology",
                    "datasource": "URL",
                    "value": null
                }
            ]
        }
    },
    "success": true
}
[2019-05-28T08:54:56.637Z] ERROR HTTP query error
    [
    "TypeError",
    "parsing_helper.wrong_path"
]
[2019-05-28T08:54:56.639Z] INFO sending __callback tx...
    {
    "contract_myid": "0x72fdf59adf3ecc92244e3b173ce1657252ab5eb877c3569a393599d34dd2c848",
    "contract_address": "0x481a276d14a6a74e1ec1f74b64c2af226ba7033c"
}
[2019-05-28T08:55:01.853Z] INFO contract 0x481a276d14a6a74e1ec1f74b64c2af226ba7033c __callback tx sent, transaction hash: 0xfada229b6f9860e0717b3a098dd93aaef280852dbf75109c830b555c488e6c81
    {
    "myid": "0x72fdf59adf3ecc92244e3b173ce1657252ab5eb877c3569a393599d34dd2c848",
    "result": "",
    "proof": null,
    "proof_type": "0x00",
    "contract_address": "0x481a276d14a6a74e1ec1f74b64c2af226ba7033c",
    "gas_limit": 200000,
    "gas_price": null
}
</code>```

Please help to solve this.

答:
Thank you for adding the error logs.

Actual answer:

If you're adding POST data as a string but that's in a valid JSON format, it will be parsed as such. In order to preserve it as a string, you need to add a newline char or whitespace so the beginning of the string:

"\n<post-data-here"

Original answer re the parsing-error which proved not to be the main issue in the end...

You're hitting a parsing error in the ethereum-bridge due to it trying but failing to parse the returned json from your query.

However at the time of writing, your local tunnel is returning a 404 error rather than the data it originally returned.

Then, as the ethereum-bridgeattempts to parse thejsonto pluck the value from thea` key, per your query:

json(https://purple-squid-54.localtunnel.me).a

...it can't because there is not json and so no a field and so you get a parsing error.

To fix it, ensure your local tunnel is working and that the data returned is in correct json format, and that there is an a key present for the parser to work with.

Body:
My aim is to pass some string to the data source and then process there and get back the result.
Below given code works in solidity

oraclize_query("URL", "json(https://clever-ape-38.localtunnel.me).a","sfdg");

But when i try to fetch some value from blockchain and use it, if fails

string memory st = arr[msg.sender];
oraclize_query("URL", "json(https://clever-ape-38.localtunnel.me).a",st);

everything compiles properly. Even truffle migrate --reset works fine.
I feel that the fetching from blockchain takes some time and oraclize_query() is called before the fetch.

Below there is mentioned the error.

    [2019-05-28T08:54:50.206Z] INFO new HTTP query created, id: 72e3a263387ed365d97bc97a64c601380a5b4e8bbd1b3740bcc2af1e2bc97b19
[2019-05-28T08:54:50.215Z] INFO checking HTTP query 72e3a263387ed365d97bc97a64c601380a5b4e8bbd1b3740bcc2af1e2bc97b19 status in 0 seconds
[2019-05-28T08:54:50.215Z] INFO checking HTTP query 72e3a263387ed365d97bc97a64c601380a5b4e8bbd1b3740bcc2af1e2bc97b19 status every 5 seconds...
[2019-05-28T08:54:56.634Z] INFO 72e3a263387ed365d97bc97a64c601380a5b4e8bbd1b3740bcc2af1e2bc97b19 HTTP query result:
    {
    "result": {
        "_timestamp": 1559033691,
        "id": "72e3a263387ed365d97bc97a64c601380a5b4e8bbd1b3740bcc2af1e2bc97b19",
        "daterange": [
            1559033689,
            1559035489
        ],
        "_lock": false,
        "id2": "72fdf59adf3ecc92244e3b173ce1657252ab5eb877c3569a393599d34dd2c848",
        "actions": [],
        "interval": 3600,
        "checks": [
            {
                "errors": [
                    "TypeError",
                    "parsing_helper.wrong_path"
                ],
                "success": true,
                "timestamp": 1559033691,
                "results": [
                    ""
                ],
                "proofs": [
                    null
                ],
                "match": true
            }
        ],
        "version": 3,
        "_timestamp_creation": 1559033689,
        "context": {
            "protocol": "eth",
            "relative_timestamp": 1559033687,
            "type": "blockchain",
            "name": "eth_AB65E563DB"
        },
        "active": false,
        "hidden": false,
        "payload": {
            "conditions": [
                {
                    "query": [
                        "json(https://purple-squid-54.localtunnel.me).a",
                        "28189689"
                    ],
                    "proof_type": 0,
                    "check_op": "tautology",
                    "datasource": "URL",
                    "value": null
                }
            ]
        }
    },
    "success": true
}
[2019-05-28T08:54:56.637Z] ERROR HTTP query error
    [
    "TypeError",
    "parsing_helper.wrong_path"
]
[2019-05-28T08:54:56.639Z] INFO sending __callback tx...
    {
    "contract_myid": "0x72fdf59adf3ecc92244e3b173ce1657252ab5eb877c3569a393599d34dd2c848",
    "contract_address": "0x481a276d14a6a74e1ec1f74b64c2af226ba7033c"
}
[2019-05-28T08:55:01.853Z] INFO contract 0x481a276d14a6a74e1ec1f74b64c2af226ba7033c __callback tx sent, transaction hash: 0xfada229b6f9860e0717b3a098dd93aaef280852dbf75109c830b555c488e6c81
    {
    "myid": "0x72fdf59adf3ecc92244e3b173ce1657252ab5eb877c3569a393599d34dd2c848",
    "result": "",
    "proof": null,
    "proof_type": "0x00",
    "contract_address": "0x481a276d14a6a74e1ec1f74b64c2af226ba7033c",
    "gas_limit": 200000,
    "gas_price": null
}

Please help to solve this.


问:
How to use a dictionary to translate a start and end date to a period of time, eg jan-dec being a calender year
I have a data frame which has the start date and end date of a period of time as yyyy-mm and I want to have a new column which has the period of time - for example start date of 2019-01 and end date of 2019-12 would be Cal-19 in the new column, want to have this for years and quarters and then if it isn't either of those to do mm-yyyy - mm-yyyy as a string of the start to end dates.

I have tried to do this with a dictionary which had two inputs, start and end date, and would have the output for the period but this hasn't worked.

```<code>from Dictionary import Period

df["Start Period"]=pd.to_datetime(df["Start Date"], dayfirst=True).dt.to_period("M")

df["End Period"]=pd.to_datetime(df["End Date"], dayfirst=True).dt.to_period("M")

df["Period"] = df["Start Period"].map(Period) #This is the line which isn't working
</code>```

Where Period is a dictionary as follows:

```<code>Period = dict({("2019-01","2019-12"):"Cal-19",
            ("2020-01","2020-12"):"Cal-20",
            ("2021-01","2021-12"):"Cal-21",
            ("2019-01","2019-03"):"Q1-19",
            ("2019-04","2019-06"):"Q2-19",
            ("2019-07","2019-09"):"Q3-19",
            ("2019-10","2019-12"):"Q4-19",
            ("2020-01","2020-03"):"Q1-20",
            ("2020-04","2020-06"):"Q2-20",
            ("2020-07","2020-09"):"Q3-20"})
</code>```

Would expect to get the period but get an error within the dictionary itself but even when trying on a small subset of data I get NaN in the output column.

答:
I'm making the assumption that the date in Start Date and End Date is in string format. Otherwise the code below needs adjustment.
This should do the trick:

```<code>def get_period_form_start_and_end(x):
    yr_start = x['Start Date'][0:4]
    yr_end = x['End Date'][0:4]
    m_start = x['Start Date'][5:7]
    m_end = x['End Date'][5:7]

    if yr_start == yr_end:
        if m_start == "01" and m_end == "12":
            return "Cal-" + yr_start[2:4]
        elif m_start == "01" and m_end == "03":
            return "Q1-" + yr_start[2:4]
        elif m_start == "04" and m_end == "06":
            return "Q2-" + yr_start[2:4]
        elif m_start == "07" and m_end == "09":
            return "Q3-" + yr_start[2:4]
        elif m_start == "10" and m_end == "12":
            return "Q4-" + yr_start[2:4]
    else:
        return "{} - {}".format(x['Start Date'], x['End Date'])

df.loc[:, 'Period'] = df.loc[: , ['Start Date', 'End Date']].apply(lambda x: get_period_form_start_and_end(x), axis=1)
</code>```

So first we define a function which handles what type of period it is and then we apply this function to the concerning columns in the DataFrame.

Body:
I have a data frame which has the start date and end date of a period of time as yyyy-mm and I want to have a new column which has the period of time - for example start date of 2019-01 and end date of 2019-12 would be Cal-19 in the new column, want to have this for years and quarters and then if it isn't either of those to do mm-yyyy - mm-yyyy as a string of the start to end dates.

I have tried to do this with a dictionary which had two inputs, start and end date, and would have the output for the period but this hasn't worked.

from Dictionary import Period

df["Start Period"]=pd.to_datetime(df["Start Date"], dayfirst=True).dt.to_period("M")

df["End Period"]=pd.to_datetime(df["End Date"], dayfirst=True).dt.to_period("M")

df["Period"] = df["Start Period"].map(Period) #This is the line which isn't working

Where Period is a dictionary as follows:

Period = dict({("2019-01","2019-12"):"Cal-19",
            ("2020-01","2020-12"):"Cal-20",
            ("2021-01","2021-12"):"Cal-21",
            ("2019-01","2019-03"):"Q1-19",
            ("2019-04","2019-06"):"Q2-19",
            ("2019-07","2019-09"):"Q3-19",
            ("2019-10","2019-12"):"Q4-19",
            ("2020-01","2020-03"):"Q1-20",
            ("2020-04","2020-06"):"Q2-20",
            ("2020-07","2020-09"):"Q3-20"})

Would expect to get the period but get an error within the dictionary itself but even when trying on a small subset of data I get NaN in the output column.

Body:
I'm making the assumption that the date in Start Date and End Date is in string format. Otherwise the code below needs adjustment.
This should do the trick:

def get_period_form_start_and_end(x):
    yr_start = x['Start Date'][0:4]
    yr_end = x['End Date'][0:4]
    m_start = x['Start Date'][5:7]
    m_end = x['End Date'][5:7]

    if yr_start == yr_end:
        if m_start == "01" and m_end == "12":
            return "Cal-" + yr_start[2:4]
        elif m_start == "01" and m_end == "03":
            return "Q1-" + yr_start[2:4]
        elif m_start == "04" and m_end == "06":
            return "Q2-" + yr_start[2:4]
        elif m_start == "07" and m_end == "09":
            return "Q3-" + yr_start[2:4]
        elif m_start == "10" and m_end == "12":
            return "Q4-" + yr_start[2:4]
    else:
        return "{} - {}".format(x['Start Date'], x['End Date'])

df.loc[:, 'Period'] = df.loc[: , ['Start Date', 'End Date']].apply(lambda x: get_period_form_start_and_end(x), axis=1)

So first we define a function which handles what type of period it is and then we apply this function to the concerning columns in the DataFrame.


问:
How to write stored procedure in DB2
Please Help me in to write the stored procedure in Db2.

```<code>CREATE PROCEDURE assedt
BEGIN

 SELECT ASSETNUM FROM ASSET
END
</code>```

I tried the above code it is throwing an error like below:

Error report -
  DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=SELECT ASSETNUM;ROCEDURE p1
  BEGIN

;, DRIVER=4.12.55

答:
It seems you are missing a Colon after "P1". It should be "P1:"
Checkout this site for the sample example</p>

Title: How to write stored procedure in DB2

Body:
Please Help me in to write the stored procedure in Db2.

CREATE PROCEDURE assedt
BEGIN

 SELECT ASSETNUM FROM ASSET
END

I tried the above code it is throwing an error like below:

Error report -
  DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=SELECT ASSETNUM;ROCEDURE p1
  BEGIN

;, DRIVER=4.12.55


问:
Removing bullets from radio buttons when using Django forms
I'm trying to remove the bullets that are showing up beside the radio button when rendering a form.

My template is as follows:

```<code><form class="form-horizontal" enctype="multipart/form-data" method="POST" action="" class="uniForm">
<fieldset class="inlineLabels">
{% csrf_token %}
<br>
<h6>Library Type</h6>
{{ formtoaddmodel.type }}
</fieldset>
</form>
</code>```

The type field is a TypedChoiceField, which produced radio buttons for the choices, but the problem is it puts a bullet point before each radio button.

To remove the bullets, I read that you need to include . However, I'm not sure where to put this. When I do this in the CSS it affects everywhere in my site where I use bulleted lists.
Is there a way to do this in the template to over-ride the CSS, and if yes, how?

答:
I had the same problem with bullets showing up next to radio buttons for flask forms. Using the solution for bullets in flask from here, I was able to get rid of the bullets like this:</p>

```<code><p>
   Certification:
   {{form.certification(style="list-style:none")}}
</p>
</code>```

Body:
I'm trying to remove the bullets that are showing up beside the radio button when rendering a form.

My template is as follows:

<form class="form-horizontal" enctype="multipart/form-data" method="POST" action="" class="uniForm">
<fieldset class="inlineLabels">
{% csrf_token %}

Library Type

{{ formtoaddmodel.type }}
</fieldset>
</form>

The type field is a TypedChoiceField, which produced radio buttons for the choices, but the problem is it puts a bullet point before each radio button.

To remove the bullets, I read that you need to include . However, I'm not sure where to put this. When I do this in the CSS it affects everywhere in my site where I use bulleted lists.
Is there a way to do this in the template to over-ride the CSS, and if yes, how?

Body:
I had the same problem with bullets showing up next to radio buttons for flask forms. Using the solution for bullets in flask from here, I was able to get rid of the bullets like this:

<p>
   Certification:
   {{form.certification(style="list-style:none")}}
</p>


问:
Error with variable array size using the visual C++ compiler (Visual Studio 2010). How to circumvent this issue?
I am experiencing some troubles compiling a c++ file that worked well as a previous build under GCC.
The issue is, I am using vectors of variable array size:

```<code>unsigned int howmany;
std::vector<int>* array_adresses[howmany];
</code>```

I am currently using the Visual-Studio 2010 C++ compiler to built Matlab 64-bit Mex-Files.
Since VC++ won't allow me to use arrays whose size is unknown at compile time, I am receiving the following error messages:

error 2057: constant expression expected
error 2466:
error 2133: unknown size

Is there any way to build the 64 bit mex file using a GCC-compiler option or build it with a different 64-bit compiler under Matlab?

Thanks in advance!!

答:
Simply replace
int ptr[howmany];
with
vector<int> ptr(howmany);
to obtain also automatic deallocation at the end of the scope.

ContentLicense: CC BY-SA 2.5

Body:
I am experiencing some troubles compiling a c++ file that worked well as a previous build under GCC.
The issue is, I am using vectors of variable array size:

unsigned int howmany;
std::vector<int>* array_adresses[howmany];

I am currently using the Visual-Studio 2010 C++ compiler to built Matlab 64-bit Mex-Files.
Since VC++ won't allow me to use arrays whose size is unknown at compile time, I am receiving the following error messages:

error 2057: constant expression expected
error 2466:
error 2133: unknown size

Is there any way to build the 64 bit mex file using a GCC-compiler option or build it with a different 64-bit compiler under Matlab?

Thanks in advance!!