id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
12,138 | import argparse
import json
import math
import os
import subprocess
import time
import zipfile
from collections import Counter
import requests
The provided code snippet includes necessary dependencies for implementing the `get_artifacts_links` function. Write a Python function `def get_artifacts_links(worflow_run_id)`... | Get all artifact links from a workflow run |
12,139 | import argparse
import json
import math
import os
import subprocess
import time
import zipfile
from collections import Counter
import requests
The provided code snippet includes necessary dependencies for implementing the `download_artifact` function. Write a Python function `def download_artifact(artifact_name, artif... | Download a GitHub Action artifact from a URL. The URL is of the from `https://api.github.com/repos/huggingface/transformers/actions/artifacts/{ARTIFACT_ID}/zip`, but it can't be used to download directly. We need to get a redirect URL first. See https://docs.github.com/en/rest/actions/artifacts#download-an-artifact |
12,140 | import argparse
import json
import math
import os
import subprocess
import time
import zipfile
from collections import Counter
import requests
def get_errors_from_single_artifact(artifact_zip_path, job_links=None):
"""Extract errors from a downloaded artifact (in .zip format)"""
errors = []
failed_tests = [... | Extract errors from all artifact files |
12,141 | import argparse
import json
import math
import os
import subprocess
import time
import zipfile
from collections import Counter
import requests
The provided code snippet includes necessary dependencies for implementing the `reduce_by_error` function. Write a Python function `def reduce_by_error(logs, error_filter=None)... | count each error |
12,142 | import argparse
import json
import math
import os
import subprocess
import time
import zipfile
from collections import Counter
import requests
def get_model(test):
"""Get the model name from a test method"""
test = test.split("::")[0]
if test.startswith("tests/models/"):
test = test.split("/")[2]
... | count each error per model |
12,143 | import argparse
import json
import math
import os
import subprocess
import time
import zipfile
from collections import Counter
import requests
def make_github_table(reduced_by_error):
header = "| no. | error | status |"
sep = "|-:|:-|:-|"
lines = [header, sep]
for error in reduced_by_error:
cou... | null |
12,144 | import argparse
import json
import math
import os
import subprocess
import time
import zipfile
from collections import Counter
import requests
def make_github_table_per_model(reduced_by_model):
header = "| model | no. of errors | major error | count |"
sep = "|-:|-:|-:|-:|"
lines = [header, sep]
for mo... | null |
12,145 | import argparse
import collections
import importlib.util
import os
import re
import tempfile
import pandas as pd
from datasets import Dataset
from huggingface_hub import Repository
def get_frameworks_table():
"""
Generates a dataframe containing the supported auto classes for each model type, using the content ... | Update the metada for the Transformers repo. |
12,146 | import argparse
import collections
import importlib.util
import os
import re
import tempfile
import pandas as pd
from datasets import Dataset
from huggingface_hub import Repository
transformers_module = spec.loader.load_module()
PIPELINE_TAGS_AND_AUTO_MODELS = [
("pretraining", "MODEL_FOR_PRETRAINING_MAPPING_NAMES"... | null |
12,147 | import argparse
import os
import re
PATH_TO_TRANSFORMERS = "src/transformers"
def sort_imports(file, check_only=True):
"""
Sort `_import_structure` imports in `file`, `check_only` determines if we only check or overwrite.
"""
with open(file, encoding="utf-8") as f:
code = f.read()
if "_impor... | null |
12,148 | import argparse
import os
import re
PATH_TO_AUTO_MODULE = "src/transformers/models/auto"
def sort_auto_mapping(fname, overwrite: bool = False):
with open(fname, "r", encoding="utf-8") as f:
content = f.read()
lines = content.split("\n")
new_lines = []
line_idx = 0
while line_idx < len(lines)... | null |
12,149 | import argparse
import collections
import importlib.util
import os
import re
PATH_TO_DOCS = "docs/source/en"
def _find_text_in_file(filename, start_prompt, end_prompt):
"""
Find the text in `filename` between a line beginning with `start_prompt` and before `end_prompt`, removing empty
lines.
"""
wit... | Check the model table in the index.rst is consistent with the state of the lib and maybe `overwrite`. |
12,150 | import argparse
import collections
import importlib.util
import os
import re
PATH_TO_DOCS = "docs/source/en"
def _find_text_in_file(filename, start_prompt, end_prompt):
"""
Find the text in `filename` between a line beginning with `start_prompt` and before `end_prompt`, removing empty
lines.
"""
wit... | Check the model list in the serialization.mdx is consistent with the state of the lib and maybe `overwrite`. |
12,151 | import argparse
import json
import os
from tensorflow.core.protobuf.saved_model_pb2 import SavedModel
REPO_PATH = "."
INTERNAL_OPS = [
"Assert",
"AssignVariableOp",
"EmptyTensorList",
"MergeV2Checkpoints",
"ReadVariableOp",
"ResourceGather",
"RestoreV2",
"SaveV2",
"ShardedFilename",
... | null |
12,152 | import argparse
import os
import re
PATH_TO_TRANSFORMERS = "src/transformers"
def create_dummy_files(backend_specific_objects=None):
"""Create the content of the dummy files."""
if backend_specific_objects is None:
backend_specific_objects = read_init()
# For special correspondence backend to module... | Check if the dummy files are up to date and maybe `overwrite` with the right content. |
12,153 | import argparse
import glob
import importlib.util
import os
import re
import black
from doc_builder.style_doc import style_docstrings_in_code
TRANSFORMERS_PATH = "src/transformers"
def is_copy_consistent(filename, overwrite=False):
def check_model_list_copy(overwrite=False, max_per_line=119):
def check_copies(overwrit... | null |
12,154 | import argparse
import glob
import importlib.util
import os
import re
import black
from doc_builder.style_doc import style_docstrings_in_code
FULL_COPIES = {
"examples/tensorflow/question-answering/utils_qa.py": "examples/pytorch/question-answering/utils_qa.py",
"examples/flax/question-answering/utils_qa.py": "... | null |
12,155 | import argparse
import glob
import importlib.util
import os
import re
import black
from doc_builder.style_doc import style_docstrings_in_code
REPO_PATH = "."
LOCALIZED_READMES = {
# If the introduction or the conclusion of the list change, the prompts may need to be updated.
"README.md": {
"start_prompt... | null |
12,156 | from typing import List, Dict, Any
import argparse
import gc
import logging
import os
import re
import time
from collections import defaultdict, OrderedDict
from glob import glob
from pathlib import Path
from tqdm import tqdm
import torch
from scripts.utils import load_and_pop_last_optimizer_state
logger = logging.getL... | null |
12,157 | from typing import List, Dict, Any
import argparse
import gc
import logging
import os
import re
import time
from collections import defaultdict, OrderedDict
from glob import glob
from pathlib import Path
from tqdm import tqdm
import torch
from scripts.utils import load_and_pop_last_optimizer_state
def consolidate_shard... | null |
12,158 | import time
import argparse
import os
import numpy as np
from scripts.utils import torch_load_cpu
def save_numpy(weight_dict, to_folder):
os.makedirs(to_folder, exist_ok=True)
for tensor_name, tensor in weight_dict.items():
print(f"- Writing tensor {tensor_name} with shape {tensor.shape}")
t = ... | null |
12,159 | import argparse
import dataclasses
import math
import numpy as np
import pulp
from flexgen.compression import CompressionConfig
from flexgen.opt_config import get_opt_config
from flexgen.flex_opt import Policy
from flexgen.utils import GB, T
alpha_g = 0.8
alpha_c = 0.8
alpha_n = 0.8
def solve(config, solve_lp, args):
... | null |
12,160 | import re
def replace_url(match):
pr_number = match.group(1)
return f"[#{pr_number}](https://github.com/gee-community/geemap/pull/{pr_number})" | null |
12,161 | import os
import platform
from subprocess import DEVNULL, STDOUT, check_call
import json
The provided code snippet includes necessary dependencies for implementing the `set_heroku_vars` function. Write a Python function `def set_heroku_vars(token_name="EARTHENGINE_TOKEN")` to solve the following problem:
Extracts Eart... | Extracts Earth Engine token from the local computer and sets it as an environment variable on heroku. Args: token_name (str, optional): Name of the Earth Engine token. Defaults to 'EARTHENGINE_TOKEN'. |
12,162 | import os
import shutil
import urllib.request
from collections import deque
from pathlib import Path
import pkg_resources
from .common import *
def js_to_python(
in_file,
out_file=None,
use_qgis=True,
github_repo=None,
show_map=True,
import_geemap=False,
Map="m",
):
"""Converts an Earth ... | Converts all Earth Engine JavaScripts in a folder recursively to Python scripts. Args: in_dir (str): The input folder containing Earth Engine JavaScripts. out_dir (str, optional): The output folder containing Earth Engine Python scripts. Defaults to None. use_qgis (bool, optional): Whether to add "from ee_plugin import... |
12,163 | import os
import shutil
import urllib.request
from collections import deque
from pathlib import Path
import pkg_resources
from .common import *
import os
import shutil
The provided code snippet includes necessary dependencies for implementing the `get_js_examples` function. Write a Python function `def get_js_example... | Gets Earth Engine JavaScript examples from the geemap package. Args: out_dir (str, optional): The folder to copy the JavaScript examples to. Defaults to None. Returns: str: The folder containing the JavaScript examples. |
12,164 | import os
import shutil
import urllib.request
from collections import deque
from pathlib import Path
import pkg_resources
from .common import *
def py_to_ipynb(
in_file,
template_file=None,
out_file=None,
github_username=None,
github_repo=None,
Map="m",
):
"""Converts Earth Engine Python scr... | Converts Earth Engine Python scripts in a folder recursively to Jupyter notebooks. Args: in_dir (str): Input folder containing Earth Engine Python scripts. out_dir str, optional): Output folder. Defaults to None. template_file (str): Input jupyter notebook template file. github_username (str, optional): GitHub username... |
12,165 | import os
import shutil
import urllib.request
from collections import deque
from pathlib import Path
import pkg_resources
from .common import *
def execute_notebook(in_file):
"""Executes a Jupyter notebook and save output cells
Args:
in_file (str): Input Jupyter notebook.
"""
# command = 'jupyte... | Executes all Jupyter notebooks in the given directory recursively and save output cells. Args: in_dir (str): Input folder containing notebooks. |
12,166 | import os
import shutil
import urllib.request
from collections import deque
from pathlib import Path
import pkg_resources
from .common import *
def update_nb_header(in_file, github_username=None, github_repo=None):
"""Updates notebook header (binder and Google Colab URLs).
Args:
in_file (str): The input... | Updates header (binder and Google Colab URLs) of all notebooks in a folder . Args: in_dir (str): The input directory containing Jupyter notebooks. github_username (str, optional): GitHub username. Defaults to None. github_repo (str, optional): GitHub repo name. Defaults to None. |
12,167 | import os
import shutil
import urllib.request
from collections import deque
from pathlib import Path
import pkg_resources
from .common import *
import os
import urllib.request
The provided code snippet includes necessary dependencies for implementing the `download_gee_app` function. Write a Python function `def downl... | Downloads JavaScript source code from a GEE App Args: url (str): The URL of the GEE App. out_file (str, optional): The output file path for the downloaded JavaScript. Defaults to None. |
12,168 | import functools
import IPython
from IPython.core.display import HTML, display
import ee
import ipytree
import ipywidgets
from . import common
from traceback import format_tb
def _set_css_in_cell_output(info):
display(
HTML(
"""
<style>
.geemap-dark {
... | null |
12,169 | import logging
import os
import subprocess
import sys
import warnings
from collections.abc import Iterable
from io import BytesIO
import ee
import matplotlib as mpl
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
import requests
from matplotlib import cm, colors
from matplotlib i... | Helper function to check dependencies used for cartoee Dependencies not included in main geemap are: cartopy, PIL, and scipys raises: Exception: when conda is not found in path Exception: when auto install fails to install/import packages |
12,170 | import logging
import os
import subprocess
import sys
import warnings
from collections.abc import Iterable
from io import BytesIO
import ee
import matplotlib as mpl
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
import requests
from matplotlib import cm, colors
from matplotlib i... | Add a colorbar to the map based on visualization parameters provided args: ax (cartopy.mpl.geoaxes.GeoAxesSubplot | cartopy.mpl.geoaxes.GeoAxes): required cartopy GeoAxesSubplot object to add image overlay to loc (str, optional): string specifying the position vis_params (dict, optional): visualization parameters as a ... |
12,171 | import logging
import os
import subprocess
import sys
import warnings
from collections.abc import Iterable
from io import BytesIO
import ee
import matplotlib as mpl
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
import requests
from matplotlib import cm, colors
from matplotlib i... | Helper function to reorder a list of coordinates from [W,S,E,N] to [W,E,S,N] args: bbox (list[float]): list (or tuple) or coordinates in the order of [W,S,E,N] returns: extent (tuple[float]): tuple of coordinates in the order of [W,E,S,N] |
12,172 | import logging
import os
import subprocess
import sys
import warnings
from collections.abc import Iterable
from io import BytesIO
import ee
import matplotlib as mpl
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
import requests
from matplotlib import cm, colors
from matplotlib i... | Function to pad area around the view extent of a map, used for visual appeal args: ax (cartopy.mpl.geoaxes.GeoAxesSubplot | cartopy.mpl.geoaxes.GeoAxes): required cartopy GeoAxesSubplot object to pad view extent factor (float | list[float], optional): factor to pad view extent accepts float [0-1] of a list of floats wh... |
12,173 | import logging
import os
import subprocess
import sys
import warnings
from collections.abc import Iterable
from io import BytesIO
import ee
import matplotlib as mpl
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
import requests
from matplotlib import cm, colors
from matplotlib i... | Add a scale bar to the map. Args: ax (cartopy.mpl.geoaxes.GeoAxesSubplot | cartopy.mpl.geoaxes.GeoAxes): required cartopy GeoAxesSubplot object. metric_distance (int | float, optional): length in meters of each region of the scale bar. Default to 4. unit (str, optional): scale bar distance unit. Default to "km" at_x (f... |
12,174 | import logging
import os
import subprocess
import sys
import warnings
from collections.abc import Iterable
from io import BytesIO
import ee
import matplotlib as mpl
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
import requests
from matplotlib import cm, colors
from matplotlib i... | null |
12,175 | import logging
import os
import subprocess
import sys
import warnings
from collections.abc import Iterable
from io import BytesIO
import ee
import matplotlib as mpl
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
import requests
from matplotlib import cm, colors
from matplotlib i... | Adds a legend to the map. The legend elements can be formatted as: legend_elements = [Line2D([], [], color='#00ffff', lw=2, label='Coastline'), Line2D([], [], marker='o', color='#A8321D', label='City', markerfacecolor='#A8321D', markersize=10, ls ='')] For more legend properties, see: https://matplotlib.org/stable/api/... |
12,176 | import logging
import os
import subprocess
import sys
import warnings
from collections.abc import Iterable
from io import BytesIO
import ee
import matplotlib as mpl
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
import requests
from matplotlib import cm, colors
from matplotlib i... | Download all the images in an image collection and use them to generate a gif/video. Args: ee_ic (object): ee.ImageCollection out_dir (str): The output directory of images and video. out_gif (str): The name of the gif file. vis_params (dict): Visualization parameters as a dictionary. region (list | tuple): Geospatial r... |
12,177 | import os
The provided code snippet includes necessary dependencies for implementing the `ee_table_to_legend` function. Write a Python function `def ee_table_to_legend(in_table, out_file)` to solve the following problem:
Converts an Earth Engine color table to a dictionary Args: in_table (str): The input file path (*.... | Converts an Earth Engine color table to a dictionary Args: in_table (str): The input file path (*.txt) to the Earth Engine color table. out_file (str): The output file path (*.txt) to the legend dictionary. |
12,178 | import datetime
import glob
import io
import os
import shutil
import ee
from .common import *
from typing import Union, List
import os
The provided code snippet includes necessary dependencies for implementing the `merge_gifs` function. Write a Python function `def merge_gifs(in_gifs, out_gif)` to solve the following... | Merge multiple gifs into one. Args: in_gifs (str | list): The input gifs as a list or a directory path. out_gif (str): The output gif. Raises: Exception: Raise exception when gifsicle is not installed. |
12,179 | import datetime
import glob
import io
import os
import shutil
import ee
from .common import *
from typing import Union, List
def create_timelapse(
collection,
start_date,
end_date,
region=None,
bands=None,
frequency="year",
reducer="median",
date_format=None,
out_gif=None,
palett... | Create a timelapse from NAIP imagery. Args: roi (ee.Geometry): The region to use to filter the collection of images. It must be an ee.Geometry object. Defaults to None. start_year (int | str, optional): The start year of the timeseries. It must be formatted like this: 'YYYY'. Defaults to 2003. end_year (int | str, opti... |
12,180 | import datetime
import glob
import io
import os
import shutil
import ee
from .common import *
from typing import Union, List
import datetime
import ee
def ee_to_geojson(ee_ob... | 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): Region of interest to creat... |
12,181 | import datetime
import glob
import io
import os
import shutil
import ee
from .common import *
from typing import Union, List
import datetime
import ee
... | 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 (object, optional): Region of interest to create the timelapse. Defaults to None. start_year (int, op... |
12,182 | import datetime
import glob
import io
import os
import shutil
import ee
from .common import *
from typing import Union, List
def add_overlay(
collection: ee.ImageCollection,
overlay_data: Union[str, ee.Geometry, ee.FeatureCollection],
color: str = "black",
width: int = 1,
opacity: float = 1.0,
r... | 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 None. out_gif (str, opt... |
12,183 | import datetime
import glob
import io
import os
import shutil
import ee
from .common import *
from typing import Union, List
def add_overlay(
collection: ee.ImageCollection,
overlay_data: Union[str, ee.Geometry, ee.FeatureCollection],
color: str = "black",
width: int = 1,
opacity: float = 1.0,
r... | 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 None. out_gif (str, opt... |
12,184 | import datetime
import glob
import io
import os
import shutil
import ee
from .common import *
from typing import Union, List
def add_overlay(
collection: ee.ImageCollection,
overlay_data: Union[str, ee.Geometry, ee.FeatureCollection],
color: str = "black",
width: int = 1,
opacity: float = 1.0,
r... | Generates a Sentinel-1 timelapse animated GIF or MP4. Args: roi (object, optional): Region of interest to create the timelapse. Defaults to LV & Lake Mead. out_gif (str, optional): File path to the output animated GIF. Defaults to Downloads\s1_ts_*.gif. start_year (int, optional): Starting year for the timelapse. Defau... |
12,185 | import datetime
import glob
import io
import os
import shutil
import ee
from .common import *
from typing import Union, List
def add_overlay(
collection: ee.ImageCollection,
overlay_data: Union[str, ee.Geometry, ee.FeatureCollection],
color: str = "black",
width: int = 1,
opacity: float = 1.0,
r... | Generates a Sentinel-2 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 None. out_gif (str, ... |
12,186 | import datetime
import glob
import io
import os
import shutil
import ee
from .common import *
from typing import Union, List
def add_overlay(
collection: ee.ImageCollection,
overlay_data: Union[str, ee.Geometry, ee.FeatureCollection],
color: str = "black",
width: int = 1,
opacity: float = 1.0,
r... | Create a timelapse of GOES data. The code is adapted from Justin Braaten's code: https://code.earthengine.google.com/57245f2d3d04233765c42fb5ef19c1f4. Credits to Justin Braaten. See also https://jstnbraaten.medium.com/goes-in-earth-engine-53fbc8783c16 Args: roi (ee.Geometry, optional): The region of interest. Defaults ... |
12,187 | import datetime
import glob
import io
import os
import shutil
import ee
from .common import *
from typing import Union, List
def add_overlay(
collection: ee.ImageCollection,
overlay_data: Union[str, ee.Geometry, ee.FeatureCollection],
color: str = "black",
width: int = 1,
opacity: float = 1.0,
r... | Create a timelapse of GOES fire data. The code is adapted from Justin Braaten's code: https://code.earthengine.google.com/8a083a7fb13b95ad4ba148ed9b65475e. Credits to Justin Braaten. See also https://jstnbraaten.medium.com/goes-in-earth-engine-53fbc8783c16 Args: out_gif (str): The file path to save the gif. start_date ... |
12,188 | import datetime
import glob
import io
import os
import shutil
import ee
from .common import *
from typing import Union, List
def add_overlay(
collection: ee.ImageCollection,
overlay_data: Union[str, ee.Geometry, ee.FeatureCollection],
color: str = "black",
width: int = 1,
opacity: float = 1.0,
r... | Create MODIS NDVI timelapse. The source code is adapted from https://developers.google.com/earth-engine/tutorials/community/modis-ndvi-time-series-animation. Args: roi (ee.Geometry, optional): The geometry used to filter the image collection. Defaults to None. out_gif (str): The output gif file path. Defaults to None. ... |
12,189 | import datetime
import glob
import io
import os
import shutil
import ee
from .common import *
from typing import Union, List
def create_timelapse(
collection,
start_date,
end_date,
region=None,
bands=None,
frequency="year",
reducer="median",
date_format=None,
out_gif=None,
palett... | Creates a ocean color timelapse from MODIS. https://developers.google.com/earth-engine/datasets/catalog/NASA_OCEANDATA_MODIS-Aqua_L3SMI Args: satellite (str): The satellite to use, can be either "Terra" or "Aqua". start_date (str): The start date of the timeseries. It must be formatted like this: 'YYYY-MM-dd'. end_date... |
12,190 | import datetime
import glob
import io
import os
import shutil
import ee
from .common import *
from typing import Union, List
def create_timeseries(
collection,
start_date,
end_date,
region=None,
bands=None,
frequency="year",
reducer="median",
drop_empty=True,
date_format=None,
pa... | Create Dynamic World timeseries. Args: region (ee.Geometry | ee.FeatureCollection): The region of interest. start_date (str | ee.Date): The start date of the query. Default to "2016-01-01". end_date (str | ee.Date): The end date of the query. Default to "2021-12-31". cloud_pct (int, optional): The cloud percentage thre... |
12,191 | import datetime
import glob
import io
import os
import shutil
import ee
from .common import *
from typing import Union, List
def create_timelapse(
collection,
start_date,
end_date,
region=None,
bands=None,
frequency="year",
reducer="median",
date_format=None,
out_gif=None,
palett... | Create a timelapse from any ee.ImageCollection. Args: roi (ee.Geometry, optional): The region to use to filter the collection of images. It must be an ee.Geometry object. Defaults to None. out_gif (str): The output gif file path. Defaults to None. start_year (int, optional): Starting year for the timelapse. Defaults to... |
12,192 | import datetime
import glob
import io
import os
import shutil
import ee
from .common import *
from typing import Union, List
def gif_to_mp4(in_gif, out_mp4):
"""Converts a gif to mp4.
Args:
in_gif (str): The input gif file.
out_mp4 (str): The output mp4 file.
"""
from PIL import Image
... | Convert a vector to a gif. This function was inspired by by Johannes Uhl's shapefile2gif repo at https://github.com/johannesuhl/shapefile2gif. Credits to Johannes Uhl. Args: filename (str): The input vector file. Can be a directory path or http URL, e.g., "https://i.imgur.com/ZWSZC5z.gif" out_gif (str): The output gif ... |
12,193 | import json
import os
import shutil
import urllib.request
from pathlib import Path
import ipywidgets as widgets
import pkg_resources
from box import Box
from IPython.display import display
from .common import download_from_url, ee_data_html, search_ee_data
def get_data_csv():
"""Gets the file path to the CSV file c... | Updates the Earth Engine Data Catalog dataset list. Args: out_dir (str, optional): The output directory to save the GitHub repository. Defaults to ".". Raises: Exception: If the CSV file fails to save. |
12,194 | import json
import os
import shutil
import urllib.request
from pathlib import Path
import ipywidgets as widgets
import pkg_resources
from box import Box
from IPython.display import display
from .common import download_from_url, ee_data_html, search_ee_data
def get_data_list():
"""Gets a list of Earth Engine dataset... | Gets the Earth Engine Data Catalog as a nested dictionary. Returns: dict: The nested dictionary containing the information about the Earth Engine Data Catalog. |
12,195 | import json
import os
import shutil
import urllib.request
from pathlib import Path
import ipywidgets as widgets
import pkg_resources
from box import Box
from IPython.display import display
from .common import download_from_url, ee_data_html, search_ee_data
def search_ee_data(
keywords,
regex=False,
source=... | Gets metadata about an Earth Engine asset. Args: asset_id (str): The Earth Engine asset id. source (str): 'ee', 'community' or 'all'. Raises: Exception: If search fails. |
12,196 | import os
import ee
import folium
from box import Box
from folium import plugins
from branca.element import Figure, JavascriptLink, MacroElement
from folium.elements import JSCSSMixin
from folium.map import Layer
from jinja2 import Template
from .basemaps import xyz_to_folium
from .common import *
from .conversion impo... | Deletes a datapane report. Args: name (str): Name of the report to delete. |
12,197 | import os
import ee
import folium
from box import Box
from folium import plugins
from branca.element import Figure, JavascriptLink, MacroElement
from folium.elements import JSCSSMixin
from folium.map import Layer
from jinja2 import Template
from .basemaps import xyz_to_folium
from .common import *
from .conversion impo... | Deletes all datapane reports. |
12,198 | import os
import ee
import folium
from box import Box
from folium import plugins
from branca.element import Figure, JavascriptLink, MacroElement
from folium.elements import JSCSSMixin
from folium.map import Layer
from jinja2 import Template
from .basemaps import xyz_to_folium
from .common import *
from .conversion impo... | 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'. shown (bool, optional): A flag in... |
12,199 | import os
import ee
import folium
from box import Box
from folium import plugins
from branca.element import Figure, JavascriptLink, MacroElement
from folium.elements import JSCSSMixin
from folium.map import Layer
from jinja2 import Template
from .basemaps import xyz_to_folium
from .common import *
from .conversion impo... | Returns the map center coordinates for a given latitude and longitude. If the system variable 'map_center' exists, it is used. Otherwise, the default is returned. Args: lat (float): Latitude. lon (float): Longitude. Raises: Exception: If streamlit is not installed. Returns: list: The map center coordinates. |
12,200 | import os
import ee
import folium
from box import Box
from folium import plugins
from branca.element import Figure, JavascriptLink, MacroElement
from folium.elements import JSCSSMixin
from folium.map import Layer
from jinja2 import Template
from .basemaps import xyz_to_folium
from .common import *
from .conversion impo... | Saves the map bounds to the session state. Args: map (folium.folium.Map): The map to save the bounds from. |
12,201 | import os
import ee
import folium
from box import Box
from folium import plugins
from branca.element import Figure, JavascriptLink, MacroElement
from folium.elements import JSCSSMixin
from folium.map import Layer
from jinja2 import Template
from .basemaps import xyz_to_folium
from .common import *
from .conversion impo... | null |
12,202 | from .common import check_package
def osm_gdf_from_address(address, tags, dist=1000):
"""Create GeoDataFrame of OSM entities within some distance N, S, E, W of address.
Args:
address (str): The address to geocode and use as the central point around which to get the geometries.
tags (dict): Dict ... | Download OSM entities within some distance N, S, E, W of address as a shapefile. Args: address (str): The address to geocode and use as the central point around which to get the geometries. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each ... |
12,203 | from .common import check_package
def osm_gdf_from_address(address, tags, dist=1000):
"""Create GeoDataFrame of OSM entities within some distance N, S, E, W of address.
Args:
address (str): The address to geocode and use as the central point around which to get the geometries.
tags (dict): Dict ... | Download OSM entities within some distance N, S, E, W of address as a GeoJSON. Args: address (str): The address to geocode and use as the central point around which to get the geometries. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each in... |
12,204 | from .common import check_package
def osm_gdf_from_place(query, tags, which_result=None, buffer_dist=None):
"""Create GeoDataFrame of OSM entities within boundaries of geocodable place(s).
Args:
query (str | dict | list): Query string(s) or structured dict(s) to geocode.
tags (dict): Dict of tag... | Download OSM entities within boundaries of geocodable place(s) as a shapefile. Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result ... |
12,205 | from .common import check_package
def osm_gdf_from_place(query, tags, which_result=None, buffer_dist=None):
"""Create GeoDataFrame of OSM entities within boundaries of geocodable place(s).
Args:
query (str | dict | list): Query string(s) or structured dict(s) to geocode.
tags (dict): Dict of tag... | Download OSM entities within boundaries of geocodable place(s) as a GeoJSON. Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result ma... |
12,206 | from .common import check_package
def osm_gdf_from_point(center_point, tags, dist=1000):
"""Create GeoDataFrame of OSM entities within some distance N, S, E, W of a point.
Args:
center_point (tuple): The (lat, lng) center point around which to get the geometries.
tags (dict): Dict of tags used f... | Download OSM entities within some distance N, S, E, W of point as a shapefile. Args: center_point (tuple): The (lat, lng) center point around which to get the geometries. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Eac... |
12,207 | from .common import check_package
def osm_gdf_from_point(center_point, tags, dist=1000):
"""Create GeoDataFrame of OSM entities within some distance N, S, E, W of a point.
Args:
center_point (tuple): The (lat, lng) center point around which to get the geometries.
tags (dict): Dict of tags used f... | Download OSM entities within some distance N, S, E, W of point as a GeoJSON. Args: center_point (tuple): The (lat, lng) center point around which to get the geometries. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each ... |
12,208 | from .common import check_package
def osm_gdf_from_polygon(polygon, tags):
"""Create GeoDataFrame of OSM entities within boundaries of a (multi)polygon.
Args:
polygon (shapely.geometry.Polygon | shapely.geometry.MultiPolygon): Geographic boundaries to fetch geometries within
tags (dict): Dict of... | Download OSM entities within boundaries of a (multi)polygon as a shapefile. Args: polygon (shapely.geometry.Polygon | shapely.geometry.MultiPolygon): Geographic boundaries to fetch geometries within tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection... |
12,209 | from .common import check_package
def osm_gdf_from_polygon(polygon, tags):
"""Create GeoDataFrame of OSM entities within boundaries of a (multi)polygon.
Args:
polygon (shapely.geometry.Polygon | shapely.geometry.MultiPolygon): Geographic boundaries to fetch geometries within
tags (dict): Dict of... | Download OSM entities within boundaries of a (multi)polygon as a GeoJSON. Args: polygon (shapely.geometry.Polygon | shapely.geometry.MultiPolygon): Geographic boundaries to fetch geometries within tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection o... |
12,210 | from .common import check_package
def osm_gdf_from_bbox(north, south, east, west, tags):
"""Create a GeoDataFrame of OSM entities within a N, S, E, W bounding box.
Args:
north (float): Northern latitude of bounding box.
south (float): Southern latitude of bounding box.
east (float): East... | Download OSM entities within a N, S, E, W bounding box as a shapefile. Args: north (float): Northern latitude of bounding box. south (float): Southern latitude of bounding box. east (float): Eastern longitude of bounding box. west (float): Western longitude of bounding box. tags (dict): Dict of tags used for finding ob... |
12,211 | from .common import check_package
def osm_gdf_from_bbox(north, south, east, west, tags):
"""Create a GeoDataFrame of OSM entities within a N, S, E, W bounding box.
Args:
north (float): Northern latitude of bounding box.
south (float): Southern latitude of bounding box.
east (float): East... | Download OSM entities within a N, S, E, W bounding box as a GeoJSON. Args: north (float): Northern latitude of bounding box. south (float): Southern latitude of bounding box. east (float): Eastern longitude of bounding box. west (float): Western longitude of bounding box. tags (dict): Dict of tags used for finding obje... |
12,212 | from .common import check_package
def check_package(name, URL=""):
try:
__import__(name.lower())
except Exception:
raise ImportError(
f"{name} is not installed. Please install it before proceeding. {URL}"
)
The provided code snippet includes necessary dependencies for imple... | Create a GeoDataFrame of OSM entities in an OSM-formatted XML file. Args: filepath (str): File path to file containing OSM XML data polygon (shapely.geometry.Polygon, optional): Optional geographic boundary to filter objects. Defaults to None. tags (dict): Dict of tags used for finding objects in the selected area. Res... |
12,213 | from .common import check_package
def osm_gdf_from_geocode(
query,
which_result=None,
by_osmid=False,
buffer_dist=None,
):
"""Retrieves place(s) by name or ID from the Nominatim API as a GeoDataFrame.
Args:
query (str | dict | list): Query string(s) or structured dict(s) to geocode.
... | Download place(s) by name or ID from the Nominatim API as a shapefile. Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. filepath (str): File path to the output shapefile. which_result (int, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise... |
12,214 | from .common import check_package
def osm_gdf_from_geocode(
query,
which_result=None,
by_osmid=False,
buffer_dist=None,
):
"""Retrieves place(s) by name or ID from the Nominatim API as a GeoDataFrame.
Args:
query (str | dict | list): Query string(s) or structured dict(s) to geocode.
... | Download place(s) by name or ID from the Nominatim API as a GeoJSON. Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. filepath (str): File path to the output GeoJSON. which_result (int, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an ... |
12,215 | from .common import check_package
The provided code snippet includes necessary dependencies for implementing the `osm_tags_list` function. Write a Python function `def osm_tags_list()` to solve the following problem:
Open a browser to see all tags of OSM features.
Here is the function:
def osm_tags_list():
"""Op... | Open a browser to see all tags of OSM features. |
12,216 | import multiprocessing as mp
import os
from functools import partial
import ee
import numpy as np
import pandas as pd
def tree_to_string(estimator, feature_names, labels=None, output_mode="INFER"):
"""Function to convert a sklearn decision tree object to a string format that EE can interpret
args:
estim... | Function to convert a ensemble of decision trees into a list of strings. Wraps `tree_to_string` args: estimator (sklearn.ensemble.estimator): A decision tree classifier or regressor object created using sklearn feature_names (list[str]): List of strings that define the name of features (i.e. bands) used to create the m... |
12,217 | import multiprocessing as mp
import os
from functools import partial
import ee
import numpy as np
import pandas as pd
The provided code snippet includes necessary dependencies for implementing the `strings_to_classifier` function. Write a Python function `def strings_to_classifier(trees)` to solve the following proble... | Function that takes string representation of decision trees and creates a ee.Classifier that can be used with ee objects args: trees (list[str]): list of string representation of the decision trees returns: classifier (ee.Classifier): ee classifier object representing an ensemble decision tree |
12,218 | import multiprocessing as mp
import os
from functools import partial
import ee
import numpy as np
import pandas as pd
The provided code snippet includes necessary dependencies for implementing the `export_trees_to_fc` function. Write a Python function `def export_trees_to_fc(trees, asset_id, description="geemap_rf_exp... | Function that creates a feature collection with a property tree which contains the string representation of decision trees and exports to ee asset for later use args: trees (list[str]): list of string representation of the decision trees asset_id (str): ee asset id path to export the feature collection to kwargs: descr... |
12,219 | import multiprocessing as mp
import os
from functools import partial
import ee
import numpy as np
import pandas as pd
The provided code snippet includes necessary dependencies for implementing the `trees_to_csv` function. Write a Python function `def trees_to_csv(trees, out_csv)` to solve the following problem:
Save a... | Save a list of strings (an ensemble of decision trees) to a CSV file. Args: trees (list): A list of strings (an ensemble of decision trees). out_csv (str): File path to the output csv |
12,220 | import multiprocessing as mp
import os
from functools import partial
import ee
import numpy as np
import pandas as pd
def fc_to_classifier(fc):
"""Function that takes a feature collection resulting from `export_trees_to_fc` and creates a ee.Classifier that can be used with ee objects
args:
fc (ee.Featur... | Convert a CSV file containing a list of strings (an ensemble of decision trees) to an ee.Classifier. Args: in_csv (str): File path to the input CSV. Returns: object: ee.Classifier. |
12,221 | import box
import ee
import folium
import ipyleaflet
from functools import lru_cache
from . import common
def _ee_object_to_image(ee_object, vis_params):
def _get_tile_url_format(ee_object, vis_params):
image = _ee_object_to_image(ee_object, vis_params)
map_id_dict = ee.Image(image).getMapId(vis_params)
re... | null |
12,222 | import box
import ee
import folium
import ipyleaflet
from functools import lru_cache
from . import common
def _validate_palette(palette):
if isinstance(palette, tuple):
palette = list(palette)
if isinstance(palette, box.Box):
if "default" not in palette:
raise ValueError("The provide... | null |
12,223 | import os
import numpy as np
import pandas as pd
import ipywidgets as widgets
from .basemaps import xyz_to_plotly
from .common import *
from .osm import *
from . import examples
import os
import shutil
The provided code snippet includes necessary dependencies for implementing the `fix_widget_error` function. Write a ... | Fix FigureWidget - 'mapbox._derived' Value Error. Adopted from: https://github.com/plotly/plotly.py/issues/2570#issuecomment-738735816 |
12,224 | import collections
import os
import requests
import folium
import ipyleaflet
import xyzservices
from .common import check_package, planet_tiles
XYZ_TILES = {
"OpenStreetMap": {
"url": "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
"attribution": "OpenStreetMap",
"name": "OpenStreetMap... | Convert xyz tile services to ipyleaflet tile layers. Returns: dict: A dictionary of ipyleaflet tile layers. |
12,225 | import collections
import os
import requests
import folium
import ipyleaflet
import xyzservices
from .common import check_package, planet_tiles
XYZ_TILES = {
"OpenStreetMap": {
"url": "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
"attribution": "OpenStreetMap",
"name": "OpenStreetMap... | Convert xyz tile services to folium tile layers. Returns: dict: A dictionary of folium tile layers. |
12,226 | import collections
import os
import requests
import folium
import ipyleaflet
import xyzservices
from .common import check_package, planet_tiles
XYZ_TILES = {
"OpenStreetMap": {
"url": "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
"attribution": "OpenStreetMap",
"name": "OpenStreetMap... | Convert xyz tile services to pydeck custom tile layers. Returns: dict: A dictionary of pydeck tile layers. |
12,227 | import collections
import os
import requests
import folium
import ipyleaflet
import xyzservices
from .common import check_package, planet_tiles
XYZ_TILES = {
"OpenStreetMap": {
"url": "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
"attribution": "OpenStreetMap",
"name": "OpenStreetMap... | Convert xyz tile services to plotly tile layers. Returns: dict: A dictionary of plotly tile layers. |
12,228 | import collections
import os
import requests
import folium
import ipyleaflet
import xyzservices
from .common import check_package, planet_tiles
The provided code snippet includes necessary dependencies for implementing the `search_qms` function. Write a Python function `def search_qms(keywords, limit=10)` to solve the... | Search qms files for keywords. Reference: https://github.com/geopandas/xyzservices/issues/65 Args: keywords (str): Keywords to search for. limit (int): Number of results to return. |
12,229 | import collections
import os
import requests
import folium
import ipyleaflet
import xyzservices
from .common import check_package, planet_tiles
def get_qms(service_id):
QMS_API = "https://qms.nextgis.com/api/v1/geoservices"
service_details = requests.get(f"{QMS_API}/{service_id}")
return service_details.jso... | Convert a qms service to an ipyleaflet tile layer. Args: service_id (str): Service ID. Returns: ipyleaflet.TileLayer: An ipyleaflet tile layer. |
12,230 | import csv
import datetime
import io
import json
import math
import os
import requests
import shutil
import tarfile
import urllib.request
import warnings
import zipfile
import ee
import ipywidgets as widgets
from ipytree import Node, Tree
from typing import Union, List, Dict, Optional, Tuple
def ee_export_image(
ee... | 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 specified. Defaults to None. crs (str, optio... |
12,231 | import csv
import datetime
import io
import json
import math
import os
import requests
import shutil
import tarfile
import urllib.request
import warnings
import zipfile
import ee
import ipywidgets as widgets
from ipytree import Node, Tree
from typing import Union, List, Dict, Optional, Tuple
def ee_export_image_to_driv... | Creates a batch task to export an ImageCollection as raster images to Google Drive. Args: ee_object: The image collection to export. descriptions: A list of human-readable names of the tasks. folder: The name of a unique folder in your Drive account to export into. Defaults to the root of the drive. fileNamePrefix: The... |
12,232 | import csv
import datetime
import io
import json
import math
import os
import requests
import shutil
import tarfile
import urllib.request
import warnings
import zipfile
import ee
import ipywidgets as widgets
from ipytree import Node, Tree
from typing import Union, List, Dict, Optional, Tuple
def ee_export_image_to_asse... | Creates a batch task to export an ImageCollection as raster images to Google Drive. Args: ee_object: The image collection to export. descriptions: A list of human-readable names of the tasks. assetIds: The destination asset ID. pyramidingPolicy: The pyramiding policy to apply to each band in the image, a dictionary key... |
12,233 | import csv
import datetime
import io
import json
import math
import os
import requests
import shutil
import tarfile
import urllib.request
import warnings
import zipfile
import ee
import ipywidgets as widgets
from ipytree import Node, Tree
from typing import Union, List, Dict, Optional, Tuple
def ee_export_image_to_clou... | Creates a batch task to export an ImageCollection as raster images to a Google Cloud bucket. Args: ee_object: The image collection to export. descriptions: A list of human-readable names of the tasks. bucket: The name of a Cloud Storage bucket for the export. fileNamePrefix: Cloud Storage object name prefix for the exp... |
12,234 | import csv
import datetime
import io
import json
import math
import os
import requests
import shutil
import tarfile
import urllib.request
import warnings
import zipfile
import ee
import ipywidgets as widgets
from ipytree import Node, Tree
from typing import Union, List, Dict, Optional, Tuple
def random_string(string_le... | Exports Earth Engine FeatureCollection to geojson. Args: ee_object (object): ee.FeatureCollection to export. filename (str): Output file name. Defaults to None. selectors (list, optional): A list of attributes to export. Defaults to None. timeout (int, optional): Timeout in seconds. Defaults to 300 seconds. proxies (di... |
12,235 | import csv
import datetime
import io
import json
import math
import os
import requests
import shutil
import tarfile
import urllib.request
import warnings
import zipfile
import ee
import ipywidgets as widgets
from ipytree import Node, Tree
from typing import Union, List, Dict, Optional, Tuple
The provided code snippet ... | Creates a task to export a FeatureCollection to Drive. Args: collection: The feature collection to be exported. description: Human-readable name of the task. folder: The name of a unique folder in your Drive account to export into. Defaults to the root of the drive. fileNamePrefix: The Google Drive filename for the exp... |
12,236 | import csv
import datetime
import io
import json
import math
import os
import requests
import shutil
import tarfile
import urllib.request
import warnings
import zipfile
import ee
import ipywidgets as widgets
from ipytree import Node, Tree
from typing import Union, List, Dict, Optional, Tuple
def ee_user_id():
"""Ge... | Creates a task to export a FeatureCollection to Asset. Args: collection: The feature collection to be exported. description: Human-readable name of the task. assetId: The destination asset ID. maxVertices: Max number of uncut vertices per geometry; geometries with more vertices will be cut into pieces smaller than this... |
12,237 | import csv
import datetime
import io
import json
import math
import os
import requests
import shutil
import tarfile
import urllib.request
import warnings
import zipfile
import ee
import ipywidgets as widgets
from ipytree import Node, Tree
from typing import Union, List, Dict, Optional, Tuple
The provided code snippet ... | Creates a task to export a FeatureCollection to Google Cloud Storage. Args: collection: The feature collection to be exported. description: Human-readable name of the task. bucket: The name of a Cloud Storage bucket for the export. fileNamePrefix: Cloud Storage object name prefix for the export. Defaults to the name of... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.