uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
5ed67c2b5aa9f2294347dcdb
train
class
class StageGAN(object): def __init__(self, loss, discriminators, generator): """ Provides GAN model. :param loss: loss functions (scores real, scores pseudo), must return two expressions loss for discriminator training and generator loss for **minimization** . :param discriminators: a `craynn.Ex...
class StageGAN(object):
def __init__(self, loss, discriminators, generator): """ Provides GAN model. :param loss: loss functions (scores real, scores pseudo), must return two expressions loss for discriminator training and generator loss for **minimization** . :param discriminators: a `craynn.Expression` should return ...
self.cycle_loss_YXY = apply(self.loss_YXY, Y, YXY) self.loss_generator = reduce(lambda a, b: a + b, [ l for l in [ self.adv_loss_XtoY, self.adv_loss_YtoX, self.semi_cycle_loss_YX, self.semi_cycle_loss_XY, self.cycle_loss_YXY, self.cycle_loss_YXY ] if l is not None ]) ...
133
133
445
5
128
maxim-borisyak/craynn
craynn/networks/gans/gan.py
Python
StageGAN
StageGAN
135
186
135
135
600e2c829562f21a4b07481bffe0011665832c78
bigcode/the-stack
train
65a9b59b9ec01a0e801ff77c
train
class
class CycleGAN(object): def __init__(self, XtoY, discriminator_Y, YtoX=None, discriminator_X=None, loss_Y=energy_based(), loss_X=None, loss_XY=None, loss_YX=None, loss_XYX=None, loss_YXY=None ): self.XtoY = XtoY self.YtoX = YtoX s...
class CycleGAN(object):
def __init__(self, XtoY, discriminator_Y, YtoX=None, discriminator_X=None, loss_Y=energy_based(), loss_X=None, loss_XY=None, loss_YX=None, loss_XYX=None, loss_YXY=None ): self.XtoY = XtoY self.YtoX = YtoX self.discriminator_X = di...
.generator(Z) self.scores_real, = self.discriminator(X_real) self.scores_pseudo, = self.discriminator(self.X_pseudo) self.losses_discriminator, self.losses_generator = self.loss(self.scores_real, self.scores_pseudo) self.pure_loss_discriminator = T.mean(self.losses_discriminator) self.pure_loss_g...
186
186
621
5
180
maxim-borisyak/craynn
craynn/networks/gans/gan.py
Python
CycleGAN
CycleGAN
60
133
60
60
bad282b3777ad7c785d34a92cb56a461cb6e3a22
bigcode/the-stack
train
0281afc7a805cef50360b20c
train
class
@dataclass class Root: class Meta: name = "root" namespace = "http://xstest-tns" meeting: List["Root.Meeting"] = field( default_factory=list, metadata={ "name": "Meeting", "type": "Element", "namespace": "", "min_occurs": 1, ...
@dataclass class Root:
class Meta: name = "root" namespace = "http://xstest-tns" meeting: List["Root.Meeting"] = field( default_factory=list, metadata={ "name": "Meeting", "type": "Element", "namespace": "", "min_occurs": 1, } ) @datacla...
from dataclasses import dataclass, field from typing import List, Optional, Union __NAMESPACE__ = "http://xstest-tns" @dataclass class Root:
38
64
167
6
32
tefra/xsdata-w3c-tests
output/models/ibm_data/valid/s3_12/s3_12v11_xsd/s3_12v11.py
Python
Root
Root
7
39
7
8
b8bcd2973c83c5e8a503755666c41d0a95bc0120
bigcode/the-stack
train
a3756eaafd9073b166bb9007
train
function
def build_brief_link(complete, path, text, permission_needed=None): return { 'complete': complete, 'path': path, 'text': text, 'permissionNeeded': permission_needed }
def build_brief_link(complete, path, text, permission_needed=None):
return { 'complete': complete, 'path': path, 'text': text, 'permissionNeeded': permission_needed }
else: links.append( build_brief_link( False, '/2/buyer-award/{}'.format(brief.id), 'Download work order', permission_needed ) ) return links def build_brief_link(complete,...
64
64
47
16
47
AusDTO/dto-digitalmarketplace-api
app/api/business/brief_overview_business.py
Python
build_brief_link
build_brief_link
321
327
321
321
acd859e28c1fd640f1c870911e63515b2d1d566b
bigcode/the-stack
train
961bd9c0fcf4a4350f3c8631
train
function
def is_brief_section_complete(brief, section): from ...brief_utils import determine_required_fields if section['required']: required_fields = determine_required_fields(brief, section, enforce_required=False) return brief_contains_all_required_fields(brief, required_fields) else: retu...
def is_brief_section_complete(brief, section):
from ...brief_utils import determine_required_fields if section['required']: required_fields = determine_required_fields(brief, section, enforce_required=False) return brief_contains_all_required_fields(brief, required_fields) else: return brief_contains_any_optional_fields(brief, se...
required_fields: if not brief.data.get(key): return False return True def brief_contains_any_optional_fields(brief, optional_fields): for key in optional_fields: if brief.data.get(key): return True return False def is_brief_section_complete(brief, section):
64
64
73
11
52
AusDTO/dto-digitalmarketplace-api
app/api/business/brief_overview_business.py
Python
is_brief_section_complete
is_brief_section_complete
160
166
160
160
f5200fecb7bee9c418a674be875a8bef7934c7a5
bigcode/the-stack
train
36c2bc9203d09ba03a80d6e5
train
function
def get_evaluation_links(brief): links = [] # No green tick needed for evaluation template links.append( build_brief_link( False, get_path_for_brief_link(brief, '/static/media/documents/Scoring_Template.xlsx'), 'Evaluation template (XLSX 13KB)')) return link...
def get_evaluation_links(brief):
links = [] # No green tick needed for evaluation template links.append( build_brief_link( False, get_path_for_brief_link(brief, '/static/media/documents/Scoring_Template.xlsx'), 'Evaluation template (XLSX 13KB)')) return links
' else None ) links.append( build_brief_link( False, view_responses_path, 'View responses', None if current_user.has_permission('download_responses') else 'download_responses' ) ) return links def get_evaluation_links(brief):
64
64
73
8
55
AusDTO/dto-digitalmarketplace-api
app/api/business/brief_overview_business.py
Python
get_evaluation_links
get_evaluation_links
255
265
255
255
7c6dfc2f1308e82d58c725eb3cf42aca47b16a16
bigcode/the-stack
train
3b8922b410ffc352729aabb1
train
function
def can_close_opportunity_early(brief): seller_selector = brief.data.get('sellerSelector', '') invited_sellers = list(brief.data.get('sellers', {}).keys()) number_of_candidates = int(brief.data.get('numberOfSuppliers', 0)) if brief.status == 'live' and len(invited_sellers) == 1 and ( (brief.lot...
def can_close_opportunity_early(brief):
seller_selector = brief.data.get('sellerSelector', '') invited_sellers = list(brief.data.get('sellers', {}).keys()) number_of_candidates = int(brief.data.get('numberOfSuppliers', 0)) if brief.status == 'live' and len(invited_sellers) == 1 and ( (brief.lot.slug in ['rfx', 'training2'] and seller...
_closed_early_email, send_opportunity_withdrawn_email_to_buyers, send_opportunity_withdrawn_email_to_seller) from app.tasks import publish_tasks from app.tasks.s3 import create_responses_zip from app.validation import get_sections as get_validation_sections def can_close_...
68
68
227
10
57
AusDTO/dto-digitalmarketplace-api
app/api/business/brief_overview_business.py
Python
can_close_opportunity_early
can_close_opportunity_early
20
42
20
20
283d43a9b3191553b7e35e5e832a84b7d8579e29
bigcode/the-stack
train
13c9ab94c336ba27cf776347
train
function
def get_work_order_links(brief): links = [] old_work_order_creator = use_old_work_order_creator(brief.published_at) has_permission = current_user.has_permission('create_work_orders') permission_needed = None if has_permission else 'create_work_orders' # No need for green ticks to indicate completio...
def get_work_order_links(brief):
links = [] old_work_order_creator = use_old_work_order_creator(brief.published_at) has_permission = current_user.has_permission('create_work_orders') permission_needed = None if has_permission else 'create_work_orders' # No need for green ticks to indicate completion if brief.work_order: ...
) ) return links def get_evaluation_links(brief): links = [] # No green tick needed for evaluation template links.append( build_brief_link( False, get_path_for_brief_link(brief, '/static/media/documents/Scoring_Template.xlsx'), 'Evaluation templ...
89
89
299
8
80
AusDTO/dto-digitalmarketplace-api
app/api/business/brief_overview_business.py
Python
get_work_order_links
get_work_order_links
268
318
268
268
3b735e8062c2aea0674615b27d69de253d7cc754
bigcode/the-stack
train
8248048c8445243c6b8e8576
train
function
def withdraw_opportunity(user_id, brief_id, withdrawal_reason): brief = brief_service.get(brief_id) if not brief: raise NotFoundError('Opportunity {} does not exist'.format(brief_id)) if not brief_service.has_permission_to_brief(user_id, brief_id): raise UnauthorisedError('Not authorised to...
def withdraw_opportunity(user_id, brief_id, withdrawal_reason):
brief = brief_service.get(brief_id) if not brief: raise NotFoundError('Opportunity {} does not exist'.format(brief_id)) if not brief_service.has_permission_to_brief(user_id, brief_id): raise UnauthorisedError('Not authorised to withdraw opportunity {}'.format(brief_id)) if brief.status...
audit_type=audit_types.close_opportunity_early, data={ 'briefId': brief.id }, db_object=brief, user=user.email_address ) publish_tasks.brief.delay( publish_tasks.compress_brief(brief), 'closed_early', ...
105
105
350
13
91
AusDTO/dto-digitalmarketplace-api
app/api/business/brief_overview_business.py
Python
withdraw_opportunity
withdraw_opportunity
86
132
86
86
df8cb6a443f32a3685107aeba1b1e285f2d2b78a
bigcode/the-stack
train
0e8c209f8e60aa63c4d8d2c6
train
function
def brief_contains_any_optional_fields(brief, optional_fields): for key in optional_fields: if brief.data.get(key): return True return False
def brief_contains_any_optional_fields(brief, optional_fields):
for key in optional_fields: if brief.data.get(key): return True return False
=path, work_order_id=work_order_id, brief_id=brief.id) def brief_contains_all_required_fields(brief, required_fields): for key in required_fields: if not brief.data.get(key): return False return True def brief_contains_any_optional_fields(brief, optional_fields):
64
64
34
12
51
AusDTO/dto-digitalmarketplace-api
app/api/business/brief_overview_business.py
Python
brief_contains_any_optional_fields
brief_contains_any_optional_fields
152
157
152
152
144896d63a7a6f7edd7ed4dd2d82dcae362de7fd
bigcode/the-stack
train
e0b264be4208413d14e58ae4
train
function
def get_path_for_brief_link(brief, link, paths=None): path = '/buyers/frameworks/{}/requirements/{}/{}'.format(brief.framework.slug, brief.lot.slug, brief.id) work_order_id = brief.work_order.id if brief.work_order else None if paths: return paths[link].format(path=path, work_order_id=work_order_id)...
def get_path_for_brief_link(brief, link, paths=None):
path = '/buyers/frameworks/{}/requirements/{}/{}'.format(brief.framework.slug, brief.lot.slug, brief.id) work_order_id = brief.work_order.id if brief.work_order else None if paths: return paths[link].format(path=path, work_order_id=work_order_id) return link.format(path=path, work_order_id=work...
.brief.delay( publish_tasks.compress_brief(brief), 'withdrawn', email_address=user.email_address, name=user.name ) except Exception as e: rollbar.report_exc_info() return brief def get_path_for_brief_link(brief, link, paths=None):
64
64
103
15
48
AusDTO/dto-digitalmarketplace-api
app/api/business/brief_overview_business.py
Python
get_path_for_brief_link
get_path_for_brief_link
135
141
135
135
46b8721053d60499318b5f3a5915ac833eb7f960
bigcode/the-stack
train
61edb4e15762b4823dfc6361
train
function
def close_opportunity_early(user_id, brief_id): brief = brief_service.get(brief_id) if not brief: raise NotFoundError('Opportunity {} does not exist'.format(brief_id)) if not brief_service.has_permission_to_brief(user_id, brief_id): raise UnauthorisedError('Not authorised to close opportuni...
def close_opportunity_early(user_id, brief_id):
brief = brief_service.get(brief_id) if not brief: raise NotFoundError('Opportunity {} does not exist'.format(brief_id)) if not brief_service.has_permission_to_brief(user_id, brief_id): raise UnauthorisedError('Not authorised to close opportunity {}'.format(brief_id)) if not can_close_o...
=invited_seller_code, status='submitted' ).count() if brief.lot.slug in ['rfx', 'training2'] and response_count == 1: return True if brief.lot.slug == 'specialist' and response_count == number_of_candidates: return True return False def close_opportunit...
81
81
272
12
68
AusDTO/dto-digitalmarketplace-api
app/api/business/brief_overview_business.py
Python
close_opportunity_early
close_opportunity_early
45
83
45
45
1b165f0a1683c5438b93926d74f2fdb4954f3f56
bigcode/the-stack
train
13b9761dffba710ef3590bfc
train
function
def get_shortlist_links(brief): links = [] view_responses_path = ( get_path_for_brief_link(brief, '{path}/responses') if brief.status == 'closed' else None ) links.append( build_brief_link( False, view_responses_path, 'View responses', ...
def get_shortlist_links(brief):
links = [] view_responses_path = ( get_path_for_brief_link(brief, '{path}/responses') if brief.status == 'closed' else None ) links.append( build_brief_link( False, view_responses_path, 'View responses', None if current_user.has_p...
links.append( build_brief_link( brief.status == 'closed', answer_question_path, 'Answer a question', None if current_user.has_permission('answer_seller_questions') else 'answer_seller_questions' ) ) return links def get_shortlist_links(brief):
64
64
97
8
55
AusDTO/dto-digitalmarketplace-api
app/api/business/brief_overview_business.py
Python
get_shortlist_links
get_shortlist_links
236
252
236
236
3b7332401aff56d2dbed2c50dc144c000cffcd5a
bigcode/the-stack
train
588175a81087a5dcfcd7fed3
train
function
def build_section(links, title): return { 'links': links, 'title': title }
def build_section(links, title):
return { 'links': links, 'title': title }
) ) return links def build_brief_link(complete, path, text, permission_needed=None): return { 'complete': complete, 'path': path, 'text': text, 'permissionNeeded': permission_needed } def build_section(links, title):
64
64
25
8
56
AusDTO/dto-digitalmarketplace-api
app/api/business/brief_overview_business.py
Python
build_section
build_section
330
334
330
330
6230c2f4dd373c6896da84e5b1d20579172ca07f
bigcode/the-stack
train
b528de610796280913a788bd
train
function
def get_publish_links(brief): links = [] draft_brief = brief.status == 'draft' brief_builder_paths = { 'How long your brief will be open': '{path}/edit/how-long-your-brief-will-be-open/requirementsLength', 'Description of work': '{path}/description-of-work', 'Location': '{path}/edit/...
def get_publish_links(brief):
links = [] draft_brief = brief.status == 'draft' brief_builder_paths = { 'How long your brief will be open': '{path}/edit/how-long-your-brief-will-be-open/requirementsLength', 'Description of work': '{path}/description-of-work', 'Location': '{path}/edit/location/location', 'Q...
brief, required_fields): for key in required_fields: if not brief.data.get(key): return False return True def brief_contains_any_optional_fields(brief, optional_fields): for key in optional_fields: if brief.data.get(key): return True return False def is_brie...
142
143
477
7
135
AusDTO/dto-digitalmarketplace-api
app/api/business/brief_overview_business.py
Python
get_publish_links
get_publish_links
169
214
169
169
05fafc6325ef8c3bf788dd05c523b0a74ef33ca9
bigcode/the-stack
train
8679660c748c640eee0280c7
train
function
def brief_contains_all_required_fields(brief, required_fields): for key in required_fields: if not brief.data.get(key): return False return True
def brief_contains_all_required_fields(brief, required_fields):
for key in required_fields: if not brief.data.get(key): return False return True
if brief.work_order else None if paths: return paths[link].format(path=path, work_order_id=work_order_id) return link.format(path=path, work_order_id=work_order_id, brief_id=brief.id) def brief_contains_all_required_fields(brief, required_fields):
64
64
35
12
52
AusDTO/dto-digitalmarketplace-api
app/api/business/brief_overview_business.py
Python
brief_contains_all_required_fields
brief_contains_all_required_fields
144
149
144
144
9de1cd189cff82538ec1280fd32cfb602e6da0d5
bigcode/the-stack
train
0812d1e0e839d37a883e3500
train
function
def get_sections(brief): sections = [] sections.append(build_section(get_publish_links(brief), 'Publish your brief')) sections.append(build_section(get_live_links(brief), 'While the opportunity is live')) sections.append(build_section(get_shortlist_links(brief), 'Shortlist responses')) if brief.lo...
def get_sections(brief):
sections = [] sections.append(build_section(get_publish_links(brief), 'Publish your brief')) sections.append(build_section(get_live_links(brief), 'While the opportunity is live')) sections.append(build_section(get_shortlist_links(brief), 'Shortlist responses')) if brief.lot.slug == 'digital-profes...
=None): return { 'complete': complete, 'path': path, 'text': text, 'permissionNeeded': permission_needed } def build_section(links, title): return { 'links': links, 'title': title } def get_sections(brief):
64
64
119
6
58
AusDTO/dto-digitalmarketplace-api
app/api/business/brief_overview_business.py
Python
get_sections
get_sections
337
348
337
337
7bbaf8233d31a67535f4a4b24fd481b8222910bd
bigcode/the-stack
train
e0223c7122bec54227d54e83
train
function
def get_live_links(brief): links = [] # Answer a question is complete if the brief is closed answer_question_path = ( get_path_for_brief_link( brief, '/2/brief/{brief_id}/questions') if brief.status == 'live' else None) links.append( build_brief_link( ...
def get_live_links(brief):
links = [] # Answer a question is complete if the brief is closed answer_question_path = ( get_path_for_brief_link( brief, '/2/brief/{brief_id}/questions') if brief.status == 'live' else None) links.append( build_brief_link( brief.status == 'closed', ...
_path = get_path_for_brief_link(brief, '{path}/publish') if draft_brief else None links.append( build_brief_link( publish_completed, publish_path, 'Review and publish your requirements' ) ) return links def get_live_links(brief...
64
64
118
7
56
AusDTO/dto-digitalmarketplace-api
app/api/business/brief_overview_business.py
Python
get_live_links
get_live_links
217
233
217
217
1ba487a15ed6f591bedd742df8545b341788a517
bigcode/the-stack
train
0bc51f5945b0756131d805e3
train
function
def check_pkg_in_base_repo(deb_name): result = commands.getstatusoutput("apt-cache search %s" % deb_name) if result[0] == 0 and re.search("%s" % deb_name, result[1], re.I): return True else: return False
def check_pkg_in_base_repo(deb_name):
result = commands.getstatusoutput("apt-cache search %s" % deb_name) if result[0] == 0 and re.search("%s" % deb_name, result[1], re.I): return True else: return False
# -*- coding: utf-8 -*- import re import commands def check_pkg_in_base_repo(deb_name):
24
64
64
10
13
daniel-yavorovich/cpan2repo
cpan2repo/apt_cache.py
Python
check_pkg_in_base_repo
check_pkg_in_base_repo
6
12
6
6
78bb08d262b05741641e28a70573d064f7477186
bigcode/the-stack
train
d122fe0240b5cdc9a01a6e96
train
class
class RoundManagement: @staticmethod def save_description(listener, raw_description, audit_stream, working_directory): if '\n' not in raw_description: return newline_index = raw_description.find('\n') round_id = raw_description[:newline_index] last_fetched_round = R...
class RoundManagement: @staticmethod
def save_description(listener, raw_description, audit_stream, working_directory): if '\n' not in raw_description: return newline_index = raw_description.find('\n') round_id = raw_description[:newline_index] last_fetched_round = RoundManagement.get_last_fetched_round(work...
import os CHALLENGES_FOLDER = 'challenges' LAST_FETCHED_ROUND_PATH = '{}/XR.txt'.format(CHALLENGES_FOLDER) class RoundManagement: @staticmethod
40
97
324
8
32
DPNT-Sourcecode/CHK-hbjk01
virtualenv/Lib/site-packages/tdl/runner/round_management.py
Python
RoundManagement
RoundManagement
8
47
8
10
2cf9cc8eefd08673253f29797bfb0397d62ad242
bigcode/the-stack
train
9964ef72ee983c817b29054a
train
class
class User: def __init__(user): self.id = user.id self.date = '' #TODO self.code = ''
class User:
def __init__(user): self.id = user.id self.date = '' #TODO self.code = ''
class User:
3
64
31
3
0
jess-sys/TwentyTwo
Verifier.py
Python
User
User
1
6
1
2
e6a8eff80d0b834442f2539e9df25cf61319bd21
bigcode/the-stack
train
7164930e231e7c0179a8306a
train
class
class Verifier: users = [] @staticmethod def add(user): ''' Add a user to the list of users to verify ''' users.append(User(user)) @staticmethod def send_code(user, mail): ''' Send a mail with a verification code ''' i = len(self.users) - 1 while i > 0 and ...
class Verifier:
users = [] @staticmethod def add(user): ''' Add a user to the list of users to verify ''' users.append(User(user)) @staticmethod def send_code(user, mail): ''' Send a mail with a verification code ''' i = len(self.users) - 1 while i > 0 and user.id != users[...
class User: def __init__(user): self.id = user.id self.date = '' #TODO self.code = '' class Verifier:
35
64
163
4
31
jess-sys/TwentyTwo
Verifier.py
Python
Verifier
Verifier
8
34
8
9
953147407278e18bf1a71e0f3f3db720b4425c4e
bigcode/the-stack
train
3d0492fbe5355b31d55cb788
train
function
def api_docs(): """Open a browser and navigate to the geemap API documentation. """ import webbrowser url = 'https://geemap.readthedocs.io/en/latest/source/geemap.html#geemap-package' webbrowser.open_new_tab(url)
def api_docs():
"""Open a browser and navigate to the geemap API documentation. """ import webbrowser url = 'https://geemap.readthedocs.io/en/latest/source/geemap.html#geemap-package' webbrowser.open_new_tab(url)
the YouTube tutorials for geemap. """ import webbrowser url = 'https://www.youtube.com/playlist?list=PLAxJ4-o7ZoPccOFv1dCwvGI6TYnirRTg3' webbrowser.open_new_tab(url) def api_docs():
64
64
57
4
60
hugoledoux/geemap
geemap/geemap.py
Python
api_docs
api_docs
2,604
2,610
2,604
2,604
cb6cd75f455a41cab056819f71a9e7af21ab4f83
bigcode/the-stack
train
578946665a3a7b5f688af8f4
train
function
def ee_data_html(asset): """Generates HTML from an asset to be used in the HTML widget. Args: asset (dict): A dictionary containing an Earth Engine asset. Returns: str: A string containing HTML. """ template = ''' <html> <body> <h3>asset_title</h3> ...
def ee_data_html(asset):
"""Generates HTML from an asset to be used in the HTML widget. Args: asset (dict): A dictionary containing an Earth Engine asset. Returns: str: A string containing HTML. """ template = ''' <html> <body> <h3>asset_title</h3> <h4>Dataset Availa...
_url) try: if r.status_code != 200: html_page = urllib.request.urlopen(asset_url) soup = BeautifulSoup(html_page, features="html.parser") for img in soup.findAll('img'): if 'sample.png' in img.get('src'): thumbnail_url = img.get('src'...
97
97
324
6
90
hugoledoux/geemap
geemap/geemap.py
Python
ee_data_html
ee_data_html
4,415
4,454
4,415
4,415
eaf044bb171e30fbe51981d49d39e0e49768f4ab
bigcode/the-stack
train
c4cc7bc4c8b3d1eff662f67f
train
function
def minimum_bounding_box(geojson): """Gets the minimum bounding box for a geojson polygon. Args: geojson (dict): A geojson dictionary. Returns: tuple: Returns a tuple containing the minimum bounding box in the format of (lower_left(lat, lon), upper_right(lat, lon)), such as ((13, -130), (3...
def minimum_bounding_box(geojson):
"""Gets the minimum bounding box for a geojson polygon. Args: geojson (dict): A geojson dictionary. Returns: tuple: Returns a tuple containing the minimum bounding box in the format of (lower_left(lat, lon), upper_right(lat, lon)), such as ((13, -130), (32, -120)). """ coordinates ...
gamma' not in video_args.keys(): video_args['gamma'] = [1, 1, 1] download_ee_video(col, video_args, out_gif) return out_gif except Exception as e: print(e) return def minimum_bounding_box(geojson):
66
66
223
9
56
hugoledoux/geemap
geemap/geemap.py
Python
minimum_bounding_box
minimum_bounding_box
4,189
4,213
4,189
4,189
0d0e3c6b870851ec1ed7bb843e75d1e46d107e0d
bigcode/the-stack
train
2cd14b5b43505b1dc57f0c1f
train
function
def search_ee_data(keywords): """Searches Earth Engine data catalog. Args: keywords (str): Keywords to search for can be id, provider, tag and so on Returns: list: Returns a lit of assets. """ try: cmd = 'geeadd search --keywords "{}"'.format(str(keywords)) output =...
def search_ee_data(keywords):
"""Searches Earth Engine data catalog. Args: keywords (str): Keywords to search for can be id, provider, tag and so on Returns: list: Returns a lit of assets. """ try: cmd = 'geeadd search --keywords "{}"'.format(str(keywords)) output = os.popen(cmd).read() ...
if lat >= -90 and lat <= 90 and lon >= -180 and lat <= 180: return lat, lon else: return None except Exception as e: print(e) print('The lat-lon coordinates should be numbers only and separated by comma or space, such as 40.2, -100.3') return None def search...
87
87
291
8
78
hugoledoux/geemap
geemap/geemap.py
Python
search_ee_data
search_ee_data
4,340
4,375
4,340
4,340
3787ab1c745d1bf99df44928ded1dd1683ef2610
bigcode/the-stack
train
9b934ee14bc612173c4460eb
train
function
def ee_export_vector_to_drive(ee_object, description, folder, file_format='shp', selectors=None): """Exports Earth Engine FeatureCollection to Google Drive. other formats, including shp, csv, json, kml, and kmz. Args: ee_object (object): ee.FeatureCollection to export. description (str): File n...
def ee_export_vector_to_drive(ee_object, description, folder, file_format='shp', selectors=None):
"""Exports Earth Engine FeatureCollection to Google Drive. other formats, including shp, csv, json, kml, and kmz. Args: ee_object (object): ee.FeatureCollection to export. description (str): File name of the output file. folder (str): Folder name within Google Drive to save the exported...
) return try: if filetype == 'shp': z = zipfile.ZipFile(filename) z.extractall(os.path.dirname(filename)) os.remove(filename) filename = filename.replace('.zip', '.shp') print('Data downloaded to {}'.format(filename)) except Exception as ...
94
94
314
23
71
hugoledoux/geemap
geemap/geemap.py
Python
ee_export_vector_to_drive
ee_export_vector_to_drive
2,848
2,878
2,848
2,848
972e1c0054ba3814d201a9392ec61e3dea520032
bigcode/the-stack
train
1a525edd54b06f758d073960
train
function
def search_api_tree(keywords, api_tree): """Search Earth Engine API and return functions containing the specified keywords Args: keywords (str): The keywords to search for. api_tree (dict): The dictionary containing the Earth Engine API tree. Returns: object: An ipytree object/widg...
def search_api_tree(keywords, api_tree):
"""Search Earth Engine API and return functions containing the specified keywords Args: keywords (str): The keywords to search for. api_tree (dict): The dictionary containing the Earth Engine API tree. Returns: object: An ipytree object/widget. """ import warnings warni...
node.add_node(tree_dict[func]) if index == len(func_list) - 1: node = tree_dict[func_list[index]] node.icon = 'file' node.observe(handle_click, 'selected') return tree, tree_dict def search_api_tree(key...
64
64
113
10
53
hugoledoux/geemap
geemap/geemap.py
Python
search_api_tree
search_api_tree
4,745
4,764
4,745
4,745
4a875e3ac16cca4400a6d86d8da009eb598d0641
bigcode/the-stack
train
4261281f8edde33dd7ebe5d1
train
function
def create_code_cell(code='', where='below'): """Creates a code cell in the IPython Notebook. Args: code (str, optional): Code to fill the new code cell with. Defaults to ''. where (str, optional): Where to add the new code cell. It can be one of the following: above, below, at_bottom. Defaults...
def create_code_cell(code='', where='below'):
"""Creates a code cell in the IPython Notebook. Args: code (str, optional): Code to fill the new code cell with. Defaults to ''. where (str, optional): Where to add the new code cell. It can be one of the following: above, below, at_bottom. Defaults to 'below'. """ import base64 fr...
('asset_url', asset['asset_url']) # asset['thumbnail'] = ee_data_thumbnail(asset['id']) text = text.replace('thumbnail_url', asset['thumbnail_url']) return text except Exception as e: print(e) return def create_code_cell(code='', where='below'):
64
64
153
10
53
hugoledoux/geemap
geemap/geemap.py
Python
create_code_cell
create_code_cell
4,457
4,471
4,457
4,457
859fedaeeeefaff7539427fb265f672a37c19cd1
bigcode/the-stack
train
5b682aa7c491cc88c7187458
train
function
def check_install(package): """Checks whether a package is installed. If not, it will install the package. Args: package (str): The name of the package to check. """ import subprocess try: __import__(package) print('{} is already installed.'.format(package)) except Impo...
def check_install(package):
"""Checks whether a package is installed. If not, it will install the package. Args: package (str): The name of the package to check. """ import subprocess try: __import__(package) print('{} is already installed.'.format(package)) except ImportError: print('{} i...
# layout={'border': '1px solid black', 'width': '815px'}) out.clear_output(wait=True) display(out) with out: display(YouTubeVideo(id, width=800, height=450)) except Exception as e: print(e) def check_install(package):
64
64
134
5
59
hugoledoux/geemap
geemap/geemap.py
Python
check_install
check_install
2,633
2,651
2,633
2,633
b2de3df429cdcea6f8831e89ad981464e8e2ffc3
bigcode/the-stack
train
7ea7db123a1871908cb1abd1
train
function
def add_image_to_gif(in_gif, out_gif, in_image, xy=None, image_size=(80, 80), circle_mask=False): """Adds an image logo to a GIF image. Args: in_gif (str): Input file path to the GIF image. out_gif (str): Output file path to the GIF image. in_image (str): Input file path to the image. ...
def add_image_to_gif(in_gif, out_gif, in_image, xy=None, image_size=(80, 80), circle_mask=False):
"""Adds an image logo to a GIF image. Args: in_gif (str): Input file path to the GIF image. out_gif (str): Output file path to the GIF image. in_image (str): Input file path to the image. xy (tuple, optional): Top left corner of the text. It can be formatted like this: (10, 10) ...
(out_dir) # a = urlparse(url) # out_name = os.path.basename(a.path) # out_path = os.path.join(out_dir, out_name) # download_from_url(url, out_name, out_dir, unzip=False) # img = Image.open(out_path) # else: response = requests.get(url) ...
256
256
1,028
32
223
hugoledoux/geemap
geemap/geemap.py
Python
add_image_to_gif
add_image_to_gif
2,236
2,348
2,236
2,236
e530832ecce6771ab9667476fc4f78eb698f5048
bigcode/the-stack
train
da2f829df7af42f7d3514008
train
function
def system_fonts(show_full_path=False): """Gets a list of system fonts. # Common font locations: # Linux: /usr/share/fonts/TTF/ # Windows: C:\Windows\Fonts # macOS: System > Library > Fonts Args: show_full_path (bool, optional): Whether to show the full path of each sy...
def system_fonts(show_full_path=False):
"""Gets a list of system fonts. # Common font locations: # Linux: /usr/share/fonts/TTF/ # Windows: C:\Windows\Fonts # macOS: System > Library > Fonts Args: show_full_path (bool, optional): Whether to show the full path of each system font. Defaults to False. Retur...
.') return else: try: out_color = colour.Color(in_color) return out_color.hex_l except Exception as e: print('The provided color is invalid. Using the default black color.') print(e) return out_color def system_fonts(show_full_p...
64
64
184
8
55
hugoledoux/geemap
geemap/geemap.py
Python
system_fonts
system_fonts
2,000
2,030
2,000
2,000
53ae780e1a808994ed0b7ff180627c0eeeca8deb
bigcode/the-stack
train
0913dd9e37360ebab4f89b6b
train
function
def ee_initialize(): """Authenticates Earth Engine and initialize an Earth Engine session """ try: ee.Initialize() except: ee.Authenticate() ee.Initialize()
def ee_initialize():
"""Authenticates Earth Engine and initialize an Earth Engine session """ try: ee.Initialize() except: ee.Authenticate() ee.Initialize()
as plt from ipyfilechooser import FileChooser from ipyleaflet import * from ipytree import Tree, Node from IPython.display import display from .basemaps import ee_basemaps from .conversion import * from .legends import builtin_legends def ee_initialize():
64
64
38
4
59
hugoledoux/geemap
geemap/geemap.py
Python
ee_initialize
ee_initialize
24
32
24
24
32ded23569ff1b379c484afcdfca37303742dc65
bigcode/the-stack
train
9302e818d080252bbf9cbb8e
train
function
def download_ee_video(collection, video_args, out_gif): """Downloads a video thumbnail as a GIF image from Earth Engine. Args: collection (object): An ee.ImageCollection. video_args ([type]): Parameters for expring the video thumbnail. out_gif (str): File path to the output GIF. """...
def download_ee_video(collection, video_args, out_gif):
"""Downloads a video thumbnail as a GIF image from Earth Engine. Args: collection (object): An ee.ImageCollection. video_args ([type]): Parameters for expring the video thumbnail. out_gif (str): File path to the output GIF. """ import requests out_gif = os.path.abspath(out_...
ee_object.sampleRectangle( region=region, properties=properties, defaultValue=default_value) band_values = [] for band in bands: band_arr = band_arrs.get(band).getInfo() band_value = np.array(band_arr) band_values.append(band_value) image = np.d...
101
101
337
14
87
hugoledoux/geemap
geemap/geemap.py
Python
download_ee_video
download_ee_video
3,163
3,211
3,163
3,163
81a663ac9a73a3e74908a767f72a4850e1809524
bigcode/the-stack
train
f086e0c46569859ebd73ea36
train
function
def build_asset_tree(limit=100): import warnings import geeadd.ee_report as geeadd warnings.filterwarnings('ignore') ee_initialize() tree = Tree(multiple_selection=False) tree_dict = {} asset_types = {} asset_icons = { 'FOLDER': 'folder', 'TABLE': 'table', 'IM...
def build_asset_tree(limit=100):
import warnings import geeadd.ee_report as geeadd warnings.filterwarnings('ignore') ee_initialize() tree = Tree(multiple_selection=False) tree_dict = {} asset_types = {} asset_icons = { 'FOLDER': 'folder', 'TABLE': 'table', 'IMAGE': 'image', 'IMAGE_COLL...
: if text.value == '': print('Loading...') tree_widget.clear_output(wait=True) display(flags.docs) else: tree_widget.clear_output() print('Searching...') tree_widget.cl...
256
256
860
8
247
hugoledoux/geemap
geemap/geemap.py
Python
build_asset_tree
build_asset_tree
4,912
5,029
4,912
4,913
bc7ae1e85e63d8eaa616edc3ed5dd2b2ac4e79c1
bigcode/the-stack
train
0c75664b0f3d75c28fd59962
train
function
def ee_export_image_to_drive(ee_object, description, folder=None, region=None, scale=None, crs=None, max_pixels=1.0E13, file_format='GeoTIFF'): """Creates a batch task to export an Image as a raster to Google Drive. Args: ee_object (object): The image to export. description (str): A human-reada...
def ee_export_image_to_drive(ee_object, description, folder=None, region=None, scale=None, crs=None, max_pixels=1.0E13, file_format='GeoTIFF'):
"""Creates a batch task to export an Image as a raster to Google Drive. Args: ee_object (object): The image to export. description (str): A human-readable name of the task. folder (str, optional): The Google Drive Folder that the export will reside in. Defaults to None. region ...
image.get('system:index').getInfo() + '.tif' filename = os.path.join(os.path.abspath(out_dir), name) print('Exporting {}/{}: {}'.format(i+1, count, name)) ee_export_image(image, filename=filename, scale=scale, crs=crs, region=region, file_per_band=file_pe...
135
135
452
41
94
hugoledoux/geemap
geemap/geemap.py
Python
ee_export_image_to_drive
ee_export_image_to_drive
3,033
3,073
3,033
3,033
6f4b4c34e3781d31d2e683c78ce1cdbf3a37facd
bigcode/the-stack
train
e596b82c39ba5ab3191825bb
train
function
def sentinel2_timeseries(roi=None, start_year=2015, end_year=2019, start_date='01-01', end_date='12-31'): """Generates an annual Sentinel 2 ImageCollection. This algorithm is adapted from https://gist.github.com/jdbcode/76b9ac49faf51627ebd3ff988e10adbc. A huge thank you to Justin Braaten for sharing his fantastic w...
def sentinel2_timeseries(roi=None, start_year=2015, end_year=2019, start_date='01-01', end_date='12-31'):
"""Generates an annual Sentinel 2 ImageCollection. This algorithm is adapted from https://gist.github.com/jdbcode/76b9ac49faf51627ebd3ff988e10adbc. A huge thank you to Justin Braaten for sharing his fantastic work. Images include both level 1C and level 2A imagery. Args: roi (object, optional): ...
, optional): Ending year for the timeseries. Defaults to 2018. Returns: object: An ee.ImageCollection representing annual NAIP imagery. """ ee_initialize() try: def get_annual_NAIP(year): try: collection = ee.ImageCollection('USDA/NAIP/DOQQ') ...
256
256
1,923
35
221
hugoledoux/geemap
geemap/geemap.py
Python
sentinel2_timeseries
sentinel2_timeseries
3,653
3,845
3,653
3,653
c422958785344552fbd691e125d8cc7f6084f504
bigcode/the-stack
train
a9ae5dd3da893d2a78514c21
train
function
def check_color(in_color): """Checks the input color and returns the corresponding hex color code. Args: in_color (str or tuple): It can be a string (e.g., 'red', '#ffff00') or tuple (e.g., (255, 127, 0)). Returns: str: A hex color code. """ out_color = '#000000' # default black c...
def check_color(in_color):
"""Checks the input color and returns the corresponding hex color code. Args: in_color (str or tuple): It can be a string (e.g., 'red', '#ffff00') or tuple (e.g., (255, 127, 0)). Returns: str: A hex color code. """ out_color = '#000000' # default black color if isinstance(in_c...
code as a string. Defaults to 'FFFFFF'. Returns: tuple: RGB color as a tuple. """ value = value.lstrip('#') lv = len(value) return tuple(int(value[i:i+lv//3], 16) for i in range(0, lv, lv//3)) def check_color(in_color):
72
72
241
6
66
hugoledoux/geemap
geemap/geemap.py
Python
check_color
check_color
1,971
1,997
1,971
1,971
8dbcf592579f6e74b37826e307ee3d1a6a8285c5
bigcode/the-stack
train
863699e4dd8b1c49f81d589d
train
function
def open_youtube(): """Opens the YouTube tutorials for geemap. """ import webbrowser url = 'https://www.youtube.com/playlist?list=PLAxJ4-o7ZoPccOFv1dCwvGI6TYnirRTg3' webbrowser.open_new_tab(url)
def open_youtube():
"""Opens the YouTube tutorials for geemap. """ import webbrowser url = 'https://www.youtube.com/playlist?list=PLAxJ4-o7ZoPccOFv1dCwvGI6TYnirRTg3' webbrowser.open_new_tab(url)
repository. Defaults to True. """ url = 'https://github.com/giswqs/geemap/archive/master.zip' filename = 'geemap-master.zip' download_from_url(url, out_file_name=filename, out_dir=out_dir, unzip=unzip) def open_youtube():
64
64
69
5
59
hugoledoux/geemap
geemap/geemap.py
Python
open_youtube
open_youtube
2,595
2,601
2,595
2,595
4ba8c54f23344ba5b165736d9e24ff724c72b579
bigcode/the-stack
train
5ee34150f7a14bb55ef105b4
train
function
def add_text_to_gif(in_gif, out_gif, xy=None, text_sequence=None, font_type="arial.ttf", font_size=20, font_color='#000000', add_progress_bar=True, progress_bar_color='white', progress_bar_height=5, duration=100, loop=0): """Adds animated text to a GIF image. Args: in_gif (str): The file path to the in...
def add_text_to_gif(in_gif, out_gif, xy=None, text_sequence=None, font_type="arial.ttf", font_size=20, font_color='#000000', add_progress_bar=True, progress_bar_color='white', progress_bar_height=5, duration=100, loop=0):
"""Adds animated text to a GIF image. Args: in_gif (str): The file path to the input GIF image. out_gif (str): The file path to the output GIF image. xy (tuple, optional): Top left corner of the text. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. t...
print(e) return out_color def system_fonts(show_full_path=False): """Gets a list of system fonts. # Common font locations: # Linux: /usr/share/fonts/TTF/ # Windows: C:\Windows\Fonts # macOS: System > Library > Fonts Args: show_full_path (bool,...
256
256
1,637
63
193
hugoledoux/geemap
geemap/geemap.py
Python
add_text_to_gif
add_text_to_gif
2,033
2,177
2,033
2,033
506fbdc061225cf7f98445fb0664045e42d611df
bigcode/the-stack
train
af00403608596a4a289a51a7
train
function
def clone_google_repo(url, out_dir=None): """Clones an Earth Engine repository from https://earthengine.googlesource.com, such as https://earthengine.googlesource.com/users/google/datasets Args: url (str): The link to the Earth Engine repository out_dir (str, optional): The output directory for...
def clone_google_repo(url, out_dir=None):
"""Clones an Earth Engine repository from https://earthengine.googlesource.com, such as https://earthengine.googlesource.com/users/google/datasets Args: url (str): The link to the Earth Engine repository out_dir (str, optional): The output directory for the cloned repository. Defaults to None. ...
(out_dir): print( 'The specified output directory already exists. Please choose a new directory.') return try: porcelain.clone(url, out_dir) except Exception as e: print('Failed to clone the repository.') print(e) def clone_google_repo(url, out_dir=None):
64
64
193
10
54
hugoledoux/geemap
geemap/geemap.py
Python
clone_google_repo
clone_google_repo
5,432
5,455
5,432
5,432
3f167a19180b983c69c34d73db48bea1314153e4
bigcode/the-stack
train
41923b8b3bc5d2bb4b82667e
train
function
def is_latlon_valid(location): """Checks whether a pair of coordinates is valid. Args: location (str): A pair of latlon coordinates separated by comma or space. Returns: bool: Returns True if valid. """ latlon = [] if ',' in location: latlon = [float(x) for x in locatio...
def is_latlon_valid(location):
"""Checks whether a pair of coordinates is valid. Args: location (str): A pair of latlon coordinates separated by comma or space. Returns: bool: Returns True if valid. """ latlon = [] if ',' in location: latlon = [float(x) for x in location.split(',')] elif ' ' in l...
address = result.address if not address in addresses: addresses.add(address) locations.append(result) if len(locations) > 0: return locations else: return None except Exception as e: pr...
64
64
204
7
56
hugoledoux/geemap
geemap/geemap.py
Python
is_latlon_valid
is_latlon_valid
4,278
4,305
4,278
4,278
2465864e51763d6a776da92ba345f19e15169c8a
bigcode/the-stack
train
a0eb8aea9e6e43200e82e081
train
function
def ee_export_vector(ee_object, filename, selectors=None): """Exports Earth Engine FeatureCollection to other formats, including shp, csv, json, kml, and kmz. Args: ee_object (object): ee.FeatureCollection to export. filename (str): Output file name. selectors (list, optional): A list o...
def ee_export_vector(ee_object, filename, selectors=None):
"""Exports Earth Engine FeatureCollection to other formats, including shp, csv, json, kml, and kmz. Args: ee_object (object): ee.FeatureCollection to export. filename (str): Output file name. selectors (list, optional): A list of attributes to export. Defaults to None. """ impor...
the shapefile. """ ee_initialize() try: json_data = shp_to_geojson(in_shp) ee_object = geojson_to_ee(json_data) return ee_object except Exception as e: print(e) def filter_polygons(ftr): """Converts GeometryCollection to Polygon/MultiPolygon Args: ftr ...
193
193
645
13
180
hugoledoux/geemap
geemap/geemap.py
Python
ee_export_vector
ee_export_vector
2,765
2,845
2,765
2,765
809ed5dd079b3659c59370585c73924a5d925e52
bigcode/the-stack
train
46cb5d42846d4a07919208d1
train
function
def clone_repo(out_dir='.', unzip=True): """Clones the geemap GitHub repository. Args: out_dir (str, optional): Output folder for the repo. Defaults to '.'. unzip (bool, optional): Whether to unzip the repository. Defaults to True. """ url = 'https://github.com/giswqs/geemap/archive/mas...
def clone_repo(out_dir='.', unzip=True):
"""Clones the geemap GitHub repository. Args: out_dir (str, optional): Output folder for the repo. Defaults to '.'. unzip (bool, optional): Whether to unzip the repository. Defaults to True. """ url = 'https://github.com/giswqs/geemap/archive/master.zip' filename = 'geemap-master.zi...
'source': url += '/tree/master/geemap/' elif subdir == 'examples': url += '/tree/master/examples' elif subdir == 'tutorials': url += '/tree/master/tutorials' webbrowser.open_new_tab(url) def clone_repo(out_dir='.', unzip=True):
64
64
112
10
54
hugoledoux/geemap
geemap/geemap.py
Python
clone_repo
clone_repo
2,582
2,592
2,582
2,582
2b85dab31e9efc99f2f810fd4b7526c496fb3711
bigcode/the-stack
train
0f772586e7938096e21a0d23
train
function
def ee_to_geojson(ee_object, out_json=None): """Converts Earth Engine object to geojson. Args: ee_object (object): An Earth Engine object. Returns: object: GeoJSON object. """ from json import dumps ee_initialize() try: if isinstance(ee_object, ee.geometry.Geometry...
def ee_to_geojson(ee_object, out_json=None):
"""Converts Earth Engine object to geojson. Args: ee_object (object): An Earth Engine object. Returns: object: GeoJSON object. """ from json import dumps ee_initialize() try: if isinstance(ee_object, ee.geometry.Geometry) or isinstance(ee_object, ee.feature.Feature...
['geometry'], "", geodesic) return geom else: print("Could not convert the geojson to ee.Geometry()") except Exception as e: print("Could not convert the geojson to ee.Geometry()") print(e) def ee_to_geojson(ee_object, out_json=None):
66
66
220
13
53
hugoledoux/geemap
geemap/geemap.py
Python
ee_to_geojson
ee_to_geojson
2,532
2,559
2,532
2,532
68c12a7b5444002a5203f34035d0bde437e24f78
bigcode/the-stack
train
fc6b7d052b9c94b650e782ce
train
function
def geocode(location, max_rows=10, reverse=False): """Search location by address and lat/lon coordinates. Args: location (str): Place name or address max_rows (int, optional): Maximum number of records to return. Defaults to 10. reverse (bool, optional): Search place based on coordinate...
def geocode(location, max_rows=10, reverse=False):
"""Search location by address and lat/lon coordinates. Args: location (str): Place name or address max_rows (int, optional): Maximum number of records to return. Defaults to 10. reverse (bool, optional): Search place based on coordinates. Defaults to False. Returns: list: R...
_left = min([x[1] for x in coordinates]), min( [x[0] for x in coordinates]) # (lat, lon) upper_right = max([x[1] for x in coordinates]), max([x[0] for x in coordinates]) # (lat, lon) bounds = (lower_left, upper_right) ret...
109
109
365
13
95
hugoledoux/geemap
geemap/geemap.py
Python
geocode
geocode
4,216
4,275
4,216
4,216
aba25f3c3c6960420ec656c79abf6d428ea1ffb7
bigcode/the-stack
train
2bed578df8775a9f72345322
train
function
def ee_tile_layer(ee_object, vis_params={}, name='Layer untitled', shown=True, opacity=1.0): """Converts and Earth Engine layer to ipyleaflet TileLayer. Args: ee_object (Collection|Feature|Image|MapId): The object to add to the map. vis_params (dict, optional): The visualization parameters. Def...
def ee_tile_layer(ee_object, vis_params={}, name='Layer untitled', shown=True, opacity=1.0):
"""Converts and Earth Engine layer to ipyleaflet TileLayer. Args: ee_object (Collection|Feature|Image|MapId): The object to add to the map. vis_params (dict, optional): The visualization parameters. Defaults to {}. name (str, optional): The name of the layer. Defaults to 'Layer untitled...
create a legend. """ try: ee_class_table = ee_class_table.strip() lines = ee_class_table.split('\n')[1:] if lines[0] == 'Value\tColor\tDescription': lines = lines[1:] legend_dict = {} for index, line in enumerate(lines): items = line.split("\t")...
157
157
525
26
131
hugoledoux/geemap
geemap/geemap.py
Python
ee_tile_layer
ee_tile_layer
2,433
2,484
2,433
2,433
20194d5c420594b5967080e5d7615c73bc6d9215
bigcode/the-stack
train
8ba47a6b8793f84543271518
train
function
def open_github(subdir=None): """Opens the GitHub repository for this package. Args: subdir (str, optional): Sub-directory of the repository. Defaults to None. """ import webbrowser url = 'https://github.com/giswqs/geemap' if subdir == 'source': url += '/tree/master/geemap/' ...
def open_github(subdir=None):
"""Opens the GitHub repository for this package. Args: subdir (str, optional): Sub-directory of the repository. Defaults to None. """ import webbrowser url = 'https://github.com/giswqs/geemap' if subdir == 'source': url += '/tree/master/geemap/' elif subdir == 'examples': ...
": "FeatureCollection", "features": json_object}, indent=2) + "\n") geojson.close() return json_object else: print("Could not convert the Earth Engine object to geojson") except Exception as e: print(e) def open_github(subdir=None):
64
64
122
8
56
hugoledoux/geemap
geemap/geemap.py
Python
open_github
open_github
2,562
2,579
2,562
2,562
22cb8ef5340a817288e49233fff30744ff43295b
bigcode/the-stack
train
e0165dbfa19cb289f45b6df0
train
function
def zonal_statistics_by_group(in_value_raster, in_zone_vector, out_file_path, statistics_type='SUM', decimal_places=0, denominator=1.0, scale=None, crs=None, tile_scale=1.0): """Summarizes the area or percentage of a raster by group within the zones of another dataset and exports the results as a csv, shp, json, km...
def zonal_statistics_by_group(in_value_raster, in_zone_vector, out_file_path, statistics_type='SUM', decimal_places=0, denominator=1.0, scale=None, crs=None, tile_scale=1.0):
"""Summarizes the area or percentage of a raster by group within the zones of another dataset and exports the results as a csv, shp, json, kml, or kmz. Args: in_value_raster (object): An integer Image that contains the values on which to calculate area/percentage. in_zone_vector (object): An ee...
.Reducer.sum(), 'VARIANCE': ee.Reducer.variance(), 'HIST': ee.Reducer.histogram(maxBuckets=max_buckets, minBucketWidth=min_bucket_width, maxRaw=max_raw), 'FIXED_HIST': ee.Reducer.fixedHistogram(hist_min, hist_max, hist_steps) } if not (statistics_type.upper() in allowed_statistics.keys(...
256
256
1,306
49
207
hugoledoux/geemap
geemap/geemap.py
Python
zonal_statistics_by_group
zonal_statistics_by_group
3,302
3,426
3,302
3,302
be223e0eab4d18de6865edbe911ce3c8b21b9815
bigcode/the-stack
train
513bb298cd53b3abb3f8e458
train
function
def clone_github_repo(url, out_dir): """Clones a GitHub repository. Args: url (str): The link to the GitHub repository out_dir (str): The output directory for the cloned repository. """ import zipfile repo_name = os.path.basename(url) url_zip = os.path.join(url, 'archive/mast...
def clone_github_repo(url, out_dir):
"""Clones a GitHub repository. Args: url (str): The link to the GitHub repository out_dir (str): The output directory for the cloned repository. """ import zipfile repo_name = os.path.basename(url) url_zip = os.path.join(url, 'archive/master.zip') if os.path.exists(out_d...
in output: return True else: url = 'https://git-scm.com/downloads' print( "Git is not installed. Please download Git from {} and install it.".format(url)) webbrowser.open_new_tab(url) return False def clone_github_repo(url, out_dir):
67
67
225
10
56
hugoledoux/geemap
geemap/geemap.py
Python
clone_github_repo
clone_github_repo
5,367
5,399
5,367
5,367
ca08f85cdb9f1ef5970f884263c122a49580497e
bigcode/the-stack
train
27f6285db2da166307547f2c
train
function
def build_repo_tree(out_dir=None, name='gee_repos'): """Builds a repo tree for GEE account. Args: out_dir (str): The output directory for the repos. Defaults to None. name (str, optional): The output name for the repo directory. Defaults to 'gee_repos'. Returns: tuple: Returns a tu...
def build_repo_tree(out_dir=None, name='gee_repos'):
"""Builds a repo tree for GEE account. Args: out_dir (str): The output directory for the repos. Defaults to None. name (str, optional): The output name for the repo directory. Defaults to 'gee_repos'. Returns: tuple: Returns a tuple containing a tree widget, an output widget, and a...
) elif asset_types[key] == 'IMAGE_COLLECTION': path_widget.value = "ee.ImageCollection('{}')".format( key) elif asset_types[key] == 'TABLE': path_widget.value = "ee.FeatureCollection('{}')".format( ...
253
253
846
14
238
hugoledoux/geemap
geemap/geemap.py
Python
build_repo_tree
build_repo_tree
5,032
5,132
5,032
5,032
b27221825b57bf1e496729faeaa68ae51ec8110d
bigcode/the-stack
train
7b5a92865607ff10c373a2a2
train
function
def clone_github_repo2(url, out_dir=None): """Clones a GitHub repository. Args: url (str): The link to the GitHub repository out_dir (str, optional): The output directory for the cloned repository. Defaults to None. """ check_install('dulwich') from dulwich import porcelain rep...
def clone_github_repo2(url, out_dir=None):
"""Clones a GitHub repository. Args: url (str): The link to the GitHub repository out_dir (str, optional): The output directory for the cloned repository. Defaults to None. """ check_install('dulwich') from dulwich import porcelain repo_name = os.path.basename(url) if out_...
with zipfile.ZipFile(out_file_path, "r") as zip_ref: zip_ref.extractall(parent_dir) src = out_file_path.replace('.zip', '-master') os.rename(src, out_dir) os.remove(out_file_path) def clone_github_repo2(url, out_dir=None):
64
64
182
12
52
hugoledoux/geemap
geemap/geemap.py
Python
clone_github_repo2
clone_github_repo2
5,402
5,429
5,402
5,402
f21a97bea64912b22dafbbca0b145cd4bfd174b1
bigcode/the-stack
train
93195018aae6404ec17c2c4d
train
function
def legend_from_ee(ee_class_table): """Extract legend from an Earth Engine class table on the Earth Engine Data Catalog page such as https://developers.google.com/earth-engine/datasets/catalog/MODIS_051_MCD12Q1 Value Color Description 0 1c0dff Water 1 05450a Evergreen needleleaf forest 2 086a10...
def legend_from_ee(ee_class_table):
"""Extract legend from an Earth Engine class table on the Earth Engine Data Catalog page such as https://developers.google.com/earth-engine/datasets/catalog/MODIS_051_MCD12Q1 Value Color Description 0 1c0dff Water 1 05450a Evergreen needleleaf forest 2 086a10 Evergreen broadleaf forest 3 54...
', 'height': str(height + 10) + 'px'},) out.clear_output(wait=True) display(out) with out: file = open(img_path, "rb") image = file.read() if (width is None) and (height is None): display(widgets.Image(value=image)) elif (width is n...
135
135
453
10
125
hugoledoux/geemap
geemap/geemap.py
Python
legend_from_ee
legend_from_ee
2,382
2,430
2,382
2,382
2df3ab8789a718de4bd83f7d8a5ebe67559cf7d0
bigcode/the-stack
train
cf060099dfc442d618de26c7
train
function
def has_transparency(img): """Checks whether an image has transparency. Args: img (object): a PIL Image object. Returns: bool: True if it has transparency, False otherwise. """ if img.mode == "P": transparent = img.info.get("transparency", -1) for _, index in img....
def has_transparency(img):
"""Checks whether an image has transparency. Args: img (object): a PIL Image object. Returns: bool: True if it has transparency, False otherwise. """ if img.mode == "P": transparent = img.info.get("transparency", -1) for _, index in img.getcolors(): if...
_url(url, out_name, out_dir, unzip=False) # img = Image.open(out_path) # else: response = requests.get(url) img = Image.open(BytesIO(response.content)) return img except Exception as e: print(e) def has_transparency(img):
64
64
122
6
58
hugoledoux/geemap
geemap/geemap.py
Python
has_transparency
has_transparency
2,213
2,233
2,213
2,213
51b54f3db5174c2e0b82b8efbebb5de6829eed0f
bigcode/the-stack
train
3ecb07231adbd5d6e08d6a70
train
function
def check_git_install(): """Checks if Git is installed. Returns: bool: Returns True if Git is installed, otherwise returns False. """ import webbrowser cmd = 'git --version' output = os.popen(cmd).read() if 'git version' in output: return True else: url = 'http...
def check_git_install():
"""Checks if Git is installed. Returns: bool: Returns True if Git is installed, otherwise returns False. """ import webbrowser cmd = 'git --version' output = os.popen(cmd).read() if 'git version' in output: return True else: url = 'https://git-scm.com/downloads...
node parent_node.add_node(node) node.observe(handle_file_click, 'selected') with tree_widget: tree_widget.clear_output() display(tree) if return_sep_widgets: return left_widget, right_widget, tree_dict else: return full_widget def check_git_...
64
64
118
5
58
hugoledoux/geemap
geemap/geemap.py
Python
check_git_install
check_git_install
5,346
5,364
5,346
5,346
7ceb195a9b315ee312b6f3ad1e52297b93d743bd
bigcode/the-stack
train
ef140ece68cbec448dbd45d5
train
function
def ee_api_to_csv(outfile=None): """Extracts Earth Engine API documentation from https://developers.google.com/earth-engine/api_docs as a csv file. Args: outfile (str, optional): The output file path to a csv file. Defaults to None. """ import csv import requests from bs4 import Beautif...
def ee_api_to_csv(outfile=None):
"""Extracts Earth Engine API documentation from https://developers.google.com/earth-engine/api_docs as a csv file. Args: outfile (str, optional): The output file path to a csv file. Defaults to None. """ import csv import requests from bs4 import BeautifulSoup pkg_dir = os.path.dir...
asset_url', asset['asset_url']) # asset['thumbnail'] = ee_data_thumbnail(asset['id']) text = text.replace('thumbnail_url', asset['thumbnail_url']) return text except Exception as e: print(e) return def create_code_cell(code='', where='below'): """Creates a code cell i...
214
215
718
8
206
hugoledoux/geemap
geemap/geemap.py
Python
ee_api_to_csv
ee_api_to_csv
4,474
4,578
4,474
4,474
f1a6b24534e99209bc8f6c9e85607527bd1f9e23
bigcode/the-stack
train
959ac3d77727cd5c35d2fe37
train
function
def ee_to_numpy(ee_object, bands=None, region=None, properties=None, default_value=None): """Extracts a rectangular region of pixels from an image into a 2D numpy array per band. Args: ee_object (object): The image to sample. bands (list, optional): The list of band names to extract. Please mak...
def ee_to_numpy(ee_object, bands=None, region=None, properties=None, default_value=None):
"""Extracts a rectangular region of pixels from an image into a 2D numpy array per band. Args: ee_object (object): The image to sample. bands (list, optional): The list of band names to extract. Please make sure that all bands have the same spatial resolution. Defaults to None. region ...
images.') return if descriptions is None: descriptions = ee_object.aggregate_array('system:index').getInfo() images = ee_object.toList(count) for i in range(0, count): image = ee.Image(images.get(i)) name = descriptions[i] ee_export...
117
117
392
21
96
hugoledoux/geemap
geemap/geemap.py
Python
ee_to_numpy
ee_to_numpy
3,118
3,160
3,118
3,118
eb4eff55f6623168c4655e4c332644588b988588
bigcode/the-stack
train
07e39f6d369bcbb9bed5c42e
train
function
def create_colorbar(width=150, height=30, palette=['blue', 'green', 'red'], add_ticks=True, add_labels=True, labels=None, vertical=False, out_file=None, font_type='arial.ttf', font_size=12, font_color='black', add_outline=True, outline_color='black'): """Creates a colorbar based on the provided palette. Args: ...
def create_colorbar(width=150, height=30, palette=['blue', 'green', 'red'], add_ticks=True, add_labels=True, labels=None, vertical=False, out_file=None, font_type='arial.ttf', font_size=12, font_color='black', add_outline=True, outline_color='black'):
"""Creates a colorbar based on the provided palette. Args: width (int, optional): Width of the colorbar in pixels. Defaults to 150. height (int, optional): Height of the colorbar in pixels. Defaults to 30. palette (list, optional): Palette for the colorbar. Each color can be provided as...
= get_keys(groups) values = get_values(groups) total_area = ee.List(values).reduce(ee.Reducer.sum()) def get_class_values(x): cls_value = ee.Algorithms.If( keys.contains(x), values.get(keys.indexOf(x)), 0) cls_value = ee.Algorithm...
256
256
1,795
65
191
hugoledoux/geemap
geemap/geemap.py
Python
create_colorbar
create_colorbar
3,429
3,614
3,429
3,429
02fdaea36348b5f5be6acbac467b27ec277d8336
bigcode/the-stack
train
e5e16f7c1d6998ec8ee7a422
train
function
def ee_data_thumbnail(asset_id): """Retrieves the thumbnail URL of an Earth Engine asset. Args: asset_id (str): An Earth Engine asset id. Returns: str: An http url of the thumbnail. """ import requests import urllib from bs4 import BeautifulSoup asset_uid = asset_id.re...
def ee_data_thumbnail(asset_id):
"""Retrieves the thumbnail URL of an Earth Engine asset. Args: asset_id (str): An Earth Engine asset id. Returns: str: An http url of the thumbnail. """ import requests import urllib from bs4 import BeautifulSoup asset_uid = asset_id.replace('/', '_') asset_url = "...
/' + asset['uid'] # asset['thumbnail'] = 'https://mw1.google.com/ges/dd/images/{}_sample.png'.format( # asset['uid']) results.append(asset) return results except Exception as e: print(e) return def ee_data_thumbnail(asset_id):
67
67
224
7
59
hugoledoux/geemap
geemap/geemap.py
Python
ee_data_thumbnail
ee_data_thumbnail
4,378
4,412
4,378
4,378
0d4288ad78a405f31c1509761a5f18cfe38519d6
bigcode/the-stack
train
2935086b932513837baf0e9d
train
function
def landsat_ts_gif(roi=None, out_gif=None, start_year=1984, end_year=2019, start_date='06-10', end_date='09-20', bands=['NIR', 'Red', 'Green'], vis_params=None, dimensions=768, frames_per_second=10): """Generates a Landsat timelapse GIF image. This function is adapted from https://emaprlab.users.earthengine.app/vie...
def landsat_ts_gif(roi=None, out_gif=None, start_year=1984, end_year=2019, start_date='06-10', end_date='09-20', bands=['NIR', 'Red', 'Green'], vis_params=None, dimensions=768, frames_per_second=10):
"""Generates a Landsat timelapse GIF image. This function is adapted from https://emaprlab.users.earthengine.app/view/lt-gee-time-series-animator. A huge thank you to Justin Braaten for sharing his fantastic work. Args: roi (object, optional): Region of interest to create the timelapse. Defaults to Non...
r = lt.select(['SWIR1_fit']).arrayFlatten([yearsStr]).toShort() # g = lt.select(['NIR_fit']).arrayFlatten([yearsStr]).toShort() # b = lt.select(['Green_fit']).arrayFlatten([yearsStr]).toShort() # for i, c in zip([r, g, b], ['r', 'g', 'b']): # descr = 'mamore-river-'+c # name = 'users/user/...
256
256
1,065
66
190
hugoledoux/geemap
geemap/geemap.py
Python
landsat_ts_gif
landsat_ts_gif
4,088
4,186
4,088
4,088
0576b80c9e51a855a1f96952de77eb8f50c3051e
bigcode/the-stack
train
dfae191251f551e7aaa8b43c
train
function
def latlon_from_text(location): """Extracts latlon from text. Args: location (str): A pair of latlon coordinates separated by comma or space. Returns: bool: Returns (lat, lon) if valid. """ latlon = [] try: if ',' in location: latlon = [float(x) for x in loc...
def latlon_from_text(location):
"""Extracts latlon from text. Args: location (str): A pair of latlon coordinates separated by comma or space. Returns: bool: Returns (lat, lon) if valid. """ latlon = [] try: if ',' in location: latlon = [float(x) for x in location.split(',')] elif '...
: lat, lon = float(latlon[0]), float(latlon[1]) if lat >= -90 and lat <= 90 and lon >= -180 and lat <= 180: return True else: return False except Exception as e: print(e) return False def latlon_from_text(location):
72
72
240
7
64
hugoledoux/geemap
geemap/geemap.py
Python
latlon_from_text
latlon_from_text
4,308
4,337
4,308
4,308
01d16459fe0622261ad804bbb55580479fe804a0
bigcode/the-stack
train
97de1d10b008bef6dae021af
train
function
def shp_to_geojson(in_shp, out_json=None): """Converts a shapefile to GeoJSON. Args: in_shp (str): File path of the input shapefile. out_json (str, optional): File path of the output GeoJSON. Defaults to None. Returns: object: The json object representing the shapefile. """ ...
def shp_to_geojson(in_shp, out_json=None):
"""Converts a shapefile to GeoJSON. Args: in_shp (str): File path of the input shapefile. out_json (str, optional): File path of the output GeoJSON. Defaults to None. Returns: object: The json object representing the shapefile. """ # check_install('pyshp') ee_initialize...
_dir = os.path.join(download_dir, 'geemap-master') work_dir = os.getcwd() os.chdir(pkg_dir) cmd = 'pip install .' os.system(cmd) os.chdir(work_dir) print("\nPlease comment out 'geemap.update_package()' and restart the kernel to take effect:\nJupyter menu -> Kernel -> Res...
102
102
343
13
89
hugoledoux/geemap
geemap/geemap.py
Python
shp_to_geojson
shp_to_geojson
2,678
2,725
2,678
2,678
2483415a985906ed0f20f09744c29e4e871bce66
bigcode/the-stack
train
0fab2df986318aaa9931b49b
train
function
def show_youtube(id='h0pz3S6Tvx0'): """Displays a YouTube video within Jupyter notebooks. Args: id (str, optional): Unique ID of the video. Defaults to 'h0pz3S6Tvx0'. """ from IPython.display import YouTubeVideo, display try: out = widgets.Output( layout={'width': '815p...
def show_youtube(id='h0pz3S6Tvx0'):
"""Displays a YouTube video within Jupyter notebooks. Args: id (str, optional): Unique ID of the video. Defaults to 'h0pz3S6Tvx0'. """ from IPython.display import YouTubeVideo, display try: out = widgets.Output( layout={'width': '815px'}) # layout={'border': '1p...
and navigate to the geemap API documentation. """ import webbrowser url = 'https://geemap.readthedocs.io/en/latest/source/geemap.html#geemap-package' webbrowser.open_new_tab(url) def show_youtube(id='h0pz3S6Tvx0'):
64
64
149
16
48
hugoledoux/geemap
geemap/geemap.py
Python
show_youtube
show_youtube
2,613
2,630
2,613
2,613
55e3d4cc9684556826eeba0b10ebeaa0d015abfc
bigcode/the-stack
train
2122d8ab06e766a16895f06b
train
function
def build_api_tree(api_dict, output_widget, layout_width='100%'): """Builds an Earth Engine API tree view. Args: api_dict (dict): The dictionary containing information about each Earth Engine API function. output_widget (object): An Output widget. layout_width (str, optional): The perce...
def build_api_tree(api_dict, output_widget, layout_width='100%'):
"""Builds an Earth Engine API tree view. Args: api_dict (dict): The dictionary containing information about each Earth Engine API function. output_widget (object): An Output widget. layout_width (str, optional): The percentage width of the widget. Defaults to '100%'. Returns: ...
[0] == 'ee': for i in range(2, len(items) + 1): func_list.append('.'.join(items[0:i])) else: for i in range(1, len(items) + 1): func_list.append('.'.join(items[0:i])) return func_list except Exception as e: print(e) print('The ...
105
106
354
16
89
hugoledoux/geemap
geemap/geemap.py
Python
build_api_tree
build_api_tree
4,691
4,742
4,691
4,691
afc42e7f6c09e5c4eec9d7a842aa43baed44c538
bigcode/the-stack
train
55f73bfb03b22ad6ce9983f2
train
function
def ee_export_image(ee_object, filename, scale=None, crs=None, region=None, file_per_band=False): """Exports an ee.Image as a GeoTIFF. Args: ee_object (object): The ee.Image to download. filename (str): Output filename for the exported image. scale (float, optional): A default scale to ...
def ee_export_image(ee_object, filename, scale=None, crs=None, region=None, file_per_band=False):
"""Exports an ee.Image as a GeoTIFF. Args: ee_object (object): The ee.Image to download. filename (str): Output filename for the exported image. scale (float, optional): A default scale to use for any bands that do not specify one; ignored if crs and crs_transform is specified. Defaults...
end with .shp') except Exception as e: print(e) def ee_to_csv(ee_object, filename, selectors=None): """Downloads an ee.FeatureCollection as a CSV file. Args: ee_object (object): ee.FeatureCollection filename (str): The output filepath of the CSV file. selectors (list, op...
173
173
579
25
148
hugoledoux/geemap
geemap/geemap.py
Python
ee_export_image
ee_export_image
2,921
2,989
2,921
2,921
7398e24eac5bfd5d8d54464957a84844d3674829
bigcode/the-stack
train
5566d5635208d72fb46d33d0
train
function
def ee_to_shp(ee_object, filename, selectors=None): """Downloads an ee.FeatureCollection as a shapefile. Args: ee_object (object): ee.FeatureCollection filename (str): The output filepath of the shapefile. selectors (list, optional): A list of attributes to export. Defaults to None. ...
def ee_to_shp(ee_object, filename, selectors=None):
"""Downloads an ee.FeatureCollection as a shapefile. Args: ee_object (object): ee.FeatureCollection filename (str): The output filepath of the shapefile. selectors (list, optional): A list of attributes to export. Defaults to None. """ ee_initialize() try: if filenam...
if selectors is not None: task_config['selectors'] = selectors print('Exporting {}...'.format(description)) task = ee.batch.Export.table.toDrive(ee_object, description, **task_config) task.start() def ee_to_shp(ee_object, filename, selectors=None):
64
64
135
14
50
hugoledoux/geemap
geemap/geemap.py
Python
ee_to_shp
ee_to_shp
2,881
2,898
2,881
2,881
8f20211b811459f1abe6eeacc01dc8da2237d78a
bigcode/the-stack
train
646710dcede0fc3f1b8bc08b
train
class
class Map(ipyleaflet.Map): """The Map class inherits from ipyleaflet.Map Args: ipyleaflet (object): An ipyleaflet map instance. The arguments you can pass to the Map can be found at https://ipyleaflet.readthedocs.io/en/latest/api_reference/map.html By default, the Map will add Google Maps as th...
class Map(ipyleaflet.Map):
"""The Map class inherits from ipyleaflet.Map Args: ipyleaflet (object): An ipyleaflet map instance. The arguments you can pass to the Map can be found at https://ipyleaflet.readthedocs.io/en/latest/api_reference/map.html By default, the Map will add Google Maps as the basemap. Set add_google_m...
"""Main module for interactive mapping using Google Earth Engine Python API and ipyleaflet. Keep in mind that Earth Engine functions use both camel case and snake case, such as setOptions(), setCenter(), centerObject(), addLayer(). ipyleaflet functions use snake case, such as add_tile_layer(), add_wms_layer(), add_mini...
216
256
16,299
8
208
hugoledoux/geemap
geemap/geemap.py
Python
Map
Map
35
1,880
35
35
ed897623497a104dc594752b9f40b2860fb69869
bigcode/the-stack
train
f7a8c6a55e2019b96a54e490
train
function
def ee_search(asset_limit=100): """Search Earth Engine API and user assets. If you received a warning (IOPub message rate exceeded) in Jupyter notebook, you can relaunch Jupyter notebook using the following command: jupyter notebook --NotebookApp.iopub_msg_rate_limit=10000 Args: asset_limit (in...
def ee_search(asset_limit=100):
"""Search Earth Engine API and user assets. If you received a warning (IOPub message rate exceeded) in Jupyter notebook, you can relaunch Jupyter notebook using the following command: jupyter notebook --NotebookApp.iopub_msg_rate_limit=10000 Args: asset_limit (int, optional): The number of asse...
tree_dict[first] = Node(first) tree_dict[first].opened = False tree.add_node(tree_dict[first]) for index, func in enumerate(func_list): if index > 0: if func not in tree_dict.keys(): node = tree_dict[func_list[index - 1]] ...
256
256
931
8
247
hugoledoux/geemap
geemap/geemap.py
Python
ee_search
ee_search
4,767
4,893
4,767
4,767
08925e36f38ec254cda72c693fb8ff3aa1a3cc29
bigcode/the-stack
train
201dc677745c308632861bc1
train
function
def update_package(): """Updates the geemap package from the geemap GitHub repository without the need to use pip or conda. In this way, I don't have to keep updating pypi and conda-forge with every minor update of the package. """ try: download_dir = os.path.join(os.path.expanduser('~'), '...
def update_package():
"""Updates the geemap package from the geemap GitHub repository without the need to use pip or conda. In this way, I don't have to keep updating pypi and conda-forge with every minor update of the package. """ try: download_dir = os.path.join(os.path.expanduser('~'), 'Downloads') if...
installed. Installing ...'.format(package)) try: subprocess.check_call(["python", '-m', 'pip', 'install', package]) except Exception as e: print('Failed to install {}'.format(package)) print(e) print("{} has been installed successfully.".format(package)) def ...
64
64
192
4
60
hugoledoux/geemap
geemap/geemap.py
Python
update_package
update_package
2,654
2,675
2,654
2,654
fb77380a32576e9939c85315b97163ea34ff8554
bigcode/the-stack
train
05cf52974995dea0c690f801
train
function
def ee_export_image_collection(ee_object, out_dir, scale=None, crs=None, region=None, file_per_band=False): """Exports an ImageCollection as GeoTIFFs. Args: ee_object (object): The ee.Image to download. out_dir (str): The output directory for the exported images. scale (float, optional)...
def ee_export_image_collection(ee_object, out_dir, scale=None, crs=None, region=None, file_per_band=False):
"""Exports an ImageCollection as GeoTIFFs. Args: ee_object (object): The ee.Image to download. out_dir (str): The output directory for the exported images. scale (float, optional): A default scale to use for any bands that do not specify one; ignored if crs and crs_transform is specifie...
except Exception as e: print('An error occurred while downloading.') print(e) return try: z = zipfile.ZipFile(filename_zip) z.extractall(os.path.dirname(filename)) os.remove(filename_zip) if file_per_band: print('Data downloaded to {}'.format(os...
118
118
395
27
91
hugoledoux/geemap
geemap/geemap.py
Python
ee_export_image_collection
ee_export_image_collection
2,992
3,030
2,992
2,992
3f10d928fce5a3d056d1c024568e178568b641af
bigcode/the-stack
train
dca29befeb0b3010f6cc2ec5
train
function
def landsat_timeseries(roi=None, start_year=1984, end_year=2019, start_date='06-10', end_date='09-20'): """Generates an annual Landsat ImageCollection. This algorithm is adapted from https://gist.github.com/jdbcode/76b9ac49faf51627ebd3ff988e10adbc. A huge thank you to Justin Braaten for sharing his fantastic work. ...
def landsat_timeseries(roi=None, start_year=1984, end_year=2019, start_date='06-10', end_date='09-20'):
"""Generates an annual Landsat ImageCollection. This algorithm is adapted from https://gist.github.com/jdbcode/76b9ac49faf51627ebd3ff988e10adbc. A huge thank you to Justin Braaten for sharing his fantastic work. Args: roi ([type], optional): [description]. Defaults to None. start_year (int, opt...
y, 'system:time_start': startDate.millis(), 'nBands': nBands})) ################################################################################ # Make a dummy image for missing years. bandNames = ee.List(['Blue', 'Green', 'Red', 'Red Edge 1', 'Red Edge 2', 'Red Edge 3', 'NIR', ...
256
256
2,080
35
220
hugoledoux/geemap
geemap/geemap.py
Python
landsat_timeseries
landsat_timeseries
3,848
4,047
3,848
3,848
3989e8f2a040750b5d4268cf616d29b9b7929698
bigcode/the-stack
train
e70605345d5081c6549803b3
train
function
def read_api_csv(): """Extracts Earth Engine API from a csv file and returns a dictionary containing information about each function. Returns: dict: The dictionary containing information about each function, including name, description, function form, return type, arguments, html. """ import c...
def read_api_csv():
"""Extracts Earth Engine API from a csv file and returns a dictionary containing information about each function. Returns: dict: The dictionary containing information about each function, including name, description, function form, return type, arguments, html. """ import copy import csv ...
detail_table != '': items = [item.text for item in detail_table.find_all('p')] else: items = "" details.append(items) csv_file = open(outfile, 'w', encoding='utf-8') csv_writer = csv.writer(csv_file, delimiter='\t') csv_writer.writerow( ...
192
192
643
5
187
hugoledoux/geemap
geemap/geemap.py
Python
read_api_csv
read_api_csv
4,581
4,663
4,581
4,581
043e35ea6135e915ad52f4b1bceb2cbac24f7ae7
bigcode/the-stack
train
d8ec2709687a93ffc0c3587d
train
function
def file_browser(in_dir=None, show_hidden=False, add_root_node=True, search_description=None, use_import=False, return_sep_widgets=False): """Creates a simple file browser and text editor. Args: in_dir (str, optional): The input directory. Defaults to None, which will use the current working directory....
def file_browser(in_dir=None, show_hidden=False, add_root_node=True, search_description=None, use_import=False, return_sep_widgets=False):
"""Creates a simple file browser and text editor. Args: in_dir (str, optional): The input directory. Defaults to None, which will use the current working directory. show_hidden (bool, optional): Whether to show hidden files/folders. Defaults to False. add_root_node (bool, optional): Whe...
url = path_widget.value default_dir = os.path.join(repo_dir, 'Examples') if url == '': path_widget.value = 'Please enter a valid URL to the repository.' else: for group in groups: key = os.path.join(repo_dir, group) node = tree_dict...
256
256
1,541
29
226
hugoledoux/geemap
geemap/geemap.py
Python
file_browser
file_browser
5,135
5,343
5,135
5,135
34d271277aeb355c0e64b31ce10a7e458982cc39
bigcode/the-stack
train
2b45d05bba8796cf45766cf1
train
function
def ee_to_csv(ee_object, filename, selectors=None): """Downloads an ee.FeatureCollection as a CSV file. Args: ee_object (object): ee.FeatureCollection filename (str): The output filepath of the CSV file. selectors (list, optional): A list of attributes to export. Defaults to None. "...
def ee_to_csv(ee_object, filename, selectors=None):
"""Downloads an ee.FeatureCollection as a CSV file. Args: ee_object (object): ee.FeatureCollection filename (str): The output filepath of the CSV file. selectors (list, optional): A list of attributes to export. Defaults to None. """ ee_initialize() try: if filename....
endswith('.shp'): ee_export_vector(ee_object=ee_object, filename=filename, selectors=selectors) else: print('The filename must end with .shp') except Exception as e: print(e) def ee_to_csv(ee_object, filename, selectors=None):
64
64
132
13
51
hugoledoux/geemap
geemap/geemap.py
Python
ee_to_csv
ee_to_csv
2,901
2,918
2,901
2,901
b99061169a97d71b43c929b504f72b7ceefa8d10
bigcode/the-stack
train
c164cea72089ed43a12f0ac0
train
function
def open_image_from_url(url): """Loads an image from the specified URL. Args: url (str): URL of the image. Returns: object: Image object. """ from PIL import Image import requests from io import BytesIO from urllib.parse import urlparse try: # if url.endsw...
def open_image_from_url(url):
"""Loads an image from the specified URL. Args: url (str): URL of the image. Returns: object: Image object. """ from PIL import Image import requests from io import BytesIO from urllib.parse import urlparse try: # if url.endswith('.gif'): # out...
/ # Save the frames as a new image frames[0].save(out_gif, save_all=True, append_images=frames[1:], duration=duration, loop=loop, optimize=True) except Exception as e: print(e) return def open_image_from_url(url):
64
64
214
7
56
hugoledoux/geemap
geemap/geemap.py
Python
open_image_from_url
open_image_from_url
2,180
2,210
2,180
2,180
675cea538670f101af26dcbd28bfe2d180a952d5
bigcode/the-stack
train
13278b16184978bf057c5638
train
function
def ee_export_image_collection_to_drive(ee_object, descriptions=None, folder=None, region=None, scale=None, crs=None, max_pixels=1.0E13, file_format='GeoTIFF'): """Creates a batch task to export an ImageCollection as raster images to Google Drive. Args: ee_object (object): The image to export. ...
def ee_export_image_collection_to_drive(ee_object, descriptions=None, folder=None, region=None, scale=None, crs=None, max_pixels=1.0E13, file_format='GeoTIFF'):
"""Creates a batch task to export an ImageCollection as raster images to Google Drive. Args: ee_object (object): The image to export. descriptions (list): A list of human-readable names of the tasks. folder (str, optional): The Google Drive Folder that the export will reside in. Defaul...
_object.projection().nominalScale().multiply(10) params['scale'] = scale if crs is not None: params['crs'] = crs params['maxPixels'] = max_pixels params['fileFormat'] = file_format task = ee.batch.Export.image(ee_object, description, params) task.start() ...
141
141
470
43
98
hugoledoux/geemap
geemap/geemap.py
Python
ee_export_image_collection_to_drive
ee_export_image_collection_to_drive
3,076
3,115
3,076
3,076
9e96149f81cf6474035ebc74c53f3ed589e6c0bd
bigcode/the-stack
train
3a977775cbeb4b1c17d82afd
train
function
def rgb_to_hex(rgb=(255, 255, 255)): """Converts RGB to hex color. In RGB color R stands for Red, G stands for Green, and B stands for Blue, and it ranges from the decimal value of 0 – 255. Args: rgb (tuple, optional): RGB color code as a tuple of (red, green, blue). Defaults to (255, 255, 255). R...
def rgb_to_hex(rgb=(255, 255, 255)):
"""Converts RGB to hex color. In RGB color R stands for Red, G stands for Green, and B stands for Blue, and it ranges from the decimal value of 0 – 255. Args: rgb (tuple, optional): RGB color code as a tuple of (red, green, blue). Defaults to (255, 255, 255). Returns: str: hex color code ...
.'.format(pkg_name)) # print("\nPlease comment out 'install_from_github()' and restart the kernel to take effect:\nJupyter menu -> Kernel -> Restart & Clear Output") except Exception as e: print(e) def rgb_to_hex(rgb=(255, 255, 255)):
64
64
118
14
50
hugoledoux/geemap
geemap/geemap.py
Python
rgb_to_hex
rgb_to_hex
1,945
1,954
1,945
1,945
ad9cf7830df85140d6dd60b75137a555d7ca27b4
bigcode/the-stack
train
d6b3782e2a4bd338c2665777
train
function
def show_image(img_path, width=None, height=None): """Shows an image within Jupyter notebook. Args: img_path (str): The image file path. width (int, optional): Width of the image in pixels. Defaults to None. height (int, optional): Height of the image in pixels. Defaults to None. "...
def show_image(img_path, width=None, height=None):
"""Shows an image within Jupyter notebook. Args: img_path (str): The image file path. width (int, optional): Width of the image in pixels. Defaults to None. height (int, optional): Height of the image in pixels. Defaults to None. """ from IPython.display import display try...
) b = io.BytesIO() frame.save(b, format="GIF") frame = Image.open(b) frames.append(frame) frames[0].save(out_gif, save_all=True, append_images=frames[1:]) except Exception as e: print(e) return def show_image(img_path, width=None, height=None...
75
75
252
12
62
hugoledoux/geemap
geemap/geemap.py
Python
show_image
show_image
2,351
2,379
2,351
2,351
233f4c048a7df1a7005ec98a841e79165f41a78c
bigcode/the-stack
train
636d3aa98de37369640faa37
train
function
def zonal_statistics(in_value_raster, in_zone_vector, out_file_path, statistics_type='MEAN', scale=None, crs=None, tile_scale=1.0, **kwargs): """Summarizes the values of a raster within the zones of another dataset and exports the results as a csv, shp, json, kml, or kmz. Args: in_value_raster (object)...
def zonal_statistics(in_value_raster, in_zone_vector, out_file_path, statistics_type='MEAN', scale=None, crs=None, tile_scale=1.0, **kwargs):
"""Summarizes the values of a raster within the zones of another dataset and exports the results as a csv, shp, json, kml, or kmz. Args: in_value_raster (object): An ee.Image that contains the values on which to calculate a statistic. in_zone_vector (object): An ee.FeatureCollection that define...
.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if 'region' in video_args.keys(): roi = video_args['region'] if not isinstance(roi, ee.Geometry): try: roi = roi.geometry() except Exception as e: print('Could not conver...
256
256
1,101
40
216
hugoledoux/geemap
geemap/geemap.py
Python
zonal_statistics
zonal_statistics
3,214
3,299
3,214
3,214
80f10c9deb03aefb9e4aeb07ad6e3cb9a3dd0be3
bigcode/the-stack
train
17dec0743561e7858f9938d4
train
function
def filter_polygons(ftr): """Converts GeometryCollection to Polygon/MultiPolygon Args: ftr (object): ee.Feature Returns: object: ee.Feature """ ee_initialize() geometries = ftr.geometry().geometries() geometries = geometries.map(lambda geo: ee.Feature( ee.Geometry(g...
def filter_polygons(ftr):
"""Converts GeometryCollection to Polygon/MultiPolygon Args: ftr (object): ee.Feature Returns: object: ee.Feature """ ee_initialize() geometries = ftr.geometry().geometries() geometries = geometries.map(lambda geo: ee.Feature( ee.Geometry(geo)).set('geoType', ee.Ge...
: Earth Engine objects representing the shapefile. """ ee_initialize() try: json_data = shp_to_geojson(in_shp) ee_object = geojson_to_ee(json_data) return ee_object except Exception as e: print(e) def filter_polygons(ftr):
64
64
128
7
57
hugoledoux/geemap
geemap/geemap.py
Python
filter_polygons
filter_polygons
2,746
2,762
2,746
2,746
0f49cae8e1377e4c7c15e5209b8fb3ffd2f17017
bigcode/the-stack
train
4a409c27622caac41ee57237
train
function
def screen_capture(outfile, monitor=1): """Takes a full screenshot of the selected monitor. Args: outfile (str): The output file path to the screenshot. monitor (int, optional): The monitor to take the screenshot. Defaults to 1. """ from mss import mss out_dir = os.path.dirname(out...
def screen_capture(outfile, monitor=1):
"""Takes a full screenshot of the selected monitor. Args: outfile (str): The output file path to the screenshot. monitor (int, optional): The monitor to take the screenshot. Defaults to 1. """ from mss import mss out_dir = os.path.dirname(outfile) if not os.path.exists(out_dir)...
_dim, rgb_dim='band') else: layer = da.leaflet.plot( self, x_dim=x_dim, y_dim=y_dim, colormap=colormap) layer.name = layer_name # The functions below are outside the Map class. def screen_capture(outfile, monitor=1):
64
64
156
9
55
hugoledoux/geemap
geemap/geemap.py
Python
screen_capture
screen_capture
1,885
1,909
1,885
1,885
0ca06ec764b1a9cb748f2b14c3efbab436bf1fc3
bigcode/the-stack
train
6bb3919a746cdc74f1576e97
train
function
def geojson_to_ee(geo_json, geodesic=True): """Converts a geojson to ee.Geometry() Args: geo_json (dict): A geojson geometry dictionary or file path. Returns: ee_object: An ee.Geometry object """ ee_initialize() try: import json if not isinstance(geo_json, di...
def geojson_to_ee(geo_json, geodesic=True):
"""Converts a geojson to ee.Geometry() Args: geo_json (dict): A geojson geometry dictionary or file path. Returns: ee_object: An ee.Geometry object """ ee_initialize() try: import json if not isinstance(geo_json, dict) and os.path.isfile(geo_json): ...
.ImageCollection): image = ee_object.mosaic() map_id_dict = ee.Image(image).getMapId(vis_params) tile_layer = ipyleaflet.TileLayer( url=map_id_dict['tile_fetcher'].url_format, attribution='Google Earth Engine', name=name, opacity=opacity, visible=True # v...
99
99
332
15
83
hugoledoux/geemap
geemap/geemap.py
Python
geojson_to_ee
geojson_to_ee
2,487
2,529
2,487
2,487
1d84112e56269772f69663a1b50ce4c3c8f4f782
bigcode/the-stack
train
61ed05ef41001213a4c27dcc
train
function
def hex_to_rgb(value='FFFFFF'): """Converts hex color to RGB color. Args: value (str, optional): Hex color code as a string. Defaults to 'FFFFFF'. Returns: tuple: RGB color as a tuple. """ value = value.lstrip('#') lv = len(value) return tuple(int(value[i:i+lv//3], 16) for...
def hex_to_rgb(value='FFFFFF'):
"""Converts hex color to RGB color. Args: value (str, optional): Hex color code as a string. Defaults to 'FFFFFF'. Returns: tuple: RGB color as a tuple. """ value = value.lstrip('#') lv = len(value) return tuple(int(value[i:i+lv//3], 16) for i in range(0, lv, lv//3))
tuple, optional): RGB color code as a tuple of (red, green, blue). Defaults to (255, 255, 255). Returns: str: hex color code """ return '%02x%02x%02x' % rgb def hex_to_rgb(value='FFFFFF'):
64
64
97
8
55
hugoledoux/geemap
geemap/geemap.py
Python
hex_to_rgb
hex_to_rgb
1,957
1,968
1,957
1,957
ee0b6731b5d09c5e383b9727eb08e29fa135cefd
bigcode/the-stack
train
7a99b0946789806f97fcbbe1
train
function
def ee_user_id(): """Gets Earth Engine account user id. Returns: str: A string containing the user id. """ ee_initialize() roots = ee.data.getAssetRoots() if len(roots) == 0: return None else: root = ee.data.getAssetRoots()[0] user_id = root['id'].replace("pr...
def ee_user_id():
"""Gets Earth Engine account user id. Returns: str: A string containing the user id. """ ee_initialize() roots = ee.data.getAssetRoots() if len(roots) == 0: return None else: root = ee.data.getAssetRoots()[0] user_id = root['id'].replace("projects/earthengine...
_output(wait=True) display(flags.assets) else: tree_widget.clear_output() print('Searching...') tree_widget.clear_output(wait=True) sub_tree = search_api_tree(text.value, flags.asset_dict) ...
64
64
94
5
59
hugoledoux/geemap
geemap/geemap.py
Python
ee_user_id
ee_user_id
4,896
4,909
4,896
4,896
44aff7d943ae358f55a955cc10433e161bb8485c
bigcode/the-stack
train
abac0c513c6d3720e90fccbc
train
function
def naip_timeseries(roi=None, start_year=2009, end_year=2018): """Creates NAIP annual timeseries Args: roi (object, optional): An ee.Geometry representing the region of interest. Defaults to None. start_year (int, optional): Starting year for the timeseries. Defaults to2009. end_year (i...
def naip_timeseries(roi=None, start_year=2009, end_year=2018):
"""Creates NAIP annual timeseries Args: roi (object, optional): An ee.Geometry representing the region of interest. Defaults to None. start_year (int, optional): Starting year for the timeseries. Defaults to2009. end_year (int, optional): Ending year for the timeseries. Defaults to 2018...
(keys[index] * width + w - w_tmp / 2) spacing = int(h * 0.05) y = height + spacing draw.text((x, y), label, font=font, fill=font_color) im = background.copy() im.save(out_file) return out_file def naip_timeseries(roi=None, start_year=2009, end_year=2018)...
89
89
299
21
67
hugoledoux/geemap
geemap/geemap.py
Python
naip_timeseries
naip_timeseries
3,617
3,650
3,617
3,617
415bac286ed6f5fdfc4141e3a446df83726e599f
bigcode/the-stack
train
d593e17633be4ae78a66432f
train
function
def shp_to_ee(in_shp): """Converts a shapefile to Earth Engine objects. Args: in_shp (str): File path to a shapefile. Returns: object: Earth Engine objects representing the shapefile. """ ee_initialize() try: json_data = shp_to_geojson(in_shp) ee_object = geojso...
def shp_to_ee(in_shp):
"""Converts a shapefile to Earth Engine objects. Args: in_shp (str): File path to a shapefile. Returns: object: Earth Engine objects representing the shapefile. """ ee_initialize() try: json_data = shp_to_geojson(in_shp) ee_object = geojson_to_ee(json_data) ...
"FeatureCollection", "features": buffer}, indent=2) + "\n") geojson.close() with open(out_json) as f: json_data = json.load(f) return json_data except Exception as e: print(e) def shp_to_ee(in_shp):
64
64
100
9
55
hugoledoux/geemap
geemap/geemap.py
Python
shp_to_ee
shp_to_ee
2,728
2,743
2,728
2,728
0bf42c7f44872c2ddc7cb8ccb06af6290b997f4b
bigcode/the-stack
train
86ea68d581b8aea4e21b6436
train
function
def install_from_github(url): """Install a package from a GitHub repository. Args: url (str): The URL of the GitHub repository. """ try: download_dir = os.path.join(os.path.expanduser('~'), 'Downloads') if not os.path.exists(download_dir): os.makedirs(download_dir) ...
def install_from_github(url):
"""Install a package from a GitHub repository. Args: url (str): The URL of the GitHub repository. """ try: download_dir = os.path.join(os.path.expanduser('~'), 'Downloads') if not os.path.exists(download_dir): os.makedirs(download_dir) repo_name = os.path.b...
(out_dir) if not isinstance(monitor, int): print('The monitor number must be an integer.') return try: with mss() as sct: sct.shot(output=outfile, mon=monitor) return outfile except Exception as e: print(e) return None def install_from_githu...
76
76
254
7
68
hugoledoux/geemap
geemap/geemap.py
Python
install_from_github
install_from_github
1,912
1,942
1,912
1,912
f852a30df36591bb0550578ba9b2e8728048b752
bigcode/the-stack
train
3a18c34aae3744efebe99669
train
function
def ee_function_tree(name): """Construct the tree structure based on an Earth Engine function. For example, the function "ee.Algorithms.FMask.matchClouds" will return a list ["ee.Algorithms", "ee.Algorithms.FMask", "ee.Algorithms.FMask.matchClouds"] Args: name (str): The name of the Earth Engine functi...
def ee_function_tree(name):
"""Construct the tree structure based on an Earth Engine function. For example, the function "ee.Algorithms.FMask.matchClouds" will return a list ["ee.Algorithms", "ee.Algorithms.FMask", "ee.Algorithms.FMask.matchClouds"] Args: name (str): The name of the Earth Engine function Returns: lis...
'function': line.get('function'), 'returns': line.get('returns'), 'argument': line.get('argument'), 'type': line.get('type'), 'details': line.get('details'), 'html': contents } return api_dict def ee_functio...
64
64
201
6
57
hugoledoux/geemap
geemap/geemap.py
Python
ee_function_tree
ee_function_tree
4,666
4,688
4,666
4,666
8e313b515311e1772124e139ad622996d6181b7f
bigcode/the-stack
train
1b895501343284c9785826a5
train
class
class FGSMSettingForm(forms.ModelForm): class Meta: model = ScanSettingFGSM fields = ('epsilon', 'epsilon_step', 'targeted', 'batch_size', 'dataset_num',)
class FGSMSettingForm(forms.ModelForm):
class Meta: model = ScanSettingFGSM fields = ('epsilon', 'epsilon_step', 'targeted', 'batch_size', 'dataset_num',)
fields = ('name', 'x_train', 'y_train', 'x_test', 'y_test', 'overview', 'author', 'accuracy', 'registration_date', 'rank', 'last_scan_date', 'status', 'target_path') # FGSM. class FGSMSettingForm(forms.ModelForm):
64
64
44
9
55
gyoisamurai/GyoiBoard
atd/forms.py
Python
FGSMSettingForm
FGSMSettingForm
53
56
53
53
dede7596c18d01ab4dc47fb6906dc66c7eb29335
bigcode/the-stack
train
3bc05702eea76e0aef9b4edb
train
class
class JSMASettingForm(forms.ModelForm): class Meta: model = ScanSettingJSMA fields = ('theta', 'gamma', 'batch_size', 'dataset_num',)
class JSMASettingForm(forms.ModelForm):
class Meta: model = ScanSettingJSMA fields = ('theta', 'gamma', 'batch_size', 'dataset_num',)
'batch_size', 'dataset_num',) # CnW. class CnWSettingForm(forms.ModelForm): class Meta: model = ScanSettingCnW fields = ('confidence', 'batch_size', 'dataset_num',) # JSMA. class JSMASettingForm(forms.ModelForm):
64
64
39
9
55
gyoisamurai/GyoiBoard
atd/forms.py
Python
JSMASettingForm
JSMASettingForm
67
70
67
67
27f3d4653477dbe1de127444dae184b4389afa6d
bigcode/the-stack
train
a308026176bcc7b3d7302f60
train
class
class TargetRegistrationForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(TargetRegistrationForm, self).__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs["class"] = "form-control" class Meta: model = FileUpload fields = (...
class TargetRegistrationForm(forms.ModelForm):
def __init__(self, *args, **kwargs): super(TargetRegistrationForm, self).__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs["class"] = "form-control" class Meta: model = FileUpload fields = ('file_model', 'file_x_train', 'file_y_train', '...
import os from django import forms from atd.models import FileUpload, Target, ScanSettingFGSM, ScanSettingCnW, ScanSettingJSMA class TargetRegistrationForm(forms.ModelForm):
41
64
99
8
32
gyoisamurai/GyoiBoard
atd/forms.py
Python
TargetRegistrationForm
TargetRegistrationForm
6
14
6
6
26e454082564c1c6250bbd4bbe78772526a07dfd
bigcode/the-stack
train
c46f0d05fbd1f0d84d40f97f
train
class
class CnWSettingForm(forms.ModelForm): class Meta: model = ScanSettingCnW fields = ('confidence', 'batch_size', 'dataset_num',)
class CnWSettingForm(forms.ModelForm):
class Meta: model = ScanSettingCnW fields = ('confidence', 'batch_size', 'dataset_num',)
') # FGSM. class FGSMSettingForm(forms.ModelForm): class Meta: model = ScanSettingFGSM fields = ('epsilon', 'epsilon_step', 'targeted', 'batch_size', 'dataset_num',) # CnW. class CnWSettingForm(forms.ModelForm):
64
64
37
10
54
gyoisamurai/GyoiBoard
atd/forms.py
Python
CnWSettingForm
CnWSettingForm
60
63
60
60
34380a8fc9c5a31bacad0104c294fa50ffedb2f4
bigcode/the-stack
train
8030ec05c56e38e8d7c50037
train
class
class TargetUpdateForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(TargetUpdateForm, self).__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs["class"] = "form-control" class Meta: model = FileUpload fields = ('file_model'...
class TargetUpdateForm(forms.ModelForm):
def __init__(self, *args, **kwargs): super(TargetUpdateForm, self).__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs["class"] = "form-control" class Meta: model = FileUpload fields = ('file_model',)
(): field.widget.attrs["class"] = "form-control" class Meta: model = FileUpload fields = ('file_model', 'file_x_train', 'file_y_train', 'file_x_test', 'file_y_test', 'overview', 'author') class TargetUpdateForm(forms.ModelForm):
64
64
74
8
56
gyoisamurai/GyoiBoard
atd/forms.py
Python
TargetUpdateForm
TargetUpdateForm
17
25
17
17
830c1701d401883a877a9f65bf257e3c2ac8cad4
bigcode/the-stack
train
32d2f904cee66fbfcb0b732c
train
class
class TargetForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs["class"] = "form-control" self.fields['name'].widget.attrs['readonly'] = 'readonly' self.fields['x_train'].widg...
class TargetForm(forms.ModelForm):
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs["class"] = "form-control" self.fields['name'].widget.attrs['readonly'] = 'readonly' self.fields['x_train'].widget.attrs['readonly'] = 'readonly' ...
'author') class TargetUpdateForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(TargetUpdateForm, self).__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs["class"] = "form-control" class Meta: model = FileUpload fields = ...
84
84
283
7
77
gyoisamurai/GyoiBoard
atd/forms.py
Python
TargetForm
TargetForm
28
49
28
28
c799871bddfab3ecddcd5209a4851a14c4cc02ed
bigcode/the-stack
train
3ee26595248dc7cf6c81dbca
train
function
@ops.RegisterShape("WarpRNNT") def _RNNTLossShape(op): inputs_shape = op.inputs[0].get_shape().with_rank(4) batch_size = inputs_shape[0] return [batch_size, inputs_shape]
@ops.RegisterShape("WarpRNNT") def _RNNTLossShape(op):
inputs_shape = op.inputs[0].get_shape().with_rank(4) batch_size = inputs_shape[0] return [batch_size, inputs_shape]
we are batch first, cannot use _BroadcastMul grad_loss = tf.reshape(grad_loss, (-1, 1, 1, 1)) return [grad_loss * grad, None, None, None] @ops.RegisterShape("WarpRNNT") def _RNNTLossShape(op):
64
64
52
17
47
fd873630/warp-transducer
tensorflow_binding/warprnnt_tensorflow/__init__.py
Python
_RNNTLossShape
_RNNTLossShape
44
48
44
45
3c7854b5f2f35538bf2b2ee8aa0932078b2d8cf6
bigcode/the-stack
train
f0d39bde5c1ac011d0626575
train
function
@ops.RegisterGradient("WarpRNNT") def _RNNTLossGrad(op, grad_loss, _): grad = op.outputs[1] # NOTE since here we are batch first, cannot use _BroadcastMul grad_loss = tf.reshape(grad_loss, (-1, 1, 1, 1)) return [grad_loss * grad, None, None, None]
@ops.RegisterGradient("WarpRNNT") def _RNNTLossGrad(op, grad_loss, _):
grad = op.outputs[1] # NOTE since here we are batch first, cannot use _BroadcastMul grad_loss = tf.reshape(grad_loss, (-1, 1, 1, 1)) return [grad_loss * grad, None, None, None]
should be label 0. ''' loss, _ = _warprnnt.warp_rnnt(acts, labels, input_lengths, label_lengths, blank_label) return loss @ops.RegisterGradient("WarpRNNT") def _RNNTLossGrad(op, grad_loss, _):
64
64
82
22
41
fd873630/warp-transducer
tensorflow_binding/warprnnt_tensorflow/__init__.py
Python
_RNNTLossGrad
_RNNTLossGrad
37
42
37
38
6b77037f6da0a222730ed71eee93f8a118793505
bigcode/the-stack
train
92e997b3720859ef3b6b5037
train
function
def rnnt_loss(acts, labels, input_lengths, label_lengths, blank_label=0): '''Computes the RNNT loss between a sequence of activations and a ground truth labeling. Args: acts: A 4-D Tensor of floats. The dimensions should be (B, T, U, V), where B is the minibatch index, ...
def rnnt_loss(acts, labels, input_lengths, label_lengths, blank_label=0):
'''Computes the RNNT loss between a sequence of activations and a ground truth labeling. Args: acts: A 4-D Tensor of floats. The dimensions should be (B, T, U, V), where B is the minibatch index, T is the time index, U is the prediction network sequence ...
import imp import tensorflow as tf from tensorflow.python.framework import ops lib_file = imp.find_module('kernels', __path__)[1] _warprnnt = tf.load_op_library(lib_file) def rnnt_loss(acts, labels, input_lengths, label_lengths, blank_label=0):
64
92
308
20
44
fd873630/warp-transducer
tensorflow_binding/warprnnt_tensorflow/__init__.py
Python
rnnt_loss
rnnt_loss
9
34
9
9
b6a29aa1247b40470eca18967dd863c57093c64d
bigcode/the-stack
train
41c88208910306ae8569ec4c
train
class
class LGBMDeprecationWarning(UserWarning): """Custom deprecation warning.""" pass
class LGBMDeprecationWarning(UserWarning):
"""Custom deprecation warning.""" pass
_tb): if self.path.is_file(): self.path.unlink() class LightGBMError(Exception): """Error thrown by LightGBM.""" pass # DeprecationWarning is not shown by default, so let's create our own with higher level class LGBMDeprecationWarning(UserWarning):
64
64
21
11
52
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
LGBMDeprecationWarning
LGBMDeprecationWarning
276
279
276
276
88d274e192eb5402928e884ce8ba4b9fa673c2ad
bigcode/the-stack
train
39309ac8499ccc474cb03983
train
function
def is_numpy_column_array(data): """Check whether data is a column numpy array.""" if not isinstance(data, np.ndarray): return False shape = data.shape return len(shape) == 2 and shape[1] == 1
def is_numpy_column_array(data):
"""Check whether data is a column numpy array.""" if not isinstance(data, np.ndarray): return False shape = data.shape return len(shape) == 2 and shape[1] == 1
a string or a number # ValueError: invalid literal return False def is_numpy_1d_array(data): """Check whether data is a numpy 1-D array.""" return isinstance(data, np.ndarray) and len(data.shape) == 1 def is_numpy_column_array(data):
64
64
54
7
56
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
is_numpy_column_array
is_numpy_column_array
144
149
144
144
d0fecca578357e47c4d06a788b5d7ad6a4e41bfb
bigcode/the-stack
train
f99c954ce93ad1d6c5e28a2f
train
class
class Sequence(abc.ABC): """ Generic data access interface. Object should support the following operations: .. code-block:: # Get total row number. >>> len(seq) # Random access by row index. Used for data sampling. >>> seq[10] # Range data access. Used to read ...
class Sequence(abc.ABC):
""" Generic data access interface. Object should support the following operations: .. code-block:: # Get total row number. >>> len(seq) # Random access by row index. Used for data sampling. >>> seq[10] # Range data access. Used to read data in batch when constr...
offset = max_offset f.seek(offset, SEEK_END) lines = f.readlines() if len(lines) >= 2: break offset *= 2 last_line = lines[-1].decode('utf-8').strip() if not last_line.startswith(pandas_key): last_line = lin...
147
147
491
7
139
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
Sequence
Sequence
605
668
605
605
66cf3af2f24bc215e59ddb07a0d2e7fc65158154
bigcode/the-stack
train