Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def deep_insert(path_list, value, config): if len(path_list) > 1: inside_config = config.setdefault(path_list[0], {}) deep_insert(path_list[1:], value, inside_config) else: config[path_list[0]] = value
[ "Inserts value into config by path, generating intermediate dictionaries.\n\n Example:\n >>> deep_insert(path.split(\".\"), value, {})\n " ]
Please provide a description of the function:def from_bytes_list(cls, function_descriptor_list): assert isinstance(function_descriptor_list, list) if len(function_descriptor_list) == 0: # This is a function descriptor of driver task. return FunctionDescriptor.for_driver_...
[ "Create a FunctionDescriptor instance from list of bytes.\n\n This function is used to create the function descriptor from\n backend data.\n\n Args:\n cls: Current class which is required argument for classmethod.\n function_descriptor_list: list of bytes to represent the\...
Please provide a description of the function:def from_function(cls, function): module_name = function.__module__ function_name = function.__name__ class_name = "" function_source_hasher = hashlib.sha1() try: # If we are running a script or are in IPython, in...
[ "Create a FunctionDescriptor from a function instance.\n\n This function is used to create the function descriptor from\n a python function. If a function is a class function, it should\n not be used by this function.\n\n Args:\n cls: Current class which is required argument f...
Please provide a description of the function:def from_class(cls, target_class): module_name = target_class.__module__ class_name = target_class.__name__ return cls(module_name, "__init__", class_name)
[ "Create a FunctionDescriptor from a class.\n\n Args:\n cls: Current class which is required argument for classmethod.\n target_class: the python class used to create the function\n descriptor.\n\n Returns:\n The FunctionDescriptor instance created accord...
Please provide a description of the function:def is_for_driver_task(self): return all( len(x) == 0 for x in [self.module_name, self.class_name, self.function_name])
[ "See whether this function descriptor is for a driver or not.\n\n Returns:\n True if this function descriptor is for driver tasks.\n " ]
Please provide a description of the function:def _get_function_id(self): if self.is_for_driver_task: return ray.FunctionID.nil() function_id_hash = hashlib.sha1() # Include the function module and name in the hash. function_id_hash.update(self.module_name.encode("asc...
[ "Calculate the function id of current function descriptor.\n\n This function id is calculated from all the fields of function\n descriptor.\n\n Returns:\n ray.ObjectID to represent the function descriptor.\n " ]
Please provide a description of the function:def get_function_descriptor_list(self): descriptor_list = [] if self.is_for_driver_task: # Driver task returns an empty list. return descriptor_list else: descriptor_list.append(self.module_name.encode("asc...
[ "Return a list of bytes representing the function descriptor.\n\n This function is used to pass this function descriptor to backend.\n\n Returns:\n A list of bytes.\n " ]
Please provide a description of the function:def export_cached(self): for remote_function in self._functions_to_export: self._do_export(remote_function) self._functions_to_export = None for info in self._actors_to_export: (key, actor_class_info) = info ...
[ "Export cached remote functions\n\n Note: this should be called only once when worker is connected.\n " ]
Please provide a description of the function:def export(self, remote_function): if self._worker.mode is None: # If the worker isn't connected, cache the function # and export it later. self._functions_to_export.append(remote_function) return if se...
[ "Export a remote function.\n\n Args:\n remote_function: the RemoteFunction object.\n " ]
Please provide a description of the function:def _do_export(self, remote_function): if self._worker.load_code_from_local: return # Work around limitations of Python pickling. function = remote_function._function function_name_global_valid = function.__name__ in funct...
[ "Pickle a remote function and export it to redis.\n\n Args:\n remote_function: the RemoteFunction object.\n " ]
Please provide a description of the function:def fetch_and_register_remote_function(self, key): (driver_id_str, function_id_str, function_name, serialized_function, num_return_vals, module, resources, max_calls) = self._worker.redis_client.hmget(key, [ "driver_id", "funct...
[ "Import a remote function." ]
Please provide a description of the function:def get_execution_info(self, driver_id, function_descriptor): if self._worker.load_code_from_local: # Load function from local code. # Currently, we don't support isolating code by drivers, # thus always set driver ID to N...
[ "Get the FunctionExecutionInfo of a remote function.\n\n Args:\n driver_id: ID of the driver that the function belongs to.\n function_descriptor: The FunctionDescriptor of the function to get.\n\n Returns:\n A FunctionExecutionInfo object.\n " ]
Please provide a description of the function:def _wait_for_function(self, function_descriptor, driver_id, timeout=10): start_time = time.time() # Only send the warning once. warning_sent = False while True: with self.lock: if (self._worker.actor_id.is...
[ "Wait until the function to be executed is present on this worker.\n\n This method will simply loop until the import thread has imported the\n relevant function. If we spend too long in this loop, that may indicate\n a problem somewhere and we will push an error message to the user.\n\n ...
Please provide a description of the function:def _publish_actor_class_to_key(self, key, actor_class_info): # We set the driver ID here because it may not have been available when # the actor class was defined. self._worker.redis_client.hmset(key, actor_class_info) self._worker.r...
[ "Push an actor class definition to Redis.\n\n The is factored out as a separate function because it is also called\n on cached actor class definitions when a worker connects for the first\n time.\n\n Args:\n key: The key to store the actor class info at.\n actor_cla...
Please provide a description of the function:def load_actor_class(self, driver_id, function_descriptor): function_id = function_descriptor.function_id # Check if the actor class already exists in the cache. actor_class = self._loaded_actor_classes.get(function_id, None) if actor...
[ "Load the actor class.\n\n Args:\n driver_id: Driver ID of the actor.\n function_descriptor: Function descriptor of the actor constructor.\n\n Returns:\n The actor class.\n " ]
Please provide a description of the function:def _load_actor_from_local(self, driver_id, function_descriptor): module_name, class_name = (function_descriptor.module_name, function_descriptor.class_name) try: module = importlib.import_module(module_...
[ "Load actor class from local code." ]
Please provide a description of the function:def _load_actor_class_from_gcs(self, driver_id, function_descriptor): key = (b"ActorClass:" + driver_id.binary() + b":" + function_descriptor.function_id.binary()) # Wait for the actor class key to have been imported by the # i...
[ "Load actor class from GCS." ]
Please provide a description of the function:def _make_actor_method_executor(self, method_name, method, actor_imported): def actor_method_executor(dummy_return_id, actor, *args): # Update the actor's task counter to reflect the task we're about # to execute. self._w...
[ "Make an executor that wraps a user-defined actor method.\n\n The wrapped method updates the worker's internal state and performs any\n necessary checkpointing operations.\n\n Args:\n method_name (str): The name of the actor method.\n method (instancemethod): The actor met...
Please provide a description of the function:def _save_and_log_checkpoint(self, actor): actor_id = self._worker.actor_id checkpoint_info = self._worker.actor_checkpoint_info[actor_id] checkpoint_info.num_tasks_since_last_checkpoint += 1 now = int(1000 * time.time()) chec...
[ "Save an actor checkpoint if necessary and log any errors.\n\n Args:\n actor: The actor to checkpoint.\n\n Returns:\n The result of the actor's user-defined `save_checkpoint` method.\n " ]
Please provide a description of the function:def _restore_and_log_checkpoint(self, actor): actor_id = self._worker.actor_id try: checkpoints = ray.actor.get_checkpoints_for_actor(actor_id) if len(checkpoints) > 0: # If we found previously saved checkpoint...
[ "Restore an actor from a checkpoint if available and log any errors.\n\n This should only be called on workers that have just executed an actor\n creation task.\n\n Args:\n actor: The actor to restore from a checkpoint.\n " ]
Please provide a description of the function:def _env_runner(base_env, extra_batch_callback, policies, policy_mapping_fn, unroll_length, horizon, preprocessors, obs_filters, clip_rewards, clip_actions, pack, callbacks, tf_sess, perf_stats, soft_horizon): try: ...
[ "This implements the common experience collection logic.\n\n Args:\n base_env (BaseEnv): env implementing BaseEnv.\n extra_batch_callback (fn): function to send extra batch data to.\n policies (dict): Map of policy ids to PolicyGraph instances.\n policy_mapping_fn (func): Function tha...
Please provide a description of the function:def _process_observations(base_env, policies, batch_builder_pool, active_episodes, unfiltered_obs, rewards, dones, infos, off_policy_actions, horizon, preprocessors, obs_filters, unroll_length, pac...
[ "Record new data from the environment and prepare for policy evaluation.\n\n Returns:\n active_envs: set of non-terminated env ids\n to_eval: map of policy_id to list of agent PolicyEvalData\n outputs: list of metrics and samples to return from the sampler\n " ]
Please provide a description of the function:def _do_policy_eval(tf_sess, to_eval, policies, active_episodes): eval_results = {} if tf_sess: builder = TFRunBuilder(tf_sess, "policy_eval") pending_fetches = {} else: builder = None if log_once("compute_actions_input"): ...
[ "Call compute actions on observation batches to get next actions.\n\n Returns:\n eval_results: dict of policy to compute_action() outputs.\n " ]
Please provide a description of the function:def _process_policy_eval_results(to_eval, eval_results, active_episodes, active_envs, off_policy_actions, policies, clip_actions): actions_to_send = defaultdict(dict) for env_id in active_envs: ...
[ "Process the output of policy neural network evaluation.\n\n Records policy evaluation results into the given episode objects and\n returns replies to send back to agents in the env.\n\n Returns:\n actions_to_send: nested dict of env id -> agent id -> agent replies.\n " ]
Please provide a description of the function:def _fetch_atari_metrics(base_env): unwrapped = base_env.get_unwrapped() if not unwrapped: return None atari_out = [] for u in unwrapped: monitor = get_wrapper_by_cls(u, MonitorEnv) if not monitor: return None ...
[ "Atari games have multiple logical episodes, one per life.\n\n However for metrics reporting we count full episodes all lives included.\n " ]
Please provide a description of the function:def compare_version(a, b): aa = string.split(a, ".") bb = string.split(b, ".") for i in range(0, 4): if aa[i] != bb[i]: return cmp(int(aa[i]), int(bb[i])) return 0
[ "Compare two version number strings of the form W.X.Y.Z.\n\n The numbers are compared most-significant to least-significant.\n For example, 12.345.67.89 > 2.987.88.99.\n\n Args:\n a: First version number string to compare\n b: Second version number string to compare\n\n Returns:\n 0 if the numbers are ...
Please provide a description of the function:def configure_cmake(self): cmake = CMake(self) cmake.definitions["FLATBUFFERS_BUILD_TESTS"] = False cmake.definitions["FLATBUFFERS_BUILD_SHAREDLIB"] = self.options.shared cmake.definitions["FLATBUFFERS_BUILD_FLATLIB"] = not self.optio...
[ "Create CMake instance and execute configure step\n " ]
Please provide a description of the function:def package(self): cmake = self.configure_cmake() cmake.install() self.copy(pattern="LICENSE.txt", dst="licenses") self.copy(pattern="FindFlatBuffers.cmake", dst=os.path.join("lib", "cmake", "flatbuffers"), src="CMake") self.c...
[ "Copy Flatbuffers' artifacts to package folder\n " ]
Please provide a description of the function:def package_info(self): self.cpp_info.libs = tools.collect_libs(self) self.user_info.flatc = os.path.join(self.package_folder, "bin", "flatc")
[ "Collect built libraries names and solve flatc path.\n " ]
Please provide a description of the function:def Offset(self, vtableOffset): vtable = self.Pos - self.Get(N.SOffsetTFlags, self.Pos) vtableEnd = self.Get(N.VOffsetTFlags, vtable) if vtableOffset < vtableEnd: return self.Get(N.VOffsetTFlags, vtable + vtableOffset) re...
[ "Offset provides access into the Table's vtable.\n\n Deprecated fields are ignored by checking the vtable's length." ]
Please provide a description of the function:def Indirect(self, off): N.enforce_number(off, N.UOffsetTFlags) return off + encode.Get(N.UOffsetTFlags.packer_type, self.Bytes, off)
[ "Indirect retrieves the relative offset stored at `offset`." ]
Please provide a description of the function:def String(self, off): N.enforce_number(off, N.UOffsetTFlags) off += encode.Get(N.UOffsetTFlags.packer_type, self.Bytes, off) start = off + N.UOffsetTFlags.bytewidth length = encode.Get(N.UOffsetTFlags.packer_type, self.Bytes, off) ...
[ "String gets a string from data stored inside the flatbuffer." ]
Please provide a description of the function:def VectorLen(self, off): N.enforce_number(off, N.UOffsetTFlags) off += self.Pos off += encode.Get(N.UOffsetTFlags.packer_type, self.Bytes, off) ret = encode.Get(N.UOffsetTFlags.packer_type, self.Bytes, off) return ret
[ "VectorLen retrieves the length of the vector whose offset is stored\n at \"off\" in this object." ]
Please provide a description of the function:def Vector(self, off): N.enforce_number(off, N.UOffsetTFlags) off += self.Pos x = off + self.Get(N.UOffsetTFlags, off) # data starts after metadata containing the vector length x += N.UOffsetTFlags.bytewidth return x
[ "Vector retrieves the start of data of the vector whose offset is\n stored at \"off\" in this object." ]
Please provide a description of the function:def Union(self, t2, off): assert type(t2) is Table N.enforce_number(off, N.UOffsetTFlags) off += self.Pos t2.Pos = off + self.Get(N.UOffsetTFlags, off) t2.Bytes = self.Bytes
[ "Union initializes any Table-derived type to point to the union at\n the given offset." ]
Please provide a description of the function:def Get(self, flags, off): N.enforce_number(off, N.UOffsetTFlags) return flags.py_type(encode.Get(flags.packer_type, self.Bytes, off))
[ "\n Get retrieves a value of the type specified by `flags` at the\n given offset.\n " ]
Please provide a description of the function:def GetVectorAsNumpy(self, flags, off): offset = self.Vector(off) length = self.VectorLen(off) # TODO: length accounts for bytewidth, right? numpy_dtype = N.to_numpy_type(flags) return encode.GetVectorAsNumpy(numpy_dtype, self.Bytes, ...
[ "\n GetVectorAsNumpy returns the vector that starts at `Vector(off)`\n as a numpy array with the type specified by `flags`. The array is\n a `view` into Bytes, so modifying the returned array will\n modify Bytes in place.\n " ]
Please provide a description of the function:def GetVOffsetTSlot(self, slot, d): N.enforce_number(slot, N.VOffsetTFlags) N.enforce_number(d, N.VOffsetTFlags) off = self.Offset(slot) if off == 0: return d return off
[ "\n GetVOffsetTSlot retrieves the VOffsetT that the given vtable location\n points to. If the vtable value is zero, the default value `d`\n will be returned.\n " ]
Please provide a description of the function:def GetVectorAsNumpy(numpy_type, buf, count, offset): if np is not None: # TODO: could set .flags.writeable = False to make users jump through # hoops before modifying... return np.frombuffer(buf, dtype=numpy_type, count=count, offset=o...
[ " GetVecAsNumpy decodes values starting at buf[head] as\n `numpy_type`, where `numpy_type` is a numpy dtype. " ]
Please provide a description of the function:def Write(packer_type, buf, head, n): packer_type.pack_into(buf, head, n)
[ " Write encodes `n` at buf[head] using `packer_type`. " ]
Please provide a description of the function:def main(): if len(sys.argv) < 2: sys.stderr.write('Usage: run_flatc.py flatbuffers_dir [flatc_args]\n') return 1 cwd = os.getcwd() flatc = '' flatbuffers_dir = sys.argv[1] for path in FLATC_SEARCH_PATHS: current = os.path.join(flatbuffers_dir, path,...
[ "Script that finds and runs flatc built from source." ]
Please provide a description of the function:def import_numpy(): try: imp.find_module('numpy') numpy_exists = True except ImportError: numpy_exists = False if numpy_exists: # We do this outside of try/except block in case numpy exists # but is not installed corr...
[ "\n Returns the numpy module if it exists on the system,\n otherwise returns None.\n " ]
Please provide a description of the function:def vtableEqual(a, objectStart, b): N.enforce_number(objectStart, N.UOffsetTFlags) if len(a) * N.VOffsetTFlags.bytewidth != len(b): return False for i, elem in enumerate(a): x = encode.Get(packer.voffset, b, i * N.VOffsetTFlags.bytewidth) ...
[ "vtableEqual compares an unwritten vtable to a written vtable." ]
Please provide a description of the function:def StartObject(self, numfields): self.assertNotNested() # use 32-bit offsets so that arithmetic doesn't overflow. self.current_vtable = [0 for _ in range_func(numfields)] self.objectEnd = self.Offset() self.nested = True
[ "StartObject initializes bookkeeping for writing a new object." ]
Please provide a description of the function:def WriteVtable(self): # Prepend a zero scalar to the object. Later in this function we'll # write an offset here that points to the object's vtable: self.PrependSOffsetTRelative(0) objectOffset = self.Offset() existingVtabl...
[ "\n WriteVtable serializes the vtable for the current object, if needed.\n\n Before writing out the vtable, this checks pre-existing vtables for\n equality to this one. If an equal vtable is found, point the object to\n the existing vtable and return.\n\n Because vtable values are...
Please provide a description of the function:def growByteBuffer(self): if len(self.Bytes) == Builder.MAX_BUFFER_SIZE: msg = "flatbuffers: cannot grow buffer beyond 2 gigabytes" raise BuilderSizeError(msg) newSize = min(len(self.Bytes) * 2, Builder.MAX_BUFFER_SIZE) ...
[ "Doubles the size of the byteslice, and copies the old data towards\n the end of the new buffer (since we build the buffer backwards)." ]
Please provide a description of the function:def Pad(self, n): for i in range_func(n): self.Place(0, N.Uint8Flags)
[ "Pad places zeros at the current offset." ]
Please provide a description of the function:def Prep(self, size, additionalBytes): # Track the biggest thing we've ever aligned to. if size > self.minalign: self.minalign = size # Find the amount of alignment needed such that `size` is properly # aligned after `ad...
[ "\n Prep prepares to write an element of `size` after `additional_bytes`\n have been written, e.g. if you write a string, you need to align\n such the int length field is aligned to SizeInt32, and the string\n data follows it directly.\n If all you need to do is align, `additional...
Please provide a description of the function:def PrependSOffsetTRelative(self, off): # Ensure alignment is already done: self.Prep(N.SOffsetTFlags.bytewidth, 0) if not (off <= self.Offset()): msg = "flatbuffers: Offset arithmetic error." raise OffsetArithmeticEr...
[ "\n PrependSOffsetTRelative prepends an SOffsetT, relative to where it\n will be written.\n " ]
Please provide a description of the function:def PrependUOffsetTRelative(self, off): # Ensure alignment is already done: self.Prep(N.UOffsetTFlags.bytewidth, 0) if not (off <= self.Offset()): msg = "flatbuffers: Offset arithmetic error." raise OffsetArithmeticEr...
[ "Prepends an unsigned offset into vector data, relative to where it\n will be written.\n " ]
Please provide a description of the function:def StartVector(self, elemSize, numElems, alignment): self.assertNotNested() self.nested = True self.Prep(N.Uint32Flags.bytewidth, elemSize*numElems) self.Prep(alignment, elemSize*numElems) # In case alignment > int. return ...
[ "\n StartVector initializes bookkeeping for writing a new vector.\n\n A vector has the following format:\n - <UOffsetT: number of elements in this vector>\n - <T: data>+, where T is the type of elements of this vector.\n " ]
Please provide a description of the function:def EndVector(self, vectorNumElems): self.assertNested() ## @cond FLATBUFFERS_INTERNAL self.nested = False ## @endcond # we already made space for this, so write without PrependUint32 self.PlaceUOffsetT(vectorNumElems...
[ "EndVector writes data necessary to finish vector construction." ]
Please provide a description of the function:def CreateString(self, s, encoding='utf-8', errors='strict'): self.assertNotNested() ## @cond FLATBUFFERS_INTERNAL self.nested = True ## @endcond if isinstance(s, compat.string_types): x = s.encode(encoding, erro...
[ "CreateString writes a null-terminated byte string as a vector." ]
Please provide a description of the function:def CreateByteVector(self, x): self.assertNotNested() ## @cond FLATBUFFERS_INTERNAL self.nested = True ## @endcond if not isinstance(x, compat.binary_types): raise TypeError("non-byte vector passed to CreateByteV...
[ "CreateString writes a byte vector." ]
Please provide a description of the function:def CreateNumpyVector(self, x): if np is None: # Numpy is required for this feature raise NumpyRequiredForThisFeature("Numpy was not found.") if not isinstance(x, np.ndarray): raise TypeError("non-numpy-ndarray p...
[ "CreateNumpyVector writes a numpy array into the buffer." ]
Please provide a description of the function:def assertStructIsInline(self, obj): N.enforce_number(obj, N.UOffsetTFlags) if obj != self.Offset(): msg = ("flatbuffers: Tried to write a Struct at an Offset that " "is different from the current Offset of the Builder...
[ "\n Structs are always stored inline, so need to be created right\n where they are used. You'll get this error if you created it\n elsewhere.\n " ]
Please provide a description of the function:def Slot(self, slotnum): self.assertNested() self.current_vtable[slotnum] = self.Offset()
[ "\n Slot sets the vtable key `voffset` to the current location in the\n buffer.\n\n " ]
Please provide a description of the function:def __Finish(self, rootTable, sizePrefix): N.enforce_number(rootTable, N.UOffsetTFlags) prepSize = N.UOffsetTFlags.bytewidth if sizePrefix: prepSize += N.Int32Flags.bytewidth self.Prep(self.minalign, prepSize) self...
[ "Finish finalizes a buffer, pointing to the given `rootTable`." ]
Please provide a description of the function:def PrependUOffsetTRelativeSlot(self, o, x, d): if x != d: self.PrependUOffsetTRelative(x) self.Slot(o)
[ "\n PrependUOffsetTRelativeSlot prepends an UOffsetT onto the object at\n vtable slot `o`. If value `x` equals default `d`, then the slot will\n be set to zero and no other data will be written.\n " ]
Please provide a description of the function:def PrependStructSlot(self, v, x, d): N.enforce_number(d, N.UOffsetTFlags) if x != d: self.assertStructIsInline(x) self.Slot(v)
[ "\n PrependStructSlot prepends a struct onto the object at vtable slot `o`.\n Structs are stored inline, so nothing additional is being added.\n In generated code, `d` is always 0.\n " ]
Please provide a description of the function:def Place(self, x, flags): N.enforce_number(x, flags) self.head = self.head - flags.bytewidth encode.Write(flags.packer_type, self.Bytes, self.Head(), x)
[ "\n Place prepends a value specified by `flags` to the Builder,\n without checking for available space.\n " ]
Please provide a description of the function:def PlaceVOffsetT(self, x): N.enforce_number(x, N.VOffsetTFlags) self.head = self.head - N.VOffsetTFlags.bytewidth encode.Write(packer.voffset, self.Bytes, self.Head(), x)
[ "PlaceVOffsetT prepends a VOffsetT to the Builder, without checking\n for space.\n " ]
Please provide a description of the function:def PlaceSOffsetT(self, x): N.enforce_number(x, N.SOffsetTFlags) self.head = self.head - N.SOffsetTFlags.bytewidth encode.Write(packer.soffset, self.Bytes, self.Head(), x)
[ "PlaceSOffsetT prepends a SOffsetT to the Builder, without checking\n for space.\n " ]
Please provide a description of the function:def PlaceUOffsetT(self, x): N.enforce_number(x, N.UOffsetTFlags) self.head = self.head - N.UOffsetTFlags.bytewidth encode.Write(packer.uoffset, self.Bytes, self.Head(), x)
[ "PlaceUOffsetT prepends a UOffsetT to the Builder, without checking\n for space.\n " ]
Please provide a description of the function:def site_data_dir(appname=None, appauthor=None, version=None, multipath=False): r if system == "win32": if appauthor is None: appauthor = appname path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA")) if appname: ...
[ "Return full path to the user-shared data dir for this application.\n\n \"appname\" is the name of application.\n If None, just the system directory is returned.\n \"appauthor\" (only used on Windows) is the name of the\n appauthor or distributing body for this application. Typic...
Please provide a description of the function:def user_config_dir(appname=None, appauthor=None, version=None, roaming=False): r if system in ["win32", "darwin"]: path = user_data_dir(appname, appauthor, None, roaming) else: path = os.getenv('XDG_CONFIG_HOME', os.path.expanduser("~/.config")) ...
[ "Return full path to the user-specific config dir for this application.\n\n \"appname\" is the name of application.\n If None, just the system directory is returned.\n \"appauthor\" (only used on Windows) is the name of the\n appauthor or distributing body for this application. T...
Please provide a description of the function:def request(method, url, **kwargs): # By using the 'with' statement we are sure the session is closed, thus we # avoid leaving sockets open which can trigger a ResourceWarning in some # cases, and look like a memory leak in others. with sessions.Session...
[ "Constructs and sends a :class:`Request <Request>`.\n\n :param method: method for the new :class:`Request` object.\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary, list of tuples or bytes to send\n in the body of the :class:`Request`.\n :param data: (...
Please provide a description of the function:def get(url, params=None, **kwargs): r kwargs.setdefault('allow_redirects', True) return request('get', url, params=params, **kwargs)
[ "Sends a GET request.\n\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary, list of tuples or bytes to send\n in the body of the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response <Response>` o...
Please provide a description of the function:def dump(o, f): if not f.write: raise TypeError("You can only dump an object to a file descriptor") d = dumps(o) f.write(d) return d
[ "Writes out dict as toml to a file\n\n Args:\n o: Object to dump into toml\n f: File descriptor where the toml should be stored\n\n Returns:\n String containing the toml corresponding to dictionary\n\n Raises:\n TypeError: When anything other than file descriptor is passed\n ...
Please provide a description of the function:def dumps(o, encoder=None): retval = "" if encoder is None: encoder = TomlEncoder(o.__class__) addtoretval, sections = encoder.dump_sections(o, "") retval += addtoretval while sections: newsections = encoder.get_empty_table() ...
[ "Stringifies input dict as toml\n\n Args:\n o: Object to dump into toml\n\n preserve: Boolean parameter. If true, preserve inline tables.\n\n Returns:\n String containing the toml corresponding to dict\n " ]
Please provide a description of the function:def dump_inline_table(self, section): retval = "" if isinstance(section, dict): val_list = [] for k, v in section.items(): val = self.dump_inline_table(v) val_list.append(k + " = " + val) ...
[ "Preserve inline table in its compact syntax instead of expanding\n into subsection.\n\n https://github.com/toml-lang/toml#user-content-inline-table\n " ]
Please provide a description of the function:def _is_env_truthy(name): if name not in os.environ: return False return os.environ.get(name).lower() not in ("0", "false", "no", "off")
[ "An environment variable is truthy if it exists and isn't one of (0, false, no, off)\n " ]
Please provide a description of the function:def is_in_virtualenv(): pipenv_active = os.environ.get("PIPENV_ACTIVE", False) virtual_env = None use_system = False ignore_virtualenvs = bool(os.environ.get("PIPENV_IGNORE_VIRTUALENVS", False)) if not pipenv_active and not ignore_virtualenvs: ...
[ "\n Check virtualenv membership dynamically\n\n :return: True or false depending on whether we are in a regular virtualenv or not\n :rtype: bool\n " ]
Please provide a description of the function:def unpackb(packed, **kwargs): unpacker = Unpacker(None, **kwargs) unpacker.feed(packed) try: ret = unpacker._unpack() except OutOfData: raise UnpackValueError("Data is not enough.") if unpacker._got_extradata(): raise ExtraDa...
[ "\n Unpack an object from `packed`.\n\n Raises `ExtraData` when `packed` contains extra bytes.\n See :class:`Unpacker` for options.\n " ]
Please provide a description of the function:def _consume(self): self._stream_offset += self._buff_i - self._buf_checkpoint self._buf_checkpoint = self._buff_i
[ " Gets rid of the used parts of the buffer. " ]
Please provide a description of the function:def _new_conn(self): extra_kw = {} if self.source_address: extra_kw['source_address'] = self.source_address if self.socket_options: extra_kw['socket_options'] = self.socket_options try: conn = con...
[ " Establish a socket connection and set nodelay settings on it.\n\n :return: New socket connection.\n " ]
Please provide a description of the function:def request_chunked(self, method, url, body=None, headers=None): headers = HTTPHeaderDict(headers if headers is not None else {}) skip_accept_encoding = 'accept-encoding' in headers skip_host = 'host' in headers self.putrequest( ...
[ "\n Alternative to the common request method, which sends the\n body with chunked encoding and not as one block\n " ]
Please provide a description of the function:def set_cert(self, key_file=None, cert_file=None, cert_reqs=None, ca_certs=None, assert_hostname=None, assert_fingerprint=None, ca_cert_dir=None): # If cert_reqs is not provided, we can try to guess. If the ...
[ "\n This method should only be called once, before the connection is used.\n " ]
Please provide a description of the function:def prettify_exc(error): matched_exceptions = [k for k in KNOWN_EXCEPTIONS.keys() if k in error] if not matched_exceptions: return "{}".format(vistir.misc.decode_for_output(error)) errors = [] for match in matched_exceptions: _, error, in...
[ "Catch known errors and prettify them instead of showing the\n entire traceback, for better UX" ]
Please provide a description of the function:def get_stream_handle(stream=sys.stdout): handle = stream if os.name == "nt": from ctypes import windll handle_id = WIN_STDOUT_HANDLE_ID handle = windll.kernel32.GetStdHandle(handle_id) return handle
[ "\n Get the OS appropriate handle for the corresponding output stream.\n\n :param str stream: The the stream to get the handle for\n :return: A handle to the appropriate stream, either a ctypes buffer\n or **sys.stdout** or **sys.stderr**.\n " ]
Please provide a description of the function:def hide_cursor(stream=sys.stdout): handle = get_stream_handle(stream=stream) if os.name == "nt": from ctypes import windll cursor_info = CONSOLE_CURSOR_INFO() windll.kernel32.GetConsoleCursorInfo(handle, ctypes.byref(cursor_info)) ...
[ "\n Hide the console cursor on the given stream\n\n :param stream: The name of the stream to get the handle for\n :return: None\n :rtype: None\n " ]
Please provide a description of the function:def choice_complete(self, ctx, incomplete): return [ (c, None) for c in self.choices if completion_configuration.match_incomplete(c, incomplete) ]
[ "Returns the completion results for click.core.Choice\n\n Parameters\n ----------\n ctx : click.core.Context\n The current context\n incomplete :\n The string to complete\n\n Returns\n -------\n [(str, str)]\n A list of completion results\n " ]
Please provide a description of the function:def _shellcomplete(cli, prog_name, complete_var=None): if complete_var is None: complete_var = '_%s_COMPLETE' % (prog_name.replace('-', '_')).upper() complete_instr = os.environ.get(complete_var) if not complete_instr: return if complete...
[ "Internal handler for the bash completion support.\n\n Parameters\n ----------\n cli : click.Command\n The main click Command of the program\n prog_name : str\n The program name on the command line\n complete_var : str\n The environment variable name used to control the completio...
Please provide a description of the function:def patch(): import click click.types.ParamType.complete = param_type_complete click.types.Choice.complete = choice_complete click.core.MultiCommand.get_command_short_help = multicommand_get_command_short_help click.core._bashcomplete = _shellcomplet...
[ "Patch click" ]
Please provide a description of the function:def parse_expr(tokens, options): seq = parse_seq(tokens, options) if tokens.current() != '|': return seq result = [Required(*seq)] if len(seq) > 1 else seq while tokens.current() == '|': tokens.move() seq = parse_seq(tokens, optio...
[ "expr ::= seq ( '|' seq )* ;" ]
Please provide a description of the function:def parse_seq(tokens, options): result = [] while tokens.current() not in [None, ']', ')', '|']: atom = parse_atom(tokens, options) if tokens.current() == '...': atom = [OneOrMore(*atom)] tokens.move() result += at...
[ "seq ::= ( atom [ '...' ] )* ;" ]
Please provide a description of the function:def parse_argv(tokens, options, options_first=False): parsed = [] while tokens.current() is not None: if tokens.current() == '--': return parsed + [Argument(None, v) for v in tokens] elif tokens.current().startswith('--'): ...
[ "Parse command-line argument vector.\n\n If options_first:\n argv ::= [ long | shorts ]* [ argument ]* [ '--' [ argument ]* ] ;\n else:\n argv ::= [ long | shorts | argument ]* [ '--' [ argument ]* ] ;\n\n " ]
Please provide a description of the function:def unnest(elem): if isinstance(elem, Iterable) and not isinstance(elem, six.string_types): elem, target = tee(elem, 2) else: target = elem for el in target: if isinstance(el, Iterable) and not isinstance(el, six.string_types): ...
[ "Flatten an arbitrarily nested iterable\n\n :param elem: An iterable to flatten\n :type elem: :class:`~collections.Iterable`\n\n >>> nested_iterable = (1234, (3456, 4398345, (234234)), (2396, (23895750, 9283798, 29384, (289375983275, 293759, 2347, (2098, 7987, 27599)))))\n >>> list(vistir.misc.unnest(ne...
Please provide a description of the function:def run( cmd, env=None, return_object=False, block=True, cwd=None, verbose=False, nospin=False, spinner_name=None, combine_stderr=True, display_limit=200, write_to_stdout=True, ): _env = os.environ.copy() if env: ...
[ "Use `subprocess.Popen` to get the output of a command and decode it.\n\n :param list cmd: A list representing the command you want to run.\n :param dict env: Additional environment settings to pass through to the subprocess.\n :param bool return_object: When True, returns the whole subprocess instance\n ...
Please provide a description of the function:def load_path(python): python = Path(python).as_posix() out, err = run( [python, "-c", "import json, sys; print(json.dumps(sys.path))"], nospin=True ) if out: return json.loads(out) else: return []
[ "Load the :mod:`sys.path` from the given python executable's environment as json\n\n :param str python: Path to a valid python executable\n :return: A python representation of the `sys.path` value of the given python executable.\n :rtype: list\n\n >>> load_path(\"/home/user/.virtualenvs/requirementslib-...
Please provide a description of the function:def to_bytes(string, encoding="utf-8", errors="ignore"): if not errors: if encoding.lower() == "utf-8": errors = "surrogateescape" if six.PY3 else "ignore" else: errors = "strict" if isinstance(string, bytes): if ...
[ "Force a value to bytes.\n\n :param string: Some input that can be converted to a bytes.\n :type string: str or bytes unicode or a memoryview subclass\n :param encoding: The encoding to use for conversions, defaults to \"utf-8\"\n :param encoding: str, optional\n :return: Corresponding byte represent...
Please provide a description of the function:def to_text(string, encoding="utf-8", errors=None): if not errors: if encoding.lower() == "utf-8": errors = "surrogateescape" if six.PY3 else "ignore" else: errors = "strict" if issubclass(type(string), six.text_type): ...
[ "Force a value to a text-type.\n\n :param string: Some input that can be converted to a unicode representation.\n :type string: str or bytes unicode\n :param encoding: The encoding to use for conversions, defaults to \"utf-8\"\n :param encoding: str, optional\n :return: The unicode representation of ...
Please provide a description of the function:def divide(n, iterable): seq = tuple(iterable) q, r = divmod(len(seq), n) ret = [] for i in range(n): start = (i * q) + (i if i < r else r) stop = ((i + 1) * q) + (i + 1 if i + 1 < r else r) ret.append(iter(seq[start:stop])) ...
[ "\n split an iterable into n groups, per https://more-itertools.readthedocs.io/en/latest/api.html#grouping\n\n :param int n: Number of unique groups\n :param iter iterable: An iterable to split up\n :return: a list of new iterables derived from the original iterable\n :rtype: list\n " ]
Please provide a description of the function:def getpreferredencoding(): # Borrowed from Invoke # (see https://github.com/pyinvoke/invoke/blob/93af29d/invoke/runners.py#L881) _encoding = locale.getpreferredencoding(False) if six.PY2 and not sys.platform == "win32": _default_encoding = loca...
[ "Determine the proper output encoding for terminal rendering" ]
Please provide a description of the function:def decode_for_output(output, target_stream=None, translation_map=None): if not isinstance(output, six.string_types): return output encoding = None if target_stream is not None: encoding = getattr(target_stream, "encoding", None) encodin...
[ "Given a string, decode it for output to a terminal\n\n :param str output: A string to print to a terminal\n :param target_stream: A stream to write to, we will encode to target this stream if possible.\n :param dict translation_map: A mapping of unicode character ordinals to replacement strings.\n :ret...
Please provide a description of the function:def get_canonical_encoding_name(name): # type: (str) -> str import codecs try: codec = codecs.lookup(name) except LookupError: return name else: return codec.name
[ "\n Given an encoding name, get the canonical name from a codec lookup.\n\n :param str name: The name of the codec to lookup\n :return: The canonical version of the codec name\n :rtype: str\n " ]
Please provide a description of the function:def get_wrapped_stream(stream): if stream is None: raise TypeError("must provide a stream to wrap") encoding = getattr(stream, "encoding", None) encoding = get_output_encoding(encoding) return StreamWrapper(stream, encoding, "replace", line_buff...
[ "\n Given a stream, wrap it in a `StreamWrapper` instance and return the wrapped stream.\n\n :param stream: A stream instance to wrap\n :returns: A new, wrapped stream\n :rtype: :class:`StreamWrapper`\n " ]
Please provide a description of the function:def is_connection_dropped(conn): # Platform-specific sock = getattr(conn, 'sock', False) if sock is False: # Platform-specific: AppEngine return False if sock is None: # Connection already closed (such as by httplib). return True try: ...
[ "\n Returns True if the connection is dropped and should be closed.\n\n :param conn:\n :class:`httplib.HTTPConnection` object.\n\n Note: For platforms like AppEngine, this will always return ``False`` to\n let the platform handle connection recycling transparently for us.\n " ]
Please provide a description of the function:def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None, socket_options=None): host, port = address if host.startswith('['): host = host.strip('[]') err = None # Using the value from allo...
[ "Connect to *address* and return the socket object.\n\n Convenience function. Connect to *address* (a 2-tuple ``(host,\n port)``) and return the socket object. Passing the optional\n *timeout* parameter will set the timeout on the socket instance\n before attempting to connect. If no *timeout* is sup...
Please provide a description of the function:def _has_ipv6(host): sock = None has_ipv6 = False # App Engine doesn't support IPV6 sockets and actually has a quota on the # number of sockets that can be used, so just early out here instead of # creating a socket needlessly. # See https://git...
[ " Returns True if the system can bind an IPv6 address. " ]