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 count ( data , axis = None ) : return np . sum ( np . logical_not ( isnull ( data ) ) , axis = axis )
| 1 |
python number of non nan elements in array
|
Count the number of non - NA in this array along the given axis or axes
|
cosqa-train-15800
|
def count(data, axis=None):
"""Count the number of non-NA in this array along the given axis or axes
"""
return np.sum(np.logical_not(isnull(data)), axis=axis)
|
def delimited ( items , character = '|' ) : return '|' . join ( items ) if type ( items ) in ( list , tuple , set ) else items
| 0 |
how to concatonate characters in a list python 3
|
Returns a character delimited version of the provided list as a Python string
|
cosqa-train-15801
|
def delimited(items, character='|'):
"""Returns a character delimited version of the provided list as a Python string"""
return '|'.join(items) if type(items) in (list, tuple, set) else items
|
def length ( self ) : return np . sqrt ( np . sum ( self ** 2 , axis = 1 ) ) . view ( np . ndarray )
| 1 |
python numpy array every nth element
|
Array of vector lengths
|
cosqa-train-15802
|
def length(self):
"""Array of vector lengths"""
return np.sqrt(np.sum(self**2, axis=1)).view(np.ndarray)
|
def covstr ( s ) : try : ret = int ( s ) except ValueError : ret = float ( s ) return ret
| 0 |
how to connect a string to a float in python
|
convert string to int or float .
|
cosqa-train-15803
|
def covstr(s):
""" convert string to int or float. """
try:
ret = int(s)
except ValueError:
ret = float(s)
return ret
|
def flatten_array ( grid ) : grid = [ grid [ i ] [ j ] for i in range ( len ( grid ) ) for j in range ( len ( grid [ i ] ) ) ] while type ( grid [ 0 ] ) is list : grid = flatten_array ( grid ) return grid
| 1 |
python numpy array of arrays flatten
|
Takes a multi - dimensional array and returns a 1 dimensional array with the same contents .
|
cosqa-train-15804
|
def flatten_array(grid):
"""
Takes a multi-dimensional array and returns a 1 dimensional array with the
same contents.
"""
grid = [grid[i][j] for i in range(len(grid)) for j in range(len(grid[i]))]
while type(grid[0]) is list:
grid = flatten_array(grid)
return grid
|
def main ( ctx , connection ) : ctx . obj = Manager ( connection = connection ) ctx . obj . bind ( )
| 0 |
how to connect python to user interfaaces
|
Command line interface for PyBEL .
|
cosqa-train-15805
|
def main(ctx, connection):
"""Command line interface for PyBEL."""
ctx.obj = Manager(connection=connection)
ctx.obj.bind()
|
def as_float_array ( a ) : return np . asarray ( a , dtype = np . quaternion ) . view ( ( np . double , 4 ) )
| 1 |
python numpy conver to float64
|
View the quaternion array as an array of floats
|
cosqa-train-15806
|
def as_float_array(a):
"""View the quaternion array as an array of floats
This function is fast (of order 1 microsecond) because no data is
copied; the returned quantity is just a "view" of the original.
The output view has one more dimension (of size 4) than the input
array, but is otherwise the same shape.
"""
return np.asarray(a, dtype=np.quaternion).view((np.double, 4))
|
def run ( context , port ) : global ctx ctx = context app . run ( port = port )
| 0 |
how to connect to flask socketio from python script
|
Run the Webserver / SocketIO and app
|
cosqa-train-15807
|
def run(context, port):
""" Run the Webserver/SocketIO and app
"""
global ctx
ctx = context
app.run(port=port)
|
def length ( self ) : return np . sqrt ( np . sum ( self ** 2 , axis = 1 ) ) . view ( np . ndarray )
| 0 |
python numpy define 2 dimensional list
|
Array of vector lengths
|
cosqa-train-15808
|
def length(self):
"""Array of vector lengths"""
return np.sqrt(np.sum(self**2, axis=1)).view(np.ndarray)
|
def find_nearest_index ( arr , value ) : arr = np . array ( arr ) index = ( abs ( arr - value ) ) . argmin ( ) return index
| 1 |
python numpy index of nearest value
|
For a given value the function finds the nearest value in the array and returns its index .
|
cosqa-train-15809
|
def find_nearest_index(arr, value):
"""For a given value, the function finds the nearest value
in the array and returns its index."""
arr = np.array(arr)
index = (abs(arr-value)).argmin()
return index
|
def pick_unused_port ( self ) : s = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) s . bind ( ( '127.0.0.1' , 0 ) ) _ , port = s . getsockname ( ) s . close ( ) return port
| 1 |
how to correct socket not define error in python
|
Pick an unused port . There is a slight chance that this wont work .
|
cosqa-train-15810
|
def pick_unused_port(self):
""" Pick an unused port. There is a slight chance that this wont work. """
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 0))
_, port = s.getsockname()
s.close()
return port
|
def mag ( z ) : if isinstance ( z [ 0 ] , np . ndarray ) : return np . array ( list ( map ( np . linalg . norm , z ) ) ) else : return np . linalg . norm ( z )
| 1 |
python numpy magnitude of vector
|
Get the magnitude of a vector .
|
cosqa-train-15811
|
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 total_regular_pixels_from_mask ( mask ) : total_regular_pixels = 0 for y in range ( mask . shape [ 0 ] ) : for x in range ( mask . shape [ 1 ] ) : if not mask [ y , x ] : total_regular_pixels += 1 return total_regular_pixels
| 0 |
how to count masked values in masked array python
|
Compute the total number of unmasked regular pixels in a masks .
|
cosqa-train-15812
|
def total_regular_pixels_from_mask(mask):
"""Compute the total number of unmasked regular pixels in a masks."""
total_regular_pixels = 0
for y in range(mask.shape[0]):
for x in range(mask.shape[1]):
if not mask[y, x]:
total_regular_pixels += 1
return total_regular_pixels
|
def Max ( a , axis , keep_dims ) : return np . amax ( a , axis = axis if not isinstance ( axis , np . ndarray ) else tuple ( axis ) , keepdims = keep_dims ) ,
| 0 |
python numpy max demension
|
Max reduction op .
|
cosqa-train-15813
|
def Max(a, axis, keep_dims):
"""
Max reduction op.
"""
return np.amax(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),
keepdims=keep_dims),
|
def line_count ( fn ) : with open ( fn ) as f : for i , l in enumerate ( f ) : pass return i + 1
| 0 |
how to count number of lines in a files in python
|
Get line count of file
|
cosqa-train-15814
|
def line_count(fn):
""" Get line count of file
Args:
fn (str): Path to file
Return:
Number of lines in file (int)
"""
with open(fn) as f:
for i, l in enumerate(f):
pass
return i + 1
|
def save_json ( object , handle , indent = 2 ) : obj_json = json . dumps ( object , indent = indent , cls = NumpyJSONEncoder ) handle . write ( obj_json )
| 1 |
python numpy save to json
|
Save object as json on CNS .
|
cosqa-train-15815
|
def save_json(object, handle, indent=2):
"""Save object as json on CNS."""
obj_json = json.dumps(object, indent=indent, cls=NumpyJSONEncoder)
handle.write(obj_json)
|
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 |
how to count the frequency of a string in a text file python
|
Return a dictionary of words and word counts in a string .
|
cosqa-train-15816
|
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 bytes_base64 ( x ) : if six . PY2 : return base64 . encodestring ( x ) . replace ( '\n' , '' ) return base64 . encodebytes ( bytes_encode ( x ) ) . replace ( b'\n' , b'' )
| 1 |
python obfuscate base64 codecs eval
|
Turn bytes into base64
|
cosqa-train-15817
|
def bytes_base64(x):
"""Turn bytes into base64"""
if six.PY2:
return base64.encodestring(x).replace('\n', '')
return base64.encodebytes(bytes_encode(x)).replace(b'\n', b'')
|
def count_rows ( self , table_name ) : self . table_must_exist ( table_name ) query = "SELECT COUNT (*) FROM `%s`" % table_name . lower ( ) self . own_cursor . execute ( query ) return int ( self . own_cursor . fetchone ( ) [ 0 ] )
| 0 |
how to count the noofrows in table using python
|
Return the number of entries in a table by counting them .
|
cosqa-train-15818
|
def count_rows(self, table_name):
"""Return the number of entries in a table by counting them."""
self.table_must_exist(table_name)
query = "SELECT COUNT (*) FROM `%s`" % table_name.lower()
self.own_cursor.execute(query)
return int(self.own_cursor.fetchone()[0])
|
def get_list_from_file ( file_name ) : with open ( file_name , mode = 'r' , encoding = 'utf-8' ) as f1 : lst = f1 . readlines ( ) return lst
| 0 |
python open a text file as a list
|
read the lines from a file into a list
|
cosqa-train-15819
|
def get_list_from_file(file_name):
"""read the lines from a file into a list"""
with open(file_name, mode='r', encoding='utf-8') as f1:
lst = f1.readlines()
return lst
|
def debug ( sequence ) : points = [ ] for i , p in enumerate ( sequence ) : copy = Point ( p ) copy [ 'index' ] = i points . append ( copy ) return sequence . __class__ ( points )
| 1 |
how to create a sequence of points in python
|
adds information to the sequence for better debugging currently only an index property on each point in the sequence .
|
cosqa-train-15820
|
def debug(sequence):
"""
adds information to the sequence for better debugging, currently only
an index property on each point in the sequence.
"""
points = []
for i, p in enumerate(sequence):
copy = Point(p)
copy['index'] = i
points.append(copy)
return sequence.__class__(points)
|
def chmod_add_excute ( filename ) : st = os . stat ( filename ) os . chmod ( filename , st . st_mode | stat . S_IEXEC )
| 1 |
python open file with exclusive access permissions
|
Adds execute permission to file . : param filename : : return :
|
cosqa-train-15821
|
def chmod_add_excute(filename):
"""
Adds execute permission to file.
:param filename:
:return:
"""
st = os.stat(filename)
os.chmod(filename, st.st_mode | stat.S_IEXEC)
|
def make_temp ( text ) : import tempfile ( handle , path ) = tempfile . mkstemp ( text = True ) os . close ( handle ) afile = File ( path ) afile . write ( text ) return afile
| 0 |
how to create a temporary text file from a string python
|
Creates a temprorary file and writes the text into it
|
cosqa-train-15822
|
def make_temp(text):
"""
Creates a temprorary file and writes the `text` into it
"""
import tempfile
(handle, path) = tempfile.mkstemp(text=True)
os.close(handle)
afile = File(path)
afile.write(text)
return afile
|
def shader_string ( body , glsl_version = '450 core' ) : line_count = len ( body . split ( '\n' ) ) line_number = inspect . currentframe ( ) . f_back . f_lineno + 1 - line_count return """\
#version %s
%s
""" % ( glsl_version , shader_substring ( body , stack_frame = 2 ) )
| 0 |
python opengl render text
|
Call this method from a function that defines a literal shader string as the body argument . Dresses up a shader string in three ways : 1 ) Insert #version at the top 2 ) Insert #line number declaration 3 ) un - indents The line number information can help debug glsl compile errors . The version string needs to be the very first characters in the shader which can be distracting requiring backslashes or other tricks . The unindenting allows you to type the shader code at a pleasing indent level in your python method while still creating an unindented GLSL string at the end .
|
cosqa-train-15823
|
def shader_string(body, glsl_version='450 core'):
"""
Call this method from a function that defines a literal shader string as the "body" argument.
Dresses up a shader string in three ways:
1) Insert #version at the top
2) Insert #line number declaration
3) un-indents
The line number information can help debug glsl compile errors.
The version string needs to be the very first characters in the shader,
which can be distracting, requiring backslashes or other tricks.
The unindenting allows you to type the shader code at a pleasing indent level
in your python method, while still creating an unindented GLSL string at the end.
"""
line_count = len(body.split('\n'))
line_number = inspect.currentframe().f_back.f_lineno + 1 - line_count
return """\
#version %s
%s
""" % (glsl_version, shader_substring(body, stack_frame=2))
|
def sometimesish ( fn ) : def wrapped ( * args , * * kwargs ) : if random . randint ( 1 , 2 ) == 1 : return fn ( * args , * * kwargs ) return wrapped
| 0 |
how to create an automated test in python to check if an integer is part of a random function
|
Has a 50 / 50 chance of calling a function
|
cosqa-train-15824
|
def sometimesish(fn):
"""
Has a 50/50 chance of calling a function
"""
def wrapped(*args, **kwargs):
if random.randint(1, 2) == 1:
return fn(*args, **kwargs)
return wrapped
|
def average_gradient ( data , * kwargs ) : return np . average ( np . array ( np . gradient ( data ) ) ** 2 )
| 0 |
how to create an image gradient in python
|
Compute average gradient norm of an image
|
cosqa-train-15825
|
def average_gradient(data, *kwargs):
""" Compute average gradient norm of an image
"""
return np.average(np.array(np.gradient(data))**2)
|
def perl_cmd ( ) : perl = which ( os . path . join ( get_bcbio_bin ( ) , "perl" ) ) if perl : return perl else : return which ( "perl" )
| 0 |
python or perl scripting 2017
|
Retrieve path to locally installed conda Perl or first in PATH .
|
cosqa-train-15826
|
def perl_cmd():
"""Retrieve path to locally installed conda Perl or first in PATH.
"""
perl = which(os.path.join(get_bcbio_bin(), "perl"))
if perl:
return perl
else:
return which("perl")
|
def dumped ( text , level , indent = 2 ) : return indented ( "{\n%s\n}" % indented ( text , level + 1 , indent ) or "None" , level , indent ) + "\n"
| 0 |
how to create an indent in python
|
Put curly brackets round an indented text
|
cosqa-train-15827
|
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 format_op_hdr ( ) : txt = 'Base Filename' . ljust ( 36 ) + ' ' txt += 'Lines' . rjust ( 7 ) + ' ' txt += 'Words' . rjust ( 7 ) + ' ' txt += 'Unique' . ljust ( 8 ) + '' return txt
| 1 |
how to create header in python
|
Build the header
|
cosqa-train-15828
|
def format_op_hdr():
"""
Build the header
"""
txt = 'Base Filename'.ljust(36) + ' '
txt += 'Lines'.rjust(7) + ' '
txt += 'Words'.rjust(7) + ' '
txt += 'Unique'.ljust(8) + ''
return txt
|
def resize_image_with_crop_or_pad ( img , target_height , target_width ) : h , w = target_height , target_width max_h , max_w , c = img . shape # crop img = crop_center ( img , min ( max_h , h ) , min ( max_w , w ) ) # pad padded_img = np . zeros ( shape = ( h , w , c ) , dtype = img . dtype ) padded_img [ : img . shape [ 0 ] , : img . shape [ 1 ] , : img . shape [ 2 ] ] = img return padded_img
| 1 |
python pad image boundary with 0
|
Crops and / or pads an image to a target width and height .
|
cosqa-train-15829
|
def resize_image_with_crop_or_pad(img, target_height, target_width):
"""
Crops and/or pads an image to a target width and height.
Resizes an image to a target width and height by either cropping the image or padding it with zeros.
NO CENTER CROP. NO CENTER PAD. (Just fill bottom right or crop bottom right)
:param img: Numpy array representing the image.
:param target_height: Target height.
:param target_width: Target width.
:return: The cropped and padded image.
"""
h, w = target_height, target_width
max_h, max_w, c = img.shape
# crop
img = crop_center(img, min(max_h, h), min(max_w, w))
# pad
padded_img = np.zeros(shape=(h, w, c), dtype=img.dtype)
padded_img[:img.shape[0], :img.shape[1], :img.shape[2]] = img
return padded_img
|
def interface_direct_class ( data_class ) : if data_class in ASSET : interface = AssetsInterface ( ) elif data_class in PARTY : interface = PartiesInterface ( ) elif data_class in BOOK : interface = BooksInterface ( ) elif data_class in CORPORATE_ACTION : interface = CorporateActionsInterface ( ) elif data_class in MARKET_DATA : interface = MarketDataInterface ( ) elif data_class in TRANSACTION : interface = TransactionsInterface ( ) else : interface = AssetManagersInterface ( ) return interface
| 1 |
how to create interfaces python
|
help to direct to the correct interface interacting with DB by class name only
|
cosqa-train-15830
|
def interface_direct_class(data_class):
"""help to direct to the correct interface interacting with DB by class name only"""
if data_class in ASSET:
interface = AssetsInterface()
elif data_class in PARTY:
interface = PartiesInterface()
elif data_class in BOOK:
interface = BooksInterface()
elif data_class in CORPORATE_ACTION:
interface = CorporateActionsInterface()
elif data_class in MARKET_DATA:
interface = MarketDataInterface()
elif data_class in TRANSACTION:
interface = TransactionsInterface()
else:
interface = AssetManagersInterface()
return interface
|
def zero_pad ( m , n = 1 ) : return np . pad ( m , ( n , n ) , mode = 'constant' , constant_values = [ 0 ] )
| 0 |
python pad symmetrical matrix
|
Pad a matrix with zeros on all sides .
|
cosqa-train-15831
|
def zero_pad(m, n=1):
"""Pad a matrix with zeros, on all sides."""
return np.pad(m, (n, n), mode='constant', constant_values=[0])
|
def chunked ( l , n ) : return [ l [ i : i + n ] for i in range ( 0 , len ( l ) , n ) ]
| 0 |
how to cut a list into groups of 10 python
|
Chunk one big list into few small lists .
|
cosqa-train-15832
|
def chunked(l, n):
"""Chunk one big list into few small lists."""
return [l[i:i + n] for i in range(0, len(l), n)]
|
def dcounts ( self ) : print ( "WARNING: Distinct value count for all tables can take a long time..." , file = sys . stderr ) sys . stderr . flush ( ) data = [ ] for t in self . tables ( ) : for c in t . columns ( ) : data . append ( [ t . name ( ) , c . name ( ) , c . dcount ( ) , t . size ( ) , c . dcount ( ) / float ( t . size ( ) ) ] ) df = pd . DataFrame ( data , columns = [ "table" , "column" , "distinct" , "size" , "fraction" ] ) return df
| 0 |
python panda how to column counts and turn them into a df
|
: return : a data frame with names and distinct counts and fractions for all columns in the database
|
cosqa-train-15833
|
def dcounts(self):
"""
:return: a data frame with names and distinct counts and fractions for all columns in the database
"""
print("WARNING: Distinct value count for all tables can take a long time...", file=sys.stderr)
sys.stderr.flush()
data = []
for t in self.tables():
for c in t.columns():
data.append([t.name(), c.name(), c.dcount(), t.size(), c.dcount() / float(t.size())])
df = pd.DataFrame(data, columns=["table", "column", "distinct", "size", "fraction"])
return df
|
def _remove_empty_items ( d , required ) : new_dict = { } for k , v in d . items ( ) : if k in required : new_dict [ k ] = v elif isinstance ( v , int ) or v : # "if v" would suppress emitting int(0) new_dict [ k ] = v return new_dict
| 0 |
how to decleare an empty dictinoary in python
|
Return a new dict with any empty items removed .
|
cosqa-train-15834
|
def _remove_empty_items(d, required):
"""Return a new dict with any empty items removed.
Note that this is not a deep check. If d contains a dictionary which
itself contains empty items, those are never checked.
This method exists to make to_serializable() functions cleaner.
We could revisit this some day, but for now, the serialized objects are
stripped of empty values to keep the output YAML more compact.
Args:
d: a dictionary
required: list of required keys (for example, TaskDescriptors always emit
the "task-id", even if None)
Returns:
A dictionary with empty items removed.
"""
new_dict = {}
for k, v in d.items():
if k in required:
new_dict[k] = v
elif isinstance(v, int) or v:
# "if v" would suppress emitting int(0)
new_dict[k] = v
return new_dict
|
def ms_panset ( self , viewer , event , data_x , data_y , msg = True ) : if self . canpan and ( event . state == 'down' ) : self . _panset ( viewer , data_x , data_y , msg = msg ) return True
| 0 |
python panedwindow is not defined
|
An interactive way to set the pan position . The location ( data_x data_y ) will be centered in the window .
|
cosqa-train-15835
|
def ms_panset(self, viewer, event, data_x, data_y,
msg=True):
"""An interactive way to set the pan position. The location
(data_x, data_y) will be centered in the window.
"""
if self.canpan and (event.state == 'down'):
self._panset(viewer, data_x, data_y, msg=msg)
return True
|
def disassemble_file ( filename , outstream = None ) : filename = check_object_path ( filename ) ( version , timestamp , magic_int , co , is_pypy , source_size ) = load_module ( filename ) if type ( co ) == list : for con in co : disco ( version , con , outstream ) else : disco ( version , co , outstream , is_pypy = is_pypy ) co = None
| 0 |
how to decompile python pyd file
|
disassemble Python byte - code file ( . pyc )
|
cosqa-train-15836
|
def disassemble_file(filename, outstream=None):
"""
disassemble Python byte-code file (.pyc)
If given a Python source file (".py") file, we'll
try to find the corresponding compiled object.
"""
filename = check_object_path(filename)
(version, timestamp, magic_int, co, is_pypy,
source_size) = load_module(filename)
if type(co) == list:
for con in co:
disco(version, con, outstream)
else:
disco(version, co, outstream, is_pypy=is_pypy)
co = None
|
def load_results ( result_files , options , run_set_id = None , columns = None , columns_relevant_for_diff = set ( ) ) : return parallel . map ( load_result , result_files , itertools . repeat ( options ) , itertools . repeat ( run_set_id ) , itertools . repeat ( columns ) , itertools . repeat ( columns_relevant_for_diff ) )
| 1 |
python parallel load different files
|
Version of load_result for multiple input files that will be loaded concurrently .
|
cosqa-train-15837
|
def load_results(result_files, options, run_set_id=None, columns=None,
columns_relevant_for_diff=set()):
"""Version of load_result for multiple input files that will be loaded concurrently."""
return parallel.map(
load_result,
result_files,
itertools.repeat(options),
itertools.repeat(run_set_id),
itertools.repeat(columns),
itertools.repeat(columns_relevant_for_diff))
|
def split ( s ) : l = [ _split ( x ) for x in _SPLIT_RE . split ( s ) ] return [ item for sublist in l for item in sublist ]
| 0 |
how to dectect spaces in string python
|
Uses dynamic programming to infer the location of spaces in a string without spaces .
|
cosqa-train-15838
|
def split(s):
"""Uses dynamic programming to infer the location of spaces in a string without spaces."""
l = [_split(x) for x in _SPLIT_RE.split(s)]
return [item for sublist in l for item in sublist]
|
def expandvars_dict ( settings ) : return dict ( ( key , os . path . expandvars ( value ) ) for key , value in settings . iteritems ( ) )
| 0 |
python parse enviornment variables
|
Expands all environment variables in a settings dictionary .
|
cosqa-train-15839
|
def expandvars_dict(settings):
"""Expands all environment variables in a settings dictionary."""
return dict(
(key, os.path.expandvars(value))
for key, value in settings.iteritems()
)
|
def Bernstein ( n , k ) : coeff = binom ( n , k ) def _bpoly ( x ) : return coeff * x ** k * ( 1 - x ) ** ( n - k ) return _bpoly
| 0 |
how to define a binomial coeffecient function python
|
Bernstein polynomial .
|
cosqa-train-15840
|
def Bernstein(n, k):
"""Bernstein polynomial.
"""
coeff = binom(n, k)
def _bpoly(x):
return coeff * x ** k * (1 - x) ** (n - k)
return _bpoly
|
def from_pb ( cls , pb ) : obj = cls . _from_pb ( pb ) obj . _pb = pb return obj
| 0 |
python parse local protobuf
|
Instantiate the object from a protocol buffer .
|
cosqa-train-15841
|
def from_pb(cls, pb):
"""Instantiate the object from a protocol buffer.
Args:
pb (protobuf)
Save a reference to the protocol buffer on the object.
"""
obj = cls._from_pb(pb)
obj._pb = pb
return obj
|
def get_table_width ( table ) : columns = transpose_table ( prepare_rows ( table ) ) widths = [ max ( len ( cell ) for cell in column ) for column in columns ] return len ( '+' + '|' . join ( '-' * ( w + 2 ) for w in widths ) + '+' )
| 0 |
how to define length of a new table in python
|
Gets the width of the table that would be printed . : rtype : int
|
cosqa-train-15842
|
def get_table_width(table):
"""
Gets the width of the table that would be printed.
:rtype: ``int``
"""
columns = transpose_table(prepare_rows(table))
widths = [max(len(cell) for cell in column) for column in columns]
return len('+' + '|'.join('-' * (w + 2) for w in widths) + '+')
|
def parse ( self ) : f = open ( self . parse_log_path , "r" ) self . parse2 ( f ) f . close ( )
| 1 |
python parse log file example
|
Parse file specified by constructor .
|
cosqa-train-15843
|
def parse(self):
"""
Parse file specified by constructor.
"""
f = open(self.parse_log_path, "r")
self.parse2(f)
f.close()
|
def main ( idle ) : while True : LOG . debug ( "Sleeping for {0} seconds." . format ( idle ) ) time . sleep ( idle )
| 0 |
how to delay for loop in python
|
Any normal python logic which runs a loop . Can take arguments .
|
cosqa-train-15844
|
def main(idle):
"""Any normal python logic which runs a loop. Can take arguments."""
while True:
LOG.debug("Sleeping for {0} seconds.".format(idle))
time.sleep(idle)
|
def urlencoded ( body , charset = 'ascii' , * * kwargs ) : return parse_query_string ( text ( body , charset = charset ) , False )
| 0 |
python parse query string
|
Converts query strings into native Python objects
|
cosqa-train-15845
|
def urlencoded(body, charset='ascii', **kwargs):
"""Converts query strings into native Python objects"""
return parse_query_string(text(body, charset=charset), False)
|
def _delete_local ( self , filename ) : if os . path . exists ( filename ) : os . remove ( filename )
| 1 |
how to delete a file after reading in python script
|
Deletes the specified file from the local filesystem .
|
cosqa-train-15846
|
def _delete_local(self, filename):
"""Deletes the specified file from the local filesystem."""
if os.path.exists(filename):
os.remove(filename)
|
def _parse_single_response ( cls , response_data ) : if not isinstance ( response_data , dict ) : raise errors . RPCInvalidRequest ( "No valid RPC-package." ) if "id" not in response_data : raise errors . RPCInvalidRequest ( """Invalid Response, "id" missing.""" ) request_id = response_data [ 'id' ] if "jsonrpc" not in response_data : raise errors . RPCInvalidRequest ( """Invalid Response, "jsonrpc" missing.""" , request_id ) if not isinstance ( response_data [ "jsonrpc" ] , ( str , unicode ) ) : raise errors . RPCInvalidRequest ( """Invalid Response, "jsonrpc" must be a string.""" ) if response_data [ "jsonrpc" ] != "2.0" : raise errors . RPCInvalidRequest ( """Invalid jsonrpc version.""" , request_id ) error = response_data . get ( 'error' , None ) result = response_data . get ( 'result' , None ) if error and result : raise errors . RPCInvalidRequest ( """Invalid Response, only "result" OR "error" allowed.""" , request_id ) if error : if not isinstance ( error , dict ) : raise errors . RPCInvalidRequest ( "Invalid Response, invalid error-object." , request_id ) if not ( "code" in error and "message" in error ) : raise errors . RPCInvalidRequest ( "Invalid Response, invalid error-object." , request_id ) error_data = error . get ( "data" , None ) if error [ 'code' ] in errors . ERROR_CODE_CLASS_MAP : raise errors . ERROR_CODE_CLASS_MAP [ error [ 'code' ] ] ( error_data , request_id ) else : error_object = errors . RPCFault ( error_data , request_id ) error_object . error_code = error [ 'code' ] error_object . message = error [ 'message' ] raise error_object return result , request_id
| 0 |
python parse rpc response
|
de - serialize a JSON - RPC Response / error
|
cosqa-train-15847
|
def _parse_single_response(cls, response_data):
"""de-serialize a JSON-RPC Response/error
:Returns: | [result, id] for Responses
:Raises: | RPCFault+derivates for error-packages/faults, RPCParseError, RPCInvalidRPC
"""
if not isinstance(response_data, dict):
raise errors.RPCInvalidRequest("No valid RPC-package.")
if "id" not in response_data:
raise errors.RPCInvalidRequest("""Invalid Response, "id" missing.""")
request_id = response_data['id']
if "jsonrpc" not in response_data:
raise errors.RPCInvalidRequest("""Invalid Response, "jsonrpc" missing.""", request_id)
if not isinstance(response_data["jsonrpc"], (str, unicode)):
raise errors.RPCInvalidRequest("""Invalid Response, "jsonrpc" must be a string.""")
if response_data["jsonrpc"] != "2.0":
raise errors.RPCInvalidRequest("""Invalid jsonrpc version.""", request_id)
error = response_data.get('error', None)
result = response_data.get('result', None)
if error and result:
raise errors.RPCInvalidRequest("""Invalid Response, only "result" OR "error" allowed.""", request_id)
if error:
if not isinstance(error, dict):
raise errors.RPCInvalidRequest("Invalid Response, invalid error-object.", request_id)
if not ("code" in error and "message" in error):
raise errors.RPCInvalidRequest("Invalid Response, invalid error-object.", request_id)
error_data = error.get("data", None)
if error['code'] in errors.ERROR_CODE_CLASS_MAP:
raise errors.ERROR_CODE_CLASS_MAP[error['code']](error_data, request_id)
else:
error_object = errors.RPCFault(error_data, request_id)
error_object.error_code = error['code']
error_object.message = error['message']
raise error_object
return result, request_id
|
def trim ( self ) : for key , value in list ( iteritems ( self . counters ) ) : if value . empty ( ) : del self . counters [ key ]
| 0 |
how to delete all empty values in dictionary python
|
Clear not used counters
|
cosqa-train-15848
|
def trim(self):
"""Clear not used counters"""
for key, value in list(iteritems(self.counters)):
if value.empty():
del self.counters[key]
|
def xml_str_to_dict ( s ) : xml = minidom . parseString ( s ) return pythonzimbra . tools . xmlserializer . dom_to_dict ( xml . firstChild )
| 1 |
python parse xml string to dict
|
Transforms an XML string it to python - zimbra dict format
|
cosqa-train-15849
|
def xml_str_to_dict(s):
""" Transforms an XML string it to python-zimbra dict format
For format, see:
https://github.com/Zimbra-Community/python-zimbra/blob/master/README.md
:param: a string, containing XML
:returns: a dict, with python-zimbra format
"""
xml = minidom.parseString(s)
return pythonzimbra.tools.xmlserializer.dom_to_dict(xml.firstChild)
|
def delete_all_eggs ( self ) : path_to_delete = os . path . join ( self . egg_directory , "lib" , "python" ) if os . path . exists ( path_to_delete ) : shutil . rmtree ( path_to_delete )
| 0 |
how to delete all old python on ubuntu
|
delete all the eggs in the directory specified
|
cosqa-train-15850
|
def delete_all_eggs(self):
""" delete all the eggs in the directory specified """
path_to_delete = os.path.join(self.egg_directory, "lib", "python")
if os.path.exists(path_to_delete):
shutil.rmtree(path_to_delete)
|
def distinct ( l ) : seen = set ( ) seen_add = seen . add return ( _ for _ in l if not ( _ in seen or seen_add ( _ ) ) )
| 1 |
how to delete the elements of one list from another python without duplicates
|
Return a list where the duplicates have been removed .
|
cosqa-train-15851
|
def distinct(l):
"""
Return a list where the duplicates have been removed.
Args:
l (list): the list to filter.
Returns:
list: the same list without duplicates.
"""
seen = set()
seen_add = seen.add
return (_ for _ in l if not (_ in seen or seen_add(_)))
|
def safe_call ( cls , method , * args ) : return cls . call ( method , * args , safe = True )
| 1 |
python passing instance method to api
|
Call a remote api method but don t raise if an error occurred .
|
cosqa-train-15852
|
def safe_call(cls, method, *args):
""" Call a remote api method but don't raise if an error occurred."""
return cls.call(method, *args, safe=True)
|
def get_height_for_line ( self , lineno ) : if self . wrap_lines : return self . ui_content . get_height_for_line ( lineno , self . window_width ) else : return 1
| 1 |
how to denote the total width of a line in python
|
Return the height of the given line . ( The height that it would take if this line became visible . )
|
cosqa-train-15853
|
def get_height_for_line(self, lineno):
"""
Return the height of the given line.
(The height that it would take, if this line became visible.)
"""
if self.wrap_lines:
return self.ui_content.get_height_for_line(lineno, self.window_width)
else:
return 1
|
def grandparent_path ( self ) : return os . path . basename ( os . path . join ( self . path , '../..' ) )
| 0 |
python path parent's parent
|
return grandparent s path string
|
cosqa-train-15854
|
def grandparent_path(self):
""" return grandparent's path string """
return os.path.basename(os.path.join(self.path, '../..'))
|
def get_best_encoding ( stream ) : rv = getattr ( stream , 'encoding' , None ) or sys . getdefaultencoding ( ) if is_ascii_encoding ( rv ) : return 'utf-8' return rv
| 0 |
how to detect encoding of a character python
|
Returns the default stream encoding if not found .
|
cosqa-train-15855
|
def get_best_encoding(stream):
"""Returns the default stream encoding if not found."""
rv = getattr(stream, 'encoding', None) or sys.getdefaultencoding()
if is_ascii_encoding(rv):
return 'utf-8'
return rv
|
def get_size_in_bytes ( self , handle ) : fpath = self . _fpath_from_handle ( handle ) return os . stat ( fpath ) . st_size
| 1 |
python pathlib path get file size
|
Return the size in bytes .
|
cosqa-train-15856
|
def get_size_in_bytes(self, handle):
"""Return the size in bytes."""
fpath = self._fpath_from_handle(handle)
return os.stat(fpath).st_size
|
def watched_extension ( extension ) : for ext in hamlpy . VALID_EXTENSIONS : if extension . endswith ( '.' + ext ) : return True return False
| 0 |
how to detect files with specific extensions python
|
Return True if the given extension is one of the watched extensions
|
cosqa-train-15857
|
def watched_extension(extension):
"""Return True if the given extension is one of the watched extensions"""
for ext in hamlpy.VALID_EXTENSIONS:
if extension.endswith('.' + ext):
return True
return False
|
def seconds ( num ) : now = pytime . time ( ) end = now + num until ( end )
| 0 |
python pause in a loop
|
Pause for this many seconds
|
cosqa-train-15858
|
def seconds(num):
"""
Pause for this many seconds
"""
now = pytime.time()
end = now + num
until(end)
|
def region_from_segment ( image , segment ) : x , y , w , h = segment return image [ y : y + h , x : x + w ]
| 0 |
how to detect segments in an image python
|
given a segment ( rectangle ) and an image returns it s corresponding subimage
|
cosqa-train-15859
|
def region_from_segment(image, segment):
"""given a segment (rectangle) and an image, returns it's corresponding subimage"""
x, y, w, h = segment
return image[y:y + h, x:x + w]
|
def set_trace ( ) : # https://github.com/nose-devs/nose/blob/master/nose/tools/nontrivial.py pdb . Pdb ( stdout = sys . __stdout__ ) . set_trace ( sys . _getframe ( ) . f_back )
| 1 |
python pdb stack frame
|
Start a Pdb instance at the calling frame with stdout routed to sys . __stdout__ .
|
cosqa-train-15860
|
def set_trace():
"""Start a Pdb instance at the calling frame, with stdout routed to sys.__stdout__."""
# https://github.com/nose-devs/nose/blob/master/nose/tools/nontrivial.py
pdb.Pdb(stdout=sys.__stdout__).set_trace(sys._getframe().f_back)
|
def _calculate_similarity ( c ) : ma = { } for idc in c : set1 = _get_seqs ( c [ idc ] ) [ ma . update ( { ( idc , idc2 ) : _common ( set1 , _get_seqs ( c [ idc2 ] ) , idc , idc2 ) } ) for idc2 in c if idc != idc2 and ( idc2 , idc ) not in ma ] # logger.debug("_calculate_similarity_ %s" % ma) return ma
| 1 |
how to detect similarities in lists in python
|
Get a similarity matrix of % of shared sequence
|
cosqa-train-15861
|
def _calculate_similarity(c):
"""Get a similarity matrix of % of shared sequence
:param c: cluster object
:return ma: similarity matrix
"""
ma = {}
for idc in c:
set1 = _get_seqs(c[idc])
[ma.update({(idc, idc2): _common(set1, _get_seqs(c[idc2]), idc, idc2)}) for idc2 in c if idc != idc2 and (idc2, idc) not in ma]
# logger.debug("_calculate_similarity_ %s" % ma)
return ma
|
def load ( self , filename = 'classifier.dump' ) : ifile = open ( filename , 'r+' ) self . classifier = pickle . load ( ifile ) ifile . close ( )
| 0 |
python pickle failing to load old pickle file
|
Unpickles the classifier used
|
cosqa-train-15862
|
def load(self, filename='classifier.dump'):
"""
Unpickles the classifier used
"""
ifile = open(filename, 'r+')
self.classifier = pickle.load(ifile)
ifile.close()
|
def isin ( elems , line ) : found = False for e in elems : if e in line . lower ( ) : found = True break return found
| 0 |
how to deterine if a string is in a list python
|
Check if an element from a list is in a string .
|
cosqa-train-15863
|
def isin(elems, line):
"""Check if an element from a list is in a string.
:type elems: list
:type line: str
"""
found = False
for e in elems:
if e in line.lower():
found = True
break
return found
|
def unpickle_file ( picklefile , * * kwargs ) : with open ( picklefile , 'rb' ) as f : return pickle . load ( f , * * kwargs )
| 1 |
python pickle load return value
|
Helper function to unpickle data from picklefile .
|
cosqa-train-15864
|
def unpickle_file(picklefile, **kwargs):
"""Helper function to unpickle data from `picklefile`."""
with open(picklefile, 'rb') as f:
return pickle.load(f, **kwargs)
|
def _string_width ( self , s ) : s = str ( s ) w = 0 for i in s : w += self . character_widths [ i ] return w * self . font_size / 1000.0
| 1 |
how to determine font of a string in python
|
Get width of a string in the current font
|
cosqa-train-15865
|
def _string_width(self, s):
"""Get width of a string in the current font"""
s = str(s)
w = 0
for i in s:
w += self.character_widths[i]
return w * self.font_size / 1000.0
|
def to_pydatetime ( self ) : dt = datetime . datetime . combine ( self . _date . to_pydate ( ) , self . _time . to_pytime ( ) ) from . tz import FixedOffsetTimezone return dt . replace ( tzinfo = _utc ) . astimezone ( FixedOffsetTimezone ( self . _offset ) )
| 0 |
python pillow datetime timezone offset
|
Converts datetimeoffset object into Python s datetime . datetime object
|
cosqa-train-15866
|
def to_pydatetime(self):
"""
Converts datetimeoffset object into Python's datetime.datetime object
@return: time zone aware datetime.datetime
"""
dt = datetime.datetime.combine(self._date.to_pydate(), self._time.to_pytime())
from .tz import FixedOffsetTimezone
return dt.replace(tzinfo=_utc).astimezone(FixedOffsetTimezone(self._offset))
|
def bundle_dir ( ) : if frozen ( ) : directory = sys . _MEIPASS else : directory = os . path . dirname ( os . path . abspath ( stack ( ) [ 1 ] [ 1 ] ) ) if os . path . exists ( directory ) : return directory
| 0 |
how to determine that path at runtime on any machine from python program
|
Handle resource management within an executable file .
|
cosqa-train-15867
|
def bundle_dir():
"""Handle resource management within an executable file."""
if frozen():
directory = sys._MEIPASS
else:
directory = os.path.dirname(os.path.abspath(stack()[1][1]))
if os.path.exists(directory):
return directory
|
def add_matplotlib_cmap ( cm , name = None ) : global cmaps cmap = matplotlib_to_ginga_cmap ( cm , name = name ) cmaps [ cmap . name ] = cmap
| 0 |
python plot custom colormap
|
Add a matplotlib colormap .
|
cosqa-train-15868
|
def add_matplotlib_cmap(cm, name=None):
"""Add a matplotlib colormap."""
global cmaps
cmap = matplotlib_to_ginga_cmap(cm, name=name)
cmaps[cmap.name] = cmap
|
def disable_cert_validation ( ) : current_context = ssl . _create_default_https_context ssl . _create_default_https_context = ssl . _create_unverified_context try : yield finally : ssl . _create_default_https_context = current_context
| 1 |
how to disable ssl certificate verification in python
|
Context manager to temporarily disable certificate validation in the standard SSL library .
|
cosqa-train-15869
|
def disable_cert_validation():
"""Context manager to temporarily disable certificate validation in the standard SSL
library.
Note: This should not be used in production code but is sometimes useful for
troubleshooting certificate validation issues.
By design, the standard SSL library does not provide a way to disable verification
of the server side certificate. However, a patch to disable validation is described
by the library developers. This context manager allows applying the patch for
specific sections of code.
"""
current_context = ssl._create_default_https_context
ssl._create_default_https_context = ssl._create_unverified_context
try:
yield
finally:
ssl._create_default_https_context = current_context
|
def human__decision_tree ( ) : # build data N = 1000000 M = 3 X = np . zeros ( ( N , M ) ) X . shape y = np . zeros ( N ) X [ 0 , 0 ] = 1 y [ 0 ] = 8 X [ 1 , 1 ] = 1 y [ 1 ] = 8 X [ 2 , 0 : 2 ] = 1 y [ 2 ] = 4 # fit model xor_model = sklearn . tree . DecisionTreeRegressor ( max_depth = 2 ) xor_model . fit ( X , y ) return xor_model
| 0 |
python plot decision tree in sklearn
|
Decision Tree
|
cosqa-train-15870
|
def human__decision_tree():
""" Decision Tree
"""
# build data
N = 1000000
M = 3
X = np.zeros((N,M))
X.shape
y = np.zeros(N)
X[0, 0] = 1
y[0] = 8
X[1, 1] = 1
y[1] = 8
X[2, 0:2] = 1
y[2] = 4
# fit model
xor_model = sklearn.tree.DecisionTreeRegressor(max_depth=2)
xor_model.fit(X, y)
return xor_model
|
def print_images ( self , * printable_images ) : printable_image = reduce ( lambda x , y : x . append ( y ) , list ( printable_images ) ) self . print_image ( printable_image )
| 1 |
how to display a list of images in python
|
This method allows printing several images in one shot . This is useful if the client code does not want the printer to make pause during printing
|
cosqa-train-15871
|
def print_images(self, *printable_images):
"""
This method allows printing several images in one shot. This is useful if the client code does not want the
printer to make pause during printing
"""
printable_image = reduce(lambda x, y: x.append(y), list(printable_images))
self.print_image(printable_image)
|
def plotfft ( s , fmax , doplot = False ) : fs = abs ( numpy . fft . fft ( s ) ) f = numpy . linspace ( 0 , fmax / 2 , len ( s ) / 2 ) if doplot : plot ( list ( f [ 1 : int ( len ( s ) / 2 ) ] ) , list ( fs [ 1 : int ( len ( s ) / 2 ) ] ) ) return f [ 1 : int ( len ( s ) / 2 ) ] . copy ( ) , fs [ 1 : int ( len ( s ) / 2 ) ] . copy ( )
| 0 |
python plot fft of signal
|
----- Brief ----- This functions computes the Fast Fourier Transform of a signal returning the frequency and magnitude values .
|
cosqa-train-15872
|
def plotfft(s, fmax, doplot=False):
"""
-----
Brief
-----
This functions computes the Fast Fourier Transform of a signal, returning the frequency and magnitude values.
-----------
Description
-----------
Fast Fourier Transform (FFT) is a method to computationally calculate the Fourier Transform of discrete finite
signals. This transform converts the time domain signal into a frequency domain signal by abdicating the temporal
dimension.
This function computes the FFT of the input signal and returns the frequency and respective amplitude values.
----------
Parameters
----------
s: array-like
the input signal.
fmax: int
the sampling frequency.
doplot: boolean
a variable to indicate whether the plot is done or not.
Returns
-------
f: array-like
the frequency values (xx axis)
fs: array-like
the amplitude of the frequency values (yy axis)
"""
fs = abs(numpy.fft.fft(s))
f = numpy.linspace(0, fmax / 2, len(s) / 2)
if doplot:
plot(list(f[1:int(len(s) / 2)]), list(fs[1:int(len(s) / 2)]))
return f[1:int(len(s) / 2)].copy(), fs[1:int(len(s) / 2)].copy()
|
def get_unique_indices ( df , axis = 1 ) : return dict ( zip ( df . columns . names , dif . columns . levels ) )
| 1 |
how to display unique rows in python data frame
|
cosqa-train-15873
|
def get_unique_indices(df, axis=1):
"""
:param df:
:param axis:
:return:
"""
return dict(zip(df.columns.names, dif.columns.levels))
|
|
def multi_pop ( d , * args ) : retval = { } for key in args : if key in d : retval [ key ] = d . pop ( key ) return retval
| 1 |
python pop dictionary iteration
|
pops multiple keys off a dict like object
|
cosqa-train-15874
|
def multi_pop(d, *args):
""" pops multiple keys off a dict like object """
retval = {}
for key in args:
if key in d:
retval[key] = d.pop(key)
return retval
|
def computeFactorial ( n ) : sleep_walk ( 10 ) ret = 1 for i in range ( n ) : ret = ret * ( i + 1 ) return ret
| 0 |
how to do factorials using 4 loops in python
|
computes factorial of n
|
cosqa-train-15875
|
def computeFactorial(n):
"""
computes factorial of n
"""
sleep_walk(10)
ret = 1
for i in range(n):
ret = ret * (i + 1)
return ret
|
def auth_request ( self , url , headers , body ) : return self . req . post ( url , headers , body = body )
| 1 |
python post auth token requests
|
Perform auth request for token .
|
cosqa-train-15876
|
def auth_request(self, url, headers, body):
"""Perform auth request for token."""
return self.req.post(url, headers, body=body)
|
def _comment ( string ) : lines = [ line . strip ( ) for line in string . splitlines ( ) ] return "# " + ( "%s# " % linesep ) . join ( lines )
| 0 |
how to do multiline comments in python
|
return string as a comment
|
cosqa-train-15877
|
def _comment(string):
"""return string as a comment"""
lines = [line.strip() for line in string.splitlines()]
return "# " + ("%s# " % linesep).join(lines)
|
def psql ( sql , show = True ) : out = postgres ( 'psql -c "%s"' % sql ) if show : print_command ( sql ) return out
| 0 |
python postgres print query results
|
Runs SQL against the project s database .
|
cosqa-train-15878
|
def psql(sql, show=True):
"""
Runs SQL against the project's database.
"""
out = postgres('psql -c "%s"' % sql)
if show:
print_command(sql)
return out
|
def download_url ( url , filename , headers ) : ensure_dirs ( filename ) response = requests . get ( url , headers = headers , stream = True ) if response . status_code == 200 : with open ( filename , 'wb' ) as f : for chunk in response . iter_content ( 16 * 1024 ) : f . write ( chunk )
| 0 |
how to download a file with python requests
|
Download a file from url to filename .
|
cosqa-train-15879
|
def download_url(url, filename, headers):
"""Download a file from `url` to `filename`."""
ensure_dirs(filename)
response = requests.get(url, headers=headers, stream=True)
if response.status_code == 200:
with open(filename, 'wb') as f:
for chunk in response.iter_content(16 * 1024):
f.write(chunk)
|
def dictfetchall ( cursor ) : desc = cursor . description return [ dict ( zip ( [ col [ 0 ] for col in desc ] , row ) ) for row in cursor . fetchall ( ) ]
| 0 |
python postgres query result as dictionary
|
Returns all rows from a cursor as a dict ( rather than a headerless table )
|
cosqa-train-15880
|
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 vline ( self , x , y , height , color ) : self . rect ( x , y , 1 , height , color , fill = True )
| 1 |
how to draw a vertcile line in python on a graph
|
Draw a vertical line up to a given length .
|
cosqa-train-15881
|
def vline(self, x, y, height, color):
"""Draw a vertical line up to a given length."""
self.rect(x, y, 1, height, color, fill=True)
|
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 |
python pre exit handle
|
r A function to support exiting from exit hooks .
|
cosqa-train-15882
|
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 destroy ( self ) : with self . _db_conn ( ) as conn : for table_name in self . _tables : conn . execute ( 'DROP TABLE IF EXISTS %s' % table_name ) return self
| 0 |
how to drop a table in python
|
Destroy the SQLStepQueue tables in the database
|
cosqa-train-15883
|
def destroy(self):
""" Destroy the SQLStepQueue tables in the database """
with self._db_conn() as conn:
for table_name in self._tables:
conn.execute('DROP TABLE IF EXISTS %s' % table_name)
return self
|
def _do_auto_predict ( machine , X , * args ) : if auto_predict and hasattr ( machine , "predict" ) : return machine . predict ( X )
| 0 |
python predict method is returning a list while only one number is given as input
|
Performs an automatic prediction for the specified machine and returns the predicted values .
|
cosqa-train-15884
|
def _do_auto_predict(machine, X, *args):
"""Performs an automatic prediction for the specified machine and returns
the predicted values.
"""
if auto_predict and hasattr(machine, "predict"):
return machine.predict(X)
|
def has_edit_permission ( self , request ) : return request . user . is_authenticated and request . user . is_active and request . user . is_staff
| 0 |
how to elevate permissions in python
|
Can edit this object
|
cosqa-train-15885
|
def has_edit_permission(self, request):
""" Can edit this object """
return request.user.is_authenticated and request.user.is_active and request.user.is_staff
|
def pretty_dict_str ( d , indent = 2 ) : b = StringIO ( ) write_pretty_dict_str ( b , d , indent = indent ) return b . getvalue ( )
| 0 |
python pretty json string
|
shows JSON indented representation of d
|
cosqa-train-15886
|
def pretty_dict_str(d, indent=2):
"""shows JSON indented representation of d"""
b = StringIO()
write_pretty_dict_str(b, d, indent=indent)
return b.getvalue()
|
def unpunctuate ( s , * , char_blacklist = string . punctuation ) : # remove punctuation s = "" . join ( c for c in s if c not in char_blacklist ) # remove consecutive spaces return " " . join ( filter ( None , s . split ( " " ) ) )
| 1 |
how to eliminate white spaces in strings in python
|
Remove punctuation from string s .
|
cosqa-train-15887
|
def unpunctuate(s, *, char_blacklist=string.punctuation):
""" Remove punctuation from string s. """
# remove punctuation
s = "".join(c for c in s if c not in char_blacklist)
# remove consecutive spaces
return " ".join(filter(None, s.split(" ")))
|
def _get_pretty_string ( obj ) : sio = StringIO ( ) pprint . pprint ( obj , stream = sio ) return sio . getvalue ( )
| 0 |
python prettyprint custom objects
|
Return a prettier version of obj
|
cosqa-train-15888
|
def _get_pretty_string(obj):
"""Return a prettier version of obj
Parameters
----------
obj : object
Object to pretty print
Returns
-------
s : str
Pretty print object repr
"""
sio = StringIO()
pprint.pprint(obj, stream=sio)
return sio.getvalue()
|
def do_forceescape ( value ) : if hasattr ( value , '__html__' ) : value = value . __html__ ( ) return escape ( text_type ( value ) )
| 1 |
how to encode html into python
|
Enforce HTML escaping . This will probably double escape variables .
|
cosqa-train-15889
|
def do_forceescape(value):
"""Enforce HTML escaping. This will probably double escape variables."""
if hasattr(value, '__html__'):
value = value.__html__()
return escape(text_type(value))
|
def get_previous ( self ) : return BillingCycle . objects . filter ( date_range__lt = self . date_range ) . order_by ( 'date_range' ) . last ( )
| 1 |
python previous date from row above
|
Get the billing cycle prior to this one . May return None
|
cosqa-train-15890
|
def get_previous(self):
"""Get the billing cycle prior to this one. May return None"""
return BillingCycle.objects.filter(date_range__lt=self.date_range).order_by('date_range').last()
|
def go_to_new_line ( self ) : self . stdkey_end ( False , False ) self . insert_text ( self . get_line_separator ( ) )
| 1 |
how to enter a new line into python
|
Go to the end of the current line and create a new line
|
cosqa-train-15891
|
def go_to_new_line(self):
"""Go to the end of the current line and create a new line"""
self.stdkey_end(False, False)
self.insert_text(self.get_line_separator())
|
def _get_pretty_string ( obj ) : sio = StringIO ( ) pprint . pprint ( obj , stream = sio ) return sio . getvalue ( )
| 0 |
python print fields in a object
|
Return a prettier version of obj
|
cosqa-train-15892
|
def _get_pretty_string(obj):
"""Return a prettier version of obj
Parameters
----------
obj : object
Object to pretty print
Returns
-------
s : str
Pretty print object repr
"""
sio = StringIO()
pprint.pprint(obj, stream=sio)
return sio.getvalue()
|
def go_to_new_line ( self ) : self . stdkey_end ( False , False ) self . insert_text ( self . get_line_separator ( ) )
| 1 |
how to enter to a new line in python
|
Go to the end of the current line and create a new line
|
cosqa-train-15893
|
def go_to_new_line(self):
"""Go to the end of the current line and create a new line"""
self.stdkey_end(False, False)
self.insert_text(self.get_line_separator())
|
def imp_print ( self , text , end ) : sys . stdout . write ( ( text + end ) . encode ( "utf-8" ) )
| 0 |
python print from character to end of line
|
Directly send utf8 bytes to stdout
|
cosqa-train-15894
|
def imp_print(self, text, end):
"""Directly send utf8 bytes to stdout"""
sys.stdout.write((text + end).encode("utf-8"))
|
def All ( sequence ) : return bool ( reduce ( lambda x , y : x and y , sequence , True ) )
| 0 |
how to evaluate list of booleans python
|
: param sequence : Any sequence whose elements can be evaluated as booleans . : returns : true if all elements of the sequence satisfy True and x .
|
cosqa-train-15895
|
def All(sequence):
"""
:param sequence: Any sequence whose elements can be evaluated as booleans.
:returns: true if all elements of the sequence satisfy True and x.
"""
return bool(reduce(lambda x, y: x and y, sequence, True))
|
def _get_printable_columns ( columns , row ) : if not columns : return row # Extract the column values, in the order specified. return tuple ( row [ c ] for c in columns )
| 0 |
python print function column limit
|
Return only the part of the row which should be printed .
|
cosqa-train-15896
|
def _get_printable_columns(columns, row):
"""Return only the part of the row which should be printed.
"""
if not columns:
return row
# Extract the column values, in the order specified.
return tuple(row[c] for c in columns)
|
def _remove_from_index ( index , obj ) : try : index . value_map [ indexed_value ( index , obj ) ] . remove ( obj . id ) except KeyError : pass
| 1 |
how to exclude item from index python
|
Removes object obj from the index .
|
cosqa-train-15897
|
def _remove_from_index(index, obj):
"""Removes object ``obj`` from the ``index``."""
try:
index.value_map[indexed_value(index, obj)].remove(obj.id)
except KeyError:
pass
|
def print ( * a ) : try : _print ( * a ) return a [ 0 ] if len ( a ) == 1 else a except : _print ( * a )
| 0 |
python print only one return value from function
|
print just one that returns what you give it instead of None
|
cosqa-train-15898
|
def print(*a):
""" print just one that returns what you give it instead of None """
try:
_print(*a)
return a[0] if len(a) == 1 else a
except:
_print(*a)
|
def _quit ( self , * args ) : self . logger . warn ( 'Bye!' ) sys . exit ( self . exit ( ) )
| 0 |
how to exit the logger in python
|
quit crash
|
cosqa-train-15899
|
def _quit(self, *args):
""" quit crash """
self.logger.warn('Bye!')
sys.exit(self.exit())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.