query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
The output stream of the last executed command. Will execute default command if none is set, or error if there's no default. Returns str The `String` scalar type represents textual data, represented as UTF8 character sequences. The String type is most often used by GraphQL to represent freeform humanreadable text. Rais...
def stdout(self) -> str: _args: list[Arg] = [] _ctx = self._select("stdout", _args) return _ctx.execute_sync(str)
[ "def execute_stream(self):\n if self._mode != \"sync\":\n raise DALServiceError(\n \"Cannot execute a non-synchronous query. Use submit instead\")\n\n url = self.getqueryurl()\n\n try:\n return self.submit().raw\n except requests.RequestException as e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the user to be set for all commands. Returns Optional[str] The `String` scalar type represents textual data, represented as UTF8 character sequences. The String type is most often used by GraphQL to represent freeform humanreadable text. Raises ExecuteTimeoutError If the time to execute the query exceeds the ...
def user(self) -> Optional[str]: _args: list[Arg] = [] _ctx = self._select("user", _args) return _ctx.execute_sync(Optional[str])
[ "def user_data(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"user_data\")", "def get_user_input(self):\r\n\r\n defaults = get_settings_from_client(self.client)\r\n timeout = defaults['timeout']\r\n\r\n # Ask for username\r\n while True:\r\n usernam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves this container but with a different command entrypoint.
def with_entrypoint(self, args: Sequence[str]) -> "Container": _args = [ Arg("args", args), ] _ctx = self._select("withEntrypoint", _args) return Container(_ctx)
[ "def get_entrypoint():\n return config.get(\"app\", \"entrypoint\")", "def container_command(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:\n return pulumi.get(self, \"container_command\")", "def exec_cmd(self, container: _t.Any, cmd: str) -> _t.Any:", "def get_entry_point_command(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Expose a network port.
def with_exposed_port( self, port: int, protocol: Optional[NetworkProtocol] = None, description: Optional[str] = None, ) -> "Container": _args = [ Arg("port", port), Arg("protocol", protocol, None), Arg("description", description, None), ...
[ "def expose_port(self, port: int) -> None:\n self.container_options.ports[port] = port", "def add_port(cls, port, ser):\n cls._open_ports[port] = ser", "def set_port(self, port):\n \tself._port = port", "def set_port(self, port):\n self.port = port\n self.__endpoint_liveness_che...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves this container plus the given label.
def with_label(self, name: str, value: str) -> "Container": _args = [ Arg("name", name), Arg("value", value), ] _ctx = self._select("withLabel", _args) return Container(_ctx)
[ "def add_label(self, label):\n return self.label(label, action='ADD')", "def get_label(self, label):\n return self.labels[label]", "def get_item_from_label(self, label):\n idx = self.labels.index(label)\n item = self[idx][0]\n return item", "def addLabel(self, name):\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves this container plus a cache volume mounted at the given path.
def with_mounted_cache( self, path: str, cache: CacheVolume, source: Optional["Directory"] = None, sharing: Optional[CacheSharingMode] = None, owner: Optional[str] = None, ) -> "Container": _args = [ Arg("path", path), Arg("cache", cach...
[ "def cache_volume(self, key: str) -> CacheVolume:\n _args = [\n Arg(\"key\", key),\n ]\n _ctx = self._select(\"cacheVolume\", _args)\n return CacheVolume(_ctx)", "def getCachedVolume( node ):\n return cache.CACHE.getData(node, key=\"boundingVolume\")", "def cache_path(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves this container plus a temporary directory mounted at the given path.
def with_mounted_temp(self, path: str) -> "Container": _args = [ Arg("path", path), ] _ctx = self._select("withMountedTemp", _args) return Container(_ctx)
[ "def get_temporary_directory(path, ticket_id):\n return os.path.join(path, \"tmp\", ticket_id)", "def tmp_path():\n return {\"path\": \"/tmp\"}", "def tempdir():\n\n # Create a directory and return the path\n return tempfile.mkdtemp()", "def make_tmpfs_dir(path):\n if path in self._dir_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves this container with a registry authentication for a given address.
def with_registry_auth( self, address: str, username: str, secret: "Secret", ) -> "Container": _args = [ Arg("address", address), Arg("username", username), Arg("secret", secret), ] _ctx = self._select("withRegistryAuth", _a...
[ "def without_registry_auth(self, address: str) -> \"Container\":\n _args = [\n Arg(\"address\", address),\n ]\n _ctx = self._select(\"withoutRegistryAuth\", _args)\n return Container(_ctx)", "def get(registry_url, path, **kwargs):\n url = registry_url + path\n response...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Establish a runtime dependency on a service. The service will be started automatically when needed and detached when it is no longer needed, executing the default command if none is set. The service will be reachable from the container via the provided hostname alias. The service dependency will also convey to any file...
def with_service_binding(self, alias: str, service: "Container") -> "Container": _args = [ Arg("alias", alias), Arg("service", service), ] _ctx = self._select("withServiceBinding", _args) return Container(_ctx)
[ "def start_service(self):\n logger = logging.getLogger(self.dkr_name)\n logger.info(\"Starting up service\")\n\n self.start_swarm()\n\n container_spec = docker.types.ContainerSpec(\n image=self.dkr_image,\n command=self.dkr_command,\n env=self.dkr_env\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves this container plus a socket forwarded to the given Unix socket path.
def with_unix_socket( self, path: str, source: "Socket", owner: Optional[str] = None, ) -> "Container": _args = [ Arg("path", path), Arg("source", source), Arg("owner", owner, None), ] _ctx = self._select("withUnixSocket", _...
[ "def unix_socket(self, path: str) -> \"Socket\":\n _args = [\n Arg(\"path\", path),\n ]\n _ctx = self._select(\"unixSocket\", _args)\n return Socket(_ctx)", "def get_socket_path(self):\n\n return self._socket_path", "def get_socket_path():\r\n cmd = ['i3', '--get-soc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves this container minus the given environment variable.
def without_env_variable(self, name: str) -> "Container": _args = [ Arg("name", name), ] _ctx = self._select("withoutEnvVariable", _args) return Container(_ctx)
[ "def remove_from_environment_variable(self, key, value):\n script = (\"$env:{k} = python -c \\\"\"\n \"print(';'.join(r'$env:{k}'.split(';')\"\n \"[:r'$env:{k}'.split(r';').index(r'{v}')] + \"\n \"r'$env:{k}'.split(';')\"\n \"[r'$env:{k}'.sp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unexpose a previously exposed port. Currently experimental; set _EXPERIMENTAL_DAGGER_SERVICES_DNS=0 to disable.
def without_exposed_port( self, port: int, protocol: Optional[NetworkProtocol] = None, ) -> "Container": _args = [ Arg("port", port), Arg("protocol", protocol, None), ] _ctx = self._select("withoutExposedPort", _args) return Container(_...
[ "def deregister_port(event):\n upnp.deleteportmapping(hass.config.api.port, 'TCP')", "def deconfigure_port(self):\n self.dyn_lacp_port_selected = LACP_PORT_NOTCONFIGURED", "def del_port(self, name):\n\n # check if port of this name is already available.\n port = self.find_port_by_nam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves this container minus the given environment label.
def without_label(self, name: str) -> "Container": _args = [ Arg("name", name), ] _ctx = self._select("withoutLabel", _args) return Container(_ctx)
[ "def without_env_variable(self, name: str) -> \"Container\":\n _args = [\n Arg(\"name\", name),\n ]\n _ctx = self._select(\"withoutEnvVariable\", _args)\n return Container(_ctx)", "def remove_label(self, ):\n if self.AttributeNames.LABEL in self.attrs:\n de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves this container after unmounting everything at the given path.
def without_mount(self, path: str) -> "Container": _args = [ Arg("path", path), ] _ctx = self._select("withoutMount", _args) return Container(_ctx)
[ "def unmount_path(path):\n r = util.subp(['umount', path])\n if r.return_code != 0:\n raise ValueError(r.stderr)", "def with_mounted_temp(self, path: str) -> \"Container\":\n _args = [\n Arg(\"path\", path),\n ]\n _ctx = self._select(\"withMountedTemp\", _a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves this container without the registry authentication of a given address.
def without_registry_auth(self, address: str) -> "Container": _args = [ Arg("address", address), ] _ctx = self._select("withoutRegistryAuth", _args) return Container(_ctx)
[ "def with_registry_auth(\n self,\n address: str,\n username: str,\n secret: \"Secret\",\n ) -> \"Container\":\n _args = [\n Arg(\"address\", address),\n Arg(\"username\", username),\n Arg(\"secret\", secret),\n ]\n _ctx = self._sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves this container with a previously added Unix socket removed.
def without_unix_socket(self, path: str) -> "Container": _args = [ Arg("path", path), ] _ctx = self._select("withoutUnixSocket", _args) return Container(_ctx)
[ "def remove_socket(self, socket_rem):\n clients_to_pop = []\n # Iterate through the dictionary to find the client to pop. Can't pop the clien during the\n # iteration because the dictionary size will change and you will get the error:\n # RuntimeError: dictionary changed size during iter...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the working directory for all commands. Returns Optional[str] The `String` scalar type represents textual data, represented as UTF8 character sequences. The String type is most often used by GraphQL to represent freeform humanreadable text. Raises ExecuteTimeoutError If the time to execute the query exceeds t...
def workdir(self) -> Optional[str]: _args: list[Arg] = [] _ctx = self._select("workdir", _args) return _ctx.execute_sync(Optional[str])
[ "def _getquery(self):\r\n if self.mode.lower() == \"query\":\r\n result = self._session.execute(\"folder -show query \\\"%s\\\"\" % self.objectname)\r\n return result.output.strip()\r\n else:\r\n raise CCMException(\"%s is not a query base folder.\" % (self.objectname)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the difference between this directory and an another directory.
def diff(self, other: "Directory") -> "Directory": _args = [ Arg("other", other), ] _ctx = self._select("diff", _args) return Directory(_ctx)
[ "def diff(self):\n return self.repository._client.diff('./tmp-', self.path)", "def diff(self, other):\n return self.distance(other)", "def extract_diff(self):\n\n if self.diff:\n target = self.path_1.split('\\\\')[1:-1] + ['Difference']\n path_1_miss = target + [\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves this directory with all file/dir timestamps set to the given time.
def with_timestamps(self, timestamp: int) -> "Directory": _args = [ Arg("timestamp", timestamp), ] _ctx = self._select("withTimestamps", _args) return Directory(_ctx)
[ "def utimens(self, path, times=None):\n\n if times:\n # atime = times[0]\n mtime = times[1]\n else:\n # atime = time()\n mtime = time()", "def extract_all_times(directory, subdirs=None):\n\ttimes = set()\n\tif not subdirs:\n\t\tfor dirpath, subdirs, files ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves this directory with the directory at the given path removed.
def without_directory(self, path: str) -> "Directory": _args = [ Arg("path", path), ] _ctx = self._select("withoutDirectory", _args) return Directory(_ctx)
[ "def remove(self, path):\n path = Path(path)\n if not path.is_relative:\n raise RuntimeError(\"Path must be relative to container.\")\n \n grandparent = None\n parent = self\n for dir_name in path.names[:-1]:\n grandparent = parent\n parent ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the contents of the file. Returns str The `String` scalar type represents textual data, represented as UTF8 character sequences. The String type is most often used by GraphQL to represent freeform humanreadable text. Raises ExecuteTimeoutError If the time to execute the query exceeds the configured timeout. Q...
def contents(self) -> str: _args: list[Arg] = [] _ctx = self._select("contents", _args) return _ctx.execute_sync(str)
[ "def _get_content(self, path, encoding=None):\n mode = 'rt' if encoding else 'rb'\n try:\n with open(path, mode, encoding=encoding) as fd:\n s = fd.read()\n except (OSError, IOError) as e:\n raise exc.FinderError(exc.ERROR_OPEN, e)\n return s", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the contentaddressed identifier of the file. Note This is lazyly evaluated, no operation is actually run. Returns FileID A file identifier. Raises ExecuteTimeoutError If the time to execute the query exceeds the configured timeout. QueryError If the API returns an error.
def id(self) -> FileID: _args: list[Arg] = [] _ctx = self._select("id", _args) return _ctx.execute_sync(FileID)
[ "def file_id(self) -> int:\n\t\treturn self._file_id", "def get_file_by_id(id):\n return my_query(construct_get_file_by_id(id))", "def getid(self):\n if self._file:\n return self._file\n else:\n import md5\n return md5.new(self._content).hexdigest()", "def _Ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves this file with its created/modified timestamps set to the given time.
def with_timestamps(self, timestamp: int) -> "File": _args = [ Arg("timestamp", timestamp), ] _ctx = self._select("withTimestamps", _args) return File(_ctx)
[ "def utimens(self, path, times=None):\n\n if times:\n # atime = times[0]\n mtime = times[1]\n else:\n # atime = time()\n mtime = time()", "def getModifiedTime(self):\n return os.stat(\"%s\" % self.file)[8]", "def _set_ts(self, path):\n # TO...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The digest of the current value of this ref. Returns str The `String` scalar type represents textual data, represented as UTF8 character sequences. The String type is most often used by GraphQL to represent freeform humanreadable text. Raises ExecuteTimeoutError If the time to execute the query exceeds the configured t...
def digest(self) -> str: _args: list[Arg] = [] _ctx = self._select("digest", _args) return _ctx.execute_sync(str)
[ "def string_digest(self) -> str:\n pass", "def digest(self):\n return self._parsed[\"digest\"]", "def digest(self):\n return self._hash", "def digest(self) -> Digest:\n return self.exe.digest", "def digest(self):\n # For discussion of big-endian vs little-endian for the ha...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Lists of branches on the repository. Returns list[str] The `String` scalar type represents textual data, represented as UTF8 character sequences. The String type is most often used by GraphQL to represent freeform humanreadable text. Raises ExecuteTimeoutError If the time to execute the query exceeds the configured tim...
def branches(self) -> list[str]: _args: list[Arg] = [] _ctx = self._select("branches", _args) return _ctx.execute_sync(list[str])
[ "def list_branches(self) -> List[str]:\n self.__verify_repo_initialized()\n branches = heads.get_branch_names(self._env.branchenv)\n return branches", "def branches() -> List[str]:\n out = shell.run(\n 'git branch',\n capture=True,\n never_pretend=True\n ).stdout.st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Lists of tags on the repository. Returns list[str] The `String` scalar type represents textual data, represented as UTF8 character sequences. The String type is most often used by GraphQL to represent freeform humanreadable text. Raises ExecuteTimeoutError If the time to execute the query exceeds the configured timeout...
def tags(self) -> list[str]: _args: list[Arg] = [] _ctx = self._select("tags", _args) return _ctx.execute_sync(list[str])
[ "def list_tags(self) -> List[str]:\n self._validate()\n\n cmd = \"git tag --list --sort v:refname\"\n cmd_params = cmd_exec.CommandParameters(cwd=self.get_source_directory())\n tag_output = cmd_exec.run_command(cmd, cmd_params)\n\n tag_list = [tag.strip() for tag in tag_output.split('\\n') if tag]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Accesses a Unix socket on the host.
def unix_socket(self, path: str) -> "Socket": _args = [ Arg("path", path), ] _ctx = self._select("unixSocket", _args) return Socket(_ctx)
[ "def unix_sock(self):\n return self._unix_sock", "def unix_socket_in_use(socket_path):\n if not os.path.exists(socket_path):\n return False\n\n try:\n sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n sock.connect(socket_path)\n except OSError:\n return False\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The port number. Returns int The `Int` scalar type represents nonfractional signed whole numeric values. Int can represent values between (2^31) and 2^31 1. Raises ExecuteTimeoutError If the time to execute the query exceeds the configured timeout. QueryError If the API returns an error.
def port(self) -> int: if hasattr(self, "_port"): return self._port _args: list[Arg] = [] _ctx = self._select("port", _args) return _ctx.execute_sync(int)
[ "def Port(self) -> int:", "def get_port_number(self):\n return self.port", "def port(self):\n try:\n return int(self.server_properties['server-port'])\n except (ValueError, KeyError):\n ''' KeyError: server-port option does not exist\n ValueError: value ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The transport layer network protocol. Returns NetworkProtocol Transport layer network protocol associated to a port. Raises ExecuteTimeoutError If the time to execute the query exceeds the configured timeout. QueryError If the API returns an error.
def protocol(self) -> NetworkProtocol: if hasattr(self, "_protocol"): return self._protocol _args: list[Arg] = [] _ctx = self._select("protocol", _args) return _ctx.execute_sync(NetworkProtocol)
[ "def network_protocol(self):\n return self._network_protocol", "def transport_protocol(self) -> pulumi.Input['ConfigTransportProtocol']:\n return pulumi.get(self, \"transport_protocol\")", "def thrift_transport_protocol(self) -> Optional[str]:\n return pulumi.get(self, \"thrift_transport_pr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A unique identifier for this command. Note This is lazyly evaluated, no operation is actually run. Returns ProjectCommandID A unique project command identifier. Raises ExecuteTimeoutError If the time to execute the query exceeds the configured timeout. QueryError If the API returns an error.
def id(self) -> ProjectCommandID: _args: list[Arg] = [] _ctx = self._select("id", _args) return _ctx.execute_sync(ProjectCommandID)
[ "def project_command(\n self,\n id: Optional[ProjectCommandID] = None,\n ) -> ProjectCommand:\n _args = [\n Arg(\"id\", id, None),\n ]\n _ctx = self._select(\"projectCommand\", _args)\n return ProjectCommand(_ctx)", "def project_id(self) -> str:\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a cache volume for a given cache key.
def cache_volume(self, key: str) -> CacheVolume: _args = [ Arg("key", key), ] _ctx = self._select("cacheVolume", _args) return CacheVolume(_ctx)
[ "def _create_cache_volume(self, context, img_meta,\n img_service, cachevol_props):\n lcfg = self.configuration\n cache_dir = '%s/' % lcfg.zfssa_cache_directory\n cache_vol = Volume()\n cache_vol.provider_location = self.mount_path\n cache_vol._name_id =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads a container from ID. Null ID returns an empty container (scratch). Optional platform argument initializes new containers to execute and publish as that platform. Platform defaults to that of the builder's host.
def container( self, id: Optional[ContainerID] = None, platform: Optional[Platform] = None, ) -> Container: _args = [ Arg("id", id, None), Arg("platform", platform, None), ] _ctx = self._select("container", _args) return Container(_ctx)
[ "def container_by_id(self, id):\n if not id:\n return None\n return next((container for container in self.containers(all=True)\n if container['Id'] == id), None)", "def _create_pilot_container(self, job_id: int) -> Container:\n image_file = Path(__file__).parent...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The default platform of the builder. Returns Platform The platform config OS and architecture in a Container. The format is [os]/[platform]/[version] (e.g., "darwin/arm64/v7", "windows/amd64", "linux/arm64"). Raises ExecuteTimeoutError If the time to execute the query exceeds the configured timeout. QueryError If the A...
def default_platform(self) -> Platform: _args: list[Arg] = [] _ctx = self._select("defaultPlatform", _args) return _ctx.execute_sync(Platform)
[ "def platform(self) -> Platform:\n _args: list[Arg] = []\n _ctx = self._select(\"platform\", _args)\n return _ctx.execute_sync(Platform)", "def platform(self) -> Optional[pulumi.Input['DockerImagePlatformArgs']]:\n return pulumi.get(self, \"platform\")", "def Platform(self):\n if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load a directory by ID. No argument produces an empty directory.
def directory(self, id: Optional[DirectoryID] = None) -> Directory: _args = [ Arg("id", id, None), ] _ctx = self._select("directory", _args) return Directory(_ctx)
[ "def get_directory_from_id(self, a_id, a_local_dir = None):\r\n filename = '%s.meta' % (a_id)\r\n \r\n #local_dir can be passed to avoid scanning the filesystem (because of WIN7 fs weaknesses)\r\n if a_local_dir:\r\n the_dir = '%s/%s' % (self._db_dir, a_local_dir)\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load a project command from ID.
def project_command( self, id: Optional[ProjectCommandID] = None, ) -> ProjectCommand: _args = [ Arg("id", id, None), ] _ctx = self._select("projectCommand", _args) return ProjectCommand(_ctx)
[ "def get_command(self, run_id: str, command_id: str) -> Command:\n select_run_commands = sqlalchemy.select(run_table.c.commands).where(\n run_table.c.id == run_id\n )\n with self._sql_engine.begin() as transaction:\n try:\n row = transaction.execute(select_r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads a secret from its ID.
def secret(self, id: SecretID) -> "Secret": _args = [ Arg("id", id), ] _ctx = self._select("secret", _args) return Secret(_ctx)
[ "def lookup_secret_by_id(self, id):\n\n endpoint = \"/secrets/lookup/{}\".format(id)\n return self._internal_call(\"GET\", self._geturl(endpoint))", "def get_secret(self, id):\n\n endpoint = \"/secrets/{}\".format(id)\n return self._internal_call(\"GET\", self._geturl(endpoint))", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets a secret given a user defined name to its plaintext and returns the secret. The plaintext value is limited to a size of 128000 bytes.
def set_secret(self, name: str, plaintext: str) -> "Secret": _args = [ Arg("name", name), Arg("plaintext", plaintext), ] _ctx = self._select("setSecret", _args) return Secret(_ctx)
[ "def new_text_secret(self, secret_name, content):\n with self.__client as client:\n return self.__exec_cmd(client, Command.NEW_TEXT_SECRET, secret_name, content)", "def run(self, name: str = None):\n if name is None:\n name = self.secret_name\n if name is None:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads a socket by its ID.
def socket(self, id: Optional[SocketID] = None) -> "Socket": _args = [ Arg("id", id, None), ] _ctx = self._select("socket", _args) return Socket(_ctx)
[ "def check_id(_id):\n try:\n with open(\"sockets.json\", \"r\") as sock:\n js = json.loads(sock.read())\n if _id in js:\n port = js[_id]\n return port\n except:\n return False", "def socket_id(self, socket_id):\n if self.local_vars_configu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The identifier for this secret. Note This is lazyly evaluated, no operation is actually run. Returns SecretID A unique identifier for a secret. Raises ExecuteTimeoutError If the time to execute the query exceeds the configured timeout. QueryError If the API returns an error.
def id(self) -> SecretID: _args: list[Arg] = [] _ctx = self._select("id", _args) return _ctx.execute_sync(SecretID)
[ "def secret_id(self):\n if self._secret_id:\n return self._secret_id\n return self.device_id", "def query_id(self) -> str:\n return pulumi.get(self, \"query_id\")", "def query_id(self) -> Optional[str]:\n return pulumi.get(self, \"query_id\")", "def get_secret_id_from_se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The contentaddressed identifier of the socket. Note This is lazyly evaluated, no operation is actually run. Returns SocketID A contentaddressed socket identifier. Raises ExecuteTimeoutError If the time to execute the query exceeds the configured timeout. QueryError If the API returns an error.
def id(self) -> SocketID: _args: list[Arg] = [] _ctx = self._select("id", _args) return _ctx.execute_sync(SocketID)
[ "def connection_id(self) -> str:\n return self._id", "def host_id(self):\n return self._host_id", "def select_instant_messaging_id(self, cnx, im_name, logger=None):\n found = None\n cursor = cnx.cursor()\n query = \"SELECT id \" \\\n \"FROM instant_messaging \" ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recursive generator to traverse through the next attribute and \ crawl through the links to be followed
def traverse_next(page, next, results): for link in page.extract_links(next['follow_link']): print(Back.YELLOW + Fore.BLUE + "Loading page ", link.url + Back.RESET + Fore.RESET) r = results.copy() for attribute in next['scraping'].get('data'): if attribute['field'] != "": ...
[ "def extract_linked_items(pages):\n for page in pages:\n for iterate in iterate_on_items(page):\n yield((iterate[1:])[:-1])", "def parse_link(self, response):\n try:\n self.logger1.info(\n \"Start to parse page {} the detail link of {}\".format(response.meta.g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the case with the given id.
def get_case( case_id: str, db: Session = Depends(get_db), ) -> Any: case_and_site = crud.case.get_case_with_site(db, id=case_id) if not case_and_site: return None (case, site) = case_and_site return schemas.CaseWithTaskInfo.get_case_with_task_info(case, site)
[ "def case(self, case_id=None):\n cases = self.cases()\n if case_id:\n for case in cases:\n if case.case_id == case_id:\n return case\n else:\n if cases:\n return cases[0]\n\n return None", "def get_case(self, key: s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new case with the given parameters.
def create_case( case_attrs: schemas.CaseBase = Body(...), data_file: UploadFile | None = None, db: Session = Depends(get_db), ) -> Any: case = crud.case.create(db, obj_in=case_attrs, data_file=data_file) case_with_site = crud.case.get_case_with_site(db, id=case.id) if not case_with_site: ...
[ "def _build_case(self, **data):\n return TestCase(self.connection, plan_id = self.plan_id, **data)", "def create(self, data):\n\t\tassert isinstance(data, dict), 'The data type must be a dictionary'\n\t\tassert data, 'Case data must not be an empty dictionary'\n\n\t\turl = f'{self.root.url}/api/v1.2/cases'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete the case with the given id.
def delete_case( case_id: str, db: Session = Depends(get_db), ) -> Any: return crud.case.remove(db, id=case_id)
[ "def delete_case(self, case):\n mongo_case = self.case(case)\n \n if mongo_case:\n logger.info(\"Removing case {0} from database\".format(\n mongo_case.get('case_id')\n ))\n self.db.case.remove({'_id': mongo_case['_id']})\n else:\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Download a compressed tarball of the case with the given id.
def download_case(case_id: str, db: Session = Depends(get_db)) -> Any: case_and_site = crud.case.get_case_with_site(db, id=case_id) if not case_and_site: return None (case, site) = case_and_site case_folder_name = case.env["CASE_FOLDER_NAME"] archive_name = settings.ARCHIVES_ROOT / f"{ca...
[ "def download_result_archive(run_id):\n from robflask.service import service\n with service() as api:\n ioBuffer = api.runs().get_result_archive(run_id=run_id)\n return send_file(\n ioBuffer.open(),\n as_attachment=True,\n attachment_filename='run.tar.gz',\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Provides a list of all installed screens with various options.
def list_screens(self): # Check if the form ws submitted form = request.forms.get("submit", False) # If so... if form: # ...find out what the user wanted to do and to which screen action, screen = form.split("+") # Call the relevant action ...
[ "def getScreenList(self, verbose = False):\n return execCmd(\"%s -list\" % self._screenPath, verbose)", "def list_screens():\n list_cmd = \"screen -ls\"\n return [\n Screen(\".\".join(l.split(\".\")[1:]).split(\"\\t\")[0])\n for l in getoutput(list_cmd).split('\\n')\n if \"\\t\" ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if giving no arguments to func raises TypeError
def check_if_giving_no_args_to_func_raises_type_error(self): self.assertRaises(TypeError, add_expressions()()) self.assertRaises(TypeError, add_expressions(1, 2, 3)()) self.assertRaises(TypeError, add_expressions()(1, 2, 3))
[ "def test_atomic_TypeErrors(func, argument):\n with pytest.raises(TypeError):\n func(argument)", "def arguments_not_none(func):\n def wrapper(*args, **kwargs):\n for arg in args:\n if arg is None:\n raise NullArgument()\n for arg, val in kwargs.iteritems():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if keys and values from result dict are int type
def test_if_keys_or_values_in_result_dict_are_int(self): for key, value in add_expressions(1, 2, 8)(2, 3).items(): self.assertIsInstance(key, int) self.assertIsInstance(value, int)
[ "def dict_keys_to_int(dict):\n try:\n converted = {int(key): value for key, value in dict}\n except Exception as e:\n return dict\n return converted", "def test_dict_keys_int_range_valid_i64(self):\n assert (\n orjson.dumps(\n {9223372036854775807: True},\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute indexes for communities on a lattice e.g. A A A B B B A A A B B B A A A B B B C C C D D D C C C D D D C C C D D D community_side = 3 community_size = 33 = 9 communities_per_side = 2 num_communities = 4 tot nodes = 49
def make_communities(community_side, communities_per_side): community_size = community_side * community_side communities = [] seed_node = 0 for i in range(communities_per_side): for j in range(communities_per_side): community = [] for k in range(community_side): ...
[ "def find_overlapping_nodes( communities ):\n\tcommunity_counts = defaultdict(int)\t\n\tfor comm in communities:\n\t\tfor node_index in comm:\n\t\t\tcommunity_counts[node_index] += 1\n\toverlapping_nodes = set()\n\tfor node_index in community_counts:\n\t\tif community_counts[node_index] > 1:\n\t\t\toverlapping_node...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates and returns the frame for time t.
def make_frame(t): mlab.view(360*t/duration, 90) # camera angle return mlab.screenshot(antialiased=True) # return a RGB image
[ "def make_frame(t):\r\n while world['t'] < hours_per_second*t:\r\n update(world)\r\n return world_to_npimage(world)", "def make_frame(t):\n y = np.sin(3 * u) * (0.2 + 0.5 * np.cos(2 * np.pi * t / duration))\n l.mlab_source.set(y=y) # change y-coordinates of the mesh\n mlab.view(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
two parameter mlp test nn n.b. by default tf and np add 1d arrays and row vectors to matrices rowwise, but column vectors columnwise
def mlp_test(a0, weights): a1 = tf.tanh(tf.matmul(a0, weights[0])) prediction = tf.reduce_sum(a1, axis = 1, keepdims = True) return prediction
[ "def test_parametrized_mul(self, param_backend):\n variable_lin_op = linOpHelper((2, 2), type='variable', data=1)\n param_backend.param_to_size = {-1: 1, 2: 4}\n param_backend.param_to_col = {2: 0, -1: 4}\n param_backend.param_size_plus_one = 5\n param_backend.var_length = 4\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
It creates N list of files based on filesize to average the size between lists.
def dispatch_files_bysize(nb_list, files): logging.info('Having {} files to dispatch in {} lists'.format(len(files), nb_list)) # # 1 - Init N lists of size 0. # sublists = {} for list_id in range(0,nb_list): sublists[list_id] = { 'files' : [], 'size' :...
[ "def largest_files(n):\n file_sizes = []\n for root, dirs, files in os.walk(\".\"):\n for name in files:\n file_sizes.append([getsize(join(root, name)), join(root, name)])\n file_sizes = sorted(file_sizes, key = lambda tup: tup[0], reverse = True)\n big_files = []\n for i in range(n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the smallest sublist
def _get_smallest_sublist(sublists): smallest_list_id = 0 for list_id, sublist in sublists.items(): if sublist['size'] < sublists[smallest_list_id]['size']: smallest_list_id = list_id return smallest_list_id
[ "def get_shortest_list(list_of_lists):\n return min(list_of_lists, key=len)", "def minimum(list):\n\n\treturn min(list)", "def recursive_min(nested_num_list):\n smallest = nested_num_list[0]\n while type(smallest) == type([]):\n smallest = smallest[0]\n\n for element in nested_num_list:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assert the correctness of the v1 prime number calculation algorithm using the list of prime booleans
def test_v1_correct(self): for index, expected_result in enumerate(self.prime_booleans): n = index + 1 self.assertEqual(prime_numbers_v1(n), expected_result)
[ "def test_v2_correct(self):\r\n\r\n for index, expected_result in enumerate(self.prime_booleans):\r\n\r\n n = index + 1\r\n self.assertEqual(prime_numbers_v2(n), expected_result)", "def test_v3_correct(self):\r\n\r\n for index, expected_result in enumerate(self.prime_booleans):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assert the correctness of the v2 prime number calculation algorithm using the list of prime booleans
def test_v2_correct(self): for index, expected_result in enumerate(self.prime_booleans): n = index + 1 self.assertEqual(prime_numbers_v2(n), expected_result)
[ "def test_v1_correct(self):\r\n\r\n for index, expected_result in enumerate(self.prime_booleans):\r\n\r\n n = index + 1\r\n self.assertEqual(prime_numbers_v1(n), expected_result)", "def test_v3_correct(self):\r\n\r\n for index, expected_result in enumerate(self.prime_booleans):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assert the correctness of the v3 prime number calculation algorithm using the list of prime booleans
def test_v3_correct(self): for index, expected_result in enumerate(self.prime_booleans): n = index + 1 self.assertEqual(prime_numbers_v3(n), expected_result)
[ "def test_v2_correct(self):\r\n\r\n for index, expected_result in enumerate(self.prime_booleans):\r\n\r\n n = index + 1\r\n self.assertEqual(prime_numbers_v2(n), expected_result)", "def test_v1_correct(self):\r\n\r\n for index, expected_result in enumerate(self.prime_booleans):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests how much time it takes for v1 to calculate if the numbers 1 through 30000 are primes. The results are not saved, as this is only a test of the performance of the algorithm. Print the time required for the calculations in seconds.
def test_v1_runtime(self): start_time = time.time() for n in range(1, 30000): prime_numbers_v1(n) elapsed_time = round(time.time() - start_time, 3) print(f"v1, time required: {elapsed_time}")
[ "def test_v2_runtime(self):\r\n\r\n start_time = time.time()\r\n\r\n for n in range(1, 30000):\r\n prime_numbers_v2(n)\r\n\r\n elapsed_time = round(time.time() - start_time, 3)\r\n\r\n print(f\"v2, time required: {elapsed_time}\")", "def test_primes_under_1000000(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests how much time it takes for v1 to calculate if the numbers 1 through 30000 are primes. The results are not saved, as this is only a test of the performance of the algorithm. Print the time required for the calculations in seconds.
def test_v2_runtime(self): start_time = time.time() for n in range(1, 30000): prime_numbers_v2(n) elapsed_time = round(time.time() - start_time, 3) print(f"v2, time required: {elapsed_time}")
[ "def test_v1_runtime(self):\r\n\r\n start_time = time.time()\r\n\r\n for n in range(1, 30000):\r\n prime_numbers_v1(n)\r\n\r\n elapsed_time = round(time.time() - start_time, 3)\r\n\r\n print(f\"v1, time required: {elapsed_time}\")", "def test_primes_under_1000000(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enhanced version of fnmatch.filter() that accepts multiple inclusion and exclusion patterns. If only inclusion_patterns is specified, only the names which match one or more patterns are returned. If only exclusion_patterns is specified, only the names which do not match any pattern are returned. If both are specified, ...
def superfilter(names, inclusion_patterns=(), exclusion_patterns=()): is_mapping = isinstance(names, collections.Mapping) keys = names.iterkeys() if is_mapping else names included = multifilter(keys, inclusion_patterns) if inclusion_patterns else keys excluded = multifilter(keys, exclusion_patterns) if ...
[ "def _make_include_filter(patterns):\n # Trivial case: exclude everything\n if not patterns:\n def _filter(names):\n return names[0:0]\n\n return _filter\n # Use fnmatch.filter if it's applicable\n if len(patterns) == 1:\n def _filter(names):\n return fnmatch.f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines whether key is in collection. If collection is a mapping type, recursively checks for key inclusion
def key_is_in_collection(key, collection): if isinstance(key, collections.Mapping): for subkey in key.iterkeys(): if key_is_in_collection(subkey, collection): return True return False else: return key in collection
[ "def contains(collection, target):\n\treturn target in collection", "def collection_should_contain(collection, *members):\n if not isinstance(collection, collections.Iterable):\n return False\n for m in members:\n if m not in collection:\n return False\n else:\n return Tru...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generator function which yields the names that match one or more of the patterns.
def multifilter(names, patterns): for name in names: if isinstance(name, collections.Mapping): for key in name.iterkeys(): for pattern in patterns: if fnmatch.fnmatch(key, pattern): yield key break else: ...
[ "def find_matching(cls, path, patterns):\n for pattern in patterns:\n if pattern.match(path):\n yield pattern", "def pattern_filter(patterns, name):\n return [pat for pat in patterns if fnmatch.fnmatchcase(name, pat)]", "def match(self, pattern):\n import fnmatch\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Do a batched gather on a 3D tensor.
def batch_gather_3d(values, indices): return tf.gather(tf.reshape(values, [-1, tf.shape(values)[2]]), tf.range(0, tf.shape(values)[0]) * tf.shape(values)[1] + indices)
[ "def _gather_3d(params, indices, name=None):\n batch_size = tf.shape(params)[0]\n grid_size = tf.shape(params)[1]\n\n # range_size = tf.shape(indices)[2]\n\n params = _merge_first_two_dims(params)\n indices = _merge_first_two_dims(indices)\n\n output = _gather_2d(params, indices, name)\n output...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Do a batched gather on a 2D tensor.
def batch_gather_2d(values, indices): return tf.gather(tf.reshape(values, [-1]), tf.range(0, tf.shape(values)[0]) * tf.shape(values)[1] + indices)
[ "def batchwise_gather(tensor, idxs, batch_dim=None):\n batch_size = shape(tensor)[batch_dim]\n \n batch_idxs = np.asarray(range(batch_size))\n if batch_dim == 0:\n gather_idxs = tf.stack([batch_idxs, idxs], axis=-1)\n elif batch_dim == 1:\n gather_idxs = tf.stack([idxs, batch_idxs], axis=-1)\n return tf...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initial test to ensure five studies are listed with no filter
def test_list_all_dx(self): self.client.login(username='temporary', password='temporary') response = self.client.get(reverse('dx_summary_list_filter'), follow=True) self.assertEqual(response.status_code, 200) responses_text = u'There are 5 studies in this list.' self.assertContai...
[ "def test_returns_all_studies_with_no_query(self):\n url = self.get_url()\n response = self.client.get(url)\n pks = get_autocomplete_view_ids(response)\n self.assertEqual(sorted([study.pk for study in self.studies]), sorted(pks))", "def test_all_by_study(self):\n pass", "def t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply study description filter
def test_filter_study_desc(self): self.client.login(username='temporary', password='temporary') response = self.client.get(reverse_lazy('dx_summary_list_filter') + '?study_description=CR', follow=True) self.assertEqual(response.status_code, 200) one_responses_text = u'There are 2 studies...
[ "def test_filter_include_study_description(self):\n from remapp.netdicom.qrscu import _filter\n\n query = DicomQuery.objects.get()\n _filter(query, u\"study\", u\"study_description\", [u\"test\", ], u\"include\")\n\n self.assertEqual(query.dicomqrrspstudy_set.all().count(), 2)\n s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the parent directory of this file. This makes it so the app will work, (and the db will be found) no matter the current working directory.
def getParentDirectory(): path = os.path.dirname(os.path.realpath(__file__)) path = '/'.join( path.split('/')[:-1] ) return path
[ "def get_parent_path(self):\n return os.path.abspath(os.path.join(self.current_path, os.pardir))", "def parent_dir(current_dir):\n return os.path.abspath(os.path.join(current_dir, os.pardir))", "def parent_directory():\n current_directory = os.getcwd()\n os.chdir(\"..\")\n relative_path = os....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the two sequences to be compared. >>> s = SequenceMatcher() >>> s.set_seqs("abcd", "bcde") >>> s.ratio() 0.75
def set_seqs(self, a, b): self.set_seq1(a) self.set_seq2(b)
[ "def _match(a, b):\n return SequenceMatcher(None, a, b).ratio()", "def stringSimilar(s1, s2):\n return SequenceMatcher(None, s1, s2).ratio()", "def testSeqs(self, mock_gs):\n self.mr._sequences = ['apple', 'banana']\n\n self.assertEqual(\n ['apple', 'banana'],\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the View from the path to help build the list of safe views.
def _get_view(self, view_path): right_most_dot = view_path.rfind('.') module_path, view_name = ( view_path[:right_most_dot], view_path[right_most_dot + 1:]) module = __import__(module_path, globals(), locals(), [view_name]) return getattr(module, view_name)
[ "def _get_view_and_args(path, request):\n # Let's use urlconf from request object, if available:\n urlconf = getattr(request, \"urlconf\", settings.ROOT_URLCONF)\n resolver = RegexURLResolver(r\"^/\", urlconf)\n return resolver.resolve(path)", "def view_paths():\n\treturn [os.path.join(os.path.dirname...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a mask with specified bit ranges set. An integer mask is generated based on the bits and bit ranges specified by the arguments. Any number of arguments can be provided. Each argument may be either a 2tuple of integers, a list of integers, or an individual integer. The result is the combination of masks produced...
def bitmask(*args: Union[int, Sequence[int], Tuple[int, int]]) -> int: mask = 0 for a in args: if isinstance(a, tuple): hi, lo = a mask |= ((1 << (hi - lo + 1)) - 1) << lo elif isinstance(a, (list, set)): mask |= reduce(operator.or_, ((1 << b) for b in a)) ...
[ "def create_instruction(arguments):\n masks = [argument << shift for argument, shift in arguments]\n return reduce(lambda integer, mask: integer | mask, masks)", "def combine(masks: Sequence[int], bits: Iterable[Any]) -> int:\n value = 0\n\n for bit, mask in zip(bits, masks):\n if bit:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the bitwise inverted value of the argument given a specified width. value Integer value to be inverted. width Bit width of both the input and output. If not supplied, this defaults to 32. Integer of the bitwise inversion of value.
def bit_invert(value: int, width: int = 32) -> int: return ((1 << width) - 1) & (~value)
[ "def invert(x, out=None, **kwargs):\n return _unary_func_helper(x, _npi.bitwise_not, _np.bitwise_not, out=out, **kwargs)", "def swap32(value: int) -> int:\n return swap(value, 32)", "def a_inv(self):\n return Word(int.__sub__((1 << 16), self) % (1 << 16))", "def __invert__(self):\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Modified the bitfield in a register value. self The Bitfield object. register_value Integer register value. field_value New value for the bitfield. Must not be shifted into place already. Integer register value with the bitfield updated to `field_value`.
def set(self, register_value: int, field_value: int) -> int: return bfi(register_value, self._msb, self._lsb, field_value)
[ "def set_register(self, register, value):\n if not Vm.is_register(register):\n raise ValueError(\"Expected register value, instead got: \" + str(register))\n\n self.registers[(register - REGISTER_0)] = value", "def set_bit_field_value(self, name, value):\n eval(\"self.\" + str(name...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test whether two sequences contain the same values. Unlike a simple equality comparison, this function works as expected when the two sequences are of different types, such as a list and bytearray. The sequences must return compatible types from indexing.
def same(d1: Sequence[Any], d2: Sequence[Any]) -> bool: if len(d1) != len(d2): return False for i in range(len(d1)): if d1[i] != d2[i]: return False return True
[ "def sequence_equals(sequence1, sequence2):\n return sequence1 == sequence2", "def equal (a, b):\n assert is_iterable(a)\n assert is_iterable(b)\n return contains (a, b) and contains (b, a)", "def __eq__(self, other):\n\n if not isinstance(other, LUTSequence):\n return False\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return value aligned down to multiple.
def align_down(value: int, multiple: int) -> int: return value // multiple * multiple
[ "def align_up(value: int, multiple: int) -> int:\n return (value + multiple - 1) // multiple * multiple", "def align_value(value, factor):\n return (value + factor - 1) // factor*factor", "def align(val):\n ovr = val % ALIGNMENT\n if (ovr):\n val = val + ALIGNMENT - ovr\n return val", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return value aligned up to multiple.
def align_up(value: int, multiple: int) -> int: return (value + multiple - 1) // multiple * multiple
[ "def align_down(value: int, multiple: int) -> int:\n return value // multiple * multiple", "def align(val):\n ovr = val % ALIGNMENT\n if (ovr):\n val = val + ALIGNMENT - ovr\n return val", "def align_value(value, factor):\n return (value + factor - 1) // factor*factor", "def align_down(a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return value divided by the divisor, rounding up to the nearest multiple of the divisor.
def round_up_div(value: int, divisor: int) -> int: return (value + divisor - 1) // divisor
[ "def round_to_multiple_of(val, divisor):\n new_val = max(divisor, int(val + divisor / 2) // divisor * divisor)\n return new_val if new_val >= val else new_val + divisor", "def _round_to_multiple_of(val, divisor, round_up_bias=0.9):\n assert 0.0 < round_up_bias < 1.0\n new_val = max(divisor, int(val + ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute parity over a 32bit value. This function is intended to be used for computing parity over a 32bit value transferred in an Arm ADI AP/DP register transfer. The result is returned in bit 32, ready to be OR'd into the register value to form the 33bit data + parity for the AP/DP register transfer. n 32bit integer. ...
def parity32_high(n: int) -> int: n ^= n >> 16 n ^= n >> 8 n ^= n >> 4 n &= 0xf return (0xD32C0000 << n) & (1 << 32)
[ "def parity_odd(x):\r\n\t\t\tx = x ^ (x >> 4)\r\n\t\t\tx = x ^ (x >> 2)\r\n\t\t\tx = x ^ (x >> 1)\r\n\t\t\treturn x & 1", "def parity(n):\n if n%2==0:\n p=1\n else:\n p=-1\n return p", "def parity(it):\n \n return sum(it)%2", "def parity64(x):\n\n x ^= x >> 32\n x ^= x >> 16\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test fib_digits returns correct integer pairs.
def test_fib_digits(n, result): from even_digit_primes import f assert f(n) == result
[ "def test_fibonacci_fourty(self):\n self.assertEqual(sequences.fibonacci(40), 102334155)", "def test_fibonacci_twenty(self):\n self.assertEqual(sequences.fibonacci(20), 6765)", "def test_fibonacci_100(self):\n self.assertEqual(sequences.fibonacci(100), 354224848179261915075)", "def test_f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Download and install "miniconda".
def conda_install(): require('MINICONDA_NAME') require('MINICONDA_FILE') with cd(utils.home()): if not files.exists(env.MINICONDA_NAME): # Download the miniconda installer. run('wget {0}'.format(env.MINICONDA_FILE)) # Give permission to execute installer. ru...
[ "def install_miniconda(self):\n install_url = (\"https://repo.continuum.io/miniconda/\"\n \"Miniconda3-{}-Linux-x86_64.sh\"\n \"\".format(self.miniconda_verion))\n if self.check_urls:\n check_url(install_url)\n\n workdir_cmd = \"WORKDIR /op...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List all conda virtual environments.
def conda_list_environments(): conda = '{0}/bin/conda'.format(utils.home('apps', 'miniconda')) run('{conda} info --envs'.format(conda=conda))
[ "def get_list_conda_envs():\r\n global CONDA_ENV_LIST_CACHE\r\n\r\n env_list = {}\r\n conda = find_conda()\r\n if conda is None:\r\n return env_list\r\n\r\n cmdstr = ' '.join([conda, 'env', 'list', '--json'])\r\n try:\r\n out, __ = run_shell_command(cmdstr, env={}).communicate()\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Places a vehicle modeled as a box as 8 points in the world coordinate system about a position and orientation in degrees
def place_vehicle_box(position, heading_from_x_axis, length=5.0, width=2.0, height=2.0): quat = helper.quat_from_rpy(0.0, 0.0, heading_from_x_axis) # define 8 points as points of the rectangular prism l, w, h = length/2.0, width/2.0, height base_points = np.array([[-l, -w, 0], [-l, w, 0], [l, w, 0...
[ "def draw_box(self) -> None:\n from math import pi, sin, cos\n import pymol\n from pymol import cmd\n\n # Convert angle\n angle1 = (self.angle1.value() / 180.0) * pi\n angle2 = (self.angle2.value() / 180.0) * pi\n\n # Get positions of box vertices\n # P1\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes an instantiated camera, its definition, and vehicle grid placement parameters and generates world center and orientation of a vehicle
def camera_grid_generator(camera, vehicle_params): start_x, start_y = 0.0, 0.0 end_x, end_y = camera.R_x, camera.R_y step_x, step_y = end_x/vehicle_params["x_pixel_steps_per_line"], end_y/vehicle_params["y_pixel_steps_per_line"] start_heading = 0.0 orientation_step = vehicle_params["orientation_step...
[ "def rotate_vector(u_east, v_north, lons, lon_displacement):\n # Current values in the file are stored as east-north components.\n # We need to read these and rotate into model currents.\n nx, ny = u_east.shape\n # Angle by which we need to rotate currents to get the oriented with the model grid.\n p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check module clock against computer clock Print metadata summary
def meta_summary(self, compclock, tolerance, prefix=0): dtdelta = (compclock - self.dumpdt).total_seconds() dtdays = int(abs(dtdelta) / 86400) dthours = int((abs(dtdelta) - (dtdays * 86400)) / 3600) dtmins = int((abs(dtdelta) - (dtdays * 86400) - (dthours * 3600)) / 60) dtsecs = ...
[ "def assert_clock_sync(self):\n log.error(\"====== Sung ====== assert_clock_sync\")\n dt = self.assert_get(WorkhorseParameter.TIME)\n lt = time.strftime(\"%Y/%m/%d,%H:%M:%S\", time.gmtime(time.mktime(time.localtime())))\n self.assertTrue(lt[:13].upper() in dt.upper())", "def test_clock...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make an initial comparison of local system time with NTP server
def check_ntp_server(ntpserv): ntpcheck = "\n--- Network Time Server Check ---\n" ntpoffset = 0.0 try: client = ntplib.NTPClient() response = client.request(ntpserv) ntpoffset = response.offset if ntpoffset < 0: ntpcheck += "*** localhost system clock is {:.2f} s...
[ "def updateRTCFromNTP(strip, start = False):\r\n wifi = connectToWifi(strip, start)\r\n try:\r\n ntptime.settime()\r\n except OSError:\r\n for i in range(0, 3):\r\n ledFlash(strip, LED_COLOR_RED, 0.5)\r\n print(\"Can not connect to NTP server\")\r\n machine.reset()\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show a list of ports and ask the user for a choice. To make selection easier on systems with long device names, also allow the input of an index.
def ask_for_port(): sys.stderr.write("\n--- Available ports:\n\n") ports = [] # for n, (port, desc, hwid) in enumerate(sorted(comports()), 1): for n, (port, desc, hwid) in enumerate( sorted(serial.tools.list_ports.grep(r"usb")), 1 ): # sys.stderr.write(' {:2}: {:20}\n\n'.format(n, po...
[ "def ask_for_port():\n sys.stderr.write('\\nAvailable ports: <index:> <name> <desc> <hwid>\\n')\n ports = []\n for n, (port, desc, hwid) in enumerate(sorted(comports()), 1):\n sys.stderr.write('{:2}: {:40} {!r} {!r}\\n'.format(n, port, desc, hwid))\n ports.append(port)\n while True:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send CtrlC CtrlC to TC module to wake it up, capture header content Get computer's UTC time for comparison to time reported in module header If debug flag, write module response to stderr
def wake_tc_get_header(ser, ntpoffset, debug=0): ser.reset_input_buffer() ser.reset_output_buffer() wakeup = b"\x03\x03" for b in serial.iterbytes(wakeup): n = ser.write(b) if debug: LOGGER.debug("{} byte ({}) written to port".format(n, b)) time.sleep(0.1) timec...
[ "def wake_ssc_get_header(ser, ntpoffset, debug=0):\n ser.reset_output_buffer()\n\n xloop = 0\n while not ser.in_waiting:\n xloop += 1\n if xloop > 1000:\n return None, None\n time.sleep(0.01)\n\n timecheck = datetime.utcnow() + timedelta(seconds=ntpoffset)\n\n capture ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wait 10 seconds for response to waking SSC module, capture header content Get computer's UTC time for comparison to time reported in module header If debug flag, write module response to stderr
def wake_ssc_get_header(ser, ntpoffset, debug=0): ser.reset_output_buffer() xloop = 0 while not ser.in_waiting: xloop += 1 if xloop > 1000: return None, None time.sleep(0.01) timecheck = datetime.utcnow() + timedelta(seconds=ntpoffset) capture = "" rx = 1 ...
[ "def print_header(now):\n global config\n date_time = datetime.datetime.fromtimestamp(now).strftime('%Y-%m-%d %H:%M:%S')\n\n print('*************************************')\n print(f'HTTP LOGS STATISTICS - {date_time}')", "def run_diagnostics(self):\n request = {\n 'jsonrpc': '2.0',\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send 'TEXT.DUMP' command to module, wait for response Write response (hopefully module header and data) to stderr and output file. Check each record for sync flag 'CAFE', change output file name as necessary.
def dump_data(ser, meta, args): ser.reset_input_buffer() ser.reset_output_buffer() command = b"TEXT.DUMP\r" rx = "" ntry = 0 while not rx or (rx.split()[-1] != "data?"): rx = send_cmd(ser, command, args.debug) # sys.stderr.write(rx) ntry += 1 if ntry > 3: ...
[ "def core_dump(self):\r\r\n loggerModem = logging.getLogger(__name__ + 'core_dump')\r\r\n cmd_l=[r'at%debug=0', r'at%debug=2']\r\r\n cmd_str='\\r\\n'.join(cmd_l)\r\r\n\r\r\n text_str = \"AT command\"\r\r\n if self.dumpfile:\r\r\n loggerModem.debug(\"Core file : %s\" % s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update all sections in a semester. If given abbreviation + course_number, update only that course's sections.
def update(self, semester, year, abbreviation=None, course_number=None): print({ 'message': 'Updating sections.', 'semester': semester, 'year': year, 'abbreviation': abbreviation, 'course_number': course_number, }) # Get list of course...
[ "async def update(self, course_section):\n await self.session.put('sections/' + course_section['id'],\n json=course_section);", "def updateData(self):\n for section_num in self.sections:\n self.parseData(section_num=section_num)\n self.updateSectionData(section_num=s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update all sections for a course in a semester. Though not rigorously defined, a 'class' here is the collection of sections for a course offered in a single semester.
def _update_class(self, course, semester, year): if cache_result := cache.get(f'no classes {course.id}'): print(f'no classes found for course {course.id} at {cache_result}') return # Get response from SIS class resource response = sis_class_resource.get( sem...
[ "def update(self, semester, year, abbreviation=None, course_number=None):\n print({\n 'message': 'Updating sections.',\n 'semester': semester,\n 'year': year,\n 'abbreviation': abbreviation,\n 'course_number': course_number,\n })\n\n # Get ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true, if all elements of sequence are equal
def all_equal(sequence): return all(x == sequence[0] for x in sequence)
[ "def equal(seq):\n return len(set(seq)) <= 1", "def seq_all_same(seq, **kw):\n return seq_all_same_r(seq, **kw).same", "def same(seq: typing.Iterable[typing.Any]) -> bool:\n seq = iter(seq)\n first = type(next(seq))\n return all(isinstance(i, first) for i in seq)", "def allsame(xs):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save stereo or mono sonifications
def save_stereo(self, fname, master_volume=1.): if len(self.out_channels) > 2: print("Warning: sonification has > 2 channels, only first 2 will be used. See 'save_combined' method.") # first pass - find max amplitude value to normalise output # and concatenate channels to l...
[ "def stereo(filename,time,wout=True):\n n, data, data_dB,sr,ch=inputwav(filename)\n s_shift=int(sr*time*1E-3)\n R=np.zeros(n)\n L=np.zeros(n)\n if ch==2:\n L[:]=data[:,0]\n R[:]=data[:,1]\n if ch==1:\n L[:]=data[:,0]\n R[:]=data[:,0]\n print('Applying stereo width.....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save render as a combined multichannel wav file Can use this function to save sonification of any audio_setup, using ffmpeg processing, and unscrampling to the correct channel order.
def save_combined(self, fname, ffmpeg_output=False, master_volume=1.): # setup list to house wav stream data inputs = [None]*len(self.out_channels) # first pass - find max amplitude value to normalise output vmax = 0. for c in range(len(self.out_channels)): vmax = m...
[ "def save_stereo(self, fname, master_volume=1.):\n\n if len(self.out_channels) > 2:\n print(\"Warning: sonification has > 2 channels, only first 2 will be used. See 'save_combined' method.\")\n \n # first pass - find max amplitude value to normalise output\n # and concatenate ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
plot the waveforms and embed player in the notebook Show waveforms and embed an audio player in the python notebook for direct playback. the notebook player only supports up to stereo, so if more than two channels, only the first two are used as left and right.
def notebook_display(self): time = self.out_channels['0'].samples / self.out_channels['0'].samprate vmax = 0. for c in range(len(self.out_channels)): vmax = max( abs(self.out_channels[str(c)].values.max()), abs(self.out_channels[str(c)].values.min()),...
[ "def plotAudio(self):\n pylab.plot(self.audio.flatten())\n pylab.show()", "def show_wav(self):\r\n pylab.figure(1)\r\n pylab.plot(self.data,\"r\")\r\n pylab.ylabel('level of signal ' + self.title)\r\n pylab.xlabel('time (1/44100 sec)')\r\n pylab.show()", "def vie...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Default string representation of an episode
def __repr__(self: object) -> str: measstring: str = "Tatort - {:04d} - {} - {} - {} - {}".format(self.episode_id, self.episode_name, self.episode_inspectors, self.episode_sequence, self.episode_broadcast) return measstring
[ "def test_repr_episode(self):\n self.assertEquals(\n repr(self.t['CNNNN'][1][1]),\n \"<Episode 01x01 - September 19, 2002 (20:30 - 21:00)>\"\n )", "def seasonEpisode(self):\n return f's{str(self.seasonNumber).zfill(2)}e{str(self.episodeNumber).zfill(2)}'", "def episode...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if episode matches the filename
def matches(self: object, filename: str) -> bool: # Filename is equal to episode string representation if str(self) == filename: return True # Check leading episode number => download marked as special episode manually filename_match: Match[str] = re.search(r"(^[0-9]{4} )", ...
[ "def episode_file_filter(season, episode):\n string_templates = (\n 's{season:02d}e{episode:02d}',\n '{season}x{episode:02d}',\n )\n search_strings = [template.format(season=season, episode=episode)\n for template in string_templates]\n def is_in(filename):\n fo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates an MSBuild payload. The file's name will be staged/stageless_64/32.xml depending on the staging and architecture of the generated payload.
def generateMSBuild( self, agscriptPath: str, listener: str, outputPath: str = './', staged: bool = False, x64: bool = True ): shellcode = self.generateShellcode(listener, staged=staged, x64=x64) if shellcode: encoded = base64.b64encode(shellcode) if x64: arch = "64" else: arch = ...
[ "def gen_payload(dummy_payload=None):\n size = 0 if dummy_payload is None else len(dummy_payload)\n flag_offset = 0 if dummy_payload is None else dummy_payload.find(b\"flagA\")\n cat_offset = 0 if dummy_payload is None else dummy_payload.find(b\"/bin/cat\")\n\n # Aarch64 payload\n pwn.context.clear(a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Connect to CS team server
def connectTeamserver(self): # In my testing, I found that there were issues sending too many # messages to event log over one connection ( => ~7), so I recommend # creating a new object every so often or disconnecting and reconnecting. # This issue needs to be troubleshot (troubleshooted?) in the future i...
[ "def connect_to_server(self):\n\n server=os.popen('hostname').read()\n if 'epfl.ch' not in server:\n conn = mds.Connection('tcvdata.epfl.ch')\n conn.openTree('tcv_shot', self.shot)\n self.tree = conn\n print(\"You are in server \"+server+\", so I'll open a c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Disconnect from CS team server
def disconnectTeamserver(self): # close the agscript process if self.cs_process: self.cs_process.close() else: print("CS was already disconnected! Hopefully you already knew this.") # clear config vars #self.socks_port = '' #self.beacon_pid = '' #self.bid = '' #self.socks_port_connected = False
[ "def disconnect(self):\n r = requests.post(f'{self.SERVER_ADDR}/api/disconnect', headers={'Authorization': 'Token ' + self.token})\n r.raise_for_status()", "def disconnect(c):\n\tprint('client.user.disconnect')\n\tGameLogic.data['server'].close()", "def disconnect():\r\n global sock, ip_address...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads a TF DistilBERT model from disk. Requires a TF model JSON and matching weights HDF5.
def get_bert_clf(): model = tf.keras.models.model_from_json(get_object('distilbert_model.json', 'r')) model.load_weights(model_dir/'distilbert_weights.hdf5') return model
[ "def load_bert_model():\r\n logging.critical(\"Loading BERT model...\")\r\n json_file = open('model.json', 'r')\r\n loaded_model_json = json_file.read()\r\n json_file.close()\r\n loaded_model = model_from_json(loaded_model_json, custom_objects={\"BertModelLayer\": bert.BertModelLayer})\r\n # load ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes a prediction on `query` using `clf_type`, optionally returning probabilities.
def predict(query, clf_type, probas=False): clf_types = ['bert'] if clf_type not in clf_types: raise ValueError(f'`clf_type` must be one of {clf_types}') if clf_type == 'bert': x = bert_tkzr(query, padding='max_length', max_length=100, truncation=True, return_tensors='tf') pred = ber...
[ "def Predict(credentials, model, query):\n http = httplib2.Http()\n http = credentials.authorize(http)\n\n service = build(\"prediction\", \"v1.4\", http=http)\n\n trained_model = service.trainedmodels()\n\n body = {\"input\":{\"csvInstance\":[query]}}\n logging.info(\"New request: %r\" % body)\n\n predictio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }