Datasets:

function_name
stringlengths
1
63
docstring
stringlengths
50
5.89k
masked_code
stringlengths
50
882k
implementation
stringlengths
169
12.9k
start_line
int32
1
14.6k
end_line
int32
16
14.6k
file_content
stringlengths
274
882k
read_namespaced_job_status
read status of the specified Job This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_job_status(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the Job (requi...
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.13.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import sys import os i...
def read_namespaced_job_status(self, name, namespace, **kwargs): """ read status of the specified Job This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_job_status(name, na...
1,108
1,129
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.13.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import sys import os i...
read_namespaced_job_status_with_http_info
read status of the specified Job This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_job_status_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of...
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.13.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import sys import os i...
def read_namespaced_job_status_with_http_info(self, name, namespace, **kwargs): """ read status of the specified Job This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_job_...
1,131
1,213
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.13.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import sys import os i...
replace_namespaced_job
replace the specified Job This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_job(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the Job (required) ...
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.13.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import sys import os i...
def replace_namespaced_job(self, name, namespace, body, **kwargs): """ replace the specified Job This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_job(name, namespace, ...
1,215
1,238
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.13.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import sys import os i...
replace_namespaced_job_with_http_info
replace the specified Job This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_job_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the ...
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.13.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import sys import os i...
def replace_namespaced_job_with_http_info(self, name, namespace, body, **kwargs): """ replace the specified Job This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_job_wi...
1,240
1,331
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.13.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import sys import os i...
replace_namespaced_job_status
replace status of the specified Job This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_job_status(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of th...
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.13.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import sys import os i...
def replace_namespaced_job_status(self, name, namespace, body, **kwargs): """ replace status of the specified Job This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_job_...
1,333
1,356
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.13.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import sys import os i...
replace_namespaced_job_status_with_http_info
replace status of the specified Job This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_job_status_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool :param str n...
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.13.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import sys import os i...
def replace_namespaced_job_status_with_http_info(self, name, namespace, body, **kwargs): """ replace status of the specified Job This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_...
1,358
1,449
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.13.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import sys import os i...
_evaluate_steps
One step evaluation across replica. Args: per_replica_features: the batched features. per_replica_labels: the batched labels. Returns: The loss corresponding to the given batch.
"""Tensorflow trainer class.""" import logging import math import os from typing import Callable, Dict, Optional import numpy as np import tensorflow as tf from .modeling_tf_utils import TFPreTrainedModel, shape_list from .optimization_tf import GradientAccumulator, create_optimizer from .trainer_utils import PREFIX...
@tf.function def _evaluate_steps(self, per_replica_features, per_replica_labels): """ One step evaluation across replica. Args: per_replica_features: the batched features. per_replica_labels: the batched labels. Returns: The loss corresponding to the...
161
180
"""Tensorflow trainer class.""" import logging import math import os from typing import Callable, Dict, Optional import numpy as np import tensorflow as tf from .modeling_tf_utils import TFPreTrainedModel, shape_list from .optimization_tf import GradientAccumulator, create_optimizer from .trainer_utils import PREFIX...
_run_model
Computes the loss of the given features and labels pair. Args: features: the batched features. labels: the batched labels. training: run the model in training mode or not
"""Tensorflow trainer class.""" import logging import math import os from typing import Callable, Dict, Optional import numpy as np import tensorflow as tf from .modeling_tf_utils import TFPreTrainedModel, shape_list from .optimization_tf import GradientAccumulator, create_optimizer from .trainer_utils import PREFIX...
def _run_model(self, features, labels, training): """ Computes the loss of the given features and labels pair. Args: features: the batched features. labels: the batched labels. training: run the model in training mode or not """ if self.args.mode...
383
410
"""Tensorflow trainer class.""" import logging import math import os from typing import Callable, Dict, Optional import numpy as np import tensorflow as tf from .modeling_tf_utils import TFPreTrainedModel, shape_list from .optimization_tf import GradientAccumulator, create_optimizer from .trainer_utils import PREFIX...
predict
Run prediction and return predictions and potential metrics. Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method will also return metrics, like in evaluate(). Args: test_dataset: something similar to a PT Dataset. This is just temporary before to have a fram...
"""Tensorflow trainer class.""" import logging import math import os from typing import Callable, Dict, Optional import numpy as np import tensorflow as tf from .modeling_tf_utils import TFPreTrainedModel, shape_list from .optimization_tf import GradientAccumulator, create_optimizer from .trainer_utils import PREFIX...
def predict(self, test_dataset: tf.data.Dataset) -> PredictionOutput: """ Run prediction and return predictions and potential metrics. Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method will also return metrics, like in evaluat...
412
424
"""Tensorflow trainer class.""" import logging import math import os from typing import Callable, Dict, Optional import numpy as np import tensorflow as tf from .modeling_tf_utils import TFPreTrainedModel, shape_list from .optimization_tf import GradientAccumulator, create_optimizer from .trainer_utils import PREFIX...
create_tenant
Creates a new tenant. Note this route only works when run against Prefect Server. Args: - name (str): the name of the tenant to create - slug (str, optional): the slug of the tenant to create; defaults to name Returns: - str: the ID of the newly created tenant, or the ID of the currently active tenant R...
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
def create_tenant(self, name: str, slug: str = None) -> str: """ Creates a new tenant. Note this route only works when run against Prefect Server. Args: - name (str): the name of the tenant to create - slug (str, optional): the slug of the tenant to create; ...
128
159
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
get
Convenience function for calling the Prefect API with token auth and GET request Args: - path (str): the path of the API url. For example, to GET http://prefect-server/v1/auth/login, path would be 'auth/login'. - server (str, optional): the server to send the GET request to; defaults to `self.a...
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
def get( self, path: str, server: str = None, headers: dict = None, params: Dict[str, JSONLike] = None, token: str = None, retry_on_api_error: bool = True, ) -> dict: """ Convenience function for calling the Prefect API with token auth and ...
164
202
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
post
Convenience function for calling the Prefect API with token auth and POST request Args: - path (str): the path of the API url. For example, to POST http://prefect-server/v1/auth/login, path would be 'auth/login'. - server (str, optional): the server to send the POST request to; defaults to `sel...
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
def post( self, path: str, server: str = None, headers: dict = None, params: Dict[str, JSONLike] = None, token: str = None, retry_on_api_error: bool = True, ) -> dict: """ Convenience function for calling the Prefect API with token auth and...
204
242
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
get_auth_token
Returns an auth token: - if no explicit access token is stored, returns the api token - if there is an access token: - if there's a refresh token and the access token expires in the next 30 seconds, then we refresh the access token and store the result - return the access token Return...
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
def get_auth_token(self) -> str: """ Returns an auth token: - if no explicit access token is stored, returns the api token - if there is an access token: - if there's a refresh token and the access token expires in the next 30 seconds, then w...
486
505
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
_refresh_access_token
Refresh the client's JWT access token. NOTE: this should only be called by users who have provided a USER-scoped API token. Returns: - bool: True if the refresh succeeds
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
def _refresh_access_token(self) -> bool: """ Refresh the client's JWT access token. NOTE: this should only be called by users who have provided a USER-scoped API token. Returns: - bool: True if the refresh succeeds """ payload = self.graphql( ...
609
638
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
create_project
Create a new Project Args: - project_name (str): the project that should contain this flow - project_description (str, optional): the project description Returns: - str: the ID of the newly-created project Raises: - ClientError: if the project creation failed
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
def create_project(self, project_name: str, project_description: str = None) -> str: """ Create a new Project Args: - project_name (str): the project that should contain this flow - project_description (str, optional): the project description Returns: ...
869
900
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
get_flow_run_state
Retrieves the current state for a flow run. Args: - flow_run_id (str): the id for this flow run Returns: - State: a Prefect State object
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
def get_flow_run_state(self, flow_run_id: str) -> "prefect.engine.state.State": """ Retrieves the current state for a flow run. Args: - flow_run_id (str): the id for this flow run Returns: - State: a Prefect State object """ query = { ...
1,072
1,092
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
set_flow_run_state
Sets new state for a flow run in the database. Args: - flow_run_id (str): the id of the flow run to set state for - state (State): the new state for this flow run - version (int, optional): the current version of the flow run state. This is optional but it can be supplied to enforce version-locking...
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
def set_flow_run_state( self, flow_run_id: str, state: "prefect.engine.state.State", version: int = None, ) -> "prefect.engine.state.State": """ Sets new state for a flow run in the database. Args: - flow_run_id (str): the id of the flow run t...
1,094
1,150
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
get_task_run_info
Retrieves version and current state information for the given task run. Args: - flow_run_id (str): the id of the flow run that this task run lives in - task_id (str): the task id for this task run - map_index (int, optional): the mapping index for this task run; if `None`, it is assumed this task i...
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
def get_task_run_info( self, flow_run_id: str, task_id: str, map_index: Optional[int] = None ) -> TaskRunInfoResult: """ Retrieves version and current state information for the given task run. Args: - flow_run_id (str): the id of the flow run that this task run lives...
1,192
1,255
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
get_task_run_state
Retrieves the current state for a task run. Args: - task_run_id (str): the id for this task run Returns: - State: a Prefect State object
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
def get_task_run_state(self, task_run_id: str) -> "prefect.engine.state.State": """ Retrieves the current state for a task run. Args: - task_run_id (str): the id for this task run Returns: - State: a Prefect State object """ query = { ...
1,282
1,302
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
set_task_run_state
Sets new state for a task run. Args: - task_run_id (str): the id of the task run to set state for - state (State): the new state for this task run - version (int, optional): the current version of the task run state. This is optional but it can be supplied to enforce version-locking. - cache_fo...
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
def set_task_run_state( self, task_run_id: str, state: "prefect.engine.state.State", version: int = None, cache_for: datetime.timedelta = None, ) -> "prefect.engine.state.State": """ Sets new state for a task run. Args: - task_run_id (...
1,304
1,362
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
set_secret
Set a secret with the given name and value. Args: - name (str): the name of the secret; used for retrieving the secret during task runs - value (Any): the value of the secret Raises: - ClientError: if the GraphQL mutation is bad for any reason - ValueError: if the secret-setting was unsuccessf...
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
def set_secret(self, name: str, value: Any) -> None: """ Set a secret with the given name and value. Args: - name (str): the name of the secret; used for retrieving the secret during task runs - value (Any): the value of the secret Raises: ...
1,364
1,388
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
write_run_logs
Uploads a collection of logs to Cloud. Args: - logs (List[Dict]): a list of log entries to add Raises: - ValueError: if uploading the logs fail
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
def write_run_logs(self, logs: List[Dict]) -> None: """ Uploads a collection of logs to Cloud. Args: - logs (List[Dict]): a list of log entries to add Raises: - ValueError: if uploading the logs fail """ mutation = { "mutation($in...
1,466
1,487
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
register_agent
Register an agent with a backend API Args: - agent_type (str): The type of agent being registered - name: (str, optional): The name of the agent being registered - labels (List[str], optional): A list of any present labels on the agent being registered - agent_config_id (str, optional): The ID ...
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
def register_agent( self, agent_type: str, name: str = None, labels: List[str] = None, agent_config_id: str = None, ) -> str: """ Register an agent with a backend API Args: - agent_type (str): The type of agent being registered ...
1,489
1,531
import datetime import json import os import re import time import uuid import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from urllib.parse import urljoin # if simplejson is installed, `requests` defaults to using it instead of json # this allows th...
get_json_state
Gets a json-encoded description of the simulation's state. As of now, it takes output and input capacities as arguments because the JSON state is described through relative values. (For instance, first output at 0.3 capacity). @param input_capacities An array containing the maximum capacities of the input. @param out...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2005 onwards University of Deusto # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # # This software consists of contributions made by many individuals, # list...
def get_json_state(self, input_capacities, output_capacities): """ Gets a json-encoded description of the simulation's state. As of now, it takes output and input capacities as arguments because the JSON state is described through relative values. (For instance, first output at 0.3 ...
211
239
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2005 onwards University of Deusto # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # # This software consists of contributions made by many individuals, # list...
do_deactivate_realm
Deactivate this realm. Do NOT deactivate the users -- we need to be able to tell the difference between users that were intentionally deactivated, e.g. by a realm admin, and users who can't currently use Zulip because their realm has been deactivated.
import datetime import itertools import logging import os import platform import time from collections import defaultdict from operator import itemgetter from typing import ( AbstractSet, Any, Callable, Dict, Iterable, List, Mapping, MutableMapping, Optional, Sequence, Set, ...
def do_deactivate_realm(realm: Realm, acting_user: Optional[UserProfile]=None) -> None: """ Deactivate this realm. Do NOT deactivate the users -- we need to be able to tell the difference between users that were intentionally deactivated, e.g. by a realm admin, and users who can't currently use Zulip be...
795
827
import datetime import itertools import logging import os import platform import time from collections import defaultdict from operator import itemgetter from typing import ( AbstractSet, Any, Callable, Dict, Iterable, List, Mapping, MutableMapping, Optional, Sequence, Set, ...
_internal_prep_message
Create a message object and checks it, but doesn't send it or save it to the database. The internal function that calls this can therefore batch send a bunch of created messages together as one database query. Call do_send_messages with a list of the return values of this method.
import datetime import itertools import logging import os import platform import time from collections import defaultdict from operator import itemgetter from typing import ( AbstractSet, Any, Callable, Dict, Iterable, List, Mapping, MutableMapping, Optional, Sequence, Set, ...
def _internal_prep_message(realm: Realm, sender: UserProfile, addressee: Addressee, content: str) -> Optional[Dict[str, Any]]: """ Create a message object and checks it, but doesn't send it or save it to the database. The inter...
2,385
2,415
import datetime import itertools import logging import os import platform import time from collections import defaultdict from operator import itemgetter from typing import ( AbstractSet, Any, Callable, Dict, Iterable, List, Mapping, MutableMapping, Optional, Sequence, Set, ...
add_and_switch_to_new_task
Adds a new task to an existing TARS model. Sets necessary attributes and finally 'switches' to the new task. Parameters are similar to the constructor except for model choice, batch size and negative sampling. This method does not store the resultant model onto disk. :param task_name: a string depicting the name of the...
import logging from collections import OrderedDict from pathlib import Path from typing import List, Optional, Set, Tuple, Union import numpy as np import torch from sklearn.metrics.pairwise import cosine_similarity from sklearn.preprocessing import minmax_scale from tqdm import tqdm import flair from flair.data impo...
def add_and_switch_to_new_task( self, task_name, label_dictionary: Union[List, Set, Dictionary, str], label_type: str, multi_label: bool = True, force_switch: bool = False, ): """ Adds a new task to an existing TARS model. Sets necessary attributes...
180
224
import logging from collections import OrderedDict from pathlib import Path from typing import List, Optional, Set, Tuple, Union import numpy as np import torch from sklearn.metrics.pairwise import cosine_similarity from sklearn.preprocessing import minmax_scale from tqdm import tqdm import flair from flair.data impo...
__init__
Initializes a TextClassifier :param task_name: a string depicting the name of the task :param label_dictionary: dictionary of labels you want to predict :param embeddings: name of the pre-trained transformer model e.g., 'bert-base-uncased' etc :param num_negative_labels_to_sample: number of negative labels to sample fo...
import logging from collections import OrderedDict from pathlib import Path from typing import List, Optional, Set, Tuple, Union import numpy as np import torch from sklearn.metrics.pairwise import cosine_similarity from sklearn.preprocessing import minmax_scale from tqdm import tqdm import flair from flair.data impo...
def __init__( self, task_name: Optional[str] = None, label_dictionary: Optional[Dictionary] = None, label_type: Optional[str] = None, embeddings: Union[TransformerWordEmbeddings, str] = "bert-base-uncased", num_negative_labels_to_sample: int = 2, prefix: bool ...
326
389
import logging from collections import OrderedDict from pathlib import Path from typing import List, Optional, Set, Tuple, Union import numpy as np import torch from sklearn.metrics.pairwise import cosine_similarity from sklearn.preprocessing import minmax_scale from tqdm import tqdm import flair from flair.data impo...
__init__
Initializes a TextClassifier :param task_name: a string depicting the name of the task :param label_dictionary: dictionary of labels you want to predict :param embeddings: name of the pre-trained transformer model e.g., 'bert-base-uncased' etc :param num_negative_labels_to_sample: number of negative labels to sample fo...
import logging from collections import OrderedDict from pathlib import Path from typing import List, Optional, Set, Tuple, Union import numpy as np import torch from sklearn.metrics.pairwise import cosine_similarity from sklearn.preprocessing import minmax_scale from tqdm import tqdm import flair from flair.data impo...
def __init__( self, task_name: Optional[str] = None, label_dictionary: Optional[Dictionary] = None, label_type: Optional[str] = None, embeddings: Union[TransformerDocumentEmbeddings, str] = "bert-base-uncased", num_negative_labels_to_sample: int = 2, prefix: b...
595
660
import logging from collections import OrderedDict from pathlib import Path from typing import List, Optional, Set, Tuple, Union import numpy as np import torch from sklearn.metrics.pairwise import cosine_similarity from sklearn.preprocessing import minmax_scale from tqdm import tqdm import flair from flair.data impo...
__repr__
Returns a string representation of this Point. For each coordinate (x and y), the representation: - Uses no decimal points if the number is close to an integer, - Else it uses 2 decimal places after the decimal point. Examples: Point(10, 3.14) Point(3.01, 2.99)
""" A simple Line class. NOTE: This is NOT rosegraphics -- it is your OWN Line class. Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher, Mark Hays, Amanda Stouder, Aaron Wilkin, their colleagues, and Jacob Jarski. """ # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE. import math impor...
def __repr__(self): """ Returns a string representation of this Point. For each coordinate (x and y), the representation: - Uses no decimal points if the number is close to an integer, - Else it uses 2 decimal places after the decimal point. Examples: P...
94
119
""" A simple Line class. NOTE: This is NOT rosegraphics -- it is your OWN Line class. Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher, Mark Hays, Amanda Stouder, Aaron Wilkin, their colleagues, and Jacob Jarski. """ # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE. import math impor...
__init__
:param port: port number to start the redis server on. Specify none to automatically generate :type port: int|None :param extra_args: any extra arguments kwargs will be passed to redis server as --key val
import subprocess import socket import tempfile import redis import time import os import itertools import sys # Environment variable pointing to the redis executable REDIS_PATH_ENVVAR = 'REDIS_PATH' def get_random_port(): sock = socket.socket() sock.listen(0) _, port = sock.getsockname() sock.close(...
def __init__(self, port=None, path='redis-server', **extra_args): """ :param port: port number to start the redis server on. Specify none to automatically generate :type port: int|None :param extra_args: any extra arguments kwargs will be passed to redis server as --key val "...
24
39
import subprocess import socket import tempfile import redis import time import os import itertools import sys # Environment variable pointing to the redis executable REDIS_PATH_ENVVAR = 'REDIS_PATH' def get_random_port(): sock = socket.socket() sock.listen(0) _, port = sock.getsockname() sock.close(...
_sample_reduce
Reduce function used on the sample and choice functions. Parameters ---------- reduce_iter : iterable Each element is a tuple coming generated by the _sample_map_partitions function. Returns a sequence of uniformly distributed samples;
import heapq import math import random as rnd from functools import partial from .core import Bag def sample(population, k): """Chooses k unique random elements from a bag. Returns a new bag containing elements from the population while leaving the original population unchanged. Parameters ---...
def _sample_reduce(reduce_iter, k, replace): """ Reduce function used on the sample and choice functions. Parameters ---------- reduce_iter : iterable Each element is a tuple coming generated by the _sample_map_partitions function. Returns a sequence of uniformly distributed samples; ...
93
126
import heapq import math import random as rnd from functools import partial from .core import Bag def sample(population, k): """Chooses k unique random elements from a bag. Returns a new bag containing elements from the population while leaving the original population unchanged. Parameters ---...
get_observations
Generate a `~gammapy.data.Observations`. Parameters ---------- obs_id : list Observation IDs. skip_missing : bool, optional Skip missing observations, default: False Returns ------- observations : `~gammapy.data.Observations` Container holding a list of `~gammapy.data.DataStoreObservation`
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import absolute_import, division, print_function, unicode_literals import logging import subprocess from ..utils.scripts import make_path from ..utils.testing import Checker from .obs_table import ObservationTable from .hdu_index_table impo...
def get_observations(self, obs_id, skip_missing=False): """Generate a `~gammapy.data.Observations`. Parameters ---------- obs_id : list Observation IDs. skip_missing : bool, optional Skip missing observations, default: False Returns -...
186
213
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import absolute_import, division, print_function, unicode_literals import logging import subprocess from ..utils.scripts import make_path from ..utils.testing import Checker from .obs_table import ObservationTable from .hdu_index_table impo...
copy_obs
Create a new `~gammapy.data.DataStore` containing a subset of observations. Parameters ---------- obs_id : array-like, `~gammapy.data.ObservationTable` List of observations to copy outdir : str, Path Directory for the new store hdu_class : list of str see :attr:`gammapy.data.HDUIndexTable.VALID_HDU_CLASS` ...
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import absolute_import, division, print_function, unicode_literals import logging import subprocess from ..utils.scripts import make_path from ..utils.testing import Checker from .obs_table import ObservationTable from .hdu_index_table impo...
def copy_obs(self, obs_id, outdir, hdu_class=None, verbose=False, overwrite=False): """Create a new `~gammapy.data.DataStore` containing a subset of observations. Parameters ---------- obs_id : array-like, `~gammapy.data.ObservationTable` List of observations to copy ...
215
262
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import absolute_import, division, print_function, unicode_literals import logging import subprocess from ..utils.scripts import make_path from ..utils.testing import Checker from .obs_table import ObservationTable from .hdu_index_table impo...
get
Get an existing CSIStorageCapacity resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: ...
# coding=utf-8 # *** WARNING: this file was generated by pulumigen. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities from ... import me...
@staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'CSIStorageCapacity': """ Get an existing CSIStorageCapacity resource's state with the given name, id, and optional extra properties used to qualify ...
259
282
# coding=utf-8 # *** WARNING: this file was generated by pulumigen. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities from ... import me...
commits
获取分支的commits @param branch: @param kwargs: @return:
# -*- coding: utf-8 -*- """ walle-web :copyright: © 2015-2019 walle-web.io :created time: 2019-02-24 10:47:53 :author: wushuiyong@walle-web.io """ import os import re import os.path as osp import git as PyGit from git import Repo as PyRepo class Repo: path = None def __init__(self, path=Non...
def commits(self, branch): ''' 获取分支的commits @param branch: @param kwargs: @return: ''' self.checkout_2_branch(branch) commit_log = PyGit.Git(self.path).log('--pretty=%h #@_@# %an #@_@# %s', max_count=50) commit_list = commit_log.split('\n') ...
118
144
# -*- coding: utf-8 -*- """ walle-web :copyright: © 2015-2019 walle-web.io :created time: 2019-02-24 10:47:53 :author: wushuiyong@walle-web.io """ import os import re import os.path as osp import git as PyGit from git import Repo as PyRepo class Repo: path = None def __init__(self, path=Non...
quadprog
Input: Numpy arrays, the format follows MATLAB quadprog function: https://www.mathworks.com/help/optim/ug/quadprog.html Output: Numpy array of the solution
from json import load import os import argparse import random from copy import deepcopy import torchvision import torchvision.transforms as transforms from torch import nn import sys import torch import numpy as np import cvxopt torch.manual_seed(0) from fedlab.core.client.serial_trainer import SubsetSerialTrainer fro...
def quadprog(Q, q, G, h, A, b): """ Input: Numpy arrays, the format follows MATLAB quadprog function: https://www.mathworks.com/help/optim/ug/quadprog.html Output: Numpy array of the solution """ Q = cvxopt.matrix(Q.tolist()) q = cvxopt.matrix(q.tolist(), tc='d') G = cvxopt.matrix(G.tolist()...
24
36
from json import load import os import argparse import random from copy import deepcopy import torchvision import torchvision.transforms as transforms from torch import nn import sys import torch import numpy as np import cvxopt torch.manual_seed(0) from fedlab.core.client.serial_trainer import SubsetSerialTrainer fro...
refine_dict
Clean dictionary based on frequency and gap of frequency. For example, {'s1': ['t1': 999, 't2': 199, 't3':1], 's2': ['m1': 2000, 'm2': 100]} => {'s1': ['t1': 999, 't2': 199], 's2': ['m1': 2000]} Args: full_mapping: clean_dict_filename: threshold: ignore_gap: Returns:
import argparse import json import os from collections import Counter, defaultdict from helper import _is_token_alnum THRESHOLD = 0.01 GAP = 10 def get_full_mapping(src_filename, trg_filename, align_filename, mapping_filename, reverse_src2trg=False, lowercase=True): """ Get full mapping giv...
def refine_dict(full_mapping, clean_dict_filename, threshold, ignore_gap): """ Clean dictionary based on frequency and gap of frequency. For example, {'s1': ['t1': 999, 't2': 199, 't3':1], 's2': ['m1': 2000, 'm2': 100]} => {'s1': ['t1': 999, 't2': 199], 's2': ['m1': 2000]} Args: ...
92
134
import argparse import json import os from collections import Counter, defaultdict from helper import _is_token_alnum THRESHOLD = 0.01 GAP = 10 def get_full_mapping(src_filename, trg_filename, align_filename, mapping_filename, reverse_src2trg=False, lowercase=True): """ Get full mapping giv...
generate_yaml_template
Args: base_yaml: A string representation of one type job's base yaml. slots_proto: A proto map object representation of modification template's operable smallest units. Returns: string: A yaml_template
# Copyright 2020 The FedLearner Authors. 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. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
def generate_yaml_template(base_yaml, slots_proto): """ Args: base_yaml: A string representation of one type job's base yaml. slots_proto: A proto map object representation of modification template's operable smallest units. Returns: string: A yaml_template """ slots ...
48
63
# Copyright 2020 The FedLearner Authors. 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. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
remote_shards
Returns a Dict[int, RRef] with keys being the RPC rank and values being RRefs to shards on that rank. Need to initialize the RPC framework for this functionality. Raises an exception if ShardedTensor was created with ``init_rrefs=False``
from dataclasses import dataclass, field from enum import Enum from typing import ( Callable, Dict, List, Optional, Union ) import weakref import threading import torch import torch.distributed as dist from torch.distributed import rpc from torch.distributed import distributed_c10d from torch.distr...
def remote_shards(self) -> Dict[int, List[rpc.RRef[Shard]]]: """ Returns a Dict[int, RRef] with keys being the RPC rank and values being RRefs to shards on that rank. Need to initialize the RPC framework for this functionality. Raises an exception if ShardedTensor was create...
632
644
from dataclasses import dataclass, field from enum import Enum from typing import ( Callable, Dict, List, Optional, Union ) import weakref import threading import torch import torch.distributed as dist from torch.distributed import rpc from torch.distributed import distributed_c10d from torch.distr...
prerelease_local_scheme
Return local scheme version unless building on master in CircleCI. This function returns the local scheme version number (e.g. 0.0.0.dev<N>+g<HASH>) unless building on CircleCI for a pre-release in which case it ignores the hash and produces a PEP440 compliant pre-release version number (e.g. 0.0.0.dev<N>).
import os from setuptools import setup, find_packages with open('README.rst') as readme_file: readme = readme_file.read() # MASKED: prerelease_local_scheme function (lines 8-22) setup( name='histomicsui', use_scm_version={'local_scheme': prerelease_local_scheme}, setup_requires=['setuptools-scm'], ...
def prerelease_local_scheme(version): """ Return local scheme version unless building on master in CircleCI. This function returns the local scheme version number (e.g. 0.0.0.dev<N>+g<HASH>) unless building on CircleCI for a pre-release in which case it ignores the hash and produces a PEP440 co...
8
22
import os from setuptools import setup, find_packages with open('README.rst') as readme_file: readme = readme_file.read() def prerelease_local_scheme(version): """ Return local scheme version unless building on master in CircleCI. This function returns the local scheme version number (e.g. 0.0.0...
to_proto
Converts an on demand feature view object to its protobuf representation. Returns: A OnDemandFeatureViewProto protobuf.
import copy import functools import warnings from types import MethodType from typing import Dict, List, Optional, Type, Union import dill import pandas as pd from feast.base_feature_view import BaseFeatureView from feast.data_source import RequestSource from feast.errors import RegistryInferenceFailure, SpecifiedFea...
def to_proto(self) -> OnDemandFeatureViewProto: """ Converts an on demand feature view object to its protobuf representation. Returns: A OnDemandFeatureViewProto protobuf. """ meta = OnDemandFeatureViewMeta() if self.created_timestamp: meta.cr...
253
287
import copy import functools import warnings from types import MethodType from typing import Dict, List, Optional, Type, Union import dill import pandas as pd from feast.base_feature_view import BaseFeatureView from feast.data_source import RequestSource from feast.errors import RegistryInferenceFailure, SpecifiedFea...
custom_name_func
A custom test name function that will ensure that the tests are run such that they're batched with all tests for a given data set are run together, avoiding re-reading the data more than necessary. Tests are run in alphabetical order, so put the test case first. An alternate option is to right justify the test number (...
import ast import csv import logging import math import os from nose_parameterized import parameterized import numpy import SimpleITK as sitk import six from radiomics import getTestCase, imageoperations # Get the logger. This is done outside the class, as it is needed by both the class and the custom_name_func log...
def custom_name_func(testcase_func, param_num, param): """ A custom test name function that will ensure that the tests are run such that they're batched with all tests for a given data set are run together, avoiding re-reading the data more than necessary. Tests are run in alphabetical order, so put the test ca...
22
51
import ast import csv import logging import math import os from nose_parameterized import parameterized import numpy import SimpleITK as sitk import six from radiomics import getTestCase, imageoperations # Get the logger. This is done outside the class, as it is needed by both the class and the custom_name_func log...
readBaselineFiles
Reads the 'baseline' folder contained in dataDir. All files starting with 'baseline_' are read as baseline files. These files should therefore be named as follows: 'baseline_<className>.csv'.
import ast import csv import logging import math import os from nose_parameterized import parameterized import numpy import SimpleITK as sitk import six from radiomics import getTestCase, imageoperations # Get the logger. This is done outside the class, as it is needed by both the class and the custom_name_func log...
def readBaselineFiles(self): """ Reads the 'baseline' folder contained in dataDir. All files starting with 'baseline_' are read as baseline files. These files should therefore be named as follows: 'baseline_<className>.csv'. """ baselineFiles = [fileName for fileName in os.listdir(self._baselineDi...
95
109
import ast import csv import logging import math import os from nose_parameterized import parameterized import numpy import SimpleITK as sitk import six from radiomics import getTestCase, imageoperations # Get the logger. This is done outside the class, as it is needed by both the class and the custom_name_func log...
getFeatureNames
Gets all features for which a baseline value is available for the current class and test case. Returns a list containing the feature names (without image type and feature class specifiers, i.e. just the feature name).
import ast import csv import logging import math import os from nose_parameterized import parameterized import numpy import SimpleITK as sitk import six from radiomics import getTestCase, imageoperations # Get the logger. This is done outside the class, as it is needed by both the class and the custom_name_func log...
def getFeatureNames(self, className, test): """ Gets all features for which a baseline value is available for the current class and test case. Returns a list containing the feature names (without image type and feature class specifiers, i.e. just the feature name). """ if className not in self._ba...
117
124
import ast import csv import logging import math import os from nose_parameterized import parameterized import numpy import SimpleITK as sitk import six from radiomics import getTestCase, imageoperations # Get the logger. This is done outside the class, as it is needed by both the class and the custom_name_func log...
gradients
Take gradient of output node with respect to each node in node_list. Parameters ---------- output_node: output node that we are taking derivative of. node_list: list of nodes that we are taking derivative wrt. Returns ------- A list of gradient values, one for each node in node_list respectively.
""" library to take autodiff and execute a computation graph """ from __future__ import absolute_import import numpy as np from .Node import Op from .. import ndarray from ..stream import * import ctypes import os from pynvml import * FLAG_SHOW_GRAPH = False G_NODE_ID = 0 NAME_RULE = 1 def communicate_init(worker_nu...
def gradients(output_node, node_list, scheduler_policy=None): """Take gradient of output node with respect to each node in node_list. Parameters ---------- output_node: output node that we are taking derivative of. node_list: list of nodes that we are taking derivative wrt. Returns -------...
446
488
""" library to take autodiff and execute a computation graph """ from __future__ import absolute_import import numpy as np from .Node import Op from .. import ndarray from ..stream import * import ctypes import os from pynvml import * FLAG_SHOW_GRAPH = False G_NODE_ID = 0 NAME_RULE = 1 def communicate_init(worker_nu...
distributed_gradients
Take gradient of output node with respect to each node in node_list. Parameters ---------- output_node: output node that we are taking derivative of. node_list: list of nodes that we are taking derivative wrt. Returns ------- A list of gradient values, one for each node in node_list respectively.
""" library to take autodiff and execute a computation graph """ from __future__ import absolute_import import numpy as np from .Node import Op from .. import ndarray from ..stream import * import ctypes import os from pynvml import * FLAG_SHOW_GRAPH = False G_NODE_ID = 0 NAME_RULE = 1 def communicate_init(worker_nu...
def distributed_gradients(output_node, node_list, scheduler_policy=None): """Take gradient of output node with respect to each node in node_list. Parameters ---------- output_node: output node that we are taking derivative of. node_list: list of nodes that we are taking derivative wrt. Returns...
491
531
""" library to take autodiff and execute a computation graph """ from __future__ import absolute_import import numpy as np from .Node import Op from .. import ndarray from ..stream import * import ctypes import os from pynvml import * FLAG_SHOW_GRAPH = False G_NODE_ID = 0 NAME_RULE = 1 def communicate_init(worker_nu...
find_topo_sort
Given a list of nodes, return a topo ordering of nodes ending in them. A simple algorithm is to do a post-order DFS traversal on the given nodes, going backwards based on input edges. Since a node is added to the ordering after all its predecessors are traversed due to post-order DFS, we get a topological sort.
""" library to take autodiff and execute a computation graph """ from __future__ import absolute_import import numpy as np from .Node import Op from .. import ndarray from ..stream import * import ctypes import os from pynvml import * FLAG_SHOW_GRAPH = False G_NODE_ID = 0 NAME_RULE = 1 def communicate_init(worker_nu...
def find_topo_sort(node_list): """Given a list of nodes, return a topo ordering of nodes ending in them. A simple algorithm is to do a post-order DFS traversal on the given nodes, going backwards based on input edges. Since a node is added to the ordering after all its predecessors are traversed due to...
538
551
""" library to take autodiff and execute a computation graph """ from __future__ import absolute_import import numpy as np from .Node import Op from .. import ndarray from ..stream import * import ctypes import os from pynvml import * FLAG_SHOW_GRAPH = False G_NODE_ID = 0 NAME_RULE = 1 def communicate_init(worker_nu...
broadcast_rule
Return output shape of broadcast shape_a, shape_b. e.g. broadcast_rule((3,2), (4,3,2)) returns output_shape = (4,3,2) Check out explanations and more examples at https://docs.scipy.org/doc/numpy-1.10.0/user/basics.broadcasting.html http://eli.thegreenplace.net/2015/broadcasting-arrays-in-numpy/
""" library to take autodiff and execute a computation graph """ from __future__ import absolute_import import numpy as np from .Node import Op from .. import ndarray from ..stream import * import ctypes import os from pynvml import * FLAG_SHOW_GRAPH = False G_NODE_ID = 0 NAME_RULE = 1 def communicate_init(worker_nu...
def broadcast_rule(shape_a, shape_b): """Return output shape of broadcast shape_a, shape_b. e.g. broadcast_rule((3,2), (4,3,2)) returns output_shape = (4,3,2) Check out explanations and more examples at https://docs.scipy.org/doc/numpy-1.10.0/user/basics.broadcasting.html http://eli.thegreenpla...
571
597
""" library to take autodiff and execute a computation graph """ from __future__ import absolute_import import numpy as np from .Node import Op from .. import ndarray from ..stream import * import ctypes import os from pynvml import * FLAG_SHOW_GRAPH = False G_NODE_ID = 0 NAME_RULE = 1 def communicate_init(worker_nu...
infer_shape
Given shapes of feed_dict nodes, infer shape for all nodes in graph. Implementation note: Iteratively calls node.op.infer_shape to infer shapes. Node shapes stored in self.node_to_shape_map. Parameters ---------- feed_shapes: node->shapes mapping for feed_dict nodes.
""" library to take autodiff and execute a computation graph """ from __future__ import absolute_import import numpy as np from .Node import Op from .. import ndarray from ..stream import * import ctypes import os from pynvml import * FLAG_SHOW_GRAPH = False G_NODE_ID = 0 NAME_RULE = 1 def communicate_init(worker_nu...
def infer_shape(self, feed_shapes): """Given shapes of feed_dict nodes, infer shape for all nodes in graph. Implementation note: Iteratively calls node.op.infer_shape to infer shapes. Node shapes stored in self.node_to_shape_map. Parameters ---------- feed_s...
97
118
""" library to take autodiff and execute a computation graph """ from __future__ import absolute_import import numpy as np from .Node import Op from .. import ndarray from ..stream import * import ctypes import os from pynvml import * FLAG_SHOW_GRAPH = False G_NODE_ID = 0 NAME_RULE = 1 def communicate_init(worker_nu...
memory_plan
Allocates ndarray.NDArray for every node except feed_dict nodes. Implementation note: Option 1: Alloc a ndarray.NDArray per node that persists across run() Option 2: Implement a memory pool to reuse memory for nodes of same shapes. More details see Lecture 7. For both options, self.node_to_arr_map stores node...
""" library to take autodiff and execute a computation graph """ from __future__ import absolute_import import numpy as np from .Node import Op from .. import ndarray from ..stream import * import ctypes import os from pynvml import * FLAG_SHOW_GRAPH = False G_NODE_ID = 0 NAME_RULE = 1 def communicate_init(worker_nu...
def memory_plan(self, feed_shapes): """Allocates ndarray.NDArray for every node except feed_dict nodes. Implementation note: Option 1: Alloc a ndarray.NDArray per node that persists across run() Option 2: Implement a memory pool to reuse memory for nodes of same shap...
120
149
""" library to take autodiff and execute a computation graph """ from __future__ import absolute_import import numpy as np from .Node import Op from .. import ndarray from ..stream import * import ctypes import os from pynvml import * FLAG_SHOW_GRAPH = False G_NODE_ID = 0 NAME_RULE = 1 def communicate_init(worker_nu...
run
Parameters ---------- feed_dict: a dictionary of node->np.ndarray supplied by user. convert_to_numpy_ret_vals: whether to convert ret vals to np.array Returns ------- A list of values for nodes in eval_node_list. NDArray or np.ndarray.
""" library to take autodiff and execute a computation graph """ from __future__ import absolute_import import numpy as np from .Node import Op from .. import ndarray from ..stream import * import ctypes import os from pynvml import * FLAG_SHOW_GRAPH = False G_NODE_ID = 0 NAME_RULE = 1 def communicate_init(worker_nu...
def run(self, feed_dict, convert_to_numpy_ret_vals=False): """ Parameters ---------- feed_dict: a dictionary of node->np.ndarray supplied by user. convert_to_numpy_ret_vals: whether to convert ret vals to np.array Returns ------- A list of values for ...
151
214
""" library to take autodiff and execute a computation graph """ from __future__ import absolute_import import numpy as np from .Node import Op from .. import ndarray from ..stream import * import ctypes import os from pynvml import * FLAG_SHOW_GRAPH = False G_NODE_ID = 0 NAME_RULE = 1 def communicate_init(worker_nu...
_callback
This will be called repeatedly every `self.interval` seconds. `self.subscriptions` contain tuples of (obj, args, kwargs) for each subscribing object. If overloading, this callback is expected to handle all subscriptions when it is triggered. It should not return anything and should not traceback on poorly designed hoo...
""" TickerHandler This implements an efficient Ticker which uses a subscription model to 'tick' subscribed objects at regular intervals. The ticker mechanism is used by importing and accessing the instantiated TICKER_HANDLER instance in this module. This instance is run by the server; it will save its status across s...
@inlineCallbacks def _callback(self): """ This will be called repeatedly every `self.interval` seconds. `self.subscriptions` contain tuples of (obj, args, kwargs) for each subscribing object. If overloading, this callback is expected to handle all subscriptions w...
88
139
""" TickerHandler This implements an efficient Ticker which uses a subscription model to 'tick' subscribed objects at regular intervals. The ticker mechanism is used by importing and accessing the instantiated TICKER_HANDLER instance in this module. This instance is run by the server; it will save its status across s...
__init__
Set up the ticker Args: interval (int): The stepping interval.
""" TickerHandler This implements an efficient Ticker which uses a subscription model to 'tick' subscribed objects at regular intervals. The ticker mechanism is used by importing and accessing the instantiated TICKER_HANDLER instance in this module. This instance is run by the server; it will save its status across s...
def __init__(self, interval): """ Set up the ticker Args: interval (int): The stepping interval. """ self.interval = interval self.subscriptions = {} self._is_ticking = False self._to_remove = [] self._to_add = [] # set up...
142
156
""" TickerHandler This implements an efficient Ticker which uses a subscription model to 'tick' subscribed objects at regular intervals. The ticker mechanism is used by importing and accessing the instantiated TICKER_HANDLER instance in this module. This instance is run by the server; it will save its status across s...
validate
Start/stop the task depending on how many subscribers we have using it. Args: start_delay (int): Time to way before starting.
""" TickerHandler This implements an efficient Ticker which uses a subscription model to 'tick' subscribed objects at regular intervals. The ticker mechanism is used by importing and accessing the instantiated TICKER_HANDLER instance in this module. This instance is run by the server; it will save its status across s...
def validate(self, start_delay=None): """ Start/stop the task depending on how many subscribers we have using it. Args: start_delay (int): Time to way before starting. """ subs = self.subscriptions if self.task.running: if not subs: ...
158
172
""" TickerHandler This implements an efficient Ticker which uses a subscription model to 'tick' subscribed objects at regular intervals. The ticker mechanism is used by importing and accessing the instantiated TICKER_HANDLER instance in this module. This instance is run by the server; it will save its status across s...
add
Add new ticker subscriber. Args: store_key (str): Unique storage hash. args (any, optional): Arguments to send to the hook method.
""" TickerHandler This implements an efficient Ticker which uses a subscription model to 'tick' subscribed objects at regular intervals. The ticker mechanism is used by importing and accessing the instantiated TICKER_HANDLER instance in this module. This instance is run by the server; it will save its status across s...
def add(self, store_key, *args, **kwargs): """ Add new ticker subscriber. Args: store_key (str): Unique storage hash. args (any, optional): Arguments to send to the hook method. """ _, _, _, interval, _, _ = store_key if not interval: ...
237
253
""" TickerHandler This implements an efficient Ticker which uses a subscription model to 'tick' subscribed objects at regular intervals. The ticker mechanism is used by importing and accessing the instantiated TICKER_HANDLER instance in this module. This instance is run by the server; it will save its status across s...
all_display
Get all tickers on an easily displayable form. Returns: tickers (dict): A list of all storekeys
""" TickerHandler This implements an efficient Ticker which uses a subscription model to 'tick' subscribed objects at regular intervals. The ticker mechanism is used by importing and accessing the instantiated TICKER_HANDLER instance in this module. This instance is run by the server; it will save its status across s...
def all_display(self): """ Get all tickers on an easily displayable form. Returns: tickers (dict): A list of all storekeys """ store_keys = [] for ticker in self.ticker_pool.tickers.itervalues(): for (objtup, callfunc, path, interval, idstrin...
564
576
""" TickerHandler This implements an efficient Ticker which uses a subscription model to 'tick' subscribed objects at regular intervals. The ticker mechanism is used by importing and accessing the instantiated TICKER_HANDLER instance in this module. This instance is run by the server; it will save its status across s...
size_num_grads
Count total size of all gradient arrays of a given link Args: link (chainer.link.Link): Target link object.
import multiprocessing import warnings import six from chainer.backends import cuda from chainer.dataset import convert from chainer import reporter from chainer.training.updaters import standard_updater try: from cupy.cuda import nccl _available = True except Exception: _available = False import numpy...
def size_num_grads(link): """Count total size of all gradient arrays of a given link Args: link (chainer.link.Link): Target link object. """ size = 0 num = 0 for param in link.params(): if param.size == 0: continue size += param.size num += 1 retu...
276
289
import multiprocessing import warnings import six from chainer.backends import cuda from chainer.dataset import convert from chainer import reporter from chainer.training.updaters import standard_updater try: from cupy.cuda import nccl _available = True except Exception: _available = False import numpy...
gather_grads
Put together all gradient arrays and make a single array Args: link (chainer.link.Link): Target link object. Return: cupy.ndarray
import multiprocessing import warnings import six from chainer.backends import cuda from chainer.dataset import convert from chainer import reporter from chainer.training.updaters import standard_updater try: from cupy.cuda import nccl _available = True except Exception: _available = False import numpy...
def gather_grads(link): """Put together all gradient arrays and make a single array Args: link (chainer.link.Link): Target link object. Return: cupy.ndarray """ if link.xp is numpy: raise RuntimeError('gather_grads works only on GPU.') return _gather(link, 'grad')
359
369
import multiprocessing import warnings import six from chainer.backends import cuda from chainer.dataset import convert from chainer import reporter from chainer.training.updaters import standard_updater try: from cupy.cuda import nccl _available = True except Exception: _available = False import numpy...
gather_params
Put together all gradient arrays and make a single array Args: link (chainer.link.Link): Target link object. Return: cupy.ndarray
import multiprocessing import warnings import six from chainer.backends import cuda from chainer.dataset import convert from chainer import reporter from chainer.training.updaters import standard_updater try: from cupy.cuda import nccl _available = True except Exception: _available = False import numpy...
def gather_params(link): """Put together all gradient arrays and make a single array Args: link (chainer.link.Link): Target link object. Return: cupy.ndarray """ if link.xp is numpy: raise RuntimeError('Link.gather_params works only on GPU.') return _gather(link, 'data')
372
382
import multiprocessing import warnings import six from chainer.backends import cuda from chainer.dataset import convert from chainer import reporter from chainer.training.updaters import standard_updater try: from cupy.cuda import nccl _available = True except Exception: _available = False import numpy...
get_heaviest_peak
Returns: the header_hash, height, and weight of the heaviest block that one of our peers has notified us of.
import asyncio import logging from typing import Dict, List, Optional, Set, Tuple from seno.types.blockchain_format.sized_bytes import bytes32 from seno.util.ints import uint32, uint128 log = logging.getLogger(__name__) class SyncStore: # Whether or not we are syncing sync_mode: bool long_sync: bool ...
def get_heaviest_peak(self) -> Optional[Tuple[bytes32, uint32, uint128]]: """ Returns: the header_hash, height, and weight of the heaviest block that one of our peers has notified us of. """ if len(self.peer_to_peak) == 0: return None heaviest_peak_hash: ...
101
120
import asyncio import logging from typing import Dict, List, Optional, Set, Tuple from seno.types.blockchain_format.sized_bytes import bytes32 from seno.util.ints import uint32, uint128 log = logging.getLogger(__name__) class SyncStore: # Whether or not we are syncing sync_mode: bool long_sync: bool ...
calculate_chunk_slices
Calculate slices for indexing an adapter. Parameters ---------- items_per_chunk: int Approximate number of items per chunk. num_items: int Total number of items. Returns ------- list of slices
#!/usr/bin/env python import os import re import pickle import json import glob import numpy as np from abc import ABC, abstractmethod from concurrent.futures import ProcessPoolExecutor from contextlib import contextmanager from collections import namedtuple, OrderedDict from tqdm import tqdm from .utils import img...
def calculate_chunk_slices(items_per_chunk, num_items): """Calculate slices for indexing an adapter. Parameters ---------- items_per_chunk: int Approximate number of items per chunk. num_items: int Total number of items. Returns ------- list of slices """ asser...
462
480
#!/usr/bin/env python import os import re import pickle import json import glob import numpy as np from abc import ABC, abstractmethod from concurrent.futures import ProcessPoolExecutor from contextlib import contextmanager from collections import namedtuple, OrderedDict from tqdm import tqdm from .utils import img...
iter_all
Iterate over all frames in the gulp. Parameters ---------- accepted_ids: list of str A filter for accepted ids. shuffle: bool Shuffle the items or not. Returns ------- iterator An iterator that yield a series of frames,meta tuples. See `read_frames` for details.
#!/usr/bin/env python import os import re import pickle import json import glob import numpy as np from abc import ABC, abstractmethod from concurrent.futures import ProcessPoolExecutor from contextlib import contextmanager from collections import namedtuple, OrderedDict from tqdm import tqdm from .utils import img...
def iter_all(self, accepted_ids=None, shuffle=False): """ Iterate over all frames in the gulp. Parameters ---------- accepted_ids: list of str A filter for accepted ids. shuffle: bool Shuffle the items or not. Returns ------- ...
393
423
#!/usr/bin/env python import os import re import pickle import json import glob import numpy as np from abc import ABC, abstractmethod from concurrent.futures import ProcessPoolExecutor from contextlib import contextmanager from collections import namedtuple, OrderedDict from tqdm import tqdm from .utils import img...
__init__
Constructs a NsynthConfig. Args: gansynth_subset: bool, whether to use the subset of the dataset introduced in the ICLR 2019 GANSynth paper (Engel, et al. 2018). This subset uses acoustic-only instrument sources and limits the pitches to the interval [24, 84]. The train and test splits are also modified ...
# coding=utf-8 # Copyright 2019 The TensorFlow Datasets Authors. # # 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 appl...
def __init__(self, gansynth_subset=False, estimate_f0_and_loudness=False, **kwargs): """Constructs a NsynthConfig. Args: gansynth_subset: bool, whether to use the subset of the dataset introduced in the ICLR 2019 GANSynth paper (Engel, et al. 2018). ...
107
138
# coding=utf-8 # Copyright 2019 The TensorFlow Datasets Authors. # # 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 appl...
validate_linux_host_name
Validates a string as a legal host name component. This validation will also occur server-side in the ARM API, but that may take a minute or two before the user sees it. So it's more user-friendly to validate in the CLI pre-flight.
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
def validate_linux_host_name(namespace): """Validates a string as a legal host name component. This validation will also occur server-side in the ARM API, but that may take a minute or two before the user sees it. So it's more user-friendly to validate in the CLI pre-flight. """ # https://stack...
71
83
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
__init__
Provides a proxy protocol policy, which allows an ELB to carry a client connection information to a backend. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[list] instance_ports: List of instance ports to which the policy shou...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import json import warnings import pulumi import pulumi.runtime from .. import utilities, tables class ProxyProtocolPolicy(pulumi.Cust...
def __init__(__self__, resource_name, opts=None, instance_ports=None, load_balancer=None, __name__=None, __opts__=None): """ Provides a proxy protocol policy, which allows an ELB to carry a client connection information to a backend. :param str resource_name: The name of the resourc...
22
60
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import json import warnings import pulumi import pulumi.runtime from .. import utilities, tables class ProxyProtocolPolicy(pulumi.Cust...
transform_audio
Add background noise audio. Note that this is an in-place transformation. :param audio_segment: Audio segment to add effects to. :type audio_segment: AudioSegmenet|SpeechSegment
# Copyright (c) 2021 PaddlePaddle Authors. 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. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
def transform_audio(self, audio_segment): """Add background noise audio. Note that this is an in-place transformation. :param audio_segment: Audio segment to add effects to. :type audio_segment: AudioSegmenet|SpeechSegment """ noise_json = self._rng.choice(self._noi...
45
64
# Copyright (c) 2021 PaddlePaddle Authors. 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. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
symrcm
Returns the permutation array that orders a sparse CSR or CSC matrix or Qobj in Reverse-Cuthill McKee ordering. Since the input matrix must be symmetric, this routine works on the matrix A+Trans(A) if the sym flag is set to False (Default). It is assumed by default (*sym=False*) that the input matrix is not symmetric...
# This file is part of QuTiP: Quantum Toolbox in Python. # # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met...
def symrcm(A, sym=False): """ Returns the permutation array that orders a sparse CSR or CSC matrix or Qobj in Reverse-Cuthill McKee ordering. Since the input matrix must be symmetric, this routine works on the matrix A+Trans(A) if the sym flag is set to False (Default). It is assumed by defaul...
104
149
# This file is part of QuTiP: Quantum Toolbox in Python. # # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met...
inner
Inner is called when a generated method (publicGetX) is called. _self is a reference to self created by function.__get__(exchange, type(exchange)) https://en.wikipedia.org/wiki/Closure_(computer_programming) equivalent to functools.partial
# -*- coding: utf-8 -*- """Base exchange class""" # ----------------------------------------------------------------------------- __version__ = '1.18.575' # ----------------------------------------------------------------------------- from ccxt.base.errors import ExchangeError from ccxt.base.errors import NetworkE...
@functools.wraps(entry) def inner(_self, params=None): """ Inner is called when a generated method (publicGetX) is called. _self is a reference to self created by function.__get__(exchange...
396
406
# -*- coding: utf-8 -*- """Base exchange class""" # ----------------------------------------------------------------------------- __version__ = '1.18.575' # ----------------------------------------------------------------------------- from ccxt.base.errors import ExchangeError from ccxt.base.errors import NetworkE...
is_story_file
Checks if a file is a Rasa story file. Args: file_path: Path of the file which should be checked. Returns: `True` if it's a story file, otherwise `False`.
import logging import os import shutil import tempfile import uuid import re from typing import Tuple, List, Text, Set, Union, Optional, Iterable from rasa.nlu.training_data import loading from rasa.utils.io import DEFAULT_ENCODING logger = logging.getLogger(__name__) def get_core_directory(paths: Optional[Union[Tex...
def is_story_file(file_path: Text) -> bool: """Checks if a file is a Rasa story file. Args: file_path: Path of the file which should be checked. Returns: `True` if it's a story file, otherwise `False`. """ if not file_path.endswith(".md"): return False try: wi...
140
167
import logging import os import shutil import tempfile import uuid import re from typing import Tuple, List, Text, Set, Union, Optional, Iterable from rasa.nlu.training_data import loading from rasa.utils.io import DEFAULT_ENCODING logger = logging.getLogger(__name__) def get_core_directory(paths: Optional[Union[Tex...
predict
predict function Args: model: keras model fit by fit_model X_test: Test features cate_cols: categorical columns list Returns: y_pred
from typing import Tuple, Union import numpy as np import pandas as pd import tensorflow as tf from src.models.dnn_regressor_funcs import ( _compile_model, _create_keras_model, _fit_model, _to_input_list, ) # MASKED: predict function (lines 15-28) def train( X_train: pd.DataFrame, y_train:...
def predict(model: tf.keras.Model, X_test: pd.DataFrame, cate_cols: list) -> np.array: """ predict function Args: model: keras model fit by fit_model X_test: Test features cate_cols: categorical columns list Returns: y_pred """ X_test_list = _to_input_list(df=X_test, ca...
15
28
from typing import Tuple, Union import numpy as np import pandas as pd import tensorflow as tf from src.models.dnn_regressor_funcs import ( _compile_model, _create_keras_model, _fit_model, _to_input_list, ) def predict(model: tf.keras.Model, X_test: pd.DataFrame, cate_cols: list) -> np.array: ""...
train
Training main function that takes dataset and parameters as input and returns the trained model with history Args: X_train: Train features y_train: train labels X_val: Validation labels y_val: validation labels layers: List of nodes in hidden layers num_classes: Number of classes in target varia...
from typing import Tuple, Union import numpy as np import pandas as pd import tensorflow as tf from src.models.dnn_regressor_funcs import ( _compile_model, _create_keras_model, _fit_model, _to_input_list, ) def predict(model: tf.keras.Model, X_test: pd.DataFrame, cate_cols: list) -> np.array: ""...
def train( X_train: pd.DataFrame, y_train: Union[pd.Series, np.array], X_val: pd.DataFrame, y_val: Union[pd.Series, np.array], layers: list, num_classes: int, cate_cols: list, learning_rate: float, epochs: int, batch_size: int, dropout_rate: float = 0.3, ) -> Tuple[tf.keras.c...
31
97
from typing import Tuple, Union import numpy as np import pandas as pd import tensorflow as tf from src.models.dnn_regressor_funcs import ( _compile_model, _create_keras_model, _fit_model, _to_input_list, ) def predict(model: tf.keras.Model, X_test: pd.DataFrame, cate_cols: list) -> np.array: ""...
contact_list
Displays a list of :model:`rr.Contact` linked to :model:`rr.ServiceProvider`. Includes a ModelForm for adding :model:`rr.Contact` to :model:`rr.ServiceProvider`. **Context** ``object_list`` List of :model:`rr.Contact`. ``form`` ModelForm for creating a :model:`rr.Contact` ``object`` An instance of :mod...
import logging from django.contrib import messages from django.contrib.auth.decorators import login_required from django.shortcuts import render from django.utils import timezone from django.utils.translation import ugettext as _ from rr.forms.contact import ContactForm from rr.models.contact import Contact from rr.u...
@login_required def contact_list(request, pk): """ Displays a list of :model:`rr.Contact` linked to :model:`rr.ServiceProvider`. Includes a ModelForm for adding :model:`rr.Contact` to :model:`rr.ServiceProvider`. **Context** ``object_list`` List of :model:`rr.Contact`. ``form...
16
50
import logging from django.contrib import messages from django.contrib.auth.decorators import login_required from django.shortcuts import render from django.utils import timezone from django.utils.translation import ugettext as _ from rr.forms.contact import ContactForm from rr.models.contact import Contact from rr.u...
parametrize
Parametrizes the CirqOperation. Args: *args (float): the parameters for the operations
# Copyright 2019-2020 Xanadu Quantum Technologies Inc. # 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 or...
def parametrize(self, *args): """Parametrizes the CirqOperation. Args: *args (float): the parameters for the operations """ self.parametrized_cirq_gates = self.parametrization(*args) if not isinstance(self.parametrized_cirq_gates, Sequence): self.par...
54
67
# Copyright 2019-2020 Xanadu Quantum Technologies Inc. # 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 or...
apply
Applies the CirqOperation. Args: *qubits (Cirq:Qid): the qubits on which the Cirq gates should be performed.
# Copyright 2019-2020 Xanadu Quantum Technologies Inc. # 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 or...
def apply(self, *qubits): """Applies the CirqOperation. Args: *qubits (Cirq:Qid): the qubits on which the Cirq gates should be performed. """ if not self.parametrized_cirq_gates: raise qml.DeviceError("CirqOperation must be parametrized before it can be appli...
69
78
# Copyright 2019-2020 Xanadu Quantum Technologies Inc. # 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 or...
save
Saves the current module dictionary. Args: filename (str): name of output file
import os import urllib import torch from torch.utils import model_zoo class CheckpointIO(object): ''' CheckpointIO class. It handles saving and loading checkpoints. Args: checkpoint_dir (str): path where checkpoints are saved ''' def __init__(self, checkpoint_dir='./chkpts', **kwargs):...
def save(self, filename, **kwargs): ''' Saves the current module dictionary. Args: filename (str): name of output file ''' if not os.path.isabs(filename): filename = os.path.join(self.checkpoint_dir, filename) outdict = kwargs for k, v in sel...
27
39
import os import urllib import torch from torch.utils import model_zoo class CheckpointIO(object): ''' CheckpointIO class. It handles saving and loading checkpoints. Args: checkpoint_dir (str): path where checkpoints are saved ''' def __init__(self, checkpoint_dir='./chkpts', **kwargs):...
parse_state_dict
Parse state_dict of model and return scalars. Args: state_dict (dict): State dict of model
import os import urllib import torch from torch.utils import model_zoo class CheckpointIO(object): ''' CheckpointIO class. It handles saving and loading checkpoints. Args: checkpoint_dir (str): path where checkpoints are saved ''' def __init__(self, checkpoint_dir='./chkpts', **kwargs):...
def parse_state_dict(self, state_dict): '''Parse state_dict of model and return scalars. Args: state_dict (dict): State dict of model ''' for k, v in self.module_dict.items(): if k in state_dict: v.load_state_dict(state_dict[k]) ...
83
97
import os import urllib import torch from torch.utils import model_zoo class CheckpointIO(object): ''' CheckpointIO class. It handles saving and loading checkpoints. Args: checkpoint_dir (str): path where checkpoints are saved ''' def __init__(self, checkpoint_dir='./chkpts', **kwargs):...
get_extra_rules
Helper to provide custom (project level/user level) anonymization rules as a mapping of tags -> action function. Args: use_extra (bool): If use extra rules. extra_json_path (Path_Str): Path to extra rules json file. It should be flat json with action as a key and list of tags as value. Returns: Option...
""" This module is intended to extend functionality of the code provided by original authors. The process is as follows: 1. User has to provide source root path containing (possibly nested) folders with dicom files 2. The program will recreate the structure in the destination root path and anonymize all ...
def get_extra_rules( use_extra: bool, extra_json_path: Path_Str, ) -> Optional[ActionsDict]: """Helper to provide custom (project level/user level) anonymization rules as a mapping of tags -> action function. Args: use_extra (bool): If use extra rules. extra_json_path (Path_Str): Pa...
47
73
""" This module is intended to extend functionality of the code provided by original authors. The process is as follows: 1. User has to provide source root path containing (possibly nested) folders with dicom files 2. The program will recreate the structure in the destination root path and anonymize all ...
anonymize_dicom_folder
Anonymize dicom files in `in_path`, if `in_path` doesn't contain dicom files, will do nothing. Debug == True will do sort of dry run to check if all good for the large data storages Args: in_path (Path_Str): path to the folder containing dicom files out_path (Path_Str): path to the folder there anonymized copi...
""" This module is intended to extend functionality of the code provided by original authors. The process is as follows: 1. User has to provide source root path containing (possibly nested) folders with dicom files 2. The program will recreate the structure in the destination root path and anonymize all ...
def anonymize_dicom_folder( in_path: Path_Str, out_path: Path_Str, debug: bool = False, **kwargs ): """Anonymize dicom files in `in_path`, if `in_path` doesn't contain dicom files, will do nothing. Debug == True will do sort of dry run to check if all good for the large data storages Args: ...
76
122
""" This module is intended to extend functionality of the code provided by original authors. The process is as follows: 1. User has to provide source root path containing (possibly nested) folders with dicom files 2. The program will recreate the structure in the destination root path and anonymize all ...
_cmdf_in
`{cmd}` - Adds you to the game. This command also allows moderators to add other users and arbitrary strings as participants. **Example:** `{cmd} an elephant` - Adds "an elephant" as a participant.
import asyncio import random import re import textwrap import discord from .. import utils, errors, cmd from ..servermodule import ServerModule, registered from ..enums import PrivilegeLevel @registered class TruthGame(ServerModule): MODULE_NAME = "Truth Game" MODULE_SHORT_DESCRIPTION = "Tools to play *Truth*...
@cmd.add(_cmdd, "in", top=True) async def _cmdf_in(self, substr, msg, privilege_level): """ `{cmd}` - Adds you to the game. This command also allows moderators to add other users and arbitrary strings as participants. **Example:** `{cmd} an elephant` - Adds "an elephant" as a participant....
84
107
import asyncio import random import re import textwrap import discord from .. import utils, errors, cmd from ..servermodule import ServerModule, registered from ..enums import PrivilegeLevel @registered class TruthGame(ServerModule): MODULE_NAME = "Truth Game" MODULE_SHORT_DESCRIPTION = "Tools to play *Truth*...
resize_axis
Truncates or pads a tensor to new_size on on a given axis. Truncate or extend tensor such that tensor.shape[axis] == new_size. If the size increases, the padding will be performed at the end, using fill_value. Args: tensor: The tensor to be resized. axis: An integer representing the dimension to be sliced. new_si...
import io import os import random import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from PIL import Image # MASKED: resize_axis function (lines 12-43) class CircleLoss(torch.nn.Module): def __init__(self, m=0.25, gamma=256): super(CircleLoss, self).__init__() ...
def resize_axis(tensor, axis, new_size, fill_value=0, random_sampling=False): """Truncates or pads a tensor to new_size on on a given axis. Truncate or extend tensor such that tensor.shape[axis] == new_size. If the size increases, the padding will be performed at the end, using fill_value. Args: t...
12
43
import io import os import random import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from PIL import Image def resize_axis(tensor, axis, new_size, fill_value=0, random_sampling=False): """Truncates or pads a tensor to new_size on on a given axis. Truncate or extend tensor s...
_query_for_init
返回某些类型合约的 query todo: 为了兼容旧版提供给用户的 api._data["quote"].items() 类似用法,应该限制交易所 ["SHFE", "DCE", "CZCE", "INE", "CFFEX", "KQ"]
#!usr/bin/env python3 # -*- coding:utf-8 -*- __author__ = 'yanqiong' import random import secrets from bisect import bisect_right from sgqlc.operation import Operation from pandas.core.internals import BlockManager from tqsdk.ins_schema import ins_schema, _add_all_frags RD = random.Random(secrets.randbits(128)) #...
def _query_for_init(): """ 返回某些类型合约的 query todo: 为了兼容旧版提供给用户的 api._data["quote"].items() 类似用法,应该限制交易所 ["SHFE", "DCE", "CZCE", "INE", "CFFEX", "KQ"] """ op = Operation(ins_schema.rootQuery) query = op.multi_symbol_info(class_=["FUTURE", "INDEX", "OPTION", "COMBINE", "CONT"], ...
39
48
#!usr/bin/env python3 # -*- coding:utf-8 -*- __author__ = 'yanqiong' import random import secrets from bisect import bisect_right from sgqlc.operation import Operation from pandas.core.internals import BlockManager from tqsdk.ins_schema import ins_schema, _add_all_frags RD = random.Random(secrets.randbits(128)) #...
solve_for_target_return
Solve for the weights of the minimum variance portfolio which has a specific targeted return. Constraints: sum of weights = 1, weights bound by [0, 0.2], portfolio return = target return, Returns the weights and the jacobian used to generate the solution.
''' A collection of functions to perform portfolio analysis. Max Gosselin, 2019 ''' import numpy as np import pandas as pd from scipy import optimize def portfolio_metrics(weights, avg_xs_returns, covariance_matrix): ''' Compute basic portfolio metrics: return, stdv, sharpe ratio ''' por...
def solve_for_target_return(xs_avg, covariance_matrix, target): ''' Solve for the weights of the minimum variance portfolio which has a specific targeted return. Constraints: sum of weights = 1, weights bound by [0, 0.2], portfolio return = target return, ...
103
135
''' A collection of functions to perform portfolio analysis. Max Gosselin, 2019 ''' import numpy as np import pandas as pd from scipy import optimize def portfolio_metrics(weights, avg_xs_returns, covariance_matrix): ''' Compute basic portfolio metrics: return, stdv, sharpe ratio ''' por...
_consistency_check
Required defintions: -- WHITESPACE (Default done automatically) => Assert. -- NEWLINE (Default done automatically) => Assert. Inadmissible 'eat-into'. -- SUPPRESSOR shall not eat into [NEWLINE] -- NEWLINE shall not eat into [WHITESPACE, BADSPACE, SUSPEND, SUPPRESSOR] -- WHITESPACE shall not eat in...
# Project Quex (http://quex.sourceforge.net); License: MIT; # (C) 2005-2020 Frank-Rene Schaefer; #_______________________________________________________________________________ from quex.input.setup import NotificationDB from quex.input.regular_expression.pattern import Patt...
def _consistency_check(self): """ Required defintions: -- WHITESPACE (Default done automatically) => Assert. -- NEWLINE (Default done automatically) => Assert. Inadmissible 'eat-into'. -- SUPPRESSOR shall not eat into [NEWLINE] -- NEWLINE sh...
258
342
# Project Quex (http://quex.sourceforge.net); License: MIT; # (C) 2005-2020 Frank-Rene Schaefer; #_______________________________________________________________________________ from quex.input.setup import NotificationDB from quex.input.regular_expression.pattern import Patt...
get_enrollment_dates
Takes a course object and returns student dates of enrollment. Useful for handling late registrations and modified deadlines. Example: course.get_enrollment_date()
import requests import urllib.parse import posixpath import pandas as pd # MASKED: get_enrollment_dates function (lines 6-34) def get_assignments(course): '''Takes a course object and returns a Pandas data frame with all existing assignments and their attributes/data Example: course.get_assignments()...
def get_enrollment_dates(course): '''Takes a course object and returns student dates of enrollment. Useful for handling late registrations and modified deadlines. Example: course.get_enrollment_date()''' url_path = posixpath.join("api", "v1", "courses", course['course_id'], "enrollments") api_u...
6
34
import requests import urllib.parse import posixpath import pandas as pd def get_enrollment_dates(course): '''Takes a course object and returns student dates of enrollment. Useful for handling late registrations and modified deadlines. Example: course.get_enrollment_date()''' url_path = posixpath....
get_assignments
Takes a course object and returns a Pandas data frame with all existing assignments and their attributes/data Example: course.get_assignments()
import requests import urllib.parse import posixpath import pandas as pd def get_enrollment_dates(course): '''Takes a course object and returns student dates of enrollment. Useful for handling late registrations and modified deadlines. Example: course.get_enrollment_date()''' url_path = posixpath....
def get_assignments(course): '''Takes a course object and returns a Pandas data frame with all existing assignments and their attributes/data Example: course.get_assignments()''' url_path = posixpath.join("api", "v1", "courses", course['course_id'], "assignments") api_url = urllib.parse.urljoin...
36
57
import requests import urllib.parse import posixpath import pandas as pd def get_enrollment_dates(course): '''Takes a course object and returns student dates of enrollment. Useful for handling late registrations and modified deadlines. Example: course.get_enrollment_date()''' url_path = posixpath....
get_assignment_lock_date
Takes a course object and the name of a Canvas assignment and returns the due date. Returns None if no due date assigned. Example: course.get_assignment_due_date('worksheet_01')
import requests import urllib.parse import posixpath import pandas as pd def get_enrollment_dates(course): '''Takes a course object and returns student dates of enrollment. Useful for handling late registrations and modified deadlines. Example: course.get_enrollment_date()''' url_path = posixpath....
def get_assignment_lock_date(course, assignment): '''Takes a course object and the name of a Canvas assignment and returns the due date. Returns None if no due date assigned. Example: course.get_assignment_due_date('worksheet_01')''' assignments = get_assignments(course) assignments = assignmen...
59
71
import requests import urllib.parse import posixpath import pandas as pd def get_enrollment_dates(course): '''Takes a course object and returns student dates of enrollment. Useful for handling late registrations and modified deadlines. Example: course.get_enrollment_date()''' url_path = posixpath....
get_assignment_due_date
Takes a course object and the name of a Canvas assignment and returns the due date. Returns None if no due date assigned. Example: course.get_assignment_due_date('worksheet_01')
import requests import urllib.parse import posixpath import pandas as pd def get_enrollment_dates(course): '''Takes a course object and returns student dates of enrollment. Useful for handling late registrations and modified deadlines. Example: course.get_enrollment_date()''' url_path = posixpath....
def get_assignment_due_date(course, assignment): '''Takes a course object and the name of a Canvas assignment and returns the due date. Returns None if no due date assigned. Example: course.get_assignment_due_date('worksheet_01')''' assignments = get_assignments(course) assignments = assignment...
75
87
import requests import urllib.parse import posixpath import pandas as pd def get_enrollment_dates(course): '''Takes a course object and returns student dates of enrollment. Useful for handling late registrations and modified deadlines. Example: course.get_enrollment_date()''' url_path = posixpath....
get_assignment_unlock_date
Takes a course object and the name of a Canvas assignment and returns the due date. Returns None if no due date assigned. Example: course.get_assignment_unlock_date('worksheet_01')
import requests import urllib.parse import posixpath import pandas as pd def get_enrollment_dates(course): '''Takes a course object and returns student dates of enrollment. Useful for handling late registrations and modified deadlines. Example: course.get_enrollment_date()''' url_path = posixpath....
def get_assignment_unlock_date(course, assignment): '''Takes a course object and the name of a Canvas assignment and returns the due date. Returns None if no due date assigned. Example: course.get_assignment_unlock_date('worksheet_01')''' assignments = get_assignments(course) assignments = assi...
89
100
import requests import urllib.parse import posixpath import pandas as pd def get_enrollment_dates(course): '''Takes a course object and returns student dates of enrollment. Useful for handling late registrations and modified deadlines. Example: course.get_enrollment_date()''' url_path = posixpath....
get_assignment_id
Takes a course object and the name of a Canvas assignment and returns the Canvas ID. Example: course.get_assignment_id('worksheet_01')
import requests import urllib.parse import posixpath import pandas as pd def get_enrollment_dates(course): '''Takes a course object and returns student dates of enrollment. Useful for handling late registrations and modified deadlines. Example: course.get_enrollment_date()''' url_path = posixpath....
def get_assignment_id(course, assignment): '''Takes a course object and the name of a Canvas assignment and returns the Canvas ID. Example: course.get_assignment_id('worksheet_01')''' assignments = get_assignments(course) assignments = assignments[['name', 'id']].query('name == @assignment') ...
103
110
import requests import urllib.parse import posixpath import pandas as pd def get_enrollment_dates(course): '''Takes a course object and returns student dates of enrollment. Useful for handling late registrations and modified deadlines. Example: course.get_enrollment_date()''' url_path = posixpath....
post_grade
Takes a course object, an assignment name, student id, and score to upload. Posts to Canvas. Example: course.post_grades(dsci100, 'worksheet_01', '23423', 10)
import requests import urllib.parse import posixpath import pandas as pd def get_enrollment_dates(course): '''Takes a course object and returns student dates of enrollment. Useful for handling late registrations and modified deadlines. Example: course.get_enrollment_date()''' url_path = posixpath....
def post_grade(course, assignment, student, score): '''Takes a course object, an assignment name, student id, and score to upload. Posts to Canvas. Example: course.post_grades(dsci100, 'worksheet_01', '23423', 10)''' assignment_id = get_assignment_id(course, assignment) url_post_path = posixpath.jo...
168
186
import requests import urllib.parse import posixpath import pandas as pd def get_enrollment_dates(course): '''Takes a course object and returns student dates of enrollment. Useful for handling late registrations and modified deadlines. Example: course.get_enrollment_date()''' url_path = posixpath....
make_kinetic_precond
Preconditioner P = 1 / (||k|| + ε) Keyword Arguments: kpointset --
from ..coefficient_array import PwCoeffs from scipy.sparse import dia_matrix import numpy as np # MASKED: make_kinetic_precond function (lines 6-43) class Preconditioner: def __init__(self): pass class DiagonalPreconditioner(Preconditioner): """ Apply diagonal preconditioner and project result...
def make_kinetic_precond(kpointset, c0, eps=0.1, asPwCoeffs=True): """ Preconditioner P = 1 / (||k|| + ε) Keyword Arguments: kpointset -- """ nk = len(kpointset) nc = kpointset.ctx().num_spins() if nc == 1 and nk == 1 and not asPwCoeffs: # return as np.matrix kp = k...
6
43
from ..coefficient_array import PwCoeffs from scipy.sparse import dia_matrix import numpy as np def make_kinetic_precond(kpointset, c0, eps=0.1, asPwCoeffs=True): """ Preconditioner P = 1 / (||k|| + ε) Keyword Arguments: kpointset -- """ nk = len(kpointset) nc = kpointset.ctx().num_s...
rbbox2d_to_near_bbox
convert rotated bbox to nearest 'standing' or 'lying' bbox. Args: rbboxes: [N, 5(x, y, xdim, ydim, rad)] rotated bboxes Returns: bboxes: [N, 4(xmin, ymin, xmax, ymax)] bboxes
from pathlib import Path import numba import numpy as np from det3d.core.bbox.geometry import ( points_count_convex_polygon_3d_jit, points_in_convex_polygon_3d_jit, ) try: from spconv.utils import rbbox_intersection, rbbox_iou except: print("Import spconv fail, no support for sparse convolution!") de...
def rbbox2d_to_near_bbox(rbboxes): """convert rotated bbox to nearest 'standing' or 'lying' bbox. Args: rbboxes: [N, 5(x, y, xdim, ydim, rad)] rotated bboxes Returns: bboxes: [N, 4(xmin, ymin, xmax, ymax)] bboxes """ rots = rbboxes[..., -1] rots_0_pi_div_2 = np.abs(limit_period(r...
131
143
from pathlib import Path import numba import numpy as np from det3d.core.bbox.geometry import ( points_count_convex_polygon_3d_jit, points_in_convex_polygon_3d_jit, ) try: from spconv.utils import rbbox_intersection, rbbox_iou except: print("Import spconv fail, no support for sparse convolut...
rotation_2d
rotation 2d points based on origin point clockwise when angle positive. Args: points (float array, shape=[N, point_size, 2]): points to be rotated. angles (float array, shape=[N]): rotation angle. Returns: float array: same shape as points
from pathlib import Path import numba import numpy as np from det3d.core.bbox.geometry import ( points_count_convex_polygon_3d_jit, points_in_convex_polygon_3d_jit, ) try: from spconv.utils import rbbox_intersection, rbbox_iou except: print("Import spconv fail, no support for sparse convolution!") de...
def rotation_2d(points, angles): """rotation 2d points based on origin point clockwise when angle positive. Args: points (float array, shape=[N, point_size, 2]): points to be rotated. angles (float array, shape=[N]): rotation angle. Returns: float array: same shape as points ""...
207
220
from pathlib import Path import numba import numpy as np from det3d.core.bbox.geometry import ( points_count_convex_polygon_3d_jit, points_in_convex_polygon_3d_jit, ) try: from spconv.utils import rbbox_intersection, rbbox_iou except: print("Import spconv fail, no support for sparse convolut...
rotation_box
rotation 2d points based on origin point clockwise when angle positive. Args: points (float array, shape=[N, point_size, 2]): points to be rotated. angle (float): rotation angle. Returns: float array: same shape as points
from pathlib import Path import numba import numpy as np from det3d.core.bbox.geometry import ( points_count_convex_polygon_3d_jit, points_in_convex_polygon_3d_jit, ) try: from spconv.utils import rbbox_intersection, rbbox_iou except: print("Import spconv fail, no support for sparse convolution!") de...
def rotation_box(box_corners, angle): """rotation 2d points based on origin point clockwise when angle positive. Args: points (float array, shape=[N, point_size, 2]): points to be rotated. angle (float): rotation angle. Returns: float array: same shape as points """ rot_sin...
223
238
from pathlib import Path import numba import numpy as np from det3d.core.bbox.geometry import ( points_count_convex_polygon_3d_jit, points_in_convex_polygon_3d_jit, ) try: from spconv.utils import rbbox_intersection, rbbox_iou except: print("Import spconv fail, no support for sparse convolut...
center_to_corner_box3d
convert kitti locations, dimensions and angles to corners Args: centers (float array, shape=[N, 3]): locations in kitti label file. dims (float array, shape=[N, 3]): dimensions in kitti label file. angles (float array, shape=[N]): rotation_y in kitti label file. origin (list or array or float): origin ...
from pathlib import Path import numba import numpy as np from det3d.core.bbox.geometry import ( points_count_convex_polygon_3d_jit, points_in_convex_polygon_3d_jit, ) try: from spconv.utils import rbbox_intersection, rbbox_iou except: print("Import spconv fail, no support for sparse convolution!") de...
def center_to_corner_box3d(centers, dims, angles=None, origin=(0.5, 0.5, 0.5), axis=2): """convert kitti locations, dimensions and angles to corners Args: centers (float array, shape=[N, 3]): locations in kitti label file. dims (float array, shape=[N, 3]): dimensions in kitti label file. ...
241
262
from pathlib import Path import numba import numpy as np from det3d.core.bbox.geometry import ( points_count_convex_polygon_3d_jit, points_in_convex_polygon_3d_jit, ) try: from spconv.utils import rbbox_intersection, rbbox_iou except: print("Import spconv fail, no support for sparse convolut...
center_to_corner_box2d
convert kitti locations, dimensions and angles to corners. format: center(xy), dims(xy), angles(clockwise when positive) Args: centers (float array, shape=[N, 2]): locations in kitti label file. dims (float array, shape=[N, 2]): dimensions in kitti label file. angles (float array, shape=[N]): rotation_y in...
from pathlib import Path import numba import numpy as np from det3d.core.bbox.geometry import ( points_count_convex_polygon_3d_jit, points_in_convex_polygon_3d_jit, ) try: from spconv.utils import rbbox_intersection, rbbox_iou except: print("Import spconv fail, no support for sparse convolution!") de...
def center_to_corner_box2d(centers, dims, angles=None, origin=0.5): """convert kitti locations, dimensions and angles to corners. format: center(xy), dims(xy), angles(clockwise when positive) Args: centers (float array, shape=[N, 2]): locations in kitti label file. dims (float array, shape=...
265
285
from pathlib import Path import numba import numpy as np from det3d.core.bbox.geometry import ( points_count_convex_polygon_3d_jit, points_in_convex_polygon_3d_jit, ) try: from spconv.utils import rbbox_intersection, rbbox_iou except: print("Import spconv fail, no support for sparse convolut...
iou_jit
calculate box iou. note that jit version runs 2x faster than cython in my machine! Parameters ---------- boxes: (N, 4) ndarray of float query_boxes: (K, 4) ndarray of float Returns ------- overlaps: (N, K) ndarray of overlap between boxes and query_boxes
from pathlib import Path import numba import numpy as np from det3d.core.bbox.geometry import ( points_count_convex_polygon_3d_jit, points_in_convex_polygon_3d_jit, ) try: from spconv.utils import rbbox_intersection, rbbox_iou except: print("Import spconv fail, no support for sparse convolution!") de...
@numba.jit(nopython=True) def iou_jit(boxes, query_boxes, eps=1.0): """calculate box iou. note that jit version runs 2x faster than cython in my machine! Parameters ---------- boxes: (N, 4) ndarray of float query_boxes: (K, 4) ndarray of float Returns ------- overlaps: (N, K) ndarray...
496
535
from pathlib import Path import numba import numpy as np from det3d.core.bbox.geometry import ( points_count_convex_polygon_3d_jit, points_in_convex_polygon_3d_jit, ) try: from spconv.utils import rbbox_intersection, rbbox_iou except: print("Import spconv fail, no support for sparse convolut...
image_box_region_area
check a 2d voxel is contained by a box. used to filter empty anchors. Summed-area table algorithm: ==> W ------------------ | | | |------A---------B | | | | | | |----- C---------D Iabcd = ID-IB-IC+IA Args: img_cumsum: [M, H, W](yx) cumsumed image. bbox: [N, 4](xyxy) boundi...
from pathlib import Path import numba import numpy as np from det3d.core.bbox.geometry import ( points_count_convex_polygon_3d_jit, points_in_convex_polygon_3d_jit, ) try: from spconv.utils import rbbox_intersection, rbbox_iou except: print("Import spconv fail, no support for sparse convolution!") de...
def image_box_region_area(img_cumsum, bbox): """check a 2d voxel is contained by a box. used to filter empty anchors. Summed-area table algorithm: ==> W ------------------ | | | |------A---------B | | | | | | |----- C---------D Iabcd = I...
742
766
from pathlib import Path import numba import numpy as np from det3d.core.bbox.geometry import ( points_count_convex_polygon_3d_jit, points_in_convex_polygon_3d_jit, ) try: from spconv.utils import rbbox_intersection, rbbox_iou except: print("Import spconv fail, no support for sparse convolut...
parse_command_args
This parses the arguments and returns a tuple containing: (args, command, command_args) For example, "--config=bar start --with=baz" would return: (['--config=bar'], 'start', ['--with=baz'])
""" logan.runner ~~~~~~~~~~~~ :copyright: (c) 2012 David Cramer. :license: Apache License 2.0, see NOTICE for more details. """ import argparse import os import re import sys from django.core import management from nautobot import __version__ from . import importer from .settings import create_default_settings __...
def parse_command_args(args): """ This parses the arguments and returns a tuple containing: (args, command, command_args) For example, "--config=bar start --with=baz" would return: (['--config=bar'], 'start', ['--with=baz']) """ index = None for arg_i, arg in enumerate(args): ...
29
49
""" logan.runner ~~~~~~~~~~~~ :copyright: (c) 2012 David Cramer. :license: Apache License 2.0, see NOTICE for more details. """ import argparse import os import re import sys from django.core import management from nautobot import __version__ from . import importer from .settings import create_default_settings __...