code_tokens
stringlengths 60
3.94k
| label
int64 0
1
| doc
stringlengths 16
98
| docstring_tokens
stringlengths 0
1.41k
| idx
stringlengths 13
17
| code
stringlengths 87
6.4k
|
---|---|---|---|---|---|
def writeBoolean ( self , n ) : t = TYPE_BOOL_TRUE if n is False : t = TYPE_BOOL_FALSE self . stream . write ( t ) | 0 | python code to write bool value 1 | Writes a Boolean to the stream . | cosqa-train-0 | def writeBoolean(self, n):
"""
Writes a Boolean to the stream.
"""
t = TYPE_BOOL_TRUE
if n is False:
t = TYPE_BOOL_FALSE
self.stream.write(t) |
def paste ( xsel = False ) : selection = "primary" if xsel else "clipboard" try : return subprocess . Popen ( [ "xclip" , "-selection" , selection , "-o" ] , stdout = subprocess . PIPE ) . communicate ( ) [ 0 ] . decode ( "utf-8" ) except OSError as why : raise XclipNotFound | 0 | "python how to manipulate clipboard" | Returns system clipboard contents . | cosqa-train-1 | def paste(xsel=False):
"""Returns system clipboard contents."""
selection = "primary" if xsel else "clipboard"
try:
return subprocess.Popen(["xclip", "-selection", selection, "-o"], stdout=subprocess.PIPE).communicate()[0].decode("utf-8")
except OSError as why:
raise XclipNotFound |
def _format_json ( data , theme ) : output = json . dumps ( data , indent = 2 , sort_keys = True ) if pygments and sys . stdout . isatty ( ) : style = get_style_by_name ( theme ) formatter = Terminal256Formatter ( style = style ) return pygments . highlight ( output , JsonLexer ( ) , formatter ) return output | 0 | python colored output to html | Pretty print a dict as a JSON with colors if pygments is present . | cosqa-train-2 | def _format_json(data, theme):
"""Pretty print a dict as a JSON, with colors if pygments is present."""
output = json.dumps(data, indent=2, sort_keys=True)
if pygments and sys.stdout.isatty():
style = get_style_by_name(theme)
formatter = Terminal256Formatter(style=style)
return pygments.highlight(output, JsonLexer(), formatter)
return output |
def create_path ( path ) : import os if not os . path . exists ( path ) : os . makedirs ( path ) | 0 | python "create directory" using "relative path" | Creates a absolute path in the file system . | cosqa-train-3 | def create_path(path):
"""Creates a absolute path in the file system.
:param path: The path to be created
"""
import os
if not os.path.exists(path):
os.makedirs(path) |
def _vector_or_scalar ( x , type = 'row' ) : if isinstance ( x , ( list , tuple ) ) : x = np . array ( x ) if isinstance ( x , np . ndarray ) : assert x . ndim == 1 if type == 'column' : x = x [ : , None ] return x | 0 | python column of an array | Convert an object to either a scalar or a row or column vector . | cosqa-train-4 | def _vector_or_scalar(x, type='row'):
"""Convert an object to either a scalar or a row or column vector."""
if isinstance(x, (list, tuple)):
x = np.array(x)
if isinstance(x, np.ndarray):
assert x.ndim == 1
if type == 'column':
x = x[:, None]
return x |
def experiment_property ( prop ) : exp = experiment ( session ) p = getattr ( exp , prop ) return success_response ( field = prop , data = p , request_type = prop ) | 0 | python calling a property returns "property object" | Get a property of the experiment by name . | cosqa-train-5 | def experiment_property(prop):
"""Get a property of the experiment by name."""
exp = experiment(session)
p = getattr(exp, prop)
return success_response(field=prop, data=p, request_type=prop) |
def data_from_file ( file ) : fp = wave . open ( file , 'r' ) data = fp . readframes ( fp . getnframes ( ) ) channels = fp . getnchannels ( ) freq = fp . getframerate ( ) bits = fp . getsampwidth ( ) # Unpack bytes -- warning currently only tested with 16 bit wavefiles. 32 # bit not supported. data = struct . unpack ( ( '%sh' % fp . getnframes ( ) ) * channels , data ) # Only use first channel channel1 = [ ] n = 0 for d in data : if n % channels == 0 : channel1 . append ( d ) n += 1 fp . close ( ) return ( channel1 , freq , bits ) | 0 | python combine wav file into one as separate channels | Return ( first channel data sample frequency sample width ) from a . wav file . | cosqa-train-6 | def data_from_file(file):
"""Return (first channel data, sample frequency, sample width) from a .wav
file."""
fp = wave.open(file, 'r')
data = fp.readframes(fp.getnframes())
channels = fp.getnchannels()
freq = fp.getframerate()
bits = fp.getsampwidth()
# Unpack bytes -- warning currently only tested with 16 bit wavefiles. 32
# bit not supported.
data = struct.unpack(('%sh' % fp.getnframes()) * channels, data)
# Only use first channel
channel1 = []
n = 0
for d in data:
if n % channels == 0:
channel1.append(d)
n += 1
fp.close()
return (channel1, freq, bits) |
def source_range ( start , end , nr_var_dict ) : return OrderedDict ( ( k , e - s ) for k , ( s , e ) in source_range_tuple ( start , end , nr_var_dict ) . iteritems ( ) ) | 0 | +how to use range with a dictionary python | Given a range of source numbers as well as a dictionary containing the numbers of each source returns a dictionary containing tuples of the start and end index for each source variable type . | cosqa-train-7 | def source_range(start, end, nr_var_dict):
"""
Given a range of source numbers, as well as a dictionary
containing the numbers of each source, returns a dictionary
containing tuples of the start and end index
for each source variable type.
"""
return OrderedDict((k, e-s)
for k, (s, e)
in source_range_tuple(start, end, nr_var_dict).iteritems()) |
def timespan ( start_time ) : timespan = datetime . datetime . now ( ) - start_time timespan_ms = timespan . total_seconds ( ) * 1000 return timespan_ms | 0 | python compare timespan to number | Return time in milliseconds from start_time | cosqa-train-8 | def timespan(start_time):
"""Return time in milliseconds from start_time"""
timespan = datetime.datetime.now() - start_time
timespan_ms = timespan.total_seconds() * 1000
return timespan_ms |
def _convert_to_array ( array_like , dtype ) : if isinstance ( array_like , bytes ) : return np . frombuffer ( array_like , dtype = dtype ) return np . asarray ( array_like , dtype = dtype ) | 1 | 1d array in char datatype in python | Convert Matrix attributes which are array - like or buffer to array . | cosqa-train-9 | def _convert_to_array(array_like, dtype):
"""
Convert Matrix attributes which are array-like or buffer to array.
"""
if isinstance(array_like, bytes):
return np.frombuffer(array_like, dtype=dtype)
return np.asarray(array_like, dtype=dtype) |
def get_uniques ( l ) : result = [ ] for i in l : if i not in result : result . append ( i ) return result | 0 | python comprehension list distinct | Returns a list with no repeated elements . | cosqa-train-10 | def get_uniques(l):
""" Returns a list with no repeated elements.
"""
result = []
for i in l:
if i not in result:
result.append(i)
return result |
def interp ( x , xp , * args , * * kwargs ) : return interpolate_1d ( x , xp , * args , * * kwargs ) | 0 | 1d interpolation function python example | Wrap interpolate_1d for deprecated interp . | cosqa-train-11 | def interp(x, xp, *args, **kwargs):
"""Wrap interpolate_1d for deprecated interp."""
return interpolate_1d(x, xp, *args, **kwargs) |
def _array2cstr ( arr ) : out = StringIO ( ) np . save ( out , arr ) return b64encode ( out . getvalue ( ) ) | 0 | python compress array to string | Serializes a numpy array to a compressed base64 string | cosqa-train-12 | def _array2cstr(arr):
""" Serializes a numpy array to a compressed base64 string """
out = StringIO()
np.save(out, arr)
return b64encode(out.getvalue()) |
def percentile ( values , k ) : if not values : return None values . sort ( ) index = ( len ( values ) * ( float ( k ) / 100 ) ) - 1 return values [ int ( math . ceil ( index ) ) ] | 0 | 25 and 75 percentile of a list python | Find the percentile of a list of values . | cosqa-train-13 | def percentile(values, k):
"""Find the percentile of a list of values.
:param list values: The list of values to find the percentile of
:param int k: The percentile to find
:rtype: float or int
"""
if not values:
return None
values.sort()
index = (len(values) * (float(k) / 100)) - 1
return values[int(math.ceil(index))] |
def _string_hash ( s ) : h = 5381 for c in s : h = h * 33 + ord ( c ) return h | 0 | python compute hash of string | String hash ( djb2 ) with consistency between py2 / py3 and persistency between runs ( unlike hash ) . | cosqa-train-14 | def _string_hash(s):
"""String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`)."""
h = 5381
for c in s:
h = h * 33 + ord(c)
return h |
def transform_from_rot_trans ( R , t ) : R = R . reshape ( 3 , 3 ) t = t . reshape ( 3 , 1 ) return np . vstack ( ( np . hstack ( [ R , t ] ) , [ 0 , 0 , 0 , 1 ] ) ) | 0 | 3d rotatioin matrix in python | Transforation matrix from rotation matrix and translation vector . | cosqa-train-15 | def transform_from_rot_trans(R, t):
"""Transforation matrix from rotation matrix and translation vector."""
R = R.reshape(3, 3)
t = t.reshape(3, 1)
return np.vstack((np.hstack([R, t]), [0, 0, 0, 1])) |
def _encode_bool ( name , value , dummy0 , dummy1 ) : return b"\x08" + name + ( value and b"\x01" or b"\x00" ) | 0 | python concatenate bool to string | Encode a python boolean ( True / False ) . | cosqa-train-16 | def _encode_bool(name, value, dummy0, dummy1):
"""Encode a python boolean (True/False)."""
return b"\x08" + name + (value and b"\x01" or b"\x00") |
def transform_to_3d ( points , normal , z = 0 ) : d = np . cross ( normal , ( 0 , 0 , 1 ) ) M = rotation_matrix ( d ) transformed_points = M . dot ( points . T ) . T + z return transformed_points | 0 | 3d rotation in python around z axis | Project points into 3d from 2d points . | cosqa-train-17 | def transform_to_3d(points,normal,z=0):
"""Project points into 3d from 2d points."""
d = np.cross(normal, (0, 0, 1))
M = rotation_matrix(d)
transformed_points = M.dot(points.T).T + z
return transformed_points |
def _not ( condition = None , * * kwargs ) : result = True if condition is not None : result = not run ( condition , * * kwargs ) return result | 1 | python condition non none | Return the opposite of input condition . | cosqa-train-18 | def _not(condition=None, **kwargs):
"""
Return the opposite of input condition.
:param condition: condition to process.
:result: not condition.
:rtype: bool
"""
result = True
if condition is not None:
result = not run(condition, **kwargs)
return result |
def HttpResponse403 ( request , template = KEY_AUTH_403_TEMPLATE , content = KEY_AUTH_403_CONTENT , content_type = KEY_AUTH_403_CONTENT_TYPE ) : return AccessFailedResponse ( request , template , content , content_type , status = 403 ) | 0 | 403 code from request python | HTTP response for forbidden access ( status code 403 ) | cosqa-train-19 | def HttpResponse403(request, template=KEY_AUTH_403_TEMPLATE,
content=KEY_AUTH_403_CONTENT, content_type=KEY_AUTH_403_CONTENT_TYPE):
"""
HTTP response for forbidden access (status code 403)
"""
return AccessFailedResponse(request, template, content, content_type, status=403) |
def items ( self , section_name ) : return [ ( k , v ) for k , v in super ( GitConfigParser , self ) . items ( section_name ) if k != '__name__' ] | 0 | python configparser get keys in section | : return : list (( option value ) ... ) pairs of all items in the given section | cosqa-train-20 | def items(self, section_name):
""":return: list((option, value), ...) pairs of all items in the given section"""
return [(k, v) for k, v in super(GitConfigParser, self).items(section_name) if k != '__name__'] |
def mag ( z ) : if isinstance ( z [ 0 ] , np . ndarray ) : return np . array ( list ( map ( np . linalg . norm , z ) ) ) else : return np . linalg . norm ( z ) | 0 | a array of vector, compute the norm of each vector python | Get the magnitude of a vector . | cosqa-train-21 | def mag(z):
"""Get the magnitude of a vector."""
if isinstance(z[0], np.ndarray):
return np.array(list(map(np.linalg.norm, z)))
else:
return np.linalg.norm(z) |
def config_parser_to_dict ( config_parser ) : response = { } for section in config_parser . sections ( ) : for option in config_parser . options ( section ) : response . setdefault ( section , { } ) [ option ] = config_parser . get ( section , option ) return response | 0 | python configparser transfer dict | Convert a ConfigParser to a dictionary . | cosqa-train-22 | def config_parser_to_dict(config_parser):
"""
Convert a ConfigParser to a dictionary.
"""
response = {}
for section in config_parser.sections():
for option in config_parser.options(section):
response.setdefault(section, {})[option] = config_parser.get(section, option)
return response |
def __add__ ( self , other ) : return self . _handle_type ( other ) ( self . value + other . value ) | 0 | a+b in python addition code | Handle the + operator . | cosqa-train-23 | def __add__(self, other):
"""Handle the `+` operator."""
return self._handle_type(other)(self.value + other.value) |
def connect_mysql ( host , port , user , password , database ) : return pymysql . connect ( host = host , port = port , user = user , passwd = password , db = database ) | 0 | python connect mysql denied password | Connect to MySQL with retries . | cosqa-train-24 | def connect_mysql(host, port, user, password, database):
"""Connect to MySQL with retries."""
return pymysql.connect(
host=host, port=port,
user=user, passwd=password,
db=database
) |
def get_column ( self , X , column ) : if isinstance ( X , pd . DataFrame ) : return X [ column ] . values return X [ : , column ] | 1 | accessing a column from a matrix in python | Return a column of the given matrix . | cosqa-train-25 | def get_column(self, X, column):
"""Return a column of the given matrix.
Args:
X: `numpy.ndarray` or `pandas.DataFrame`.
column: `int` or `str`.
Returns:
np.ndarray: Selected column.
"""
if isinstance(X, pd.DataFrame):
return X[column].values
return X[:, column] |
def connect ( url , username , password ) : bb_session = stashy . connect ( url , username , password ) logger . info ( 'Connected to: %s as %s' , url , username ) return bb_session | 0 | python connecting to an api with username and password | Return a connected Bitbucket session | cosqa-train-26 | def connect(url, username, password):
"""
Return a connected Bitbucket session
"""
bb_session = stashy.connect(url, username, password)
logger.info('Connected to: %s as %s', url, username)
return bb_session |
def add_blank_row ( self , label ) : col_labels = self . df . columns blank_item = pd . Series ( { } , index = col_labels , name = label ) # use .loc to add in place (append won't do that) self . df . loc [ blank_item . name ] = blank_item return self . df | 0 | add empty series to data frame python | Add a blank row with only an index value to self . df . This is done inplace . | cosqa-train-27 | def add_blank_row(self, label):
"""
Add a blank row with only an index value to self.df.
This is done inplace.
"""
col_labels = self.df.columns
blank_item = pd.Series({}, index=col_labels, name=label)
# use .loc to add in place (append won't do that)
self.df.loc[blank_item.name] = blank_item
return self.df |
def teardown ( self ) : while self . _http_clients : self . _http_clients . pop ( ) . close ( ) if self . created : self . halt ( ) | 0 | python container pod stuck in terminating | Stop and remove the container if it exists . | cosqa-train-28 | def teardown(self):
"""
Stop and remove the container if it exists.
"""
while self._http_clients:
self._http_clients.pop().close()
if self.created:
self.halt() |
def dumped ( text , level , indent = 2 ) : return indented ( "{\n%s\n}" % indented ( text , level + 1 , indent ) or "None" , level , indent ) + "\n" | 0 | add indentations to code in python | Put curly brackets round an indented text | cosqa-train-29 | def dumped(text, level, indent=2):
"""Put curly brackets round an indented text"""
return indented("{\n%s\n}" % indented(text, level + 1, indent) or "None", level, indent) + "\n" |
def context ( self ) : parent = _ACTION_CONTEXT . set ( self ) try : yield self finally : _ACTION_CONTEXT . reset ( parent ) | 0 | python context manager exit | Create a context manager that ensures code runs within action s context . | cosqa-train-30 | def context(self):
"""
Create a context manager that ensures code runs within action's context.
The action does NOT finish when the context is exited.
"""
parent = _ACTION_CONTEXT.set(self)
try:
yield self
finally:
_ACTION_CONTEXT.reset(parent) |
def pformat ( object , indent = 1 , width = 80 , depth = None ) : return PrettyPrinter ( indent = indent , width = width , depth = depth ) . pformat ( object ) | 0 | add print depth inpython | Format a Python object into a pretty - printed representation . | cosqa-train-31 | def pformat(object, indent=1, width=80, depth=None):
"""Format a Python object into a pretty-printed representation."""
return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object) |
def replace_sys_args ( new_args ) : # Replace sys.argv arguments # for module import old_args = sys . argv sys . argv = new_args try : yield finally : sys . argv = old_args | 0 | python contextmanager temperarily set env | Temporarily replace sys . argv with current arguments | cosqa-train-32 | def replace_sys_args(new_args):
"""Temporarily replace sys.argv with current arguments
Restores sys.argv upon exit of the context manager.
"""
# Replace sys.argv arguments
# for module import
old_args = sys.argv
sys.argv = new_args
try:
yield
finally:
sys.argv = old_args |
def serialize ( obj ) : if isinstance ( obj , list ) : return [ serialize ( o ) for o in obj ] return GenericSerializer ( ModelProviderImpl ( ) ) . serialize ( obj ) | 0 | add serializer for type python | Takes a object and produces a dict - like representation | cosqa-train-33 | def serialize(obj):
"""Takes a object and produces a dict-like representation
:param obj: the object to serialize
"""
if isinstance(obj, list):
return [serialize(o) for o in obj]
return GenericSerializer(ModelProviderImpl()).serialize(obj) |
def advance_one_line ( self ) : current_line = self . _current_token . line_number while current_line == self . _current_token . line_number : self . _current_token = ConfigParser . Token ( * next ( self . _token_generator ) ) | 0 | python continuation on next line | Advances to next line . | cosqa-train-34 | def advance_one_line(self):
"""Advances to next line."""
current_line = self._current_token.line_number
while current_line == self._current_token.line_number:
self._current_token = ConfigParser.Token(*next(self._token_generator)) |
def generate_swagger_html ( swagger_static_root , swagger_json_url ) : tmpl = _get_template ( "swagger.html" ) return tmpl . render ( swagger_root = swagger_static_root , swagger_json_url = swagger_json_url ) | 0 | add swagger to python django | given a root directory for the swagger statics and a swagger json path return back a swagger html designed to use those values . | cosqa-train-35 | def generate_swagger_html(swagger_static_root, swagger_json_url):
"""
given a root directory for the swagger statics, and
a swagger json path, return back a swagger html designed
to use those values.
"""
tmpl = _get_template("swagger.html")
return tmpl.render(
swagger_root=swagger_static_root, swagger_json_url=swagger_json_url
) |
def do_next ( self , args ) : self . _do_print_from_last_cmd = True self . _interp . step_over ( ) return True | 0 | python continue executing the next command | Step over the next statement | cosqa-train-36 | def do_next(self, args):
"""Step over the next statement
"""
self._do_print_from_last_cmd = True
self._interp.step_over()
return True |
def __add__ ( self , other ) : assert self . matrix . shape [ 1 ] == other . matrix . shape [ 1 ] return LabeledMatrix ( np . concatenate ( [ self . matrix , other . matrix ] , axis = 0 ) , self . labels ) | 0 | add two matrix with same shape expect one dim python | If the number of columns matches we can concatenate two LabeldMatrices with the + operator . | cosqa-train-37 | def __add__(self,other):
"""
If the number of columns matches, we can concatenate two LabeldMatrices
with the + operator.
"""
assert self.matrix.shape[1] == other.matrix.shape[1]
return LabeledMatrix(np.concatenate([self.matrix,other.matrix],axis=0),self.labels) |
def get_line_flux ( line_wave , wave , flux , * * kwargs ) : return np . interp ( line_wave , wave , flux , * * kwargs ) | 0 | python contourf interpolation method | Interpolated flux at a given wavelength ( calls np . interp ) . | cosqa-train-38 | def get_line_flux(line_wave, wave, flux, **kwargs):
"""Interpolated flux at a given wavelength (calls np.interp)."""
return np.interp(line_wave, wave, flux, **kwargs) |
def send ( message , request_context = None , binary = False ) : if binary : return uwsgi . websocket_send_binary ( message , request_context ) return uwsgi . websocket_send ( message , request_context ) | 0 | add websocket support to python | Sends a message to websocket . | cosqa-train-39 | def send(message, request_context=None, binary=False):
"""Sends a message to websocket.
:param str message: data to send
:param request_context:
:raises IOError: If unable to send a message.
"""
if binary:
return uwsgi.websocket_send_binary(message, request_context)
return uwsgi.websocket_send(message, request_context) |
def get_number ( s , cast = int ) : import string d = "" . join ( x for x in str ( s ) if x in string . digits ) return cast ( d ) | 0 | python conver string to number | Try to get a number out of a string and cast it . | cosqa-train-40 | def get_number(s, cast=int):
"""
Try to get a number out of a string, and cast it.
"""
import string
d = "".join(x for x in str(s) if x in string.digits)
return cast(d) |
def get_hline ( ) : return Window ( width = LayoutDimension . exact ( 1 ) , height = LayoutDimension . exact ( 1 ) , content = FillControl ( '-' , token = Token . Line ) ) | 0 | adding a horxontal line python | gets a horiztonal line | cosqa-train-41 | def get_hline():
""" gets a horiztonal line """
return Window(
width=LayoutDimension.exact(1),
height=LayoutDimension.exact(1),
content=FillControl('-', token=Token.Line)) |
def parse_cookies_str ( cookies ) : cookie_dict = { } for record in cookies . split ( ";" ) : key , value = record . strip ( ) . split ( "=" , 1 ) cookie_dict [ key ] = value return cookie_dict | 0 | python cookies change to dict | parse cookies str to dict : param cookies : cookies str : type cookies : str : return : cookie dict : rtype : dict | cosqa-train-42 | def parse_cookies_str(cookies):
"""
parse cookies str to dict
:param cookies: cookies str
:type cookies: str
:return: cookie dict
:rtype: dict
"""
cookie_dict = {}
for record in cookies.split(";"):
key, value = record.strip().split("=", 1)
cookie_dict[key] = value
return cookie_dict |
def to_snake_case ( name ) : s1 = FIRST_CAP_REGEX . sub ( r'\1_\2' , name ) return ALL_CAP_REGEX . sub ( r'\1_\2' , s1 ) . lower ( ) | 0 | alternate uppercase and lower case in python | Given a name in camelCase return in snake_case | cosqa-train-43 | def to_snake_case(name):
""" Given a name in camelCase return in snake_case """
s1 = FIRST_CAP_REGEX.sub(r'\1_\2', name)
return ALL_CAP_REGEX.sub(r'\1_\2', s1).lower() |
def populate_obj ( obj , attrs ) : for k , v in attrs . iteritems ( ) : setattr ( obj , k , v ) | 0 | python copy a dict to object attributes | Populates an object s attributes using the provided dict | cosqa-train-44 | def populate_obj(obj, attrs):
"""Populates an object's attributes using the provided dict
"""
for k, v in attrs.iteritems():
setattr(obj, k, v) |
def wordfreq ( text , is_filename = False ) : if is_filename : with open ( text ) as f : text = f . read ( ) freqs = { } for word in text . split ( ) : lword = word . lower ( ) freqs [ lword ] = freqs . get ( lword , 0 ) + 1 return freqs | 0 | analyze the frequency of a word using python | Return a dictionary of words and word counts in a string . | cosqa-train-45 | def wordfreq(text, is_filename=False):
"""Return a dictionary of words and word counts in a string."""
if is_filename:
with open(text) as f:
text = f.read()
freqs = {}
for word in text.split():
lword = word.lower()
freqs[lword] = freqs.get(lword, 0) + 1
return freqs |
def copyFile ( input , output , replace = None ) : _found = findFile ( output ) if not _found or ( _found and replace ) : shutil . copy2 ( input , output ) | 0 | python copy files effeciently | Copy a file whole from input to output . | cosqa-train-46 | def copyFile(input, output, replace=None):
"""Copy a file whole from input to output."""
_found = findFile(output)
if not _found or (_found and replace):
shutil.copy2(input, output) |
def push ( h , x ) : h . push ( x ) up ( h , h . size ( ) - 1 ) | 0 | append last element of the stack in pythong | Push a new value into heap . | cosqa-train-47 | def push(h, x):
"""Push a new value into heap."""
h.push(x)
up(h, h.size()-1) |
def yank ( event ) : event . current_buffer . paste_clipboard_data ( event . cli . clipboard . get_data ( ) , count = event . arg , paste_mode = PasteMode . EMACS ) | 0 | python copy paste clipboard drop | Paste before cursor . | cosqa-train-48 | def yank(event):
"""
Paste before cursor.
"""
event.current_buffer.paste_clipboard_data(
event.cli.clipboard.get_data(), count=event.arg, paste_mode=PasteMode.EMACS) |
def filter_contour ( imageFile , opFile ) : im = Image . open ( imageFile ) im1 = im . filter ( ImageFilter . CONTOUR ) im1 . save ( opFile ) | 0 | apply a filter to an image python | convert an image by applying a contour | cosqa-train-49 | def filter_contour(imageFile, opFile):
""" convert an image by applying a contour """
im = Image.open(imageFile)
im1 = im.filter(ImageFilter.CONTOUR)
im1.save(opFile) |
def count ( lines ) : words = [ w for l in lines for w in l . strip ( ) . split ( ) ] return Counter ( words ) | 0 | python count number of words in each sentence | Counts the word frequences in a list of sentences . | cosqa-train-50 | def count(lines):
""" Counts the word frequences in a list of sentences.
Note:
This is a helper function for parallel execution of `Vocabulary.from_text`
method.
"""
words = [w for l in lines for w in l.strip().split()]
return Counter(words) |
def dictapply ( d , fn ) : for k , v in d . items ( ) : if isinstance ( v , dict ) : v = dictapply ( v , fn ) else : d [ k ] = fn ( v ) return d | 0 | apply a function to dictionary python | apply a function to all non - dict values in a dictionary | cosqa-train-51 | def dictapply(d, fn):
"""
apply a function to all non-dict values in a dictionary
"""
for k, v in d.items():
if isinstance(v, dict):
v = dictapply(v, fn)
else:
d[k] = fn(v)
return d |
def count_replica ( self , partition ) : return sum ( 1 for b in partition . replicas if b in self . brokers ) | 0 | python count partitions of a number | Return count of replicas of given partition . | cosqa-train-52 | def count_replica(self, partition):
"""Return count of replicas of given partition."""
return sum(1 for b in partition.replicas if b in self.brokers) |
def visit_Name ( self , node ) : return self . add ( node , self . result [ node . id ] ) | 0 | apply range to method python | Get range for parameters for examples or false branching . | cosqa-train-53 | def visit_Name(self, node):
""" Get range for parameters for examples or false branching. """
return self.add(node, self.result[node.id]) |
def mkdir ( dir , enter ) : if not os . path . exists ( dir ) : os . makedirs ( dir ) | 0 | python creat a dir | Create directory with template for topic of the current environment | cosqa-train-54 | def mkdir(dir, enter):
"""Create directory with template for topic of the current environment
"""
if not os.path.exists(dir):
os.makedirs(dir) |
def qrot ( vector , quaternion ) : t = 2 * np . cross ( quaternion [ 1 : ] , vector ) v_rot = vector + quaternion [ 0 ] * t + np . cross ( quaternion [ 1 : ] , t ) return v_rot | 0 | apply rotation on vector along a axis python | Rotate a 3D vector using quaternion algebra . | cosqa-train-55 | def qrot(vector, quaternion):
"""Rotate a 3D vector using quaternion algebra.
Implemented by Vladimir Kulikovskiy.
Parameters
----------
vector: np.array
quaternion: np.array
Returns
-------
np.array
"""
t = 2 * np.cross(quaternion[1:], vector)
v_rot = vector + quaternion[0] * t + np.cross(quaternion[1:], t)
return v_rot |
def _numpy_char_to_bytes ( arr ) : # based on: http://stackoverflow.com/a/10984878/809705 arr = np . array ( arr , copy = False , order = 'C' ) dtype = 'S' + str ( arr . shape [ - 1 ] ) return arr . view ( dtype ) . reshape ( arr . shape [ : - 1 ] ) | 0 | python create a numpy of chars | Like netCDF4 . chartostring but faster and more flexible . | cosqa-train-56 | def _numpy_char_to_bytes(arr):
"""Like netCDF4.chartostring, but faster and more flexible.
"""
# based on: http://stackoverflow.com/a/10984878/809705
arr = np.array(arr, copy=False, order='C')
dtype = 'S' + str(arr.shape[-1])
return arr.view(dtype).reshape(arr.shape[:-1]) |
def _string_hash ( s ) : h = 5381 for c in s : h = h * 33 + ord ( c ) return h | 1 | are python strings hashable | String hash ( djb2 ) with consistency between py2 / py3 and persistency between runs ( unlike hash ) . | cosqa-train-57 | def _string_hash(s):
"""String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`)."""
h = 5381
for c in s:
h = h * 33 + ord(c)
return h |
def csv_to_dicts ( file , header = None ) : with open ( file ) as csvfile : return [ row for row in csv . DictReader ( csvfile , fieldnames = header ) ] | 0 | python create list of dictionary from csv file no key | Reads a csv and returns a List of Dicts with keys given by header row . | cosqa-train-58 | def csv_to_dicts(file, header=None):
"""Reads a csv and returns a List of Dicts with keys given by header row."""
with open(file) as csvfile:
return [row for row in csv.DictReader(csvfile, fieldnames=header)] |
def get_tri_area ( pts ) : a , b , c = pts [ 0 ] , pts [ 1 ] , pts [ 2 ] v1 = np . array ( b ) - np . array ( a ) v2 = np . array ( c ) - np . array ( a ) area_tri = abs ( sp . linalg . norm ( sp . cross ( v1 , v2 ) ) / 2 ) return area_tri | 0 | area of a triangle python function | Given a list of coords for 3 points Compute the area of this triangle . | cosqa-train-59 | def get_tri_area(pts):
"""
Given a list of coords for 3 points,
Compute the area of this triangle.
Args:
pts: [a, b, c] three points
"""
a, b, c = pts[0], pts[1], pts[2]
v1 = np.array(b) - np.array(a)
v2 = np.array(c) - np.array(a)
area_tri = abs(sp.linalg.norm(sp.cross(v1, v2)) / 2)
return area_tri |
def one_hot ( x , size , dtype = np . float32 ) : return np . array ( x [ ... , np . newaxis ] == np . arange ( size ) , dtype ) | 0 | python create numpy onehot | Make a n + 1 dim one - hot array from n dim int - categorical array . | cosqa-train-60 | def one_hot(x, size, dtype=np.float32):
"""Make a n+1 dim one-hot array from n dim int-categorical array."""
return np.array(x[..., np.newaxis] == np.arange(size), dtype) |
def round_to_int ( number , precision ) : precision = int ( precision ) rounded = ( int ( number ) + precision / 2 ) // precision * precision return rounded | 0 | around to precision python | Round a number to a precision | cosqa-train-61 | def round_to_int(number, precision):
"""Round a number to a precision"""
precision = int(precision)
rounded = (int(number) + precision / 2) // precision * precision
return rounded |
def to_unicode_repr ( _letter ) : # Python 2-3 compatible return u"u'" + u"" . join ( [ u"\\u%04x" % ord ( l ) for l in _letter ] ) + u"'" | 0 | ascii character representation in python 3 | helpful in situations where browser / app may recognize Unicode encoding in the \ u0b8e type syntax but not actual unicode glyph / code - point | cosqa-train-62 | def to_unicode_repr( _letter ):
""" helpful in situations where browser/app may recognize Unicode encoding
in the \u0b8e type syntax but not actual unicode glyph/code-point"""
# Python 2-3 compatible
return u"u'"+ u"".join( [ u"\\u%04x"%ord(l) for l in _letter ] ) + u"'" |
def create_path ( path ) : import os if not os . path . exists ( path ) : os . makedirs ( path ) | 0 | python create path pathlib create directory | Creates a absolute path in the file system . | cosqa-train-63 | def create_path(path):
"""Creates a absolute path in the file system.
:param path: The path to be created
"""
import os
if not os.path.exists(path):
os.makedirs(path) |
def string_input ( prompt = '' ) : v = sys . version [ 0 ] if v == '3' : return input ( prompt ) else : return raw_input ( prompt ) | 0 | ask any python 3 question | Python 3 input () / Python 2 raw_input () | cosqa-train-64 | def string_input(prompt=''):
"""Python 3 input()/Python 2 raw_input()"""
v = sys.version[0]
if v == '3':
return input(prompt)
else:
return raw_input(prompt) |
def cfloat64_array_to_numpy ( cptr , length ) : if isinstance ( cptr , ctypes . POINTER ( ctypes . c_double ) ) : return np . fromiter ( cptr , dtype = np . float64 , count = length ) else : raise RuntimeError ( 'Expected double pointer' ) | 0 | python create pointer ctypes array | Convert a ctypes double pointer array to a numpy array . | cosqa-train-65 | def cfloat64_array_to_numpy(cptr, length):
"""Convert a ctypes double pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_double)):
return np.fromiter(cptr, dtype=np.float64, count=length)
else:
raise RuntimeError('Expected double pointer') |
def yn_prompt ( msg , default = True ) : ret = custom_prompt ( msg , [ "y" , "n" ] , "y" if default else "n" ) if ret == "y" : return True return False | 0 | asking user yes or no in python | Prompts the user for yes or no . | cosqa-train-66 | def yn_prompt(msg, default=True):
"""
Prompts the user for yes or no.
"""
ret = custom_prompt(msg, ["y", "n"], "y" if default else "n")
if ret == "y":
return True
return False |
def _display ( self , layout ) : print ( file = self . out ) TextWriter ( ) . format ( layout , self . out ) | 0 | python create print text in grid | launch layouts display | cosqa-train-67 | def _display(self, layout):
"""launch layouts display"""
print(file=self.out)
TextWriter().format(layout, self.out) |
def assert_list ( self , putative_list , expected_type = string_types , key_arg = None ) : return assert_list ( putative_list , expected_type , key_arg = key_arg , raise_type = lambda msg : TargetDefinitionException ( self , msg ) ) | 0 | assert based on part of string in a list python | : API : public | cosqa-train-68 | def assert_list(self, putative_list, expected_type=string_types, key_arg=None):
"""
:API: public
"""
return assert_list(putative_list, expected_type, key_arg=key_arg,
raise_type=lambda msg: TargetDefinitionException(self, msg)) |
def assert_exactly_one_true ( bool_list ) : assert isinstance ( bool_list , list ) counter = 0 for item in bool_list : if item : counter += 1 return counter == 1 | 1 | assure all true of a list of boolean python | This method asserts that only one value of the provided list is True . | cosqa-train-69 | def assert_exactly_one_true(bool_list):
"""This method asserts that only one value of the provided list is True.
:param bool_list: List of booleans to check
:return: True if only one value is True, False otherwise
"""
assert isinstance(bool_list, list)
counter = 0
for item in bool_list:
if item:
counter += 1
return counter == 1 |
def _get_random_id ( ) : symbols = string . ascii_uppercase + string . ascii_lowercase + string . digits return '' . join ( random . choice ( symbols ) for _ in range ( 15 ) ) | 0 | python create unique 5 letter id | Get a random ( i . e . unique ) string identifier | cosqa-train-70 | def _get_random_id():
""" Get a random (i.e., unique) string identifier"""
symbols = string.ascii_uppercase + string.ascii_lowercase + string.digits
return ''.join(random.choice(symbols) for _ in range(15)) |
async def list ( source ) : result = [ ] async with streamcontext ( source ) as streamer : async for item in streamer : result . append ( item ) yield result | 0 | async list comprehension python | Generate a single list from an asynchronous sequence . | cosqa-train-71 | async def list(source):
"""Generate a single list from an asynchronous sequence."""
result = []
async with streamcontext(source) as streamer:
async for item in streamer:
result.append(item)
yield result |
def _attrprint ( d , delimiter = ', ' ) : return delimiter . join ( ( '"%s"="%s"' % item ) for item in sorted ( d . items ( ) ) ) | 0 | attr dot notation python | Print a dictionary of attributes in the DOT format | cosqa-train-72 | def _attrprint(d, delimiter=', '):
"""Print a dictionary of attributes in the DOT format"""
return delimiter.join(('"%s"="%s"' % item) for item in sorted(d.items())) |
def get_next_scheduled_time ( cron_string ) : itr = croniter . croniter ( cron_string , datetime . utcnow ( ) ) return itr . get_next ( datetime ) | 0 | python croniter sigle question | Calculate the next scheduled time by creating a crontab object with a cron string | cosqa-train-73 | def get_next_scheduled_time(cron_string):
"""Calculate the next scheduled time by creating a crontab object
with a cron string"""
itr = croniter.croniter(cron_string, datetime.utcnow())
return itr.get_next(datetime) |
def exit ( exit_code = 0 ) : core . processExitHooks ( ) if state . isExitHooked and not hasattr ( sys , 'exitfunc' ) : # The function is called from the exit hook sys . stderr . flush ( ) sys . stdout . flush ( ) os . _exit ( exit_code ) #pylint: disable=W0212 sys . exit ( exit_code ) | 0 | autoexit python shell after script executed | r A function to support exiting from exit hooks . | cosqa-train-74 | def exit(exit_code=0):
r"""A function to support exiting from exit hooks.
Could also be used to exit from the calling scripts in a thread safe manner.
"""
core.processExitHooks()
if state.isExitHooked and not hasattr(sys, 'exitfunc'): # The function is called from the exit hook
sys.stderr.flush()
sys.stdout.flush()
os._exit(exit_code) #pylint: disable=W0212
sys.exit(exit_code) |
def dot_product ( self , other ) : return self . x * other . x + self . y * other . y | 0 | python cross product of two vectors | Return the dot product of the given vectors . | cosqa-train-75 | def dot_product(self, other):
""" Return the dot product of the given vectors. """
return self.x * other.x + self.y * other.y |
def reloader_thread ( softexit = False ) : while RUN_RELOADER : if code_changed ( ) : # force reload if softexit : sys . exit ( 3 ) else : os . _exit ( 3 ) time . sleep ( 1 ) | 0 | automatically restart python program after crash | If soft_exit is True we use sys . exit () ; otherwise os_exit will be used to end the process . | cosqa-train-76 | def reloader_thread(softexit=False):
"""If ``soft_exit`` is True, we use sys.exit(); otherwise ``os_exit``
will be used to end the process.
"""
while RUN_RELOADER:
if code_changed():
# force reload
if softexit:
sys.exit(3)
else:
os._exit(3)
time.sleep(1) |
def list_to_csv ( value ) : if isinstance ( value , ( list , tuple , set ) ) : value = "," . join ( value ) return value | 0 | python csv with comma in string | Converts list to string with comma separated values . For string is no - op . | cosqa-train-77 | def list_to_csv(value):
"""
Converts list to string with comma separated values. For string is no-op.
"""
if isinstance(value, (list, tuple, set)):
value = ",".join(value)
return value |
def average ( iterator ) : count = 0 total = 0 for num in iterator : count += 1 total += num return float ( total ) / count | 0 | average time python takes to run a for loop | Iterative mean . | cosqa-train-78 | def average(iterator):
"""Iterative mean."""
count = 0
total = 0
for num in iterator:
count += 1
total += num
return float(total)/count |
def cint32_array_to_numpy ( cptr , length ) : if isinstance ( cptr , ctypes . POINTER ( ctypes . c_int32 ) ) : return np . fromiter ( cptr , dtype = np . int32 , count = length ) else : raise RuntimeError ( 'Expected int pointer' ) | 0 | python ctypes array int | Convert a ctypes int pointer array to a numpy array . | cosqa-train-79 | def cint32_array_to_numpy(cptr, length):
"""Convert a ctypes int pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_int32)):
return np.fromiter(cptr, dtype=np.int32, count=length)
else:
raise RuntimeError('Expected int pointer') |
def _aws_get_instance_by_tag ( region , name , tag , raw ) : client = boto3 . session . Session ( ) . client ( 'ec2' , region ) matching_reservations = client . describe_instances ( Filters = [ { 'Name' : tag , 'Values' : [ name ] } ] ) . get ( 'Reservations' , [ ] ) instances = [ ] [ [ instances . append ( _aws_instance_from_dict ( region , instance , raw ) ) # pylint: disable=expression-not-assigned for instance in reservation . get ( 'Instances' ) ] for reservation in matching_reservations if reservation ] return instances | 0 | aws python boto3 list all ec2 with tags | Get all instances matching a tag . | cosqa-train-80 | def _aws_get_instance_by_tag(region, name, tag, raw):
"""Get all instances matching a tag."""
client = boto3.session.Session().client('ec2', region)
matching_reservations = client.describe_instances(Filters=[{'Name': tag, 'Values': [name]}]).get('Reservations', [])
instances = []
[[instances.append(_aws_instance_from_dict(region, instance, raw)) # pylint: disable=expression-not-assigned
for instance in reservation.get('Instances')] for reservation in matching_reservations if reservation]
return instances |
def cfloat64_array_to_numpy ( cptr , length ) : if isinstance ( cptr , ctypes . POINTER ( ctypes . c_double ) ) : return np . fromiter ( cptr , dtype = np . float64 , count = length ) else : raise RuntimeError ( 'Expected double pointer' ) | 1 | python ctypes array to pointer | Convert a ctypes double pointer array to a numpy array . | cosqa-train-81 | def cfloat64_array_to_numpy(cptr, length):
"""Convert a ctypes double pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_double)):
return np.fromiter(cptr, dtype=np.float64, count=length)
else:
raise RuntimeError('Expected double pointer') |
def loganalytics_data_plane_client ( cli_ctx , _ ) : from . vendored_sdks . loganalytics import LogAnalyticsDataClient from azure . cli . core . _profile import Profile profile = Profile ( cli_ctx = cli_ctx ) cred , _ , _ = profile . get_login_credentials ( resource = "https://api.loganalytics.io" ) return LogAnalyticsDataClient ( cred ) | 0 | azure python use cli session | Initialize Log Analytics data client for use with CLI . | cosqa-train-82 | def loganalytics_data_plane_client(cli_ctx, _):
"""Initialize Log Analytics data client for use with CLI."""
from .vendored_sdks.loganalytics import LogAnalyticsDataClient
from azure.cli.core._profile import Profile
profile = Profile(cli_ctx=cli_ctx)
cred, _, _ = profile.get_login_credentials(
resource="https://api.loganalytics.io")
return LogAnalyticsDataClient(cred) |
def cfloat32_array_to_numpy ( cptr , length ) : if isinstance ( cptr , ctypes . POINTER ( ctypes . c_float ) ) : return np . fromiter ( cptr , dtype = np . float32 , count = length ) else : raise RuntimeError ( 'Expected float pointer' ) | 0 | python ctypes make float string | Convert a ctypes float pointer array to a numpy array . | cosqa-train-83 | def cfloat32_array_to_numpy(cptr, length):
"""Convert a ctypes float pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_float)):
return np.fromiter(cptr, dtype=np.float32, count=length)
else:
raise RuntimeError('Expected float pointer') |
def underscore ( text ) : return UNDERSCORE [ 1 ] . sub ( r'\1_\2' , UNDERSCORE [ 0 ] . sub ( r'\1_\2' , text ) ) . lower ( ) | 0 | before after underscore python | Converts text that may be camelcased into an underscored format | cosqa-train-84 | def underscore(text):
"""Converts text that may be camelcased into an underscored format"""
return UNDERSCORE[1].sub(r'\1_\2', UNDERSCORE[0].sub(r'\1_\2', text)).lower() |
def cint8_array_to_numpy ( cptr , length ) : if isinstance ( cptr , ctypes . POINTER ( ctypes . c_int8 ) ) : return np . fromiter ( cptr , dtype = np . int8 , count = length ) else : raise RuntimeError ( 'Expected int pointer' ) | 0 | python ctypes pointer from int | Convert a ctypes int pointer array to a numpy array . | cosqa-train-85 | def cint8_array_to_numpy(cptr, length):
"""Convert a ctypes int pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_int8)):
return np.fromiter(cptr, dtype=np.int8, count=length)
else:
raise RuntimeError('Expected int pointer') |
def get_stoplist ( language ) : file_path = os . path . join ( "stoplists" , "%s.txt" % language ) try : stopwords = pkgutil . get_data ( "justext" , file_path ) except IOError : raise ValueError ( "Stoplist for language '%s' is missing. " "Please use function 'get_stoplists' for complete list of stoplists " "and feel free to contribute by your own stoplist." % language ) return frozenset ( w . decode ( "utf8" ) . lower ( ) for w in stopwords . splitlines ( ) ) | 0 | best stopword list for python | Returns an built - in stop - list for the language as a set of words . | cosqa-train-86 | def get_stoplist(language):
"""Returns an built-in stop-list for the language as a set of words."""
file_path = os.path.join("stoplists", "%s.txt" % language)
try:
stopwords = pkgutil.get_data("justext", file_path)
except IOError:
raise ValueError(
"Stoplist for language '%s' is missing. "
"Please use function 'get_stoplists' for complete list of stoplists "
"and feel free to contribute by your own stoplist." % language
)
return frozenset(w.decode("utf8").lower() for w in stopwords.splitlines()) |
def add_str ( window , line_num , str ) : try : window . addstr ( line_num , 0 , str ) except curses . error : pass | 0 | python curses addstr returned err | attempt to draw str on screen and ignore errors if they occur | cosqa-train-87 | def add_str(window, line_num, str):
""" attempt to draw str on screen and ignore errors if they occur """
try:
window.addstr(line_num, 0, str)
except curses.error:
pass |
def relative_path ( path ) : return os . path . join ( os . path . dirname ( __file__ ) , path ) | 1 | best way to give file path in python | Return the given path relative to this file . | cosqa-train-88 | def relative_path(path):
"""
Return the given path relative to this file.
"""
return os.path.join(os.path.dirname(__file__), path) |
def dictfetchall ( cursor ) : desc = cursor . description return [ dict ( zip ( [ col [ 0 ] for col in desc ] , row ) ) for row in cursor . fetchall ( ) ] | 0 | python cursor fetchall field name | Returns all rows from a cursor as a dict ( rather than a headerless table ) | cosqa-train-89 | def dictfetchall(cursor):
"""Returns all rows from a cursor as a dict (rather than a headerless table)
From Django Documentation: https://docs.djangoproject.com/en/dev/topics/db/sql/
"""
desc = cursor.description
return [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()] |
def xmltreefromfile ( filename ) : try : return ElementTree . parse ( filename , ElementTree . XMLParser ( collect_ids = False ) ) except TypeError : return ElementTree . parse ( filename , ElementTree . XMLParser ( ) ) | 0 | best way to parse xml files in python | Internal function to read an XML file | cosqa-train-90 | def xmltreefromfile(filename):
"""Internal function to read an XML file"""
try:
return ElementTree.parse(filename, ElementTree.XMLParser(collect_ids=False))
except TypeError:
return ElementTree.parse(filename, ElementTree.XMLParser()) |
def _dictfetchall ( self , cursor ) : columns = [ col [ 0 ] for col in cursor . description ] return [ dict ( zip ( columns , row ) ) for row in cursor . fetchall ( ) ] | 0 | python cursor fetchone to dictionary | Return all rows from a cursor as a dict . | cosqa-train-91 | def _dictfetchall(self, cursor):
""" Return all rows from a cursor as a dict. """
columns = [col[0] for col in cursor.description]
return [
dict(zip(columns, row))
for row in cursor.fetchall()
] |
def beta_pdf ( x , a , b ) : bc = 1 / beta ( a , b ) fc = x ** ( a - 1 ) sc = ( 1 - x ) ** ( b - 1 ) return bc * fc * sc | 0 | beta distribution function graph in python | Beta distirbution probability density function . | cosqa-train-92 | def beta_pdf(x, a, b):
"""Beta distirbution probability density function."""
bc = 1 / beta(a, b)
fc = x ** (a - 1)
sc = (1 - x) ** (b - 1)
return bc * fc * sc |
def filter_out ( queryset , setting_name ) : kwargs = helpers . get_settings ( ) . get ( setting_name , { } ) . get ( 'FILTER_OUT' , { } ) queryset = queryset . exclude ( * * kwargs ) return queryset | 0 | python custom filter based on extra | Remove unwanted results from queryset | cosqa-train-93 | def filter_out(queryset, setting_name):
"""
Remove unwanted results from queryset
"""
kwargs = helpers.get_settings().get(setting_name, {}).get('FILTER_OUT', {})
queryset = queryset.exclude(**kwargs)
return queryset |
def intToBin ( i ) : # divide in two parts (bytes) i1 = i % 256 i2 = int ( i / 256 ) # make string (little endian) return i . to_bytes ( 2 , byteorder = 'little' ) | 0 | bin as 8 digits python | Integer to two bytes | cosqa-train-94 | def intToBin(i):
""" Integer to two bytes """
# divide in two parts (bytes)
i1 = i % 256
i2 = int(i / 256)
# make string (little endian)
return i.to_bytes(2, byteorder='little') |
def listlike ( obj ) : return hasattr ( obj , "__iter__" ) and not issubclass ( type ( obj ) , str ) and not issubclass ( type ( obj ) , unicode ) | 0 | python custom object nonetype | Is an object iterable like a list ( and not a string ) ? | cosqa-train-95 | def listlike(obj):
"""Is an object iterable like a list (and not a string)?"""
return hasattr(obj, "__iter__") \
and not issubclass(type(obj), str)\
and not issubclass(type(obj), unicode) |
def table_top_abs ( self ) : table_height = np . array ( [ 0 , 0 , self . table_full_size [ 2 ] ] ) return string_to_array ( self . floor . get ( "pos" ) ) + table_height | 1 | bottom 5 rows in python | Returns the absolute position of table top | cosqa-train-96 | def table_top_abs(self):
"""Returns the absolute position of table top"""
table_height = np.array([0, 0, self.table_full_size[2]])
return string_to_array(self.floor.get("pos")) + table_height |
def pdf ( x , mu , std ) : return ( 1.0 / ( std * sqrt ( 2 * pi ) ) ) * np . exp ( - ( x - mu ) ** 2 / ( 2 * std ** 2 ) ) | 0 | python custom probability distribution | Probability density function ( normal distribution ) | cosqa-train-97 | def pdf(x, mu, std):
"""Probability density function (normal distribution)"""
return (1.0 / (std * sqrt(2 * pi))) * np.exp(-(x - mu) ** 2 / (2 * std ** 2)) |
def bytes_to_c_array ( data ) : chars = [ "'{}'" . format ( encode_escape ( i ) ) for i in decode_escape ( data ) ] return ', ' . join ( chars ) + ', 0' | 0 | c style array to python | Make a C array using the given string . | cosqa-train-98 | def bytes_to_c_array(data):
"""
Make a C array using the given string.
"""
chars = [
"'{}'".format(encode_escape(i))
for i in decode_escape(data)
]
return ', '.join(chars) + ', 0' |
def gray2bgr ( img ) : img = img [ ... , None ] if img . ndim == 2 else img out_img = cv2 . cvtColor ( img , cv2 . COLOR_GRAY2BGR ) return out_img | 1 | python cv2 np array to gray scale | Convert a grayscale image to BGR image . | cosqa-train-99 | def gray2bgr(img):
"""Convert a grayscale image to BGR image.
Args:
img (ndarray or str): The input image.
Returns:
ndarray: The converted BGR image.
"""
img = img[..., None] if img.ndim == 2 else img
out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
return out_img |