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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a0d6f946b7481fc5235a00cc | train | class | class HNSW(pecos.BaseClass):
@dc.dataclass
class TrainParams(pecos.BaseParams):
"""Training Parameters of HNSW class
Attributes:
M (int): maximum number of edges per node for layer l=1,...,L. For layer l=0, its 2*M. Default 32
efC (int): size of the priority queue when p... | class HNSW(pecos.BaseClass):
@dc.dataclass
| class TrainParams(pecos.BaseParams):
"""Training Parameters of HNSW class
Attributes:
M (int): maximum number of edges per node for layer l=1,...,L. For layer l=0, its 2*M. Default 32
efC (int): size of the priority queue when performing best first search during construction... | # Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
# with the License. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file acco... | 252 | 256 | 2,445 | 16 | 235 | xeisberg/pecos | pecos/ann/hnsw/model.py | Python | HNSW | HNSW | 31 | 266 | 31 | 32 | 4749cd3ebafb78f5fe8d147282266561e4bcbcac | bigcode/the-stack | train |
edb2e157522dcf11db2d46bd | train | class | class IkatsMetadataMgr(IkatsGenericApiEndPoint):
"""
Ikats EndPoint specific to Metadata management
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.api.emulate:
self.dm_client = DatamodelStub(session=self.api.session)
else:
... | class IkatsMetadataMgr(IkatsGenericApiEndPoint):
| """
Ikats EndPoint specific to Metadata management
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.api.emulate:
self.dm_client = DatamodelStub(session=self.api.session)
else:
self.dm_client = DatamodelClient(session=self... | # -*- coding: utf-8 -*-
"""
Copyright 2019 CS Systèmes d'Information
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law... | 209 | 251 | 838 | 13 | 195 | IKATS/ikats_api | ikats/manager/metadata_mgr_.py | Python | IkatsMetadataMgr | IkatsMetadataMgr | 27 | 128 | 27 | 27 | be8b33ec8bec056206bd23a5f0aeb4a44b2ea703 | bigcode/the-stack | train |
85606ba88364be84d6fb6ff6 | train | class | class Event:
def __init__(self, Player, Event, url, end):
self.breakloop = False
self.player = Player
self.event = Event
self.end = end
self.eventList = []
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
chrome_opti... | class Event:
| def __init__(self, Player, Event, url, end):
self.breakloop = False
self.player = Player
self.event = Event
self.end = end
self.eventList = []
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
chrome_options.add_argum... | import concurrent.futures
from datetime import datetime
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.ui import WebDriverWait
from se... | 70 | 148 | 495 | 3 | 66 | kevinfjiang/NBATextAlerts | NBATextAlerts/gameCheckBot.py | Python | Event | Event | 15 | 89 | 15 | 15 | 478dcbda2ee776269da948b06e790d4810a324c9 | bigcode/the-stack | train |
ce611e3a0e239b011c1e1fbf | train | class | class Professor(Pessoa):
def __init__(self, nome, disciplinas, matricula = None):
# invocando construtor da superclasse
super().__init__(nome)
# disciplinas é um dicionario (chave, valor). P.ex. {'poo':'Programacao OO'}
self.disciplinas = disciplinas
self.matricula = matricu... | class Professor(Pessoa):
| def __init__(self, nome, disciplinas, matricula = None):
# invocando construtor da superclasse
super().__init__(nome)
# disciplinas é um dicionario (chave, valor). P.ex. {'poo':'Programacao OO'}
self.disciplinas = disciplinas
self.matricula = matricula
def listarDiscipl... | # -*- coding: utf-8 -*-
from pessoa import Pessoa
# Professor herda da classe Pessoa
class Professor(Pessoa):
| 26 | 65 | 217 | 5 | 20 | std29006/oo-java-e-python | exemplo04/professor.py | Python | Professor | Professor | 6 | 29 | 6 | 7 | 9f8a97a0387065d80b49f470290212de2ef9fe81 | bigcode/the-stack | train |
5890ff64b9288177cf62a8e1 | train | function | def test_exists():
"""exists"""
assert os.path.isfile(prg)
| def test_exists():
| """exists"""
assert os.path.isfile(prg)
| #!/usr/bin/env python3
"""tests for jump.py"""
import os
import subprocess
import sys
prg = "./jump.py"
# --------------------------------------------------
def test_exists():
| 36 | 64 | 16 | 4 | 32 | FreshGrill/tiny_python_projects | 04_jump_the_five/test.py | Python | test_exists | test_exists | 13 | 16 | 13 | 13 | 76eddf741a543d5c0a9d9a610dd2741751a6d4c3 | bigcode/the-stack | train |
8abb3d11a34a604472d7c4cc | train | function | def test_02():
"""test"""
# rv, out = getstatusoutput(f'{prg} "That number to call is 098-765-4321."')
# assert rv == 0
# assert out.rstrip() == 'That number to call is 512-340-6789.'
output = ""
try:
output = subprocess.check_output(
["python3", prg, "That number to call is... | def test_02():
| """test"""
# rv, out = getstatusoutput(f'{prg} "That number to call is 098-765-4321."')
# assert rv == 0
# assert out.rstrip() == 'That number to call is 512-340-6789.'
output = ""
try:
output = subprocess.check_output(
["python3", prg, "That number to call is 098-765-4321."... | error: " + e.output)
print("Command output: " + output)
sys.exit(e.returncode)
# assert False,output.decode('utf-8').lower()
assert output.decode("utf-8") == "987-604-3215"
# --------------------------------------------------
def test_02():
| 64 | 64 | 204 | 5 | 59 | FreshGrill/tiny_python_projects | 04_jump_the_five/test.py | Python | test_02 | test_02 | 60 | 80 | 60 | 60 | 17dd6fce898e6f5e207c68de0bcc74eddf2fff30 | bigcode/the-stack | train |
5ffb126cd1e5d05698103983 | train | function | def test_usage():
"""usage"""
for flag in ["-h", "--help"]:
# rv, out = getstatusoutput(f'{prg} {flag}')
# assert rv == 0
# assert out.lower().startswith('usage')
output = ""
try:
output = subprocess.check_output(["python3", prg, flag])
# print (... | def test_usage():
| """usage"""
for flag in ["-h", "--help"]:
# rv, out = getstatusoutput(f'{prg} {flag}')
# assert rv == 0
# assert out.lower().startswith('usage')
output = ""
try:
output = subprocess.check_output(["python3", prg, flag])
# print ("Command output: "... | #!/usr/bin/env python3
"""tests for jump.py"""
import os
import subprocess
import sys
prg = "./jump.py"
# --------------------------------------------------
def test_exists():
"""exists"""
assert os.path.isfile(prg)
# --------------------------------------------------
def test_usage():
| 55 | 64 | 161 | 4 | 51 | FreshGrill/tiny_python_projects | 04_jump_the_five/test.py | Python | test_usage | test_usage | 20 | 37 | 20 | 20 | 217accc2fc48d9e08f6f6f92046f21576d4fb193 | bigcode/the-stack | train |
76c4a583730e98599bb0b0b8 | train | function | def test_01():
"""test"""
# rv, out = getstatusoutput(f'{prg} 123-456-7890')
# assert rv == 0
# assert out == '987-604-3215'
output = ""
try:
output = subprocess.check_output(["python3", prg, "123-456-7890"])
# print ("Command output: " + output.decode('utf-8'))
except subpr... | def test_01():
| """test"""
# rv, out = getstatusoutput(f'{prg} 123-456-7890')
# assert rv == 0
# assert out == '987-604-3215'
output = ""
try:
output = subprocess.check_output(["python3", prg, "123-456-7890"])
# print ("Command output: " + output.decode('utf-8'))
except subprocess.CalledPro... | Command error: " + e.output)
print("Command output: " + output)
sys.exit(e.returncode)
# assert False,output.decode('utf-8').lower()
assert output.decode("utf-8").lower().strip().startswith("usage")
# --------------------------------------------------
def test_01():
| 64 | 64 | 166 | 5 | 59 | FreshGrill/tiny_python_projects | 04_jump_the_five/test.py | Python | test_01 | test_01 | 41 | 56 | 41 | 41 | 0c647c8ff4babc75e4b9ef6ac56fd61fca6a3aa3 | bigcode/the-stack | train |
f71d40529288af5d39f35149 | train | class | @pulumi.output_type
class ListConfigurationStoreKeysResult:
"""
The result of a request to list API keys.
"""
def __init__(__self__, next_link=None, value=None):
if next_link and not isinstance(next_link, str):
raise TypeError("Expected argument 'next_link' to be a str")
pulu... | @pulumi.output_type
class ListConfigurationStoreKeysResult:
| """
The result of a request to list API keys.
"""
def __init__(__self__, next_link=None, value=None):
if next_link and not isinstance(next_link, str):
raise TypeError("Expected argument 'next_link' to be a str")
pulumi.set(__self__, "next_link", next_link)
if value an... | , Mapping, Optional, Sequence, Union
from .. import _utilities, _tables
from . import outputs
__all__ = [
'ListConfigurationStoreKeysResult',
'AwaitableListConfigurationStoreKeysResult',
'list_configuration_store_keys',
]
@pulumi.output_type
class ListConfigurationStoreKeysResult:
| 67 | 67 | 226 | 13 | 54 | pulumi/pulumi-azure-nextgen | sdk/python/pulumi_azure_nextgen/appconfiguration/list_configuration_store_keys.py | Python | ListConfigurationStoreKeysResult | ListConfigurationStoreKeysResult | 18 | 45 | 18 | 19 | 6e5aebb491f5c00d7be5e9d55c424117ce3c56f4 | bigcode/the-stack | train |
ea51bea722e02594a8a28165 | train | function | def list_configuration_store_keys(config_store_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
skip_token: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableListConfi... | def list_configuration_store_keys(config_store_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
skip_token: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableListConfi... | """
The result of a request to list API keys.
API Version: 2020-06-01.
:param str config_store_name: The name of the configuration store.
:param str resource_group_name: The name of the resource group to which the container registry belongs.
:param str skip_token: A skip token is used to conti... | constant-test
def __await__(self):
if False:
yield self
return ListConfigurationStoreKeysResult(
next_link=self.next_link,
value=self.value)
def list_configuration_store_keys(config_store_name: Optional[str] = None,
resource_group... | 96 | 96 | 322 | 58 | 38 | pulumi/pulumi-azure-nextgen | sdk/python/pulumi_azure_nextgen/appconfiguration/list_configuration_store_keys.py | Python | list_configuration_store_keys | list_configuration_store_keys | 58 | 83 | 58 | 61 | 00aa49861d786819f712a1e3d900e4232ffd6031 | bigcode/the-stack | train |
161b913c0bcbbf866da65843 | train | class | class AwaitableListConfigurationStoreKeysResult(ListConfigurationStoreKeysResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return ListConfigurationStoreKeysResult(
next_link=self.next_link,
value=self.value)
| class AwaitableListConfigurationStoreKeysResult(ListConfigurationStoreKeysResult):
# pylint: disable=using-constant-test
| def __await__(self):
if False:
yield self
return ListConfigurationStoreKeysResult(
next_link=self.next_link,
value=self.value)
| .getter
def value(self) -> Optional[Sequence['outputs.ApiKeyResponseResult']]:
"""
The collection value.
"""
return pulumi.get(self, "value")
class AwaitableListConfigurationStoreKeysResult(ListConfigurationStoreKeysResult):
# pylint: disable=using-constant-test
| 64 | 64 | 60 | 25 | 39 | pulumi/pulumi-azure-nextgen | sdk/python/pulumi_azure_nextgen/appconfiguration/list_configuration_store_keys.py | Python | AwaitableListConfigurationStoreKeysResult | AwaitableListConfigurationStoreKeysResult | 48 | 55 | 48 | 49 | 959258dd5f84293b6775ec0615cf403b2c816b74 | bigcode/the-stack | train |
f850dd7ae9af2f6e179f7f60 | train | function | def subp_run(cmd, allow_failure: bool = False) -> subprocess.CompletedProcess:
output = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
if not allow_failure and output.returncode != 0:
raise CattTestError('The command "{}" failed.'.format(" ".join(cmd)))
... | def subp_run(cmd, allow_failure: bool = False) -> subprocess.CompletedProcess:
| output = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
if not allow_failure and output.returncode != 0:
raise CattTestError('The command "{}" failed.'.format(" ".join(cmd)))
return output
| d"]
VALIDATE_ARGS = ["info", "-j"]
STOP_ARGS = ["stop"]
SCAN_CMD = ["catt", "scan", "-j"]
# Uses subprocess.run(), so py3.5+ is required.
def subp_run(cmd, allow_failure: bool = False) -> subprocess.CompletedProcess:
| 64 | 64 | 74 | 18 | 46 | DatGuy1/catt | realcc_tests/test_procedure.py | Python | subp_run | subp_run | 16 | 20 | 16 | 16 | 5dbbb47007c12f38bcea473d5bd2cd64cca22494 | bigcode/the-stack | train |
e98679148d27f3f31b4434fb | train | class | class CattTestError(click.ClickException):
pass
| class CattTestError(click.ClickException):
| pass
| output = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
if not allow_failure and output.returncode != 0:
raise CattTestError('The command "{}" failed.'.format(" ".join(cmd)))
return output
class CattTestError(click.ClickException):
| 64 | 64 | 12 | 9 | 54 | DatGuy1/catt | realcc_tests/test_procedure.py | Python | CattTestError | CattTestError | 23 | 24 | 23 | 23 | 31fd0e1be3e34a6c2edb0b0435d88631702077f4 | bigcode/the-stack | train |
49daaa823986eb4f3491747d | train | function | @click.command()
@click.option("-s", "--standard", help="Name of standard chromecast device.")
@click.option("-a", "--audio", help="Name of audio chromecast device.")
@click.option("-u", "--ultra", help="Name of ultra chromecast device.")
def cli(standard, audio, ultra):
if run_tests(standard=standard, audio=audio,... | @click.command()
@click.option("-s", "--standard", help="Name of standard chromecast device.")
@click.option("-a", "--audio", help="Name of audio chromecast device.")
@click.option("-u", "--ultra", help="Name of ultra chromecast device.")
def cli(standard, audio, ultra):
| if run_tests(standard=standard, audio=audio, ultra=ultra):
click.echo("\nAll tests were successfully completed.")
else:
raise CattTestError("Some tests were not successful.")
| @click.command()
@click.option("-s", "--standard", help="Name of standard chromecast device.")
@click.option("-a", "--audio", help="Name of audio chromecast device.")
@click.option("-u", "--ultra", help="Name of ultra chromecast device.")
def cli(standard, audio, ultra):
| 64 | 64 | 109 | 64 | 0 | DatGuy1/catt | realcc_tests/test_procedure.py | Python | cli | cli | 282 | 290 | 282 | 286 | 9650e13456b1c806b6d4be6b7f9a635b33da1e31 | bigcode/the-stack | train |
d09e4599869e6c2ea9a848b1 | train | class | class CattTest:
def __init__(
self,
desc: str,
cmd_args: list,
sleep: int = 10,
should_fail: bool = False,
substring: bool = False,
time_test: bool = False,
check_data: Any = None,
check_err: str = "",
) -> None:
if (should_fail and... | class CattTest:
| def __init__(
self,
desc: str,
cmd_args: list,
sleep: int = 10,
should_fail: bool = False,
substring: bool = False,
time_test: bool = False,
check_data: Any = None,
check_err: str = "",
) -> None:
if (should_fail and not check_err) ... | #!/usr/bin/env python3
import json
import subprocess
import time
from typing import Any
import click
CMD_BASE = ["catt", "-d"]
VALIDATE_ARGS = ["info", "-j"]
STOP_ARGS = ["stop"]
SCAN_CMD = ["catt", "scan", "-j"]
# Uses subprocess.run(), so py3.5+ is required.
def subp_run(cmd, allow_failure: bool = False) -> subpr... | 169 | 220 | 734 | 5 | 163 | DatGuy1/catt | realcc_tests/test_procedure.py | Python | CattTest | CattTest | 27 | 111 | 27 | 27 | bd80d77f4023b5ad42f0dc2b90e5e53319fb7268 | bigcode/the-stack | train |
d8c582d9119138853d2a911b | train | function | def run_tests(standard: str = "", audio: str = "", ultra: str = ""):
if not standard and not audio and not ultra:
raise CattTestError("No test devices were specified.")
test_outcomes = [] # type: list
all_suites = zip([standard, audio, ultra], [STANDARD_TESTS, AUDIO_TESTS, ULTRA_TESTS])
suites... | def run_tests(standard: str = "", audio: str = "", ultra: str = ""):
| if not standard and not audio and not ultra:
raise CattTestError("No test devices were specified.")
test_outcomes = [] # type: list
all_suites = zip([standard, audio, ultra], [STANDARD_TESTS, AUDIO_TESTS, ULTRA_TESTS])
suites_to_run = {} # type: dict
scan_result = json.loads(subp_run(SCAN... | ", "https://physicallysick.bandcamp.com/track/freak-is-out"],
substring=True,
check_data=("content_id", "track?enc=wav"),
),
]
STANDARD_TESTS = DEFAULT_CTRL_TESTS + YOUTUBE_CTRL_TESTS + DASHCAST_CTRL_TESTS
AUDIO_TESTS = AUDIO_ONLY_TESTS
ULTRA_TESTS = [] # type: list
def run_tests(standard: str = "... | 102 | 102 | 343 | 20 | 81 | DatGuy1/catt | realcc_tests/test_procedure.py | Python | run_tests | run_tests | 246 | 279 | 246 | 246 | 227d47edd07c5c20a2c26be6a6348d5652bcf9da | bigcode/the-stack | train |
5a6c5128702e8e8464db4830 | train | class | class FeatureScannerRule(ScannerRule):
_fundamental_rule = FeatureCompleteFundamentalRule()
| class FeatureScannerRule(ScannerRule):
| _fundamental_rule = FeatureCompleteFundamentalRule()
| _complete=True,
lhs=left_edge.nextsym()):
for new_edge in fr.apply(chart, grammar, left_edge, right_edge):
yield new_edge
class FeatureCompleterRule(CompleterRule):
_fundamental_rule = FeatureCompleteFundamentalRule()
class FeatureScannerRule... | 64 | 64 | 20 | 8 | 56 | wangyum/anaconda | pkgs/nltk-3.2-py27_0/lib/python2.7/site-packages/nltk/parse/earleychart.py | Python | FeatureScannerRule | FeatureScannerRule | 217 | 218 | 217 | 217 | 2fae7f7abc2fa0ef6bad450fd14e74b28e97e6b4 | bigcode/the-stack | train |
4dd58d18391b219d504fd6b4 | train | class | class FeatureIncrementalTopDownChartParser(FeatureIncrementalChartParser):
def __init__(self, grammar, **parser_args):
FeatureIncrementalChartParser.__init__(self, grammar, TD_INCREMENTAL_FEATURE_STRATEGY, **parser_args)
| class FeatureIncrementalTopDownChartParser(FeatureIncrementalChartParser):
| def __init__(self, grammar, **parser_args):
FeatureIncrementalChartParser.__init__(self, grammar, TD_INCREMENTAL_FEATURE_STRATEGY, **parser_args)
| FeatureEarleyChartParser(FeatureIncrementalChartParser):
def __init__(self, grammar, **parser_args):
FeatureIncrementalChartParser.__init__(self, grammar, EARLEY_FEATURE_STRATEGY, **parser_args)
class FeatureIncrementalTopDownChartParser(FeatureIncrementalChartParser):
| 64 | 64 | 53 | 15 | 49 | wangyum/anaconda | pkgs/nltk-3.2-py27_0/lib/python2.7/site-packages/nltk/parse/earleychart.py | Python | FeatureIncrementalTopDownChartParser | FeatureIncrementalTopDownChartParser | 395 | 397 | 395 | 395 | 0486b8d7473cfbbf3f47c8cdf9bf782772abb538 | bigcode/the-stack | train |
1bfb76a4371224f8b3e67fcc | train | class | class IncrementalBottomUpChartParser(IncrementalChartParser):
def __init__(self, grammar, **parser_args):
IncrementalChartParser.__init__(self, grammar, BU_INCREMENTAL_STRATEGY, **parser_args)
| class IncrementalBottomUpChartParser(IncrementalChartParser):
| def __init__(self, grammar, **parser_args):
IncrementalChartParser.__init__(self, grammar, BU_INCREMENTAL_STRATEGY, **parser_args)
| pass
class IncrementalTopDownChartParser(IncrementalChartParser):
def __init__(self, grammar, **parser_args):
IncrementalChartParser.__init__(self, grammar, TD_INCREMENTAL_STRATEGY, **parser_args)
class IncrementalBottomUpChartParser(IncrementalChartParser):
| 64 | 64 | 49 | 13 | 51 | wangyum/anaconda | pkgs/nltk-3.2-py27_0/lib/python2.7/site-packages/nltk/parse/earleychart.py | Python | IncrementalBottomUpChartParser | IncrementalBottomUpChartParser | 342 | 344 | 342 | 342 | 93ddfa67066e03db0715ebe704654d3bc5cd0d3f | bigcode/the-stack | train |
4fa4e8a5adfa8d0cd779d377 | train | class | class FeatureIncrementalBottomUpLeftCornerChartParser(FeatureIncrementalChartParser):
def __init__(self, grammar, **parser_args):
FeatureIncrementalChartParser.__init__(self, grammar, BU_LC_INCREMENTAL_FEATURE_STRATEGY, **parser_args)
| class FeatureIncrementalBottomUpLeftCornerChartParser(FeatureIncrementalChartParser):
| def __init__(self, grammar, **parser_args):
FeatureIncrementalChartParser.__init__(self, grammar, BU_LC_INCREMENTAL_FEATURE_STRATEGY, **parser_args)
| ChartParser(FeatureIncrementalChartParser):
def __init__(self, grammar, **parser_args):
FeatureIncrementalChartParser.__init__(self, grammar, BU_INCREMENTAL_FEATURE_STRATEGY, **parser_args)
class FeatureIncrementalBottomUpLeftCornerChartParser(FeatureIncrementalChartParser):
| 64 | 64 | 57 | 17 | 47 | wangyum/anaconda | pkgs/nltk-3.2-py27_0/lib/python2.7/site-packages/nltk/parse/earleychart.py | Python | FeatureIncrementalBottomUpLeftCornerChartParser | FeatureIncrementalBottomUpLeftCornerChartParser | 403 | 405 | 403 | 403 | 90d1840a8ca062a4cb8d6184ad3adca2f7439f54 | bigcode/the-stack | train |
a3ad8939a85981b0be3aeca3 | train | class | class FeatureEarleyChartParser(FeatureIncrementalChartParser):
def __init__(self, grammar, **parser_args):
FeatureIncrementalChartParser.__init__(self, grammar, EARLEY_FEATURE_STRATEGY, **parser_args)
| class FeatureEarleyChartParser(FeatureIncrementalChartParser):
| def __init__(self, grammar, **parser_args):
FeatureIncrementalChartParser.__init__(self, grammar, EARLEY_FEATURE_STRATEGY, **parser_args)
| chart_class=FeatureIncrementalChart,
**parser_args):
IncrementalChartParser.__init__(self, grammar,
strategy=strategy,
trace_chart_width=trace_chart_width,
chart_class=c... | 64 | 64 | 50 | 13 | 51 | wangyum/anaconda | pkgs/nltk-3.2-py27_0/lib/python2.7/site-packages/nltk/parse/earleychart.py | Python | FeatureEarleyChartParser | FeatureEarleyChartParser | 391 | 393 | 391 | 391 | c70ddc97f4974c5d3515d3552d36215838c4522a | bigcode/the-stack | train |
d8f88211c7a98020faec49d6 | train | class | class FilteredCompleteFundamentalRule(FilteredSingleEdgeFundamentalRule):
def apply(self, chart, grammar, edge):
# Since the Filtered rule only works for grammars without empty productions,
# we only have to bother with complete edges here.
if edge.is_complete():
for new_edg... | class FilteredCompleteFundamentalRule(FilteredSingleEdgeFundamentalRule):
| def apply(self, chart, grammar, edge):
# Since the Filtered rule only works for grammars without empty productions,
# we only have to bother with complete edges here.
if edge.is_complete():
for new_edge in self._apply_complete(chart, grammar, edge):
yield new... | chart, grammar, edge):
if isinstance(edge, LeafEdge):
for new_edge in self._fundamental_rule.apply(chart, grammar, edge):
yield new_edge
class PredictorRule(CachedTopDownPredictRule):
pass
class FilteredCompleteFundamentalRule(FilteredSingleEdgeFundamentalRule):
| 64 | 64 | 80 | 15 | 48 | wangyum/anaconda | pkgs/nltk-3.2-py27_0/lib/python2.7/site-packages/nltk/parse/earleychart.py | Python | FilteredCompleteFundamentalRule | FilteredCompleteFundamentalRule | 190 | 196 | 190 | 190 | 65a90be4946ac86b6b2fc1f55c5a0094ee724917 | bigcode/the-stack | train |
9704773ace2250413dac0c5a | train | class | class IncrementalBottomUpLeftCornerChartParser(IncrementalChartParser):
def __init__(self, grammar, **parser_args):
IncrementalChartParser.__init__(self, grammar, BU_LC_INCREMENTAL_STRATEGY, **parser_args)
| class IncrementalBottomUpLeftCornerChartParser(IncrementalChartParser):
| def __init__(self, grammar, **parser_args):
IncrementalChartParser.__init__(self, grammar, BU_LC_INCREMENTAL_STRATEGY, **parser_args)
| class IncrementalBottomUpChartParser(IncrementalChartParser):
def __init__(self, grammar, **parser_args):
IncrementalChartParser.__init__(self, grammar, BU_INCREMENTAL_STRATEGY, **parser_args)
class IncrementalBottomUpLeftCornerChartParser(IncrementalChartParser):
| 64 | 64 | 53 | 15 | 49 | wangyum/anaconda | pkgs/nltk-3.2-py27_0/lib/python2.7/site-packages/nltk/parse/earleychart.py | Python | IncrementalBottomUpLeftCornerChartParser | IncrementalBottomUpLeftCornerChartParser | 346 | 348 | 346 | 346 | b1a447ce20c205aa264c3d3b76576733a772951b | bigcode/the-stack | train |
328741beb1c841de4a717c71 | train | class | class FeaturePredictorRule(FeatureTopDownPredictRule):
pass
| class FeaturePredictorRule(FeatureTopDownPredictRule):
| pass
| _edge, right_edge):
yield new_edge
class FeatureCompleterRule(CompleterRule):
_fundamental_rule = FeatureCompleteFundamentalRule()
class FeatureScannerRule(ScannerRule):
_fundamental_rule = FeatureCompleteFundamentalRule()
class FeaturePredictorRule(FeatureTopDownPredictRule):
| 64 | 64 | 15 | 12 | 52 | wangyum/anaconda | pkgs/nltk-3.2-py27_0/lib/python2.7/site-packages/nltk/parse/earleychart.py | Python | FeaturePredictorRule | FeaturePredictorRule | 220 | 221 | 220 | 220 | 1bb1e42eeb45bc9849236a92d8edf0a63e875286 | bigcode/the-stack | train |
a5f3f50c1e3f1b5792bfde0e | train | class | class FeatureIncrementalChart(IncrementalChart, FeatureChart):
def select(self, end, **restrictions):
edgelist = self._edgelists[end]
# If there are no restrictions, then return all edges.
if restrictions=={}: return iter(edgelist)
# Find the index corresponding to the given... | class FeatureIncrementalChart(IncrementalChart, FeatureChart):
| def select(self, end, **restrictions):
edgelist = self._edgelists[end]
# If there are no restrictions, then return all edges.
if restrictions=={}: return iter(edgelist)
# Find the index corresponding to the given restrictions.
restr_keys = sorted(restrictions.keys())... | )
def _register_with_indexes(self, edge):
end = edge.end()
for (restr_keys, index) in self._indexes.items():
vals = tuple(getattr(edge, key)() for key in restr_keys)
index[end].setdefault(vals, []).append(edge)
def _append_edge(self, edge):
self._edgeli... | 113 | 113 | 378 | 13 | 100 | wangyum/anaconda | pkgs/nltk-3.2-py27_0/lib/python2.7/site-packages/nltk/parse/earleychart.py | Python | FeatureIncrementalChart | FeatureIncrementalChart | 114 | 155 | 114 | 114 | e2605c51e2779e91437f2d249e0551e8194ddda1 | bigcode/the-stack | train |
0c6d1c75163d2369febf8da0 | train | class | class IncrementalChartParser(ChartParser):
"""
An *incremental* chart parser implementing Jay Earley's
parsing algorithm:
| For each index end in [0, 1, ..., N]:
| For each edge such that edge.end = end:
| If edge is incomplete and edge.next is not a part of speech:
| Ap... | class IncrementalChartParser(ChartParser):
| """
An *incremental* chart parser implementing Jay Earley's
parsing algorithm:
| For each index end in [0, 1, ..., N]:
| For each edge such that edge.end = end:
| If edge is incomplete and edge.next is not a part of speech:
| Apply PredictorRule to edge
| If edge... | amentalRule()
class FeatureScannerRule(ScannerRule):
_fundamental_rule = FeatureCompleteFundamentalRule()
class FeaturePredictorRule(FeatureTopDownPredictRule):
pass
#////////////////////////////////////////////////////////////
# Incremental CFG Chart Parsers
#//////////////////////////////////////... | 218 | 219 | 730 | 9 | 209 | wangyum/anaconda | pkgs/nltk-3.2-py27_0/lib/python2.7/site-packages/nltk/parse/earleychart.py | Python | IncrementalChartParser | IncrementalChartParser | 249 | 331 | 249 | 249 | a174dd0310eee31942894e21dbd553c8eb4bd5cb | bigcode/the-stack | train |
2473df008fd6b0e0defabf35 | train | class | class FeatureIncrementalChartParser(IncrementalChartParser, FeatureChartParser):
def __init__(self, grammar,
strategy=BU_LC_INCREMENTAL_FEATURE_STRATEGY,
trace_chart_width=20,
chart_class=FeatureIncrementalChart,
**parser_args):
Incre... | class FeatureIncrementalChartParser(IncrementalChartParser, FeatureChartParser):
| def __init__(self, grammar,
strategy=BU_LC_INCREMENTAL_FEATURE_STRATEGY,
trace_chart_width=20,
chart_class=FeatureIncrementalChart,
**parser_args):
IncrementalChartParser.__init__(self, grammar,
... | PredictRule(),
FeatureCompleteFundamentalRule()]
BU_LC_INCREMENTAL_FEATURE_STRATEGY = [LeafInitRule(),
FeatureEmptyPredictRule(),
FeatureBottomUpPredictCombineRule(),
... | 63 | 64 | 97 | 16 | 47 | wangyum/anaconda | pkgs/nltk-3.2-py27_0/lib/python2.7/site-packages/nltk/parse/earleychart.py | Python | FeatureIncrementalChartParser | FeatureIncrementalChartParser | 379 | 389 | 379 | 379 | 763cccf85e186d93f8e261d8dd35edfe61cda60b | bigcode/the-stack | train |
9e8431e16624f9e46599e2be | train | class | class ScannerRule(CompleteFundamentalRule):
_fundamental_rule = CompleteFundamentalRule()
def apply(self, chart, grammar, edge):
if isinstance(edge, LeafEdge):
for new_edge in self._fundamental_rule.apply(chart, grammar, edge):
yield new_edge
| class ScannerRule(CompleteFundamentalRule):
| _fundamental_rule = CompleteFundamentalRule()
def apply(self, chart, grammar, edge):
if isinstance(edge, LeafEdge):
for new_edge in self._fundamental_rule.apply(chart, grammar, edge):
yield new_edge
| Rule):
_fundamental_rule = CompleteFundamentalRule()
def apply(self, chart, grammar, edge):
if not isinstance(edge, LeafEdge):
for new_edge in self._fundamental_rule.apply(chart, grammar, edge):
yield new_edge
class ScannerRule(CompleteFundamentalRule):
| 64 | 64 | 61 | 9 | 54 | wangyum/anaconda | pkgs/nltk-3.2-py27_0/lib/python2.7/site-packages/nltk/parse/earleychart.py | Python | ScannerRule | ScannerRule | 180 | 185 | 180 | 180 | cd130fbd69e127f6aec7541d1946395c04c9ae17 | bigcode/the-stack | train |
2e7078c4a52836a94eaebb4a | train | class | class EarleyChartParser(IncrementalChartParser):
def __init__(self, grammar, **parser_args):
IncrementalChartParser.__init__(self, grammar, EARLEY_STRATEGY, **parser_args)
pass
| class EarleyChartParser(IncrementalChartParser):
| def __init__(self, grammar, **parser_args):
IncrementalChartParser.__init__(self, grammar, EARLEY_STRATEGY, **parser_args)
pass
| = list(rule.apply(chart, grammar, edge))
trace_new_edges(chart, rule, new_edges, trace, trace_edge_width)
for new_edge in new_edges:
if new_edge.end()==end:
agenda.append(new_edge)
return chart
class EarleyChartP... | 64 | 64 | 49 | 11 | 52 | wangyum/anaconda | pkgs/nltk-3.2-py27_0/lib/python2.7/site-packages/nltk/parse/earleychart.py | Python | EarleyChartParser | EarleyChartParser | 333 | 336 | 333 | 333 | dec0b4322049a4c0a265b4a458a11baa15a12f89 | bigcode/the-stack | train |
2bdb9ab8c381a45ba73b3b5d | train | class | class IncrementalChart(Chart):
def initialize(self):
# A sequence of edge lists contained in this chart.
self._edgelists = tuple([] for x in self._positions())
# The set of child pointer lists associated with each edge.
self._edge_to_cpls = {}
# Indexes mapping attr... | class IncrementalChart(Chart):
| def initialize(self):
# A sequence of edge lists contained in this chart.
self._edgelists = tuple([] for x in self._positions())
# The set of child pointer lists associated with each edge.
self._edge_to_cpls = {}
# Indexes mapping attribute values to lists of edges
... |
from nltk.parse.chart import (Chart, ChartParser, EdgeI, LeafEdge, LeafInitRule,
BottomUpPredictRule, BottomUpPredictCombineRule,
TopDownInitRule, SingleEdgeFundamentalRule,
EmptyPredictRule,
Ca... | 153 | 153 | 513 | 7 | 145 | wangyum/anaconda | pkgs/nltk-3.2-py27_0/lib/python2.7/site-packages/nltk/parse/earleychart.py | Python | IncrementalChart | IncrementalChart | 50 | 111 | 50 | 50 | aafd43b3fbfc380a6b6ad5bf95de247a2f0864da | bigcode/the-stack | train |
0b579bcfcbb6c3448fbe26db | train | class | class FeatureCompleterRule(CompleterRule):
_fundamental_rule = FeatureCompleteFundamentalRule()
| class FeatureCompleterRule(CompleterRule):
| _fundamental_rule = FeatureCompleteFundamentalRule()
| empty complete edges here.
for right_edge in chart.select(start=end, end=end,
is_complete=True,
lhs=left_edge.nextsym()):
for new_edge in fr.apply(chart, grammar, left_edge, right_edge):
yield new_edg... | 64 | 64 | 22 | 10 | 53 | wangyum/anaconda | pkgs/nltk-3.2-py27_0/lib/python2.7/site-packages/nltk/parse/earleychart.py | Python | FeatureCompleterRule | FeatureCompleterRule | 214 | 215 | 214 | 214 | c6ff8a99c0b4b7683ff334a140bee3c141b7e8a1 | bigcode/the-stack | train |
c6698f7ac8d193ab5cbbc308 | train | class | class PredictorRule(CachedTopDownPredictRule):
pass
| class PredictorRule(CachedTopDownPredictRule):
| pass
| Rule):
_fundamental_rule = CompleteFundamentalRule()
def apply(self, chart, grammar, edge):
if isinstance(edge, LeafEdge):
for new_edge in self._fundamental_rule.apply(chart, grammar, edge):
yield new_edge
class PredictorRule(CachedTopDownPredictRule):
| 64 | 64 | 13 | 10 | 53 | wangyum/anaconda | pkgs/nltk-3.2-py27_0/lib/python2.7/site-packages/nltk/parse/earleychart.py | Python | PredictorRule | PredictorRule | 187 | 188 | 187 | 187 | 802fc7d90937229cbeed5065608191ef99028a23 | bigcode/the-stack | train |
ea1013f08cfb865d83ee19f5 | train | class | class CompleteFundamentalRule(SingleEdgeFundamentalRule):
def _apply_incomplete(self, chart, grammar, left_edge):
end = left_edge.end()
# When the chart is incremental, we only have to look for
# empty complete edges here.
for right_edge in chart.select(start=end, end=end,
... | class CompleteFundamentalRule(SingleEdgeFundamentalRule):
| def _apply_incomplete(self, chart, grammar, left_edge):
end = left_edge.end()
# When the chart is incremental, we only have to look for
# empty complete edges here.
for right_edge in chart.select(start=end, end=end,
is_complete=True,
... | .items():
vals = tuple(self._get_type_if_possible(getattr(edge, key)())
for key in restr_keys)
index[end].setdefault(vals, []).append(edge)
#////////////////////////////////////////////////////////////
# Incremental CFG Rules
#////////////////////////////////////... | 64 | 64 | 117 | 12 | 51 | wangyum/anaconda | pkgs/nltk-3.2-py27_0/lib/python2.7/site-packages/nltk/parse/earleychart.py | Python | CompleteFundamentalRule | CompleteFundamentalRule | 161 | 171 | 161 | 161 | 987122c5fe1353b021a34155d15af77c9b735019 | bigcode/the-stack | train |
eef90c03574620d0c09313ae | train | class | class IncrementalLeftCornerChartParser(IncrementalChartParser):
def __init__(self, grammar, **parser_args):
if not grammar.is_nonempty():
raise ValueError("IncrementalLeftCornerParser only works for grammars "
"without empty productions.")
IncrementalCha... | class IncrementalLeftCornerChartParser(IncrementalChartParser):
| def __init__(self, grammar, **parser_args):
if not grammar.is_nonempty():
raise ValueError("IncrementalLeftCornerParser only works for grammars "
"without empty productions.")
IncrementalChartParser.__init__(self, grammar, LC_INCREMENTAL_STRATEGY, **parse... | alBottomUpLeftCornerChartParser(IncrementalChartParser):
def __init__(self, grammar, **parser_args):
IncrementalChartParser.__init__(self, grammar, BU_LC_INCREMENTAL_STRATEGY, **parser_args)
class IncrementalLeftCornerChartParser(IncrementalChartParser):
| 64 | 64 | 79 | 13 | 51 | wangyum/anaconda | pkgs/nltk-3.2-py27_0/lib/python2.7/site-packages/nltk/parse/earleychart.py | Python | IncrementalLeftCornerChartParser | IncrementalLeftCornerChartParser | 350 | 355 | 350 | 350 | 3082698ceb3c92e56baafc7374b69d7f8f4a5d53 | bigcode/the-stack | train |
dc99a4ef64a807907ba6397d | train | class | class IncrementalTopDownChartParser(IncrementalChartParser):
def __init__(self, grammar, **parser_args):
IncrementalChartParser.__init__(self, grammar, TD_INCREMENTAL_STRATEGY, **parser_args)
| class IncrementalTopDownChartParser(IncrementalChartParser):
| def __init__(self, grammar, **parser_args):
IncrementalChartParser.__init__(self, grammar, TD_INCREMENTAL_STRATEGY, **parser_args)
| chart
class EarleyChartParser(IncrementalChartParser):
def __init__(self, grammar, **parser_args):
IncrementalChartParser.__init__(self, grammar, EARLEY_STRATEGY, **parser_args)
pass
class IncrementalTopDownChartParser(IncrementalChartParser):
| 64 | 64 | 49 | 13 | 50 | wangyum/anaconda | pkgs/nltk-3.2-py27_0/lib/python2.7/site-packages/nltk/parse/earleychart.py | Python | IncrementalTopDownChartParser | IncrementalTopDownChartParser | 338 | 340 | 338 | 338 | 1fc040adf7f2f350feaf5097ea19187cd1e6dbc5 | bigcode/the-stack | train |
1e6c194b7fc43e86fb9b8a40 | train | function | def demo(print_times=True, print_grammar=False,
print_trees=True, trace=2,
sent='I saw John with a dog with my cookie', numparses=5):
"""
A demonstration of the Earley parsers.
"""
import sys, time
from nltk.parse.chart import demo_grammar
# The grammar for ChartParse... | def demo(print_times=True, print_grammar=False,
print_trees=True, trace=2,
sent='I saw John with a dog with my cookie', numparses=5):
| """
A demonstration of the Earley parsers.
"""
import sys, time
from nltk.parse.chart import demo_grammar
# The grammar for ChartParser and SteppingChartParser:
grammar = demo_grammar()
if print_grammar:
print("* Grammar")
print(grammar)
# Tokenize the s... | alChartParser.__init__(self, grammar, BU_LC_INCREMENTAL_FEATURE_STRATEGY, **parser_args)
#////////////////////////////////////////////////////////////
# Demonstration
#////////////////////////////////////////////////////////////
def demo(print_times=True, print_grammar=False,
print_trees=True, trace=2,... | 76 | 76 | 256 | 40 | 35 | wangyum/anaconda | pkgs/nltk-3.2-py27_0/lib/python2.7/site-packages/nltk/parse/earleychart.py | Python | demo | demo | 412 | 449 | 412 | 414 | 4854c92e1e4eb8577a40b999a8dfbcb3af4026d8 | bigcode/the-stack | train |
835a1314029a31f53a98241b | train | class | class FeatureCompleteFundamentalRule(FeatureSingleEdgeFundamentalRule):
def _apply_incomplete(self, chart, grammar, left_edge):
fr = self._fundamental_rule
end = left_edge.end()
# When the chart is incremental, we only have to look for
# empty complete edges here.
for r... | class FeatureCompleteFundamentalRule(FeatureSingleEdgeFundamentalRule):
| def _apply_incomplete(self, chart, grammar, left_edge):
fr = self._fundamental_rule
end = left_edge.end()
# When the chart is incremental, we only have to look for
# empty complete edges here.
for right_edge in chart.select(start=end, end=end,
... | only have to bother with complete edges here.
if edge.is_complete():
for new_edge in self._apply_complete(chart, grammar, edge):
yield new_edge
#////////////////////////////////////////////////////////////
# Incremental FCFG Rules
#///////////////////////////////////////////... | 64 | 64 | 116 | 14 | 49 | wangyum/anaconda | pkgs/nltk-3.2-py27_0/lib/python2.7/site-packages/nltk/parse/earleychart.py | Python | FeatureCompleteFundamentalRule | FeatureCompleteFundamentalRule | 202 | 212 | 202 | 202 | a0fd728b1c2b995edcb2573181883cb597604e21 | bigcode/the-stack | train |
41e0077991ac71f05d9bd07d | train | class | class FeatureIncrementalBottomUpChartParser(FeatureIncrementalChartParser):
def __init__(self, grammar, **parser_args):
FeatureIncrementalChartParser.__init__(self, grammar, BU_INCREMENTAL_FEATURE_STRATEGY, **parser_args)
| class FeatureIncrementalBottomUpChartParser(FeatureIncrementalChartParser):
| def __init__(self, grammar, **parser_args):
FeatureIncrementalChartParser.__init__(self, grammar, BU_INCREMENTAL_FEATURE_STRATEGY, **parser_args)
| TopDownChartParser(FeatureIncrementalChartParser):
def __init__(self, grammar, **parser_args):
FeatureIncrementalChartParser.__init__(self, grammar, TD_INCREMENTAL_FEATURE_STRATEGY, **parser_args)
class FeatureIncrementalBottomUpChartParser(FeatureIncrementalChartParser):
| 64 | 64 | 53 | 15 | 49 | wangyum/anaconda | pkgs/nltk-3.2-py27_0/lib/python2.7/site-packages/nltk/parse/earleychart.py | Python | FeatureIncrementalBottomUpChartParser | FeatureIncrementalBottomUpChartParser | 399 | 401 | 399 | 399 | aed94b515105d978c52fc9254ecb5c35e3b7894f | bigcode/the-stack | train |
945a7ce00708f78bcde6537d | train | class | class CompleterRule(CompleteFundamentalRule):
_fundamental_rule = CompleteFundamentalRule()
def apply(self, chart, grammar, edge):
if not isinstance(edge, LeafEdge):
for new_edge in self._fundamental_rule.apply(chart, grammar, edge):
yield new_edge
| class CompleterRule(CompleteFundamentalRule):
| _fundamental_rule = CompleteFundamentalRule()
def apply(self, chart, grammar, edge):
if not isinstance(edge, LeafEdge):
for new_edge in self._fundamental_rule.apply(chart, grammar, edge):
yield new_edge
| (start=end, end=end,
is_complete=True,
lhs=left_edge.nextsym()):
new_edge = left_edge.move_dot_forward(right_edge.end())
if chart.insert_with_backpointer(new_edge, left_edge, right_edge):
yield new... | 64 | 64 | 63 | 10 | 53 | wangyum/anaconda | pkgs/nltk-3.2-py27_0/lib/python2.7/site-packages/nltk/parse/earleychart.py | Python | CompleterRule | CompleterRule | 173 | 178 | 173 | 173 | 450f1f801b0102777f98b7df0e37075d50ee574f | bigcode/the-stack | train |
1bcef570c8970102d643d9ee | train | function | def main():
ini = IniBuffer()
ini.LoadFile("/home/pascal/Desktop/test.ini")
#------------------------------------------------------------------
# Request an int
section_name = "04_integers"
key_name = "key02"
value = ini.GetValue_int(section_name, key_name)
print("section:"+section_name+"; key... | def main():
| ini = IniBuffer()
ini.LoadFile("/home/pascal/Desktop/test.ini")
#------------------------------------------------------------------
# Request an int
section_name = "04_integers"
key_name = "key02"
value = ini.GetValue_int(section_name, key_name)
print("section:"+section_name+"; key:"+key_name+... | #!/usr/bin/env python3
from IniBuffer import *
def main():
| 15 | 98 | 327 | 3 | 12 | pascalenderli/IniFile | src/app/python_example.py | Python | main | main | 4 | 50 | 4 | 4 | f1dbdfb113a1f22f445ee3df66aa2cfc44e32fe5 | bigcode/the-stack | train |
95cc732087a9ad20c1473766 | train | class | class DummyQuestionForm(forms.Form):
"""
This dummy form asks for payment authorization.
"""
authorize_payment = ChoiceField(label=_("authorization"), choices=((1, _('yes')), (0, _('no'))))
| class DummyQuestionForm(forms.Form):
| """
This dummy form asks for payment authorization.
"""
authorize_payment = ChoiceField(label=_("authorization"), choices=((1, _('yes')), (0, _('no'))))
| from django.forms import forms
from django.forms.fields import ChoiceField
from django.utils.translation import ugettext as _
class DummyQuestionForm(forms.Form):
| 30 | 64 | 45 | 7 | 23 | beatap123/django-getpaid | getpaid/backends/dummy/forms.py | Python | DummyQuestionForm | DummyQuestionForm | 6 | 10 | 6 | 6 | 78464e18b4f137a036df68d0d8b4a8898dee6070 | bigcode/the-stack | train |
e30fd689f9b7207b46262e62 | train | function | def process_aliases(ctx: Context):
"""
Processes aliases
"""
ctx.debug('processing aliases')
for alias, value in ctx.settings.aliases.items():
ctx.debug(f'processing alias: {alias}')
ctx.markdown_text = ctx.markdown_text.replace(alias, value)
| def process_aliases(ctx: Context):
| """
Processes aliases
"""
ctx.debug('processing aliases')
for alias, value in ctx.settings.aliases.items():
ctx.debug(f'processing alias: {alias}')
ctx.markdown_text = ctx.markdown_text.replace(alias, value)
| # coding=utf-8
"""
Processes aliases
"""
from . import Context
def process_aliases(ctx: Context):
| 24 | 64 | 61 | 8 | 15 | etcher-be/EDLM | edlm/convert/_preprocessor/_markdown/_aliases.py | Python | process_aliases | process_aliases | 9 | 16 | 9 | 9 | 3a347b8b7fce0463d9c88a4e471946e267d4ec90 | bigcode/the-stack | train |
c34fdfdf2a223a7a946fb5c0 | train | class | class AppfolderConfig(AppConfig):
name = 'appFolder'
| class AppfolderConfig(AppConfig):
| name = 'appFolder'
| from django.apps import AppConfig
class AppfolderConfig(AppConfig):
| 14 | 64 | 14 | 7 | 6 | santarini/DjangoForBegin | Template/projectContainer/appFolder/apps.py | Python | AppfolderConfig | AppfolderConfig | 4 | 5 | 4 | 4 | ad299ac5825091cf7a0e64ada75fa0852406f4ae | bigcode/the-stack | train |
5e872976023fa48ced5b5d8f | train | function | def monitor():
signals = blinker.Namespace()
@asyncio.coroutine
def dropbot_monitor(*args):
try:
yield asyncio.From(db.monitor.monitor(*args))
except asyncio.CancelledError:
_L().info('Stopped DropBot monitor.')
monitor_task = cancellable(dropbot_monitor)
th... | def monitor():
| signals = blinker.Namespace()
@asyncio.coroutine
def dropbot_monitor(*args):
try:
yield asyncio.From(db.monitor.monitor(*args))
except asyncio.CancelledError:
_L().info('Stopped DropBot monitor.')
monitor_task = cancellable(dropbot_monitor)
thread = threadin... | __future__ import (absolute_import, division, print_function,
unicode_literals)
import threading
from asyncio_helpers import cancellable
from logging_helpers import _L
import blinker
import dropbot as db
import dropbot.hardware_test
import dropbot.monitor
import trollius as asyncio
def monitor... | 64 | 64 | 97 | 3 | 60 | sci-bots/dropbot-monitor | src/dropbot_monitor/monitor.py | Python | monitor | monitor | 14 | 28 | 14 | 14 | da958f5cdd37bd74906a9f680593145d3649a38a | bigcode/the-stack | train |
ba79a7c355b92cc7623b2521 | train | class | class IdxSampler(sampler.Sampler):
"""Samples elements from [0, length) randomly without replacement.
Parameters
----------
length : int
Length of the sequence.
"""
def __init__(self, indices_selected):
if isinstance(indices_selected, list):
indices_selected = np.arr... | class IdxSampler(sampler.Sampler):
| """Samples elements from [0, length) randomly without replacement.
Parameters
----------
length : int
Length of the sequence.
"""
def __init__(self, indices_selected):
if isinstance(indices_selected, list):
indices_selected = np.array(indices_selected)
self._... | 15:47
# @Author : Chen
# @File : datasets.py
# @Software: PyCharm
import os, warnings
from mxnet.gluon.data import dataset, sampler
from mxnet import image
import numpy as np
class IdxSampler(sampler.Sampler):
| 64 | 64 | 127 | 9 | 54 | pengpeg/PFAN_MX | datasets/datasets.py | Python | IdxSampler | IdxSampler | 11 | 31 | 11 | 11 | e5d60316066f8a5180efe461e3b7205b47efb613 | bigcode/the-stack | train |
e83bd3cdb6cdc9c65b4726d7 | train | class | class ImageFolderDataset(dataset.Dataset):
"""A dataset for loading image files stored in a folder structure.
like::
root/car/0001.jpg
root/car/xxxa.jpg
root/car/yyyb.jpg
root/bus/123.jpg
root/bus/023.jpg
root/bus/wwww.jpg
Parameters
----------
root... | class ImageFolderDataset(dataset.Dataset):
| """A dataset for loading image files stored in a folder structure.
like::
root/car/0001.jpg
root/car/xxxa.jpg
root/car/yyyb.jpg
root/bus/123.jpg
root/bus/023.jpg
root/bus/wwww.jpg
Parameters
----------
root : str
Path to root directory.
... | : datasets.py
# @Software: PyCharm
import os, warnings
from mxnet.gluon.data import dataset, sampler
from mxnet import image
import numpy as np
class IdxSampler(sampler.Sampler):
"""Samples elements from [0, length) randomly without replacement.
Parameters
----------
length : int
Length of... | 174 | 174 | 581 | 7 | 166 | pengpeg/PFAN_MX | datasets/datasets.py | Python | ImageFolderDataset | ImageFolderDataset | 34 | 104 | 34 | 34 | dbc2470b308d95ebccf0bdf696fc15cceab95d40 | bigcode/the-stack | train |
33475d49a60b73ebffe0a7ea | train | function | @app.route('/')
def home():
#deployed model goes here
return "<h1>Hello, World!</h1>"
| @app.route('/')
def home():
#deployed model goes here
| return "<h1>Hello, World!</h1>"
| from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
#deployed model goes here
| 26 | 64 | 26 | 15 | 11 | AuFeld/twitoff | hello.py | Python | home | home | 4 | 7 | 4 | 6 | bc418582c9eadaee1706551703b1966e33b04ed9 | bigcode/the-stack | train |
9429466908b0f1ca28e46517 | train | function | @app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return f'User {username}'
| @app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
| return f'User {username}'
|
#deployed model goes here
return "<h1>Hello, World!</h1>"
if __name__ == "__main__":
app.run(debug=True, port = 8080)
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
| 64 | 64 | 32 | 24 | 40 | AuFeld/twitoff | hello.py | Python | show_user_profile | show_user_profile | 12 | 15 | 12 | 14 | e854d6ddbdf64780693af2317a2739154cfcc011 | bigcode/the-stack | train |
222cb8167e863305d9d83faf | train | function | @app.route('/post/<post_id>')
def show_post(post_id):
# show the post with the given id, the id in an integer
return 'Post %d' % (post_id + 1) | @app.route('/post/<post_id>')
def show_post(post_id):
# show the post with the given id, the id in an integer
| return 'Post %d' % (post_id + 1) | )
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return f'User {username}'
@app.route('/post/<post_id>')
def show_post(post_id):
# show the post with the given id, the id in an integer
| 63 | 64 | 45 | 30 | 33 | AuFeld/twitoff | hello.py | Python | show_post | show_post | 17 | 20 | 17 | 19 | f370d377694fb99de5fdafaa6c4349c1656c9e2e | bigcode/the-stack | train |
f1a74123f10f8f3d10fb4994 | train | function | def add_autosummary_create_documenter(func):
import sphinx.ext.autosummary
sphinx.ext.autosummary.Autosummary.create_documenter = func
| def add_autosummary_create_documenter(func):
| import sphinx.ext.autosummary
sphinx.ext.autosummary.Autosummary.create_documenter = func
| Documenter,
AccessorMethodDocumenter,
)
try:
__version__ = version("sphinx-autosummary-accessors")
except Exception:
__version__ = "999"
templates_path = str(pathlib.Path(__file__).parent / "templates")
def add_autosummary_create_documenter(func):
| 64 | 64 | 35 | 10 | 54 | CagtayFabry/sphinx-autosummary-accessors | sphinx_autosummary_accessors/__init__.py | Python | add_autosummary_create_documenter | add_autosummary_create_documenter | 24 | 27 | 24 | 24 | db162b679f0e5e8b410c95c2cecbfeba69b357d8 | bigcode/the-stack | train |
b33110ec6ca8a72a7800961d | train | function | def setup(app):
app.setup_extension("sphinx.ext.autosummary")
app.add_autodocumenter(AccessorDocumenter)
app.add_autodocumenter(AccessorAttributeDocumenter)
app.add_autodocumenter(AccessorMethodDocumenter)
app.add_autodocumenter(AccessorCallableDocumenter)
add_autosummary_create_documenter(aut... | def setup(app):
| app.setup_extension("sphinx.ext.autosummary")
app.add_autodocumenter(AccessorDocumenter)
app.add_autodocumenter(AccessorAttributeDocumenter)
app.add_autodocumenter(AccessorMethodDocumenter)
app.add_autodocumenter(AccessorCallableDocumenter)
add_autosummary_create_documenter(autosummary.create_... | Exception:
__version__ = "999"
templates_path = str(pathlib.Path(__file__).parent / "templates")
def add_autosummary_create_documenter(func):
import sphinx.ext.autosummary
sphinx.ext.autosummary.Autosummary.create_documenter = func
def setup(app):
| 64 | 64 | 99 | 4 | 59 | CagtayFabry/sphinx-autosummary-accessors | sphinx_autosummary_accessors/__init__.py | Python | setup | setup | 30 | 40 | 30 | 30 | 4e18c4f4ee20eb11e864ece72d1ea925eebd5ed1 | bigcode/the-stack | train |
7edad1dc66107305c8b13255 | train | function | @command(outgoing=True, pattern="^.alive$")
async def amireallyalive(alive):
""" For .alive command, check if the bot is running. """
await alive.edit("**`POCO BOT IS ACTIVATED! ψ(`∇´)ψ`**\n\n"
"`Telethon version: 3.1.3\nPython: 2.1.2 Kapak Merah`\n"
"`Database St... | @command(outgoing=True, pattern="^.alive$")
async def amireallyalive(alive):
| """ For .alive command, check if the bot is running. """
await alive.edit("**`POCO BOT IS ACTIVATED! ψ(`∇´)ψ`**\n\n"
"`Telethon version: 3.1.3\nPython: 2.1.2 Kapak Merah`\n"
"`Database Status: Databases functioning normally!\n\nAlways with you, my master!\n`"
... | """Check if userbot alive. If you change these, you become the gayest gay such that even the gay world will disown you."""
import asyncio
from telethon import events
from telethon.tl.types import ChannelParticipantsAdmins
from platform import uname
from userbot import ALIVE_NAME
from userbot.utils import admin_cm... | 113 | 256 | 1,434 | 21 | 92 | fforius/X-tra-Telegram | userbot/plugins/alive.py | Python | amireallyalive | amireallyalive | 11 | 46 | 11 | 12 | b37a5bcd83e114f0d92b75d85f16c185f1c239f0 | bigcode/the-stack | train |
3151ba2ba02aa8e9879bec5c | train | function | def make_circuit(n: int, input_qubit):
c = cirq.Circuit() # circuit begin
c.append(cirq.H.on(input_qubit[0])) # number=1
c.append(cirq.H.on(input_qubit[1])) # number=2
c.append(cirq.H.on(input_qubit[1])) # number=7
c.append(cirq.H.on(input_qubit[2])) # number=3
c.append(cirq.H.on(input_qubit... | def make_circuit(n: int, input_qubit):
| c = cirq.Circuit() # circuit begin
c.append(cirq.H.on(input_qubit[0])) # number=1
c.append(cirq.H.on(input_qubit[1])) # number=2
c.append(cirq.H.on(input_qubit[1])) # number=7
c.append(cirq.H.on(input_qubit[2])) # number=3
c.append(cirq.H.on(input_qubit[3])) # number=4
c.append(cirq.H.o... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 5/15/20 4:49 PM
# @File : grover.py
# qubit number=4
# total number=21
import cirq
import cirq.google as cg
from typing import Optional
import sys
from math import log2
import numpy as np
#thatsNoCode
def make_circuit(n: int, input_qubit):
| 101 | 131 | 438 | 12 | 88 | UCLA-SEAL/QDiff | data/cirq_new/cirq_program/startCirq_noisy693.py | Python | make_circuit | make_circuit | 17 | 42 | 17 | 17 | a995c2264fc7511c9ad0cc91b5c0c9bfdb4fac53 | bigcode/the-stack | train |
feca86f00ae5b53f7b264570 | train | function | def bitstring(bits):
return ''.join(str(int(b)) for b in bits)
| def bitstring(bits):
| return ''.join(str(int(b)) for b in bits)
| bit[0])) # number=19
c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=20
# circuit end
c.append(cirq.measure(*input_qubit, key='result'))
return c
def bitstring(bits):
| 64 | 64 | 18 | 5 | 58 | UCLA-SEAL/QDiff | data/cirq_new/cirq_program/startCirq_noisy693.py | Python | bitstring | bitstring | 44 | 45 | 44 | 44 | d8906cddcb2bd582e6d3ac5751986873fa7d631d | bigcode/the-stack | train |
36fdabfdbdc546646677b8f5 | train | class | class CometBlueStates:
"""CometBlue Thermostat States"""
TEMPERATURE_OFF = 7.5 # special temperature, valve fully closed
_TEMPERATURES_STRUCT_PACKING = '<bbbbbbb'
_STATUS_STRUCT_PACKING = '<BBB'
_STATUS_BITMASKS = {
'childlock': 0x80,
'manual_mode': 0x1,
'adapting': 0x400,... | class CometBlueStates:
| """CometBlue Thermostat States"""
TEMPERATURE_OFF = 7.5 # special temperature, valve fully closed
_TEMPERATURES_STRUCT_PACKING = '<bbbbbbb'
_STATUS_STRUCT_PACKING = '<BBB'
_STATUS_BITMASKS = {
'childlock': 0x80,
'manual_mode': 0x1,
'adapting': 0x400,
'not_ready': 0... | 1df67"
SOFTWARE_REV = "00002a28-0000-1000-8000-00805f9b34fb" # software_revision (0.0.6-sygonix1)
MODEL_CHAR = "00002a24-0000-1000-8000-00805f9b34fb" # model_number (Comet Blue)
MANUFACTURER_CHAR = "00002a29-0000-1000-8000-00805f9b34fb" # manufacturer_name (EUROtronic GmbH)
FIRMWARE_CHAR = "47e9ee2d-47e9... | 256 | 256 | 1,587 | 6 | 250 | neffs/python-cometblue_lite | cometblue_lite/cometblue.py | Python | CometBlueStates | CometBlueStates | 44 | 238 | 44 | 44 | 833b8844fdc1ffbfba5b9504732c5dcbb7835bab | bigcode/the-stack | train |
4b1f4b63488befecefe43436 | train | function | def _encode_datetime(dt):
if dt.year < 2000:
raise RuntimeError('Invalid year')
return struct.pack(
_DATETIME_STRUCT_PACKING,
dt.minute,
dt.hour,
dt.day,
dt.month,
dt.year - 2000)
| def _encode_datetime(dt):
| if dt.year < 2000:
raise RuntimeError('Invalid year')
return struct.pack(
_DATETIME_STRUCT_PACKING,
dt.minute,
dt.hour,
dt.day,
dt.month,
dt.year - 2000)
| d-47e9-11e4-8939-164230d1df67" # firmware_revision2 (COBL0126)
_PIN_STRUCT_PACKING = '<I'
_DATETIME_STRUCT_PACKING = '<BBBBB'
_DAY_STRUCT_PACKING = '<BBBBBBBB'
def _encode_datetime(dt):
| 64 | 64 | 60 | 6 | 58 | neffs/python-cometblue_lite | cometblue_lite/cometblue.py | Python | _encode_datetime | _encode_datetime | 32 | 41 | 32 | 32 | 3b57de1a59339f3a10c3c64991b4b2b49807164a | bigcode/the-stack | train |
4732ad25b02c06fe5f9b5950 | train | class | class CometBlue:
"""CometBlue Thermostat """
def __init__(self, address, pin):
super(CometBlue, self).__init__()
self._address = address
self._pin = pin
self.available = False
self._handles = dict()
self._current = CometBlueStates()
self._target = CometBl... | class CometBlue:
| """CometBlue Thermostat """
def __init__(self, address, pin):
super(CometBlue, self).__init__()
self._address = address
self._pin = pin
self.available = False
self._handles = dict()
self._current = CometBlueStates()
self._target = CometBlueStates()
... | if -128 in temps:
_LOGGER.debug("Got invalid Temperatures: {}".format(temps))
return
# preserve current "target_temperature" when TEMPERATURE_OFF is active
if manual_temp / 2.0 == CometBlueStates.TEMPERATURE_OFF:
self.is_off = True
else:
s... | 256 | 256 | 1,900 | 5 | 250 | neffs/python-cometblue_lite | cometblue_lite/cometblue.py | Python | CometBlue | CometBlue | 242 | 489 | 242 | 242 | 06707b3a6f0020ef58c471e2d1027247660697a3 | bigcode/the-stack | train |
9ca0d8917061791f40f83e8c | train | class | class FirstLoginMiddleware(object):
def process_request(self, request):
if request.user.is_authenticated:
langs = UserLanguage.objects.filter(user=request.user)
if langs.__len__() == 0:
return redirect('phrasebook:first_login')
return self.get_response(request... | class FirstLoginMiddleware(object):
| def process_request(self, request):
if request.user.is_authenticated:
langs = UserLanguage.objects.filter(user=request.user)
if langs.__len__() == 0:
return redirect('phrasebook:first_login')
return self.get_response(request)
def get_response(self, reques... | from django.shortcuts import redirect
from .models import UserLanguage
class FirstLoginMiddleware(object):
| 19 | 64 | 70 | 6 | 12 | DanCatchpole/phrasebook-django | phrasebook/middleware.py | Python | FirstLoginMiddleware | FirstLoginMiddleware | 6 | 15 | 6 | 6 | 1046eaca788cc21288c7970e3d6aacdd6a3dae99 | bigcode/the-stack | train |
f838f8064d7a862d34c851d1 | train | class | class QualityInstruments:
def __init__(self):
pass
def read_file(self, filepath):
with open(filepath) as file:
for line in file:
print(line)
| class QualityInstruments:
| def __init__(self):
pass
def read_file(self, filepath):
with open(filepath) as file:
for line in file:
print(line)
| class QualityInstruments:
| 5 | 64 | 41 | 5 | 0 | ninc/lynx_datafetcher | src/QualityInstruments.py | Python | QualityInstruments | QualityInstruments | 3 | 11 | 3 | 4 | 0bf27d0c9e01f527835f48ccbf439ef7222959c5 | bigcode/the-stack | train |
981f1dc70801c5e47d3f4b09 | train | function | @hydra.main(config_path="../conf", config_name="config")
def train(cfg):
print(f"Training started with parameters: {cfg}")
DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
torch.manual_seed(cfg.seed)
model = ChessPiecePredictor()
t = transforms.Compose(
[
... | @hydra.main(config_path="../conf", config_name="config")
def train(cfg):
| print(f"Training started with parameters: {cfg}")
DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
torch.manual_seed(cfg.seed)
model = ChessPiecePredictor()
t = transforms.Compose(
[
transforms.Resize((cfg.image_size, cfg.image_size)),
... | import hydra
import matplotlib.pyplot as plt
import numpy as np
import torch
from model import CNN, ChessPiecePredictor
from torch import nn, optim
from torchvision.datasets import ImageFolder
from torchvision import transforms
import torch.utils.data as data_utils
from torch.utils.data import DataLoader
from kornia.x ... | 96 | 224 | 749 | 18 | 77 | Mads94MLOps/chess_positions_recognition | src/models/train_model.py | Python | train | train | 14 | 117 | 14 | 16 | d6e2b556c58b991bf5b1ec17701d2c69d7e8f953 | bigcode/the-stack | train |
5abb8a8507b96cdcbcdeaaac | train | class | class Solution:
'''
64.58%
'''
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
'''
nums: sorted
'''
l, r = 0, len(nums) - 1
def buildTree(lix, rix) -> 'root':
'''
0, 0 0, 1 0, 2 0, 3 0, 4
0 0... | class Solution:
| '''
64.58%
'''
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
'''
nums: sorted
'''
l, r = 0, len(nums) - 1
def buildTree(lix, rix) -> 'root':
'''
0, 0 0, 1 0, 2 0, 3 0, 4
0 0 1 1... | two subtrees of every node never differs by more than one.
Created on 17 Apr 2021
@author: Odys Zhou
'''
from unittest import TestCase
from typing import List
from utils.treehelper2 import TreeNode, list2tree
# Definition for a binary tree node.
class Solution:
| 64 | 64 | 190 | 3 | 61 | odys-z/hello | challenge/leet/easy/q108.py | Python | Solution | Solution | 21 | 44 | 21 | 21 | 33fde6f2d607960e7150ad88c4a8025ec5cea387 | bigcode/the-stack | train |
af0ae9acad3aee1a54a943b3 | train | function | def planAreaFractions( Ri, mlist ):
Npx = np.prod( np.array(Ri.shape) )
r = np.zeros( np.shape(mlist) )
j = 0
for im in mlist:
r[j] = np.count_nonzero( Ri == im )/float( Npx )
print(' Mask {} plan area fraction = {:.2f} '.format(im, r[j]))
j += 1
return r
| def planAreaFractions( Ri, mlist ):
| Npx = np.prod( np.array(Ri.shape) )
r = np.zeros( np.shape(mlist) )
j = 0
for im in mlist:
r[j] = np.count_nonzero( Ri == im )/float( Npx )
print(' Mask {} plan area fraction = {:.2f} '.format(im, r[j]))
j += 1
return r
| m_var[j], m_std[j]))
j += 1
return m_mean, m_var, m_std
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def planAreaFractions( Ri, mlist ):
| 64 | 64 | 101 | 11 | 53 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | planAreaFractions | planAreaFractions | 740 | 749 | 740 | 740 | 04bc2c7ea4ab63daf00a93c29e2568d6280f40f6 | bigcode/the-stack | train |
86853373f923b2606830bd91 | train | function | def splitLabels(R, shapeCount, labelsize):
import scipy.ndimage as sn
for i in range(1,shapeCount+1):
nlabels = np.count_nonzero(R==i)
if (nlabels > labelsize):
print(' Label no. '+str(i)+' will be split. Original size: '+str(nlabels)+' px.')
nleft = nlabels
while (nleft > labelsize)... | def splitLabels(R, shapeCount, labelsize):
| import scipy.ndimage as sn
for i in range(1,shapeCount+1):
nlabels = np.count_nonzero(R==i)
if (nlabels > labelsize):
print(' Label no. '+str(i)+' will be split. Original size: '+str(nlabels)+' px.')
nleft = nlabels
while (nleft > labelsize):
L = R==i
LU = np.zeros(L... | Rl, shapeCount = snms.label(Rm) # this might be slow for unfiltered data
Rm = None
print(' Found {} shapes from the data.'.format(shapeCount))
return Rl, shapeCount
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def splitLabels(R, shapeCount, labelsize):
| 90 | 90 | 301 | 11 | 79 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | splitLabels | splitLabels | 604 | 630 | 604 | 604 | 07b2adfb331afe4c2ff0230abb98b64071e58a41 | bigcode/the-stack | train |
da51a0ffa50f693adbe68314 | train | function | def numpyArray2Tif( arr ):
from PIL import Image
return Image.fromarray( arr )
| def numpyArray2Tif( arr ):
| from PIL import Image
return Image.fromarray( arr )
| 000
im = Image.open(tifFile)
#im.show()
a = np.array(im)
return a
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def numpyArray2Tif( arr ):
| 64 | 64 | 23 | 9 | 55 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | numpyArray2Tif | numpyArray2Tif | 648 | 651 | 648 | 648 | b1fb8471bcfb9e63790f375aeff7cecfb4f927d3 | bigcode/the-stack | train |
df52195392d6d15fd3eb90aa | train | function | def readNumpyZGridData( filename, idx=0 ):
Rdict = readNumpyZTile(filename, dataOnly=True)
Rxdims=np.array(np.shape(Rdict['R']))
Rdict['R'] = []
RxOrig=Rdict['GlobOrig']
dPx=Rdict['dPx']
name = filename.strip('.npz') # Extract the tile name.
hdict = {'id':idx,'name': name, 'ncols':Rxdims[1],'nrows':Rxdims... | def readNumpyZGridData( filename, idx=0 ):
| Rdict = readNumpyZTile(filename, dataOnly=True)
Rxdims=np.array(np.shape(Rdict['R']))
Rdict['R'] = []
RxOrig=Rdict['GlobOrig']
dPx=Rdict['dPx']
name = filename.strip('.npz') # Extract the tile name.
hdict = {'id':idx,'name': name, 'ncols':Rxdims[1],'nrows':Rxdims[0],\
'xtlcorner':RxOrig[1],'ytl... |
saveTileAsNumpyZ( filename.strip('.asc'), Rdict )
return Rdict
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def readNumpyZGridData( filename, idx=0 ):
| 64 | 64 | 170 | 14 | 50 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | readNumpyZGridData | readNumpyZGridData | 88 | 99 | 88 | 88 | b39d909779c02edc929ee9556b5926cabf16fece | bigcode/the-stack | train |
1912c0f2fd62b764b2f7403a | train | function | def rotatePoint(pivot, point, angle):
# Simple 2D rotation matrix
rotatedPoint = np.zeros(2)
rotatedPoint[1] = pivot[1] + np.cos(angle) * (point[1] - pivot[1]) - np.sin(angle) * (point[0] - pivot[0])
rotatedPoint[0] = pivot[0] + np.sin(angle) * (point[1] - pivot[1]) + np.cos(angle) * (point[0] - pivot[0])
ret... | def rotatePoint(pivot, point, angle):
# Simple 2D rotation matrix
| rotatedPoint = np.zeros(2)
rotatedPoint[1] = pivot[1] + np.cos(angle) * (point[1] - pivot[1]) - np.sin(angle) * (point[0] - pivot[0])
rotatedPoint[0] = pivot[0] + np.sin(angle) * (point[1] - pivot[1]) + np.cos(angle) * (point[0] - pivot[0])
return rotatedPoint
| )*CtY[1] # N-Y
return XR, YR
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def rotatePoint(pivot, point, angle):
# Simple 2D rotation matrix
| 64 | 64 | 119 | 19 | 45 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | rotatePoint | rotatePoint | 360 | 365 | 360 | 361 | 97209dd2812b77353507291ea415d8faf73f9d67 | bigcode/the-stack | train |
aad1e14351ef38b7d79d9dab | train | function | def frontalAreas( Ri, hclip=1. ):
# Calculate frontal areas of the domain
Ae = 0.
for i in range( Ri.shape[0] ):
ce = (Ri[i,1:] > Ri[i,:-1]).astype(float)
he = (Ri[i,1:]-Ri[i,:-1]); he[(he<hclip)] = 0. # Height, clip out non-buildings
Ae += np.sum( ce * he )
An = 0.
for j in range( Ri.shape[1] ):... | def frontalAreas( Ri, hclip=1. ):
# Calculate frontal areas of the domain
| Ae = 0.
for i in range( Ri.shape[0] ):
ce = (Ri[i,1:] > Ri[i,:-1]).astype(float)
he = (Ri[i,1:]-Ri[i,:-1]); he[(he<hclip)] = 0. # Height, clip out non-buildings
Ae += np.sum( ce * he )
An = 0.
for j in range( Ri.shape[1] ):
cn = (Ri[1:,j] > Ri[:-1,j]).astype(float)
hn = (Ri[1:,j]-Ri[:-1,j])... | At = Npx*np.abs(np.prod(dx))
return At
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def frontalAreas( Ri, hclip=1. ):
# Calculate frontal areas of the domain
| 64 | 64 | 181 | 21 | 43 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | frontalAreas | frontalAreas | 703 | 717 | 703 | 704 | ceac55add9a683ddfe2dbfff127d762c10ec1a89 | bigcode/the-stack | train |
23c29d5b6f9a51885df24d7d | train | function | def slowCoarsen(R1,R2dims,s,n1,n2,e1,e2,Rtype):
'''Function to coarsen an integer field using the most common value. This is relatively slow for strong coarsenings.'''
from scipy import stats
print(' Coarsening using mode as value.')
maxDims = np.array(np.shape(R1))
RT = np.zeros( np.append(R2dims,int(np.rou... | def slowCoarsen(R1,R2dims,s,n1,n2,e1,e2,Rtype):
| '''Function to coarsen an integer field using the most common value. This is relatively slow for strong coarsenings.'''
from scipy import stats
print(' Coarsening using mode as value.')
maxDims = np.array(np.shape(R1))
RT = np.zeros( np.append(R2dims,int(np.round(1/s))), Rtype )
i = np.zeros(R2dims,int)
... | Indices for which values are missing
R[~idOk] = np.interp(x, xp, fp) # Fill in values where missing.
return R
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def slowCoarsen(R1,R2dims,s,n1,n2,e1,e2,Rtype):
| 87 | 87 | 293 | 22 | 65 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | slowCoarsen | slowCoarsen | 775 | 794 | 775 | 775 | 7c45a4cf85e2dade52ca540241e8c87870aff73a | bigcode/the-stack | train |
4b00b8bee1b3acbcf5c4ceff | train | function | def checkDictFormat( Rdict ):
# Backwards compatibility for variable name change.
if(not('gridRot' in Rdict)): Rdict['gridRot'] = 0.0
if ('XOrig' in Rdict and not('GlobOrig' in Rdict)):
Rdict['GlobOrig']=Rdict['XOrig']
# For some reason dPx arrays were saved as 'dpx' in the past hardcoded versions of ... | def checkDictFormat( Rdict ):
# Backwards compatibility for variable name change.
| if(not('gridRot' in Rdict)): Rdict['gridRot'] = 0.0
if ('XOrig' in Rdict and not('GlobOrig' in Rdict)):
Rdict['GlobOrig']=Rdict['XOrig']
# For some reason dPx arrays were saved as 'dpx' in the past hardcoded versions of saveTileAsNumpyZ.
if ('dpx' in Rdict and not('dPx' in Rdict)):
Rdict['dPx']=Rd... | .0
if( ('Rdims' not in Rdict) and (R is not None) ):
Rdict['Rdims'] = np.array( R.shape )
return Rdict
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def checkDictFormat( Rdict ):
# Backwards compatibility for variable name change.
| 89 | 89 | 299 | 18 | 71 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | checkDictFormat | checkDictFormat | 268 | 288 | 268 | 269 | d2d648e8fbe5dfa8625b12ed4084a054c7ffe2f3 | bigcode/the-stack | train |
041c41eda93d898be6ad03a0 | train | function | def farFieldMean( dat, Xcoord, excludeNearest ):
if( len(dat) != len(Xcoord) ):
sys.exit(' Error! The data and coord arrays are different length. Exiting ...')
idx = farFieldIds( Xcoord, excludeNearest )
return np.mean( dat[idx] )
| def farFieldMean( dat, Xcoord, excludeNearest ):
| if( len(dat) != len(Xcoord) ):
sys.exit(' Error! The data and coord arrays are different length. Exiting ...')
idx = farFieldIds( Xcoord, excludeNearest )
return np.mean( dat[idx] )
| .-clw)*np.min(xc)
idx = (xc < xth )
return idx
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def farFieldMean( dat, Xcoord, excludeNearest ):
| 64 | 64 | 66 | 13 | 51 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | farFieldMean | farFieldMean | 668 | 674 | 668 | 668 | b6f36fb6579ca7e6a3ed98a5d25bdaf2b3ac0033 | bigcode/the-stack | train |
c4e8c3587deb008c5588b30a | train | function | def canopyBetaFunction(height,dpz,alpha,beta,lai):
'''
Calculate lead area index using beta probability density function
(Markkanen et al., 2003, BLM 106, 437-459).
'''
from scipy.stats import beta as betadist
z_col=np.arange(0.,height+dpz[2],dpz[2]) # BUG HERE: np.arange(0.,height/dpz[2],dpz[2])
z_col=n... | def canopyBetaFunction(height,dpz,alpha,beta,lai):
| '''
Calculate lead area index using beta probability density function
(Markkanen et al., 2003, BLM 106, 437-459).
'''
from scipy.stats import beta as betadist
z_col=np.arange(0.,height+dpz[2],dpz[2]) # BUG HERE: np.arange(0.,height/dpz[2],dpz[2])
z_col=np.divide(z_col,height) # z/H
#print(' z_col (2) =... | idx = farFieldIds( Xcoord, excludeNearest )
return np.mean( dat[idx] )
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def canopyBetaFunction(height,dpz,alpha,beta,lai):
| 64 | 64 | 176 | 15 | 49 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | canopyBetaFunction | canopyBetaFunction | 678 | 691 | 678 | 678 | ea8c45cc73657473fbd55afcf95d5244a83434fd | bigcode/the-stack | train |
ad2d3a88ed2fa2eee3c82215 | train | function | def filterAndScale(Rxo, Rx, filterInfo, sx=1.0, ix=None, jx=None):
# Check if the indecies are explicitly given.
inxOn = True
if( ix is None or jx is None ):
inxOn = False
if( filterInfo.count(None) == 0):
if( 'user' in filterInfo[0] ):
nI = int(filterInfo[1])
for i in range(nI):
f... | def filterAndScale(Rxo, Rx, filterInfo, sx=1.0, ix=None, jx=None):
# Check if the indecies are explicitly given.
| inxOn = True
if( ix is None or jx is None ):
inxOn = False
if( filterInfo.count(None) == 0):
if( 'user' in filterInfo[0] ):
nI = int(filterInfo[1])
for i in range(nI):
ftmp = raw_input(' Enter <method>, <num> = ').split(',')
if( i == 0 and inxOn ): Rxf = applyFilter(Rx[ix,jx]... | ,:] + (1.-w[i])*Rm
return Rz
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def filterAndScale(Rxo, Rx, filterInfo, sx=1.0, ix=None, jx=None):
# Check if the indecies are explicitly given.
| 80 | 80 | 267 | 36 | 44 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | filterAndScale | filterAndScale | 502 | 531 | 502 | 504 | 369b49c16b896fa5c063f33a0648eb19171c3b23 | bigcode/the-stack | train |
9d029f012c8c74f16c781fad | train | function | def rotateGridAroundPivot( X, Y, xp, yp, theta, deg=True ):
if( deg ):
theta = theta * (np.pi/180.)
CtX = np.array([ np.cos(theta), -np.sin(theta) ])
CtY = np.array([ np.sin(theta) , np.cos(theta) ])
#print(' CtX = {} , CtY = {} '.format(CtX, CtY))
Mdims = np.shape(X)
XR = np.zeros( Mdims, float )
... | def rotateGridAroundPivot( X, Y, xp, yp, theta, deg=True ):
| if( deg ):
theta = theta * (np.pi/180.)
CtX = np.array([ np.cos(theta), -np.sin(theta) ])
CtY = np.array([ np.sin(theta) , np.cos(theta) ])
#print(' CtX = {} , CtY = {} '.format(CtX, CtY))
Mdims = np.shape(X)
XR = np.zeros( Mdims, float )
YR = np.zeros( Mdims, float )
for i in range( Mdims[0] )... | Nx, Ex = np.meshgrid(ni,ej)
return Rdict
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def rotateGridAroundPivot( X, Y, xp, yp, theta, deg=True ):
| 65 | 65 | 218 | 20 | 45 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | rotateGridAroundPivot | rotateGridAroundPivot | 337 | 355 | 337 | 338 | 9069aec3d4d730593664090d1a6bc4a24c35744e | bigcode/the-stack | train |
f4b982e4b3c04315a97711cb | train | function | def readAsciiGrid( filename, nHeaderEntries ):
try:
rx = np.loadtxt( filename, skiprows=nHeaderEntries ) # Note! skiprows=6.
print(' File {} read successfully.'.format(filename))
except:
print(' Could not read ascii grid file: {}. Exiting.'.format(filename))
sys.exit(1)
return rx
| def readAsciiGrid( filename, nHeaderEntries ):
| try:
rx = np.loadtxt( filename, skiprows=nHeaderEntries ) # Note! skiprows=6.
print(' File {} read successfully.'.format(filename))
except:
print(' Could not read ascii grid file: {}. Exiting.'.format(filename))
sys.exit(1)
return rx
| yllcorner'] = xdict['yllcenter'] - xdict['cellsize']/2.
return xdict
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def readAsciiGrid( filename, nHeaderEntries ):
| 64 | 64 | 79 | 11 | 53 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | readAsciiGrid | readAsciiGrid | 55 | 63 | 55 | 55 | 23b73b0b17f2f7c51c024c8a2e72ffc67945cf77 | bigcode/the-stack | train |
41b30def2b8ba4a7ce5a9765 | train | function | def applyFilter(Rx, filterInfo ):
import scipy.ndimage as sn # contains the filters
if( 'gauss' in filterInfo[0] ):
try:
Nf = float(filterInfo[1])
except:
print(' Failed to obtain <sigma> for the Gaussian filter. Exiting.')
sys.exit(1)
else:
try:
Nf = int(filterInfo[1])
ex... | def applyFilter(Rx, filterInfo ):
| import scipy.ndimage as sn # contains the filters
if( 'gauss' in filterInfo[0] ):
try:
Nf = float(filterInfo[1])
except:
print(' Failed to obtain <sigma> for the Gaussian filter. Exiting.')
sys.exit(1)
else:
try:
Nf = int(filterInfo[1])
except:
print(' Failed to obta... | else:
if( inxOn ): Rxf = applyFilter(Rx[ix,jx], filterInfo)
else: Rxf = applyFilter(Rx, filterInfo)
Rx = None
Rxo += sx*Rxf
else:
if( inxOn ):
Rxo += sx*Rx[ix,jx]
else:
Rxo += sx*Rx
return Rxo
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def applyFi... | 127 | 127 | 424 | 9 | 118 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | applyFilter | applyFilter | 535 | 573 | 535 | 535 | 3ffe7e7a88bb9eafec2b30aaf3a47ce14f4f1714 | bigcode/the-stack | train |
61b1cc8f46b6f31b61e939fc | train | function | def minMaxCoords( xdict , fileTypes ):
asc = fileTypes[0]; npz = fileTypes[1]
if( asc ):
xn = xdict['xllcorner']
yx = xdict['yllcorner']
xx = xdict['xllcorner']+xdict['ncols']*xdict['cellsize']
yn = xdict['yllcorner']-xdict['nrows']*xdict['cellsize']
else:
xn = xdict['xtlcorner']
yx = xdic... | def minMaxCoords( xdict , fileTypes ):
| asc = fileTypes[0]; npz = fileTypes[1]
if( asc ):
xn = xdict['xllcorner']
yx = xdict['yllcorner']
xx = xdict['xllcorner']+xdict['ncols']*xdict['cellsize']
yn = xdict['yllcorner']-xdict['nrows']*xdict['cellsize']
else:
xn = xdict['xtlcorner']
yx = xdict['ytlcorner']
xx = xdict['xtlcorne... | )# id, irow, jcol
return ijList, XO_TL, imax, jmax
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def minMaxCoords( xdict , fileTypes ):
| 64 | 64 | 155 | 11 | 53 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | minMaxCoords | minMaxCoords | 184 | 197 | 184 | 184 | ad3b0615c4e1a1cc22ddbbe57b69b9dd8f89e6f6 | bigcode/the-stack | train |
3e640f377e0ae4c9fbe4913a | train | function | def readAsciiGridHeader( filename, nHeaderEntries, idx=0 ):
fl = open( filename , 'r')
name = filename.strip('.asc') # Extract the tile name.
hdict = {'id':idx,'name': name }
# 'ncols': None
# 'nrows': None
# 'xllcorner': None
# 'yllcorner': None
# 'cellsize' : None
# 'NODATA_value' : None
for i in... | def readAsciiGridHeader( filename, nHeaderEntries, idx=0 ):
| fl = open( filename , 'r')
name = filename.strip('.asc') # Extract the tile name.
hdict = {'id':idx,'name': name }
# 'ncols': None
# 'nrows': None
# 'xllcorner': None
# 'yllcorner': None
# 'cellsize' : None
# 'NODATA_value' : None
for i in range(nHeaderEntries):
try:
s = fl.readline().low... | inen
mikko.auvinen@fmi.fi
Finnish Meteorological Institute
'''
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def readAsciiGridHeader( filename, nHeaderEntries, idx=0 ):
| 64 | 64 | 207 | 16 | 48 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | readAsciiGridHeader | readAsciiGridHeader | 15 | 39 | 15 | 15 | 450b153fde82f6f8835c4ba26f54744385356bbf | bigcode/the-stack | train |
be2a49b20dfe084e985d1edd | train | function | def marginIds( Rxdims, Mw ):
Li = np.zeros(2, int); Ri = Li.copy(); Bi = Li.copy(); Ti = Li.copy()
Li[0]= 0
Li[1]= max( int( np.ceil(Mw[0]*Rxdims[1]-1) ), 1 ) # These can never be -1.
Ri[0]= min( int((1.-Mw[1])*Rxdims[1]+1), Rxdims[1]-1 )
Ri[1]= Rxdims[1]
Bi[0]= min( int((1.-Mw[2])*Rxdims[0]+1), Rxdims... | def marginIds( Rxdims, Mw ):
| Li = np.zeros(2, int); Ri = Li.copy(); Bi = Li.copy(); Ti = Li.copy()
Li[0]= 0
Li[1]= max( int( np.ceil(Mw[0]*Rxdims[1]-1) ), 1 ) # These can never be -1.
Ri[0]= min( int((1.-Mw[1])*Rxdims[1]+1), Rxdims[1]-1 )
Ri[1]= Rxdims[1]
Bi[0]= min( int((1.-Mw[2])*Rxdims[0]+1), Rxdims[0]-1 )
Bi[1]= Rxdims[0]
... | Int( ax ):
try:
ax = np.mean(np.abs(ax))
except:
pass
return int(ax)
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def marginIds( Rxdims, Mw ):
| 66 | 66 | 220 | 11 | 55 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | marginIds | marginIds | 380 | 396 | 380 | 381 | 935b230905f47f3f674fd7765dfe3c7cf3e2027d | bigcode/the-stack | train |
1903643af0db40cee0457e51 | train | function | def readNumpyZTile( filename, dataOnly=False, verbose=True):
if (verbose):
print(' Read filename {} '.format(filename))
# dat must be closed to avoid leaking file descriptors.
try:
dat = np.load(filename)
Rdict = dict(dat)
dat.close()
except IOError as e:
print('Error reading file {0}: {1}'.... | def readNumpyZTile( filename, dataOnly=False, verbose=True):
| if (verbose):
print(' Read filename {} '.format(filename))
# dat must be closed to avoid leaking file descriptors.
try:
dat = np.load(filename)
Rdict = dict(dat)
dat.close()
except IOError as e:
print('Error reading file {0}: {1}'.format(filename, e.strerror))
sys.exit(e.errno)
#if(da... | ['GlobOrigBL'] = np.array([ BLN , BLE ])
return Rdict
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def readNumpyZTile( filename, dataOnly=False, verbose=True):
| 64 | 64 | 128 | 16 | 48 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | readNumpyZTile | readNumpyZTile | 291 | 308 | 291 | 291 | 2f5ca3fbccd023633a17f2dcef755779857c9d5f | bigcode/the-stack | train |
2db6077f77862b7d4b4091b9 | train | function | def asciiTileToNumpyZ(filename, nHeaderEntries, idx=0):
Rdict, idx = readAsciiGridHeader( filename, nHeaderEntries, idx )
R = readAsciiGrid( filename, nHeaderEntries )
Rdict['id'] = idx
Rdict['ytlcorner'] = Rdict['yllcorner'] + Rdict['cellsize']* Rdict['nrows']
Rdict['xtlcorner'] = Rdict['xllcorner']
... | def asciiTileToNumpyZ(filename, nHeaderEntries, idx=0):
| Rdict, idx = readAsciiGridHeader( filename, nHeaderEntries, idx )
R = readAsciiGrid( filename, nHeaderEntries )
Rdict['id'] = idx
Rdict['ytlcorner'] = Rdict['yllcorner'] + Rdict['cellsize']* Rdict['nrows']
Rdict['xtlcorner'] = Rdict['xllcorner']
# These are ofter used later.
Rdict['GlobOrig'] = np.ar... | : {}. Exiting.'.format(filename))
sys.exit(1)
return rx
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def asciiTileToNumpyZ(filename, nHeaderEntries, idx=0):
| 64 | 64 | 197 | 17 | 47 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | asciiTileToNumpyZ | asciiTileToNumpyZ | 67 | 84 | 67 | 68 | ea2376da8e64bbb515cf8b0e2eafeba1e76fc2d4 | bigcode/the-stack | train |
e103abe3fcd082d408e5bc95 | train | function | def entry2Int( ax ):
try:
ax = np.mean(np.abs(ax))
except:
pass
return int(ax)
| def entry2Int( ax ):
| try:
ax = np.mean(np.abs(ax))
except:
pass
return int(ax)
| [1] - pivot[1]) + np.cos(angle) * (point[0] - pivot[0])
return rotatedPoint
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def entry2Int( ax ):
| 64 | 64 | 30 | 7 | 57 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | entry2Int | entry2Int | 369 | 375 | 369 | 369 | 74b932a70fd0af321675c6c6de9c8de9235c1694 | bigcode/the-stack | train |
caa54143c7e12d3f538b8898 | train | function | def applyMargins( Rx, Mw, Mr, Mh ):
Rxdims = np.shape(Rx)
if( Mw.count(None) == 0 ):
print(' Zero (or non-zero) margins: L={}, R={}, B={}, T={}'.format(Mw[0],Mw[1],Mw[2],Mw[3]))
L12, R12, B12, T12 = marginIds( Rxdims, Mw )
L1 = L12[0]; L2 = L12[1]
R1 = R12[0]; R2 = R12[1]
B1 = B12[0]; B2 = B12[... | def applyMargins( Rx, Mw, Mr, Mh ):
| Rxdims = np.shape(Rx)
if( Mw.count(None) == 0 ):
print(' Zero (or non-zero) margins: L={}, R={}, B={}, T={}'.format(Mw[0],Mw[1],Mw[2],Mw[3]))
L12, R12, B12, T12 = marginIds( Rxdims, Mw )
L1 = L12[0]; L2 = L12[1]
R1 = R12[0]; R2 = R12[1]
B1 = B12[0]; B2 = B12[1]
T1 = T12[0]; T2 = T12[1]
#... | xdims, Mw ):
Li = np.zeros(2, int); Ri = Li.copy(); Bi = Li.copy(); Ti = Li.copy()
Li[0]= 0
Li[1]= max( int( np.ceil(Mw[0]*Rxdims[1]-1) ), 1 ) # These can never be -1.
Ri[0]= min( int((1.-Mw[1])*Rxdims[1]+1), Rxdims[1]-1 )
Ri[1]= Rxdims[1]
Bi[0]= min( int((1.-Mw[2])*Rxdims[0]+1), Rxdims[0]-1 )
Bi[1]=... | 256 | 256 | 913 | 13 | 243 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | applyMargins | applyMargins | 400 | 460 | 400 | 401 | ae8df983dd8d902a6c5f80b06376db679d033b69 | bigcode/the-stack | train |
57949f8b50db6b92091e0b09 | train | function | def asciiCenterToCorner( xdict ):
# Resolve the issue involving xllcorner vs xllcenter. Both are allowed by ESRI ASCII standard
if( 'xllcenter' in xdict.keys() ):
xdict['xllcorner'] = xdict['xllcenter'] - xdict['cellsize']/2.
if( 'yllcenter' in xdict.keys() ):
xdict['yllcorner'] = xdict['yllcenter'] ... | def asciiCenterToCorner( xdict ):
# Resolve the issue involving xllcorner vs xllcenter. Both are allowed by ESRI ASCII standard
| if( 'xllcenter' in xdict.keys() ):
xdict['xllcorner'] = xdict['xllcenter'] - xdict['cellsize']/2.
if( 'yllcenter' in xdict.keys() ):
xdict['yllcorner'] = xdict['yllcenter'] - xdict['cellsize']/2.
return xdict
| dict, idx
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def asciiCenterToCorner( xdict ):
# Resolve the issue involving xllcorner vs xllcenter. Both are allowed by ESRI ASCII standard
| 64 | 64 | 114 | 32 | 32 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | asciiCenterToCorner | asciiCenterToCorner | 43 | 51 | 43 | 44 | 818cffd20c2ce6d9aa4177177d5a603f7f815dfe | bigcode/the-stack | train |
b3ef23160afece30f58f667a | train | function | def labelRaster(R, maskId=None):
import scipy.ndimage.measurements as snms
Rm = np.zeros( R.shape, type(R[0,0]) )
if( maskId is not None ):
mIds = list()
if( isinstance( maskId, list) ):
mIds.extend(maskId)
elif( isinstance( maskId, int ) ):
mIds.append(maskId)
else:
sys.exit('... | def labelRaster(R, maskId=None):
| import scipy.ndimage.measurements as snms
Rm = np.zeros( R.shape, type(R[0,0]) )
if( maskId is not None ):
mIds = list()
if( isinstance( maskId, list) ):
mIds.extend(maskId)
elif( isinstance( maskId, int ) ):
mIds.append(maskId)
else:
sys.exit(' Error in labelRaster: maskId is ... | x, size=Nf)
else:
print(' No filter applied. ')
Rf = Rx
return Rf
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def labelRaster(R, maskId=None):
| 65 | 65 | 218 | 9 | 56 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | labelRaster | labelRaster | 577 | 600 | 577 | 577 | a063bcc7cc5b8d24f5cd3624bc48afaf5f46db4a | bigcode/the-stack | train |
4ab3accdb4b8efd3f600a7fa | train | function | def fastCoarsen(R,Rdims,s,n1,n2,e1,e2,Rtype):
'''Function to coarsen a field using the most common value. This is relatively fast for strong coarsenings.'''
print(' Coarsening with mean value.')
maxDims = np.array(np.shape(R))
R2 = np.zeros( Rdims, Rtype ) # Create the output array.
for k in range(maxDims[0]... | def fastCoarsen(R,Rdims,s,n1,n2,e1,e2,Rtype):
| '''Function to coarsen a field using the most common value. This is relatively fast for strong coarsenings.'''
print(' Coarsening with mean value.')
maxDims = np.array(np.shape(R))
R2 = np.zeros( Rdims, Rtype ) # Create the output array.
for k in range(maxDims[0]):
for l in range(maxDims[1]):
R2[ n2... | 2)
print(' ... done!')
return RTT[:,:,0]
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def fastCoarsen(R,Rdims,s,n1,n2,e1,e2,Rtype):
| 63 | 64 | 145 | 21 | 42 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | fastCoarsen | fastCoarsen | 799 | 808 | 799 | 799 | 87f93da18e9c2b6f918e0e49b7ce1f270c026409 | bigcode/the-stack | train |
bee273391cf169920166c79d | train | function | def applyRamp( Rz, L1, L2, LeftRight, End, Mh=None ):
dL = (L2-L1)
w = np.arange( L1, L2 ).astype(float)
w -= np.min(w); w /= np.max(w)
w *= np.pi ; w -= (np.pi/2.)
w = np.sin(w)/2. + 0.5
if ( LeftRight and not End ): # Left
if( Mh is None ): Rm = Rz[:,L1]
else: Rm = Mh[0]
... | def applyRamp( Rz, L1, L2, LeftRight, End, Mh=None ):
| dL = (L2-L1)
w = np.arange( L1, L2 ).astype(float)
w -= np.min(w); w /= np.max(w)
w *= np.pi ; w -= (np.pi/2.)
w = np.sin(w)/2. + 0.5
if ( LeftRight and not End ): # Left
if( Mh is None ): Rm = Rz[:,L1]
else: Rm = Mh[0]
#
elif( LeftRight and End ): # Right
if... | ] is None) or (Mw[3] ==0.) ):
Rx = applyRamp( Rx, T11, T22, 0, 0, Mh )
else:
Rx = applyRamp( Rx, T11, T22, 0, 0 )
return Rx
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def applyRamp( Rz, L1, L2, LeftRight, End, Mh=None ):
| 112 | 112 | 375 | 21 | 91 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | applyRamp | applyRamp | 465 | 498 | 465 | 465 | 739c8385d2c2fe4d363939f807596ef35d35ee54 | bigcode/the-stack | train |
a4c4ad8c96584e7e1cf77af7 | train | function | def replaceByNans( Rt, a, b ):
if( a is not None ):
idr = (Rt > a )
Rt[idr] = np.nan
if( b is not None ):
idr = (Rt < b )
Rt[idr] = np.nan
return Rt
| def replaceByNans( Rt, a, b ):
| if( a is not None ):
idr = (Rt > a )
Rt[idr] = np.nan
if( b is not None ):
idr = (Rt < b )
Rt[idr] = np.nan
return Rt
| area fraction = {:.2f} '.format(im, r[j]))
j += 1
return r
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def replaceByNans( Rt, a, b ):
| 64 | 64 | 68 | 12 | 52 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | replaceByNans | replaceByNans | 753 | 761 | 753 | 753 | 50bffa601be211d9aacbe048e6602328d063b96a | bigcode/the-stack | train |
cf36b58256179337f3b8b133 | train | function | def saveTileAsNumpyZ( filename, Rdict):
'''
The saved npz file doesn't contain Rdict, but separate numpy arrays matching key names.
Therefore np.load(filename) is equal to the saved Rdict.
'''
try:
np.savez_compressed(filename, **Rdict)
print(' {} saved successfully!'.format(filename))
except:
p... | def saveTileAsNumpyZ( filename, Rdict):
| '''
The saved npz file doesn't contain Rdict, but separate numpy arrays matching key names.
Therefore np.load(filename) is equal to the saved Rdict.
'''
try:
np.savez_compressed(filename, **Rdict)
print(' {} saved successfully!'.format(filename))
except:
print(' Error in saving {}.npz in saveTil... | .shape(T)))
M = None
Rdict = {'R' : T}
return Rdict
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def saveTileAsNumpyZ( filename, Rdict):
| 64 | 64 | 101 | 13 | 51 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | saveTileAsNumpyZ | saveTileAsNumpyZ | 238 | 247 | 238 | 238 | 1899306be101b7515f480379e4c874fa75136483 | bigcode/the-stack | train |
e7dff511f1d90391b2d8ec81 | train | function | def maskMeanValues(Rm, Ri, mlist):
dims = np.shape(mlist)
m_mean = np.zeros(dims)
m_var = np.zeros(dims)
m_std = np.zeros(dims)
j = 0
for im in mlist:
idm = (Rm == im)
m_mean[j] = np.mean( Ri[idm] )
m_var[j] = np.var( Ri[idm] )
m_std[j] = np.std( Ri[idm] )
print(' Mask {} mean, var,... | def maskMeanValues(Rm, Ri, mlist):
| dims = np.shape(mlist)
m_mean = np.zeros(dims)
m_var = np.zeros(dims)
m_std = np.zeros(dims)
j = 0
for im in mlist:
idm = (Rm == im)
m_mean[j] = np.mean( Ri[idm] )
m_var[j] = np.var( Ri[idm] )
m_std[j] = np.std( Ri[idm] )
print(' Mask {} mean, var, std = {:.2f}, {:.2f}, {:.2f} '.for... | hn<hclip)] = 0.
An += np.sum( cn* hn )
return Ae, An
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def maskMeanValues(Rm, Ri, mlist):
| 64 | 64 | 172 | 12 | 52 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | maskMeanValues | maskMeanValues | 721 | 736 | 721 | 721 | 5d844ec01514d3ba58e536d4622ac477a5b7af76 | bigcode/the-stack | train |
ffa195a64dcc39cba01481aa | train | function | def openTifAsNumpy(tifFile):
from PIL import Image
Image.MAX_IMAGE_PIXELS = 260000000
im = Image.open(tifFile)
#im.show()
a = np.array(im)
return a
| def openTifAsNumpy(tifFile):
| from PIL import Image
Image.MAX_IMAGE_PIXELS = 260000000
im = Image.open(tifFile)
#im.show()
a = np.array(im)
return a
| no. '+str(i)+' is now at size '+str(nleft)+' px.')
return R, shapeCount
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def openTifAsNumpy(tifFile):
| 63 | 64 | 54 | 11 | 52 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | openTifAsNumpy | openTifAsNumpy | 636 | 644 | 636 | 636 | 03f60761c3d6c060f826b80102417775fc095734 | bigcode/the-stack | train |
45e80657a3ce29b6cb697b2c | train | function | def totalArea( Rdims, dx ):
#Calculate total area of the domain
Npx = np.prod( Rdims ) # Number of pixels
At = Npx*np.abs(np.prod(dx))
return At
| def totalArea( Rdims, dx ):
#Calculate total area of the domain
| Npx = np.prod( Rdims ) # Number of pixels
At = Npx*np.abs(np.prod(dx))
return At
| (lad_d))
lad=np.multiply(lad_d,lai)
return lad
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def totalArea( Rdims, dx ):
#Calculate total area of the domain
| 64 | 64 | 49 | 18 | 46 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | totalArea | totalArea | 695 | 699 | 695 | 696 | cfced4600d1126409d564e52b023c8bdf7cbfd22 | bigcode/the-stack | train |
58fdece4aabaf6d2b99d4876 | train | function | def resolutionFromDicts( dictList ):
d1 = dictList[0]
dPxRef = d1['cellsize']
for d in dictList:
dPx = d['cellsize']
if( dPx != dPxRef ):
print('The tile resolutions do not match. Exiting.')
sys.exit(1)
return np.array([dPxRef,dPxRef])
| def resolutionFromDicts( dictList ):
| d1 = dictList[0]
dPxRef = d1['cellsize']
for d in dictList:
dPx = d['cellsize']
if( dPx != dPxRef ):
print('The tile resolutions do not match. Exiting.')
sys.exit(1)
return np.array([dPxRef,dPxRef])
| ':int(dPx[0]),'nodata_value':None}
idx += 1
return hdict, idx
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def resolutionFromDicts( dictList ):
| 64 | 64 | 86 | 9 | 55 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | resolutionFromDicts | resolutionFromDicts | 103 | 113 | 103 | 103 | 2f0ffbca09adae7c0eac9b997930383bb56fa3a6 | bigcode/the-stack | train |
d7a9266ff1c68be8dacc55e1 | train | function | def compileTileGrid( dictList, ijList, Mrows, Mcols, fileTypes, nHeaderEntries ):
M = [] # An empty array to start with.
ascii = fileTypes[0]; npz = fileTypes[1]
for i in range(Mrows):
for j in range(Mcols):
for idTile, irow, jcol in ijList:
if(irow == i and jcol == j ):
d = dictLis... | def compileTileGrid( dictList, ijList, Mrows, Mcols, fileTypes, nHeaderEntries ):
| M = [] # An empty array to start with.
ascii = fileTypes[0]; npz = fileTypes[1]
for i in range(Mrows):
for j in range(Mcols):
for idTile, irow, jcol in ijList:
if(irow == i and jcol == j ):
d = dictList[idTile]
if( ascii ):
r = readAsciiGrid( d['name']+'.asc', ... | x = xdict['ytlcorner']
xx = xdict['xtlcorner']
yn = xdict['ytlcorner']
return xn, xx, yn, yx
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def compileTileGrid( dictList, ijList, Mrows, Mcols, fileTypes, nHeaderEntries ):
| 93 | 93 | 312 | 24 | 69 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | compileTileGrid | compileTileGrid | 201 | 234 | 201 | 201 | 2509e526548c4e6f35e7edd5fd91abed46c5852e | bigcode/the-stack | train |
8b5a0c6c8ec926083e28cabb | train | function | def arrangeTileGrid( dictList, fileTypes ):
coordList = []
ascii = fileTypes[0]; npz = fileTypes[1]
XO_TL = np.zeros(2) # Initialize the Top Left Origin.
for d in dictList:
# The last two indecies are for row / col addresses.
if( ascii ):
coordList.append( [d['id'], d['xllcorner'], d['yllcorner... | def arrangeTileGrid( dictList, fileTypes ):
| coordList = []
ascii = fileTypes[0]; npz = fileTypes[1]
XO_TL = np.zeros(2) # Initialize the Top Left Origin.
for d in dictList:
# The last two indecies are for row / col addresses.
if( ascii ):
coordList.append( [d['id'], d['xllcorner'], d['yllcorner'], 0, 0] )
else: # .npz
coordList... | Orig[1],'ytlcorner':RxOrig[0],\
'cellsize':int(dPx[0]),'nodata_value':None}
idx += 1
return hdict, idx
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def resolutionFromDicts( dictList ):
d1 = dictList[0]
dPxRef = d1['cellsize']
for d in dictList:
dPx = d['cellsize']
if( dPx != dP... | 198 | 198 | 662 | 11 | 187 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | arrangeTileGrid | arrangeTileGrid | 117 | 180 | 117 | 117 | db0ccae05bad97a2375ed1af71084e1773346cc2 | bigcode/the-stack | train |
6570be028193bdd4e78db711 | train | function | def initRdict(Rdict, R=None, dPx=None ):
if( R is not None ): Rdict['R'] = R
if( dPx is not None ): Rdict['dPx'] = dPx
if( 'GlobOrig' not in Rdict ):
Rdict['GlobOrig'] = np.array( [0.,0.] )
if('gridRot' not in Rdict ):
Rdict['gridRot'] = 0.0
if( ('Rdims' not in Rdict) and (R is not No... | def initRdict(Rdict, R=None, dPx=None ):
| if( R is not None ): Rdict['R'] = R
if( dPx is not None ): Rdict['dPx'] = dPx
if( 'GlobOrig' not in Rdict ):
Rdict['GlobOrig'] = np.array( [0.,0.] )
if('gridRot' not in Rdict ):
Rdict['gridRot'] = 0.0
if( ('Rdims' not in Rdict) and (R is not None) ):
Rdict['Rdims'] = np.array( R.s... | print(' Error in saving {}.npz in saveTileAsNumpyZ().'.format(filename))
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def initRdict(Rdict, R=None, dPx=None ):
| 64 | 64 | 148 | 15 | 49 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | initRdict | initRdict | 251 | 265 | 251 | 252 | 9d1b048a32d96ce7032f7371467c0d18e6488be0 | bigcode/the-stack | train |
8ab54b0040817e4a6fa59118 | train | function | def readNumpyZTileForMesh( filename ):
Rdict = readNumpyZTile( filename )
Rx = Rdict['R']
Rxdims = np.array(np.shape(Rx))
RxOrig = Rdict['GlobOrig']
dPx = Rdict['dPx']
try:
gridRot = Rdict['gridRot']
except:
gridRot = Rdict['gridRot'] = 0
# N,E - coords, start from top left.
# Sometimes the d... | def readNumpyZTileForMesh( filename ):
| Rdict = readNumpyZTile( filename )
Rx = Rdict['R']
Rxdims = np.array(np.shape(Rx))
RxOrig = Rdict['GlobOrig']
dPx = Rdict['dPx']
try:
gridRot = Rdict['gridRot']
except:
gridRot = Rdict['gridRot'] = 0
# N,E - coords, start from top left.
# Sometimes the dPx[0] is correctly negative, but someti... | (e.errno)
#if(dataOnly):
#Rdict['R'] = []
Rdict = checkDictFormat( Rdict )
return Rdict
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def readNumpyZTileForMesh( filename ):
| 75 | 75 | 252 | 11 | 64 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | readNumpyZTileForMesh | readNumpyZTileForMesh | 312 | 332 | 312 | 312 | 9e6fc18fe6003a9e6b49daa710bb1ef82dfb594a | bigcode/the-stack | train |
97cee0ba483a0ca7cbed4d8a | train | function | def farFieldIds( xc, exclx ):
# Exclude the given percentile of the nearest upstream field.
exclx = max( 1. , exclx )
exclx = min( 99., exclx )
clw = exclx / 100.
xth = (clw)*np.max(xc) + (1.-clw)*np.min(xc)
idx = (xc < xth )
return idx
| def farFieldIds( xc, exclx ):
# Exclude the given percentile of the nearest upstream field.
| exclx = max( 1. , exclx )
exclx = min( 99., exclx )
clw = exclx / 100.
xth = (clw)*np.max(xc) + (1.-clw)*np.min(xc)
idx = (xc < xth )
return idx
| from PIL import Image
return Image.fromarray( arr )
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def farFieldIds( xc, exclx ):
# Exclude the given percentile of the nearest upstream field.
| 64 | 64 | 99 | 23 | 41 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | farFieldIds | farFieldIds | 655 | 664 | 655 | 657 | 560dd14aca7578efed485b18bbbfc26ee0152c3a | bigcode/the-stack | train |
98785c2f22c641a6e771b13b | train | function | def interpolateOverNans( R ):
idOk = ~np.isnan(R)
xp = idOk.ravel().nonzero()[0] # An increasing list of indices
fp = R[idOk] # Corresponding list of values
x = np.isnan(R).ravel().nonzero()[0] # Indices for which values are missing
R[~idOk] = np.interp(x, xp, fp) # Fill in values where ... | def interpolateOverNans( R ):
| idOk = ~np.isnan(R)
xp = idOk.ravel().nonzero()[0] # An increasing list of indices
fp = R[idOk] # Corresponding list of values
x = np.isnan(R).ravel().nonzero()[0] # Indices for which values are missing
R[~idOk] = np.interp(x, xp, fp) # Fill in values where missing.
return R
| ( b is not None ):
idr = (Rt < b )
Rt[idr] = np.nan
return Rt
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def interpolateOverNans( R ):
| 64 | 64 | 106 | 8 | 56 | mjsauvinen/P4UL | pyLib/mapTools.py | Python | interpolateOverNans | interpolateOverNans | 765 | 771 | 765 | 765 | 7e8e458a3075c516f076e4c0c591471a85f1ca34 | bigcode/the-stack | train |
052f5cf2ccaf30b8e022bef4 | train | class | class TestLoadNifti(unittest.TestCase):
@parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4, TEST_CASE_5])
def test_shape(self, input_param, filenames, expected_shape):
test_image = np.random.randint(0, 2, size=[128, 128, 128])
with tempfile.TemporaryDirectory() as tempdir:... | class TestLoadNifti(unittest.TestCase):
@parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4, TEST_CASE_5])
| def test_shape(self, input_param, filenames, expected_shape):
test_image = np.random.randint(0, 2, size=[128, 128, 128])
with tempfile.TemporaryDirectory() as tempdir:
for i, name in enumerate(filenames):
filenames[i] = os.path.join(tempdir, name)
nib.save... | anonical": True, "image_only": False}, ["test_image.nii.gz"], (128, 128, 128)]
class TestLoadNifti(unittest.TestCase):
@parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4, TEST_CASE_5])
| 67 | 68 | 227 | 41 | 26 | Irme/MONAI | tests/test_load_nifti.py | Python | TestLoadNifti | TestLoadNifti | 41 | 57 | 41 | 42 | 41d9ee27bf5ef6bcb08c4e74109827175ebe67b4 | bigcode/the-stack | train |
259d9b88f09a6615429f7188 | train | function | def optimal_points(segments):
segments = sorted(segments, key=lambda s: s.end)
points = set()
i, n = 0, len(segments)
while i < n:
p = segments[i].end
points.add(p)
while i < n and segments[i].start <= p:
i += 1
return points
| def optimal_points(segments):
| segments = sorted(segments, key=lambda s: s.end)
points = set()
i, n = 0, len(segments)
while i < n:
p = segments[i].end
points.add(p)
while i < n and segments[i].start <= p:
i += 1
return points
| # Uses python3
from collections import namedtuple
Segment = namedtuple('Segment', 'start end')
def optimal_points(segments):
| 28 | 64 | 79 | 6 | 22 | deehzee/dsalgo | practice/coursera/p01_greedy/p01_5_covering_segments.py | Python | optimal_points | optimal_points | 7 | 16 | 7 | 7 | f2724f2ab344ef53bb89b52a74a9bbcb5aecf84d | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.