_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q7900
RTMP.handle_packet
train
def handle_packet(self, packet): """Lets librtmp look at a packet and send a response if needed.""" if not isinstance(packet, RTMPPacket): raise ValueError("A RTMPPacket argument is required") return librtmp.RTMP_ClientPacket(self.rtmp, packet.packet)
python
{ "resource": "" }
q7901
RTMP.process_packets
train
def process_packets(self, transaction_id=None, invoked_method=None, timeout=None): """Wait for packets and process them as needed. :param transaction_id: int, Wait until the result of this transaction ID is recieved. :param invoked_method: ...
python
{ "resource": "" }
q7902
RTMP.call
train
def call(self, method, *args, **params): """Calls a method on the server.""" transaction_id = params.get("transaction_id") if not transaction_id: self.transaction_id += 1 transaction_id = self.transaction_id obj = params.get("obj") args = [method, tran...
python
{ "resource": "" }
q7903
RTMP.remote_method
train
def remote_method(self, method, block=False, **params): """Creates a Python function that will attempt to call a remote method when used. :param method: str, Method name on the server to call :param block: bool, Wheter to wait for result or not Usage:: >>> send_us...
python
{ "resource": "" }
q7904
RTMPCall.result
train
def result(self, timeout=None): """Retrieves the result of the call. :param timeout: The time to wait for a result from the server. Raises :exc:`RTMPTimeoutError` on timeout. """ if self.done: return self._result result = self.conn.process_packets(transacti...
python
{ "resource": "" }
q7905
add_signal_handler
train
def add_signal_handler(): """Adds a signal handler to handle KeyboardInterrupt.""" import signal def handler(sig, frame): if sig == signal.SIGINT: librtmp.RTMP_UserInterrupt() raise KeyboardInterrupt signal.signal(signal.SIGINT, handler)
python
{ "resource": "" }
q7906
BaseMesh.rotate_x
train
def rotate_x(self, deg): """Rotate mesh around x-axis :param float deg: Rotation angle (degree) :return: """ rad = math.radians(deg) mat = numpy.array([ [1, 0, 0, 0], [0, math.cos(rad), math.sin(rad), 0], [0, -math.sin(rad), math.cos(r...
python
{ "resource": "" }
q7907
BaseMesh.translate_x
train
def translate_x(self, d): """Translate mesh for x-direction :param float d: Amount to translate """ mat = numpy.array([ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [d, 0, 0, 1] ]) self.vectors = self.vectors.dot(mat) ...
python
{ "resource": "" }
q7908
BaseMesh.translate_y
train
def translate_y(self, d): """Translate mesh for y-direction :param float d: Amount to translate """ mat = numpy.array([ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, d, 0, 1] ]) self.vectors = self.vectors.dot(mat) ...
python
{ "resource": "" }
q7909
BaseMesh.translate_z
train
def translate_z(self, d): """Translate mesh for z-direction :param float d: Amount to translate """ mat = numpy.array([ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, d, 1] ]) self.vectors = self.vectors.dot(mat) ...
python
{ "resource": "" }
q7910
Stl.__load
train
def __load(fh, mode=MODE_AUTO): """Load Mesh from STL file :param FileIO fh: The file handle to open :param int mode: The mode to open, default is :py:data:`AUTOMATIC`. :return: """ header = fh.read(Stl.HEADER_SIZE).lower() name = "" data = None i...
python
{ "resource": "" }
q7911
initialize_logger
train
def initialize_logger(): """Initialize steppy logger. This logger is used throughout the steppy library to report computation progress. Example: Simple use of steppy logger: .. code-block:: python initialize_logger() logger = get_logger() ...
python
{ "resource": "" }
q7912
display_upstream_structure
train
def display_upstream_structure(structure_dict): """Displays pipeline structure in the jupyter notebook. Args: structure_dict (dict): dict returned by :func:`~steppy.base.Step.upstream_structure`. """ graph = _create_graph(structure_dict) plt = Image(graph.create_png()) displ...
python
{ "resource": "" }
q7913
persist_as_png
train
def persist_as_png(structure_dict, filepath): """Saves pipeline diagram to disk as png file. Args: structure_dict (dict): dict returned by :func:`~steppy.base.Step.upstream_structure` filepath (str): filepath to which the png with pipeline visualization should be persisted """ ...
python
{ "resource": "" }
q7914
_create_graph
train
def _create_graph(structure_dict): """Creates pydot graph from the pipeline structure dict. Args: structure_dict (dict): dict returned by step.upstream_structure Returns: graph (pydot.Dot): object representing upstream pipeline structure (with regard to the current Step). """ graph...
python
{ "resource": "" }
q7915
Adapter.adapt
train
def adapt(self, all_ouputs: AllOutputs) -> DataPacket: """Adapt inputs for the transformer included in the step. Args: all_ouputs: Dict of outputs from parent steps. The keys should match the names of these steps and the values should be their respective outp...
python
{ "resource": "" }
q7916
Step.fit_transform
train
def fit_transform(self, data): """Fit the model and transform data or load already processed data. Loads cached or persisted output or adapts data for the current transformer and executes ``transformer.fit_transform``. Args: data (dict): data dictionary with keys as input n...
python
{ "resource": "" }
q7917
Step.clean_cache_step
train
def clean_cache_step(self): """Clean cache for current step. """ logger.info('Step {}, cleaning cache'.format(self.name)) self.output = None return self
python
{ "resource": "" }
q7918
Step.clean_cache_upstream
train
def clean_cache_upstream(self): """Clean cache for all steps that are upstream to `self`. """ logger.info('Cleaning cache for the entire upstream pipeline') for step in self.all_upstream_steps.values(): logger.info('Step {}, cleaning cache'.format(step.name)) step...
python
{ "resource": "" }
q7919
Step.get_step_by_name
train
def get_step_by_name(self, name): """Extracts step by name from the pipeline. Extracted Step is a fully functional pipeline as well. All upstream Steps are already defined. Args: name (str): name of the step to be fetched Returns: Step (obj): extracted s...
python
{ "resource": "" }
q7920
Step.persist_upstream_structure
train
def persist_upstream_structure(self): """Persist json file with the upstream steps structure, that is step names and their connections.""" persist_dir = os.path.join(self.experiment_directory, '{}_upstream_structure.json'.format(self.name)) logger.info('Step {}, saving upstream pipeline structur...
python
{ "resource": "" }
q7921
Step.persist_upstream_diagram
train
def persist_upstream_diagram(self, filepath): """Creates upstream steps diagram and persists it to disk as png file. Pydot graph is created and persisted to disk as png file under the filepath directory. Args: filepath (str): filepath to which the png with steps visualization shoul...
python
{ "resource": "" }
q7922
BaseTransformer.fit_transform
train
def fit_transform(self, *args, **kwargs): """Performs fit followed by transform. This method simply combines fit and transform. Args: args: positional arguments (can be anything) kwargs: keyword arguments (can be anything) Returns: dict: output ...
python
{ "resource": "" }
q7923
generate_hotp
train
def generate_hotp(secret, counter=4): """Generate a HOTP code. :param secret: A secret token for the authentication. :param counter: HOTP is a counter based algorithm. """ # https://tools.ietf.org/html/rfc4226 msg = struct.pack('>Q', counter) digest = hmac.new(to_bytes(secret), msg, hashlib...
python
{ "resource": "" }
q7924
generate_totp
train
def generate_totp(secret, period=30, timestamp=None): """Generate a TOTP code. A TOTP code is an extension of HOTP algorithm. :param secret: A secret token for the authentication. :param period: A period that a TOTP code is valid in seconds :param timestamp: Current time stamp. """ if time...
python
{ "resource": "" }
q7925
OtpAuth.valid_hotp
train
def valid_hotp(self, code, last=0, trials=100): """Valid a HOTP code. :param code: A number that is less than 6 characters. :param last: Guess HOTP code from last + 1 range. :param trials: Guest HOTP code end at last + trials + 1. """ if not valid_code(code): ...
python
{ "resource": "" }
q7926
OtpAuth.valid_totp
train
def valid_totp(self, code, period=30, timestamp=None): """Valid a TOTP code. :param code: A number that is less than 6 characters. :param period: A period that a TOTP code is valid in seconds :param timestamp: Validate TOTP at this given timestamp """ if not valid_code(c...
python
{ "resource": "" }
q7927
OtpAuth.to_uri
train
def to_uri(self, type, label, issuer, counter=None): """Generate the otpauth protocal string. :param type: Algorithm type, hotp or totp. :param label: Label of the identifier. :param issuer: The company, the organization or something else. :param counter: Counter of the HOTP alg...
python
{ "resource": "" }
q7928
OtpAuth.to_google
train
def to_google(self, type, label, issuer, counter=None): """Generate the otpauth protocal string for Google Authenticator. .. deprecated:: 0.2.0 Use :func:`to_uri` instead. """ warnings.warn('deprecated, use to_uri instead', DeprecationWarning) return self.to_uri(type,...
python
{ "resource": "" }
q7929
ExchangeRates.install
train
def install(self, backend='money.exchange.SimpleBackend'): """Install an exchange rates backend using a python path string""" # RADAR: Python2 if isinstance(backend, money.six.string_types): path, name = backend.rsplit('.', 1) module = importlib.import_module(path) ...
python
{ "resource": "" }
q7930
ExchangeRates.rate
train
def rate(self, currency): """Return quotation between the base and another currency""" if not self._backend: raise ExchangeBackendNotInstalled() return self._backend.rate(currency)
python
{ "resource": "" }
q7931
_register_scatter
train
def _register_scatter(): """ Patch `PathCollection` and `scatter` to register their return values. This registration allows us to distinguish `PathCollection`s created by `Axes.scatter`, which should use point-like picking, from others, which should use path-like picking. The former is more common...
python
{ "resource": "" }
q7932
_call_with_selection
train
def _call_with_selection(func): """Decorator that passes a `Selection` built from the non-kwonly args.""" wrapped_kwonly_params = [ param for param in inspect.signature(func).parameters.values() if param.kind == param.KEYWORD_ONLY] sel_sig = inspect.signature(Selection) default_sel_sig =...
python
{ "resource": "" }
q7933
_set_valid_props
train
def _set_valid_props(artist, kwargs): """Set valid properties for the artist, dropping the others.""" artist.set(**{k: kwargs[k] for k in kwargs if hasattr(artist, "set_" + k)}) return artist
python
{ "resource": "" }
q7934
Money.to
train
def to(self, currency): """Return equivalent money object in another currency""" if currency == self._currency: return self rate = xrates.quotation(self._currency, currency) if rate is None: raise ExchangeRateNotFound(xrates.backend_name, ...
python
{ "resource": "" }
q7935
_get_rounded_intersection_area
train
def _get_rounded_intersection_area(bbox_1, bbox_2): """Compute the intersection area between two bboxes rounded to 8 digits.""" # The rounding allows sorting areas without floating point issues. bbox = bbox_1.intersection(bbox_1, bbox_2) return round(bbox.width * bbox.height, 8) if bbox else 0
python
{ "resource": "" }
q7936
cursor
train
def cursor(pickables=None, **kwargs): """ Create a `Cursor` for a list of artists, containers, and axes. Parameters ---------- pickables : Optional[List[Union[Artist, Container, Axes, Figure]]] All artists and containers in the list or on any of the axes or figures passed in the li...
python
{ "resource": "" }
q7937
Cursor.selections
train
def selections(self): r"""The tuple of current `Selection`\s.""" for sel in self._selections: if sel.annotation.axes is None: raise RuntimeError("Annotation unexpectedly removed; " "use 'cursor.remove_selection' instead") return tupl...
python
{ "resource": "" }
q7938
Cursor.add_selection
train
def add_selection(self, pi): """ Create an annotation for a `Selection` and register it. Returns a new `Selection`, that has been registered by the `Cursor`, with the added annotation set in the :attr:`annotation` field and, if applicable, the highlighting artist in the :attr:`e...
python
{ "resource": "" }
q7939
Cursor.add_highlight
train
def add_highlight(self, artist, *args, **kwargs): """ Create, add, and return a highlighting artist. This method is should be called with an "unpacked" `Selection`, possibly with some fields set to None. It is up to the caller to register the artist with the proper `Sel...
python
{ "resource": "" }
q7940
Cursor.connect
train
def connect(self, event, func=None): """ Connect a callback to a `Cursor` event; return the callback. Two events can be connected to: - callbacks connected to the ``"add"`` event are called when a `Selection` is added, with that selection as only argument; - callbacks...
python
{ "resource": "" }
q7941
Cursor.disconnect
train
def disconnect(self, event, cb): """ Disconnect a previously connected callback. If a callback is connected multiple times, only one connection is removed. """ try: self._callbacks[event].remove(cb) except KeyError: raise ValueError("{!r} ...
python
{ "resource": "" }
q7942
Cursor.remove
train
def remove(self): """ Remove a cursor. Remove all `Selection`\\s, disconnect all callbacks, and allow the cursor to be garbage collected. """ for disconnectors in self._disconnectors: disconnectors() for sel in self.selections: self.remove...
python
{ "resource": "" }
q7943
Cursor.remove_selection
train
def remove_selection(self, sel): """Remove a `Selection`.""" self._selections.remove(sel) # <artist>.figure will be unset so we save them first. figures = {artist.figure for artist in [sel.annotation] + sel.extras} # ValueError is raised if the artist has already been removed. ...
python
{ "resource": "" }
q7944
BaseHandler.request_access_token
train
def request_access_token(self, access_code): "Request access token from GitHub" token_response = request_session.post( "https://github.com/login/oauth/access_token", data={ "client_id": self.oauth_client_id, "client_secret": self.oauth_client_secre...
python
{ "resource": "" }
q7945
combine_dicts
train
def combine_dicts(recs): """Combine a list of recs, appending values to matching keys""" if not recs: return None if len(recs) == 1: return recs.pop() new_rec = {} for rec in recs: for k, v in rec.iteritems(): if k in new_rec: new_rec[k] = "%s, %...
python
{ "resource": "" }
q7946
combine_recs
train
def combine_recs(rec_list, key): """Use a common key to combine a list of recs""" final_recs = {} for rec in rec_list: rec_key = rec[key] if rec_key in final_recs: for k, v in rec.iteritems(): if k in final_recs[rec_key] and final_recs[rec_key][k] != v: ...
python
{ "resource": "" }
q7947
HostFromTarball._load_from_file
train
def _load_from_file(self, filename): """Find filename in tar, and load it""" if filename in self.fdata: return self.fdata[filename] else: filepath = find_in_tarball(self.tarloc, filename) return read_from_tarball(self.tarloc, filepath)
python
{ "resource": "" }
q7948
parse_extlang
train
def parse_extlang(subtags): """ Parse an 'extended language' tag, which consists of 1 to 3 three-letter language codes. Extended languages are used for distinguishing dialects/sublanguages (depending on your view) of macrolanguages such as Arabic, Bahasa Malay, and Chinese. It's supposed t...
python
{ "resource": "" }
q7949
order_error
train
def order_error(subtag, got, expected): """ Output an error indicating that tags were out of order. """ options = SUBTAG_TYPES[expected:] if len(options) == 1: expect_str = options[0] elif len(options) == 2: expect_str = '%s or %s' % (options[0], options[1]) else: exp...
python
{ "resource": "" }
q7950
tag_match_score
train
def tag_match_score(desired: {str, Language}, supported: {str, Language}) -> int: """ Return a number from 0 to 100 indicating the strength of match between the language the user desires, D, and a supported language, S. Higher numbers are better. A reasonable cutoff for not messing with your users is to...
python
{ "resource": "" }
q7951
best_match
train
def best_match(desired_language: {str, Language}, supported_languages: list, min_score: int=75) -> (str, int): """ You have software that supports any of the `supported_languages`. You want to use `desired_language`. This function lets you choose the right language, even if there isn't an...
python
{ "resource": "" }
q7952
Language.make
train
def make(cls, language=None, extlangs=None, script=None, region=None, variants=None, extensions=None, private=None): """ Create a Language object by giving any subset of its attributes. If this value has been created before, return the existing value. """ values = (...
python
{ "resource": "" }
q7953
Language.get
train
def get(tag: {str, 'Language'}, normalize=True) -> 'Language': """ Create a Language object from a language tag string. If normalize=True, non-standard or overlong tags will be replaced as they're interpreted. This is recommended. Here are several examples of language codes, wh...
python
{ "resource": "" }
q7954
Language.simplify_script
train
def simplify_script(self) -> 'Language': """ Remove the script from some parsed language data, if the script is redundant with the language. >>> Language.make(language='en', script='Latn').simplify_script() Language.make(language='en') >>> Language.make(language='yi', s...
python
{ "resource": "" }
q7955
Language.assume_script
train
def assume_script(self) -> 'Language': """ Fill in the script if it's missing, and if it can be assumed from the language subtag. This is the opposite of `simplify_script`. >>> Language.make(language='en').assume_script() Language.make(language='en', script='Latn') >>> ...
python
{ "resource": "" }
q7956
Language.prefer_macrolanguage
train
def prefer_macrolanguage(self) -> 'Language': """ BCP 47 doesn't specify what to do with macrolanguages and the languages they contain. The Unicode CLDR, on the other hand, says that when a macrolanguage has a dominant standardized language, the macrolanguage code should be used ...
python
{ "resource": "" }
q7957
Language.broaden
train
def broaden(self) -> 'List[Language]': """ Iterate through increasingly general versions of this parsed language tag. This isn't actually that useful for matching two arbitrary language tags against each other, but it is useful for matching them against a known standardized form...
python
{ "resource": "" }
q7958
Language.maximize
train
def maximize(self) -> 'Language': """ The Unicode CLDR contains a "likelySubtags" data file, which can guess reasonable values for fields that are missing from a language tag. This is particularly useful for comparing, for example, "zh-Hant" and "zh-TW", two common language tags...
python
{ "resource": "" }
q7959
Language.script_name
train
def script_name(self, language=DEFAULT_LANGUAGE, min_score: int=75) -> str: """ Describe the script part of the language tag in a natural language. """ return self._get_name('script', language, min_score)
python
{ "resource": "" }
q7960
Language.region_name
train
def region_name(self, language=DEFAULT_LANGUAGE, min_score: int=75) -> str: """ Describe the region part of the language tag in a natural language. """ return self._get_name('region', language, min_score)
python
{ "resource": "" }
q7961
Language.variant_names
train
def variant_names(self, language=DEFAULT_LANGUAGE, min_score: int=75) -> list: """ Describe each of the variant parts of the language tag in a natural language. """ names = [] for variant in self.variants: var_names = code_to_names('variant', variant) ...
python
{ "resource": "" }
q7962
Language.describe
train
def describe(self, language=DEFAULT_LANGUAGE, min_score: int=75) -> dict: """ Return a dictionary that describes a given language tag in a specified natural language. See `language_name` and related methods for more specific versions of this. The desired `language` will in fact...
python
{ "resource": "" }
q7963
Language.find_name
train
def find_name(tagtype: str, name: str, language: {str, 'Language', None}=None): """ Find the subtag of a particular `tagtype` that has the given `name`. The default language, "und", will allow matching names in any language, so you can get the code 'fr' by looking up "French", "Français...
python
{ "resource": "" }
q7964
Language.to_dict
train
def to_dict(self): """ Get a dictionary of the attributes of this Language object, which can be useful for constructing a similar object. """ if self._dict is not None: return self._dict result = {} for key in self.ATTRIBUTES: value = geta...
python
{ "resource": "" }
q7965
Language.update
train
def update(self, other: 'Language') -> 'Language': """ Update this Language with the fields of another Language. """ return Language.make( language=other.language or self.language, extlangs=other.extlangs or self.extlangs, script=other.script or self.s...
python
{ "resource": "" }
q7966
Language.update_dict
train
def update_dict(self, newdata: dict) -> 'Language': """ Update the attributes of this Language from a dictionary. """ return Language.make( language=newdata.get('language', self.language), extlangs=newdata.get('extlangs', self.extlangs), script=newdata...
python
{ "resource": "" }
q7967
Language._filter_keys
train
def _filter_keys(d: dict, keys: set) -> dict: """ Select a subset of keys from a dictionary. """ return {key: d[key] for key in keys if key in d}
python
{ "resource": "" }
q7968
Language._filter_attributes
train
def _filter_attributes(self, keyset): """ Return a copy of this object with a subset of its attributes set. """ filtered = self._filter_keys(self.to_dict(), keyset) return Language.make(**filtered)
python
{ "resource": "" }
q7969
Language._searchable_form
train
def _searchable_form(self) -> 'Language': """ Convert a parsed language tag so that the information it contains is in the best form for looking up information in the CLDR. """ if self._searchable is not None: return self._searchable self._searchable = self._f...
python
{ "resource": "" }
q7970
read_cldr_names
train
def read_cldr_names(path, language, category): """ Read CLDR's names for things in a particular language. """ filename = data_filename('{}/{}/{}.json'.format(path, language, category)) fulldata = json.load(open(filename, encoding='utf-8')) data = fulldata['main'][language]['localeDisplayNames'][...
python
{ "resource": "" }
q7971
parse_file
train
def parse_file(file): """ Take an open file containing the IANA subtag registry, and yield a dictionary of information for each subtag it describes. """ lines = [] for line in file: line = line.rstrip('\n') if line == '%%': # This is a separator between items. Parse t...
python
{ "resource": "" }
q7972
load_trie
train
def load_trie(filename): """ Load a BytesTrie from the marisa_trie on-disk format. """ trie = marisa_trie.BytesTrie() # marisa_trie raises warnings that make no sense. Ignore them. with warnings.catch_warnings(): warnings.simplefilter("ignore") trie.load(filename) return trie
python
{ "resource": "" }
q7973
name_to_code
train
def name_to_code(category, name, language: str='und'): """ Get a language, script, or region by its name in some language. The language here must be a string representing a language subtag only. The `Language.find` method can handle other representations of a language and normalize them to this for...
python
{ "resource": "" }
q7974
code_to_names
train
def code_to_names(category, code): """ Given the code for a language, script, or region, get a dictionary of its names in various languages. """ trie_name = '{}_to_name'.format(category) if trie_name not in TRIES: TRIES[trie_name] = load_trie(data_filename('trie/{}.marisa'.format(trie_na...
python
{ "resource": "" }
q7975
print_huffman_code_cwl
train
def print_huffman_code_cwl(code,p,v): """ code - code dictionary with symbol -> code map, p, v is probability map """ cwl = 0.0 for k,_v in code.items(): print(u"%s -> %s"%(k,_v)) cwl += p[v.index(k)]*len(_v) print(u"cwl = %g"%cwl) return cwl,code.values()
python
{ "resource": "" }
q7976
oridam_generate_patterns
train
def oridam_generate_patterns(word_in,cm,ed=1,level=0,pos=0,candidates=None): """ ed = 1 by default, pos - internal variable for algorithm """ alternates = cm.get(word_in[pos],[]) if not candidates: candidates = [] assert ed <= len(word_in), 'edit distance has to be comparable to word size [ins/d...
python
{ "resource": "" }
q7977
uyirmei_constructed
train
def uyirmei_constructed( mei_idx, uyir_idx): """ construct uyirmei letter give mei index and uyir index """ idx,idy = mei_idx,uyir_idx assert ( idy >= 0 and idy < uyir_len() ) assert ( idx >= 0 and idx < 6+mei_len() ) return grantha_agaram_letters[mei_idx]+accent_symbols[uyir_idx]
python
{ "resource": "" }
q7978
has_english
train
def has_english( word_in ): """ return True if word_in has any English letters in the string""" return not all_tamil(word_in) and len(word_in) > 0 and any([l in word_in for l in string.ascii_letters])
python
{ "resource": "" }
q7979
all_tamil
train
def all_tamil( word_in ): """ predicate checks if all letters of the input word are Tamil letters """ if isinstance(word_in,list): word = word_in else: word = get_letters( word_in ) return all( [(letter in tamil_letters) for letter in word] )
python
{ "resource": "" }
q7980
compare_words_lexicographic
train
def compare_words_lexicographic( word_a, word_b ): """ compare words in Tamil lexicographic order """ # sanity check for words to be all Tamil if ( not all_tamil(word_a) ) or (not all_tamil(word_b)) : #print("## ") #print(word_a) #print(word_b) #print("Both operands need to b...
python
{ "resource": "" }
q7981
word_intersection
train
def word_intersection( word_a, word_b ): """ return a list of tuples where word_a, word_b intersect """ positions = [] word_a_letters = get_letters( word_a ) word_b_letters = get_letters( word_b ) for idx,wa in enumerate(word_a_letters): for idy,wb in enumerate(word_b_letters): i...
python
{ "resource": "" }
q7982
splitMeiUyir
train
def splitMeiUyir(uyirmei_char): """ This function split uyirmei compound character into mei + uyir characters and returns in tuple. Input : It must be unicode tamil char. Written By : Arulalan.T Date : 22.09.2014 """ if not isinstance(uyirmei_char, PYTHON3 and str or unicode): ...
python
{ "resource": "" }
q7983
joinMeiUyir
train
def joinMeiUyir(mei_char, uyir_char): """ This function join mei character and uyir character, and retuns as compound uyirmei unicode character. Inputs: mei_char : It must be unicode tamil mei char. uyir_char : It must be unicode tamil uyir char. Written By : Arulalan.T Date : ...
python
{ "resource": "" }
q7984
make_pattern
train
def make_pattern( patt, flags=0 ): """ returns a compile regular expression object """ # print('input',len(patt)) patt_letters = utf8.get_letters( patt ) patt_out = list() idx = 0 # print('output',len(patt_letters)) patt = [None,None] prev = None LEN_PATT = len(patt_lette...
python
{ "resource": "" }
q7985
WordXSec.compute
train
def compute( self ): # compute the intersection graph into @xsections dictionary wordlist = self.wordlist """ build a dictionary of words, and their intersections """ xsections = {} for i in range(len(wordlist)): word_i = wordlist[i] for j in range(...
python
{ "resource": "" }
q7986
BaseStemmer.set_current
train
def set_current(self, value): ''' Set the self.current string. ''' self.current = value self.cursor = 0 self.limit = len(self.current) self.limit_backward = 0 self.bra = self.cursor self.ket = self.limit
python
{ "resource": "" }
q7987
BaseStemmer.replace_s
train
def replace_s(self, c_bra, c_ket, s): ''' to replace chars between c_bra and c_ket in self.current by the chars in s. @type c_bra int @type c_ket int @type s: string ''' adjustment = len(s) - (c_ket - c_bra) self.current = self.current[0:c_bra] + ...
python
{ "resource": "" }
q7988
BaseStemmer.slice_to
train
def slice_to(self, s): ''' Copy the slice into the supplied StringBuffer @type s: string ''' result = '' if self.slice_check(): result = self.current[self.bra:self.ket] return result
python
{ "resource": "" }
q7989
TamilTweetParser.getTamilWords
train
def getTamilWords( tweet ): """" word needs to all be in the same tamil language """ tweet = TamilTweetParser.cleanupPunct( tweet ); nonETwords = filter( lambda x: len(x) > 0 , re.split(r'\s+',tweet) );#|"+|\'+|#+ tamilWords = filter( TamilTweetParser.isTamilPredicate, nonETwords ); ...
python
{ "resource": "" }
q7990
validate_split_runs_file
train
def validate_split_runs_file(split_runs_file): """Check if structure of file is as expected and return dictionary linking names to run_IDs.""" try: content = [l.strip() for l in split_runs_file.readlines()] if content[0].upper().split('\t') == ['NAME', 'RUN_ID']: return {c.split('\t'...
python
{ "resource": "" }
q7991
change_identifiers
train
def change_identifiers(datadf, split_dict): """Change the dataset identifiers based on the names in the dictionary.""" for rid, name in split_dict.items(): datadf.loc[datadf["runIDs"] == rid, "dataset"] = name
python
{ "resource": "" }
q7992
MCP9808.begin
train
def begin(self): """Start taking temperature measurements. Returns True if the device is intialized, False otherwise. """ # Check manufacturer and device ID match expected values. mid = self._device.readU16BE(MCP9808_REG_MANUF_ID) did = self._device.readU16BE(MCP9808_REG_DEVICE_ID) self._logger.debug('Re...
python
{ "resource": "" }
q7993
MCP9808.readTempC
train
def readTempC(self): """Read sensor and return its value in degrees celsius.""" # Read temperature register value. t = self._device.readU16BE(MCP9808_REG_AMBIENT_TEMP) self._logger.debug('Raw ambient temp register value: 0x{0:04X}'.format(t & 0xFFFF)) # Scale and convert to signed value. temp = (t & 0x0FFF)...
python
{ "resource": "" }
q7994
crud_url_name
train
def crud_url_name(model, action, prefix=None): """ Returns url name for given model and action. """ if prefix is None: prefix = "" app_label = model._meta.app_label model_lower = model.__name__.lower() return '%s%s_%s_%s' % (prefix, app_label, model_lower, action)
python
{ "resource": "" }
q7995
crud_url
train
def crud_url(instance_or_model, action, prefix=None, additional_kwargs=None): """Shortcut function returns URL for instance or model and action. Example:: crud_url(author, 'update') Is same as: reverse('testapp_author_update', kwargs={'pk': author.pk}) Example:: crud_url(Au...
python
{ "resource": "" }
q7996
format_value
train
def format_value(obj, field_name): """ Simple value formatting. If value is model instance returns link to detail view if exists. """ display_func = getattr(obj, 'get_%s_display' % field_name, None) if display_func: return display_func() value = getattr(obj, field_name) if isin...
python
{ "resource": "" }
q7997
get_fields
train
def get_fields(model, fields=None): """ Assigns fields for model. """ include = [f.strip() for f in fields.split(',')] if fields else None return utils.get_fields( model, include )
python
{ "resource": "" }
q7998
crud_urls
train
def crud_urls(model, list_view=None, create_view=None, update_view=None, detail_view=None, delete_view=None, url_prefix=None, name_prefix=None, list_views=None, **kwargs): """Returns a list ...
python
{ "resource": "" }
q7999
crud_for_model
train
def crud_for_model(model, urlprefix=None): """Returns list of ``url`` items to CRUD a model. """ model_lower = model.__name__.lower() if urlprefix is None: urlprefix = '' urlprefix += model_lower + '/' urls = crud_urls( model, list_view=CRUDListView.as_view(model=model)...
python
{ "resource": "" }