nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
hltcoe/golden-horse
7a73c08e45ed94312af4ef2d97cc35a47d029e99
theano_src/neural_lib.py
python
_dropout_from_layer
(rng, layer, p)
return output
p is the probablity of dropping a unit
p is the probablity of dropping a unit
[ "p", "is", "the", "probablity", "of", "dropping", "a", "unit" ]
def _dropout_from_layer(rng, layer, p): """p is the probablity of dropping a unit """ srng = theano.tensor.shared_randomstreams.RandomStreams( rng.randint(999999)) # p=1-p because 1's indicate keep and p is prob of dropping mask = srng.binomial(n=1, p=1-p, size=layer.shape) # The cast is important because # int * float32 = float64 which pulls things off the gpu output = layer * T.cast(mask, theano.config.floatX) return output
[ "def", "_dropout_from_layer", "(", "rng", ",", "layer", ",", "p", ")", ":", "srng", "=", "theano", ".", "tensor", ".", "shared_randomstreams", ".", "RandomStreams", "(", "rng", ".", "randint", "(", "999999", ")", ")", "# p=1-p because 1's indicate keep and p is ...
https://github.com/hltcoe/golden-horse/blob/7a73c08e45ed94312af4ef2d97cc35a47d029e99/theano_src/neural_lib.py#L76-L86
ifwe/digsby
f5fe00244744aa131e07f09348d10563f3d8fa99
digsby/src/gui/windowfx.py
python
SlideTimer.Notify
(self)
Invoked by the wxTimer. Decides how much to move, and if it is time to stop.
Invoked by the wxTimer.
[ "Invoked", "by", "the", "wxTimer", "." ]
def Notify(self): ''' Invoked by the wxTimer. Decides how much to move, and if it is time to stop. ''' if not self: return if not self.window: return winrect = self.window.ScreenRect w, pos, target = self.window, vector(winrect[:2]), vector(self.target) move = lambda newpos: w.SetRect((newpos[0], newpos[1], winrect.width, winrect.height)) if pos.to(target) < self.stop_threshold: move(self.target) self.Stop() else: move( pos + (target - pos) * self.dampen )
[ "def", "Notify", "(", "self", ")", ":", "if", "not", "self", ":", "return", "if", "not", "self", ".", "window", ":", "return", "winrect", "=", "self", ".", "window", ".", "ScreenRect", "w", ",", "pos", ",", "target", "=", "self", ".", "window", ","...
https://github.com/ifwe/digsby/blob/f5fe00244744aa131e07f09348d10563f3d8fa99/digsby/src/gui/windowfx.py#L391-L407
bayotop/off-by-slash
01220cf49b53c2aec17cd9049d4c71e069a02207
off-by-slash.py
python
BurpExtender.isGet
(self, request)
return requestInfo.getMethod() == "GET"
[]
def isGet(self, request): requestInfo = self._helpers.analyzeRequest(request) return requestInfo.getMethod() == "GET"
[ "def", "isGet", "(", "self", ",", "request", ")", ":", "requestInfo", "=", "self", ".", "_helpers", ".", "analyzeRequest", "(", "request", ")", "return", "requestInfo", ".", "getMethod", "(", ")", "==", "\"GET\"" ]
https://github.com/bayotop/off-by-slash/blob/01220cf49b53c2aec17cd9049d4c71e069a02207/off-by-slash.py#L76-L78
saleor/saleor
2221bdf61b037c660ffc2d1efa484d8efe8172f5
saleor/warehouse/availability.py
python
check_preorder_threshold_in_orders
( variant: "ProductVariant", quantity: int, channel_slug: str, checkout_lines: Optional[Iterable["CheckoutLine"]], check_reservations: bool, )
Validate if there is preorder available for given variants in given country. It is used in orders, since it does not need additional logic related to limits. :raises InsufficientStock: when there is not enough items in stock for a variant.
Validate if there is preorder available for given variants in given country.
[ "Validate", "if", "there", "is", "preorder", "available", "for", "given", "variants", "in", "given", "country", "." ]
def check_preorder_threshold_in_orders( variant: "ProductVariant", quantity: int, channel_slug: str, checkout_lines: Optional[Iterable["CheckoutLine"]], check_reservations: bool, ): """Validate if there is preorder available for given variants in given country. It is used in orders, since it does not need additional logic related to limits. :raises InsufficientStock: when there is not enough items in stock for a variant. """ ( variants_channel_availability, variants_global_allocations, all_variants_channel_listings, variant_channels, ) = _get_variants_channel_availbility_info([variant], channel_slug) if check_reservations: listings_reservations = get_listings_reservations( checkout_lines, all_variants_channel_listings ) else: listings_reservations = defaultdict(int) insufficient_stocks: List[InsufficientStockData] = [] if ( variants_channel_availability[variant.id].preorder_quantity_threshold is not None ): channel_listing_id = variants_channel_availability[variant.id].listing_id available_channel_quantity = variants_channel_availability[ variant.id ].preorder_quantity available_channel_quantity -= listings_reservations[channel_listing_id] available_channel_quantity = max(available_channel_quantity, 0) if quantity > available_channel_quantity: insufficient_stocks.append( InsufficientStockData( variant=variant, available_quantity=available_channel_quantity ) ) if variant.preorder_global_threshold is not None: global_availability = variant.preorder_global_threshold global_availability -= variants_global_allocations[variant.id] for channel_listing in variant_channels[variant.id]: global_availability -= listings_reservations[channel_listing.id] global_availability = max(global_availability, 0) if quantity > global_availability: insufficient_stocks.append( InsufficientStockData( variant=variant, available_quantity=global_availability, ) ) if insufficient_stocks: raise InsufficientStock(insufficient_stocks)
[ "def", "check_preorder_threshold_in_orders", "(", "variant", ":", "\"ProductVariant\"", ",", "quantity", ":", "int", ",", "channel_slug", ":", "str", ",", "checkout_lines", ":", "Optional", "[", "Iterable", "[", "\"CheckoutLine\"", "]", "]", ",", "check_reservations...
https://github.com/saleor/saleor/blob/2221bdf61b037c660ffc2d1efa484d8efe8172f5/saleor/warehouse/availability.py#L325-L389
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/monitor/v20180724/models.py
python
DescribeAllNamespacesResponse.__init__
(self)
r""" :param QceNamespaces: 云产品的告警策略类型,已废弃 :type QceNamespaces: :class:`tencentcloud.monitor.v20180724.models.CommonNamespace` :param CustomNamespaces: 其他告警策略类型,已废弃 :type CustomNamespaces: :class:`tencentcloud.monitor.v20180724.models.CommonNamespace` :param QceNamespacesNew: 云产品的告警策略类型 :type QceNamespacesNew: list of CommonNamespace :param CustomNamespacesNew: 其他告警策略类型,暂不支持 :type CustomNamespacesNew: list of CommonNamespace :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
r""" :param QceNamespaces: 云产品的告警策略类型,已废弃 :type QceNamespaces: :class:`tencentcloud.monitor.v20180724.models.CommonNamespace` :param CustomNamespaces: 其他告警策略类型,已废弃 :type CustomNamespaces: :class:`tencentcloud.monitor.v20180724.models.CommonNamespace` :param QceNamespacesNew: 云产品的告警策略类型 :type QceNamespacesNew: list of CommonNamespace :param CustomNamespacesNew: 其他告警策略类型,暂不支持 :type CustomNamespacesNew: list of CommonNamespace :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
[ "r", ":", "param", "QceNamespaces", ":", "云产品的告警策略类型,已废弃", ":", "type", "QceNamespaces", ":", ":", "class", ":", "tencentcloud", ".", "monitor", ".", "v20180724", ".", "models", ".", "CommonNamespace", ":", "param", "CustomNamespaces", ":", "其他告警策略类型,已废弃", ":", ...
def __init__(self): r""" :param QceNamespaces: 云产品的告警策略类型,已废弃 :type QceNamespaces: :class:`tencentcloud.monitor.v20180724.models.CommonNamespace` :param CustomNamespaces: 其他告警策略类型,已废弃 :type CustomNamespaces: :class:`tencentcloud.monitor.v20180724.models.CommonNamespace` :param QceNamespacesNew: 云产品的告警策略类型 :type QceNamespacesNew: list of CommonNamespace :param CustomNamespacesNew: 其他告警策略类型,暂不支持 :type CustomNamespacesNew: list of CommonNamespace :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.QceNamespaces = None self.CustomNamespaces = None self.QceNamespacesNew = None self.CustomNamespacesNew = None self.RequestId = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "QceNamespaces", "=", "None", "self", ".", "CustomNamespaces", "=", "None", "self", ".", "QceNamespacesNew", "=", "None", "self", ".", "CustomNamespacesNew", "=", "None", "self", ".", "RequestId", "=", ...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/monitor/v20180724/models.py#L2674-L2691
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/setuptools/monkey.py
python
_patch_distribution_metadata_write_pkg_info
()
Workaround issue #197 - Python 3 prior to 3.2.2 uses an environment-local encoding to save the pkg_info. Monkey-patch its write_pkg_info method to correct this undesirable behavior.
Workaround issue #197 - Python 3 prior to 3.2.2 uses an environment-local encoding to save the pkg_info. Monkey-patch its write_pkg_info method to correct this undesirable behavior.
[ "Workaround", "issue", "#197", "-", "Python", "3", "prior", "to", "3", ".", "2", ".", "2", "uses", "an", "environment", "-", "local", "encoding", "to", "save", "the", "pkg_info", ".", "Monkey", "-", "patch", "its", "write_pkg_info", "method", "to", "corr...
def _patch_distribution_metadata_write_pkg_info(): """ Workaround issue #197 - Python 3 prior to 3.2.2 uses an environment-local encoding to save the pkg_info. Monkey-patch its write_pkg_info method to correct this undesirable behavior. """ environment_local = (3,) <= sys.version_info[:3] < (3, 2, 2) if not environment_local: return distutils.dist.DistributionMetadata.write_pkg_info = ( setuptools.dist.write_pkg_info )
[ "def", "_patch_distribution_metadata_write_pkg_info", "(", ")", ":", "environment_local", "=", "(", "3", ",", ")", "<=", "sys", ".", "version_info", "[", ":", "3", "]", "<", "(", "3", ",", "2", ",", "2", ")", "if", "not", "environment_local", ":", "retur...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/setuptools/monkey.py#L114-L126
aiidateam/aiida-core
c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2
aiida/orm/querybuilder.py
python
QueryBuilder.append
( self, cls: Optional[Union[EntityClsType, Sequence[EntityClsType]]] = None, entity_type: Optional[Union[str, Sequence[str]]] = None, tag: Optional[str] = None, filters: Optional[FilterType] = None, project: Optional[ProjectType] = None, subclassing: bool = True, edge_tag: Optional[str] = None, edge_filters: Optional[FilterType] = None, edge_project: Optional[ProjectType] = None, outerjoin: bool = False, joining_keyword: Optional[str] = None, joining_value: Optional[Any] = None, orm_base: Optional[str] = None, # pylint: disable=unused-argument **kwargs: Any )
return self
Any iterative procedure to build the path for a graph query needs to invoke this method to append to the path. :param cls: The Aiida-class (or backend-class) defining the appended vertice. Also supports a tuple/list of classes. This results in an all instances of this class being accepted in a query. However the classes have to have the same orm-class for the joining to work. I.e. both have to subclasses of Node. Valid is:: cls=(StructureData, Dict) This is invalid: cls=(Group, Node) :param entity_type: The node type of the class, if cls is not given. Also here, a tuple or list is accepted. :param tag: A unique tag. If none is given, I will create a unique tag myself. :param filters: Filters to apply for this vertex. See :meth:`.add_filter`, the method invoked in the background, or usage examples for details. :param project: Projections to apply. See usage examples for details. More information also in :meth:`.add_projection`. :param subclassing: Whether to include subclasses of the given class (default **True**). E.g. Specifying a ProcessNode as cls will include CalcJobNode, WorkChainNode, CalcFunctionNode, etc.. :param edge_tag: The tag that the edge will get. If nothing is specified (and there is a meaningful edge) the default is tag1--tag2 with tag1 being the entity joining from and tag2 being the entity joining to (this entity). :param edge_filters: The filters to apply on the edge. Also here, details in :meth:`.add_filter`. :param edge_project: The project from the edges. API-details in :meth:`.add_projection`. :param outerjoin: If True, (default is False), will do a left outerjoin instead of an inner join Joining can be specified in two ways: - Specifying the 'joining_keyword' and 'joining_value' arguments - Specify a single keyword argument The joining keyword wil be ``with_*`` or ``direction``, depending on the joining entity type. The joining value is the tag name or class of the entity to join to. A small usage example how this can be invoked:: qb = QueryBuilder() # Instantiating empty querybuilder instance qb.append(cls=StructureData) # First item is StructureData node # The # next node in the path is a PwCalculation, with # the structure joined as an input qb.append( cls=PwCalculation, with_incoming=StructureData ) :return: self
Any iterative procedure to build the path for a graph query needs to invoke this method to append to the path.
[ "Any", "iterative", "procedure", "to", "build", "the", "path", "for", "a", "graph", "query", "needs", "to", "invoke", "this", "method", "to", "append", "to", "the", "path", "." ]
def append( self, cls: Optional[Union[EntityClsType, Sequence[EntityClsType]]] = None, entity_type: Optional[Union[str, Sequence[str]]] = None, tag: Optional[str] = None, filters: Optional[FilterType] = None, project: Optional[ProjectType] = None, subclassing: bool = True, edge_tag: Optional[str] = None, edge_filters: Optional[FilterType] = None, edge_project: Optional[ProjectType] = None, outerjoin: bool = False, joining_keyword: Optional[str] = None, joining_value: Optional[Any] = None, orm_base: Optional[str] = None, # pylint: disable=unused-argument **kwargs: Any ) -> 'QueryBuilder': """ Any iterative procedure to build the path for a graph query needs to invoke this method to append to the path. :param cls: The Aiida-class (or backend-class) defining the appended vertice. Also supports a tuple/list of classes. This results in an all instances of this class being accepted in a query. However the classes have to have the same orm-class for the joining to work. I.e. both have to subclasses of Node. Valid is:: cls=(StructureData, Dict) This is invalid: cls=(Group, Node) :param entity_type: The node type of the class, if cls is not given. Also here, a tuple or list is accepted. :param tag: A unique tag. If none is given, I will create a unique tag myself. :param filters: Filters to apply for this vertex. See :meth:`.add_filter`, the method invoked in the background, or usage examples for details. :param project: Projections to apply. See usage examples for details. More information also in :meth:`.add_projection`. :param subclassing: Whether to include subclasses of the given class (default **True**). E.g. Specifying a ProcessNode as cls will include CalcJobNode, WorkChainNode, CalcFunctionNode, etc.. :param edge_tag: The tag that the edge will get. If nothing is specified (and there is a meaningful edge) the default is tag1--tag2 with tag1 being the entity joining from and tag2 being the entity joining to (this entity). :param edge_filters: The filters to apply on the edge. Also here, details in :meth:`.add_filter`. :param edge_project: The project from the edges. API-details in :meth:`.add_projection`. :param outerjoin: If True, (default is False), will do a left outerjoin instead of an inner join Joining can be specified in two ways: - Specifying the 'joining_keyword' and 'joining_value' arguments - Specify a single keyword argument The joining keyword wil be ``with_*`` or ``direction``, depending on the joining entity type. The joining value is the tag name or class of the entity to join to. A small usage example how this can be invoked:: qb = QueryBuilder() # Instantiating empty querybuilder instance qb.append(cls=StructureData) # First item is StructureData node # The # next node in the path is a PwCalculation, with # the structure joined as an input qb.append( cls=PwCalculation, with_incoming=StructureData ) :return: self """ # pylint: disable=too-many-arguments,too-many-locals,too-many-branches,too-many-statements # INPUT CHECKS ########################## # This function can be called by users, so I am checking the input now. # First of all, let's make sure the specified the class or the type (not both) if cls is not None and entity_type is not None: raise ValueError(f'You cannot specify both a class ({cls}) and a entity_type ({entity_type})') if cls is None and entity_type is None: raise ValueError('You need to specify at least a class or a entity_type') # Let's check if it is a valid class or type if cls: if isinstance(cls, (list, tuple)): for sub_cls in cls: if not inspect_isclass(sub_cls): raise TypeError(f"{sub_cls} was passed with kw 'cls', but is not a class") elif not inspect_isclass(cls): raise TypeError(f"{cls} was passed with kw 'cls', but is not a class") elif entity_type is not None: if isinstance(entity_type, (list, tuple)): for sub_type in entity_type: if not isinstance(sub_type, str): raise TypeError(f'{sub_type} was passed as entity_type, but is not a string') elif not isinstance(entity_type, str): raise TypeError(f'{entity_type} was passed as entity_type, but is not a string') ormclass, classifiers = _get_ormclass(cls, entity_type) # TAG ################################# # Let's get a tag if tag: if self._EDGE_TAG_DELIM in tag: raise ValueError( f'tag cannot contain {self._EDGE_TAG_DELIM}\nsince this is used as a delimiter for links' ) if tag in self._tags: raise ValueError(f'This tag ({tag}) is already in use') else: tag = self._get_unique_tag(classifiers) # Checks complete # This is where I start doing changes to self! # Now, several things can go wrong along the way, so I need to split into # atomic blocks that I can reverse if something goes wrong. # TAG ALIASING ############################## try: self._tags.add(tag, ormclass, cls) except Exception as exception: self.debug('Exception caught in append, cleaning up: %s', exception) self._tags.remove(tag) raise # FILTERS ###################################### try: self._filters[tag] = {} # Subclassing is currently only implemented for the `Node` and `Group` classes. # So for those cases we need to construct the correct filters, # corresponding to the provided classes and value of `subclassing`. if ormclass == EntityTypes.NODE: self._add_node_type_filter(tag, classifiers, subclassing) self._add_process_type_filter(tag, classifiers, subclassing) elif ormclass == EntityTypes.GROUP: self._add_group_type_filter(tag, classifiers, subclassing) # The order has to be first _add_node_type_filter and then add_filter. # If the user adds a query on the type column, it overwrites what I did # if the user specified a filter, add it: if filters is not None: self.add_filter(tag, filters) except Exception as exception: self.debug('Exception caught in append, cleaning up: %s', exception) self._tags.remove(tag) self._filters.pop(tag) raise # PROJECTIONS ############################## try: self._projections[tag] = [] if project is not None: self.add_projection(tag, project) except Exception as exception: self.debug('Exception caught in append, cleaning up: %s', exception) self._tags.remove(tag) self._filters.pop(tag) self._projections.pop(tag) raise exception # JOINING ##################################### # pylint: disable=too-many-nested-blocks try: # Get the functions that are implemented: spec_to_function_map = set(EntityRelationships[ormclass.value]) if ormclass == EntityTypes.NODE: # 'direction 'was an old implementation, which is now converted below to with_outgoing or with_incoming spec_to_function_map.add('direction') for key, val in kwargs.items(): if key not in spec_to_function_map: raise ValueError( f"'{key}' is not a valid keyword for {ormclass.value!r} joining specification\n" f'Valid keywords are: {spec_to_function_map or []!r}' ) if joining_keyword: raise ValueError( 'You already specified joining specification {}\n' 'But you now also want to specify {}' ''.format(joining_keyword, key) ) joining_keyword = key if joining_keyword == 'direction': if not isinstance(val, int): raise TypeError('direction=n expects n to be an integer') try: if val < 0: joining_keyword = 'with_outgoing' elif val > 0: joining_keyword = 'with_incoming' else: raise ValueError('direction=0 is not valid') joining_value = self._path[-abs(val)]['tag'] except IndexError as exc: raise ValueError( f'You have specified a non-existent entity with\ndirection={joining_value}\n{exc}\n' ) else: joining_value = self._tags.get(val) if joining_keyword is None and len(self._path) > 0: # the default is that this vertice is 'with_incoming' as the previous one if ormclass == EntityTypes.NODE: joining_keyword = 'with_incoming' else: joining_keyword = 'with_node' joining_value = self._path[-1]['tag'] except Exception as exception: self.debug('Exception caught in append (part filters), cleaning up: %s', exception) self._tags.remove(tag) self._filters.pop(tag) self._projections.pop(tag) # There's not more to clean up here! raise exception # EDGES ################################# if len(self._path) > 0: joining_value = cast(str, joining_value) try: if edge_tag is None: edge_destination_tag = self._tags.get(joining_value) edge_tag = edge_destination_tag + self._EDGE_TAG_DELIM + tag else: if edge_tag in self._tags: raise ValueError(f'The tag {edge_tag} is already in use') self.debug('edge_tag chosen: %s', edge_tag) # edge tags do not have an ormclass self._tags.add(edge_tag) # Filters on links: # Beware, I alway add this entry now, but filtering here might be # non-sensical, since this ONLY works for m2m relationship where # I go through a different table self._filters[edge_tag] = {} if edge_filters is not None: self.add_filter(edge_tag, edge_filters) # Projections on links self._projections[edge_tag] = [] if edge_project is not None: self.add_projection(edge_tag, edge_project) except Exception as exception: self.debug('Exception caught in append (part joining), cleaning up %s', exception) self._tags.remove(tag) self._filters.pop(tag) self._projections.pop(tag) if edge_tag is not None: self._tags.remove(edge_tag) self._filters.pop(edge_tag, None) self._projections.pop(edge_tag, None) # There's not more to clean up here! raise exception # EXTENDING THE PATH ################################# # Note: 'type' being a list is a relict of an earlier implementation # Could simply pass all classifiers here. path_type: Union[List[str], str] if len(classifiers) > 1: path_type = [c.ormclass_type_string for c in classifiers] else: path_type = classifiers[0].ormclass_type_string self._path.append( dict( entity_type=path_type, orm_base=ormclass.value, # type: ignore[typeddict-item] tag=tag, # for the first item joining_keyword/joining_value can be None, # but after they always default to 'with_incoming' of the previous item joining_keyword=joining_keyword, # type: ignore joining_value=joining_value, # type: ignore # same for edge_tag for which a default is applied edge_tag=edge_tag, # type: ignore outerjoin=outerjoin, ) ) return self
[ "def", "append", "(", "self", ",", "cls", ":", "Optional", "[", "Union", "[", "EntityClsType", ",", "Sequence", "[", "EntityClsType", "]", "]", "]", "=", "None", ",", "entity_type", ":", "Optional", "[", "Union", "[", "str", ",", "Sequence", "[", "str"...
https://github.com/aiidateam/aiida-core/blob/c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2/aiida/orm/querybuilder.py#L274-L561
OpenNMT/OpenNMT-py
4815f07fcd482af9a1fe1d3b620d144197178bc5
onmt/modules/weight_norm.py
python
WeightNormConv2d.reset_parameters
(self)
return
[]
def reset_parameters(self): return
[ "def", "reset_parameters", "(", "self", ")", ":", "return" ]
https://github.com/OpenNMT/OpenNMT-py/blob/4815f07fcd482af9a1fe1d3b620d144197178bc5/onmt/modules/weight_norm.py#L121-L122
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/pypy-go-no-layout-change-timed.py
python
EmptySet.add
(self, pos)
[]
def add(self, pos): self.empty_pos[pos] = len(self.empties) self.empties.append(pos)
[ "def", "add", "(", "self", ",", "pos", ")", ":", "self", ".", "empty_pos", "[", "pos", "]", "=", "len", "(", "self", ".", "empties", ")", "self", ".", "empties", ".", "append", "(", "pos", ")" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/pypy-go-no-layout-change-timed.py#L117-L119
MitjaNemec/Kicad_action_plugins
0994a10808687fbcffcb0eba507fa9bd8422ae19
replicate_layout/replicatelayout.py
python
Replicator.get_module_id
(module)
return module_id
get module id
get module id
[ "get", "module", "id" ]
def get_module_id(module): """ get module id """ module_path = get_path(module).split('/') module_id = "/".join(module_path[-1:]) return module_id
[ "def", "get_module_id", "(", "module", ")", ":", "module_path", "=", "get_path", "(", "module", ")", ".", "split", "(", "'/'", ")", "module_id", "=", "\"/\"", ".", "join", "(", "module_path", "[", "-", "1", ":", "]", ")", "return", "module_id" ]
https://github.com/MitjaNemec/Kicad_action_plugins/blob/0994a10808687fbcffcb0eba507fa9bd8422ae19/replicate_layout/replicatelayout.py#L180-L184
jacobandreas/nmn2
7e42dd98420f9580fd34185ba670490a5d86fb04
models/nmn.py
python
Module.__str__
(self)
return self.__class__.__name__
[]
def __str__(self): return self.__class__.__name__
[ "def", "__str__", "(", "self", ")", ":", "return", "self", ".", "__class__", ".", "__name__" ]
https://github.com/jacobandreas/nmn2/blob/7e42dd98420f9580fd34185ba670490a5d86fb04/models/nmn.py#L22-L23
netbox-community/netbox
50309d3ab3da2212343e1d9feaf47e497df9c3cb
netbox/utilities/choices.py
python
unpack_grouped_choices
(choices)
return unpacked_choices
Unpack a grouped choices hierarchy into a flat list of two-tuples. For example: choices = ( ('Foo', ( (1, 'A'), (2, 'B') )), ('Bar', ( (3, 'C'), (4, 'D') )) ) becomes: choices = ( (1, 'A'), (2, 'B'), (3, 'C'), (4, 'D') )
Unpack a grouped choices hierarchy into a flat list of two-tuples. For example:
[ "Unpack", "a", "grouped", "choices", "hierarchy", "into", "a", "flat", "list", "of", "two", "-", "tuples", ".", "For", "example", ":" ]
def unpack_grouped_choices(choices): """ Unpack a grouped choices hierarchy into a flat list of two-tuples. For example: choices = ( ('Foo', ( (1, 'A'), (2, 'B') )), ('Bar', ( (3, 'C'), (4, 'D') )) ) becomes: choices = ( (1, 'A'), (2, 'B'), (3, 'C'), (4, 'D') ) """ unpacked_choices = [] for key, value in choices: if isinstance(value, (list, tuple)): # Entered an optgroup for optgroup_key, optgroup_value in value: unpacked_choices.append((optgroup_key, optgroup_value)) else: unpacked_choices.append((key, value)) return unpacked_choices
[ "def", "unpack_grouped_choices", "(", "choices", ")", ":", "unpacked_choices", "=", "[", "]", "for", "key", ",", "value", "in", "choices", ":", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "# Entered an optgroup", "for",...
https://github.com/netbox-community/netbox/blob/50309d3ab3da2212343e1d9feaf47e497df9c3cb/netbox/utilities/choices.py#L28-L60
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/userreports/reports/builder/forms.py
python
ConfigureNewReportBase.__init__
(self, domain, report_name, app_id, source_type, report_source_id, existing_report=None, registry_slug=None, *args, **kwargs)
This form can be used to create a new ReportConfiguration, or to modify an existing one if existing_report is set.
This form can be used to create a new ReportConfiguration, or to modify an existing one if existing_report is set.
[ "This", "form", "can", "be", "used", "to", "create", "a", "new", "ReportConfiguration", "or", "to", "modify", "an", "existing", "one", "if", "existing_report", "is", "set", "." ]
def __init__(self, domain, report_name, app_id, source_type, report_source_id, existing_report=None, registry_slug=None, *args, **kwargs): """ This form can be used to create a new ReportConfiguration, or to modify an existing one if existing_report is set. """ super(ConfigureNewReportBase, self).__init__(*args, **kwargs) self.existing_report = existing_report self.domain = domain if self.existing_report: self._bootstrap(self.existing_report) else: self.registry_slug = registry_slug self.report_name = report_name assert source_type in REPORT_BUILDER_DATA_SOURCE_TYPE_VALUES self.source_type = source_type self.report_source_id = report_source_id self.app = Application.get(app_id) if app_id else None if self.app: assert self.domain == self.app.domain self.ds_builder = get_data_source_interface( self.domain, self.app, self.source_type, self.report_source_id, self.registry_slug ) self.report_column_options = self.ds_builder.report_column_options self.data_source_properties = self.ds_builder.data_source_properties self._report_columns_by_column_id = {} for column in self.report_column_options.values(): for agg in column.aggregation_options: indicators = column.get_indicators(agg) for i in indicators: self._report_columns_by_column_id[i['column_id']] = column
[ "def", "__init__", "(", "self", ",", "domain", ",", "report_name", ",", "app_id", ",", "source_type", ",", "report_source_id", ",", "existing_report", "=", "None", ",", "registry_slug", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "s...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/userreports/reports/builder/forms.py#L1096-L1130
pjlantz/Hale
5c4c96f18f9a7ed0362e115007813c0b56dc3853
src/utils/socks5.py
python
ClientFactory.onTimeout
(self, connector)
Timeout occured, can't continue and should stop immediately and unconditionally in the whatever state I am.
Timeout occured, can't continue and should stop immediately and unconditionally in the whatever state I am.
[ "Timeout", "occured", "can", "t", "continue", "and", "should", "stop", "immediately", "and", "unconditionally", "in", "the", "whatever", "state", "I", "am", "." ]
def onTimeout (self, connector): """ Timeout occured, can't continue and should stop immediately and unconditionally in the whatever state I am. """ connector.disconnect() #log.msg ("%s timeout %d sec" % (self, self.timeout)) self.clientConnectionFailed (self, failure.Failure ( GlobalTimeoutError ("Timeout %s" % self)))
[ "def", "onTimeout", "(", "self", ",", "connector", ")", ":", "connector", ".", "disconnect", "(", ")", "#log.msg (\"%s timeout %d sec\" % (self, self.timeout))", "self", ".", "clientConnectionFailed", "(", "self", ",", "failure", ".", "Failure", "(", "GlobalTimeoutErr...
https://github.com/pjlantz/Hale/blob/5c4c96f18f9a7ed0362e115007813c0b56dc3853/src/utils/socks5.py#L324-L331
paarthneekhara/text-to-image
b5475c140ecb254096c493850ae09c1bc9da8f7a
Python 3 Codes/skipthoughts.py
python
nn_words
(table, wordvecs, query, k=10)
Get the nearest neighbour words
Get the nearest neighbour words
[ "Get", "the", "nearest", "neighbour", "words" ]
def nn_words(table, wordvecs, query, k=10): """ Get the nearest neighbour words """ keys = list(table.keys()) qf = table[query] scores = numpy.dot(qf, wordvecs.T).flatten() sorted_args = numpy.argsort(scores)[::-1] words = [keys[a] for a in sorted_args[:k]] print(('QUERY: ' + query)) print('NEAREST: ') for i, w in enumerate(words): print(w)
[ "def", "nn_words", "(", "table", ",", "wordvecs", ",", "query", ",", "k", "=", "10", ")", ":", "keys", "=", "list", "(", "table", ".", "keys", "(", ")", ")", "qf", "=", "table", "[", "query", "]", "scores", "=", "numpy", ".", "dot", "(", "qf", ...
https://github.com/paarthneekhara/text-to-image/blob/b5475c140ecb254096c493850ae09c1bc9da8f7a/Python 3 Codes/skipthoughts.py#L201-L213
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/states/kubernetes.py
python
configmap_present
( name, namespace="default", data=None, source=None, template=None, **kwargs )
return ret
Ensures that the named configmap is present inside of the specified namespace with the given data. If the configmap exists it will be replaced. name The name of the configmap. namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the configmaps. source A file containing the data of the configmap in plain format. template Template engine to be used to render the source file.
Ensures that the named configmap is present inside of the specified namespace with the given data. If the configmap exists it will be replaced.
[ "Ensures", "that", "the", "named", "configmap", "is", "present", "inside", "of", "the", "specified", "namespace", "with", "the", "given", "data", ".", "If", "the", "configmap", "exists", "it", "will", "be", "replaced", "." ]
def configmap_present( name, namespace="default", data=None, source=None, template=None, **kwargs ): """ Ensures that the named configmap is present inside of the specified namespace with the given data. If the configmap exists it will be replaced. name The name of the configmap. namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the configmaps. source A file containing the data of the configmap in plain format. template Template engine to be used to render the source file. """ ret = {"name": name, "changes": {}, "result": False, "comment": ""} if data and source: return _error(ret, "'source' cannot be used in combination with 'data'") elif data is None: data = {} configmap = __salt__["kubernetes.show_configmap"](name, namespace, **kwargs) if configmap is None: if __opts__["test"]: ret["result"] = None ret["comment"] = "The configmap is going to be created" return ret res = __salt__["kubernetes.create_configmap"]( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs ) ret["changes"]["{}.{}".format(namespace, name)] = {"old": {}, "new": res} else: if __opts__["test"]: ret["result"] = None ret["comment"] = "The configmap is going to be replaced" return ret # TODO: improve checks # pylint: disable=fixme log.info("Forcing the recreation of the service") ret["comment"] = "The configmap is already present. Forcing recreation" res = __salt__["kubernetes.replace_configmap"]( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs ) ret["changes"] = {"data": res["data"]} ret["result"] = True return ret
[ "def", "configmap_present", "(", "name", ",", "namespace", "=", "\"default\"", ",", "data", "=", "None", ",", "source", "=", "None", ",", "template", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "\"name\"", ":", "name", ",", "\"ch...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/states/kubernetes.py#L578-L647
Pagure/pagure
512f23f5cd1f965276969747792edeb1215cba68
pagure/cli/admin.py
python
do_refresh_ssh
(_)
Regenerate the user key files. :arg _: the argparse object returned by ``parse_arguments()``, which is ignored as there are no argument to pass to this action.
Regenerate the user key files.
[ "Regenerate", "the", "user", "key", "files", "." ]
def do_refresh_ssh(_): """Regenerate the user key files. :arg _: the argparse object returned by ``parse_arguments()``, which is ignored as there are no argument to pass to this action. """ print( "Do you want to re-generate all the ssh keys for every user in " "the database? (Depending on your instance this may take a while " "and result in an outage while it lasts)" ) if _ask_confirmation(): generate_user_key_files() print("User key files regenerated") do_generate_acl()
[ "def", "do_refresh_ssh", "(", "_", ")", ":", "print", "(", "\"Do you want to re-generate all the ssh keys for every user in \"", "\"the database? (Depending on your instance this may take a while \"", "\"and result in an outage while it lasts)\"", ")", "if", "_ask_confirmation", "(", "...
https://github.com/Pagure/pagure/blob/512f23f5cd1f965276969747792edeb1215cba68/pagure/cli/admin.py#L688-L703
stellargraph/stellargraph
3c2c8c18ab4c5c16660f350d8e23d7dc39e738de
scripts/notebook_text_checker.py
python
MarkdownCell.lines
(self, sourcepos)
return number_lines(lines, one_based_start)
Retrieve the lines corresponding to the 'sourcepos' range. Args: sourcepos: pair of pairs [[start line, start column], [end line, end column]], with one based lines and columns (the same as a commonmark's Node.sourcepos property)
Retrieve the lines corresponding to the 'sourcepos' range.
[ "Retrieve", "the", "lines", "corresponding", "to", "the", "sourcepos", "range", "." ]
def lines(self, sourcepos): """ Retrieve the lines corresponding to the 'sourcepos' range. Args: sourcepos: pair of pairs [[start line, start column], [end line, end column]], with one based lines and columns (the same as a commonmark's Node.sourcepos property) """ one_based_start = sourcepos[0][0] # the commonmark sourcepos's are one based, so slicing needs an offset start = one_based_start - 1 end = sourcepos[1][0] - 1 # we want to include the end line lines = self._lines[start : end + 1] return number_lines(lines, one_based_start)
[ "def", "lines", "(", "self", ",", "sourcepos", ")", ":", "one_based_start", "=", "sourcepos", "[", "0", "]", "[", "0", "]", "# the commonmark sourcepos's are one based, so slicing needs an offset", "start", "=", "one_based_start", "-", "1", "end", "=", "sourcepos", ...
https://github.com/stellargraph/stellargraph/blob/3c2c8c18ab4c5c16660f350d8e23d7dc39e738de/scripts/notebook_text_checker.py#L74-L89
hak5/nano-tetra-modules
aa43cb5e2338b8dbd12a75314104a34ba608263b
Responder/dep/responder/tools/MultiRelay/creddump/framework/newobj.py
python
Obj.values
(self)
return valdict
Return a dictionary of this object's members and their values
Return a dictionary of this object's members and their values
[ "Return", "a", "dictionary", "of", "this", "object", "s", "members", "and", "their", "values" ]
def values(self): """Return a dictionary of this object's members and their values""" valdict = {} for k in self.members(): valdict[k] = getattr(self, k) return valdict
[ "def", "values", "(", "self", ")", ":", "valdict", "=", "{", "}", "for", "k", "in", "self", ".", "members", "(", ")", ":", "valdict", "[", "k", "]", "=", "getattr", "(", "self", ",", "k", ")", "return", "valdict" ]
https://github.com/hak5/nano-tetra-modules/blob/aa43cb5e2338b8dbd12a75314104a34ba608263b/Responder/dep/responder/tools/MultiRelay/creddump/framework/newobj.py#L123-L129
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/django/views/generic/dates.py
python
BaseDateListView.get_date_list_period
(self)
return self.date_list_period
Get the aggregation period for the list of dates: 'year', 'month', or 'day'.
Get the aggregation period for the list of dates: 'year', 'month', or 'day'.
[ "Get", "the", "aggregation", "period", "for", "the", "list", "of", "dates", ":", "year", "month", "or", "day", "." ]
def get_date_list_period(self): """ Get the aggregation period for the list of dates: 'year', 'month', or 'day'. """ return self.date_list_period
[ "def", "get_date_list_period", "(", "self", ")", ":", "return", "self", ".", "date_list_period" ]
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/django/views/generic/dates.py#L374-L378
Kismuz/btgym
7fb3316e67f1d7a17c620630fb62fb29428b2cec
btgym/research/model_based/model/bivariate.py
python
BivariateTSModel.generate
(self, batch_size, size, state=None, reconstruct=True)
return self.generate_bivariate_trajectory_fn(batch_size, size, state, reconstruct, self.u_recon)
Generates batch of time-series realisations given model state. Args: batch_size: uint, number of trajectories to generates size: uint, trajectory length to generate state: instance of BivariateTSModelState or None; if no state provided - current state is used. reconstruct: bool, if True - return time-series along with P, S trajectories, return None otherwise Returns: generated P and S processes realisations of size [batch_size, 2, size]; generated time-series reconstructions of size [batch_size, 2, size] or None;
Generates batch of time-series realisations given model state.
[ "Generates", "batch", "of", "time", "-", "series", "realisations", "given", "model", "state", "." ]
def generate(self, batch_size, size, state=None, reconstruct=True): """ Generates batch of time-series realisations given model state. Args: batch_size: uint, number of trajectories to generates size: uint, trajectory length to generate state: instance of BivariateTSModelState or None; if no state provided - current state is used. reconstruct: bool, if True - return time-series along with P, S trajectories, return None otherwise Returns: generated P and S processes realisations of size [batch_size, 2, size]; generated time-series reconstructions of size [batch_size, 2, size] or None; """ if state is None: # Fit student-t df: _ = self.p.process.driver_estimator.fit() _ = self.s.process.driver_estimator.fit() state = self.get_state() # return self.generate_trajectory_fn(batch_size, size, state, reconstruct, self.u_recon) return self.generate_bivariate_trajectory_fn(batch_size, size, state, reconstruct, self.u_recon)
[ "def", "generate", "(", "self", ",", "batch_size", ",", "size", ",", "state", "=", "None", ",", "reconstruct", "=", "True", ")", ":", "if", "state", "is", "None", ":", "# Fit student-t df:", "_", "=", "self", ".", "p", ".", "process", ".", "driver_esti...
https://github.com/Kismuz/btgym/blob/7fb3316e67f1d7a17c620630fb62fb29428b2cec/btgym/research/model_based/model/bivariate.py#L470-L493
RasaHQ/rasa
54823b68c1297849ba7ae841a4246193cd1223a1
rasa/utils/tensorflow/rasa_layers.py
python
RasaFeatureCombiningLayer.call
( self, inputs: Tuple[ List[Union[tf.Tensor, tf.SparseTensor]], List[Union[tf.Tensor, tf.SparseTensor]], tf.Tensor, ], training: bool = False, )
return features_to_return, mask_combined_sequence_sentence
Combines multiple 3-D dense/sparse feature tensors into one. Arguments: inputs: Tuple containing: sequence_features: Dense or sparse tensors representing different token-level features. sentence_features: Dense or sparse tensors representing sentence-level features. sequence_feature_lengths: A tensor containing the real sequence length (the number of real -- not padding -- tokens) for each example in the batch. training: A flag indicating whether the layer should behave in training mode (applying dropout to sparse tensors if applicable) or in inference mode (not applying dropout). Returns: combined features: A tensor containing all the features combined. mask_combined_sequence_sentence: A binary mask with 1s in place of real features in the combined feature tensor, and 0s in padded positions with fake features.
Combines multiple 3-D dense/sparse feature tensors into one.
[ "Combines", "multiple", "3", "-", "D", "dense", "/", "sparse", "feature", "tensors", "into", "one", "." ]
def call( self, inputs: Tuple[ List[Union[tf.Tensor, tf.SparseTensor]], List[Union[tf.Tensor, tf.SparseTensor]], tf.Tensor, ], training: bool = False, ) -> Tuple[tf.Tensor, tf.Tensor]: """Combines multiple 3-D dense/sparse feature tensors into one. Arguments: inputs: Tuple containing: sequence_features: Dense or sparse tensors representing different token-level features. sentence_features: Dense or sparse tensors representing sentence-level features. sequence_feature_lengths: A tensor containing the real sequence length (the number of real -- not padding -- tokens) for each example in the batch. training: A flag indicating whether the layer should behave in training mode (applying dropout to sparse tensors if applicable) or in inference mode (not applying dropout). Returns: combined features: A tensor containing all the features combined. mask_combined_sequence_sentence: A binary mask with 1s in place of real features in the combined feature tensor, and 0s in padded positions with fake features. """ sequence_features = inputs[0] sentence_features = inputs[1] sequence_feature_lengths = inputs[2] # This mask is specifically for sequence-level features. mask_sequence = compute_mask(sequence_feature_lengths) sequence_features_combined = self._combine_sequence_level_features( sequence_features, mask_sequence, training ) ( sentence_features_combined, combined_sequence_sentence_feature_lengths, ) = self._combine_sentence_level_features( sentence_features, sequence_feature_lengths, training ) mask_combined_sequence_sentence = compute_mask( combined_sequence_sentence_feature_lengths ) # If both feature types are present, combine them. Otherwise, just the present # feature type will be returned. if ( sequence_features_combined is not None and sentence_features_combined is not None ): features_to_return = self._concat_sequence_sentence_features( sequence_features_combined, sentence_features_combined, mask_combined_sequence_sentence, ) elif sequence_features_combined is not None: features_to_return = sequence_features_combined else: features_to_return = sentence_features_combined return features_to_return, mask_combined_sequence_sentence
[ "def", "call", "(", "self", ",", "inputs", ":", "Tuple", "[", "List", "[", "Union", "[", "tf", ".", "Tensor", ",", "tf", ".", "SparseTensor", "]", "]", ",", "List", "[", "Union", "[", "tf", ".", "Tensor", ",", "tf", ".", "SparseTensor", "]", "]",...
https://github.com/RasaHQ/rasa/blob/54823b68c1297849ba7ae841a4246193cd1223a1/rasa/utils/tensorflow/rasa_layers.py#L608-L676
wulczer/txpostgres
bd56a3648574bfd0c24543e4d9e4a611458c2da1
txpostgres/reconnection.py
python
DeadConnectionDetector.setReconnectable
(self, reconnectable, *connargs, **connkw)
Register a reconnectable with the detector. Needs to be called before the detector will be used. The remaining arguments will be passed to the reconnectable's `connect` method on each reconnection. :param reconnectable: An object to be reconnected. It should provide a `connect` and a `close` method. :type reconnectable: :class:`object`
Register a reconnectable with the detector. Needs to be called before the detector will be used. The remaining arguments will be passed to the reconnectable's `connect` method on each reconnection.
[ "Register", "a", "reconnectable", "with", "the", "detector", ".", "Needs", "to", "be", "called", "before", "the", "detector", "will", "be", "used", ".", "The", "remaining", "arguments", "will", "be", "passed", "to", "the", "reconnectable", "s", "connect", "m...
def setReconnectable(self, reconnectable, *connargs, **connkw): """ Register a reconnectable with the detector. Needs to be called before the detector will be used. The remaining arguments will be passed to the reconnectable's `connect` method on each reconnection. :param reconnectable: An object to be reconnected. It should provide a `connect` and a `close` method. :type reconnectable: :class:`object` """ self.reconnectable = reconnectable self._connargs = connargs self._connkw = connkw
[ "def", "setReconnectable", "(", "self", ",", "reconnectable", ",", "*", "connargs", ",", "*", "*", "connkw", ")", ":", "self", ".", "reconnectable", "=", "reconnectable", "self", ".", "_connargs", "=", "connargs", "self", ".", "_connkw", "=", "connkw" ]
https://github.com/wulczer/txpostgres/blob/bd56a3648574bfd0c24543e4d9e4a611458c2da1/txpostgres/reconnection.py#L105-L117
google-research/planet
c04226b6db136f5269625378cd6a0aa875a92842
planet/training/running.py
python
Run._read_ping
(self)
Read the duration since the last PING was written. Returns: Tuple of worker who wrote the last ping and duration until then. Raises: WorkerConflict: If file operations fail due to concurrent file access.
Read the duration since the last PING was written.
[ "Read", "the", "duration", "since", "the", "last", "PING", "was", "written", "." ]
def _read_ping(self): """Read the duration since the last PING was written. Returns: Tuple of worker who wrote the last ping and duration until then. Raises: WorkerConflict: If file operations fail due to concurrent file access. """ if not tf.gfile.Exists(os.path.join(self._logdir, 'PING')): return None, None try: with tf.gfile.Open(os.path.join(self._logdir, 'PING'), 'rb') as file_: last_worker, last_ping = pickle.load(file_) duration = (datetime.datetime.utcnow() - last_ping).total_seconds() return last_worker, duration except (EOFError, IOError, tf.errors.NotFoundError): raise WorkerConflict
[ "def", "_read_ping", "(", "self", ")", ":", "if", "not", "tf", ".", "gfile", ".", "Exists", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_logdir", ",", "'PING'", ")", ")", ":", "return", "None", ",", "None", "try", ":", "with", "tf", ...
https://github.com/google-research/planet/blob/c04226b6db136f5269625378cd6a0aa875a92842/planet/training/running.py#L286-L303
facebookresearch/fastMRI
13560d2f198cc72f06e01675e9ecee509ce5639a
fastmri/evaluate.py
python
ssim
( gt: np.ndarray, pred: np.ndarray, maxval: Optional[float] = None )
return ssim / gt.shape[0]
Compute Structural Similarity Index Metric (SSIM)
Compute Structural Similarity Index Metric (SSIM)
[ "Compute", "Structural", "Similarity", "Index", "Metric", "(", "SSIM", ")" ]
def ssim( gt: np.ndarray, pred: np.ndarray, maxval: Optional[float] = None ) -> np.ndarray: """Compute Structural Similarity Index Metric (SSIM)""" if not gt.ndim == 3: raise ValueError("Unexpected number of dimensions in ground truth.") if not gt.ndim == pred.ndim: raise ValueError("Ground truth dimensions does not match pred.") maxval = gt.max() if maxval is None else maxval ssim = np.array([0]) for slice_num in range(gt.shape[0]): ssim = ssim + structural_similarity( gt[slice_num], pred[slice_num], data_range=maxval ) return ssim / gt.shape[0]
[ "def", "ssim", "(", "gt", ":", "np", ".", "ndarray", ",", "pred", ":", "np", ".", "ndarray", ",", "maxval", ":", "Optional", "[", "float", "]", "=", "None", ")", "->", "np", ".", "ndarray", ":", "if", "not", "gt", ".", "ndim", "==", "3", ":", ...
https://github.com/facebookresearch/fastMRI/blob/13560d2f198cc72f06e01675e9ecee509ce5639a/fastmri/evaluate.py#L40-L57
python/cpython
e13cdca0f5224ec4e23bdd04bb3120506964bc8b
Lib/email/generator.py
python
Generator.__init__
(self, outfp, mangle_from_=None, maxheaderlen=None, *, policy=None)
Create the generator for message flattening. outfp is the output file-like object for writing the message to. It must have a write() method. Optional mangle_from_ is a flag that, when True (the default if policy is not set), escapes From_ lines in the body of the message by putting a `>' in front of them. Optional maxheaderlen specifies the longest length for a non-continued header. When a header line is longer (in characters, with tabs expanded to 8 spaces) than maxheaderlen, the header will split as defined in the Header class. Set maxheaderlen to zero to disable header wrapping. The default is 78, as recommended (but not required) by RFC 2822. The policy keyword specifies a policy object that controls a number of aspects of the generator's operation. If no policy is specified, the policy associated with the Message object passed to the flatten method is used.
Create the generator for message flattening.
[ "Create", "the", "generator", "for", "message", "flattening", "." ]
def __init__(self, outfp, mangle_from_=None, maxheaderlen=None, *, policy=None): """Create the generator for message flattening. outfp is the output file-like object for writing the message to. It must have a write() method. Optional mangle_from_ is a flag that, when True (the default if policy is not set), escapes From_ lines in the body of the message by putting a `>' in front of them. Optional maxheaderlen specifies the longest length for a non-continued header. When a header line is longer (in characters, with tabs expanded to 8 spaces) than maxheaderlen, the header will split as defined in the Header class. Set maxheaderlen to zero to disable header wrapping. The default is 78, as recommended (but not required) by RFC 2822. The policy keyword specifies a policy object that controls a number of aspects of the generator's operation. If no policy is specified, the policy associated with the Message object passed to the flatten method is used. """ if mangle_from_ is None: mangle_from_ = True if policy is None else policy.mangle_from_ self._fp = outfp self._mangle_from_ = mangle_from_ self.maxheaderlen = maxheaderlen self.policy = policy
[ "def", "__init__", "(", "self", ",", "outfp", ",", "mangle_from_", "=", "None", ",", "maxheaderlen", "=", "None", ",", "*", ",", "policy", "=", "None", ")", ":", "if", "mangle_from_", "is", "None", ":", "mangle_from_", "=", "True", "if", "policy", "is"...
https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/email/generator.py#L36-L66
python-telegram-bot/python-telegram-bot
ade1529986f5b6d394a65372d6a27045a70725b2
telegram/inline/inputinvoicemessagecontent.py
python
InputInvoiceMessageContent.__init__
( self, title: str, description: str, payload: str, provider_token: str, currency: str, prices: List[LabeledPrice], max_tip_amount: int = None, suggested_tip_amounts: List[int] = None, provider_data: str = None, photo_url: str = None, photo_size: int = None, photo_width: int = None, photo_height: int = None, need_name: bool = None, need_phone_number: bool = None, need_email: bool = None, need_shipping_address: bool = None, send_phone_number_to_provider: bool = None, send_email_to_provider: bool = None, is_flexible: bool = None, **_kwargs: Any, )
[]
def __init__( self, title: str, description: str, payload: str, provider_token: str, currency: str, prices: List[LabeledPrice], max_tip_amount: int = None, suggested_tip_amounts: List[int] = None, provider_data: str = None, photo_url: str = None, photo_size: int = None, photo_width: int = None, photo_height: int = None, need_name: bool = None, need_phone_number: bool = None, need_email: bool = None, need_shipping_address: bool = None, send_phone_number_to_provider: bool = None, send_email_to_provider: bool = None, is_flexible: bool = None, **_kwargs: Any, ): # Required self.title = title self.description = description self.payload = payload self.provider_token = provider_token self.currency = currency self.prices = prices # Optionals self.max_tip_amount = int(max_tip_amount) if max_tip_amount else None self.suggested_tip_amounts = ( [int(sta) for sta in suggested_tip_amounts] if suggested_tip_amounts else None ) self.provider_data = provider_data self.photo_url = photo_url self.photo_size = int(photo_size) if photo_size else None self.photo_width = int(photo_width) if photo_width else None self.photo_height = int(photo_height) if photo_height else None self.need_name = need_name self.need_phone_number = need_phone_number self.need_email = need_email self.need_shipping_address = need_shipping_address self.send_phone_number_to_provider = send_phone_number_to_provider self.send_email_to_provider = send_email_to_provider self.is_flexible = is_flexible self._id_attrs = ( self.title, self.description, self.payload, self.provider_token, self.currency, self.prices, )
[ "def", "__init__", "(", "self", ",", "title", ":", "str", ",", "description", ":", "str", ",", "payload", ":", "str", ",", "provider_token", ":", "str", ",", "currency", ":", "str", ",", "prices", ":", "List", "[", "LabeledPrice", "]", ",", "max_tip_am...
https://github.com/python-telegram-bot/python-telegram-bot/blob/ade1529986f5b6d394a65372d6a27045a70725b2/telegram/inline/inputinvoicemessagecontent.py#L150-L206
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/rings/qqbar.py
python
AlgebraicPolynomialTracker._repr_
(self)
return repr(self._poly)
r""" String representation of self. EXAMPLES:: sage: x = polygen(QQ) sage: AA.common_polynomial(x^3 - 7)._repr_() 'y^3 - 7'
r""" String representation of self.
[ "r", "String", "representation", "of", "self", "." ]
def _repr_(self): r""" String representation of self. EXAMPLES:: sage: x = polygen(QQ) sage: AA.common_polynomial(x^3 - 7)._repr_() 'y^3 - 7' """ return repr(self._poly)
[ "def", "_repr_", "(", "self", ")", ":", "return", "repr", "(", "self", ".", "_poly", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/rings/qqbar.py#L6711-L6721
eandersson/amqpstorm
7f57cf1291c8b3817527c10aae317aa1702654bc
amqpstorm/exchange.py
python
Exchange.bind
(self, destination='', source='', routing_key='', arguments=None)
return self._channel.rpc_request(bind_frame)
Bind an Exchange. :param str destination: Exchange name :param str source: Exchange to bind to :param str routing_key: The routing key to use :param dict arguments: Bind key/value arguments :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: dict
Bind an Exchange.
[ "Bind", "an", "Exchange", "." ]
def bind(self, destination='', source='', routing_key='', arguments=None): """Bind an Exchange. :param str destination: Exchange name :param str source: Exchange to bind to :param str routing_key: The routing key to use :param dict arguments: Bind key/value arguments :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: dict """ if not compatibility.is_string(destination): raise AMQPInvalidArgument('destination should be a string') elif not compatibility.is_string(source): raise AMQPInvalidArgument('source should be a string') elif not compatibility.is_string(routing_key): raise AMQPInvalidArgument('routing_key should be a string') elif arguments is not None and not isinstance(arguments, dict): raise AMQPInvalidArgument('arguments should be a dict or None') bind_frame = pamqp_exchange.Bind(destination=destination, source=source, routing_key=routing_key, arguments=arguments) return self._channel.rpc_request(bind_frame)
[ "def", "bind", "(", "self", ",", "destination", "=", "''", ",", "source", "=", "''", ",", "routing_key", "=", "''", ",", "arguments", "=", "None", ")", ":", "if", "not", "compatibility", ".", "is_string", "(", "destination", ")", ":", "raise", "AMQPInv...
https://github.com/eandersson/amqpstorm/blob/7f57cf1291c8b3817527c10aae317aa1702654bc/amqpstorm/exchange.py#L77-L106
hzy46/Deep-Learning-21-Examples
15c2d9edccad090cd67b033f24a43c544e5cba3e
chapter_6/src/models/inception_resnet_v2.py
python
block17
(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None)
return net
Builds the 17x17 resnet block.
Builds the 17x17 resnet block.
[ "Builds", "the", "17x17", "resnet", "block", "." ]
def block17(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Builds the 17x17 resnet block.""" with tf.variable_scope(scope, 'Block17', [net], reuse=reuse): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 192, 1, scope='Conv2d_1x1') with tf.variable_scope('Branch_1'): tower_conv1_0 = slim.conv2d(net, 128, 1, scope='Conv2d_0a_1x1') tower_conv1_1 = slim.conv2d(tower_conv1_0, 160, [1, 7], scope='Conv2d_0b_1x7') tower_conv1_2 = slim.conv2d(tower_conv1_1, 192, [7, 1], scope='Conv2d_0c_7x1') mixed = tf.concat([tower_conv, tower_conv1_2], 3) up = slim.conv2d(mixed, net.get_shape()[3], 1, normalizer_fn=None, activation_fn=None, scope='Conv2d_1x1') net += scale * up if activation_fn: net = activation_fn(net) return net
[ "def", "block17", "(", "net", ",", "scale", "=", "1.0", ",", "activation_fn", "=", "tf", ".", "nn", ".", "relu", ",", "scope", "=", "None", ",", "reuse", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "scope", ",", "'Block17'", ",...
https://github.com/hzy46/Deep-Learning-21-Examples/blob/15c2d9edccad090cd67b033f24a43c544e5cba3e/chapter_6/src/models/inception_resnet_v2.py#L51-L68
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/sqlalchemy/events.py
python
PoolEvents.reset
(self, dbapi_connection, connection_record)
Called before the "reset" action occurs for a pooled connection. This event represents when the ``rollback()`` method is called on the DBAPI connection before it is returned to the pool. The behavior of "reset" can be controlled, including disabled, using the ``reset_on_return`` pool argument. The :meth:`.PoolEvents.reset` event is usually followed by the :meth:`.PoolEvents.checkin` event is called, except in those cases where the connection is discarded immediately after reset. :param dbapi_connection: a DBAPI connection. :param connection_record: the :class:`._ConnectionRecord` managing the DBAPI connection. .. versionadded:: 0.8 .. seealso:: :meth:`.ConnectionEvents.rollback` :meth:`.ConnectionEvents.commit`
Called before the "reset" action occurs for a pooled connection.
[ "Called", "before", "the", "reset", "action", "occurs", "for", "a", "pooled", "connection", "." ]
def reset(self, dbapi_connection, connection_record): """Called before the "reset" action occurs for a pooled connection. This event represents when the ``rollback()`` method is called on the DBAPI connection before it is returned to the pool. The behavior of "reset" can be controlled, including disabled, using the ``reset_on_return`` pool argument. The :meth:`.PoolEvents.reset` event is usually followed by the :meth:`.PoolEvents.checkin` event is called, except in those cases where the connection is discarded immediately after reset. :param dbapi_connection: a DBAPI connection. :param connection_record: the :class:`._ConnectionRecord` managing the DBAPI connection. .. versionadded:: 0.8 .. seealso:: :meth:`.ConnectionEvents.rollback` :meth:`.ConnectionEvents.commit` """
[ "def", "reset", "(", "self", ",", "dbapi_connection", ",", "connection_record", ")", ":" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/sqlalchemy/events.py#L409-L436
sympy/sympy
d822fcba181155b85ff2b29fe525adbafb22b448
sympy/stats/stochastic_process_types.py
python
MarkovProcess._check_trans_probs
(self, trans_probs, row_sum=1)
Helper function for checking the validity of transition probabilities.
Helper function for checking the validity of transition probabilities.
[ "Helper", "function", "for", "checking", "the", "validity", "of", "transition", "probabilities", "." ]
def _check_trans_probs(self, trans_probs, row_sum=1): """ Helper function for checking the validity of transition probabilities. """ if not isinstance(trans_probs, MatrixSymbol): rows = trans_probs.tolist() for row in rows: if (sum(row) - row_sum) != 0: raise ValueError("Values in a row must sum to %s. " "If you are using Float or floats then please use Rational."%(row_sum))
[ "def", "_check_trans_probs", "(", "self", ",", "trans_probs", ",", "row_sum", "=", "1", ")", ":", "if", "not", "isinstance", "(", "trans_probs", ",", "MatrixSymbol", ")", ":", "rows", "=", "trans_probs", ".", "tolist", "(", ")", "for", "row", "in", "rows...
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/stats/stochastic_process_types.py#L453-L463
mesalock-linux/mesapy
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
pypy/module/cpyext/stubs.py
python
PyUnicode_DecodeCharmap
(space, s, size, mapping, errors)
Create a Unicode object by decoding size bytes of the encoded string s using the given mapping object. Return NULL if an exception was raised by the codec. If mapping is NULL latin-1 decoding will be done. Else it can be a dictionary mapping byte or a unicode string, which is treated as a lookup table. Byte values greater that the length of the string and U+FFFE "characters" are treated as "undefined mapping". Allowed unicode string as mapping argument. This function used an int type for size. This might require changes in your code for properly supporting 64-bit systems.
Create a Unicode object by decoding size bytes of the encoded string s using the given mapping object. Return NULL if an exception was raised by the codec. If mapping is NULL latin-1 decoding will be done. Else it can be a dictionary mapping byte or a unicode string, which is treated as a lookup table. Byte values greater that the length of the string and U+FFFE "characters" are treated as "undefined mapping".
[ "Create", "a", "Unicode", "object", "by", "decoding", "size", "bytes", "of", "the", "encoded", "string", "s", "using", "the", "given", "mapping", "object", ".", "Return", "NULL", "if", "an", "exception", "was", "raised", "by", "the", "codec", ".", "If", ...
def PyUnicode_DecodeCharmap(space, s, size, mapping, errors): """Create a Unicode object by decoding size bytes of the encoded string s using the given mapping object. Return NULL if an exception was raised by the codec. If mapping is NULL latin-1 decoding will be done. Else it can be a dictionary mapping byte or a unicode string, which is treated as a lookup table. Byte values greater that the length of the string and U+FFFE "characters" are treated as "undefined mapping". Allowed unicode string as mapping argument. This function used an int type for size. This might require changes in your code for properly supporting 64-bit systems.""" raise NotImplementedError
[ "def", "PyUnicode_DecodeCharmap", "(", "space", ",", "s", ",", "size", ",", "mapping", ",", "errors", ")", ":", "raise", "NotImplementedError" ]
https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/pypy/module/cpyext/stubs.py#L1662-L1674
coderSkyChen/Action_Recognition_Zoo
92ec5ec3efeee852aec5c057798298cd3a8e58ae
model_zoo/models/slim/nets/lenet.py
python
lenet_arg_scope
(weight_decay=0.0)
Defines the default lenet argument scope. Args: weight_decay: The weight decay to use for regularizing the model. Returns: An `arg_scope` to use for the inception v3 model.
Defines the default lenet argument scope.
[ "Defines", "the", "default", "lenet", "argument", "scope", "." ]
def lenet_arg_scope(weight_decay=0.0): """Defines the default lenet argument scope. Args: weight_decay: The weight decay to use for regularizing the model. Returns: An `arg_scope` to use for the inception v3 model. """ with slim.arg_scope( [slim.conv2d, slim.fully_connected], weights_regularizer=slim.l2_regularizer(weight_decay), weights_initializer=tf.truncated_normal_initializer(stddev=0.1), activation_fn=tf.nn.relu) as sc: return sc
[ "def", "lenet_arg_scope", "(", "weight_decay", "=", "0.0", ")", ":", "with", "slim", ".", "arg_scope", "(", "[", "slim", ".", "conv2d", ",", "slim", ".", "fully_connected", "]", ",", "weights_regularizer", "=", "slim", ".", "l2_regularizer", "(", "weight_dec...
https://github.com/coderSkyChen/Action_Recognition_Zoo/blob/92ec5ec3efeee852aec5c057798298cd3a8e58ae/model_zoo/models/slim/nets/lenet.py#L79-L93
stefanhoelzl/vue.py
f4256454256ddfe54a8be6dea493d3fc915ef1a2
vue/bridge/dict.py
python
Dict.__setattr__
(self, key, value)
[]
def __setattr__(self, key, value): if key in ["_js"]: return super().__setattr__(key, value) self[key] = value
[ "def", "__setattr__", "(", "self", ",", "key", ",", "value", ")", ":", "if", "key", "in", "[", "\"_js\"", "]", ":", "return", "super", "(", ")", ".", "__setattr__", "(", "key", ",", "value", ")", "self", "[", "key", "]", "=", "value" ]
https://github.com/stefanhoelzl/vue.py/blob/f4256454256ddfe54a8be6dea493d3fc915ef1a2/vue/bridge/dict.py#L112-L115
pyqt/examples
843bb982917cecb2350b5f6d7f42c9b7fb142ec1
src/pyqt-official/itemviews/customsortfiltermodel.py
python
Window.textFilterChanged
(self)
[]
def textFilterChanged(self): syntax = QRegExp.PatternSyntax( self.filterSyntaxComboBox.itemData( self.filterSyntaxComboBox.currentIndex())) caseSensitivity = ( self.filterCaseSensitivityCheckBox.isChecked() and Qt.CaseSensitive or Qt.CaseInsensitive) regExp = QRegExp(self.filterPatternLineEdit.text(), caseSensitivity, syntax) self.proxyModel.setFilterRegExp(regExp)
[ "def", "textFilterChanged", "(", "self", ")", ":", "syntax", "=", "QRegExp", ".", "PatternSyntax", "(", "self", ".", "filterSyntaxComboBox", ".", "itemData", "(", "self", ".", "filterSyntaxComboBox", ".", "currentIndex", "(", ")", ")", ")", "caseSensitivity", ...
https://github.com/pyqt/examples/blob/843bb982917cecb2350b5f6d7f42c9b7fb142ec1/src/pyqt-official/itemviews/customsortfiltermodel.py#L185-L193
securityclippy/elasticintel
aa08d3e9f5ab1c000128e95161139ce97ff0e334
ingest_feed_lambda/requests/utils.py
python
get_auth_from_url
(url)
return auth
Given a url with authentication components, extract them into a tuple of username,password.
Given a url with authentication components, extract them into a tuple of username,password.
[ "Given", "a", "url", "with", "authentication", "components", "extract", "them", "into", "a", "tuple", "of", "username", "password", "." ]
def get_auth_from_url(url): """Given a url with authentication components, extract them into a tuple of username,password.""" parsed = urlparse(url) try: auth = (unquote(parsed.username), unquote(parsed.password)) except (AttributeError, TypeError): auth = ('', '') return auth
[ "def", "get_auth_from_url", "(", "url", ")", ":", "parsed", "=", "urlparse", "(", "url", ")", "try", ":", "auth", "=", "(", "unquote", "(", "parsed", ".", "username", ")", ",", "unquote", "(", "parsed", ".", "password", ")", ")", "except", "(", "Attr...
https://github.com/securityclippy/elasticintel/blob/aa08d3e9f5ab1c000128e95161139ce97ff0e334/ingest_feed_lambda/requests/utils.py#L677-L687
CatalinVoss/cnn-assignments
908e977d905711483c974186821079c15090a24c
assignment1/cs231n/classifiers/softmax.py
python
softmax_loss_naive
(W, X, y, reg)
return loss, dW
Softmax loss function, naive implementation (with loops) Inputs: - W: C x D array of weights - X: D x N array of data. Data are D-dimensional columns - y: 1-dimensional array of length N with labels 0...K-1, for K classes - reg: (float) regularization strength Returns: a tuple of: - loss as single float - gradient with respect to weights W, an array of same size as W
Softmax loss function, naive implementation (with loops) Inputs: - W: C x D array of weights - X: D x N array of data. Data are D-dimensional columns - y: 1-dimensional array of length N with labels 0...K-1, for K classes - reg: (float) regularization strength Returns: a tuple of: - loss as single float - gradient with respect to weights W, an array of same size as W
[ "Softmax", "loss", "function", "naive", "implementation", "(", "with", "loops", ")", "Inputs", ":", "-", "W", ":", "C", "x", "D", "array", "of", "weights", "-", "X", ":", "D", "x", "N", "array", "of", "data", ".", "Data", "are", "D", "-", "dimensio...
def softmax_loss_naive(W, X, y, reg): """ Softmax loss function, naive implementation (with loops) Inputs: - W: C x D array of weights - X: D x N array of data. Data are D-dimensional columns - y: 1-dimensional array of length N with labels 0...K-1, for K classes - reg: (float) regularization strength Returns: a tuple of: - loss as single float - gradient with respect to weights W, an array of same size as W """ # Initialize the loss and gradient to zero. loss = 0.0 dW = np.zeros_like(W) ############################################################################# # Compute the softmax loss and its gradient using explicit loops. # # Store the loss in loss and the gradient in dW. If you are not careful # # here, it is easy to run into numeric instability. Don't forget the # # regularization! # ############################################################################# # Get shapes num_classes = W.shape[0] num_train = X.shape[1] for i in range(num_train): # Compute vector of scores f_i = W.dot(X[:, i]) # in R^{num_classes} # Normalization trick to avoid numerical instability, per http://cs231n.github.io/linear-classify/#softmax log_c = np.max(f_i) f_i -= log_c # Compute loss (and add to it, divided later) # L_i = - f(x_i)_{y_i} + log \sum_j e^{f(x_i)_j} sum_i = 0.0 for f_i_j in f_i: sum_i += np.exp(f_i_j) loss += -f_i[y[i]] + np.log(sum_i) # Compute gradient # dw_j = 1/num_train * \sum_i[x_i * (p(y_i = j)-Ind{y_i = j} )] # Here we are computing the contribution to the inner sum for a given i. for j in range(num_classes): p = np.exp(f_i[j])/sum_i dW[j, :] += (p-(j == y[i])) * X[:, i] # Compute average loss /= num_train dW /= num_train # Regularization loss += 0.5 * reg * np.sum(W * W) dW += reg*W return loss, dW
[ "def", "softmax_loss_naive", "(", "W", ",", "X", ",", "y", ",", "reg", ")", ":", "# Initialize the loss and gradient to zero.", "loss", "=", "0.0", "dW", "=", "np", ".", "zeros_like", "(", "W", ")", "####################################################################...
https://github.com/CatalinVoss/cnn-assignments/blob/908e977d905711483c974186821079c15090a24c/assignment1/cs231n/classifiers/softmax.py#L4-L62
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/bds/bds_client.py
python
BdsClient.get_bds_instance
(self, bds_instance_id, **kwargs)
Returns information about the Big Data Service cluster identified by the given ID. :param str bds_instance_id: (required) The OCID of the cluster. :param str opc_request_id: (optional) The client request ID for tracing. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.bds.models.BdsInstance` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/bds/get_bds_instance.py.html>`__ to see an example of how to use get_bds_instance API.
Returns information about the Big Data Service cluster identified by the given ID.
[ "Returns", "information", "about", "the", "Big", "Data", "Service", "cluster", "identified", "by", "the", "given", "ID", "." ]
def get_bds_instance(self, bds_instance_id, **kwargs): """ Returns information about the Big Data Service cluster identified by the given ID. :param str bds_instance_id: (required) The OCID of the cluster. :param str opc_request_id: (optional) The client request ID for tracing. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.bds.models.BdsInstance` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/bds/get_bds_instance.py.html>`__ to see an example of how to use get_bds_instance API. """ resource_path = "/bdsInstances/{bdsInstanceId}" method = "GET" # Don't accept unknown kwargs expected_kwargs = [ "retry_strategy", "opc_request_id" ] extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs] if extra_kwargs: raise ValueError( "get_bds_instance got unknown kwargs: {!r}".format(extra_kwargs)) path_params = { "bdsInstanceId": bds_instance_id } path_params = {k: v for (k, v) in six.iteritems(path_params) if v is not missing} for (k, v) in six.iteritems(path_params): if v is None or (isinstance(v, six.string_types) and len(v.strip()) == 0): raise ValueError('Parameter {} cannot be None, whitespace or empty string'.format(k)) header_params = { "accept": "application/json", "content-type": "application/json", "opc-request-id": kwargs.get("opc_request_id", missing) } header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None} retry_strategy = self.base_client.get_preferred_retry_strategy( operation_retry_strategy=kwargs.get('retry_strategy'), client_retry_strategy=self.retry_strategy ) if retry_strategy: if not isinstance(retry_strategy, retry.NoneRetryStrategy): self.base_client.add_opc_client_retries_header(header_params) retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback) return retry_strategy.make_retrying_call( self.base_client.call_api, resource_path=resource_path, method=method, path_params=path_params, header_params=header_params, response_type="BdsInstance") else: return self.base_client.call_api( resource_path=resource_path, method=method, path_params=path_params, header_params=header_params, response_type="BdsInstance")
[ "def", "get_bds_instance", "(", "self", ",", "bds_instance_id", ",", "*", "*", "kwargs", ")", ":", "resource_path", "=", "\"/bdsInstances/{bdsInstanceId}\"", "method", "=", "\"GET\"", "# Don't accept unknown kwargs", "expected_kwargs", "=", "[", "\"retry_strategy\"", ",...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/bds/bds_client.py#L1505-L1582
JetBrains/python-skeletons
95ad24b666e475998e5d1cc02ed53a2188036167
pathlib.py
python
PurePath.drive
(self)
return ''
:rtype: str
:rtype: str
[ ":", "rtype", ":", "str" ]
def drive(self): """ :rtype: str """ return ''
[ "def", "drive", "(", "self", ")", ":", "return", "''" ]
https://github.com/JetBrains/python-skeletons/blob/95ad24b666e475998e5d1cc02ed53a2188036167/pathlib.py#L37-L41
adafruit/Adafruit_Python_GPIO
a12fee39839665966bd124fd22588b2c87ced9d2
Adafruit_GPIO/GPIO.py
python
AdafruitBBIOAdapter.input
(self, pin)
return self.bbio_gpio.input(pin)
Read the specified pin and return HIGH/true if the pin is pulled high, or LOW/false if pulled low.
Read the specified pin and return HIGH/true if the pin is pulled high, or LOW/false if pulled low.
[ "Read", "the", "specified", "pin", "and", "return", "HIGH", "/", "true", "if", "the", "pin", "is", "pulled", "high", "or", "LOW", "/", "false", "if", "pulled", "low", "." ]
def input(self, pin): """Read the specified pin and return HIGH/true if the pin is pulled high, or LOW/false if pulled low. """ return self.bbio_gpio.input(pin)
[ "def", "input", "(", "self", ",", "pin", ")", ":", "return", "self", ".", "bbio_gpio", ".", "input", "(", "pin", ")" ]
https://github.com/adafruit/Adafruit_Python_GPIO/blob/a12fee39839665966bd124fd22588b2c87ced9d2/Adafruit_GPIO/GPIO.py#L286-L290
kang205/SASRec
e3738967fddab206d6eeb4fda433e7a7034dd8b1
modules.py
python
embedding
(inputs, vocab_size, num_units, zero_pad=True, scale=True, l2_reg=0.0, scope="embedding", with_t=False, reuse=None)
Embeds a given tensor. Args: inputs: A `Tensor` with type `int32` or `int64` containing the ids to be looked up in `lookup table`. vocab_size: An int. Vocabulary size. num_units: An int. Number of embedding hidden units. zero_pad: A boolean. If True, all the values of the fist row (id 0) should be constant zeros. scale: A boolean. If True. the outputs is multiplied by sqrt num_units. scope: Optional scope for `variable_scope`. reuse: Boolean, whether to reuse the weights of a previous layer by the same name. Returns: A `Tensor` with one more rank than inputs's. The last dimensionality should be `num_units`. For example, ``` import tensorflow as tf inputs = tf.to_int32(tf.reshape(tf.range(2*3), (2, 3))) outputs = embedding(inputs, 6, 2, zero_pad=True) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print sess.run(outputs) >> [[[ 0. 0. ] [ 0.09754146 0.67385566] [ 0.37864095 -0.35689294]] [[-1.01329422 -1.09939694] [ 0.7521342 0.38203377] [-0.04973143 -0.06210355]]] ``` ``` import tensorflow as tf inputs = tf.to_int32(tf.reshape(tf.range(2*3), (2, 3))) outputs = embedding(inputs, 6, 2, zero_pad=False) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print sess.run(outputs) >> [[[-0.19172323 -0.39159766] [-0.43212751 -0.66207761] [ 1.03452027 -0.26704335]] [[-0.11634696 -0.35983452] [ 0.50208133 0.53509563] [ 1.22204471 -0.96587461]]] ```
Embeds a given tensor.
[ "Embeds", "a", "given", "tensor", "." ]
def embedding(inputs, vocab_size, num_units, zero_pad=True, scale=True, l2_reg=0.0, scope="embedding", with_t=False, reuse=None): '''Embeds a given tensor. Args: inputs: A `Tensor` with type `int32` or `int64` containing the ids to be looked up in `lookup table`. vocab_size: An int. Vocabulary size. num_units: An int. Number of embedding hidden units. zero_pad: A boolean. If True, all the values of the fist row (id 0) should be constant zeros. scale: A boolean. If True. the outputs is multiplied by sqrt num_units. scope: Optional scope for `variable_scope`. reuse: Boolean, whether to reuse the weights of a previous layer by the same name. Returns: A `Tensor` with one more rank than inputs's. The last dimensionality should be `num_units`. For example, ``` import tensorflow as tf inputs = tf.to_int32(tf.reshape(tf.range(2*3), (2, 3))) outputs = embedding(inputs, 6, 2, zero_pad=True) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print sess.run(outputs) >> [[[ 0. 0. ] [ 0.09754146 0.67385566] [ 0.37864095 -0.35689294]] [[-1.01329422 -1.09939694] [ 0.7521342 0.38203377] [-0.04973143 -0.06210355]]] ``` ``` import tensorflow as tf inputs = tf.to_int32(tf.reshape(tf.range(2*3), (2, 3))) outputs = embedding(inputs, 6, 2, zero_pad=False) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print sess.run(outputs) >> [[[-0.19172323 -0.39159766] [-0.43212751 -0.66207761] [ 1.03452027 -0.26704335]] [[-0.11634696 -0.35983452] [ 0.50208133 0.53509563] [ 1.22204471 -0.96587461]]] ``` ''' with tf.variable_scope(scope, reuse=reuse): lookup_table = tf.get_variable('lookup_table', dtype=tf.float32, shape=[vocab_size, num_units], #initializer=tf.contrib.layers.xavier_initializer(), regularizer=tf.contrib.layers.l2_regularizer(l2_reg)) if zero_pad: lookup_table = tf.concat((tf.zeros(shape=[1, num_units]), lookup_table[1:, :]), 0) outputs = tf.nn.embedding_lookup(lookup_table, inputs) if scale: outputs = outputs * (num_units ** 0.5) if with_t: return outputs,lookup_table else: return outputs
[ "def", "embedding", "(", "inputs", ",", "vocab_size", ",", "num_units", ",", "zero_pad", "=", "True", ",", "scale", "=", "True", ",", "l2_reg", "=", "0.0", ",", "scope", "=", "\"embedding\"", ",", "with_t", "=", "False", ",", "reuse", "=", "None", ")",...
https://github.com/kang205/SASRec/blob/e3738967fddab206d6eeb4fda433e7a7034dd8b1/modules.py#L51-L130
nmccrea/sobot-rimulator
c4a8aa3ec00d5b4948175ae6cc4e0199d32dfba5
robot_control/supervisor.py
python
Supervisor.__init__
( self, robot_interface, # the interface through which this supervisor will interact with the robot wheel_radius, # the radius of a drive wheel on the robot wheel_base_length, # the robot's wheel base wheel_encoder_ticks_per_rev, # the number of wheel encoder ticks per revolution of a drive wheel sensor_placements, # placement pose of the sensors on the robot body sensor_range, # max detection range of the sensors goal=[0.0, 0.0], # the goal to which this supervisor will guide the robot initial_pose_args=[0.0, 0.0, 0.0], )
[]
def __init__( self, robot_interface, # the interface through which this supervisor will interact with the robot wheel_radius, # the radius of a drive wheel on the robot wheel_base_length, # the robot's wheel base wheel_encoder_ticks_per_rev, # the number of wheel encoder ticks per revolution of a drive wheel sensor_placements, # placement pose of the sensors on the robot body sensor_range, # max detection range of the sensors goal=[0.0, 0.0], # the goal to which this supervisor will guide the robot initial_pose_args=[0.0, 0.0, 0.0], ): # the pose the robot will have when control begins # internal clock time in seconds self.time = 0.0 # robot representation # NOTE: the supervisor does NOT have access to the physical robot, only the # robot's interface self.robot = robot_interface # proximity sensor information self.proximity_sensor_placements = [ Pose(rawpose[0], rawpose[1], radians(rawpose[2])) for rawpose in sensor_placements ] self.proximity_sensor_max_range = sensor_range # odometry information self.robot_wheel_radius = wheel_radius self.robot_wheel_base_length = wheel_base_length self.wheel_encoder_ticks_per_revolution = wheel_encoder_ticks_per_rev self.prev_ticks_left = 0 self.prev_ticks_right = 0 # controllers controller_interface = SupervisorControllerInterface(self) self.go_to_angle_controller = GoToAngleController(controller_interface) self.go_to_goal_controller = GoToGoalController(controller_interface) self.avoid_obstacles_controller = AvoidObstaclesController(controller_interface) self.gtg_and_ao_controller = GTGAndAOController(controller_interface) self.follow_wall_controller = FollowWallController(controller_interface) # state machine self.state_machine = SupervisorStateMachine(self) # state self.proximity_sensor_distances = [0.0, 0.0] * len( sensor_placements ) # sensor distances self.estimated_pose = Pose(*initial_pose_args) # estimated pose self.current_controller = self.go_to_goal_controller # current controller # goal self.goal = goal # control bounds self.v_max = K3_TRANS_VEL_LIMIT self.omega_max = K3_ANG_VEL_LIMIT # CONTROL OUTPUTS - UNICYCLE self.v_output = 0.0 self.omega_output = 0.0
[ "def", "__init__", "(", "self", ",", "robot_interface", ",", "# the interface through which this supervisor will interact with the robot", "wheel_radius", ",", "# the radius of a drive wheel on the robot", "wheel_base_length", ",", "# the robot's wheel base", "wheel_encoder_ticks_per_rev...
https://github.com/nmccrea/sobot-rimulator/blob/c4a8aa3ec00d5b4948175ae6cc4e0199d32dfba5/robot_control/supervisor.py#L17-L78
ales-tsurko/cells
4cf7e395cd433762bea70cdc863a346f3a6fe1d0
packaging/macos/python/lib/python3.7/operator.py
python
index
(a)
return a.__index__()
Same as a.__index__().
Same as a.__index__().
[ "Same", "as", "a", ".", "__index__", "()", "." ]
def index(a): "Same as a.__index__()." return a.__index__()
[ "def", "index", "(", "a", ")", ":", "return", "a", ".", "__index__", "(", ")" ]
https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/operator.py#L87-L89
Chaffelson/nipyapi
d3b186fd701ce308c2812746d98af9120955e810
nipyapi/nifi/models/controller_service_status_dto.py
python
ControllerServiceStatusDTO.active_thread_count
(self, active_thread_count)
Sets the active_thread_count of this ControllerServiceStatusDTO. The number of active threads for the component. :param active_thread_count: The active_thread_count of this ControllerServiceStatusDTO. :type: int
Sets the active_thread_count of this ControllerServiceStatusDTO. The number of active threads for the component.
[ "Sets", "the", "active_thread_count", "of", "this", "ControllerServiceStatusDTO", ".", "The", "number", "of", "active", "threads", "for", "the", "component", "." ]
def active_thread_count(self, active_thread_count): """ Sets the active_thread_count of this ControllerServiceStatusDTO. The number of active threads for the component. :param active_thread_count: The active_thread_count of this ControllerServiceStatusDTO. :type: int """ self._active_thread_count = active_thread_count
[ "def", "active_thread_count", "(", "self", ",", "active_thread_count", ")", ":", "self", ".", "_active_thread_count", "=", "active_thread_count" ]
https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/nifi/models/controller_service_status_dto.py#L131-L140
deepset-ai/haystack
79fdda8a7cf393d774803608a4874f2a6e63cf6f
haystack/modeling/model/biadaptive_model.py
python
BiAdaptiveModel.logits_to_loss
(self, logits: torch.Tensor, global_step: Optional[int] = None, **kwargs)
return loss
Get losses from all prediction heads & reduce to single loss *per sample*. :param logits: Logits, can vary in shape and type, depending on task. :param global_step: Number of current training step. :param kwargs: Placeholder for passing generic parameters. Note: Contains the batch (as dict of tensors), when called from Trainer.train(). :return: torch.Tensor that is the per sample loss (len: batch_size).
Get losses from all prediction heads & reduce to single loss *per sample*.
[ "Get", "losses", "from", "all", "prediction", "heads", "&", "reduce", "to", "single", "loss", "*", "per", "sample", "*", "." ]
def logits_to_loss(self, logits: torch.Tensor, global_step: Optional[int] = None, **kwargs): """ Get losses from all prediction heads & reduce to single loss *per sample*. :param logits: Logits, can vary in shape and type, depending on task. :param global_step: Number of current training step. :param kwargs: Placeholder for passing generic parameters. Note: Contains the batch (as dict of tensors), when called from Trainer.train(). :return: torch.Tensor that is the per sample loss (len: batch_size). """ all_losses = self.logits_to_loss_per_head(logits, **kwargs) # This aggregates the loss per sample across multiple prediction heads # Default is sum(), but you can configure any fn that takes [Tensor, Tensor ...] and returns [Tensor] loss = self.loss_aggregation_fn(all_losses, global_step=global_step, batch=kwargs) return loss
[ "def", "logits_to_loss", "(", "self", ",", "logits", ":", "torch", ".", "Tensor", ",", "global_step", ":", "Optional", "[", "int", "]", "=", "None", ",", "*", "*", "kwargs", ")", ":", "all_losses", "=", "self", ".", "logits_to_loss_per_head", "(", "logit...
https://github.com/deepset-ai/haystack/blob/79fdda8a7cf393d774803608a4874f2a6e63cf6f/haystack/modeling/model/biadaptive_model.py#L178-L192
msg-systems/holmes-extractor
fc536f32a5cd02a53d1c32f771adc14227d09f38
examples/example_supervised_topic_model_EN.py
python
train_model
(working_directory, zip_filename)
[]
def train_model(working_directory, zip_filename): training_basis = holmes_manager.get_supervised_topic_training_basis() with zipfile.ZipFile(zip_filename) as bbc_zipfile: for filename in ( filename for filename in bbc_zipfile.namelist() if filename.lower().endswith('.txt') and not filename.endswith('README.TXT')): category, document_number = get_document_filename_info(filename) if is_training_data(document_number): with bbc_zipfile.open(filename, 'r') as training_doc: training_contents = str(training_doc.read()) training_contents = training_contents.replace('\n', ' ').replace('\r', ' ') training_basis.parse_and_register_training_document( training_contents, category, filename) training_basis.prepare() classifier = training_basis.train().classifier() output_filename = os.sep.join((working_directory, 'model.json')) with open(output_filename, "w") as file: file.write(classifier.serialize_model()) evaluate_classifier(zip_filename, classifier)
[ "def", "train_model", "(", "working_directory", ",", "zip_filename", ")", ":", "training_basis", "=", "holmes_manager", ".", "get_supervised_topic_training_basis", "(", ")", "with", "zipfile", ".", "ZipFile", "(", "zip_filename", ")", "as", "bbc_zipfile", ":", "for"...
https://github.com/msg-systems/holmes-extractor/blob/fc536f32a5cd02a53d1c32f771adc14227d09f38/examples/example_supervised_topic_model_EN.py#L54-L72
jgagneastro/coffeegrindsize
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
App/venv/lib/python3.7/site-packages/pip/_vendor/urllib3/util/retry.py
python
Retry.get_backoff_time
(self)
return min(self.BACKOFF_MAX, backoff_value)
Formula for computing the current backoff :rtype: float
Formula for computing the current backoff
[ "Formula", "for", "computing", "the", "current", "backoff" ]
def get_backoff_time(self): """ Formula for computing the current backoff :rtype: float """ # We want to consider only the last consecutive errors sequence (Ignore redirects). consecutive_errors_len = len(list(takewhile(lambda x: x.redirect_location is None, reversed(self.history)))) if consecutive_errors_len <= 1: return 0 backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1)) return min(self.BACKOFF_MAX, backoff_value)
[ "def", "get_backoff_time", "(", "self", ")", ":", "# We want to consider only the last consecutive errors sequence (Ignore redirects).", "consecutive_errors_len", "=", "len", "(", "list", "(", "takewhile", "(", "lambda", "x", ":", "x", ".", "redirect_location", "is", "Non...
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/venv/lib/python3.7/site-packages/pip/_vendor/urllib3/util/retry.py#L213-L225
LumaPictures/pymel
fa88a3f4fa18e09bb8aa9bdf4dab53d984bada72
pymel/util/arrays.py
python
MatrixN.col
(self)
return self.axisiter(1)
m.col --> ArrayIter Iterator on the MatrixN columns Being an ArrayIter, it support __len__, __getitem__, __setitem__ and __delitem__ >>> M = MatrixN(range(1, 10), shape=(3, 3)) >>> M.nrow, M.ncol = 4, 4 >>> M[-1, -1] = 1 >>> print(M.formated()) [[1, 2, 3, 0], [4, 5, 6, 0], [7, 8, 9, 0], [0, 0, 0, 1]] >>> [c for c in M.col] [Array([1, 4, 7, 0]), Array([2, 5, 8, 0]), Array([3, 6, 9, 0]), Array([0, 0, 0, 1])] The col iterator has to rebuild sub-arrays and thus returns copies and not references. >>> c = M.col[0] >>> c Array([1, 4, 7, 0]) >>> c == M[:,0] True >>> c is M[:,0] False Multiple columns are returned as rows in a new MatrixN >>> c = M.col[:2] >>> print(c.formated()) [[1, 4, 7, 0], [2, 5, 8, 0]] >>> print(clsname(c)) MatrixN >>> s = M[:,:2] >>> print(s.formated()) [[1, 2], [4, 5], [7, 8], [0, 0]] >>> print(clsname(s)) MatrixN TODO : is it what we want ? If so invert these # >>> c == s # True # >>> c == s.T # False Results can be indexed again, using Array indexing or MatrixN methods wether they're returned as Array (single lines / columns) or MatrixN (2 dimensionnal Array). >>> r = c.row[1] >>> r Array([2, 5, 8, 0]) >>> r = s.row[1] >>> r Array([4, 5]) Multiple indexing is possible >>> M[0, 1] 2 >>> M.col[1][0] 2 >>> M.col[1, 0] 2 As results are rebuilt Arrays, values can only b set for full columns >>> M.col[1] Array([2, 5, 8, 0]) This won't work : >>> M.col[1][:2] = 10 >>> print(M.formated()) [[1, 2, 3, 0], [4, 5, 6, 0], [7, 8, 9, 0], [0, 0, 0, 1]] But this will : >>> M.col[1, :2] = 10 >>> print(M.formated()) [[1, 10, 3, 0], [4, 10, 6, 0], [7, 8, 9, 0], [0, 0, 0, 1]] >>> c = M.col[1] >>> c[:2] = [2, 5] >>> M.col[1] = c >>> print(M.formated()) [[1, 2, 3, 0], [4, 5, 6, 0], [7, 8, 9, 0], [0, 0, 0, 1]] Columns can be deleted too >>> del M.col[-1] >>> del M[-1] >>> print(M.formated()) [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
m.col --> ArrayIter
[ "m", ".", "col", "--", ">", "ArrayIter" ]
def col(self): """ m.col --> ArrayIter Iterator on the MatrixN columns Being an ArrayIter, it support __len__, __getitem__, __setitem__ and __delitem__ >>> M = MatrixN(range(1, 10), shape=(3, 3)) >>> M.nrow, M.ncol = 4, 4 >>> M[-1, -1] = 1 >>> print(M.formated()) [[1, 2, 3, 0], [4, 5, 6, 0], [7, 8, 9, 0], [0, 0, 0, 1]] >>> [c for c in M.col] [Array([1, 4, 7, 0]), Array([2, 5, 8, 0]), Array([3, 6, 9, 0]), Array([0, 0, 0, 1])] The col iterator has to rebuild sub-arrays and thus returns copies and not references. >>> c = M.col[0] >>> c Array([1, 4, 7, 0]) >>> c == M[:,0] True >>> c is M[:,0] False Multiple columns are returned as rows in a new MatrixN >>> c = M.col[:2] >>> print(c.formated()) [[1, 4, 7, 0], [2, 5, 8, 0]] >>> print(clsname(c)) MatrixN >>> s = M[:,:2] >>> print(s.formated()) [[1, 2], [4, 5], [7, 8], [0, 0]] >>> print(clsname(s)) MatrixN TODO : is it what we want ? If so invert these # >>> c == s # True # >>> c == s.T # False Results can be indexed again, using Array indexing or MatrixN methods wether they're returned as Array (single lines / columns) or MatrixN (2 dimensionnal Array). >>> r = c.row[1] >>> r Array([2, 5, 8, 0]) >>> r = s.row[1] >>> r Array([4, 5]) Multiple indexing is possible >>> M[0, 1] 2 >>> M.col[1][0] 2 >>> M.col[1, 0] 2 As results are rebuilt Arrays, values can only b set for full columns >>> M.col[1] Array([2, 5, 8, 0]) This won't work : >>> M.col[1][:2] = 10 >>> print(M.formated()) [[1, 2, 3, 0], [4, 5, 6, 0], [7, 8, 9, 0], [0, 0, 0, 1]] But this will : >>> M.col[1, :2] = 10 >>> print(M.formated()) [[1, 10, 3, 0], [4, 10, 6, 0], [7, 8, 9, 0], [0, 0, 0, 1]] >>> c = M.col[1] >>> c[:2] = [2, 5] >>> M.col[1] = c >>> print(M.formated()) [[1, 2, 3, 0], [4, 5, 6, 0], [7, 8, 9, 0], [0, 0, 0, 1]] Columns can be deleted too >>> del M.col[-1] >>> del M[-1] >>> print(M.formated()) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] """ return self.axisiter(1)
[ "def", "col", "(", "self", ")", ":", "return", "self", ".", "axisiter", "(", "1", ")" ]
https://github.com/LumaPictures/pymel/blob/fa88a3f4fa18e09bb8aa9bdf4dab53d984bada72/pymel/util/arrays.py#L5453-L5566
pencil1/ApiTestManage
851a54d5629456b7e967e15186244409ddf783cc
app/util/httprunner/built_in.py
python
multipart_encoder
(field_name, file_path, file_type=None, file_headers=None)
return MultipartEncoder(fields)
[]
def multipart_encoder(field_name, file_path, file_type=None, file_headers=None): if not os.path.isabs(file_path): file_path = os.path.join(os.getcwd(), file_path) filename = os.path.basename(file_path) with open(file_path, 'rb') as f: fields = { field_name: (filename, f.read(), file_type) } return MultipartEncoder(fields)
[ "def", "multipart_encoder", "(", "field_name", ",", "file_path", ",", "file_type", "=", "None", ",", "file_headers", "=", "None", ")", ":", "if", "not", "os", ".", "path", ".", "isabs", "(", "file_path", ")", ":", "file_path", "=", "os", ".", "path", "...
https://github.com/pencil1/ApiTestManage/blob/851a54d5629456b7e967e15186244409ddf783cc/app/util/httprunner/built_in.py#L44-L54
dmlc/dgl
8d14a739bc9e446d6c92ef83eafe5782398118de
python/dgl/convert.py
python
from_scipy
(sp_mat, eweight_name=None, idtype=None, device=None)
return g.to(device)
Create a graph from a SciPy sparse matrix and return. Parameters ---------- sp_mat : scipy.sparse.spmatrix The graph adjacency matrix. Each nonzero entry ``sp_mat[i, j]`` represents an edge from node ``i`` to ``j``. The matrix must have square shape ``(N, N)``, where ``N`` is the number of nodes in the graph. eweight_name : str, optional The edata name for storing the nonzero values of :attr:`sp_mat`. If given, DGL will store the nonzero values of :attr:`sp_mat` in ``edata[eweight_name]`` of the returned graph. idtype : int32 or int64, optional The data type for storing the structure-related graph information such as node and edge IDs. It should be a framework-specific data type object (e.g., ``torch.int32``). By default, DGL uses int64. device : device context, optional The device of the resulting graph. It should be a framework-specific device object (e.g., ``torch.device``). By default, DGL stores the graph on CPU. Returns ------- DGLGraph The created graph. Notes ----- 1. The function supports all kinds of SciPy sparse matrix classes (e.g., :class:`scipy.sparse.csr.csr_matrix`). It converts the input matrix to the COOrdinate format using :func:`scipy.sparse.spmatrix.tocoo` before creates a :class:`DGLGraph`. Creating from a :class:`scipy.sparse.coo.coo_matrix` is hence the most efficient way. 2. DGL internally maintains multiple copies of the graph structure in different sparse formats and chooses the most efficient one depending on the computation invoked. If memory usage becomes an issue in the case of large graphs, use :func:`dgl.DGLGraph.formats` to restrict the allowed formats. Examples -------- The following example uses PyTorch backend. >>> import dgl >>> import numpy as np >>> import torch >>> from scipy.sparse import coo_matrix Create a small three-edge graph. >>> # Source nodes for edges (2, 1), (3, 2), (4, 3) >>> src_ids = np.array([2, 3, 4]) >>> # Destination nodes for edges (2, 1), (3, 2), (4, 3) >>> dst_ids = np.array([1, 2, 3]) >>> # Weight for edges (2, 1), (3, 2), (4, 3) >>> eweight = np.array([0.2, 0.3, 0.5]) >>> sp_mat = coo_matrix((eweight, (src_ids, dst_ids)), shape=(5, 5)) >>> g = dgl.from_scipy(sp_mat) Retrieve the edge weights. >>> g = dgl.from_scipy(sp_mat, eweight_name='w') >>> g.edata['w'] tensor([0.2000, 0.3000, 0.5000], dtype=torch.float64) Create a graph on the first GPU with data type int32. >>> g = dgl.from_scipy(sp_mat, idtype=torch.int32, device='cuda:0') See Also -------- graph from_networkx
Create a graph from a SciPy sparse matrix and return.
[ "Create", "a", "graph", "from", "a", "SciPy", "sparse", "matrix", "and", "return", "." ]
def from_scipy(sp_mat, eweight_name=None, idtype=None, device=None): """Create a graph from a SciPy sparse matrix and return. Parameters ---------- sp_mat : scipy.sparse.spmatrix The graph adjacency matrix. Each nonzero entry ``sp_mat[i, j]`` represents an edge from node ``i`` to ``j``. The matrix must have square shape ``(N, N)``, where ``N`` is the number of nodes in the graph. eweight_name : str, optional The edata name for storing the nonzero values of :attr:`sp_mat`. If given, DGL will store the nonzero values of :attr:`sp_mat` in ``edata[eweight_name]`` of the returned graph. idtype : int32 or int64, optional The data type for storing the structure-related graph information such as node and edge IDs. It should be a framework-specific data type object (e.g., ``torch.int32``). By default, DGL uses int64. device : device context, optional The device of the resulting graph. It should be a framework-specific device object (e.g., ``torch.device``). By default, DGL stores the graph on CPU. Returns ------- DGLGraph The created graph. Notes ----- 1. The function supports all kinds of SciPy sparse matrix classes (e.g., :class:`scipy.sparse.csr.csr_matrix`). It converts the input matrix to the COOrdinate format using :func:`scipy.sparse.spmatrix.tocoo` before creates a :class:`DGLGraph`. Creating from a :class:`scipy.sparse.coo.coo_matrix` is hence the most efficient way. 2. DGL internally maintains multiple copies of the graph structure in different sparse formats and chooses the most efficient one depending on the computation invoked. If memory usage becomes an issue in the case of large graphs, use :func:`dgl.DGLGraph.formats` to restrict the allowed formats. Examples -------- The following example uses PyTorch backend. >>> import dgl >>> import numpy as np >>> import torch >>> from scipy.sparse import coo_matrix Create a small three-edge graph. >>> # Source nodes for edges (2, 1), (3, 2), (4, 3) >>> src_ids = np.array([2, 3, 4]) >>> # Destination nodes for edges (2, 1), (3, 2), (4, 3) >>> dst_ids = np.array([1, 2, 3]) >>> # Weight for edges (2, 1), (3, 2), (4, 3) >>> eweight = np.array([0.2, 0.3, 0.5]) >>> sp_mat = coo_matrix((eweight, (src_ids, dst_ids)), shape=(5, 5)) >>> g = dgl.from_scipy(sp_mat) Retrieve the edge weights. >>> g = dgl.from_scipy(sp_mat, eweight_name='w') >>> g.edata['w'] tensor([0.2000, 0.3000, 0.5000], dtype=torch.float64) Create a graph on the first GPU with data type int32. >>> g = dgl.from_scipy(sp_mat, idtype=torch.int32, device='cuda:0') See Also -------- graph from_networkx """ # Sanity check num_rows = sp_mat.shape[0] num_cols = sp_mat.shape[1] if num_rows != num_cols: raise DGLError('Expect the number of rows to be the same as the number of columns for ' 'sp_mat, got {:d} and {:d}.'.format(num_rows, num_cols)) (sparse_fmt, arrays), urange, vrange = utils.graphdata2tensors(sp_mat, idtype) g = create_from_edges(sparse_fmt, arrays, '_N', '_E', '_N', urange, vrange) if eweight_name is not None: g.edata[eweight_name] = F.tensor(sp_mat.data) return g.to(device)
[ "def", "from_scipy", "(", "sp_mat", ",", "eweight_name", "=", "None", ",", "idtype", "=", "None", ",", "device", "=", "None", ")", ":", "# Sanity check", "num_rows", "=", "sp_mat", ".", "shape", "[", "0", "]", "num_cols", "=", "sp_mat", ".", "shape", "...
https://github.com/dmlc/dgl/blob/8d14a739bc9e446d6c92ef83eafe5782398118de/python/dgl/convert.py#L1000-L1087
MultiAgentLearning/playground
8c06a21da5758b570b708e9dd3337e1fa1e67e71
pommerman/graphics.py
python
Viewer.close
(self)
[]
def close(self): self.window.close() self.isopen = False
[ "def", "close", "(", "self", ")", ":", "self", ".", "window", ".", "close", "(", ")", "self", ".", "isopen", "=", "False" ]
https://github.com/MultiAgentLearning/playground/blob/8c06a21da5758b570b708e9dd3337e1fa1e67e71/pommerman/graphics.py#L75-L77
paulwinex/pw_MultiScriptEditor
e447e99f87cb07e238baf693b7e124e50efdbc51
multi_script_editor/jedi/parser/representation.py
python
Statement.set_expression_list
(self, lst)
It's necessary for some "hacks" to change the expression_list.
It's necessary for some "hacks" to change the expression_list.
[ "It", "s", "necessary", "for", "some", "hacks", "to", "change", "the", "expression_list", "." ]
def set_expression_list(self, lst): """It's necessary for some "hacks" to change the expression_list.""" self._expression_list = lst
[ "def", "set_expression_list", "(", "self", ",", "lst", ")", ":", "self", ".", "_expression_list", "=", "lst" ]
https://github.com/paulwinex/pw_MultiScriptEditor/blob/e447e99f87cb07e238baf693b7e124e50efdbc51/multi_script_editor/jedi/parser/representation.py#L1220-L1222
numba/numba
bf480b9e0da858a65508c2b17759a72ee6a44c51
numba/core/pythonapi.py
python
PythonAPI.number_rshift
(self, lhs, rhs, inplace=False)
return self._call_number_operator("Rshift", lhs, rhs, inplace=inplace)
[]
def number_rshift(self, lhs, rhs, inplace=False): return self._call_number_operator("Rshift", lhs, rhs, inplace=inplace)
[ "def", "number_rshift", "(", "self", ",", "lhs", ",", "rhs", ",", "inplace", "=", "False", ")", ":", "return", "self", ".", "_call_number_operator", "(", "\"Rshift\"", ",", "lhs", ",", "rhs", ",", "inplace", "=", "inplace", ")" ]
https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/core/pythonapi.py#L593-L594
PokemonGoF/PokemonGo-Bot-Desktop
4bfa94f0183406c6a86f93645eff7abd3ad4ced8
build/pywin/Lib/_pyio.py
python
TextIOBase.truncate
(self, pos=None)
Truncate size to pos.
Truncate size to pos.
[ "Truncate", "size", "to", "pos", "." ]
def truncate(self, pos=None): """Truncate size to pos.""" self._unsupported("truncate")
[ "def", "truncate", "(", "self", ",", "pos", "=", "None", ")", ":", "self", ".", "_unsupported", "(", "\"truncate\"", ")" ]
https://github.com/PokemonGoF/PokemonGo-Bot-Desktop/blob/4bfa94f0183406c6a86f93645eff7abd3ad4ced8/build/pywin/Lib/_pyio.py#L1326-L1328
mcfletch/pyopengl
02d11dad9ff18e50db10e975c4756e17bf198464
OpenGL/GL/NV/shader_buffer_store.py
python
glInitShaderBufferStoreNV
()
return extensions.hasGLExtension( _EXTENSION_NAME )
Return boolean indicating whether this extension is available
Return boolean indicating whether this extension is available
[ "Return", "boolean", "indicating", "whether", "this", "extension", "is", "available" ]
def glInitShaderBufferStoreNV(): '''Return boolean indicating whether this extension is available''' from OpenGL import extensions return extensions.hasGLExtension( _EXTENSION_NAME )
[ "def", "glInitShaderBufferStoreNV", "(", ")", ":", "from", "OpenGL", "import", "extensions", "return", "extensions", ".", "hasGLExtension", "(", "_EXTENSION_NAME", ")" ]
https://github.com/mcfletch/pyopengl/blob/02d11dad9ff18e50db10e975c4756e17bf198464/OpenGL/GL/NV/shader_buffer_store.py#L44-L47
kozec/syncthing-gtk
01eeeb9ed485232e145bf39d90142832e1c9751e
syncthing_gtk/tools.py
python
set_logging_level
(verbose, debug)
Sets logging level
Sets logging level
[ "Sets", "logging", "level" ]
def set_logging_level(verbose, debug): """ Sets logging level """ logger = logging.getLogger() if debug: # everything logger.setLevel(0) elif verbose: # everything but debug logger.setLevel(11) else: # INFO and worse logger.setLevel(20) if (debug or verbose) and IS_WINDOWS: # Windows executable has no console to output to, so output is # written to logfile as well import tempfile logfile = tempfile.NamedTemporaryFile(delete=False, prefix="Syncthing-GTK-", suffix=".log") logfile.close() h = logging.FileHandler(logfile.name) h.setFormatter(logging.Formatter(LOG_FORMAT)) logging.getLogger().addHandler(h)
[ "def", "set_logging_level", "(", "verbose", ",", "debug", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", ")", "if", "debug", ":", "# everything", "logger", ".", "setLevel", "(", "0", ")", "elif", "verbose", ":", "# everything but debug", "logger"...
https://github.com/kozec/syncthing-gtk/blob/01eeeb9ed485232e145bf39d90142832e1c9751e/syncthing_gtk/tools.py#L277-L296
thinkle/gourmet
8af29c8ded24528030e5ae2ea3461f61c1e5a575
gourmet/gtk_extras/pageable_store.py
python
PageableViewStore._setup_parent_
(self, view, columns=[])
[]
def _setup_parent_ (self, view, columns=[]): self.parent_list = self.view = view self.unsorted_parent = self.unsorted_view = self.view self.columns = columns
[ "def", "_setup_parent_", "(", "self", ",", "view", ",", "columns", "=", "[", "]", ")", ":", "self", ".", "parent_list", "=", "self", ".", "view", "=", "view", "self", ".", "unsorted_parent", "=", "self", ".", "unsorted_view", "=", "self", ".", "view", ...
https://github.com/thinkle/gourmet/blob/8af29c8ded24528030e5ae2ea3461f61c1e5a575/gourmet/gtk_extras/pageable_store.py#L321-L324
OpenMDAO/OpenMDAO1
791a6fbbb7d266f3dcbc1f7bde3ae03a70dc1317
openmdao/recorders/sqlite_recorder.py
python
SqliteRecorder.startup
(self, group)
[]
def startup(self, group): super(SqliteRecorder, self).startup(group) # Need this for use when recording the metadata # Can't do this in the record_metadata method because it only gets # called for rank 0 when running in parallel and so the MPI gather # that is called in that function won't work. All processes # need to participate in that collective call self.model_viewer_data = get_model_viewer_data(group)
[ "def", "startup", "(", "self", ",", "group", ")", ":", "super", "(", "SqliteRecorder", ",", "self", ")", ".", "startup", "(", "group", ")", "# Need this for use when recording the metadata", "# Can't do this in the record_metadata method because it only gets", "# called f...
https://github.com/OpenMDAO/OpenMDAO1/blob/791a6fbbb7d266f3dcbc1f7bde3ae03a70dc1317/openmdao/recorders/sqlite_recorder.py#L63-L71
bashtage/arch
05fcc86500603352fb3e6035230a83d99e07fdc1
arch/_version.py
python
render_pep440_post
(pieces)
return rendered
TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0]
TAG[.postDISTANCE[.dev0]+gHEX] .
[ "TAG", "[", ".", "postDISTANCE", "[", ".", "dev0", "]", "+", "gHEX", "]", "." ]
def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered
[ "def", "render_pep440_post", "(", "pieces", ")", ":", "if", "pieces", "[", "\"closest-tag\"", "]", ":", "rendered", "=", "pieces", "[", "\"closest-tag\"", "]", "if", "pieces", "[", "\"distance\"", "]", "or", "pieces", "[", "\"dirty\"", "]", ":", "rendered", ...
https://github.com/bashtage/arch/blob/05fcc86500603352fb3e6035230a83d99e07fdc1/arch/_version.py#L378-L402
XX-net/XX-Net
a9898cfcf0084195fb7e69b6bc834e59aecdf14f
python3.8.2/Lib/site-packages/pip/_vendor/ipaddress.py
python
IPv6Address.is_private
(self)
return any(self in net for net in self._constants._private_networks)
Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv6-special-registry.
Test if this address is allocated for private networks.
[ "Test", "if", "this", "address", "is", "allocated", "for", "private", "networks", "." ]
def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv6-special-registry. """ return any(self in net for net in self._constants._private_networks)
[ "def", "is_private", "(", "self", ")", ":", "return", "any", "(", "self", "in", "net", "for", "net", "in", "self", ".", "_constants", ".", "_private_networks", ")" ]
https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/site-packages/pip/_vendor/ipaddress.py#L2091-L2099
iclavera/learning_to_adapt
bd7d99ba402521c96631e7d09714128f549db0f1
learning_to_adapt/mujoco_py/mjtypes.py
python
MjModelWrapper.tex_width
(self)
return arr
[]
def tex_width(self): arr = np.reshape(np.fromiter(self._wrapped.contents.tex_width, dtype=np.int, count=(self.ntex*1)), (self.ntex, 1, )) arr.setflags(write=False) return arr
[ "def", "tex_width", "(", "self", ")", ":", "arr", "=", "np", ".", "reshape", "(", "np", ".", "fromiter", "(", "self", ".", "_wrapped", ".", "contents", ".", "tex_width", ",", "dtype", "=", "np", ".", "int", ",", "count", "=", "(", "self", ".", "n...
https://github.com/iclavera/learning_to_adapt/blob/bd7d99ba402521c96631e7d09714128f549db0f1/learning_to_adapt/mujoco_py/mjtypes.py#L4986-L4989
xilaili/AOGNet
eb6376647c9baee885af990e991a8f823c3d1782
symbol/node.py
python
Tnode_Op
(data, cfg, aog, node, NodeIdtoSym, in_slices, out_slices, stride=(1, 1), bn_mom=0.9, workspace=512, name='')
slice channel first and perform operation on each slice
slice channel first and perform operation on each slice
[ "slice", "channel", "first", "and", "perform", "operation", "on", "each", "slice" ]
def Tnode_Op(data, cfg, aog, node, NodeIdtoSym, in_slices, out_slices, stride=(1, 1), bn_mom=0.9, workspace=512, name=''): ''' slice channel first and perform operation on each slice ''' # slice arr = aog.primitive_set[node.array_idx] in_channels = in_slices[arr.x2 + 1] - in_slices[arr.x1] Tnode_feat = mx.symbol.slice_axis(data=data, axis=1, begin=in_slices[arr.x1], end=in_slices[arr.x2 + 1], name=name + 'Tnode_{}_feat_slice'.format(node.id)) # perform an operation out_channels = out_slices[arr.x2 + 1] - out_slices[arr.x1] Tnode_out = eval(cfg.AOG.Tnode_basic_unit)(data=Tnode_feat, cfg=cfg, num_filters=out_channels, in_channels=in_channels, stride=stride, bn_mom=bn_mom, workspace=workspace, name=name + "Tnode_{}".format(node.id)) NodeIdtoSym[node.id] = Tnode_out
[ "def", "Tnode_Op", "(", "data", ",", "cfg", ",", "aog", ",", "node", ",", "NodeIdtoSym", ",", "in_slices", ",", "out_slices", ",", "stride", "=", "(", "1", ",", "1", ")", ",", "bn_mom", "=", "0.9", ",", "workspace", "=", "512", ",", "name", "=", ...
https://github.com/xilaili/AOGNet/blob/eb6376647c9baee885af990e991a8f823c3d1782/symbol/node.py#L5-L17
mcedit/pymclevel
8bf7b3d76479e007a51f3055198a8bcddb626c84
cachefunc.py
python
lfu_cache
(maxsize=100)
return decorating_function
Least-frequenty-used cache decorator. Arguments to the cached function must be hashable. Cache performance statistics stored in f.hits and f.misses. Clear the cache with f.clear(). http://en.wikipedia.org/wiki/Least_Frequently_Used
Least-frequenty-used cache decorator.
[ "Least", "-", "frequenty", "-", "used", "cache", "decorator", "." ]
def lfu_cache(maxsize=100): '''Least-frequenty-used cache decorator. Arguments to the cached function must be hashable. Cache performance statistics stored in f.hits and f.misses. Clear the cache with f.clear(). http://en.wikipedia.org/wiki/Least_Frequently_Used ''' def decorating_function(user_function): cache = {} # mapping of args to results use_count = Counter() # times each key has been accessed kwd_mark = object() # separate positional and keyword args @functools.wraps(user_function) def wrapper(*args, **kwds): key = args if kwds: key += (kwd_mark,) + tuple(sorted(kwds.items())) use_count[key] += 1 # get cache entry or compute if not found try: result = cache[key] wrapper.hits += 1 except KeyError: result = user_function(*args, **kwds) cache[key] = result wrapper.misses += 1 # purge least frequently used cache entry if len(cache) > maxsize: for key, _ in nsmallest(maxsize // 10, use_count.iteritems(), key=itemgetter(1)): del cache[key], use_count[key] return result def clear(): cache.clear() use_count.clear() wrapper.hits = wrapper.misses = 0 wrapper.hits = wrapper.misses = 0 wrapper.clear = clear return wrapper return decorating_function
[ "def", "lfu_cache", "(", "maxsize", "=", "100", ")", ":", "def", "decorating_function", "(", "user_function", ")", ":", "cache", "=", "{", "}", "# mapping of args to results", "use_count", "=", "Counter", "(", ")", "# times each key has been accessed", "kwd_mark", ...
https://github.com/mcedit/pymclevel/blob/8bf7b3d76479e007a51f3055198a8bcddb626c84/cachefunc.py#L92-L140
hottbox/hottbox
26580018ec6d38a1b08266c04ce4408c9e276130
hottbox/core/structures.py
python
TensorCPD.mode_names
(self)
return super(TensorCPD, self).mode_names
Description of the physical modes for a ``TensorCPD`` Returns ------- list[str]
Description of the physical modes for a ``TensorCPD``
[ "Description", "of", "the", "physical", "modes", "for", "a", "TensorCPD" ]
def mode_names(self): """ Description of the physical modes for a ``TensorCPD`` Returns ------- list[str] """ return super(TensorCPD, self).mode_names
[ "def", "mode_names", "(", "self", ")", ":", "return", "super", "(", "TensorCPD", ",", "self", ")", ".", "mode_names" ]
https://github.com/hottbox/hottbox/blob/26580018ec6d38a1b08266c04ce4408c9e276130/hottbox/core/structures.py#L1283-L1290
osirislab/Fentanyl
6635ec80bade773125c3444bf8ab1bb0761f4aec
FtlHooks.py
python
FtlHooks.preprocess
(self, name)
return 0
[]
def preprocess(self, name): self.cmd = name return 0
[ "def", "preprocess", "(", "self", ",", "name", ")", ":", "self", ".", "cmd", "=", "name", "return", "0" ]
https://github.com/osirislab/Fentanyl/blob/6635ec80bade773125c3444bf8ab1bb0761f4aec/FtlHooks.py#L16-L18
USC-ACTLab/crazyswarm
424d074f7e37d616847ea11dd3a448f89ec3c457
ros_ws/src/crazyswarm/scripts/pycrazyswarm/linuxjsdev.py
python
_JS._read_all_events
(self)
Consume all the events queued up in the JS device
Consume all the events queued up in the JS device
[ "Consume", "all", "the", "events", "queued", "up", "in", "the", "JS", "device" ]
def _read_all_events(self): """Consume all the events queued up in the JS device""" try: while True: data = self._f.read(struct.calcsize(JS_EVENT_FMT)) jsdata = struct.unpack(JS_EVENT_FMT, data) self.__updatestate(jsdata) except IOError as e: if e.errno != 11: logger.info(str(e)) self._f.close() self._f = None raise IOError("Device has been disconnected") except TypeError: pass except ValueError: # This will happen if I/O operations are done on a closed device, # which is the case when you first close and then open the device # while switching device. But, in order for SDL2 to work on Linux # (for debugging) the device needs to be closed before it's opened. # This is the workaround to make both cases work. pass
[ "def", "_read_all_events", "(", "self", ")", ":", "try", ":", "while", "True", ":", "data", "=", "self", ".", "_f", ".", "read", "(", "struct", ".", "calcsize", "(", "JS_EVENT_FMT", ")", ")", "jsdata", "=", "struct", ".", "unpack", "(", "JS_EVENT_FMT",...
https://github.com/USC-ACTLab/crazyswarm/blob/424d074f7e37d616847ea11dd3a448f89ec3c457/ros_ws/src/crazyswarm/scripts/pycrazyswarm/linuxjsdev.py#L161-L182
GoogleCloudPlatform/ml-on-gcp
ffd88931674e08ef6b0b20de27700ed1da61772c
example_zoo/tensorflow/probability/vae/trainer/vae.py
python
make_decoder
(activation, latent_size, output_shape, base_depth)
return decoder
Creates the decoder function. Args: activation: Activation function in hidden layers. latent_size: Dimensionality of the encoding. output_shape: The output image shape. base_depth: Smallest depth for a layer. Returns: decoder: A `callable` mapping a `Tensor` of encodings to a `tfd.Distribution` instance over images.
Creates the decoder function.
[ "Creates", "the", "decoder", "function", "." ]
def make_decoder(activation, latent_size, output_shape, base_depth): """Creates the decoder function. Args: activation: Activation function in hidden layers. latent_size: Dimensionality of the encoding. output_shape: The output image shape. base_depth: Smallest depth for a layer. Returns: decoder: A `callable` mapping a `Tensor` of encodings to a `tfd.Distribution` instance over images. """ deconv = functools.partial( tf.keras.layers.Conv2DTranspose, padding="SAME", activation=activation) conv = functools.partial( tf.keras.layers.Conv2D, padding="SAME", activation=activation) decoder_net = tf.keras.Sequential([ deconv(2 * base_depth, 7, padding="VALID"), deconv(2 * base_depth, 5), deconv(2 * base_depth, 5, 2), deconv(base_depth, 5), deconv(base_depth, 5, 2), deconv(base_depth, 5), conv(output_shape[-1], 5, activation=None), ]) def decoder(codes): original_shape = tf.shape(input=codes) # Collapse the sample and batch dimension and convert to rank-4 tensor for # use with a convolutional decoder network. codes = tf.reshape(codes, (-1, 1, 1, latent_size)) logits = decoder_net(codes) logits = tf.reshape( logits, shape=tf.concat([original_shape[:-1], output_shape], axis=0)) return tfd.Independent(tfd.Bernoulli(logits=logits), reinterpreted_batch_ndims=len(output_shape), name="image") return decoder
[ "def", "make_decoder", "(", "activation", ",", "latent_size", ",", "output_shape", ",", "base_depth", ")", ":", "deconv", "=", "functools", ".", "partial", "(", "tf", ".", "keras", ".", "layers", ".", "Conv2DTranspose", ",", "padding", "=", "\"SAME\"", ",", ...
https://github.com/GoogleCloudPlatform/ml-on-gcp/blob/ffd88931674e08ef6b0b20de27700ed1da61772c/example_zoo/tensorflow/probability/vae/trainer/vae.py#L229-L269
jazzband/django-queued-storage
1cbb3c973e2dc6b1f4b8823ac3306111581067a5
queued_storage/backends.py
python
QueuedStorage.get_modified_time
(self, name)
return self.get_storage(name).get_modified_time(name)
Django +1.10 Returns the last modified time (as datetime object) of the file specified by name. :param name: file name :type name: str :rtype: :class:`~python:datetime.datetime`
Django +1.10 Returns the last modified time (as datetime object) of the file specified by name.
[ "Django", "+", "1", ".", "10", "Returns", "the", "last", "modified", "time", "(", "as", "datetime", "object", ")", "of", "the", "file", "specified", "by", "name", "." ]
def get_modified_time(self, name): """ Django +1.10 Returns the last modified time (as datetime object) of the file specified by name. :param name: file name :type name: str :rtype: :class:`~python:datetime.datetime` """ return self.get_storage(name).get_modified_time(name)
[ "def", "get_modified_time", "(", "self", ",", "name", ")", ":", "return", "self", ".", "get_storage", "(", "name", ")", ".", "get_modified_time", "(", "name", ")" ]
https://github.com/jazzband/django-queued-storage/blob/1cbb3c973e2dc6b1f4b8823ac3306111581067a5/queued_storage/backends.py#L373-L384
puddletag/puddletag
e5fb85c34ff2e699ca35274298d1921f2598be98
source/puddlestuff/audioinfo/util.py
python
get_total
(tag)
If tag['track'] is of format x/y returns, y.
If tag['track'] is of format x/y returns, y.
[ "If", "tag", "[", "track", "]", "is", "of", "format", "x", "/", "y", "returns", "y", "." ]
def get_total(tag): """If tag['track'] is of format x/y returns, y.""" value = to_string(tag['track']) try: return value.split('/')[1].strip() except IndexError: raise KeyError('__total')
[ "def", "get_total", "(", "tag", ")", ":", "value", "=", "to_string", "(", "tag", "[", "'track'", "]", ")", "try", ":", "return", "value", ".", "split", "(", "'/'", ")", "[", "1", "]", ".", "strip", "(", ")", "except", "IndexError", ":", "raise", ...
https://github.com/puddletag/puddletag/blob/e5fb85c34ff2e699ca35274298d1921f2598be98/source/puddlestuff/audioinfo/util.py#L271-L277
PokemonGoF/PokemonGo-Bot-Desktop
4bfa94f0183406c6a86f93645eff7abd3ad4ced8
build/pywin/Lib/tempfile.py
python
gettempdir
()
return tempdir
Accessor for tempfile.tempdir.
Accessor for tempfile.tempdir.
[ "Accessor", "for", "tempfile", ".", "tempdir", "." ]
def gettempdir(): """Accessor for tempfile.tempdir.""" global tempdir if tempdir is None: _once_lock.acquire() try: if tempdir is None: tempdir = _get_default_tempdir() finally: _once_lock.release() return tempdir
[ "def", "gettempdir", "(", ")", ":", "global", "tempdir", "if", "tempdir", "is", "None", ":", "_once_lock", ".", "acquire", "(", ")", "try", ":", "if", "tempdir", "is", "None", ":", "tempdir", "=", "_get_default_tempdir", "(", ")", "finally", ":", "_once_...
https://github.com/PokemonGoF/PokemonGo-Bot-Desktop/blob/4bfa94f0183406c6a86f93645eff7abd3ad4ced8/build/pywin/Lib/tempfile.py#L268-L278
openstack/mistral
b2d6de569c7bba96cd3179189ffbcee6b7a28c1f
mistral/hacking/checks.py
python
BaseASTChecker.__init__
(self, tree, filename)
This object is created automatically by pep8. :param tree: an AST tree :param filename: name of the file being analyzed (ignored by our checks)
This object is created automatically by pep8.
[ "This", "object", "is", "created", "automatically", "by", "pep8", "." ]
def __init__(self, tree, filename): """This object is created automatically by pep8. :param tree: an AST tree :param filename: name of the file being analyzed (ignored by our checks) """ self._tree = tree self._errors = []
[ "def", "__init__", "(", "self", ",", "tree", ",", "filename", ")", ":", "self", ".", "_tree", "=", "tree", "self", ".", "_errors", "=", "[", "]" ]
https://github.com/openstack/mistral/blob/b2d6de569c7bba96cd3179189ffbcee6b7a28c1f/mistral/hacking/checks.py#L129-L137
Jenyay/outwiker
50530cf7b3f71480bb075b2829bc0669773b835b
src/outwiker/gui/controls/ultimatelistctrl.py
python
UltimateListCtrl.OnGetItemToolTip
(self, item, col)
This function **must** be overloaded in the derived class for a control with ``ULC_VIRTUAL`` style. It should return the string containing the text of the tooltip for the specified item. :param `item`: an integer specifying the item index; :param `col`: the column index to which the item belongs to.
This function **must** be overloaded in the derived class for a control with ``ULC_VIRTUAL`` style. It should return the string containing the text of the tooltip for the specified item.
[ "This", "function", "**", "must", "**", "be", "overloaded", "in", "the", "derived", "class", "for", "a", "control", "with", "ULC_VIRTUAL", "style", ".", "It", "should", "return", "the", "string", "containing", "the", "text", "of", "the", "tooltip", "for", ...
def OnGetItemToolTip(self, item, col): """ This function **must** be overloaded in the derived class for a control with ``ULC_VIRTUAL`` style. It should return the string containing the text of the tooltip for the specified item. :param `item`: an integer specifying the item index; :param `col`: the column index to which the item belongs to. """ # this is a pure virtual function, in fact - which is not really pure # because the controls which are not virtual don't need to implement it raise Exception("UltimateListCtrl.OnGetItemToolTip not supposed to be called")
[ "def", "OnGetItemToolTip", "(", "self", ",", "item", ",", "col", ")", ":", "# this is a pure virtual function, in fact - which is not really pure", "# because the controls which are not virtual don't need to implement it", "raise", "Exception", "(", "\"UltimateListCtrl.OnGetItemToolTip...
https://github.com/Jenyay/outwiker/blob/50530cf7b3f71480bb075b2829bc0669773b835b/src/outwiker/gui/controls/ultimatelistctrl.py#L12576-L12588
pm4py/pm4py-core
7807b09a088b02199cd0149d724d0e28793971bf
pm4py/visualization/dotted_chart/visualizer.py
python
matplotlib_view
(figure: str)
Views the dotted chart on the screen using Matplotlib Parameters --------------- figure Path to the dotted chart
Views the dotted chart on the screen using Matplotlib
[ "Views", "the", "dotted", "chart", "on", "the", "screen", "using", "Matplotlib" ]
def matplotlib_view(figure: str): """ Views the dotted chart on the screen using Matplotlib Parameters --------------- figure Path to the dotted chart """ import matplotlib.pyplot as plt import matplotlib.image as mpimg img = mpimg.imread(figure) plt.imshow(img) plt.show()
[ "def", "matplotlib_view", "(", "figure", ":", "str", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "import", "matplotlib", ".", "image", "as", "mpimg", "img", "=", "mpimg", ".", "imread", "(", "figure", ")", "plt", ".", "imshow", "(", "...
https://github.com/pm4py/pm4py-core/blob/7807b09a088b02199cd0149d724d0e28793971bf/pm4py/visualization/dotted_chart/visualizer.py#L107-L121
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
packages/source/nova/nova/api/openstack/xmlutil.py
python
MasterTemplate.attach
(self, *slaves)
Attach one or more slave templates. Attaches one or more slave templates to the master template. Slave templates must have a root element with the same tag as the master template. The slave template's apply() method will be called to determine if the slave should be applied to this master; if it returns False, that slave will be skipped. (This allows filtering of slaves based on the version of the master template.)
Attach one or more slave templates.
[ "Attach", "one", "or", "more", "slave", "templates", "." ]
def attach(self, *slaves): """Attach one or more slave templates. Attaches one or more slave templates to the master template. Slave templates must have a root element with the same tag as the master template. The slave template's apply() method will be called to determine if the slave should be applied to this master; if it returns False, that slave will be skipped. (This allows filtering of slaves based on the version of the master template.) """ slave_list = [] for slave in slaves: slave = slave.wrap() # Make sure we have a tree match if slave.root.tag != self.root.tag: slavetag = slave.root.tag mastertag = self.root.tag msg = _("Template tree mismatch; adding slave %(slavetag)s " "to master %(mastertag)s") % locals() raise ValueError(msg) # Make sure slave applies to this template if not slave.apply(self): continue slave_list.append(slave) # Add the slaves self.slaves.extend(slave_list)
[ "def", "attach", "(", "self", ",", "*", "slaves", ")", ":", "slave_list", "=", "[", "]", "for", "slave", "in", "slaves", ":", "slave", "=", "slave", ".", "wrap", "(", ")", "# Make sure we have a tree match", "if", "slave", ".", "root", ".", "tag", "!="...
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/nova/nova/api/openstack/xmlutil.py#L724-L755
etetoolkit/ete
2b207357dc2a40ccad7bfd8f54964472c72e4726
ete3/nexml/_nexml.py
python
CellSet.exportLiteralAttributes
(self, outfile, level, already_processed, name_)
[]
def exportLiteralAttributes(self, outfile, level, already_processed, name_): if self.cell is not None and 'cell' not in already_processed: already_processed.append('cell') showIndent(outfile, level) outfile.write('cell = "%s",\n' % (self.cell,)) super(CellSet, self).exportLiteralAttributes(outfile, level, already_processed, name_)
[ "def", "exportLiteralAttributes", "(", "self", ",", "outfile", ",", "level", ",", "already_processed", ",", "name_", ")", ":", "if", "self", ".", "cell", "is", "not", "None", "and", "'cell'", "not", "in", "already_processed", ":", "already_processed", ".", "...
https://github.com/etetoolkit/ete/blob/2b207357dc2a40ccad7bfd8f54964472c72e4726/ete3/nexml/_nexml.py#L11505-L11510
PaddlePaddle/PaddleX
2bab73f81ab54e328204e7871e6ae4a82e719f5d
paddlex_restful/restful/project/visualize.py
python
gray2pseudo
(gray_image)
return pseudo_img
将分割的结果映射到图片 Args: gray_image: 灰度图
将分割的结果映射到图片
[ "将分割的结果映射到图片" ]
def gray2pseudo(gray_image): """ 将分割的结果映射到图片 Args: gray_image: 灰度图 """ color_map = get_color_map_list(256) color_map = np.array(color_map).astype("uint8") # 用OpenCV进行色彩映射 c1 = cv2.LUT(gray_image, color_map[:, 0]) c2 = cv2.LUT(gray_image, color_map[:, 1]) c3 = cv2.LUT(gray_image, color_map[:, 2]) pseudo_img = np.dstack((c1, c2, c3)) return pseudo_img
[ "def", "gray2pseudo", "(", "gray_image", ")", ":", "color_map", "=", "get_color_map_list", "(", "256", ")", "color_map", "=", "np", ".", "array", "(", "color_map", ")", ".", "astype", "(", "\"uint8\"", ")", "# 用OpenCV进行色彩映射", "c1", "=", "cv2", ".", "LUT", ...
https://github.com/PaddlePaddle/PaddleX/blob/2bab73f81ab54e328204e7871e6ae4a82e719f5d/paddlex_restful/restful/project/visualize.py#L231-L244
Axelrod-Python/Axelrod
00e18323c1b1af74df873773e44f31e1b9a299c6
axelrod/player.py
python
Player.__getstate__
(self)
return self.__dict__
Used for pickling. Override if Player contains unpickleable attributes.
Used for pickling. Override if Player contains unpickleable attributes.
[ "Used", "for", "pickling", ".", "Override", "if", "Player", "contains", "unpickleable", "attributes", "." ]
def __getstate__(self): """Used for pickling. Override if Player contains unpickleable attributes.""" return self.__dict__
[ "def", "__getstate__", "(", "self", ")", ":", "return", "self", ".", "__dict__" ]
https://github.com/Axelrod-Python/Axelrod/blob/00e18323c1b1af74df873773e44f31e1b9a299c6/axelrod/player.py#L227-L229
laoqiu/pypress
06cb3ac185936a576c156ed14e5271b4cfc5ebca
pypress/twitter.py
python
User.AsDict
(self)
return data
A dict representation of this twitter.User instance. The return value uses the same key names as the JSON representation. Return: A dict representing this twitter.User instance
A dict representation of this twitter.User instance.
[ "A", "dict", "representation", "of", "this", "twitter", ".", "User", "instance", "." ]
def AsDict(self): '''A dict representation of this twitter.User instance. The return value uses the same key names as the JSON representation. Return: A dict representing this twitter.User instance ''' data = {} if self.id: data['id'] = self.id if self.name: data['name'] = self.name if self.screen_name: data['screen_name'] = self.screen_name if self.location: data['location'] = self.location if self.description: data['description'] = self.description if self.profile_image_url: data['profile_image_url'] = self.profile_image_url if self.profile_background_tile is not None: data['profile_background_tile'] = self.profile_background_tile if self.profile_background_image_url: data['profile_sidebar_fill_color'] = self.profile_background_image_url if self.profile_background_color: data['profile_background_color'] = self.profile_background_color if self.profile_link_color: data['profile_link_color'] = self.profile_link_color if self.profile_text_color: data['profile_text_color'] = self.profile_text_color if self.protected is not None: data['protected'] = self.protected if self.utc_offset: data['utc_offset'] = self.utc_offset if self.time_zone: data['time_zone'] = self.time_zone if self.url: data['url'] = self.url if self.status: data['status'] = self.status.AsDict() if self.friends_count: data['friends_count'] = self.friends_count if self.followers_count: data['followers_count'] = self.followers_count if self.statuses_count: data['statuses_count'] = self.statuses_count if self.favourites_count: data['favourites_count'] = self.favourites_count if self.geo_enabled: data['geo_enabled'] = self.geo_enabled return data
[ "def", "AsDict", "(", "self", ")", ":", "data", "=", "{", "}", "if", "self", ".", "id", ":", "data", "[", "'id'", "]", "=", "self", ".", "id", "if", "self", ".", "name", ":", "data", "[", "'name'", "]", "=", "self", ".", "name", "if", "self",...
https://github.com/laoqiu/pypress/blob/06cb3ac185936a576c156ed14e5271b4cfc5ebca/pypress/twitter.py#L1050-L1101
wikimedia/pywikibot
81a01ffaec7271bf5b4b170f85a80388420a4e78
pywikibot/logentries.py
python
LogEntry.__repr__
(self)
return '<{}({}, logid={})>'.format(type(self).__name__, self.site.sitename, self.logid())
Return a string representation of LogEntry object.
Return a string representation of LogEntry object.
[ "Return", "a", "string", "representation", "of", "LogEntry", "object", "." ]
def __repr__(self) -> str: """Return a string representation of LogEntry object.""" return '<{}({}, logid={})>'.format(type(self).__name__, self.site.sitename, self.logid())
[ "def", "__repr__", "(", "self", ")", "->", "str", ":", "return", "'<{}({}, logid={})>'", ".", "format", "(", "type", "(", "self", ")", ".", "__name__", ",", "self", ".", "site", ".", "sitename", ",", "self", ".", "logid", "(", ")", ")" ]
https://github.com/wikimedia/pywikibot/blob/81a01ffaec7271bf5b4b170f85a80388420a4e78/pywikibot/logentries.py#L68-L71
itamarst/crochet
deea55f870028c241e0b8c64c317224fb571b78a
versioneer.py
python
git_pieces_from_vcs
(tag_prefix, root, verbose, run_command=run_command)
return pieces
Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree.
Get version from 'git describe' in the root of the source tree.
[ "Get", "version", "from", "git", "describe", "in", "the", "root", "of", "the", "source", "tree", "." ]
def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ if not os.path.exists(os.path.join(root, ".git")): if verbose: print("no .git in %s" % root) raise NotThisMethod("no .git directory") GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", "%s*" % tag_prefix], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%s'" % describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" % (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits return pieces
[ "def", "git_pieces_from_vcs", "(", "tag_prefix", ",", "root", ",", "verbose", ",", "run_command", "=", "run_command", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "root", ",", "\".git\"", ")", ")", ...
https://github.com/itamarst/crochet/blob/deea55f870028c241e0b8c64c317224fb571b78a/versioneer.py#L1044-L1124
mars-project/mars
6afd7ed86db77f29cc9470485698ef192ecc6d33
mars/services/lifecycle/api/oscar.py
python
LifecycleAPI.incref_tileables
(self, tileable_keys: List[str])
return await self._lifecycle_tracker_ref.incref_tileables(tileable_keys)
Incref tileables. Parameters ---------- tileable_keys : list List of tileable keys.
Incref tileables.
[ "Incref", "tileables", "." ]
async def incref_tileables(self, tileable_keys: List[str]): """ Incref tileables. Parameters ---------- tileable_keys : list List of tileable keys. """ return await self._lifecycle_tracker_ref.incref_tileables(tileable_keys)
[ "async", "def", "incref_tileables", "(", "self", ",", "tileable_keys", ":", "List", "[", "str", "]", ")", ":", "return", "await", "self", ".", "_lifecycle_tracker_ref", ".", "incref_tileables", "(", "tileable_keys", ")" ]
https://github.com/mars-project/mars/blob/6afd7ed86db77f29cc9470485698ef192ecc6d33/mars/services/lifecycle/api/oscar.py#L76-L85
natewong1313/bird-bot
0a76dca2157c021c6cd5734928b1ffcf46a2b3b2
webhook.py
python
DiscordWebhook.add_embed
(self, embed)
[]
def add_embed(self, embed): self.embeds.append(embed.__dict__ if isinstance(embed, DiscordEmbed) else embed)
[ "def", "add_embed", "(", "self", ",", "embed", ")", ":", "self", ".", "embeds", ".", "append", "(", "embed", ".", "__dict__", "if", "isinstance", "(", "embed", ",", "DiscordEmbed", ")", "else", "embed", ")" ]
https://github.com/natewong1313/bird-bot/blob/0a76dca2157c021c6cd5734928b1ffcf46a2b3b2/webhook.py#L19-L20
wikimedia/pywikibot
81a01ffaec7271bf5b4b170f85a80388420a4e78
pywikibot/userinterfaces/terminal_interface_base.py
python
UI.flush
(self)
Output cached text. .. versionadded:: 7.0
Output cached text.
[ "Output", "cached", "text", "." ]
def flush(self): """Output cached text. .. versionadded:: 7.0 """ with self.lock: for args, kwargs in self.cache: self.stream_output(*args, **kwargs) self.cache.clear()
[ "def", "flush", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "for", "args", ",", "kwargs", "in", "self", ".", "cache", ":", "self", ".", "stream_output", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "cache", ".", "clea...
https://github.com/wikimedia/pywikibot/blob/81a01ffaec7271bf5b4b170f85a80388420a4e78/pywikibot/userinterfaces/terminal_interface_base.py#L204-L212
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/rigged_configurations/kleber_tree.py
python
KleberTree._repr_
(self)
return "Kleber tree of Cartan type %s and B = %s"%(repr(self._cartan_type), self.B)
Return a text representation of this Kleber tree. EXAMPLES:: sage: from sage.combinat.rigged_configurations.kleber_tree import KleberTree sage: KleberTree(['D', 4, 1], [[2, 2]]) # indirect doctest Kleber tree of Cartan type ['D', 4, 1] and B = ((2, 2),)
Return a text representation of this Kleber tree.
[ "Return", "a", "text", "representation", "of", "this", "Kleber", "tree", "." ]
def _repr_(self): """ Return a text representation of this Kleber tree. EXAMPLES:: sage: from sage.combinat.rigged_configurations.kleber_tree import KleberTree sage: KleberTree(['D', 4, 1], [[2, 2]]) # indirect doctest Kleber tree of Cartan type ['D', 4, 1] and B = ((2, 2),) """ return "Kleber tree of Cartan type %s and B = %s"%(repr(self._cartan_type), self.B)
[ "def", "_repr_", "(", "self", ")", ":", "return", "\"Kleber tree of Cartan type %s and B = %s\"", "%", "(", "repr", "(", "self", ".", "_cartan_type", ")", ",", "self", ".", "B", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/rigged_configurations/kleber_tree.py#L984-L994
burke-software/schooldriver
a07262ba864aee0182548ecceb661e49c925725f
appy/fields/__init__.py
python
Field.isClientVisible
(self, obj)
This method returns True if this field is visible according to master/slave relationships.
This method returns True if this field is visible according to master/slave relationships.
[ "This", "method", "returns", "True", "if", "this", "field", "is", "visible", "according", "to", "master", "/", "slave", "relationships", "." ]
def isClientVisible(self, obj): '''This method returns True if this field is visible according to master/slave relationships.''' masterData = self.getMasterData() if not masterData: return True else: master, masterValue = masterData if masterValue and callable(masterValue): return True reqValue = master.getRequestValue(obj.REQUEST) # reqValue can be a list or not if type(reqValue) not in sutils.sequenceTypes: return reqValue in masterValue else: for m in masterValue: for r in reqValue: if m == r: return True
[ "def", "isClientVisible", "(", "self", ",", "obj", ")", ":", "masterData", "=", "self", ".", "getMasterData", "(", ")", "if", "not", "masterData", ":", "return", "True", "else", ":", "master", ",", "masterValue", "=", "masterData", "if", "masterValue", "an...
https://github.com/burke-software/schooldriver/blob/a07262ba864aee0182548ecceb661e49c925725f/appy/fields/__init__.py#L327-L342
ym2011/POC-EXP
206b22d3a6b2a172359678df33bbc5b2ad04b6c3
K8/Web-Exp/sqlmap/thirdparty/chardet/chardistribution.py
python
CharDistributionAnalysis.get_confidence
(self)
return SURE_YES
return confidence based on existing data
return confidence based on existing data
[ "return", "confidence", "based", "on", "existing", "data" ]
def get_confidence(self): """return confidence based on existing data""" # if we didn't receive any character in our consideration range, # return negative answer if self._mTotalChars <= 0 or self._mFreqChars <= MINIMUM_DATA_THRESHOLD: return SURE_NO if self._mTotalChars != self._mFreqChars: r = (self._mFreqChars / ((self._mTotalChars - self._mFreqChars) * self._mTypicalDistributionRatio)) if r < SURE_YES: return r # normalize confidence (we don't want to be 100% sure) return SURE_YES
[ "def", "get_confidence", "(", "self", ")", ":", "# if we didn't receive any character in our consideration range,", "# return negative answer", "if", "self", ".", "_mTotalChars", "<=", "0", "or", "self", ".", "_mFreqChars", "<=", "MINIMUM_DATA_THRESHOLD", ":", "return", "...
https://github.com/ym2011/POC-EXP/blob/206b22d3a6b2a172359678df33bbc5b2ad04b6c3/K8/Web-Exp/sqlmap/thirdparty/chardet/chardistribution.py#L82-L96
NTMC-Community/MatchZoo-py
0e5c04e1e948aa9277abd5c85ff99d9950d8527f
matchzoo/dataloader/callbacks/histogram.py
python
_trunc_text
(input_text: list, length: list)
return [row[:length[idx]] for idx, row in enumerate(input_text)]
Truncating the input text according to the input length. :param input_text: The input text need to be truncated. :param length: The length used to truncated the text. :return: The truncated text.
Truncating the input text according to the input length.
[ "Truncating", "the", "input", "text", "according", "to", "the", "input", "length", "." ]
def _trunc_text(input_text: list, length: list) -> list: """ Truncating the input text according to the input length. :param input_text: The input text need to be truncated. :param length: The length used to truncated the text. :return: The truncated text. """ return [row[:length[idx]] for idx, row in enumerate(input_text)]
[ "def", "_trunc_text", "(", "input_text", ":", "list", ",", "length", ":", "list", ")", "->", "list", ":", "return", "[", "row", "[", ":", "length", "[", "idx", "]", "]", "for", "idx", ",", "row", "in", "enumerate", "(", "input_text", ")", "]" ]
https://github.com/NTMC-Community/MatchZoo-py/blob/0e5c04e1e948aa9277abd5c85ff99d9950d8527f/matchzoo/dataloader/callbacks/histogram.py#L37-L45
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/plat-mac/aetypes.py
python
Keyword.__repr__
(self)
return "Keyword(%r)" % repr(self.keyword)
[]
def __repr__(self): return "Keyword(%r)" % repr(self.keyword)
[ "def", "__repr__", "(", "self", ")", ":", "return", "\"Keyword(%r)\"", "%", "repr", "(", "self", ".", "keyword", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/plat-mac/aetypes.py#L133-L134
jinfagang/keras_frcnn
a1bc465ae6dc9787bff8ec9199e98540dd930812
predict_kitti.py
python
get_real_coordinates
(ratio, x1, y1, x2, y2)
return real_x1, real_y1, real_x2, real_y2
[]
def get_real_coordinates(ratio, x1, y1, x2, y2): real_x1 = int(round(x1 // ratio)) real_y1 = int(round(y1 // ratio)) real_x2 = int(round(x2 // ratio)) real_y2 = int(round(y2 // ratio)) return real_x1, real_y1, real_x2, real_y2
[ "def", "get_real_coordinates", "(", "ratio", ",", "x1", ",", "y1", ",", "x2", ",", "y2", ")", ":", "real_x1", "=", "int", "(", "round", "(", "x1", "//", "ratio", ")", ")", "real_y1", "=", "int", "(", "round", "(", "y1", "//", "ratio", ")", ")", ...
https://github.com/jinfagang/keras_frcnn/blob/a1bc465ae6dc9787bff8ec9199e98540dd930812/predict_kitti.py#L56-L62
JimmXinu/FanFicFare
bc149a2deb2636320fe50a3e374af6eef8f61889
included_dependencies/soupsieve/css_types.py
python
Immutable.__eq__
(self, other)
return ( isinstance(other, self.__base__()) and all([getattr(other, key) == getattr(self, key) for key in self.__slots__ if key != '_hash']) )
Equal.
Equal.
[ "Equal", "." ]
def __eq__(self, other): """Equal.""" return ( isinstance(other, self.__base__()) and all([getattr(other, key) == getattr(self, key) for key in self.__slots__ if key != '_hash']) )
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "return", "(", "isinstance", "(", "other", ",", "self", ".", "__base__", "(", ")", ")", "and", "all", "(", "[", "getattr", "(", "other", ",", "key", ")", "==", "getattr", "(", "self", ",", "ke...
https://github.com/JimmXinu/FanFicFare/blob/bc149a2deb2636320fe50a3e374af6eef8f61889/included_dependencies/soupsieve/css_types.py#L52-L58
rizsotto/scan-build
728e65fb6354022549797dbd399f5639e7bb92da
libscanbuild/report.py
python
Bug.__hash__
(self)
return hash(self.line) +\ hash(self.path_length) +\ hash(self.type) +\ hash(self.file)
[]
def __hash__(self): # type: (Bug) -> int return hash(self.line) +\ hash(self.path_length) +\ hash(self.type) +\ hash(self.file)
[ "def", "__hash__", "(", "self", ")", ":", "# type: (Bug) -> int", "return", "hash", "(", "self", ".", "line", ")", "+", "hash", "(", "self", ".", "path_length", ")", "+", "hash", "(", "self", ".", "type", ")", "+", "hash", "(", "self", ".", "file", ...
https://github.com/rizsotto/scan-build/blob/728e65fb6354022549797dbd399f5639e7bb92da/libscanbuild/report.py#L331-L337
Toblerity/rtree
eb04ef8933418ab108a45b6576abea95d6cbcbdb
rtree/index.py
python
RtreeContainer.delete
(self, obj, coordinates)
return super(RtreeContainer, self).delete(id(obj), coordinates)
Deletes the item from the container within the specified coordinates. :param obj: object Any object. :param coordinates: sequence or array Dimension * 2 coordinate pairs, representing the min and max coordinates in each dimension of the item to be deleted from the index. Their ordering will depend on the index's :attr:`interleaved` data member. These are not the coordinates of a space containing the item, but those of the item itself. Together with the id parameter, they determine which item will be deleted. This may be an object that satisfies the numpy array protocol. For a TPR-Tree, this must be a 3-element sequence including not only the positional coordinate pairs but also the velocity pairs `minvk` and `maxvk` and a time pair for the original time the object was inserted and the current time as a float. Example:: >>> from rtree import index >>> idx = index.RtreeContainer() >>> idx.delete(object(), ... (34.3776829412, 26.7375853734, 49.3776829412, ... 41.7375853734)) Traceback (most recent call last): ... IndexError: object is not in the index For the TPR-Tree:: >>> p = index.Property(type=index.RT_TPRTree) # doctest: +SKIP >>> idx = index.RtreeContainer(properties=p) # doctest: +SKIP >>> idx.delete(object(), ... ((34.3776829412, 26.7375853734, 49.3776829412, ... 41.7375853734), ... (0.5, 2, 1.5, 2.5), ... (3.0, 5.0))) # doctest: +SKIP Traceback (most recent call last): ... IndexError: object is not in the index
Deletes the item from the container within the specified coordinates.
[ "Deletes", "the", "item", "from", "the", "container", "within", "the", "specified", "coordinates", "." ]
def delete(self, obj, coordinates): """Deletes the item from the container within the specified coordinates. :param obj: object Any object. :param coordinates: sequence or array Dimension * 2 coordinate pairs, representing the min and max coordinates in each dimension of the item to be deleted from the index. Their ordering will depend on the index's :attr:`interleaved` data member. These are not the coordinates of a space containing the item, but those of the item itself. Together with the id parameter, they determine which item will be deleted. This may be an object that satisfies the numpy array protocol. For a TPR-Tree, this must be a 3-element sequence including not only the positional coordinate pairs but also the velocity pairs `minvk` and `maxvk` and a time pair for the original time the object was inserted and the current time as a float. Example:: >>> from rtree import index >>> idx = index.RtreeContainer() >>> idx.delete(object(), ... (34.3776829412, 26.7375853734, 49.3776829412, ... 41.7375853734)) Traceback (most recent call last): ... IndexError: object is not in the index For the TPR-Tree:: >>> p = index.Property(type=index.RT_TPRTree) # doctest: +SKIP >>> idx = index.RtreeContainer(properties=p) # doctest: +SKIP >>> idx.delete(object(), ... ((34.3776829412, 26.7375853734, 49.3776829412, ... 41.7375853734), ... (0.5, 2, 1.5, 2.5), ... (3.0, 5.0))) # doctest: +SKIP Traceback (most recent call last): ... IndexError: object is not in the index """ try: count = self._objects[id(obj)][0] - 1 except KeyError: raise IndexError('object is not in the index') if count == 0: del self._objects[id(obj)] else: self._objects[id(obj)] = (count, obj) return super(RtreeContainer, self).delete(id(obj), coordinates)
[ "def", "delete", "(", "self", ",", "obj", ",", "coordinates", ")", ":", "try", ":", "count", "=", "self", ".", "_objects", "[", "id", "(", "obj", ")", "]", "[", "0", "]", "-", "1", "except", "KeyError", ":", "raise", "IndexError", "(", "'object is ...
https://github.com/Toblerity/rtree/blob/eb04ef8933418ab108a45b6576abea95d6cbcbdb/rtree/index.py#L2067-L2122
richardaecn/class-balanced-loss
1d7857208a2abc03d84e35a9d5383af8225d4b4d
tpu/models/experimental/qanet/run_lib.py
python
predict
(override_cfg, model_dir)
Run model over a dataset and dump predictions to json file.
Run model over a dataset and dump predictions to json file.
[ "Run", "model", "over", "a", "dataset", "and", "dump", "predictions", "to", "json", "file", "." ]
def predict(override_cfg, model_dir): """Run model over a dataset and dump predictions to json file.""" assert FLAGS.predict_path cfg = _load_config(model_dir) cfg = utils.merge(cfg, override_cfg) input_fn = data.get_input_fn( split=cfg.dataset.eval_split, max_length=None, repeat=False, shuffle=False, cache=False, limit=None, data_path=cfg.dataset.data_path, vocab_path=cfg.dataset.vocab_path, is_tpu=False, use_generator=True, is_training=False) estimator = model.get_estimator(**cfg) predictions = dict() for i, prediction in enumerate(estimator.predict(input_fn)): predictions[prediction["id"]] = prediction["answer"] if i % 100 == 0: tf.logging.info("Prediction %s | %s: %s" % (i, prediction["id"], prediction["answer"])) # Dump results to a file with tf.gfile.GFile(FLAGS.predict_path, "w") as f: json.dump(predictions, f)
[ "def", "predict", "(", "override_cfg", ",", "model_dir", ")", ":", "assert", "FLAGS", ".", "predict_path", "cfg", "=", "_load_config", "(", "model_dir", ")", "cfg", "=", "utils", ".", "merge", "(", "cfg", ",", "override_cfg", ")", "input_fn", "=", "data", ...
https://github.com/richardaecn/class-balanced-loss/blob/1d7857208a2abc03d84e35a9d5383af8225d4b4d/tpu/models/experimental/qanet/run_lib.py#L143-L170
moberweger/deep-prior-pp
11f585f73d2c7957c95db302b770a3b4962c0386
src/data/importers.py
python
NYUImporter.jointImgTo3D
(self, sample)
return ret
Normalize sample to metric 3D :param sample: joints in (x,y,z) with x,y in image coordinates and z in mm :return: normalized joints in mm
Normalize sample to metric 3D :param sample: joints in (x,y,z) with x,y in image coordinates and z in mm :return: normalized joints in mm
[ "Normalize", "sample", "to", "metric", "3D", ":", "param", "sample", ":", "joints", "in", "(", "x", "y", "z", ")", "with", "x", "y", "in", "image", "coordinates", "and", "z", "in", "mm", ":", "return", ":", "normalized", "joints", "in", "mm" ]
def jointImgTo3D(self, sample): """ Normalize sample to metric 3D :param sample: joints in (x,y,z) with x,y in image coordinates and z in mm :return: normalized joints in mm """ ret = np.zeros((3,), np.float32) ret[0] = (sample[0] - self.ux) * sample[2] / self.fx ret[1] = (self.uy - sample[1]) * sample[2] / self.fy ret[2] = sample[2] return ret
[ "def", "jointImgTo3D", "(", "self", ",", "sample", ")", ":", "ret", "=", "np", ".", "zeros", "(", "(", "3", ",", ")", ",", "np", ".", "float32", ")", "ret", "[", "0", "]", "=", "(", "sample", "[", "0", "]", "-", "self", ".", "ux", ")", "*",...
https://github.com/moberweger/deep-prior-pp/blob/11f585f73d2c7957c95db302b770a3b4962c0386/src/data/importers.py#L1187-L1197
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/gdata/samples/oauth/oauth_on_appengine/appengine_utilities/cache.py
python
Cache.__setitem__
(self, key, value)
return self.set(key, value)
__setitem__ is necessary for this object to emulate a container.
__setitem__ is necessary for this object to emulate a container.
[ "__setitem__", "is", "necessary", "for", "this", "object", "to", "emulate", "a", "container", "." ]
def __setitem__(self, key, value): """ __setitem__ is necessary for this object to emulate a container. """ return self.set(key, value)
[ "def", "__setitem__", "(", "self", ",", "key", ",", "value", ")", ":", "return", "self", ".", "set", "(", "key", ",", "value", ")" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/gdata/samples/oauth/oauth_on_appengine/appengine_utilities/cache.py#L251-L255
robotlearn/pyrobolearn
9cd7c060723fda7d2779fa255ac998c2c82b8436
pyrobolearn/terminal_conditions/body_conditions.py
python
BodyCondition.body
(self, body)
Set the body instance.
Set the body instance.
[ "Set", "the", "body", "instance", "." ]
def body(self, body): """Set the body instance.""" if not isinstance(body, Body): raise TypeError("Expecting the given 'body' to be an instance of `Body`, instead got: " "{}".format(type(body))) self._body = body
[ "def", "body", "(", "self", ",", "body", ")", ":", "if", "not", "isinstance", "(", "body", ",", "Body", ")", ":", "raise", "TypeError", "(", "\"Expecting the given 'body' to be an instance of `Body`, instead got: \"", "\"{}\"", ".", "format", "(", "type", "(", "...
https://github.com/robotlearn/pyrobolearn/blob/9cd7c060723fda7d2779fa255ac998c2c82b8436/pyrobolearn/terminal_conditions/body_conditions.py#L88-L93
freyja-dev/unity-tweak-tool
ad254288d2e0fed94c59277de3f21ef399e3197f
UnityTweakTool/section/spaghetti/compiz.py
python
Compizsettings.on_sw_workspace_switcher_active_notify
(self, widget, udata = None)
[]
def on_sw_workspace_switcher_active_notify(self, widget, udata = None): dependants = ['l_horizontal_desktop', 'l_vertical_desktop', 'spin_horizontal_desktop', 'spin_vertical_desktop'] if self.ui['sw_workspace_switcher'].get_active() == True: self.ui.sensitize(dependants) gsettings.core.set_int('hsize', 2) gsettings.core.set_int('hsize', 2) self.ui['spin_horizontal_desktop'].set_value(2) self.ui['spin_vertical_desktop'].set_value(2) else: self.ui.unsensitize(dependants) gsettings.core.set_int('hsize', 1) gsettings.core.set_int('vsize', 1) self.ui['spin_horizontal_desktop'].set_value(1) self.ui['spin_vertical_desktop'].set_value(1)
[ "def", "on_sw_workspace_switcher_active_notify", "(", "self", ",", "widget", ",", "udata", "=", "None", ")", ":", "dependants", "=", "[", "'l_horizontal_desktop'", ",", "'l_vertical_desktop'", ",", "'spin_horizontal_desktop'", ",", "'spin_vertical_desktop'", "]", "if", ...
https://github.com/freyja-dev/unity-tweak-tool/blob/ad254288d2e0fed94c59277de3f21ef399e3197f/UnityTweakTool/section/spaghetti/compiz.py#L640-L658
fighting41love/cocoNLP
6c68f1ddb771de8de6fd8c7a6872554190bbd36a
dist/cocoNLP-0.0.9/cocoNLP/config/basic/time_nlp/TimeUnit.py
python
TimeUnit.norm_sethour
(self)
时-规范化方法:该方法识别时间表达式单元的时字段 :return:
时-规范化方法:该方法识别时间表达式单元的时字段 :return:
[ "时", "-", "规范化方法:该方法识别时间表达式单元的时字段", ":", "return", ":" ]
def norm_sethour(self): """ 时-规范化方法:该方法识别时间表达式单元的时字段 :return: """ rule = u"(?<!(周|星期))([0-2]?[0-9])(?=(点|时))" pattern = re.compile(rule) match = pattern.search(self.exp_time) if match is not None: self.tp.tunit[3] = int(match.group()) # print('first', self.tp.tunit[3] ) # 处理倾向于未来时间的情况 self.preferFuture(3) self.isAllDayTime = False # * 对关键字:早(包含早上/早晨/早间),上午,中午,午间,下午,午后,晚上,傍晚,晚间,晚,pm,PM的正确时间计算 # * 规约: # * 1.中午/午间0-10点视为12-22点 # * 2.下午/午后0-11点视为12-23点 # * 3.晚上/傍晚/晚间/晚1-11点视为13-23点,12点视为0点 # * 4.0-11点pm/PM视为12-23点 rule = u"凌晨" pattern = re.compile(rule) match = pattern.search(self.exp_time) if match is not None: if self.tp.tunit[3] == -1: # 增加对没有明确时间点,只写了“凌晨”这种情况的处理 self.tp.tunit[3] = RangeTimeEnum.day_break elif 12 <= self.tp.tunit[3] <= 23: self.tp.tunit[3] -= 12 elif self.tp.tunit[3] == 0: self.tp.tunit[3] = 12 # 处理倾向于未来时间的情况 self.preferFuture(3) self.isAllDayTime = False rule = u"早上|早晨|早间|晨间|今早|明早|早|清晨" pattern = re.compile(rule) match = pattern.search(self.exp_time) if match is not None: if self.tp.tunit[3] == -1: # 增加对没有明确时间点,只写了“早上/早晨/早间”这种情况的处理 self.tp.tunit[3] = RangeTimeEnum.early_morning # 处理倾向于未来时间的情况 elif 12 <= self.tp.tunit[3] <= 23: self.tp.tunit[3] -= 12 elif self.tp.tunit[3] == 0: self.tp.tunit[3] = 12 self.preferFuture(3) self.isAllDayTime = False rule = u"上午" pattern = re.compile(rule) match = pattern.search(self.exp_time) if match is not None: if self.tp.tunit[3] == -1: # 增加对没有明确时间点,只写了“上午”这种情况的处理 self.tp.tunit[3] = RangeTimeEnum.morning elif 12 <= self.tp.tunit[3] <= 23: self.tp.tunit[3] -= 12 elif self.tp.tunit[3] == 0: self.tp.tunit[3] = 12 # 处理倾向于未来时间的情况 self.preferFuture(3) self.isAllDayTime = False rule = u"(中午)|(午间)|白天" pattern = re.compile(rule) match = pattern.search(self.exp_time) if match is not None: if 0 <= self.tp.tunit[3] <= 10: self.tp.tunit[3] += 12 if self.tp.tunit[3] == -1: # 增加对没有明确时间点,只写了“中午/午间”这种情况的处理 self.tp.tunit[3] = RangeTimeEnum.noon # 处理倾向于未来时间的情况 self.preferFuture(3) self.isAllDayTime = False rule = u"(下午)|(午后)|(pm)|(PM)" pattern = re.compile(rule) match = pattern.search(self.exp_time) if match is not None: if 0 <= self.tp.tunit[3] <= 11: self.tp.tunit[3] += 12 if self.tp.tunit[3] == -1: # 增加对没有明确时间点,只写了“下午|午后”这种情况的处理 self.tp.tunit[3] = RangeTimeEnum.afternoon # 处理倾向于未来时间的情况 self.preferFuture(3) self.isAllDayTime = False rule = u"晚上|夜间|夜里|今晚|明晚|晚|夜里" pattern = re.compile(rule) match = pattern.search(self.exp_time) if match is not None: if 0 <= self.tp.tunit[3] <= 11: self.tp.tunit[3] += 12 elif self.tp.tunit[3] == 12: self.tp.tunit[3] = 0 elif self.tp.tunit[3] == -1: # 增加对没有明确时间点,只写了“下午|午后”这种情况的处理 self.tp.tunit[3] = RangeTimeEnum.lateNight # 处理倾向于未来时间的情况 self.preferFuture(3) self.isAllDayTime = False
[ "def", "norm_sethour", "(", "self", ")", ":", "rule", "=", "u\"(?<!(周|星期))([0-2]?[0-9])(?=(点|时))\"", "pattern", "=", "re", ".", "compile", "(", "rule", ")", "match", "=", "pattern", ".", "search", "(", "self", ".", "exp_time", ")", "if", "match", "is", "no...
https://github.com/fighting41love/cocoNLP/blob/6c68f1ddb771de8de6fd8c7a6872554190bbd36a/dist/cocoNLP-0.0.9/cocoNLP/config/basic/time_nlp/TimeUnit.py#L199-L298
sigmavirus24/github3.py
f642a27833d6bef93daf5bb27b35e5ddbcfbb773
src/github3/decorators.py
python
requires_app_bearer_auth
(func)
return auth_wrapper
Require the use of application authentication. .. versionadded:: 1.2.0
Require the use of application authentication.
[ "Require", "the", "use", "of", "application", "authentication", "." ]
def requires_app_bearer_auth(func): """Require the use of application authentication. .. versionadded:: 1.2.0 """ @wraps(func) def auth_wrapper(self, *args, **kwargs): from . import session if isinstance(self.session.auth, session.AppBearerTokenAuth): return func(self, *args, **kwargs) else: from . import exceptions raise exceptions.MissingAppBearerAuthentication( "This method requires GitHub App authentication." ) return auth_wrapper
[ "def", "requires_app_bearer_auth", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "auth_wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", ".", "import", "session", "if", "isinstance", "(", "self", ".", ...
https://github.com/sigmavirus24/github3.py/blob/f642a27833d6bef93daf5bb27b35e5ddbcfbb773/src/github3/decorators.py#L86-L105