Compare commits
No commits in common. "master" and "data-downloads" have entirely different histories.
master
...
data-downl
63 changed files with 869 additions and 2669 deletions
4
.gitignore
vendored
4
.gitignore
vendored
|
@ -2,8 +2,4 @@
|
|||
*.old
|
||||
.hugo_build.lock
|
||||
*.json
|
||||
/data
|
||||
backend/api_logs.txt
|
||||
*__pycache__*
|
||||
.env
|
||||
poetry.lock
|
||||
|
|
428
LICENSE.md
428
LICENSE.md
|
@ -1,428 +0,0 @@
|
|||
Attribution-ShareAlike 4.0 International
|
||||
|
||||
=======================================================================
|
||||
|
||||
Creative Commons Corporation ("Creative Commons") is not a law firm and
|
||||
does not provide legal services or legal advice. Distribution of
|
||||
Creative Commons public licenses does not create a lawyer-client or
|
||||
other relationship. Creative Commons makes its licenses and related
|
||||
information available on an "as-is" basis. Creative Commons gives no
|
||||
warranties regarding its licenses, any material licensed under their
|
||||
terms and conditions, or any related information. Creative Commons
|
||||
disclaims all liability for damages resulting from their use to the
|
||||
fullest extent possible.
|
||||
|
||||
Using Creative Commons Public Licenses
|
||||
|
||||
Creative Commons public licenses provide a standard set of terms and
|
||||
conditions that creators and other rights holders may use to share
|
||||
original works of authorship and other material subject to copyright
|
||||
and certain other rights specified in the public license below. The
|
||||
following considerations are for informational purposes only, are not
|
||||
exhaustive, and do not form part of our licenses.
|
||||
|
||||
Considerations for licensors: Our public licenses are
|
||||
intended for use by those authorized to give the public
|
||||
permission to use material in ways otherwise restricted by
|
||||
copyright and certain other rights. Our licenses are
|
||||
irrevocable. Licensors should read and understand the terms
|
||||
and conditions of the license they choose before applying it.
|
||||
Licensors should also secure all rights necessary before
|
||||
applying our licenses so that the public can reuse the
|
||||
material as expected. Licensors should clearly mark any
|
||||
material not subject to the license. This includes other CC-
|
||||
licensed material, or material used under an exception or
|
||||
limitation to copyright. More considerations for licensors:
|
||||
wiki.creativecommons.org/Considerations_for_licensors
|
||||
|
||||
Considerations for the public: By using one of our public
|
||||
licenses, a licensor grants the public permission to use the
|
||||
licensed material under specified terms and conditions. If
|
||||
the licensor's permission is not necessary for any reason--for
|
||||
example, because of any applicable exception or limitation to
|
||||
copyright--then that use is not regulated by the license. Our
|
||||
licenses grant only permissions under copyright and certain
|
||||
other rights that a licensor has authority to grant. Use of
|
||||
the licensed material may still be restricted for other
|
||||
reasons, including because others have copyright or other
|
||||
rights in the material. A licensor may make special requests,
|
||||
such as asking that all changes be marked or described.
|
||||
Although not required by our licenses, you are encouraged to
|
||||
respect those requests where reasonable. More considerations
|
||||
for the public:
|
||||
wiki.creativecommons.org/Considerations_for_licensees
|
||||
|
||||
=======================================================================
|
||||
|
||||
Creative Commons Attribution-ShareAlike 4.0 International Public
|
||||
License
|
||||
|
||||
By exercising the Licensed Rights (defined below), You accept and agree
|
||||
to be bound by the terms and conditions of this Creative Commons
|
||||
Attribution-ShareAlike 4.0 International Public License ("Public
|
||||
License"). To the extent this Public License may be interpreted as a
|
||||
contract, You are granted the Licensed Rights in consideration of Your
|
||||
acceptance of these terms and conditions, and the Licensor grants You
|
||||
such rights in consideration of benefits the Licensor receives from
|
||||
making the Licensed Material available under these terms and
|
||||
conditions.
|
||||
|
||||
|
||||
Section 1 -- Definitions.
|
||||
|
||||
a. Adapted Material means material subject to Copyright and Similar
|
||||
Rights that is derived from or based upon the Licensed Material
|
||||
and in which the Licensed Material is translated, altered,
|
||||
arranged, transformed, or otherwise modified in a manner requiring
|
||||
permission under the Copyright and Similar Rights held by the
|
||||
Licensor. For purposes of this Public License, where the Licensed
|
||||
Material is a musical work, performance, or sound recording,
|
||||
Adapted Material is always produced where the Licensed Material is
|
||||
synched in timed relation with a moving image.
|
||||
|
||||
b. Adapter's License means the license You apply to Your Copyright
|
||||
and Similar Rights in Your contributions to Adapted Material in
|
||||
accordance with the terms and conditions of this Public License.
|
||||
|
||||
c. BY-SA Compatible License means a license listed at
|
||||
creativecommons.org/compatiblelicenses, approved by Creative
|
||||
Commons as essentially the equivalent of this Public License.
|
||||
|
||||
d. Copyright and Similar Rights means copyright and/or similar rights
|
||||
closely related to copyright including, without limitation,
|
||||
performance, broadcast, sound recording, and Sui Generis Database
|
||||
Rights, without regard to how the rights are labeled or
|
||||
categorized. For purposes of this Public License, the rights
|
||||
specified in Section 2(b)(1)-(2) are not Copyright and Similar
|
||||
Rights.
|
||||
|
||||
e. Effective Technological Measures means those measures that, in the
|
||||
absence of proper authority, may not be circumvented under laws
|
||||
fulfilling obligations under Article 11 of the WIPO Copyright
|
||||
Treaty adopted on December 20, 1996, and/or similar international
|
||||
agreements.
|
||||
|
||||
f. Exceptions and Limitations means fair use, fair dealing, and/or
|
||||
any other exception or limitation to Copyright and Similar Rights
|
||||
that applies to Your use of the Licensed Material.
|
||||
|
||||
g. License Elements means the license attributes listed in the name
|
||||
of a Creative Commons Public License. The License Elements of this
|
||||
Public License are Attribution and ShareAlike.
|
||||
|
||||
h. Licensed Material means the artistic or literary work, database,
|
||||
or other material to which the Licensor applied this Public
|
||||
License.
|
||||
|
||||
i. Licensed Rights means the rights granted to You subject to the
|
||||
terms and conditions of this Public License, which are limited to
|
||||
all Copyright and Similar Rights that apply to Your use of the
|
||||
Licensed Material and that the Licensor has authority to license.
|
||||
|
||||
j. Licensor means the individual(s) or entity(ies) granting rights
|
||||
under this Public License.
|
||||
|
||||
k. Share means to provide material to the public by any means or
|
||||
process that requires permission under the Licensed Rights, such
|
||||
as reproduction, public display, public performance, distribution,
|
||||
dissemination, communication, or importation, and to make material
|
||||
available to the public including in ways that members of the
|
||||
public may access the material from a place and at a time
|
||||
individually chosen by them.
|
||||
|
||||
l. Sui Generis Database Rights means rights other than copyright
|
||||
resulting from Directive 96/9/EC of the European Parliament and of
|
||||
the Council of 11 March 1996 on the legal protection of databases,
|
||||
as amended and/or succeeded, as well as other essentially
|
||||
equivalent rights anywhere in the world.
|
||||
|
||||
m. You means the individual or entity exercising the Licensed Rights
|
||||
under this Public License. Your has a corresponding meaning.
|
||||
|
||||
|
||||
Section 2 -- Scope.
|
||||
|
||||
a. License grant.
|
||||
|
||||
1. Subject to the terms and conditions of this Public License,
|
||||
the Licensor hereby grants You a worldwide, royalty-free,
|
||||
non-sublicensable, non-exclusive, irrevocable license to
|
||||
exercise the Licensed Rights in the Licensed Material to:
|
||||
|
||||
a. reproduce and Share the Licensed Material, in whole or
|
||||
in part; and
|
||||
|
||||
b. produce, reproduce, and Share Adapted Material.
|
||||
|
||||
2. Exceptions and Limitations. For the avoidance of doubt, where
|
||||
Exceptions and Limitations apply to Your use, this Public
|
||||
License does not apply, and You do not need to comply with
|
||||
its terms and conditions.
|
||||
|
||||
3. Term. The term of this Public License is specified in Section
|
||||
6(a).
|
||||
|
||||
4. Media and formats; technical modifications allowed. The
|
||||
Licensor authorizes You to exercise the Licensed Rights in
|
||||
all media and formats whether now known or hereafter created,
|
||||
and to make technical modifications necessary to do so. The
|
||||
Licensor waives and/or agrees not to assert any right or
|
||||
authority to forbid You from making technical modifications
|
||||
necessary to exercise the Licensed Rights, including
|
||||
technical modifications necessary to circumvent Effective
|
||||
Technological Measures. For purposes of this Public License,
|
||||
simply making modifications authorized by this Section 2(a)
|
||||
(4) never produces Adapted Material.
|
||||
|
||||
5. Downstream recipients.
|
||||
|
||||
a. Offer from the Licensor -- Licensed Material. Every
|
||||
recipient of the Licensed Material automatically
|
||||
receives an offer from the Licensor to exercise the
|
||||
Licensed Rights under the terms and conditions of this
|
||||
Public License.
|
||||
|
||||
b. Additional offer from the Licensor -- Adapted Material.
|
||||
Every recipient of Adapted Material from You
|
||||
automatically receives an offer from the Licensor to
|
||||
exercise the Licensed Rights in the Adapted Material
|
||||
under the conditions of the Adapter's License You apply.
|
||||
|
||||
c. No downstream restrictions. You may not offer or impose
|
||||
any additional or different terms or conditions on, or
|
||||
apply any Effective Technological Measures to, the
|
||||
Licensed Material if doing so restricts exercise of the
|
||||
Licensed Rights by any recipient of the Licensed
|
||||
Material.
|
||||
|
||||
6. No endorsement. Nothing in this Public License constitutes or
|
||||
may be construed as permission to assert or imply that You
|
||||
are, or that Your use of the Licensed Material is, connected
|
||||
with, or sponsored, endorsed, or granted official status by,
|
||||
the Licensor or others designated to receive attribution as
|
||||
provided in Section 3(a)(1)(A)(i).
|
||||
|
||||
b. Other rights.
|
||||
|
||||
1. Moral rights, such as the right of integrity, are not
|
||||
licensed under this Public License, nor are publicity,
|
||||
privacy, and/or other similar personality rights; however, to
|
||||
the extent possible, the Licensor waives and/or agrees not to
|
||||
assert any such rights held by the Licensor to the limited
|
||||
extent necessary to allow You to exercise the Licensed
|
||||
Rights, but not otherwise.
|
||||
|
||||
2. Patent and trademark rights are not licensed under this
|
||||
Public License.
|
||||
|
||||
3. To the extent possible, the Licensor waives any right to
|
||||
collect royalties from You for the exercise of the Licensed
|
||||
Rights, whether directly or through a collecting society
|
||||
under any voluntary or waivable statutory or compulsory
|
||||
licensing scheme. In all other cases the Licensor expressly
|
||||
reserves any right to collect such royalties.
|
||||
|
||||
|
||||
Section 3 -- License Conditions.
|
||||
|
||||
Your exercise of the Licensed Rights is expressly made subject to the
|
||||
following conditions.
|
||||
|
||||
a. Attribution.
|
||||
|
||||
1. If You Share the Licensed Material (including in modified
|
||||
form), You must:
|
||||
|
||||
a. retain the following if it is supplied by the Licensor
|
||||
with the Licensed Material:
|
||||
|
||||
i. identification of the creator(s) of the Licensed
|
||||
Material and any others designated to receive
|
||||
attribution, in any reasonable manner requested by
|
||||
the Licensor (including by pseudonym if
|
||||
designated);
|
||||
|
||||
ii. a copyright notice;
|
||||
|
||||
iii. a notice that refers to this Public License;
|
||||
|
||||
iv. a notice that refers to the disclaimer of
|
||||
warranties;
|
||||
|
||||
v. a URI or hyperlink to the Licensed Material to the
|
||||
extent reasonably practicable;
|
||||
|
||||
b. indicate if You modified the Licensed Material and
|
||||
retain an indication of any previous modifications; and
|
||||
|
||||
c. indicate the Licensed Material is licensed under this
|
||||
Public License, and include the text of, or the URI or
|
||||
hyperlink to, this Public License.
|
||||
|
||||
2. You may satisfy the conditions in Section 3(a)(1) in any
|
||||
reasonable manner based on the medium, means, and context in
|
||||
which You Share the Licensed Material. For example, it may be
|
||||
reasonable to satisfy the conditions by providing a URI or
|
||||
hyperlink to a resource that includes the required
|
||||
information.
|
||||
|
||||
3. If requested by the Licensor, You must remove any of the
|
||||
information required by Section 3(a)(1)(A) to the extent
|
||||
reasonably practicable.
|
||||
|
||||
b. ShareAlike.
|
||||
|
||||
In addition to the conditions in Section 3(a), if You Share
|
||||
Adapted Material You produce, the following conditions also apply.
|
||||
|
||||
1. The Adapter's License You apply must be a Creative Commons
|
||||
license with the same License Elements, this version or
|
||||
later, or a BY-SA Compatible License.
|
||||
|
||||
2. You must include the text of, or the URI or hyperlink to, the
|
||||
Adapter's License You apply. You may satisfy this condition
|
||||
in any reasonable manner based on the medium, means, and
|
||||
context in which You Share Adapted Material.
|
||||
|
||||
3. You may not offer or impose any additional or different terms
|
||||
or conditions on, or apply any Effective Technological
|
||||
Measures to, Adapted Material that restrict exercise of the
|
||||
rights granted under the Adapter's License You apply.
|
||||
|
||||
|
||||
Section 4 -- Sui Generis Database Rights.
|
||||
|
||||
Where the Licensed Rights include Sui Generis Database Rights that
|
||||
apply to Your use of the Licensed Material:
|
||||
|
||||
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
|
||||
to extract, reuse, reproduce, and Share all or a substantial
|
||||
portion of the contents of the database;
|
||||
|
||||
b. if You include all or a substantial portion of the database
|
||||
contents in a database in which You have Sui Generis Database
|
||||
Rights, then the database in which You have Sui Generis Database
|
||||
Rights (but not its individual contents) is Adapted Material,
|
||||
including for purposes of Section 3(b); and
|
||||
|
||||
c. You must comply with the conditions in Section 3(a) if You Share
|
||||
all or a substantial portion of the contents of the database.
|
||||
|
||||
For the avoidance of doubt, this Section 4 supplements and does not
|
||||
replace Your obligations under this Public License where the Licensed
|
||||
Rights include other Copyright and Similar Rights.
|
||||
|
||||
|
||||
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
|
||||
|
||||
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
|
||||
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
|
||||
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
|
||||
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
|
||||
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
|
||||
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
||||
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
|
||||
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
|
||||
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
|
||||
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
|
||||
|
||||
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
|
||||
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
|
||||
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
|
||||
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
|
||||
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
|
||||
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
|
||||
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
|
||||
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
|
||||
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
|
||||
|
||||
c. The disclaimer of warranties and limitation of liability provided
|
||||
above shall be interpreted in a manner that, to the extent
|
||||
possible, most closely approximates an absolute disclaimer and
|
||||
waiver of all liability.
|
||||
|
||||
|
||||
Section 6 -- Term and Termination.
|
||||
|
||||
a. This Public License applies for the term of the Copyright and
|
||||
Similar Rights licensed here. However, if You fail to comply with
|
||||
this Public License, then Your rights under this Public License
|
||||
terminate automatically.
|
||||
|
||||
b. Where Your right to use the Licensed Material has terminated under
|
||||
Section 6(a), it reinstates:
|
||||
|
||||
1. automatically as of the date the violation is cured, provided
|
||||
it is cured within 30 days of Your discovery of the
|
||||
violation; or
|
||||
|
||||
2. upon express reinstatement by the Licensor.
|
||||
|
||||
For the avoidance of doubt, this Section 6(b) does not affect any
|
||||
right the Licensor may have to seek remedies for Your violations
|
||||
of this Public License.
|
||||
|
||||
c. For the avoidance of doubt, the Licensor may also offer the
|
||||
Licensed Material under separate terms or conditions or stop
|
||||
distributing the Licensed Material at any time; however, doing so
|
||||
will not terminate this Public License.
|
||||
|
||||
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
|
||||
License.
|
||||
|
||||
|
||||
Section 7 -- Other Terms and Conditions.
|
||||
|
||||
a. The Licensor shall not be bound by any additional or different
|
||||
terms or conditions communicated by You unless expressly agreed.
|
||||
|
||||
b. Any arrangements, understandings, or agreements regarding the
|
||||
Licensed Material not stated herein are separate from and
|
||||
independent of the terms and conditions of this Public License.
|
||||
|
||||
|
||||
Section 8 -- Interpretation.
|
||||
|
||||
a. For the avoidance of doubt, this Public License does not, and
|
||||
shall not be interpreted to, reduce, limit, restrict, or impose
|
||||
conditions on any use of the Licensed Material that could lawfully
|
||||
be made without permission under this Public License.
|
||||
|
||||
b. To the extent possible, if any provision of this Public License is
|
||||
deemed unenforceable, it shall be automatically reformed to the
|
||||
minimum extent necessary to make it enforceable. If the provision
|
||||
cannot be reformed, it shall be severed from this Public License
|
||||
without affecting the enforceability of the remaining terms and
|
||||
conditions.
|
||||
|
||||
c. No term or condition of this Public License will be waived and no
|
||||
failure to comply consented to unless expressly agreed to by the
|
||||
Licensor.
|
||||
|
||||
d. Nothing in this Public License constitutes or may be interpreted
|
||||
as a limitation upon, or waiver of, any privileges and immunities
|
||||
that apply to the Licensor or You, including from the legal
|
||||
processes of any jurisdiction or authority.
|
||||
|
||||
|
||||
=======================================================================
|
||||
|
||||
Creative Commons is not a party to its public
|
||||
licenses. Notwithstanding, Creative Commons may elect to apply one of
|
||||
its public licenses to material it publishes and in those instances
|
||||
will be considered the “Licensor.” The text of the Creative Commons
|
||||
public licenses is dedicated to the public domain under the CC0 Public
|
||||
Domain Dedication. Except for the limited purpose of indicating that
|
||||
material is shared under a Creative Commons public license or as
|
||||
otherwise permitted by the Creative Commons policies published at
|
||||
creativecommons.org/policies, Creative Commons does not authorize the
|
||||
use of the trademark "Creative Commons" or any other trademark or logo
|
||||
of Creative Commons without its prior written consent including,
|
||||
without limitation, in connection with any unauthorized modifications
|
||||
to any of its public licenses or any other arrangements,
|
||||
understandings, or agreements concerning use of licensed material. For
|
||||
the avoidance of doubt, this paragraph does not form part of the
|
||||
public licenses.
|
||||
|
||||
Creative Commons may be contacted at creativecommons.org.
|
||||
|
|
@ -1,3 +1,3 @@
|
|||
# My personal website ([https://baseddata.io](https://baseddata.io))
|
||||
# My personal website ([https://bitlab21.com](https://bitlab21.com))
|
||||
|
||||
This site is made using [Hugo](https://gohugo.io/), a static website generator. The backend (which powers the api for getting data for the charts) is build in python and served using gunicorn.
|
||||
|
|
|
@ -1,134 +0,0 @@
|
|||
def parse_int(args):
|
||||
try:
|
||||
return int( args )
|
||||
except ValueError:
|
||||
print(f"{args} cannot be cast to int")
|
||||
raise
|
||||
|
||||
def mangrove_by_country_latest():
|
||||
return """
|
||||
select * from models_final.final__protected_mangroves_summary_stats_by_country_agg
|
||||
where year = '2020'
|
||||
order by cumulative_pixels_diff desc
|
||||
"""
|
||||
|
||||
def mangrove_country_timeseries(args):
|
||||
country_name = args["country_with_parent"]
|
||||
return f"""
|
||||
select year, total_n_pixels from models_final.final__protected_mangroves_summary_stats_by_country_agg
|
||||
where country_with_parent = '{country_name}'
|
||||
order by year
|
||||
"""
|
||||
|
||||
def bitcoin_business_growth_timeseries(args):
|
||||
days_ago = parse_int(args["days_ago"])
|
||||
country_name = args["country_name"]
|
||||
return f"""
|
||||
select * from models_final.final__bitcoin_business_growth_by_country
|
||||
where days_ago <= {days_ago} and country_name = '{country_name}'
|
||||
order by date
|
||||
"""
|
||||
|
||||
def bitcoin_business_growth_percent_diff_days_ago(args):
|
||||
days_ago = parse_int(args["days_ago"])
|
||||
return f"""
|
||||
with
|
||||
filtered_data as (
|
||||
select country_name, date, days_ago, cumulative_value
|
||||
from models_final.final__bitcoin_business_growth_by_country
|
||||
where days_ago <= {days_ago}
|
||||
order by country_name, days_ago desc
|
||||
),
|
||||
first_and_last_values as (
|
||||
select
|
||||
country_name,
|
||||
date,
|
||||
days_ago,
|
||||
cumulative_value,
|
||||
first_value(cumulative_value) over (
|
||||
partition by country_name order by days_ago desc
|
||||
) as first_value,
|
||||
first_value(date) over (
|
||||
partition by country_name order by days_ago desc
|
||||
) as first_date,
|
||||
first_value(cumulative_value) over (
|
||||
partition by country_name order by days_ago
|
||||
) as last_value,
|
||||
first_value(date) over (
|
||||
partition by country_name order by days_ago
|
||||
) as last_date
|
||||
from filtered_data
|
||||
),
|
||||
diff as (
|
||||
select
|
||||
country_name,
|
||||
date,
|
||||
first_date,
|
||||
last_date,
|
||||
days_ago,
|
||||
cumulative_value,
|
||||
first_value,
|
||||
last_value,
|
||||
last_value - first_value as difference,
|
||||
round(
|
||||
100 * models_final.safe_divide((last_value - first_value), first_value), 2
|
||||
) as percent_difference
|
||||
from first_and_last_values
|
||||
)
|
||||
select *
|
||||
from diff
|
||||
where days_ago = 1
|
||||
order by difference desc
|
||||
"""
|
||||
|
||||
def miner_rewards(args):
|
||||
days_ago = parse_int(args["days_ago"])
|
||||
return f"""
|
||||
with
|
||||
filtered_data as (
|
||||
select * from models_final.final__miner_rewards order by date desc limit {days_ago}
|
||||
)
|
||||
select *
|
||||
from filtered_data
|
||||
order by date asc
|
||||
|
||||
"""
|
||||
|
||||
def feerate_percentiles(args):
|
||||
days_ago = parse_int(args["days_ago"])
|
||||
return f"""
|
||||
with
|
||||
filtered_data as (
|
||||
select * from models_final.final__feerate_percentiles order by date desc limit {days_ago}
|
||||
)
|
||||
select *
|
||||
from filtered_data
|
||||
order by date asc
|
||||
|
||||
"""
|
||||
|
||||
def bitcoin_price_timeseries(args):
|
||||
days_ago = parse_int(args["days_ago"])
|
||||
return f"""
|
||||
with
|
||||
filtered_data as (
|
||||
select * from models_final.final__bitcoin_price order by date desc limit {days_ago}
|
||||
)
|
||||
select *
|
||||
from filtered_data
|
||||
order by date asc
|
||||
|
||||
"""
|
||||
|
||||
def bitcoin_hashrate(args):
|
||||
days_ago = parse_int(args["days_ago"])
|
||||
return f"""
|
||||
with
|
||||
filtered_data as (
|
||||
select * from models_final.final__hashrate order by date desc limit {days_ago}
|
||||
)
|
||||
select *
|
||||
from filtered_data
|
||||
order by date asc
|
||||
|
||||
"""
|
|
@ -1,37 +0,0 @@
|
|||
from psycopg2.extras import RealDictCursor
|
||||
from dotenv import load_dotenv
|
||||
import psycopg2, os
|
||||
|
||||
load_dotenv()
|
||||
|
||||
class PostgresHandler:
|
||||
def __init__(self):
|
||||
self.connection = self.connect_to_pg()
|
||||
self.cur = self.connection.cursor(cursor_factory=RealDictCursor)
|
||||
|
||||
def connect_to_pg(self):
|
||||
try:
|
||||
connection = psycopg2.connect(
|
||||
dbname=os.getenv('PGDATABASE'),
|
||||
host=os.getenv('PGHOST'),
|
||||
user=os.getenv('PGUSER'),
|
||||
password=os.getenv('PGPASSWORD'),
|
||||
port=os.getenv('PGPORT'),
|
||||
)
|
||||
except Exception as e:
|
||||
message=f"Connection to postgres database failed: {e}"
|
||||
raise Exception(message)
|
||||
print(f"Successfully connected to DB")
|
||||
return connection
|
||||
|
||||
def execute_query(self, query):
|
||||
try:
|
||||
self.cur.execute(query)
|
||||
results = self.cur.fetchall()
|
||||
self.connection.commit()
|
||||
self.connection.close()
|
||||
return results
|
||||
except Exception:
|
||||
print("Error executing query")
|
||||
raise
|
||||
|
|
@ -1,123 +0,0 @@
|
|||
from fastapi import APIRouter
|
||||
from api.postgres_handler import PostgresHandler
|
||||
import api.pipelines as pipelines
|
||||
import api.schemas as schemas
|
||||
from api.schemas import DataSerializer
|
||||
import json
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
def parse_args_to_dict(query):
|
||||
try:
|
||||
return json.loads(query)
|
||||
except json.JSONDecodeError as e:
|
||||
return {"error": f"Invalid JSON: {e}"}
|
||||
|
||||
@router.get("/mangrove_by_country_latest")
|
||||
async def mangrove_by_country_latest():
|
||||
pipeline = pipelines.mangrove_by_country_latest()
|
||||
handler = PostgresHandler()
|
||||
|
||||
schema = schemas.mangrove_by_country_latest_schema
|
||||
serializer = DataSerializer(schema)
|
||||
rawData = handler.execute_query(pipeline)
|
||||
serializedData = serializer.serialize_many(rawData)
|
||||
return serializedData
|
||||
|
||||
@router.get("/mangrove_country_timeseries")
|
||||
async def mangrove_country_timeseries(query: str):
|
||||
args = parse_args_to_dict(query)
|
||||
|
||||
pipeline = pipelines.mangrove_country_timeseries(args)
|
||||
handler = PostgresHandler()
|
||||
|
||||
schema = schemas.mangrove_country_timeseries_schema
|
||||
serializer = DataSerializer(schema)
|
||||
rawData = handler.execute_query(pipeline)
|
||||
serializedData = serializer.serialize_many(rawData)
|
||||
return serializedData
|
||||
|
||||
@router.get("/bitcoin_business_growth_timeseries")
|
||||
async def bitcoin_business_growth_timeseries(query: str):
|
||||
args = parse_args_to_dict(query)
|
||||
|
||||
pipeline = pipelines.bitcoin_business_growth_timeseries(args)
|
||||
handler = PostgresHandler()
|
||||
|
||||
schema = schemas.bitcoin_business_growth_timeseries_schema
|
||||
serializer = DataSerializer(schema)
|
||||
|
||||
rawData = handler.execute_query(pipeline)
|
||||
serializedData = serializer.serialize_many(rawData)
|
||||
|
||||
return serializedData
|
||||
|
||||
@router.get("/bitcoin_business_growth_percent_diff")
|
||||
async def bitcoin_business_growth_percent_diff(query: str):
|
||||
args = parse_args_to_dict(query)
|
||||
|
||||
pipeline = pipelines.bitcoin_business_growth_percent_diff_days_ago(args)
|
||||
handler = PostgresHandler()
|
||||
|
||||
schema = schemas.bitcoin_business_growth_percent_diff_schema
|
||||
serializer = DataSerializer(schema)
|
||||
|
||||
rawData = handler.execute_query(pipeline)
|
||||
serializedData = serializer.serialize_many(rawData)
|
||||
return serializedData
|
||||
|
||||
@router.get("/miner_rewards")
|
||||
async def miner_rewards(query: str):
|
||||
args = parse_args_to_dict(query)
|
||||
|
||||
pipeline = pipelines.miner_rewards(args)
|
||||
handler = PostgresHandler()
|
||||
|
||||
schema = schemas.miner_rewards_schema
|
||||
serializer = DataSerializer(schema)
|
||||
|
||||
rawData = handler.execute_query(pipeline)
|
||||
serializedData = serializer.serialize_many(rawData)
|
||||
return serializedData
|
||||
|
||||
@router.get("/feerate_percentiles")
|
||||
async def feerate_percentiles(query: str):
|
||||
args = parse_args_to_dict(query)
|
||||
|
||||
pipeline = pipelines.feerate_percentiles(args)
|
||||
handler = PostgresHandler()
|
||||
|
||||
schema = schemas.feerate_percentiles_schema
|
||||
serializer = DataSerializer(schema)
|
||||
|
||||
rawData = handler.execute_query(pipeline)
|
||||
serializedData = serializer.serialize_many(rawData)
|
||||
return serializedData
|
||||
|
||||
@router.get("/bitcoin_price_timeseries")
|
||||
async def bitcoin_price_timeseries(query: str):
|
||||
args = parse_args_to_dict(query)
|
||||
|
||||
pipeline = pipelines.bitcoin_price_timeseries(args)
|
||||
handler = PostgresHandler()
|
||||
|
||||
schema = schemas.bitcoin_price_timeseries_schema
|
||||
serializer = DataSerializer(schema)
|
||||
|
||||
rawData = handler.execute_query(pipeline)
|
||||
serializedData = serializer.serialize_many(rawData)
|
||||
return serializedData
|
||||
|
||||
@router.get("/bitcoin_hashrate")
|
||||
async def bitcoin_hashrate(query: str):
|
||||
args = parse_args_to_dict(query)
|
||||
|
||||
pipeline = pipelines.bitcoin_hashrate(args)
|
||||
handler = PostgresHandler()
|
||||
|
||||
schema = schemas.bitcoin_hashrate_schema
|
||||
serializer = DataSerializer(schema)
|
||||
|
||||
rawData = handler.execute_query(pipeline)
|
||||
serializedData = serializer.serialize_many(rawData)
|
||||
return serializedData
|
|
@ -1,89 +0,0 @@
|
|||
def mangrove_by_country_latest_schema(data):
|
||||
return {
|
||||
"country_with_parent": str(data["country_with_parent"]),
|
||||
"original_pixels": int(data["original_pixels"]),
|
||||
"total_n_pixels": int(data["total_n_pixels"]),
|
||||
"cumulative_pixels_diff": int(data["cumulative_pixels_diff"]),
|
||||
"cumulative_pct_diff": float(data["cumulative_pct_diff"]),
|
||||
}
|
||||
|
||||
|
||||
def mangrove_country_timeseries_schema(data):
|
||||
return {
|
||||
"year": str(data["year"]),
|
||||
"total_n_pixels": int(data["total_n_pixels"]),
|
||||
}
|
||||
|
||||
|
||||
def mangrove_by_country_agg_schema(data):
|
||||
return {
|
||||
"country_with_parent": str(data["country_with_parent"]),
|
||||
"year": int(data["year"]),
|
||||
"total_pixels": int(data["total_pixels"]),
|
||||
}
|
||||
|
||||
|
||||
def bitcoin_business_growth_percent_diff_schema(data):
|
||||
return {
|
||||
"country_name": str(data["country_name"]),
|
||||
"date_range": str(f'{data["first_date"]} to {data["last_date"]}'),
|
||||
"first_value": int(data["first_value"]),
|
||||
"last_value": int(data["last_value"]),
|
||||
"difference": int(data["difference"]),
|
||||
"percent_difference": str(data["percent_difference"]),
|
||||
}
|
||||
|
||||
|
||||
def bitcoin_business_growth_timeseries_schema(data):
|
||||
return {
|
||||
"country_name": str(data["country_name"]),
|
||||
"date": data["date"],
|
||||
"cumulative_value": int(data["cumulative_value"]),
|
||||
}
|
||||
|
||||
|
||||
def miner_rewards_schema(data):
|
||||
return {
|
||||
"date": data["date"],
|
||||
"block_subsidy": data["block_subsidy"],
|
||||
"total_reward_usd": data["total_reward_usd"],
|
||||
"totalfee_usd": data["totalfee_usd"],
|
||||
"subsidy_usd": data["subsidy_usd"],
|
||||
}
|
||||
|
||||
def feerate_percentiles_schema(data):
|
||||
return {
|
||||
"date": data["date"],
|
||||
"feerate_10th": data["feerate_10th"],
|
||||
"feerate_25th": data["feerate_25th"],
|
||||
"feerate_50th": data["feerate_50th"],
|
||||
"feerate_75th": data["feerate_75th"],
|
||||
"feerate_90th": data["feerate_90th"],
|
||||
"maxfeerate": data["maxfeerate"],
|
||||
"minfeerate": data["minfeerate"],
|
||||
}
|
||||
|
||||
def bitcoin_price_timeseries_schema(data):
|
||||
return {
|
||||
"date": data["date"],
|
||||
"price": data["price"],
|
||||
}
|
||||
|
||||
def bitcoin_hashrate_schema(data):
|
||||
return {
|
||||
"date": data["date"],
|
||||
"hashrate": data["hashrate"],
|
||||
"difficulty": data["difficulty"],
|
||||
"hashrate28": data["hashrate28"],
|
||||
"difficulty28": data["difficulty28"],
|
||||
}
|
||||
|
||||
class DataSerializer:
|
||||
def __init__(self, schema_func):
|
||||
self.schema_func = schema_func
|
||||
|
||||
def serialize_one(self, data) -> dict:
|
||||
return self.schema_func(dict(data))
|
||||
|
||||
def serialize_many(self, data_list) -> list:
|
||||
return [self.serialize_one(data) for data in data_list]
|
63
backend/app.py
Normal file
63
backend/app.py
Normal file
|
@ -0,0 +1,63 @@
|
|||
from flask import Flask, jsonify, request, json, Response, send_from_directory, abort
|
||||
from flask_cors import CORS
|
||||
import orjson, os
|
||||
|
||||
app = Flask(__name__)
|
||||
CORS(app)
|
||||
|
||||
FILES_DIRECTORY = '../data/'
|
||||
|
||||
@app.route('/bitcoin_business_growth_by_country', methods=['GET'])
|
||||
def business_growth():
|
||||
# Parse args from request
|
||||
latest_date = request.args.get('latest_date')
|
||||
country_names = request.args.get('countries') # change this line
|
||||
cumulative_period_type = request.args.get('cumulative_period_type')
|
||||
|
||||
# Open json locally
|
||||
with open('../data/final__bitcoin_business_growth_by_country.json', 'rb') as f:
|
||||
data = orjson.loads(f.read())
|
||||
|
||||
# Filter based on args
|
||||
if latest_date:
|
||||
latest_date_bool = latest_date == 'true'
|
||||
filtered_data = [item for item in data if item['latest_date'] == latest_date_bool]
|
||||
else:
|
||||
filtered_data = data
|
||||
|
||||
if country_names:
|
||||
countries = [name.strip() for name in country_names.split(",")]
|
||||
filtered_data = [item for item in filtered_data if item['country_name'] in countries]
|
||||
|
||||
if cumulative_period_type:
|
||||
filtered_data = [item for item in filtered_data if item['cumulative_period_type'] == cumulative_period_type]
|
||||
|
||||
# Sort by date
|
||||
sorted_data = sorted(filtered_data, key=lambda x: x['date'], reverse=True)
|
||||
|
||||
# Return json
|
||||
return Response(json.dumps(sorted_data), mimetype='application/json')
|
||||
|
||||
@app.route('/get_json/<filename>', methods=['GET'])
|
||||
def get_json(filename):
|
||||
file_path = os.path.join(FILES_DIRECTORY, filename)
|
||||
if not os.path.isfile(file_path):
|
||||
abort(404)
|
||||
|
||||
with open(file_path, 'r') as file:
|
||||
data = json.load(file)
|
||||
|
||||
return jsonify(data)
|
||||
|
||||
@app.route('/download/<filename>', methods=['GET'])
|
||||
def download_file(filename):
|
||||
try:
|
||||
return send_from_directory(FILES_DIRECTORY, filename, as_attachment=True)
|
||||
except FileNotFoundError:
|
||||
abort(404)
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(debug=True)
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run()
|
|
@ -1,13 +0,0 @@
|
|||
[Unit]
|
||||
Description=Uvicorn instance to serve baseddata.io
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
User=admin
|
||||
Group=www-data
|
||||
WorkingDirectory=/var/www/baseddata.io/backend
|
||||
Environment="PATH=/var/www/baseddata.io/.venv/bin"
|
||||
ExecStart=/var/www/baseddata.io/.venv/bin/uvicorn --workers 4 --uds /var/sockets/baseddata.sock main:app
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
13
backend/bitlab21.service
Normal file
13
backend/bitlab21.service
Normal file
|
@ -0,0 +1,13 @@
|
|||
[Unit]
|
||||
Description=Gunicorn instance to serve bitlab21.com
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
User=admin
|
||||
Group=www-data
|
||||
WorkingDirectory=/var/www/bitlab21.com/backend
|
||||
Environment="PATH=/var/www/bitlab21.com/.venv/bin"
|
||||
ExecStart=/var/www/bitlab21.com/.venv/bin/gunicorn --workers 4 --bind unix:bitlab21.sock -m 007 app:app
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
|
@ -1,21 +0,0 @@
|
|||
from fastapi import FastAPI
|
||||
from api.route import router
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
app.include_router(router)
|
||||
|
||||
origins = [
|
||||
"https://baseddata.io",
|
||||
"https://api.baseddata.io",
|
||||
]
|
||||
|
||||
# Add the CORS middleware to the app
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=origins,
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
|
@ -4,11 +4,11 @@ toc: False
|
|||
|
||||
# Grounded Insights from Open Data
|
||||
|
||||
**This site is currently under construction**.
|
||||
This site is currently under construction. The direction I intend for this site to take is as a place to publish analytical insights derived from open data. I have a page called [Data Lab](/data-lab) where I publish interactive analytical dashboards, a blog to publish tutorials and thoughts on various related topics, and a [data downloads](/data-download) page for data access.
|
||||
|
||||
I intend for this to be a place to publish my personal work to share with others. I have a page called [Data Lab](/data-lab) where I publish interactive analytical dashboards based on open data, a blog to publish tutorials and thoughts I have on various topics, and a [data downloads](/data-downloads) page for data access.
|
||||
I'm interested in a broad set of topics such as Linux, analytics and data engineering, GIS and bitcoin. So expect to see content related to these topics published on this site.
|
||||
|
||||
I'm interested in a broad set of topics such as Linux, analytics and data engineering, Geographic Information Systems (GIS) and bitcoin. So expect to see content related to these topics published on this site.
|
||||
I strongly believe in the philosophy of [Free Software](https://www.gnu.org/philosophy/free-sw.html) and [Open Data](https://en.wikipedia.org/wiki/Open_data). Therefore, all material on this site is released into the public domain unless otherwise specified. For more information, see [here](/license).
|
||||
|
||||
### Explore Based Data
|
||||
|
||||
|
|
|
@ -9,13 +9,16 @@ toc: false
|
|||
|
||||
My name is Sam Chance, and this is my personal site.
|
||||
|
||||
I'm a professional Analytics Engineer with a passion for working with data. I built this website as a place to publish my personal work.
|
||||
I'm an independent Analytics Engineer with a passion for working with data. I built this website as a place to publish my personal work.
|
||||
|
||||
If you wish to work with me, then please email me on *contact@sjplab.com*.
|
||||
|
||||
More about my professional life [here](/cv).
|
||||
|
||||
|
||||
### Shortcuts to some of my work:
|
||||
|
||||
- [Data Lab](/data-lab) A selection of charts and metrics obtained from public data
|
||||
- [Based Data Lab](/data-lab) A selection of charts and metrics obtained from public data
|
||||
|
||||
- [Map Printing Service](https://semitamaps.com) A free map printing service based on Openstreetmaps
|
||||
|
||||
|
@ -25,7 +28,7 @@ If you wish to work with me, then please email me on *contact@sjplab.com*.
|
|||
|
||||
### Software I use:
|
||||
|
||||
- [**Neovim**](https://neovim.io/) for text editing (my neovim config is part of my [nixos](https://git.bitlab21.com/sam/nixos/src/branch/master/home/common/core/nixvim) configuration)
|
||||
- [**Neovim**](https://neovim.io/) for text editing (my neovim config is part of my [nixos](https://git.bitlab21.com/sam/nixos) configuration)
|
||||
|
||||
- I use **Linux** on all my machines
|
||||
|
||||
|
|
|
@ -51,7 +51,7 @@ Next we can run the following command to download the rasters. This will take so
|
|||
aws s3 cp s3://raster/SRTM_GL1/ . --recursive --endpoint-url https://opentopography.s3.sdsc.edu --no-sign-request
|
||||
{{</ highlight >}}
|
||||
|
||||
If you'd prefer to download specific rasters or rasters for a region instead of downloading them all, you can select regions for download from the OpenTopography [website](https://portal.opentopography.org/raster?opentopoID=OTSRTM.082015.4326.1) using the interactive map.
|
||||
If you'd prefer to download specific rasters or rasters for a region instead, you can checkout this [website](https://dwtkns.com/srtm30m/).
|
||||
|
||||
## Using raster2pgsql to import raster tiles into PostGIS
|
||||
Now we have the data downloaded on our system, we can import it into our database.
|
||||
|
@ -98,9 +98,9 @@ So we have just over 12 million 128x128 tiles in the database.
|
|||
|
||||
## Raster Clipping
|
||||
|
||||
Now we have global SRTM data loaded in our local database, we can extract the tiles we want for further analysis.
|
||||
Now we have global SRTM data loaded in our local database, we can extract any of the tiles for further analysis and access this using any application.
|
||||
|
||||
Here we'll create a digital elevation raster for Singapore to demonstrate using the following PostGIS commands: `st_clip`, `st_intersects` and `st_union`, then import this into QGIS to style and visualise the results.
|
||||
Here I'll demonstrate using the following PostGIS commands: `st_clip`, `st_intersects` and `st_union` to create a digital elevation table for singapore and access this from from within QGIS.
|
||||
|
||||
I already have countries vector data in my Postgres database that I extracted from OpenStreetMaps. You can download a pg_dump of this [here](/data/countries.sql) to insert into your database. Alternatively, I have a post [here](/blogs/import-osm-countries-data) that explains the process to do this manually.
|
||||
|
||||
|
@ -224,6 +224,3 @@ This DEM raster of Singapore is available for download from the downloads page [
|
|||
|
||||
#### Citations
|
||||
NASA Shuttle Radar Topography Mission (SRTM)(2013). Shuttle Radar Topography Mission (SRTM) Global. Distributed by OpenTopography. https://doi.org/10.5069/G9445JDF. Accessed: 2024-08-06
|
||||
|
||||
#### Attribution and License
|
||||
© [OpenStreetMap](https://www.openstreetmap.org/copyright)
|
||||
|
|
|
@ -1,43 +1,28 @@
|
|||
## Sam Chance | Analytics Engineer | MSc Marine Biology | United Kingdom
|
||||
***contact@sjplab.com***
|
||||
# Sam Chance
|
||||
## Analytics Engineer
|
||||
|
||||
4 years experience working in the tech industry as a Data Analyst & Engineer for a geocoding firm in London. Strong educational background with two STEM degrees. Excellent communication skills with competence at articulating complex ideas to non-technical people.
|
||||
|
||||
## Experience
|
||||
### Growth Analyst / Analytics Engineer | What3Words | May 2020 to Apr 2024 (4 years)
|
||||
*Engineered data pipelines and managed geospatial data for geocoding company that serves 200k daily users*
|
||||
|
||||
- Engineered & implemented alerting system from scratch to detect anomalous behaviour in partner API usage, resulting in 30+ actionable alerts per month & facilitating service improvements to paying customers
|
||||
- Developed ETL orchestration platform using Airflow & DBT to automate 40+ DAGS & 140+ data models
|
||||
- Lead GIS project to map and classify company spatial data using OpenStreetMaps
|
||||
- Migrated data analytics from Firebase to Mixpanel, enhancing self-serviceability of analytics & reducing work-load of Data Team by 60% from ad-hoc requests
|
||||
- Architected 80% of company KPI dashboard used by external stakeholders & potential investors
|
||||
- Designed & implemented QA tool for Product Team to monitor potential issues in new app releases
|
||||
- Promoted to Analytics Engineer after starting as a Growth Analyst
|
||||
Analytics Engineer with over 4 years experience in designing and implementing data models, pipelines, and analytics solutions. Proficient in SQL, data warehousing, dbt and building dashboards for company metrics.
|
||||
|
||||
## Skills
|
||||
- **Data Warehousing**: BigQuery | Postgres
|
||||
- **Data Analysis & Modelling**: Python (pandas, numpy) & R (dplyr) | DBT | SQL | Data Pipeline Design & Development
|
||||
- **Data Visualization**: matplotlib | ggplot | Looker Studio | Apache ECharts
|
||||
- **Programming Languages**: *proficient*: SQL, Python, Bash, R | *learning*: JavaScript
|
||||
- **Workflow Orchestration**: Apache Airflow | Prefect
|
||||
- **Sysadmin**: Linux | Networking | SSH | Reverse Proxy (Nginx) | API Management | Containerization (Docker, LXC) | Nixos
|
||||
- **Geographic Information Systems**: ArcGIS | QGIS | PostGIS | GDAL | OpenStreetMaps
|
||||
- **Code Collaboration & Version Control**: Git, Github, Self Hosted Gitea
|
||||
- **CLI wizard**: Scripting (Bash, Python) | GNU Coreutils | Neovim
|
||||
- **Web Development**: Hugo | JavaScript/HTML/CSS | Apache ECharts
|
||||
- **Personal**: Full UK Driving License | Flexible Working | Remote Working | Autonomous Worker
|
||||
- SQL
|
||||
- Python
|
||||
- Scripting/Programming
|
||||
- Data Warehousing
|
||||
- Data Modelling
|
||||
- DBT
|
||||
- Data and Statistical Analysis
|
||||
- System Administration
|
||||
|
||||
## Work Experience
|
||||
### Growth Analyst
|
||||
What3Words - May 2020 to Feb 2022
|
||||
|
||||
### Analytics Engineer
|
||||
What3Words - Feb 2022 to Apr 2024
|
||||
|
||||
## Education
|
||||
### MSc Marine Biology | Bangor University | 1 year
|
||||
*Advanced theoretical & practical training with focus on GIS skills*
|
||||
### MSc Marine Biology
|
||||
Bangor University - 2017 to 2018
|
||||
|
||||
- **Thesis**: "Quantifying the Effectiveness of Indonesia's Protected Areas at Preventing Mangrove Deforestation"
|
||||
* A GIS project that involved statistical modelling of satellite data using ArcGIS and R
|
||||
|
||||
### BSc Marine Biology & Zoology | Bangor University | 3 years
|
||||
|
||||
## Personal Websites
|
||||
- **https://semitamaps.com**: A free high-quality map printing service using self-hosted vector tiles generated from OpenStreetMaps and visualised with Maplibre.
|
||||
- **https://baseddata.io**: A site where I publish analytical content based on open data. Still a work in progress.
|
||||
- **https://git.bitlab21.com**: Self-hosted Gitea instance where I host my code.
|
||||
### BSc Marine Biology & Zoology
|
||||
Bangor University - 2008 to 2011
|
||||
|
|
|
@ -11,10 +11,7 @@ tags: ["QGIS", "SRTM", "DEM", "Raster", "download"]
|
|||
{{< figure src="/pics/blog/batch-import-postgis-rasters/singapore-final.webp" width="300">}}
|
||||
Download the Digital Elevation Model featured in [this](/blog/batch-import-postgis-rasters/) blog.
|
||||
|
||||
{{< download-data src="/singapore-srtm-dem.tif" name="singapore-srtm-dem.tif" >}} (9.6MB)
|
||||
{{< download-data src="http://localhost:5000/download/singapore-srtm-dem.tif" name="singapore-srtm-dem.tif" >}}
|
||||
|
||||
#### Citations
|
||||
NASA Shuttle Radar Topography Mission (SRTM)(2013). Shuttle Radar Topography Mission (SRTM) Global. Distributed by OpenTopography. https://doi.org/10.5069/G9445JDF. Accessed: 2024-08-06
|
||||
|
||||
#### Attribution and License
|
||||
© [OpenStreetMap](https://www.openstreetmap.org/copyright)
|
||||
|
|
|
@ -1,16 +0,0 @@
|
|||
---
|
||||
title: "Bitcoin Price USD"
|
||||
date: 2023-07-15T01:00:57+01:00
|
||||
author:
|
||||
name: "Sam Chance"
|
||||
header_image: "/pics/charts/price.webp"
|
||||
summary: "Daily bitcoin price. Data is obtained from CoinGecko using their public API."
|
||||
tags: ["Bitcoin", "Stats"]
|
||||
jsScripts: [ "/js/lib/chart-params.js", "/js/lib/helper-functions.js", "/js/lib/echarts.min.js", "/js/lib/sorttable.js", "/js/content/bitcoin-price.js"]
|
||||
---
|
||||
|
||||
Daily bitcoin price. Data is obtained from [CoinGecko](https://www.coingecko.com/) using their
|
||||
public API.
|
||||
|
||||
{{< dropdown_filter id="days_ago_dropdown_filter" >}}
|
||||
{{< chart id = "bitcoin-price-chart" >}}
|
|
@ -5,12 +5,12 @@ author:
|
|||
name: "Sam Chance"
|
||||
header_image: "/pics/charts/feerate-percentile.webp"
|
||||
summary: "Bar chart showing historical median daily feerate percentiles for the Bitcoin protocol."
|
||||
chart: "/js/feerate_percentile.js"
|
||||
tags: ["Bitcoin", "Stats"]
|
||||
jsScripts: [ "/js/lib/chart-params.js", "/js/lib/helper-functions.js", "/js/lib/echarts.min.js", "/js/lib/sorttable.js", "/js/content/feerate-percentile.js"]
|
||||
---
|
||||
|
||||
This chart shows historical median daily feerate percentiles for the Bitcoin
|
||||
protocol.
|
||||
{{< dropdown_filter id="days_ago_dropdown_filter" >}}
|
||||
protocol. The data represents a daily aggregation of all blocks. This data was
|
||||
extracted from the blockchain using the `bitcoin-cli getblockstats` command.
|
||||
|
||||
{{< chart id="feerate-percentiles-chart" >}}
|
||||
{{< chart src="/js/feerate-percentile.js" >}}
|
|
@ -1,23 +0,0 @@
|
|||
---
|
||||
title: "Global Bitcoin Business Growth"
|
||||
date: 2024-04-04T09:16:33+01:00
|
||||
author:
|
||||
name: "Sam Chance"
|
||||
header_image: "/pics/charts/growth.webp"
|
||||
summary: "This analysis uses OpenStreetMaps data to chart the yearly growth of bitcoin-accepting businesses worldwide."
|
||||
tags: ["Bitcoin", "Stats", "OpenStreetMaps"]
|
||||
jsScripts: [ "/js/lib/chart-params.js", "/js/lib/helper-functions.js", "/js/lib/echarts.min.js", "/js/lib/sorttable.js", "/js/content/global-bitcoin-business-growth.js"]
|
||||
---
|
||||
|
||||
The table below illustrates growth of businesses worldwide that accept bitcoin as payment for products or services. The accompanying chart displays the cumulative number of bitcoin-accepting businesses for the countries selected in the table. The data is sourced from OpenStreetMaps.
|
||||
|
||||
You can select the period of interest from the drop-down, which updates the values in the table. The table shows the ***Previous*** value, which was the number of businesses `n days ago` specified in the drop-down. The ***Current*** value is the number of businesses as of the latest update. The table also shows the ***Absolute Difference***, and the ***Percent Difference*** between these periods.
|
||||
|
||||
<br/>
|
||||
{{< dropdown_filter id="days_ago_dropdown_filter" >}}
|
||||
|
||||
{{< table id="bitcoin-business-growth-table" >}}
|
||||
{{< chart id="bitcoin-business-growth-chart" >}}
|
||||
|
||||
#### Attribution
|
||||
Data obtained from © [OpenStreetMap](https://www.openstreetmap.org/copyright)
|
20
content/data-lab/global-business-growth.md
Normal file
20
content/data-lab/global-business-growth.md
Normal file
|
@ -0,0 +1,20 @@
|
|||
---
|
||||
title: "Global Bitcoin Business Growth"
|
||||
date: 2024-04-04T09:16:33+01:00
|
||||
author:
|
||||
name: "Sam Chance"
|
||||
header_image: "/pics/charts/growth.webp"
|
||||
summary: "This analysis uses OpenStreetMaps data to chart the yearly growth of bitcoin-accepting businesses worldwide."
|
||||
tags: ["Bitcoin", "Stats", "OpenStreetMaps"]
|
||||
---
|
||||
|
||||
The table below illustrates growth of businesses worldwide that accept bitcoin as payment for products or services. The accompanying chart displays the yearly cumulative number of bitcoin-accepting businesses for the countries selected in the table. The data is sourced from OpenStreetMaps and is updated approximately every 2 hours.
|
||||
|
||||
You can select the growth period of interest from the drop-down, which updates the values in the table. The table shows the ***Previous*** value, which was the number of businesses *n* days ago specified in the drop-down. The ***Current*** value is the number of businesses as of the latest update. The table also shows the ***Absolute Difference***, and the ***Percent Difference*** between this period.
|
||||
|
||||
The chart always reflects the countries selected in the table. There is a zoom feature on the chart to focus in on a period of interest.
|
||||
|
||||
<br/>
|
||||
Select growth period: {{< dropdown-filter id=cumulative_period_type select="365 day,28 day,7 day,1 day" >}}
|
||||
{{< chart src="/js/bitcoin-business-growth-chart.js" >}}
|
||||
{{< table src="/js/bitcoin-business-growth-table.js" >}}
|
|
@ -6,10 +6,8 @@ author:
|
|||
header_image: "/pics/charts/hashrate.webp"
|
||||
summary: "Timeseries chart showing the Bitcoin network hashrate and difficulty."
|
||||
tags: ["Bitcoin", "Stats", "Hashrate"]
|
||||
jsScripts: [ "/js/lib/chart-params.js", "/js/lib/helper-functions.js", "/js/lib/echarts.min.js", "/js/lib/sorttable.js", "/js/content/hashrate.js"]
|
||||
---
|
||||
|
||||
This chart shows the estimated hashrate and difficulty of the Bitcoin network, accompanied by the 28-day moving average. This information is extracted from a bitcoin node using the `bitcoin-cli getnetworkhashps` command.
|
||||
The estimated hashrate and difficulty of the Bitcoin network, accompanied by the 28-day moving average.
|
||||
|
||||
{{< dropdown_filter id="days_ago_dropdown_filter" >}}
|
||||
{{< chart id = "hashrate-chart" >}}
|
||||
{{< chart src="/js/hashrate.js" >}}
|
||||
|
|
|
@ -7,11 +7,8 @@ summary: "Miner rewards"
|
|||
header_image: "/pics/charts/rewards.webp"
|
||||
draft: false
|
||||
tags: ["Bitcoin", "Stats"]
|
||||
jsScripts: [ "/js/lib/chart-params.js", "/js/lib/helper-functions.js", "/js/lib/echarts.min.js", "/js/lib/sorttable.js", "/js/content/miner-rewards.js"]
|
||||
---
|
||||
|
||||
The following chart shows daily miner revenue in USD for the period selected in the dropdown. This information is based on the sum of bitcoin mined each day (i.e. the block-subsidy) plus the transaction fees. Price data is obtained from [CoinGecko](https://www.coingecko.com/).
|
||||
Total daily aggregated miner income denominated in USD for that day.
|
||||
|
||||
{{< dropdown_filter id="days_ago_dropdown_filter" >}}
|
||||
|
||||
{{< chart id="miner-rewards-chart" >}}
|
||||
{{< chart src="/js/miner-rewards.js" >}}
|
||||
|
|
16
content/data-lab/price.md
Normal file
16
content/data-lab/price.md
Normal file
|
@ -0,0 +1,16 @@
|
|||
---
|
||||
title: "Bitcoin Price USD"
|
||||
date: 2023-07-15T01:00:57+01:00
|
||||
author:
|
||||
name: "Sam Chance"
|
||||
header_image: "/pics/charts/price.webp"
|
||||
summary: "Daily bitcoin price. Data is obtained from CoinGecko using their public API."
|
||||
tags: ["Bitcoin", "Stats"]
|
||||
---
|
||||
|
||||
Daily bitcoin price. Data is obtained from CoinGecko using their
|
||||
public API.
|
||||
|
||||
{{< bitcoin-price >}}
|
||||
|
||||
{{< chart src="/js/bitcoin-price.js" >}}
|
|
@ -1,16 +0,0 @@
|
|||
---
|
||||
title: "Global Protected Mangroves"
|
||||
date: 2024-09-04T16:00:57+01:00
|
||||
author:
|
||||
name: "Sam Chance"
|
||||
header_image: "/pics/charts/price.webp"
|
||||
summary: "Daily bitcoin price. Data is obtained from CoinGecko using their public API."
|
||||
tags: ["Bitcoin", "Stats"]
|
||||
script: "/js/mangrove-map.js"
|
||||
draft: true
|
||||
---
|
||||
|
||||
{{< table id="mangrove_countries" endpoint="mangrove_by_country_latest" headers="{'country_with_parent': 'Country', 'original_pixels': '1996 Cover', 'total_n_pixels': '2020 Cover', 'cumulative_pixels_diff': 'Diff', 'cumulative_pct_diff': '% Diff'}" maxHeight="400px" sortable="true" valueId="country_with_parent" selectableRows="single" defaultFirstSelected="true" targets="mangrove-country-timeseries-chart" >}}
|
||||
|
||||
{{< chart id="mangrove-country-timeseries-chart" endpoint="mangrove_country_timeseries" chartType="bar" xAxisField="year" yAxisField="total_n_pixels" scaleChart=true xAxisType="category" >}}
|
||||
|
|
@ -1,21 +1,3 @@
|
|||
# License
|
||||
|
||||
Where possible, all original work on this site that has been created and published by me is licensed using [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/).
|
||||
|
||||
You are free to:
|
||||
|
||||
- Share — copy and redistribute the material in any medium or format for any purpose, even commercially.
|
||||
- Adapt — remix, transform, and build upon the material for any purpose, even commercially.
|
||||
|
||||
The licensor cannot revoke these freedoms as long as you follow the license terms.
|
||||
|
||||
Under the following terms:
|
||||
- Attribution — You must give appropriate credit , provide a link to the license, and indicate if changes were made . You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.
|
||||
- ShareAlike — If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original.
|
||||
- No additional restrictions — You may not apply legal terms or technological measures that legally restrict others from doing anything the license permits.
|
||||
|
||||
Notices:
|
||||
|
||||
You do not have to comply with the license for elements of the material in the public domain or where your use is permitted by an applicable exception or limitation .
|
||||
|
||||
No warranties are given. The license may not give you all of the permissions necessary for your intended use. For example, other rights such as publicity, privacy, or moral rights may limit how you use the material.
|
||||
All work on this site is licensed using [unlicense](https://unlicense.org/). This effectively means all of the content hosted on https://bitlab21.com and in the bitlab21.com repository at https://git.bitlab21.com/sam/bitlab21.com is in the public domain. You can use this material as you wish. Attribution is appreciated, but not required.
|
||||
|
|
|
@ -1,9 +1,6 @@
|
|||
baseURL = 'https://baseddata.io'
|
||||
baseURL = 'https://baseddate.io/'
|
||||
languageCode = 'en-gb'
|
||||
title = 'Based Data'
|
||||
|
||||
[params]
|
||||
apiURL = 'https://api.baseddata.io'
|
||||
title = 'baseddata.io'
|
||||
|
||||
[markup.highlight]
|
||||
pygmentsUseClasses = false
|
||||
|
|
|
@ -1,11 +1,5 @@
|
|||
<!doctype html>
|
||||
<head>
|
||||
<script>
|
||||
const apiURL = "{{ .Site.Params.apiURL }}";
|
||||
</script>
|
||||
{{ partial "head.html" . }}
|
||||
</head>
|
||||
{{ template "partials/body.html" . }}
|
||||
{{ range .Params.jsScripts }}
|
||||
<script src="{{ . }}"></script>
|
||||
{{ end }}
|
||||
|
|
|
@ -5,6 +5,3 @@
|
|||
{{ partial "footer.html" . }}
|
||||
</div>
|
||||
</body>
|
||||
{{ if .Params.script }}
|
||||
<script src="{{ .Params.script | absURL }}"></script>
|
||||
{{ end }}
|
||||
|
|
8
layouts/partials/chart.html
Normal file
8
layouts/partials/chart.html
Normal file
|
@ -0,0 +1,8 @@
|
|||
<script src="https://cdn.jsdelivr.net/npm/echarts@5.5.1/dist/echarts.min.js"></script>
|
||||
<section class="chart-container">
|
||||
<div id="chart">
|
||||
<canvas id="{{ .id }}"></canvas>
|
||||
<script src="{{ .src }}"></script>
|
||||
</div>
|
||||
</section>
|
||||
<script src="/js/chart-params.js"></script>
|
|
@ -1,9 +1,8 @@
|
|||
<footer>
|
||||
<div id="footer">
|
||||
<p>
|
||||
baseddata.io by Sam Chance. | Built with
|
||||
<a href="https://gohugo.io/">Hugo</a>
|
||||
| <a href="/license">License</a>
|
||||
Bitlab21.com by Sam Chance.
|
||||
<a href="/license">Uncopywrited.</a>
|
||||
</p>
|
||||
</div>
|
||||
</footer>
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
<header>
|
||||
<nav class="navbar" role="navigation">
|
||||
<div class="navbar__left">
|
||||
<a href="/"><strong>BASED DATA</strong></a>
|
||||
<a href="/"><strong>Based Data</strong></a>
|
||||
</div>
|
||||
<div class="navbar__right">
|
||||
<div class="navbar-links">{{ partial "navbarlinks.html" . }}</div>
|
||||
|
|
2
layouts/partials/table.html
Normal file
2
layouts/partials/table.html
Normal file
|
@ -0,0 +1,2 @@
|
|||
<script src="{{ .src }}"></script>
|
||||
<table id="jsonTableContainer"></table>
|
19
layouts/shortcodes/bitcoin-price.html
Normal file
19
layouts/shortcodes/bitcoin-price.html
Normal file
|
@ -0,0 +1,19 @@
|
|||
<!doctype html>
|
||||
<html>
|
||||
<body>
|
||||
<p id="price"></p>
|
||||
|
||||
<script>
|
||||
fetch("https://api.bitlab21.com/price")
|
||||
.then((response) => response.json())
|
||||
.then((data) => {
|
||||
var lastElement = data[data.length - 1];
|
||||
document.getElementById("price").innerHTML =
|
||||
`The current price is: <em>$ ${lastElement.price.toLocaleString()}</em> (${lastElement.date}) `;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Error:", error);
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
|
@ -1,3 +1,2 @@
|
|||
<section class = 'chart-container' id="{{ .Get "id" }}-container">
|
||||
<div id="{{ .Get "id" }}" class="chart"></div>
|
||||
</section>
|
||||
{{ $id := .Get "src" | md5 }}
|
||||
{{ partial "chart.html" (dict "src" (.Get "src") "id" $id) }}
|
||||
|
|
|
@ -5,12 +5,7 @@
|
|||
<script>
|
||||
async function downloadFile(url, name) {
|
||||
try {
|
||||
downloadUrl = `${"{{ .Site.Params.apiURL }}"}/download${url}`
|
||||
console.log("Downloading from url:",downloadUrl)
|
||||
const response = await fetch(downloadUrl);
|
||||
if (!response.ok) {
|
||||
throw new Error('Network response was not ok');
|
||||
}
|
||||
const response = await fetch(url);
|
||||
const blob = await response.blob();
|
||||
const link = document.createElement('a');
|
||||
link.href = URL.createObjectURL(blob);
|
||||
|
@ -18,7 +13,6 @@
|
|||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(link.href); // Clean up the object URL
|
||||
} catch (error) {
|
||||
console.error('Error downloading the file:', error);
|
||||
}
|
||||
|
|
7
layouts/shortcodes/dropdown-filter.html
Normal file
7
layouts/shortcodes/dropdown-filter.html
Normal file
|
@ -0,0 +1,7 @@
|
|||
<select id={{ .Get "id" }} class="dropdownFilter">
|
||||
{{ with .Get "select" }}
|
||||
{{ range $index, $element := split . "," }}
|
||||
<option value="{{ $element }}">{{ $element }}</option>
|
||||
{{ end }}
|
||||
</select>
|
||||
{{ end }}
|
|
@ -1,4 +0,0 @@
|
|||
<div id="{{ .Get "id" }}-container" class="dropdown-filter-container">
|
||||
<select id="{{ .Get "id" }}" class="filter dropdown-filter">
|
||||
</select>
|
||||
</div>
|
|
@ -1,9 +0,0 @@
|
|||
{{ if .Get "src" }}
|
||||
<script src="{{ .Get "src" }}"></script>
|
||||
{{ else }}
|
||||
<script id="{{ .Get " id" }}">
|
||||
window.addEventListener('DOMContentLoaded', (event) => {
|
||||
{{ .Inner | safeJS }}
|
||||
});
|
||||
</script>
|
||||
{{ end }}
|
|
@ -1,15 +0,0 @@
|
|||
<script src="https://labs.geomatico.es/maplibre-cog-protocol/dist/index.js"></script>
|
||||
<script src="https://unpkg.com/maplibre-gl/dist/maplibre-gl.js"></script>
|
||||
<link
|
||||
rel="stylesheet"
|
||||
href="https://unpkg.com/maplibre-gl/dist/maplibre-gl.css"
|
||||
/>
|
||||
<section class="map-container">
|
||||
<div id="{{ .Get `id` }}" style="height: 400px"></div>
|
||||
<script>
|
||||
let map = new maplibregl.Map({
|
||||
container: "{{ .Get `id` }}",
|
||||
style: "{{ .Get `style` }}",
|
||||
});
|
||||
</script>
|
||||
</section>
|
|
@ -1,3 +1,2 @@
|
|||
<section class = 'table-container' id = '{{ .Get "id" }}-container'>
|
||||
<div id="{{ .Get "id" }}" class="table"></div>
|
||||
</section>
|
||||
{{ $id := .Get "src" | md5 }}
|
||||
{{ partial "table.html" (dict "src" (.Get "src") "id" $id) }}
|
||||
|
|
|
@ -6,39 +6,24 @@
|
|||
</div>
|
||||
<div class="article-card-container">
|
||||
{{ range.Pages }}
|
||||
<div class="article-card">
|
||||
<a class="article-card" href="{{ .RelPermalink }}">
|
||||
<div class="article-card-info">
|
||||
<div class="article-card-thumb">
|
||||
<a href="{{ .RelPermalink }}">
|
||||
<img
|
||||
class="article-card-thumbnail"
|
||||
src="{{ .Params.header_image }}"
|
||||
/>
|
||||
</a>
|
||||
<img
|
||||
class="article-card-thumbnail"
|
||||
src="{{ .Params.header_image }}"
|
||||
/>
|
||||
</div>
|
||||
<div class="article-card-summary">
|
||||
{{ template "partials/get-tags.html" . }}
|
||||
<a href="{{ .RelPermalink }}">
|
||||
<h3><strong>{{ .Title | safeHTML }}</strong></h3>
|
||||
</a>
|
||||
<p>
|
||||
{{ .Summary | safeHTML }}
|
||||
<i class="reading-time"
|
||||
>({{ .ReadingTime }} minute{{ if (ne .ReadingTime 1) }}s{{ end
|
||||
}})</i
|
||||
>
|
||||
</p>
|
||||
|
||||
<h3><strong>{{ .Title | safeHTML }}</strong></h3>
|
||||
<p>{{ .Summary | safeHTML }}</p>
|
||||
<br />
|
||||
<div class="article-card-author-row">
|
||||
{{ with .Params.author }}
|
||||
<strong><p class="author-name">{{ .name }}</p></strong>
|
||||
{{ end }}
|
||||
<time>{{ .Date.Format "January 2, 2006" }}</time>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</a>
|
||||
{{ end }}
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
@ -1,23 +0,0 @@
|
|||
[tool.poetry]
|
||||
name = "baseddata-io"
|
||||
version = "0.1.0"
|
||||
description = ""
|
||||
authors = ["Sam <samual.shop@proton.me>"]
|
||||
readme = "README.md"
|
||||
packages = [{include = "baseddata"}]
|
||||
package-mode = false
|
||||
|
||||
[virtualenvs]
|
||||
in-project = true
|
||||
|
||||
[tool.poetry.dependencies]
|
||||
python = "^3.11"
|
||||
fastapi = "^0.115.4"
|
||||
uvicorn = "^0.32.0"
|
||||
psycopg2-binary = "^2.9.10"
|
||||
load-dotenv = "^0.1.0"
|
||||
|
||||
|
||||
[build-system]
|
||||
requires = ["poetry-core"]
|
||||
build-backend = "poetry.core.masonry.api"
|
32
shell.nix
32
shell.nix
|
@ -1,28 +1,18 @@
|
|||
{pkgs ? import <nixpkgs> {}}:
|
||||
{ pkgs ? import <nixpkgs> { } }:
|
||||
|
||||
pkgs.mkShell
|
||||
{
|
||||
nativeBuildInputs = with pkgs; [
|
||||
python312Packages.flask
|
||||
python312Packages.flask-cors
|
||||
python312Packages.requests
|
||||
python312Packages.pandas
|
||||
python312Packages.orjson
|
||||
hugo
|
||||
python311
|
||||
poetry
|
||||
];
|
||||
|
||||
NIX_LD_LIBRARY_PATH=/run/current-system/sw/share/nix-ld/lib;
|
||||
NIX_LD=/run/current-system/sw/share/nix-ld/lib/ld.so;
|
||||
shellHook = ''
|
||||
${pkgs.cowsay}/bin/cowsay "Welcome to the baseddata.io development environment!" | ${pkgs.lolcat}/bin/lolcat
|
||||
export LD_LIBRARY_PATH=$NIX_LD_LIBRARY_PATH
|
||||
source .env
|
||||
source .venv/bin/activate
|
||||
get_session=$(tmux list-session | grep "baseddata")
|
||||
|
||||
if [ -z "$get_session" ];
|
||||
then
|
||||
tmux new-session -d -s baseddata
|
||||
tmux split-window -h
|
||||
tmux send-keys -t 0 "hugo server" C-m
|
||||
tmux send-keys -t 1 "cd backend && uvicorn main:app --reload" C-m
|
||||
echo "Baseddata running in dev tmux shell"
|
||||
fi
|
||||
'';
|
||||
shellHook = ''
|
||||
${pkgs.cowsay}/bin/cowsay "Welcome to the bitlab development environment!" | ${pkgs.lolcat}/bin/lolcat
|
||||
'';
|
||||
}
|
||||
|
||||
|
|
|
@ -1,21 +1,19 @@
|
|||
/* Charts */
|
||||
.chart-container {
|
||||
.chart-flex-container {
|
||||
display: flex;
|
||||
/* height: 600px; */
|
||||
aspect-ratio: 2 / 1;
|
||||
}
|
||||
|
||||
.chart {
|
||||
display: flex;
|
||||
height: 100%;
|
||||
.chart-flex-container article {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
#chart {
|
||||
width: 100%;
|
||||
aspect-ratio: 16 / 9;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.chart-container {
|
||||
margin-top: 20px;
|
||||
display: flex;
|
||||
/* height: 600px; */
|
||||
aspect-ratio: 1 / 1;
|
||||
}
|
||||
|
||||
justify-content: center;
|
||||
}
|
||||
|
|
|
@ -52,7 +52,6 @@
|
|||
|
||||
.navbar__left a {
|
||||
text-decoration: none !important;
|
||||
font-weight: 540;
|
||||
color: var(--text-color) !important;
|
||||
font-size: 22px;
|
||||
}
|
||||
|
|
|
@ -70,18 +70,17 @@
|
|||
|
||||
/* Style for WebKit browsers (Chrome, Safari, etc.) */
|
||||
*::-webkit-scrollbar {
|
||||
height: 2px;
|
||||
border-radius: 1px;
|
||||
height: 5px;
|
||||
border-radius: 6px;
|
||||
background: #1f1f28;
|
||||
}
|
||||
|
||||
*::-webkit-scrollbar-thumb {
|
||||
border-radius: 2px;
|
||||
border-radius: 6px;
|
||||
background: #585653;
|
||||
}
|
||||
|
||||
*::-webkit-scrollbar-thumb:hover {
|
||||
height: 2px;
|
||||
background: #454445; /* Background color on hover */
|
||||
}
|
||||
|
||||
|
@ -134,10 +133,7 @@ footer {
|
|||
color: var(--text-color);
|
||||
padding: 20px;
|
||||
height: 10vh;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
border-top: var(--border-width) var(--border-style) var(--border-color);
|
||||
}
|
||||
|
||||
#footer {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
|
|
@ -1,11 +1,6 @@
|
|||
/* Tables */
|
||||
.jsonTableContainer {
|
||||
display: flex;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
table.sortable th:not(.sorttable_sorted):not(.sorttable_sorted_reverse):not(.sorttable_nosort):after {
|
||||
content: " \25B4\25BE"
|
||||
#jsonTableContainer {
|
||||
max-width: 150%;
|
||||
}
|
||||
|
||||
table {
|
||||
|
@ -28,13 +23,9 @@ td {
|
|||
max-width: 90px;
|
||||
font-size: var(--table-row-font-size);
|
||||
}
|
||||
#scrollable:hover {
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
|
||||
@media only screen and (max-width: 800px) {
|
||||
#scrollable {
|
||||
scrollbar-width: thin;
|
||||
max-width: 90px;
|
||||
max-height: 100%;
|
||||
margin: 0;
|
||||
|
@ -53,10 +44,3 @@ tr:nth-child(odd) {
|
|||
background-color: var(--table-odd-row-bg-color);
|
||||
font-size: var(--table-row-font-size);
|
||||
}
|
||||
tr:hover {
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
|
||||
tr.selected {
|
||||
background-color: #d1ecf1;
|
||||
}
|
||||
|
|
98
static/js/bitcoin-business-growth-chart.js
Normal file
98
static/js/bitcoin-business-growth-chart.js
Normal file
|
@ -0,0 +1,98 @@
|
|||
let chartData = [];
|
||||
let myChart;
|
||||
|
||||
async function fetchDataForChart(str) {
|
||||
try {
|
||||
const apiEndpoint = `https://api.bitlab21.com/bitcoin_business_growth_by_country?cumulative_period_type=365 day&countries=${str}`;
|
||||
const response = await fetch(apiEndpoint);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
const fetchedData = await response.json();
|
||||
const newData = fetchedData.reduce((acc, item) => {
|
||||
const objectId = item.country_name;
|
||||
if (!acc[objectId]) {
|
||||
acc[objectId] = [];
|
||||
}
|
||||
acc[objectId].push([item.date, item.cumulative_current_value]);
|
||||
return acc;
|
||||
}, {});
|
||||
chartData = { ...chartData, ...newData };
|
||||
updateChart();
|
||||
} catch (error) {
|
||||
console.error("Fetching data failed:", error);
|
||||
}
|
||||
}
|
||||
|
||||
function updateChart() {
|
||||
let chartDataMap = new Map();
|
||||
for (let objectId in chartData) {
|
||||
chartDataMap.set(objectId, chartData[objectId]);
|
||||
}
|
||||
option = {
|
||||
backgroundColor: backgroundColor,
|
||||
grid: grid,
|
||||
tooltip: tooltip,
|
||||
toolbox: toolboxParams,
|
||||
xAxis: {
|
||||
axisTick: axisTick,
|
||||
axisLabel: axisLabel,
|
||||
axisLine: axisLine,
|
||||
type: "time",
|
||||
},
|
||||
yAxis: {
|
||||
axisTick: axisTick,
|
||||
splitLine: {
|
||||
show: false,
|
||||
},
|
||||
axisLabel: {
|
||||
fontSize: 12 * fontScale,
|
||||
color: textColor,
|
||||
formatter(value, index) {
|
||||
return nFormatter(value, 2);
|
||||
},
|
||||
},
|
||||
axisLine: axisLine,
|
||||
},
|
||||
|
||||
series: Array.from(chartDataMap.entries()).map(([name, data]) => ({
|
||||
name,
|
||||
type: "line",
|
||||
data,
|
||||
showSymbol: false,
|
||||
})),
|
||||
};
|
||||
myChart.setOption(option, true);
|
||||
}
|
||||
|
||||
function handleCheckboxChange(event) {
|
||||
if (event.target.type === "checkbox") {
|
||||
const boxChecked = event.target.checked;
|
||||
const boxId = event.target.id;
|
||||
// Remove unchecked boxes
|
||||
if (boxChecked === false) {
|
||||
delete chartData[boxId];
|
||||
updateChart();
|
||||
// Add checked boxes
|
||||
} else {
|
||||
fetchDataForChart(boxId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener("reloadTable", () => {
|
||||
myChart = echarts.init(document.getElementById("chart"));
|
||||
jsonTableCheckedBoxes = document.querySelectorAll(
|
||||
'#jsonTableContainer input[type="checkbox"]:checked',
|
||||
);
|
||||
const checkedBoxes = Array.from(jsonTableCheckedBoxes).map(
|
||||
(checkbox) => checkbox.id,
|
||||
);
|
||||
const str = checkedBoxes.join(",");
|
||||
chartData = [];
|
||||
fetchDataForChart(str);
|
||||
|
||||
jsonTable = document.getElementById("jsonTableContainer");
|
||||
jsonTable.removeEventListener("change", handleCheckboxChange);
|
||||
jsonTable.addEventListener("change", handleCheckboxChange);
|
||||
});
|
98
static/js/bitcoin-business-growth-table.js
Normal file
98
static/js/bitcoin-business-growth-table.js
Normal file
|
@ -0,0 +1,98 @@
|
|||
async function fetchDataForTable() {
|
||||
try {
|
||||
const dropdown = document.querySelector(".dropdownFilter");
|
||||
let selectedIndex = dropdown.selectedIndex;
|
||||
let selectedValue = dropdown.options[selectedIndex].value;
|
||||
const apiEndpoint =
|
||||
"https://api.bitlab21.com/bitcoin_business_growth_by_country?latest_date=true";
|
||||
const response = await fetch(
|
||||
apiEndpoint + `&cumulative_period_type=${selectedValue}`,
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
const fetchedData = await response.json();
|
||||
data = fetchedData;
|
||||
createTable(data);
|
||||
} catch (error) {
|
||||
console.error("Fetching data failed:", error);
|
||||
}
|
||||
}
|
||||
|
||||
function createTable(data) {
|
||||
const jsonTableContainer = document.getElementById("jsonTableContainer");
|
||||
jsonTableContainer.innerHTML = "";
|
||||
const table = document.createElement("table");
|
||||
let checkedBoxes = [];
|
||||
const thead = document.createElement("thead");
|
||||
const headerRow = document.createElement("tr");
|
||||
tableHeaders = [
|
||||
"Select",
|
||||
"Country",
|
||||
"Previous #",
|
||||
"Current #",
|
||||
"Diff",
|
||||
"% Diff",
|
||||
];
|
||||
tableHeaders.forEach((header) => {
|
||||
const th = document.createElement("th");
|
||||
th.textContent = header;
|
||||
headerRow.appendChild(th);
|
||||
});
|
||||
thead.appendChild(headerRow);
|
||||
table.appendChild(thead);
|
||||
const tbody = document.createElement("tbody");
|
||||
filteredData = data.filter((item) => 1 === 1);
|
||||
filteredData.sort((a, b) => {
|
||||
const sortField = "diff";
|
||||
return Math.abs(b[sortField]) - Math.abs(a[sortField]);
|
||||
});
|
||||
filteredData.forEach((row, index) => {
|
||||
const tr = document.createElement("tr");
|
||||
const checkbox = document.createElement("input");
|
||||
checkbox.type = "checkbox";
|
||||
checkbox.checked = index < 1;
|
||||
checkbox.addEventListener("change", function () {
|
||||
if (this.checked) {
|
||||
checkedBoxes.push(row["country_name"]);
|
||||
} else {
|
||||
checkedBoxes = checkedBoxes.filter((id) => id !== row["country_name"]);
|
||||
}
|
||||
});
|
||||
checkbox.id = row["country_name"];
|
||||
tr.appendChild(document.createElement("td")).append(checkbox);
|
||||
columnNames = [
|
||||
"country_name",
|
||||
"cumulative_previous_value",
|
||||
"cumulative_current_value",
|
||||
"diff",
|
||||
"pct_diff",
|
||||
];
|
||||
columnNames.forEach((columnName) => {
|
||||
const td = document.createElement("td");
|
||||
const div = document.createElement("div");
|
||||
div.id = "scrollable";
|
||||
div.textContent = row[columnName];
|
||||
td.appendChild(div);
|
||||
tr.appendChild(td);
|
||||
});
|
||||
tbody.appendChild(tr);
|
||||
if (checkbox.checked) {
|
||||
checkedBoxes.push(row["country_name"]);
|
||||
}
|
||||
});
|
||||
table.appendChild(tbody);
|
||||
const tableContainer = document.getElementById("jsonTableContainer");
|
||||
tableContainer.appendChild(table);
|
||||
tableContainer.dispatchEvent(
|
||||
new CustomEvent("reloadTable", { bubbles: true }),
|
||||
);
|
||||
}
|
||||
|
||||
window.onload = () => {
|
||||
const dropdown = document.querySelector(".dropdownFilter");
|
||||
fetchDataForTable();
|
||||
dropdown.addEventListener("change", () => {
|
||||
fetchDataForTable();
|
||||
});
|
||||
};
|
65
static/js/bitcoin-price.js
Normal file
65
static/js/bitcoin-price.js
Normal file
|
@ -0,0 +1,65 @@
|
|||
let dataArr = [];
|
||||
const myChart = echarts.init(document.getElementById("chart"));
|
||||
|
||||
async function fetchDataForChart() {
|
||||
try {
|
||||
const apiEndpoint = "https://api.bitlab21.com/get_json/final__price.json";
|
||||
const response = await fetch(apiEndpoint);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
const dataArr = await response.json();
|
||||
initEchart(dataArr);
|
||||
} catch (error) {
|
||||
console.error("Fetching data failed:", error);
|
||||
}
|
||||
}
|
||||
|
||||
function initEchart(dataArr) {
|
||||
const option = {
|
||||
backgroundColor: backgroundColor,
|
||||
tooltip: tooltip,
|
||||
toolbox: toolboxParams,
|
||||
xAxis: {
|
||||
data: dataArr.map((row) => row.date),
|
||||
axisTick: axisTick,
|
||||
axisLabel: axisLabel,
|
||||
axisLine: axisLine,
|
||||
},
|
||||
grid: grid,
|
||||
dataZoom: dataZoom(),
|
||||
yAxis: [
|
||||
{
|
||||
type: "value",
|
||||
name: "Price (USD)",
|
||||
nameGap: 30,
|
||||
nameLocation: "middle",
|
||||
nameTextStyle: textStyleMain,
|
||||
position: "left",
|
||||
alignTicks: true,
|
||||
axisTick: axisTick,
|
||||
axisLine: axisLine,
|
||||
splitLine: {
|
||||
show: false,
|
||||
},
|
||||
axisLabel: {
|
||||
...axisLabel,
|
||||
formatter(value, index) {
|
||||
return nFormatter(value, 0);
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
series: [
|
||||
{
|
||||
type: "line",
|
||||
name: "Price (USD)",
|
||||
data: dataArr.map((row) => row.price),
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
myChart.setOption(option);
|
||||
}
|
||||
|
||||
fetchDataForChart();
|
|
@ -31,7 +31,7 @@ const toolboxParams = {
|
|||
dataZoom: {
|
||||
yAxisIndex: "none",
|
||||
},
|
||||
dataView: {},
|
||||
restore: {},
|
||||
saveAsImage: {
|
||||
pixelRatio: 2,
|
||||
},
|
||||
|
@ -73,16 +73,39 @@ const yaxisTextStyle2 = {
|
|||
color: textColor,
|
||||
};
|
||||
|
||||
function dataZoom() {
|
||||
function dataZoom(start = 90, end = 100, bottom = 15, height = 15) {
|
||||
const dataZoom = [
|
||||
{
|
||||
type: "inside",
|
||||
start: start,
|
||||
end: end,
|
||||
bottom: bottom,
|
||||
height: height,
|
||||
},
|
||||
];
|
||||
|
||||
return dataZoom;
|
||||
}
|
||||
|
||||
function nFormatter(value, digits) {
|
||||
const lookup = [
|
||||
{ value: 1, symbol: "" },
|
||||
{ value: 1e3, symbol: "k" },
|
||||
{ value: 1e6, symbol: "M" },
|
||||
{ value: 1e9, symbol: "G" },
|
||||
{ value: 1e12, symbol: "T" },
|
||||
{ value: 1e15, symbol: "P" },
|
||||
{ value: 1e18, symbol: "E" },
|
||||
];
|
||||
const rx = /\.0+$|(\.[0-9]*[1-9])0+$/;
|
||||
const item = lookup
|
||||
.slice()
|
||||
.reverse()
|
||||
.find((item) => value >= item.value);
|
||||
return item
|
||||
? (value / item.value).toFixed(digits).replace(rx, "$1") + item.symbol
|
||||
: "0";
|
||||
}
|
||||
|
||||
window.addEventListener("resize", function () {
|
||||
if (myChart != null && myChart != undefined) {
|
||||
myChart.resize();
|
|
@ -1,93 +0,0 @@
|
|||
function createChart(
|
||||
chart,
|
||||
endpoint,
|
||||
xAxisType,
|
||||
scaleChart = false,
|
||||
) {
|
||||
async function fetchDataForChart(query) {
|
||||
try {
|
||||
const apiEndpoint = `${apiURL}/${endpoint}?${query}`;
|
||||
const response = await fetch(apiEndpoint);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
const chartData = await response.json();
|
||||
console.log(chartData)
|
||||
updateChart(chartData);
|
||||
} catch (error) {
|
||||
console.error("Fetching data failed:", error);
|
||||
}
|
||||
}
|
||||
|
||||
function updateChart(chartData) {
|
||||
var option = {
|
||||
tooltip: {
|
||||
...tooltip,
|
||||
},
|
||||
xAxis: {
|
||||
type: xAxisType,
|
||||
data: chartData.map((item) => item.date),
|
||||
},
|
||||
yAxis: [
|
||||
{
|
||||
type: "value",
|
||||
name: "Price (USD)",
|
||||
nameGap: 30,
|
||||
nameLocation: "middle",
|
||||
nameTextStyle: textStyleMain,
|
||||
position: "left",
|
||||
alignTicks: true,
|
||||
axisTick: axisTick,
|
||||
axisLine: axisLine,
|
||||
splitLine: {
|
||||
show: false,
|
||||
},
|
||||
axisLabel: {
|
||||
...axisLabel,
|
||||
formatter(value, index) {
|
||||
return nFormatter(value, 0);
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
series: [
|
||||
{
|
||||
type: "line",
|
||||
name: "Price (USD)",
|
||||
data: chartData.map((row) => row.price),
|
||||
},
|
||||
],
|
||||
};
|
||||
chart.setOption(option, true);
|
||||
}
|
||||
|
||||
// listen for filter events for this target
|
||||
document.addEventListener("filterChange", function(event) {
|
||||
eventDetail = event.detail;
|
||||
if (eventDetail.filterActions.includes("refresh")) {
|
||||
chartData = [];
|
||||
query = queryConstructor();
|
||||
fetchDataForChart(query);
|
||||
updateChart(chartData);
|
||||
}
|
||||
});
|
||||
|
||||
let query = queryConstructor();
|
||||
fetchDataForChart(query);
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", function() {
|
||||
chartData = [];
|
||||
let chartDom = document.getElementById("bitcoin-price-chart");
|
||||
let myChart = echarts.init(chartDom);
|
||||
|
||||
const filterPeriods = { "7 day": 7, "28 day": 28, "365 day": 365, "2 years": 730, "5 years": 1826, "10 years": 3652, "all time": 10000 };
|
||||
dropDownFilter("days_ago_dropdown_filter", "days_ago", ["bitcoin-price-chart"], filterPeriods, "365 day")
|
||||
|
||||
createChart(
|
||||
chart = myChart,
|
||||
endpoint = "bitcoin_price_timeseries",
|
||||
xAxisType = "category",
|
||||
);
|
||||
});
|
||||
|
|
@ -1,106 +0,0 @@
|
|||
function createChart(
|
||||
chart,
|
||||
endpoint,
|
||||
xAxisType,
|
||||
scaleChart = false,
|
||||
) {
|
||||
async function fetchDataForChart(query) {
|
||||
try {
|
||||
const apiEndpoint = `${apiURL}/${endpoint}?${query}`;
|
||||
const response = await fetch(apiEndpoint);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
const chartData = await response.json();
|
||||
console.log(chartData)
|
||||
updateChart(chartData);
|
||||
} catch (error) {
|
||||
console.error("Fetching data failed:", error);
|
||||
}
|
||||
}
|
||||
|
||||
function updateChart(chartData) {
|
||||
|
||||
var option = {
|
||||
tooltip: {
|
||||
...tooltip,
|
||||
},
|
||||
xAxis: {
|
||||
type: xAxisType,
|
||||
data: chartData.map((item) => item.date),
|
||||
},
|
||||
yAxis: {
|
||||
scale: scaleChart,
|
||||
type: "value",
|
||||
},
|
||||
series: [
|
||||
{
|
||||
type: "bar",
|
||||
stack: "value",
|
||||
name: "10th",
|
||||
barCategoryGap: "0%",
|
||||
data: chartData.map((row) => row.feerate_10th),
|
||||
},
|
||||
{
|
||||
type: "bar",
|
||||
stack: "value",
|
||||
name: "25th",
|
||||
barCategoryGap: "0%",
|
||||
data: chartData.map((row) => row.feerate_25th),
|
||||
},
|
||||
{
|
||||
type: "bar",
|
||||
stack: "value",
|
||||
name: "50th",
|
||||
barCategoryGap: "0%",
|
||||
data: chartData.map((row) => row.feerate_50th),
|
||||
},
|
||||
{
|
||||
type: "bar",
|
||||
stack: "value",
|
||||
name: "75th",
|
||||
barCategoryGap: "0%",
|
||||
data: chartData.map((row) => row.feerate_75th),
|
||||
},
|
||||
{
|
||||
type: "bar",
|
||||
stack: "value",
|
||||
name: "90th",
|
||||
barCategoryGap: "0%",
|
||||
data: chartData.map((row) => row.feerate_90th),
|
||||
},
|
||||
],
|
||||
};
|
||||
chart.setOption(option, true);
|
||||
}
|
||||
|
||||
// listen for filter events for this target
|
||||
document.addEventListener("filterChange", function(event) {
|
||||
eventDetail = event.detail;
|
||||
if (eventDetail.filterActions.includes("refresh")) {
|
||||
chartData = [];
|
||||
query = queryConstructor();
|
||||
fetchDataForChart(query);
|
||||
updateChart(chartData);
|
||||
}
|
||||
});
|
||||
|
||||
let query = queryConstructor();
|
||||
fetchDataForChart(query);
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", function() {
|
||||
chartData = [];
|
||||
let chartDom = document.getElementById("feerate-percentiles-chart");
|
||||
let myChart = echarts.init(chartDom);
|
||||
|
||||
const filterPeriods = {"7 day": 7, "28 day": 28, "365 day": 365, "2 years": 730, "5 years": 1826, "10 years": 3652, "all time": 10000};
|
||||
dropDownFilter("days_ago_dropdown_filter", "days_ago", ["feerate-percentile-chart"], filterPeriods, "365 day")
|
||||
|
||||
createChart(
|
||||
chart = myChart,
|
||||
endpoint = "feerate_percentiles",
|
||||
xAxisType = "category",
|
||||
);
|
||||
});
|
||||
|
|
@ -1,279 +0,0 @@
|
|||
function createTable(
|
||||
endpoint,
|
||||
tableId,
|
||||
headers,
|
||||
maxHeight,
|
||||
sortable,
|
||||
valueId,
|
||||
selectableRows,
|
||||
filterTargets,
|
||||
defaultFirstSelected,
|
||||
) {
|
||||
async function fetchDataForTable(query) {
|
||||
try {
|
||||
const apiEndpoint = `${apiURL}/${endpoint}?${query}`;
|
||||
const response = await fetch(apiEndpoint);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
const fetchedData = await response.json();
|
||||
data = fetchedData;
|
||||
generateTable(data);
|
||||
} catch (error) {
|
||||
console.error("Fetching data failed:", error);
|
||||
}
|
||||
}
|
||||
|
||||
function generateTable(data) {
|
||||
const jsonTableContainer = document.getElementById(`${tableId}-container`);
|
||||
jsonTableContainer.className = "jsonTableContainer";
|
||||
jsonTableContainer.innerHTML = "";
|
||||
jsonTableContainer.style.maxHeight = maxHeight;
|
||||
|
||||
tableHeaderNames = Object.values(headers);
|
||||
tableHeaderKeys = Object.keys(headers);
|
||||
|
||||
const table = document.createElement("table");
|
||||
table.id = tableId;
|
||||
const thead = document.createElement("thead");
|
||||
const tbody = document.createElement("tbody");
|
||||
const headerRow = document.createElement("tr");
|
||||
tableHeaderNames.forEach((header) => {
|
||||
const th = document.createElement("th");
|
||||
th.textContent = header;
|
||||
headerRow.appendChild(th);
|
||||
});
|
||||
thead.appendChild(headerRow);
|
||||
table.appendChild(thead);
|
||||
|
||||
for (const key in data) {
|
||||
const row = document.createElement("tr");
|
||||
row.value = data[key][valueId];
|
||||
tableHeaderKeys.forEach((columnName) => {
|
||||
const td = document.createElement("td");
|
||||
const div = document.createElement("div");
|
||||
div.id = "scrollable";
|
||||
div.textContent = data[key][columnName];
|
||||
td.appendChild(div);
|
||||
row.appendChild(td);
|
||||
tbody.appendChild(row);
|
||||
});
|
||||
}
|
||||
table.appendChild(thead);
|
||||
table.appendChild(tbody);
|
||||
jsonTableContainer.appendChild(table);
|
||||
|
||||
|
||||
if (sortable == true) {
|
||||
table.className = "sortable";
|
||||
sorttable.makeSortable(document.getElementById(tableId));
|
||||
}
|
||||
|
||||
if (selectableRows === "multi" || selectableRows === "single") {
|
||||
const rows = table.getElementsByTagName("tr");
|
||||
for (let i = 1; i < rows.length; i++) {
|
||||
rows[i].addEventListener("click", function() {
|
||||
if (selectableRows === "multi") {
|
||||
this.classList.toggle("selected");
|
||||
if (this.classList.contains("selected")) {
|
||||
const event = new CustomEvent("filterChange", {
|
||||
detail: {
|
||||
filterId: valueId,
|
||||
filterValue: this.value,
|
||||
filterActions: ["selected"],
|
||||
filterTargets: filterTargets,
|
||||
},
|
||||
});
|
||||
document.dispatchEvent(event);
|
||||
} else {
|
||||
const event = new CustomEvent("filterChange", {
|
||||
detail: {
|
||||
filterId: valueId,
|
||||
filterValue: this.value,
|
||||
filterActions: ["deselected"],
|
||||
filterTargets: filterTargets,
|
||||
},
|
||||
});
|
||||
document.dispatchEvent(event);
|
||||
}
|
||||
} else if (selectableRows === "single") {
|
||||
const event = new CustomEvent("filterChange", {
|
||||
detail: {
|
||||
filterId: valueId,
|
||||
filterValue: this.value,
|
||||
filterActions: ["selected"],
|
||||
filterTargets: filterTargets,
|
||||
},
|
||||
});
|
||||
document.dispatchEvent(event);
|
||||
|
||||
if (this.classList.contains("selected")) {
|
||||
this.classList.remove("selected");
|
||||
} else {
|
||||
for (let j = 1; j < rows.length; j++) {
|
||||
rows[j].classList.remove("selected");
|
||||
}
|
||||
this.classList.add("selected");
|
||||
}
|
||||
}
|
||||
});
|
||||
if (defaultFirstSelected == true) {
|
||||
if (i == 1) {
|
||||
rows[i].classList.add("selected");
|
||||
const event = new CustomEvent("filterChange", {
|
||||
detail: {
|
||||
filterId: valueId,
|
||||
filterValue: rows[i].value,
|
||||
filterActions: ["selected"],
|
||||
filterTargets: filterTargets,
|
||||
},
|
||||
});
|
||||
document.dispatchEvent(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
document.addEventListener("filterChange", function(event) {
|
||||
tableId = document.getElementById(tableId).id;
|
||||
if (event.detail.filterTargets.includes(tableId)) {
|
||||
query = queryConstructor();
|
||||
fetchDataForTable(query);
|
||||
}
|
||||
});
|
||||
|
||||
let query = queryConstructor();
|
||||
fetchDataForTable(query);
|
||||
}
|
||||
|
||||
function createChart(
|
||||
chart,
|
||||
chatId,
|
||||
endpoint,
|
||||
xAxisField,
|
||||
yAxisField,
|
||||
chartType,
|
||||
xAxisType,
|
||||
scaleChart = true,
|
||||
formatValueDecimalPlaces = null,
|
||||
) {
|
||||
async function fetchDataForChart(query, valueId) {
|
||||
try {
|
||||
const apiEndpoint = `${apiURL}/${endpoint}?${query}`;
|
||||
const response = await fetch(apiEndpoint);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
const fetchedData = await response.json();
|
||||
const newData = fetchedData.reduce((acc, item) => {
|
||||
const objectId = item[valueId];
|
||||
if (!acc[objectId]) {
|
||||
acc[objectId] = [];
|
||||
}
|
||||
acc[objectId].push([item[xAxisField], item[yAxisField]]);
|
||||
return acc;
|
||||
}, {});
|
||||
chartData = { ...chartData, ...newData };
|
||||
updateChart();
|
||||
} catch (error) {
|
||||
console.error("Fetching data failed:", error);
|
||||
}
|
||||
}
|
||||
|
||||
function updateChart() {
|
||||
let chartDataMap = new Map();
|
||||
for (let objectId in chartData) {
|
||||
chartDataMap.set(objectId, chartData[objectId]);
|
||||
}
|
||||
|
||||
var option = {
|
||||
tooltip: {
|
||||
...tooltip,
|
||||
valueFormatter(value, index) {
|
||||
return formatValueDecimalPlaces == null
|
||||
? value
|
||||
: nFormatter(value, formatValueDecimalPlaces);
|
||||
},
|
||||
},
|
||||
xAxis: {
|
||||
type: xAxisType,
|
||||
},
|
||||
yAxis: {
|
||||
scale: scaleChart,
|
||||
type: "value",
|
||||
},
|
||||
series: Array.from(chartDataMap.entries()).map(([name, data]) => ({
|
||||
name,
|
||||
type: chartType,
|
||||
data,
|
||||
showSymbol: false,
|
||||
})),
|
||||
};
|
||||
chart.setOption(option, true);
|
||||
}
|
||||
|
||||
// listen for filter events for this target
|
||||
document.addEventListener("filterChange", function(event) {
|
||||
eventDetail = event.detail;
|
||||
if (eventDetail.filterActions.includes("refresh")) {
|
||||
chartData = [];
|
||||
updateChart();
|
||||
} else {
|
||||
if (eventDetail.filterTargets.includes(chatId)) {
|
||||
if (eventDetail.filterActions.includes("selected")) {
|
||||
valueId = eventDetail.filterId;
|
||||
let selectedRow = {
|
||||
[valueId]: eventDetail.filterValue,
|
||||
};
|
||||
query = queryConstructor(selectedRow);
|
||||
|
||||
fetchDataForChart(query, valueId);
|
||||
} else {
|
||||
delete chartData[eventDetail.filterValue];
|
||||
updateChart();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", function() {
|
||||
chartData = [];
|
||||
let chartDom = document.getElementById("bitcoin-business-growth-chart");
|
||||
let myChart = echarts.init(chartDom);
|
||||
|
||||
const filterPeriods = {"7 day": 7, "28 day": 28, "365 day": 365, "2 years": 730, "5 years": 1826, "10 years": 3652, "all time": 10000};
|
||||
dropDownFilter("days_ago_dropdown_filter", "days_ago", ["bitcoin-business-growth-chart", "bitcoin-business-growth-table"], filterPeriods, "365 day")
|
||||
|
||||
createTable(
|
||||
endpoint = "bitcoin_business_growth_percent_diff",
|
||||
tableId = "bitcoin-business-growth-table",
|
||||
headers = {
|
||||
'country_name': 'Country',
|
||||
'date_range': 'Date Range',
|
||||
'first_value': 'Previous #',
|
||||
'last_value': 'Current #',
|
||||
'difference': 'Diff',
|
||||
'percent_difference': '% Diff'
|
||||
},
|
||||
maxHeight = "400px",
|
||||
sortable = true,
|
||||
valueId = "country_name",
|
||||
selectableRows = "multi",
|
||||
filterTargets = "bitcoin-business-growth-chart",
|
||||
defaultFirstSelected = true
|
||||
)
|
||||
|
||||
createChart(
|
||||
chart = myChart,
|
||||
chartId = "bitcoin-business-growth-chart",
|
||||
endpoint = "bitcoin_business_growth_timeseries",
|
||||
xAxisField = "date",
|
||||
yAxisField = "cumulative_value",
|
||||
chartType = "line",
|
||||
xAxisType = "category",
|
||||
);
|
||||
});
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
// maplibregl.addProtocol("cog", MaplibreCOGProtocol.cogProtocol);
|
||||
//
|
||||
// map.on("load", () => {
|
||||
// map.addSource("imageSource", {
|
||||
// type: "raster",
|
||||
// url: `cog://http://localhost:5000/cog?year=${year}&pid=${pid}`,
|
||||
// tileSize: 256,
|
||||
// minzoom: 0,
|
||||
// });
|
||||
//
|
||||
// map.addLayer({
|
||||
// id: "imageLayer",
|
||||
// source: "imageSource",
|
||||
// type: "raster",
|
||||
// });
|
||||
// });
|
||||
//
|
|
@ -1,261 +0,0 @@
|
|||
// let chartData = [];
|
||||
// const myChart = echarts.init(document.getElementById("chart"));
|
||||
// const filename = "final__hashrate.json";
|
||||
// const periods = [
|
||||
// "all time",
|
||||
// "last 7 days",
|
||||
// "last 28 days",
|
||||
// "last 365 days",
|
||||
// "last 2 years",
|
||||
// ];
|
||||
//
|
||||
// async function fetchDataForChart(selectedValue) {
|
||||
// try {
|
||||
// const apiEndpoint = `${apiURL}/get_json/${filename}?period=${selectedValue}`;
|
||||
// const response = await fetch(apiEndpoint);
|
||||
// if (!response.ok) {
|
||||
// throw new Error(`HTTP error! status: ${response.status}`);
|
||||
// }
|
||||
// const chartData = await response.json();
|
||||
// initEchart(chartData);
|
||||
// } catch (error) {
|
||||
// console.error("Fetching data failed:", error);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// function initEchart(chartData) {
|
||||
// const option = {
|
||||
// backgroundColor: backgroundColor,
|
||||
// tooltip: {
|
||||
// ...tooltip,
|
||||
// valueFormatter(value, index) {
|
||||
// return nFormatter(value, 0);
|
||||
// },
|
||||
// },
|
||||
// toolbox: toolboxParams,
|
||||
// xAxis: {
|
||||
// data: chartData.map((row) => row.date),
|
||||
// axisTick: axisTick,
|
||||
// axisLabel: axisLabel,
|
||||
// axisLine: axisLine,
|
||||
// },
|
||||
// grid: grid,
|
||||
// dataZoom: dataZoom(0),
|
||||
// yAxis: [
|
||||
// {
|
||||
// type: "value",
|
||||
// name: "Hashrate (H/s)",
|
||||
// nameLocation: "middle",
|
||||
// nameGap: 30,
|
||||
// nameTextStyle: textStyleMain,
|
||||
// position: "left",
|
||||
// alignTicks: true,
|
||||
// axisTick: axisTick,
|
||||
// splitLine: {
|
||||
// show: false,
|
||||
// },
|
||||
// axisLine: axisLine,
|
||||
// axisLabel: {
|
||||
// fontSize: 12 * fontScale,
|
||||
// color: textColor,
|
||||
// formatter(value, index) {
|
||||
// return nFormatter(value, 0);
|
||||
// },
|
||||
// },
|
||||
// },
|
||||
// {
|
||||
// type: "value",
|
||||
// name: "Difficulty",
|
||||
// nameLocation: "middle",
|
||||
// nameGap: 30,
|
||||
// nameTextStyle: textStyleMain,
|
||||
// axisTick: axisTick,
|
||||
// position: "right",
|
||||
// alignTicks: true,
|
||||
// axisLine: axisLine,
|
||||
// splitLine: {
|
||||
// show: false,
|
||||
// },
|
||||
// axisLabel: {
|
||||
// fontSize: 12 * fontScale,
|
||||
// color: textColor,
|
||||
// formatter(value, index) {
|
||||
// return nFormatter(value, 0);
|
||||
// },
|
||||
// },
|
||||
// },
|
||||
// ],
|
||||
// series: [
|
||||
// {
|
||||
// type: "line",
|
||||
// name: "Hashrate",
|
||||
// barCategoryGap: "0%",
|
||||
// data: chartData.map((row) => row.hashrate),
|
||||
// },
|
||||
// {
|
||||
// type: "line",
|
||||
// color: "red",
|
||||
// id: "rolling-average",
|
||||
// name: "MA28",
|
||||
// showSymbol: false,
|
||||
// barCategoryGap: "0%",
|
||||
// data: chartData.map((row) => row.hashrate28),
|
||||
// },
|
||||
// {
|
||||
// type: "line",
|
||||
// yAxisIndex: 1,
|
||||
// name: "Difficulty",
|
||||
// barCategoryGap: "0%",
|
||||
// data: chartData.map((row) => row.difficulty),
|
||||
// },
|
||||
// ],
|
||||
// };
|
||||
//
|
||||
// myChart.setOption(option);
|
||||
// }
|
||||
//
|
||||
// document.addEventListener("DOMContentLoaded", function () {
|
||||
// let periodIndex = 2;
|
||||
// periodDropdown(periods, periodIndex);
|
||||
// fetchDataForChart(periods[periodIndex]);
|
||||
// const selectElement = document.getElementById("select-period-dropdown");
|
||||
//
|
||||
// selectElement.addEventListener("change", function (event) {
|
||||
// const selectedValue = event.target.value;
|
||||
// fetchDataForChart(selectedValue);
|
||||
// });
|
||||
// });
|
||||
|
||||
|
||||
function createChart(
|
||||
chart,
|
||||
endpoint,
|
||||
xAxisType,
|
||||
scaleChart = false,
|
||||
) {
|
||||
async function fetchDataForChart(query) {
|
||||
try {
|
||||
const apiEndpoint = `${apiURL}/${endpoint}?${query}`;
|
||||
const response = await fetch(apiEndpoint);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
const chartData = await response.json();
|
||||
console.log(chartData)
|
||||
updateChart(chartData);
|
||||
} catch (error) {
|
||||
console.error("Fetching data failed:", error);
|
||||
}
|
||||
}
|
||||
|
||||
function updateChart(chartData) {
|
||||
var option = {
|
||||
tooltip: {
|
||||
...tooltip,
|
||||
},
|
||||
xAxis: {
|
||||
type: xAxisType,
|
||||
data: chartData.map((item) => item.date),
|
||||
},
|
||||
yAxis: [
|
||||
{
|
||||
type: "value",
|
||||
name: "Hashrate (H/s)",
|
||||
nameLocation: "middle",
|
||||
nameGap: 30,
|
||||
nameTextStyle: textStyleMain,
|
||||
position: "left",
|
||||
alignTicks: true,
|
||||
axisTick: axisTick,
|
||||
splitLine: {
|
||||
show: false,
|
||||
},
|
||||
axisLine: axisLine,
|
||||
axisLabel: {
|
||||
fontSize: 12 * fontScale,
|
||||
color: textColor,
|
||||
formatter(value, index) {
|
||||
return nFormatter(value, 0);
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "value",
|
||||
name: "Difficulty",
|
||||
nameLocation: "middle",
|
||||
nameGap: 30,
|
||||
nameTextStyle: textStyleMain,
|
||||
axisTick: axisTick,
|
||||
position: "right",
|
||||
alignTicks: true,
|
||||
axisLine: axisLine,
|
||||
splitLine: {
|
||||
show: false,
|
||||
},
|
||||
axisLabel: {
|
||||
fontSize: 12 * fontScale,
|
||||
color: textColor,
|
||||
formatter(value, index) {
|
||||
return nFormatter(value, 0);
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
series: [
|
||||
{
|
||||
type: "line",
|
||||
name: "Hashrate",
|
||||
barCategoryGap: "0%",
|
||||
data: chartData.map((row) => row.hashrate),
|
||||
},
|
||||
{
|
||||
type: "line",
|
||||
color: "red",
|
||||
id: "rolling-average",
|
||||
name: "MA28",
|
||||
showSymbol: false,
|
||||
barCategoryGap: "0%",
|
||||
data: chartData.map((row) => row.hashrate28),
|
||||
},
|
||||
{
|
||||
type: "line",
|
||||
yAxisIndex: 1,
|
||||
name: "Difficulty",
|
||||
barCategoryGap: "0%",
|
||||
data: chartData.map((row) => row.difficulty),
|
||||
},
|
||||
],
|
||||
};
|
||||
chart.setOption(option, true);
|
||||
}
|
||||
|
||||
// listen for filter events for this target
|
||||
document.addEventListener("filterChange", function(event) {
|
||||
eventDetail = event.detail;
|
||||
if (eventDetail.filterActions.includes("refresh")) {
|
||||
chartData = [];
|
||||
query = queryConstructor();
|
||||
fetchDataForChart(query);
|
||||
updateChart(chartData);
|
||||
}
|
||||
});
|
||||
|
||||
let query = queryConstructor();
|
||||
fetchDataForChart(query);
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", function() {
|
||||
chartData = [];
|
||||
let chartDom = document.getElementById("hashrate-chart");
|
||||
let myChart = echarts.init(chartDom);
|
||||
|
||||
const filterPeriods = { "7 day": 7, "28 day": 28, "365 day": 365, "2 years": 730, "5 years": 1826, "10 years": 3652, "all time": 10000 };
|
||||
dropDownFilter("days_ago_dropdown_filter", "days_ago", ["hashrate-chart"], filterPeriods, "365 day")
|
||||
|
||||
createChart(
|
||||
chart = myChart,
|
||||
endpoint = "bitcoin_hashrate",
|
||||
xAxisType = "category",
|
||||
);
|
||||
});
|
||||
|
|
@ -1,151 +0,0 @@
|
|||
function createChart(
|
||||
chart,
|
||||
endpoint,
|
||||
xAxisType,
|
||||
scaleChart = false,
|
||||
) {
|
||||
async function fetchDataForChart(query) {
|
||||
try {
|
||||
const apiEndpoint = `${apiURL}/${endpoint}?${query}`;
|
||||
const response = await fetch(apiEndpoint);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
const chartData = await response.json();
|
||||
console.log(chartData)
|
||||
updateChart(chartData);
|
||||
} catch (error) {
|
||||
console.error("Fetching data failed:", error);
|
||||
}
|
||||
}
|
||||
|
||||
function updateChart(chartData) {
|
||||
var option = {
|
||||
tooltip: {
|
||||
...tooltip,
|
||||
},
|
||||
xAxis: {
|
||||
type: xAxisType,
|
||||
data: chartData.map((item) => item.date),
|
||||
},
|
||||
yAxis: [
|
||||
{
|
||||
type: "value",
|
||||
name: "Rewards (USD)",
|
||||
nameLocation: "middle",
|
||||
nameGap: 30,
|
||||
nameTextStyle: textStyleMain,
|
||||
position: "left",
|
||||
alignTicks: true,
|
||||
axisTick: axisTick,
|
||||
axisLine: axisLine,
|
||||
splitLine: {
|
||||
show: false,
|
||||
},
|
||||
axisLabel: {
|
||||
...axisLabel,
|
||||
formatter(value, index) {
|
||||
return nFormatter(value, 0);
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "value",
|
||||
name: "Subsidy (BTC)",
|
||||
nameLocation: "middle",
|
||||
nameGap: 20,
|
||||
nameTextStyle: {
|
||||
fontSize: 12 * fontScale,
|
||||
color: textColor,
|
||||
},
|
||||
axisTick: axisTick,
|
||||
position: "right",
|
||||
alignTicks: true,
|
||||
axisLine: axisLine,
|
||||
splitLine: {
|
||||
show: false,
|
||||
},
|
||||
axisLabel: {
|
||||
fontSize: 12 * fontScale,
|
||||
color: textColor,
|
||||
},
|
||||
},
|
||||
],
|
||||
series: [
|
||||
{
|
||||
type: "line",
|
||||
name: "Subsidy (USD)",
|
||||
stack: "Total",
|
||||
areaStyle: {},
|
||||
symbol: "none",
|
||||
lineStyle: {
|
||||
width: 0,
|
||||
},
|
||||
data: chartData.map((row) => row.subsidy_usd),
|
||||
},
|
||||
{
|
||||
type: "line",
|
||||
name: "Fees (USD)",
|
||||
stack: "Total",
|
||||
areaStyle: {},
|
||||
symbol: "none",
|
||||
lineStyle: {
|
||||
width: 0,
|
||||
},
|
||||
data: chartData.map((row) => row.totalfee_usd),
|
||||
},
|
||||
{
|
||||
type: "line",
|
||||
name: "Total (USD)",
|
||||
symbol: "none",
|
||||
lineStyle: {
|
||||
width: 1,
|
||||
color: textColor,
|
||||
},
|
||||
data: chartData.map((row) => row.total_reward_usd),
|
||||
},
|
||||
{
|
||||
type: "line",
|
||||
yAxisIndex: 1,
|
||||
name: "Block Subsidy (BTC)",
|
||||
symbol: "none",
|
||||
lineStyle: {
|
||||
width: 3,
|
||||
},
|
||||
data: chartData.map((row) => row.block_subsidy),
|
||||
},
|
||||
],
|
||||
};
|
||||
chart.setOption(option, true);
|
||||
}
|
||||
|
||||
// listen for filter events for this target
|
||||
document.addEventListener("filterChange", function(event) {
|
||||
eventDetail = event.detail;
|
||||
if (eventDetail.filterActions.includes("refresh")) {
|
||||
chartData = [];
|
||||
query = queryConstructor();
|
||||
fetchDataForChart(query);
|
||||
updateChart(chartData);
|
||||
}
|
||||
});
|
||||
|
||||
let query = queryConstructor();
|
||||
fetchDataForChart(query);
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", function() {
|
||||
chartData = [];
|
||||
let chartDom = document.getElementById("miner-rewards-chart");
|
||||
let myChart = echarts.init(chartDom);
|
||||
|
||||
const filterPeriods = { "7 day": 7, "28 day": 28, "365 day": 365, "2 years": 730, "5 years": 1826, "10 years": 3652, "all time": 10000 };
|
||||
dropDownFilter("days_ago_dropdown_filter", "days_ago", ["miner-rewards-chart"], filterPeriods, "365 day")
|
||||
|
||||
createChart(
|
||||
chart = myChart,
|
||||
endpoint = "miner_rewards",
|
||||
xAxisType = "category",
|
||||
);
|
||||
});
|
||||
|
108
static/js/feerate-percentile.js
Normal file
108
static/js/feerate-percentile.js
Normal file
|
@ -0,0 +1,108 @@
|
|||
let dataArr = [];
|
||||
const myChart = echarts.init(document.getElementById("chart"));
|
||||
|
||||
async function fetchDataForChart() {
|
||||
try {
|
||||
const apiEndpoint =
|
||||
"https://api.bitlab21.com/get_json/final__feerate_percentiles.json";
|
||||
const response = await fetch(apiEndpoint);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
const dataArr = await response.json();
|
||||
initEchart(dataArr);
|
||||
} catch (error) {
|
||||
console.error("Fetching data failed:", error);
|
||||
}
|
||||
}
|
||||
|
||||
function initEchart(dataArr) {
|
||||
const option = {
|
||||
backgroundColor: backgroundColor,
|
||||
tooltip: {
|
||||
...tooltip,
|
||||
valueFormatter: (value) => `${value.toFixed(0)} sats/vByte`,
|
||||
},
|
||||
toolbox: toolboxParams,
|
||||
xAxis: {
|
||||
data: dataArr.map((row) => row.date),
|
||||
axisTick: axisTick,
|
||||
axisLabel: axisLabel,
|
||||
axisLine: axisLine,
|
||||
},
|
||||
yAxis: {
|
||||
axisTick: axisTick,
|
||||
splitLine: {
|
||||
show: false,
|
||||
},
|
||||
axisLabel: axisLabel,
|
||||
axisLine: axisLine,
|
||||
},
|
||||
grid: grid,
|
||||
dataZoom: dataZoom((start = 98)),
|
||||
series: [
|
||||
{
|
||||
type: "line",
|
||||
id: "min-feerate",
|
||||
name: "min",
|
||||
showSymbol: false,
|
||||
barCategoryGap: "0%",
|
||||
data: [0],
|
||||
},
|
||||
{
|
||||
type: "bar",
|
||||
stack: "value",
|
||||
name: "10th",
|
||||
barCategoryGap: "0%",
|
||||
data: dataArr.map((row) => row.feerate_10th),
|
||||
},
|
||||
{
|
||||
type: "bar",
|
||||
stack: "value",
|
||||
name: "25th",
|
||||
barCategoryGap: "0%",
|
||||
data: dataArr.map((row) => row.feerate_25th),
|
||||
},
|
||||
{
|
||||
type: "bar",
|
||||
stack: "value",
|
||||
name: "50th",
|
||||
barCategoryGap: "0%",
|
||||
data: dataArr.map((row) => row.feerate_50th),
|
||||
},
|
||||
{
|
||||
type: "line",
|
||||
id: "mean-feerate",
|
||||
name: "mean",
|
||||
showSymbol: false,
|
||||
barCategoryGap: "0%",
|
||||
data: [0],
|
||||
},
|
||||
{
|
||||
type: "bar",
|
||||
stack: "value",
|
||||
name: "75th",
|
||||
barCategoryGap: "0%",
|
||||
data: dataArr.map((row) => row.feerate_75th),
|
||||
},
|
||||
{
|
||||
type: "bar",
|
||||
stack: "value",
|
||||
name: "90th",
|
||||
barCategoryGap: "0%",
|
||||
data: dataArr.map((row) => row.feerate_90th),
|
||||
},
|
||||
{
|
||||
type: "line",
|
||||
id: "max-feerate",
|
||||
name: "max",
|
||||
showSymbol: false,
|
||||
barCategoryGap: "0%",
|
||||
data: [0],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
myChart.setOption(option);
|
||||
}
|
||||
fetchDataForChart();
|
109
static/js/hashrate.js
Normal file
109
static/js/hashrate.js
Normal file
|
@ -0,0 +1,109 @@
|
|||
let dataArr = [];
|
||||
const myChart = echarts.init(document.getElementById("chart"));
|
||||
|
||||
async function fetchDataForChart() {
|
||||
try {
|
||||
const apiEndpoint =
|
||||
"https://api.bitlab21.com/get_json/final__hashrate.json";
|
||||
const response = await fetch(apiEndpoint);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
const dataArr = await response.json();
|
||||
initEchart(dataArr);
|
||||
} catch (error) {
|
||||
console.error("Fetching data failed:", error);
|
||||
}
|
||||
}
|
||||
|
||||
function initEchart(dataArr) {
|
||||
const option = {
|
||||
backgroundColor: backgroundColor,
|
||||
tooltip: {
|
||||
...tooltip,
|
||||
valueFormatter(value, index) {
|
||||
return nFormatter(value, 0);
|
||||
},
|
||||
},
|
||||
toolbox: toolboxParams,
|
||||
xAxis: {
|
||||
data: dataArr.map((row) => row.date),
|
||||
axisTick: axisTick,
|
||||
axisLabel: axisLabel,
|
||||
axisLine: axisLine,
|
||||
},
|
||||
grid: grid,
|
||||
dataZoom: dataZoom(),
|
||||
yAxis: [
|
||||
{
|
||||
type: "value",
|
||||
name: "Hashrate (H/s)",
|
||||
nameLocation: "middle",
|
||||
nameGap: 30,
|
||||
nameTextStyle: textStyleMain,
|
||||
position: "left",
|
||||
alignTicks: true,
|
||||
axisTick: axisTick,
|
||||
splitLine: {
|
||||
show: false,
|
||||
},
|
||||
axisLine: axisLine,
|
||||
axisLabel: {
|
||||
fontSize: 12 * fontScale,
|
||||
color: textColor,
|
||||
formatter(value, index) {
|
||||
return nFormatter(value, 0);
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "value",
|
||||
name: "Difficulty",
|
||||
nameLocation: "middle",
|
||||
nameGap: 30,
|
||||
nameTextStyle: textStyleMain,
|
||||
axisTick: axisTick,
|
||||
position: "right",
|
||||
alignTicks: true,
|
||||
axisLine: axisLine,
|
||||
splitLine: {
|
||||
show: false,
|
||||
},
|
||||
axisLabel: {
|
||||
fontSize: 12 * fontScale,
|
||||
color: textColor,
|
||||
formatter(value, index) {
|
||||
return nFormatter(value, 0);
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
series: [
|
||||
{
|
||||
type: "line",
|
||||
name: "Hashrate",
|
||||
barCategoryGap: "0%",
|
||||
data: dataArr.map((row) => row.hashrate),
|
||||
},
|
||||
{
|
||||
type: "line",
|
||||
color: "red",
|
||||
id: "rolling-average",
|
||||
name: "MA28",
|
||||
showSymbol: false,
|
||||
barCategoryGap: "0%",
|
||||
data: dataArr.map((row) => row.hashrate28),
|
||||
},
|
||||
{
|
||||
type: "line",
|
||||
yAxisIndex: 1,
|
||||
name: "Difficulty",
|
||||
barCategoryGap: "0%",
|
||||
data: dataArr.map((row) => row.difficulty),
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
myChart.setOption(option);
|
||||
}
|
||||
fetchDataForChart();
|
45
static/js/lib/echarts.min.js
vendored
45
static/js/lib/echarts.min.js
vendored
File diff suppressed because one or more lines are too long
|
@ -1,64 +0,0 @@
|
|||
function queryConstructor(customFilters = {}) {
|
||||
let filters = document.querySelectorAll(".filter");
|
||||
let queryObject = {};
|
||||
|
||||
Object.assign(queryObject, customFilters);
|
||||
|
||||
filters.forEach((filter) => {
|
||||
const filterId = filter.filterId;
|
||||
const filterValue = filter.value;
|
||||
queryObject[filterId] = filterValue;
|
||||
});
|
||||
|
||||
let queryString = `query=${JSON.stringify(queryObject)}`;
|
||||
|
||||
return queryString;
|
||||
}
|
||||
|
||||
function dispatchDropdownEvent(selectElement, filterId, filterTargets) {
|
||||
const event = new CustomEvent('filterChange', {
|
||||
detail: {
|
||||
filterId: filterId,
|
||||
filterValue: selectElement.value,
|
||||
filterActions: ["refresh"],
|
||||
filterTargets: filterTargets
|
||||
}
|
||||
});
|
||||
document.dispatchEvent(event);
|
||||
}
|
||||
|
||||
function dropDownFilter(domId, filterId, filterTargets, options, defaultKey) {
|
||||
domFilter = document.getElementById(domId);
|
||||
domFilter.filterId = filterId;
|
||||
for (const [key, value] of Object.entries(options)) {
|
||||
const option = document.createElement('option');
|
||||
option.value = value;
|
||||
option.textContent = key;
|
||||
domFilter.appendChild(option);
|
||||
if (key == defaultKey) {
|
||||
option.selected = true;
|
||||
}
|
||||
}
|
||||
dispatchDropdownEvent(domFilter, filterId, filterTargets)
|
||||
domFilter.addEventListener('change', () => dispatchDropdownEvent(domFilter, filterId, filterTargets));
|
||||
}
|
||||
|
||||
function nFormatter(value, digits) {
|
||||
const lookup = [
|
||||
{ value: 1, symbol: "" },
|
||||
{ value: 1e3, symbol: "k" },
|
||||
{ value: 1e6, symbol: "M" },
|
||||
{ value: 1e9, symbol: "G" },
|
||||
{ value: 1e12, symbol: "T" },
|
||||
{ value: 1e15, symbol: "P" },
|
||||
{ value: 1e18, symbol: "E" },
|
||||
];
|
||||
const rx = /\.0+$|(\.[0-9]*[1-9])0+$/;
|
||||
const item = lookup
|
||||
.slice()
|
||||
.reverse()
|
||||
.find((item) => value >= item.value);
|
||||
return item
|
||||
? (value / item.value).toFixed(digits).replace(rx, "$1") + item.symbol
|
||||
: "0";
|
||||
}
|
|
@ -1,495 +0,0 @@
|
|||
/*
|
||||
SortTable
|
||||
version 2
|
||||
7th April 2007
|
||||
Stuart Langridge, http://www.kryogenix.org/code/browser/sorttable/
|
||||
|
||||
Instructions:
|
||||
Download this file
|
||||
Add <script src="sorttable.js"></script> to your HTML
|
||||
Add class="sortable" to any table you'd like to make sortable
|
||||
Click on the headers to sort
|
||||
|
||||
Thanks to many, many people for contributions and suggestions.
|
||||
Licenced as X11: http://www.kryogenix.org/code/browser/licence.html
|
||||
This basically means: do what you want with it.
|
||||
*/
|
||||
|
||||
|
||||
var stIsIE = /*@cc_on!@*/false;
|
||||
|
||||
sorttable = {
|
||||
init: function() {
|
||||
// quit if this function has already been called
|
||||
if (arguments.callee.done) return;
|
||||
// flag this function so we don't do the same thing twice
|
||||
arguments.callee.done = true;
|
||||
// kill the timer
|
||||
if (_timer) clearInterval(_timer);
|
||||
|
||||
if (!document.createElement || !document.getElementsByTagName) return;
|
||||
|
||||
sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
|
||||
|
||||
forEach(document.getElementsByTagName('table'), function(table) {
|
||||
if (table.className.search(/\bsortable\b/) != -1) {
|
||||
sorttable.makeSortable(table);
|
||||
}
|
||||
});
|
||||
|
||||
},
|
||||
|
||||
makeSortable: function(table) {
|
||||
if (table.getElementsByTagName('thead').length == 0) {
|
||||
// table doesn't have a tHead. Since it should have, create one and
|
||||
// put the first table row in it.
|
||||
the = document.createElement('thead');
|
||||
the.appendChild(table.rows[0]);
|
||||
table.insertBefore(the,table.firstChild);
|
||||
}
|
||||
// Safari doesn't support table.tHead, sigh
|
||||
if (table.tHead == null) table.tHead = table.getElementsByTagName('thead')[0];
|
||||
|
||||
if (table.tHead.rows.length != 1) return; // can't cope with two header rows
|
||||
|
||||
// Sorttable v1 put rows with a class of "sortbottom" at the bottom (as
|
||||
// "total" rows, for example). This is B&R, since what you're supposed
|
||||
// to do is put them in a tfoot. So, if there are sortbottom rows,
|
||||
// for backwards compatibility, move them to tfoot (creating it if needed).
|
||||
sortbottomrows = [];
|
||||
for (var i=0; i<table.rows.length; i++) {
|
||||
if (table.rows[i].className.search(/\bsortbottom\b/) != -1) {
|
||||
sortbottomrows[sortbottomrows.length] = table.rows[i];
|
||||
}
|
||||
}
|
||||
if (sortbottomrows) {
|
||||
if (table.tFoot == null) {
|
||||
// table doesn't have a tfoot. Create one.
|
||||
tfo = document.createElement('tfoot');
|
||||
table.appendChild(tfo);
|
||||
}
|
||||
for (var i=0; i<sortbottomrows.length; i++) {
|
||||
tfo.appendChild(sortbottomrows[i]);
|
||||
}
|
||||
delete sortbottomrows;
|
||||
}
|
||||
|
||||
// work through each column and calculate its type
|
||||
headrow = table.tHead.rows[0].cells;
|
||||
for (var i=0; i<headrow.length; i++) {
|
||||
// manually override the type with a sorttable_type attribute
|
||||
if (!headrow[i].className.match(/\bsorttable_nosort\b/)) { // skip this col
|
||||
mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);
|
||||
if (mtch) { override = mtch[1]; }
|
||||
if (mtch && typeof sorttable["sort_"+override] == 'function') {
|
||||
headrow[i].sorttable_sortfunction = sorttable["sort_"+override];
|
||||
} else {
|
||||
headrow[i].sorttable_sortfunction = sorttable.guessType(table,i);
|
||||
}
|
||||
// make it clickable to sort
|
||||
headrow[i].sorttable_columnindex = i;
|
||||
headrow[i].sorttable_tbody = table.tBodies[0];
|
||||
dean_addEvent(headrow[i],"click", sorttable.innerSortFunction = function(e) {
|
||||
|
||||
if (this.className.search(/\bsorttable_sorted\b/) != -1) {
|
||||
// if we're already sorted by this column, just
|
||||
// reverse the table, which is quicker
|
||||
sorttable.reverse(this.sorttable_tbody);
|
||||
this.className = this.className.replace('sorttable_sorted',
|
||||
'sorttable_sorted_reverse');
|
||||
this.removeChild(document.getElementById('sorttable_sortfwdind'));
|
||||
sortrevind = document.createElement('span');
|
||||
sortrevind.id = "sorttable_sortrevind";
|
||||
sortrevind.innerHTML = stIsIE ? ' <font face="webdings">5</font>' : ' ▴';
|
||||
this.appendChild(sortrevind);
|
||||
return;
|
||||
}
|
||||
if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {
|
||||
// if we're already sorted by this column in reverse, just
|
||||
// re-reverse the table, which is quicker
|
||||
sorttable.reverse(this.sorttable_tbody);
|
||||
this.className = this.className.replace('sorttable_sorted_reverse',
|
||||
'sorttable_sorted');
|
||||
this.removeChild(document.getElementById('sorttable_sortrevind'));
|
||||
sortfwdind = document.createElement('span');
|
||||
sortfwdind.id = "sorttable_sortfwdind";
|
||||
sortfwdind.innerHTML = stIsIE ? ' <font face="webdings">6</font>' : ' ▾';
|
||||
this.appendChild(sortfwdind);
|
||||
return;
|
||||
}
|
||||
|
||||
// remove sorttable_sorted classes
|
||||
theadrow = this.parentNode;
|
||||
forEach(theadrow.childNodes, function(cell) {
|
||||
if (cell.nodeType == 1) { // an element
|
||||
cell.className = cell.className.replace('sorttable_sorted_reverse','');
|
||||
cell.className = cell.className.replace('sorttable_sorted','');
|
||||
}
|
||||
});
|
||||
sortfwdind = document.getElementById('sorttable_sortfwdind');
|
||||
if (sortfwdind) { sortfwdind.parentNode.removeChild(sortfwdind); }
|
||||
sortrevind = document.getElementById('sorttable_sortrevind');
|
||||
if (sortrevind) { sortrevind.parentNode.removeChild(sortrevind); }
|
||||
|
||||
this.className += ' sorttable_sorted';
|
||||
sortfwdind = document.createElement('span');
|
||||
sortfwdind.id = "sorttable_sortfwdind";
|
||||
sortfwdind.innerHTML = stIsIE ? ' <font face="webdings">6</font>' : ' ▾';
|
||||
this.appendChild(sortfwdind);
|
||||
|
||||
// build an array to sort. This is a Schwartzian transform thing,
|
||||
// i.e., we "decorate" each row with the actual sort key,
|
||||
// sort based on the sort keys, and then put the rows back in order
|
||||
// which is a lot faster because you only do getInnerText once per row
|
||||
row_array = [];
|
||||
col = this.sorttable_columnindex;
|
||||
rows = this.sorttable_tbody.rows;
|
||||
for (var j=0; j<rows.length; j++) {
|
||||
row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]];
|
||||
}
|
||||
/* If you want a stable sort, uncomment the following line */
|
||||
//sorttable.shaker_sort(row_array, this.sorttable_sortfunction);
|
||||
/* and comment out this one */
|
||||
row_array.sort(this.sorttable_sortfunction);
|
||||
|
||||
tb = this.sorttable_tbody;
|
||||
for (var j=0; j<row_array.length; j++) {
|
||||
tb.appendChild(row_array[j][1]);
|
||||
}
|
||||
|
||||
delete row_array;
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
guessType: function(table, column) {
|
||||
// guess the type of a column based on its first non-blank row
|
||||
sortfn = sorttable.sort_alpha;
|
||||
for (var i=0; i<table.tBodies[0].rows.length; i++) {
|
||||
text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]);
|
||||
if (text != '') {
|
||||
if (text.match(/^-?[£$¤]?[\d,.]+%?$/)) {
|
||||
return sorttable.sort_numeric;
|
||||
}
|
||||
// check for a date: dd/mm/yyyy or dd/mm/yy
|
||||
// can have / or . or - as separator
|
||||
// can be mm/dd as well
|
||||
possdate = text.match(sorttable.DATE_RE)
|
||||
if (possdate) {
|
||||
// looks like a date
|
||||
first = parseInt(possdate[1]);
|
||||
second = parseInt(possdate[2]);
|
||||
if (first > 12) {
|
||||
// definitely dd/mm
|
||||
return sorttable.sort_ddmm;
|
||||
} else if (second > 12) {
|
||||
return sorttable.sort_mmdd;
|
||||
} else {
|
||||
// looks like a date, but we can't tell which, so assume
|
||||
// that it's dd/mm (English imperialism!) and keep looking
|
||||
sortfn = sorttable.sort_ddmm;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return sortfn;
|
||||
},
|
||||
|
||||
getInnerText: function(node) {
|
||||
// gets the text we want to use for sorting for a cell.
|
||||
// strips leading and trailing whitespace.
|
||||
// this is *not* a generic getInnerText function; it's special to sorttable.
|
||||
// for example, you can override the cell text with a customkey attribute.
|
||||
// it also gets .value for <input> fields.
|
||||
|
||||
if (!node) return "";
|
||||
|
||||
hasInputs = (typeof node.getElementsByTagName == 'function') &&
|
||||
node.getElementsByTagName('input').length;
|
||||
|
||||
if (node.getAttribute("sorttable_customkey") != null) {
|
||||
return node.getAttribute("sorttable_customkey");
|
||||
}
|
||||
else if (typeof node.textContent != 'undefined' && !hasInputs) {
|
||||
return node.textContent.replace(/^\s+|\s+$/g, '');
|
||||
}
|
||||
else if (typeof node.innerText != 'undefined' && !hasInputs) {
|
||||
return node.innerText.replace(/^\s+|\s+$/g, '');
|
||||
}
|
||||
else if (typeof node.text != 'undefined' && !hasInputs) {
|
||||
return node.text.replace(/^\s+|\s+$/g, '');
|
||||
}
|
||||
else {
|
||||
switch (node.nodeType) {
|
||||
case 3:
|
||||
if (node.nodeName.toLowerCase() == 'input') {
|
||||
return node.value.replace(/^\s+|\s+$/g, '');
|
||||
}
|
||||
case 4:
|
||||
return node.nodeValue.replace(/^\s+|\s+$/g, '');
|
||||
break;
|
||||
case 1:
|
||||
case 11:
|
||||
var innerText = '';
|
||||
for (var i = 0; i < node.childNodes.length; i++) {
|
||||
innerText += sorttable.getInnerText(node.childNodes[i]);
|
||||
}
|
||||
return innerText.replace(/^\s+|\s+$/g, '');
|
||||
break;
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
reverse: function(tbody) {
|
||||
// reverse the rows in a tbody
|
||||
newrows = [];
|
||||
for (var i=0; i<tbody.rows.length; i++) {
|
||||
newrows[newrows.length] = tbody.rows[i];
|
||||
}
|
||||
for (var i=newrows.length-1; i>=0; i--) {
|
||||
tbody.appendChild(newrows[i]);
|
||||
}
|
||||
delete newrows;
|
||||
},
|
||||
|
||||
/* sort functions
|
||||
each sort function takes two parameters, a and b
|
||||
you are comparing a[0] and b[0] */
|
||||
sort_numeric: function(a,b) {
|
||||
aa = parseFloat(a[0].replace(/[^0-9.-]/g,''));
|
||||
if (isNaN(aa)) aa = 0;
|
||||
bb = parseFloat(b[0].replace(/[^0-9.-]/g,''));
|
||||
if (isNaN(bb)) bb = 0;
|
||||
return aa-bb;
|
||||
},
|
||||
sort_alpha: function(a,b) {
|
||||
if (a[0]==b[0]) return 0;
|
||||
if (a[0]<b[0]) return -1;
|
||||
return 1;
|
||||
},
|
||||
sort_ddmm: function(a,b) {
|
||||
mtch = a[0].match(sorttable.DATE_RE);
|
||||
y = mtch[3]; m = mtch[2]; d = mtch[1];
|
||||
if (m.length == 1) m = '0'+m;
|
||||
if (d.length == 1) d = '0'+d;
|
||||
dt1 = y+m+d;
|
||||
mtch = b[0].match(sorttable.DATE_RE);
|
||||
y = mtch[3]; m = mtch[2]; d = mtch[1];
|
||||
if (m.length == 1) m = '0'+m;
|
||||
if (d.length == 1) d = '0'+d;
|
||||
dt2 = y+m+d;
|
||||
if (dt1==dt2) return 0;
|
||||
if (dt1<dt2) return -1;
|
||||
return 1;
|
||||
},
|
||||
sort_mmdd: function(a,b) {
|
||||
mtch = a[0].match(sorttable.DATE_RE);
|
||||
y = mtch[3]; d = mtch[2]; m = mtch[1];
|
||||
if (m.length == 1) m = '0'+m;
|
||||
if (d.length == 1) d = '0'+d;
|
||||
dt1 = y+m+d;
|
||||
mtch = b[0].match(sorttable.DATE_RE);
|
||||
y = mtch[3]; d = mtch[2]; m = mtch[1];
|
||||
if (m.length == 1) m = '0'+m;
|
||||
if (d.length == 1) d = '0'+d;
|
||||
dt2 = y+m+d;
|
||||
if (dt1==dt2) return 0;
|
||||
if (dt1<dt2) return -1;
|
||||
return 1;
|
||||
},
|
||||
|
||||
shaker_sort: function(list, comp_func) {
|
||||
// A stable sort function to allow multi-level sorting of data
|
||||
// see: http://en.wikipedia.org/wiki/Cocktail_sort
|
||||
// thanks to Joseph Nahmias
|
||||
var b = 0;
|
||||
var t = list.length - 1;
|
||||
var swap = true;
|
||||
|
||||
while(swap) {
|
||||
swap = false;
|
||||
for(var i = b; i < t; ++i) {
|
||||
if ( comp_func(list[i], list[i+1]) > 0 ) {
|
||||
var q = list[i]; list[i] = list[i+1]; list[i+1] = q;
|
||||
swap = true;
|
||||
}
|
||||
} // for
|
||||
t--;
|
||||
|
||||
if (!swap) break;
|
||||
|
||||
for(var i = t; i > b; --i) {
|
||||
if ( comp_func(list[i], list[i-1]) < 0 ) {
|
||||
var q = list[i]; list[i] = list[i-1]; list[i-1] = q;
|
||||
swap = true;
|
||||
}
|
||||
} // for
|
||||
b++;
|
||||
|
||||
} // while(swap)
|
||||
}
|
||||
}
|
||||
|
||||
/* ******************************************************************
|
||||
Supporting functions: bundled here to avoid depending on a library
|
||||
****************************************************************** */
|
||||
|
||||
// Dean Edwards/Matthias Miller/John Resig
|
||||
|
||||
/* for Mozilla/Opera9 */
|
||||
if (document.addEventListener) {
|
||||
document.addEventListener("DOMContentLoaded", sorttable.init, false);
|
||||
}
|
||||
|
||||
/* for Internet Explorer */
|
||||
/*@cc_on @*/
|
||||
/*@if (@_win32)
|
||||
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
|
||||
var script = document.getElementById("__ie_onload");
|
||||
script.onreadystatechange = function() {
|
||||
if (this.readyState == "complete") {
|
||||
sorttable.init(); // call the onload handler
|
||||
}
|
||||
};
|
||||
/*@end @*/
|
||||
|
||||
/* for Safari */
|
||||
if (/WebKit/i.test(navigator.userAgent)) { // sniff
|
||||
var _timer = setInterval(function() {
|
||||
if (/loaded|complete/.test(document.readyState)) {
|
||||
sorttable.init(); // call the onload handler
|
||||
}
|
||||
}, 10);
|
||||
}
|
||||
|
||||
/* for other browsers */
|
||||
window.onload = sorttable.init;
|
||||
|
||||
// written by Dean Edwards, 2005
|
||||
// with input from Tino Zijdel, Matthias Miller, Diego Perini
|
||||
|
||||
// http://dean.edwards.name/weblog/2005/10/add-event/
|
||||
|
||||
function dean_addEvent(element, type, handler) {
|
||||
if (element.addEventListener) {
|
||||
element.addEventListener(type, handler, false);
|
||||
} else {
|
||||
// assign each event handler a unique ID
|
||||
if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;
|
||||
// create a hash table of event types for the element
|
||||
if (!element.events) element.events = {};
|
||||
// create a hash table of event handlers for each element/event pair
|
||||
var handlers = element.events[type];
|
||||
if (!handlers) {
|
||||
handlers = element.events[type] = {};
|
||||
// store the existing event handler (if there is one)
|
||||
if (element["on" + type]) {
|
||||
handlers[0] = element["on" + type];
|
||||
}
|
||||
}
|
||||
// store the event handler in the hash table
|
||||
handlers[handler.$$guid] = handler;
|
||||
// assign a global event handler to do all the work
|
||||
element["on" + type] = handleEvent;
|
||||
}
|
||||
};
|
||||
// a counter used to create unique IDs
|
||||
dean_addEvent.guid = 1;
|
||||
|
||||
function removeEvent(element, type, handler) {
|
||||
if (element.removeEventListener) {
|
||||
element.removeEventListener(type, handler, false);
|
||||
} else {
|
||||
// delete the event handler from the hash table
|
||||
if (element.events && element.events[type]) {
|
||||
delete element.events[type][handler.$$guid];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
function handleEvent(event) {
|
||||
var returnValue = true;
|
||||
// grab the event object (IE uses a global event object)
|
||||
event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
|
||||
// get a reference to the hash table of event handlers
|
||||
var handlers = this.events[event.type];
|
||||
// execute each event handler
|
||||
for (var i in handlers) {
|
||||
this.$$handleEvent = handlers[i];
|
||||
if (this.$$handleEvent(event) === false) {
|
||||
returnValue = false;
|
||||
}
|
||||
}
|
||||
return returnValue;
|
||||
};
|
||||
|
||||
function fixEvent(event) {
|
||||
// add W3C standard event methods
|
||||
event.preventDefault = fixEvent.preventDefault;
|
||||
event.stopPropagation = fixEvent.stopPropagation;
|
||||
return event;
|
||||
};
|
||||
fixEvent.preventDefault = function() {
|
||||
this.returnValue = false;
|
||||
};
|
||||
fixEvent.stopPropagation = function() {
|
||||
this.cancelBubble = true;
|
||||
}
|
||||
|
||||
// Dean's forEach: http://dean.edwards.name/base/forEach.js
|
||||
/*
|
||||
forEach, version 1.0
|
||||
Copyright 2006, Dean Edwards
|
||||
License: http://www.opensource.org/licenses/mit-license.php
|
||||
*/
|
||||
|
||||
// array-like enumeration
|
||||
if (!Array.forEach) { // mozilla already supports this
|
||||
Array.forEach = function(array, block, context) {
|
||||
for (var i = 0; i < array.length; i++) {
|
||||
block.call(context, array[i], i, array);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// generic enumeration
|
||||
Function.prototype.forEach = function(object, block, context) {
|
||||
for (var key in object) {
|
||||
if (typeof this.prototype[key] == "undefined") {
|
||||
block.call(context, object[key], key, object);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// character enumeration
|
||||
String.forEach = function(string, block, context) {
|
||||
Array.forEach(string.split(""), function(chr, index) {
|
||||
block.call(context, chr, index, string);
|
||||
});
|
||||
};
|
||||
|
||||
// globally resolve forEach enumeration
|
||||
var forEach = function(object, block, context) {
|
||||
if (object) {
|
||||
var resolve = Object; // default
|
||||
if (object instanceof Function) {
|
||||
// functions have a "length" property
|
||||
resolve = Function;
|
||||
} else if (object.forEach instanceof Function) {
|
||||
// the object implements a custom forEach method so use that
|
||||
object.forEach(block, context);
|
||||
return;
|
||||
} else if (typeof object == "string") {
|
||||
// the object is a string
|
||||
resolve = String;
|
||||
} else if (typeof object.length == "number") {
|
||||
// the object is array-like
|
||||
resolve = Array;
|
||||
}
|
||||
resolve.forEach(object, block, context);
|
||||
}
|
||||
};
|
||||
|
127
static/js/miner-rewards.js
Normal file
127
static/js/miner-rewards.js
Normal file
|
@ -0,0 +1,127 @@
|
|||
let dataArr = [];
|
||||
const myChart = echarts.init(document.getElementById("chart"));
|
||||
|
||||
async function fetchDataForChart() {
|
||||
try {
|
||||
const apiEndpoint =
|
||||
"https://api.bitlab21.com/get_json/final__miner_rewards.json";
|
||||
const response = await fetch(apiEndpoint);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
const dataArr = await response.json();
|
||||
initEchart(dataArr);
|
||||
} catch (error) {
|
||||
console.error("Fetching data failed:", error);
|
||||
}
|
||||
}
|
||||
|
||||
function initEchart(dataArr) {
|
||||
const option = {
|
||||
backgroundColor: backgroundColor,
|
||||
tooltip: tooltip,
|
||||
toolbox: toolboxParams,
|
||||
xAxis: {
|
||||
data: dataArr.map((row) => row.date),
|
||||
axisTick: axisTick,
|
||||
axisLabel: axisLabel,
|
||||
axisLine: axisLine,
|
||||
},
|
||||
grid: grid,
|
||||
dataZoom: dataZoom(97),
|
||||
yAxis: [
|
||||
{
|
||||
type: "value",
|
||||
name: "Rewards (USD)",
|
||||
nameLocation: "middle",
|
||||
nameGap: 35,
|
||||
nameTextStyle: textStyleMain,
|
||||
position: "left",
|
||||
alignTicks: true,
|
||||
axisTick: axisTick,
|
||||
axisLine: axisLine,
|
||||
splitLine: {
|
||||
show: false,
|
||||
},
|
||||
axisLabel: {
|
||||
...axisLabel,
|
||||
formatter(value, index) {
|
||||
return nFormatter(value, 0);
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "value",
|
||||
name: "Block Subsidy (BTC)",
|
||||
nameLocation: "middle",
|
||||
nameGap: 20,
|
||||
nameTextStyle: {
|
||||
fontSize: 12 * fontScale,
|
||||
color: textColor,
|
||||
},
|
||||
axisTick: axisTick,
|
||||
position: "right",
|
||||
alignTicks: true,
|
||||
axisLine: axisLine,
|
||||
splitLine: {
|
||||
show: false,
|
||||
},
|
||||
axisLabel: {
|
||||
fontSize: 12 * fontScale,
|
||||
color: textColor,
|
||||
},
|
||||
},
|
||||
],
|
||||
series: [
|
||||
{
|
||||
type: "line",
|
||||
name: "Daily Subsidy (USD)",
|
||||
smooth: true,
|
||||
stack: "Total",
|
||||
areaStyle: {},
|
||||
symbol: "none",
|
||||
lineStyle: {
|
||||
width: 0,
|
||||
},
|
||||
data: dataArr.map((row) => row.subsidy_usd),
|
||||
},
|
||||
{
|
||||
type: "line",
|
||||
name: "Daily Fees (USD)",
|
||||
smooth: true,
|
||||
stack: "Total",
|
||||
areaStyle: {},
|
||||
symbol: "none",
|
||||
lineStyle: {
|
||||
width: 0,
|
||||
},
|
||||
data: dataArr.map((row) => row.totalfee_usd),
|
||||
},
|
||||
{
|
||||
type: "line",
|
||||
name: "Daily Total Reward (USD)",
|
||||
smooth: true,
|
||||
symbol: "none",
|
||||
lineStyle: {
|
||||
width: 1,
|
||||
color: textColor,
|
||||
},
|
||||
data: dataArr.map((row) => row.total_reward_usd),
|
||||
},
|
||||
{
|
||||
type: "line",
|
||||
yAxisIndex: 1,
|
||||
name: "Block Subsidy (BTC)",
|
||||
symbol: "none",
|
||||
lineStyle: {
|
||||
width: 3,
|
||||
},
|
||||
data: dataArr.map((row) => row.block_subsidy),
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
myChart.setOption(option);
|
||||
}
|
||||
|
||||
fetchDataForChart();
|
Loading…
Add table
Reference in a new issue