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 toBase64 ( s ) : if isinstance ( s , str ) : s = s . encode ( "utf-8" ) return binascii . b2a_base64 ( s ) [ : - 1 ]
| 0 |
only python base64 has leading b
|
Represent string / bytes s as base64 omitting newlines
|
cosqa-train-16600
|
def toBase64(s):
"""Represent string / bytes s as base64, omitting newlines"""
if isinstance(s, str):
s = s.encode("utf-8")
return binascii.b2a_base64(s)[:-1]
|
def downsample_with_striding ( array , factor ) : return array [ tuple ( np . s_ [ : : f ] for f in factor ) ]
| 0 |
resampling an array in python
|
Downsample x by factor using striding .
|
cosqa-train-16601
|
def downsample_with_striding(array, factor):
"""Downsample x by factor using striding.
@return: The downsampled array, of the same type as x.
"""
return array[tuple(np.s_[::f] for f in factor)]
|
def energy_string_to_float ( string ) : energy_re = re . compile ( "(-?\d+\.\d+)" ) return float ( energy_re . match ( string ) . group ( 0 ) )
| 1 |
onvert string to float in python
|
Convert a string of a calculation energy e . g . - 1 . 2345 eV to a float .
|
cosqa-train-16602
|
def energy_string_to_float( string ):
"""
Convert a string of a calculation energy, e.g. '-1.2345 eV' to a float.
Args:
string (str): The string to convert.
Return
(float)
"""
energy_re = re.compile( "(-?\d+\.\d+)" )
return float( energy_re.match( string ).group(0) )
|
def shape_list ( l , shape , dtype ) : return np . array ( l , dtype = dtype ) . reshape ( shape )
| 1 |
reshape a list as an array in python
|
Shape a list of lists into the appropriate shape and data type
|
cosqa-train-16603
|
def shape_list(l,shape,dtype):
""" Shape a list of lists into the appropriate shape and data type """
return np.array(l, dtype=dtype).reshape(shape)
|
def utime ( self , * args , * * kwargs ) : os . utime ( self . extended_path , * args , * * kwargs )
| 0 |
open a file in python based on modified date
|
Set the access and modified times of the file specified by path .
|
cosqa-train-16604
|
def utime(self, *args, **kwargs):
""" Set the access and modified times of the file specified by path. """
os.utime(self.extended_path, *args, **kwargs)
|
def batchify ( data , batch_size ) : nbatch = data . shape [ 0 ] // batch_size data = data [ : nbatch * batch_size ] data = data . reshape ( ( batch_size , nbatch ) ) . T return data
| 1 |
reshape array from 4 to 2 dimensions in n\python
|
Reshape data into ( num_example batch_size )
|
cosqa-train-16605
|
def batchify(data, batch_size):
"""Reshape data into (num_example, batch_size)"""
nbatch = data.shape[0] // batch_size
data = data[:nbatch * batch_size]
data = data.reshape((batch_size, nbatch)).T
return data
|
def unpickle_file ( picklefile , * * kwargs ) : with open ( picklefile , 'rb' ) as f : return pickle . load ( f , * * kwargs )
| 0 |
open a pickled file in python
|
Helper function to unpickle data from picklefile .
|
cosqa-train-16606
|
def unpickle_file(picklefile, **kwargs):
"""Helper function to unpickle data from `picklefile`."""
with open(picklefile, 'rb') as f:
return pickle.load(f, **kwargs)
|
def batchify ( data , batch_size ) : nbatch = data . shape [ 0 ] // batch_size data = data [ : nbatch * batch_size ] data = data . reshape ( ( batch_size , nbatch ) ) . T return data
| 0 |
reshape in python 3 dimenssionto 2 example
|
Reshape data into ( num_example batch_size )
|
cosqa-train-16607
|
def batchify(data, batch_size):
"""Reshape data into (num_example, batch_size)"""
nbatch = data.shape[0] // batch_size
data = data[:nbatch * batch_size]
data = data.reshape((batch_size, nbatch)).T
return data
|
def open_file ( file , mode ) : if hasattr ( file , "read" ) : return file if hasattr ( file , "open" ) : return file . open ( mode ) return open ( file , mode )
| 1 |
open an file for read or write python open
|
Open a file .
|
cosqa-train-16608
|
def open_file(file, mode):
"""Open a file.
:arg file: file-like or path-like object.
:arg str mode: ``mode`` argument for :func:`open`.
"""
if hasattr(file, "read"):
return file
if hasattr(file, "open"):
return file.open(mode)
return open(file, mode)
|
def render_none ( self , context , result ) : context . response . body = b'' del context . response . content_length return True
| 1 |
response object pythong content incomplete
|
Render empty responses .
|
cosqa-train-16609
|
def render_none(self, context, result):
"""Render empty responses."""
context.response.body = b''
del context.response.content_length
return True
|
def getfirstline ( file , default ) : with open ( file , 'rb' ) as fh : content = fh . readlines ( ) if len ( content ) == 1 : return content [ 0 ] . decode ( 'utf-8' ) . strip ( '\n' ) return default
| 1 |
open and read first line in a file python
|
Returns the first line of a file .
|
cosqa-train-16610
|
def getfirstline(file, default):
"""
Returns the first line of a file.
"""
with open(file, 'rb') as fh:
content = fh.readlines()
if len(content) == 1:
return content[0].decode('utf-8').strip('\n')
return default
|
def do_restart ( self , line ) : self . bot . _frame = 0 self . bot . _namespace . clear ( ) self . bot . _namespace . update ( self . bot . _initial_namespace )
| 0 |
restart discord bot with command python
|
Attempt to restart the bot .
|
cosqa-train-16611
|
def do_restart(self, line):
"""
Attempt to restart the bot.
"""
self.bot._frame = 0
self.bot._namespace.clear()
self.bot._namespace.update(self.bot._initial_namespace)
|
def execfile ( fname , variables ) : with open ( fname ) as f : code = compile ( f . read ( ) , fname , 'exec' ) exec ( code , variables )
| 1 |
open compiled python file
|
This is builtin in python2 but we have to roll our own on py3 .
|
cosqa-train-16612
|
def execfile(fname, variables):
""" This is builtin in python2, but we have to roll our own on py3. """
with open(fname) as f:
code = compile(f.read(), fname, 'exec')
exec(code, variables)
|
def extract_module_locals ( depth = 0 ) : f = sys . _getframe ( depth + 1 ) global_ns = f . f_globals module = sys . modules [ global_ns [ '__name__' ] ] return ( module , f . f_locals )
| 0 |
retrieve global variables from function python
|
Returns ( module locals ) of the funciton depth frames away from the caller
|
cosqa-train-16613
|
def extract_module_locals(depth=0):
"""Returns (module, locals) of the funciton `depth` frames away from the caller"""
f = sys._getframe(depth + 1)
global_ns = f.f_globals
module = sys.modules[global_ns['__name__']]
return (module, f.f_locals)
|
def read ( * args ) : return io . open ( os . path . join ( HERE , * args ) , encoding = "utf-8" ) . read ( )
| 1 |
open files in python without decoding
|
Reads complete file contents .
|
cosqa-train-16614
|
def read(*args):
"""Reads complete file contents."""
return io.open(os.path.join(HERE, *args), encoding="utf-8").read()
|
def get_class_method ( cls_or_inst , method_name ) : cls = cls_or_inst if isinstance ( cls_or_inst , type ) else cls_or_inst . __class__ meth = getattr ( cls , method_name , None ) if isinstance ( meth , property ) : meth = meth . fget elif isinstance ( meth , cached_property ) : meth = meth . func return meth
| 1 |
return a method from a method python
|
Returns a method from a given class or instance . When the method doest not exist it returns None . Also works with properties and cached properties .
|
cosqa-train-16615
|
def get_class_method(cls_or_inst, method_name):
"""
Returns a method from a given class or instance. When the method doest not exist, it returns `None`. Also works with
properties and cached properties.
"""
cls = cls_or_inst if isinstance(cls_or_inst, type) else cls_or_inst.__class__
meth = getattr(cls, method_name, None)
if isinstance(meth, property):
meth = meth.fget
elif isinstance(meth, cached_property):
meth = meth.func
return meth
|
def imdecode ( image_path ) : import os assert os . path . exists ( image_path ) , image_path + ' not found' im = cv2 . imread ( image_path ) return im
| 0 |
opencv python image not found
|
Return BGR image read by opencv
|
cosqa-train-16616
|
def imdecode(image_path):
"""Return BGR image read by opencv"""
import os
assert os.path.exists(image_path), image_path + ' not found'
im = cv2.imread(image_path)
return im
|
def items ( self ) : return [ ( value_descriptor . name , value_descriptor . number ) for value_descriptor in self . _enum_type . values ]
| 1 |
return all values in python enum in tuple
|
Return a list of the ( name value ) pairs of the enum .
|
cosqa-train-16617
|
def items(self):
"""Return a list of the (name, value) pairs of the enum.
These are returned in the order they were defined in the .proto file.
"""
return [(value_descriptor.name, value_descriptor.number)
for value_descriptor in self._enum_type.values]
|
def _openpyxl_read_xl ( xl_path : str ) : try : wb = load_workbook ( filename = xl_path , read_only = True ) except : raise else : return wb
| 1 |
opening blank workbook using python openpyxl
|
Use openpyxl to read an Excel file .
|
cosqa-train-16618
|
def _openpyxl_read_xl(xl_path: str):
""" Use openpyxl to read an Excel file. """
try:
wb = load_workbook(filename=xl_path, read_only=True)
except:
raise
else:
return wb
|
def get_column_keys_and_names ( table ) : ins = inspect ( table ) return ( ( k , c . name ) for k , c in ins . mapper . c . items ( ) )
| 0 |
return columns names python
|
Return a generator of tuples k c such that k is the name of the python attribute for the column and c is the name of the column in the sql table .
|
cosqa-train-16619
|
def get_column_keys_and_names(table):
"""
Return a generator of tuples k, c such that k is the name of the python attribute for
the column and c is the name of the column in the sql table.
"""
ins = inspect(table)
return ((k, c.name) for k, c in ins.mapper.c.items())
|
def naturalsortkey ( s ) : return [ int ( part ) if part . isdigit ( ) else part for part in re . split ( '([0-9]+)' , s ) ]
| 0 |
order a number in a string python
|
Natural sort order
|
cosqa-train-16620
|
def naturalsortkey(s):
"""Natural sort order"""
return [int(part) if part.isdigit() else part
for part in re.split('([0-9]+)', s)]
|
def get_X0 ( X ) : if pandas_available and isinstance ( X , pd . DataFrame ) : assert len ( X ) == 1 x = np . array ( X . iloc [ 0 ] ) else : x , = X return x
| 0 |
return only the first column of an array python
|
Return zero - th element of a one - element data container .
|
cosqa-train-16621
|
def get_X0(X):
""" Return zero-th element of a one-element data container.
"""
if pandas_available and isinstance(X, pd.DataFrame):
assert len(X) == 1
x = np.array(X.iloc[0])
else:
x, = X
return x
|
def project ( self , other ) : n = other . normalized ( ) return self . dot ( n ) * n
| 0 |
orthonormalize 1 vector corresponding to another python
|
Return one vector projected on the vector other
|
cosqa-train-16622
|
def project(self, other):
"""Return one vector projected on the vector other"""
n = other.normalized()
return self.dot(n) * n
|
def preprocess ( string ) : string = unicode ( string , encoding = "utf-8" ) # convert diacritics to simpler forms string = regex1 . sub ( lambda x : accents [ x . group ( ) ] , string ) # remove all rest of the unwanted characters return regex2 . sub ( '' , string ) . encode ( 'utf-8' )
| 0 |
return the string after removing all alphabets python
|
Preprocess string to transform all diacritics and remove other special characters than appropriate : param string : : return :
|
cosqa-train-16623
|
def preprocess(string):
"""
Preprocess string to transform all diacritics and remove other special characters than appropriate
:param string:
:return:
"""
string = unicode(string, encoding="utf-8")
# convert diacritics to simpler forms
string = regex1.sub(lambda x: accents[x.group()], string)
# remove all rest of the unwanted characters
return regex2.sub('', string).encode('utf-8')
|
def timestamp ( format = DATEFMT , timezone = 'Africa/Johannesburg' ) : return formatdate ( datetime . now ( tz = pytz . timezone ( timezone ) ) )
| 0 |
output current timezone python
|
Return current datetime with timezone applied [ all timezones ] print sorted ( pytz . all_timezones )
|
cosqa-train-16624
|
def timestamp(format=DATEFMT, timezone='Africa/Johannesburg'):
""" Return current datetime with timezone applied
[all timezones] print sorted(pytz.all_timezones) """
return formatdate(datetime.now(tz=pytz.timezone(timezone)))
|
def _try_lookup ( table , value , default = "" ) : try : string = table [ value ] except KeyError : string = default return string
| 0 |
returning a value from a python try function
|
try to get a string from the lookup table return instead of key error
|
cosqa-train-16625
|
def _try_lookup(table, value, default = ""):
""" try to get a string from the lookup table, return "" instead of key
error
"""
try:
string = table[ value ]
except KeyError:
string = default
return string
|
def write_pid_file ( ) : pidfile = os . path . basename ( sys . argv [ 0 ] ) [ : - 3 ] + '.pid' # strip .py, add .pid with open ( pidfile , 'w' ) as fh : fh . write ( "%d\n" % os . getpid ( ) ) fh . close ( )
| 0 |
outputting pid to file linux python
|
Write a file with the PID of this server instance .
|
cosqa-train-16626
|
def write_pid_file():
"""Write a file with the PID of this server instance.
Call when setting up a command line testserver.
"""
pidfile = os.path.basename(sys.argv[0])[:-3] + '.pid' # strip .py, add .pid
with open(pidfile, 'w') as fh:
fh.write("%d\n" % os.getpid())
fh.close()
|
def inverse ( d ) : output = { } for k , v in unwrap ( d ) . items ( ) : output [ v ] = output . get ( v , [ ] ) output [ v ] . append ( k ) return output
| 0 |
reverse the dictionary in python
|
reverse the k : v pairs
|
cosqa-train-16627
|
def inverse(d):
"""
reverse the k:v pairs
"""
output = {}
for k, v in unwrap(d).items():
output[v] = output.get(v, [])
output[v].append(k)
return output
|
def region_from_segment ( image , segment ) : x , y , w , h = segment return image [ y : y + h , x : x + w ]
| 0 |
overlay segmentation onto image linux python
|
given a segment ( rectangle ) and an image returns it s corresponding subimage
|
cosqa-train-16628
|
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 _round_half_hour ( record ) : k = record . datetime + timedelta ( minutes = - ( record . datetime . minute % 30 ) ) return datetime ( k . year , k . month , k . day , k . hour , k . minute , 0 )
| 0 |
round a date to the nearest hour python
|
Round a time DOWN to half nearest half - hour .
|
cosqa-train-16629
|
def _round_half_hour(record):
"""
Round a time DOWN to half nearest half-hour.
"""
k = record.datetime + timedelta(minutes=-(record.datetime.minute % 30))
return datetime(k.year, k.month, k.day, k.hour, k.minute, 0)
|
def unpack2D ( _x ) : _x = np . atleast_2d ( _x ) x = _x [ : , 0 ] y = _x [ : , 1 ] return x , y
| 0 |
ow to make x and y in same dimension in python
|
Helper function for splitting 2D data into x and y component to make equations simpler
|
cosqa-train-16630
|
def unpack2D(_x):
"""
Helper function for splitting 2D data into x and y component to make
equations simpler
"""
_x = np.atleast_2d(_x)
x = _x[:, 0]
y = _x[:, 1]
return x, y
|
def __round_time ( self , dt ) : round_to = self . _resolution . total_seconds ( ) seconds = ( dt - dt . min ) . seconds rounding = ( seconds + round_to / 2 ) // round_to * round_to return dt + timedelta ( 0 , rounding - seconds , - dt . microsecond )
| 0 |
round to nearest minute timestamp python
|
Round a datetime object to a multiple of a timedelta dt : datetime . datetime object default now .
|
cosqa-train-16631
|
def __round_time(self, dt):
"""Round a datetime object to a multiple of a timedelta
dt : datetime.datetime object, default now.
"""
round_to = self._resolution.total_seconds()
seconds = (dt - dt.min).seconds
rounding = (seconds + round_to / 2) // round_to * round_to
return dt + timedelta(0, rounding - seconds, -dt.microsecond)
|
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
| 0 |
pad image to bounding box python
|
Crops and / or pads an image to a target width and height .
|
cosqa-train-16632
|
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 py3round ( number ) : if abs ( round ( number ) - number ) == 0.5 : return int ( 2.0 * round ( number / 2.0 ) ) return int ( round ( number ) )
| 1 |
round up float to two decimal places in python 3
|
Unified rounding in all python versions .
|
cosqa-train-16633
|
def py3round(number):
"""Unified rounding in all python versions."""
if abs(round(number) - number) == 0.5:
return int(2.0 * round(number / 2.0))
return int(round(number))
|
def _parse ( self , date_str , format = '%Y-%m-%d' ) : rv = pd . to_datetime ( date_str , format = format ) if hasattr ( rv , 'to_pydatetime' ) : rv = rv . to_pydatetime ( ) return rv
| 0 |
panda python parse datetime
|
helper function for parsing FRED date string into datetime
|
cosqa-train-16634
|
def _parse(self, date_str, format='%Y-%m-%d'):
"""
helper function for parsing FRED date string into datetime
"""
rv = pd.to_datetime(date_str, format=format)
if hasattr(rv, 'to_pydatetime'):
rv = rv.to_pydatetime()
return rv
|
def home ( ) : return dict ( links = dict ( api = '{}{}' . format ( request . url , PREFIX [ 1 : ] ) ) ) , HTTPStatus . OK
| 0 |
route has get and post just return postpython service
|
Temporary helper function to link to the API routes
|
cosqa-train-16635
|
def home():
"""Temporary helper function to link to the API routes"""
return dict(links=dict(api='{}{}'.format(request.url, PREFIX[1:]))), \
HTTPStatus.OK
|
def parse_comments_for_file ( filename ) : return [ parse_comment ( strip_stars ( comment ) , next_line ) for comment , next_line in get_doc_comments ( read_file ( filename ) ) ]
| 0 |
parsing comments with python
|
Return a list of all parsed comments in a file . Mostly for testing & interactive use .
|
cosqa-train-16636
|
def parse_comments_for_file(filename):
"""
Return a list of all parsed comments in a file. Mostly for testing &
interactive use.
"""
return [parse_comment(strip_stars(comment), next_line)
for comment, next_line in get_doc_comments(read_file(filename))]
|
def is_valid_row ( cls , row ) : for k in row . keys ( ) : if row [ k ] is None : return False return True
| 1 |
row is not empty in python check
|
Indicates whether or not the given row contains valid data .
|
cosqa-train-16637
|
def is_valid_row(cls, row):
"""Indicates whether or not the given row contains valid data."""
for k in row.keys():
if row[k] is None:
return False
return True
|
def sub ( name , func , * * kwarg ) : sp = subparsers . add_parser ( name , * * kwarg ) sp . set_defaults ( func = func ) sp . arg = sp . add_argument return sp
| 1 |
pass defined parser object to subparser python
|
Add subparser
|
cosqa-train-16638
|
def sub(name, func,**kwarg):
""" Add subparser
"""
sp = subparsers.add_parser(name, **kwarg)
sp.set_defaults(func=func)
sp.arg = sp.add_argument
return sp
|
def web ( host , port ) : from . webserver . web import get_app get_app ( ) . run ( host = host , port = port )
| 0 |
running a webserver with python
|
Start web application
|
cosqa-train-16639
|
def web(host, port):
"""Start web application"""
from .webserver.web import get_app
get_app().run(host=host, port=port)
|
def as_float_array ( a ) : return np . asarray ( a , dtype = np . quaternion ) . view ( ( np . double , 4 ) )
| 0 |
pass isfinite result to array python
|
View the quaternion array as an array of floats
|
cosqa-train-16640
|
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 ( self ) : self . signal_init ( ) self . listen_init ( ) self . logger . info ( 'starting' ) self . loop . start ( )
| 0 |
running multiple event loops python
|
Run the event loop .
|
cosqa-train-16641
|
def run(self):
"""Run the event loop."""
self.signal_init()
self.listen_init()
self.logger.info('starting')
self.loop.start()
|
def dict_jsonp ( param ) : if not isinstance ( param , dict ) : param = dict ( param ) return jsonp ( param )
| 0 |
pass json paramater python
|
Convert the parameter into a dictionary before calling jsonp if it s not already one
|
cosqa-train-16642
|
def dict_jsonp(param):
"""Convert the parameter into a dictionary before calling jsonp, if it's not already one"""
if not isinstance(param, dict):
param = dict(param)
return jsonp(param)
|
def file_read ( filename ) : fobj = open ( filename , 'r' ) source = fobj . read ( ) fobj . close ( ) return source
| 0 |
safely open and close a file in python 3
|
Read a file and close it . Returns the file source .
|
cosqa-train-16643
|
def file_read(filename):
"""Read a file and close it. Returns the file source."""
fobj = open(filename,'r');
source = fobj.read();
fobj.close()
return source
|
def trigger ( self , target : str , trigger : str , parameters : Dict [ str , Any ] = { } ) : pass
| 0 |
pass paramters to a function that calls another function python
|
Calls the specified Trigger of another Area with the optionally given parameters .
|
cosqa-train-16644
|
def trigger(self, target: str, trigger: str, parameters: Dict[str, Any]={}):
"""Calls the specified Trigger of another Area with the optionally given parameters.
Args:
target: The name of the target Area.
trigger: The name of the Trigger.
parameters: The parameters of the function call.
"""
pass
|
def cat_acc ( y_true , y_pred ) : return np . mean ( y_true . argmax ( axis = 1 ) == y_pred . argmax ( axis = 1 ) )
| 0 |
same validation accuracy in python model
|
Categorical accuracy
|
cosqa-train-16645
|
def cat_acc(y_true, y_pred):
"""Categorical accuracy
"""
return np.mean(y_true.argmax(axis=1) == y_pred.argmax(axis=1))
|
def tanimoto_coefficient ( a , b ) : return sum ( map ( lambda ( x , y ) : float ( x ) * float ( y ) , zip ( a , b ) ) ) / sum ( [ - sum ( map ( lambda ( x , y ) : float ( x ) * float ( y ) , zip ( a , b ) ) ) , sum ( map ( lambda x : float ( x ) ** 2 , a ) ) , sum ( map ( lambda x : float ( x ) ** 2 , b ) ) ] )
| 0 |
pearsons cooefficient between 2 matricess in python
|
Measured similarity between two points in a multi - dimensional space .
|
cosqa-train-16646
|
def tanimoto_coefficient(a, b):
"""Measured similarity between two points in a multi-dimensional space.
Returns:
1.0 if the two points completely overlap,
0.0 if the two points are infinitely far apart.
"""
return sum(map(lambda (x,y): float(x)*float(y), zip(a,b))) / sum([
-sum(map(lambda (x,y): float(x)*float(y), zip(a,b))),
sum(map(lambda x: float(x)**2, a)),
sum(map(lambda x: float(x)**2, b))])
|
def flatten ( l , types = ( list , float ) ) : l = [ item if isinstance ( item , types ) else [ item ] for item in l ] return [ item for sublist in l for item in sublist ]
| 0 |
saticlly type python lists
|
Flat nested list of lists into a single list .
|
cosqa-train-16647
|
def flatten(l, types=(list, float)):
"""
Flat nested list of lists into a single list.
"""
l = [item if isinstance(item, types) else [item] for item in l]
return [item for sublist in l for item in sublist]
|
def dft ( blk , freqs , normalize = True ) : dft_data = ( sum ( xn * cexp ( - 1j * n * f ) for n , xn in enumerate ( blk ) ) for f in freqs ) if normalize : lblk = len ( blk ) return [ v / lblk for v in dft_data ] return list ( dft_data )
| 0 |
perform fft on data with python
|
Complex non - optimized Discrete Fourier Transform
|
cosqa-train-16648
|
def dft(blk, freqs, normalize=True):
"""
Complex non-optimized Discrete Fourier Transform
Finds the DFT for values in a given frequency list, in order, over the data
block seen as periodic.
Parameters
----------
blk :
An iterable with well-defined length. Don't use this function with Stream
objects!
freqs :
List of frequencies to find the DFT, in rad/sample. FFT implementations
like numpy.fft.ftt finds the coefficients for N frequencies equally
spaced as ``line(N, 0, 2 * pi, finish=False)`` for N frequencies.
normalize :
If True (default), the coefficient sums are divided by ``len(blk)``,
and the coefficient for the DC level (frequency equals to zero) is the
mean of the block. If False, that coefficient would be the sum of the
data in the block.
Returns
-------
A list of DFT values for each frequency, in the same order that they appear
in the freqs input.
Note
----
This isn't a FFT implementation, and performs :math:`O(M . N)` float
pointing operations, with :math:`M` and :math:`N` equals to the length of
the inputs. This function can find the DFT for any specific frequency, with
no need for zero padding or finding all frequencies in a linearly spaced
band grid with N frequency bins at once.
"""
dft_data = (sum(xn * cexp(-1j * n * f) for n, xn in enumerate(blk))
for f in freqs)
if normalize:
lblk = len(blk)
return [v / lblk for v in dft_data]
return list(dft_data)
|
def pickle_save ( thing , fname ) : pickle . dump ( thing , open ( fname , "wb" ) , pickle . HIGHEST_PROTOCOL ) return thing
| 0 |
save a pickle file for python 3 in python 2
|
save something to a pickle file
|
cosqa-train-16649
|
def pickle_save(thing,fname):
"""save something to a pickle file"""
pickle.dump(thing, open(fname,"wb"),pickle.HIGHEST_PROTOCOL)
return thing
|
def replace_list ( items , match , replacement ) : return [ replace ( item , match , replacement ) for item in items ]
| 0 |
perform string replace with string in list item python
|
Replaces occurrences of a match string in a given list of strings and returns a list of new strings . The match string can be a regex expression .
|
cosqa-train-16650
|
def replace_list(items, match, replacement):
"""Replaces occurrences of a match string in a given list of strings and returns
a list of new strings. The match string can be a regex expression.
Args:
items (list): the list of strings to modify.
match (str): the search expression.
replacement (str): the string to replace with.
"""
return [replace(item, match, replacement) for item in items]
|
def save ( self , fname ) : with open ( fname , 'wb' ) as f : json . dump ( self , f )
| 0 |
save json to file in python
|
Saves the dictionary in json format : param fname : file to save to
|
cosqa-train-16651
|
def save(self, fname):
""" Saves the dictionary in json format
:param fname: file to save to
"""
with open(fname, 'wb') as f:
json.dump(self, f)
|
def plot_decision_boundary ( model , X , y , step = 0.1 , figsize = ( 10 , 8 ) , alpha = 0.4 , size = 20 ) : x_min , x_max = X [ : , 0 ] . min ( ) - 1 , X [ : , 0 ] . max ( ) + 1 y_min , y_max = X [ : , 1 ] . min ( ) - 1 , X [ : , 1 ] . max ( ) + 1 xx , yy = np . meshgrid ( np . arange ( x_min , x_max , step ) , np . arange ( y_min , y_max , step ) ) f , ax = plt . subplots ( figsize = figsize ) Z = model . predict ( np . c_ [ xx . ravel ( ) , yy . ravel ( ) ] ) Z = Z . reshape ( xx . shape ) ax . contourf ( xx , yy , Z , alpha = alpha ) ax . scatter ( X [ : , 0 ] , X [ : , 1 ] , c = y , s = size , edgecolor = 'k' ) plt . show ( )
| 0 |
plot the decision boundary of a svm model in python
|
Plots the classification decision boundary of model on X with labels y . Using numpy and matplotlib .
|
cosqa-train-16652
|
def plot_decision_boundary(model, X, y, step=0.1, figsize=(10, 8), alpha=0.4, size=20):
"""Plots the classification decision boundary of `model` on `X` with labels `y`.
Using numpy and matplotlib.
"""
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, step),
np.arange(y_min, y_max, step))
f, ax = plt.subplots(figsize=figsize)
Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
ax.contourf(xx, yy, Z, alpha=alpha)
ax.scatter(X[:, 0], X[:, 1], c=y, s=size, edgecolor='k')
plt.show()
|
def plot_and_save ( self , * * kwargs ) : self . fig = pyplot . figure ( ) self . plot ( ) self . axes = pyplot . gca ( ) self . save_plot ( self . fig , self . axes , * * kwargs ) pyplot . close ( self . fig )
| 1 |
save plot in python without superimposing
|
Used when the plot method defined does not create a figure nor calls save_plot Then the plot method has to use self . fig
|
cosqa-train-16653
|
def plot_and_save(self, **kwargs):
"""Used when the plot method defined does not create a figure nor calls save_plot
Then the plot method has to use self.fig"""
self.fig = pyplot.figure()
self.plot()
self.axes = pyplot.gca()
self.save_plot(self.fig, self.axes, **kwargs)
pyplot.close(self.fig)
|
def __unixify ( self , s ) : return os . path . normpath ( s ) . replace ( os . sep , "/" )
| 0 |
posixpath to string python
|
stupid windows . converts the backslash to forwardslash for consistency
|
cosqa-train-16654
|
def __unixify(self, s):
""" stupid windows. converts the backslash to forwardslash for consistency """
return os.path.normpath(s).replace(os.sep, "/")
|
def to_dotfile ( G : nx . DiGraph , filename : str ) : A = to_agraph ( G ) A . write ( filename )
| 0 |
save python graph to a flder
|
Output a networkx graph to a DOT file .
|
cosqa-train-16655
|
def to_dotfile(G: nx.DiGraph, filename: str):
""" Output a networkx graph to a DOT file. """
A = to_agraph(G)
A.write(filename)
|
def _deserialize ( cls , key , value , fields ) : converter = cls . _get_converter_for_field ( key , None , fields ) return converter . deserialize ( value )
| 0 |
powershell json serialize deserialize python wcf datacontractjsonserializer
|
Marshal incoming data into Python objects .
|
cosqa-train-16656
|
def _deserialize(cls, key, value, fields):
""" Marshal incoming data into Python objects."""
converter = cls._get_converter_for_field(key, None, fields)
return converter.deserialize(value)
|
def generate_write_yaml_to_file ( file_name ) : def write_yaml ( config ) : with open ( file_name , 'w+' ) as fh : fh . write ( yaml . dump ( config ) ) return write_yaml
| 1 |
save yaml to file python
|
generate a method to write the configuration in yaml to the method desired
|
cosqa-train-16657
|
def generate_write_yaml_to_file(file_name):
""" generate a method to write the configuration in yaml to the method desired """
def write_yaml(config):
with open(file_name, 'w+') as fh:
fh.write(yaml.dump(config))
return write_yaml
|
def print_bintree ( tree , indent = ' ' ) : for n in sorted ( tree . keys ( ) ) : print "%s%s" % ( indent * depth ( n , tree ) , n )
| 0 |
print binary tree as it is in tree format python
|
print a binary tree
|
cosqa-train-16658
|
def print_bintree(tree, indent=' '):
"""print a binary tree"""
for n in sorted(tree.keys()):
print "%s%s" % (indent * depth(n,tree), n)
|
def zoom ( ax , xy = 'x' , factor = 1 ) : limits = ax . get_xlim ( ) if xy == 'x' else ax . get_ylim ( ) new_limits = ( 0.5 * ( limits [ 0 ] + limits [ 1 ] ) + 1. / factor * np . array ( ( - 0.5 , 0.5 ) ) * ( limits [ 1 ] - limits [ 0 ] ) ) if xy == 'x' : ax . set_xlim ( new_limits ) else : ax . set_ylim ( new_limits )
| 0 |
scaling your x axis to zoom in on a specific area python
|
Zoom into axis .
|
cosqa-train-16659
|
def zoom(ax, xy='x', factor=1):
"""Zoom into axis.
Parameters
----------
"""
limits = ax.get_xlim() if xy == 'x' else ax.get_ylim()
new_limits = (0.5*(limits[0] + limits[1])
+ 1./factor * np.array((-0.5, 0.5)) * (limits[1] - limits[0]))
if xy == 'x':
ax.set_xlim(new_limits)
else:
ax.set_ylim(new_limits)
|
def raw_print ( * args , * * kw ) : print ( * args , sep = kw . get ( 'sep' , ' ' ) , end = kw . get ( 'end' , '\n' ) , file = sys . __stdout__ ) sys . __stdout__ . flush ( )
| 0 |
print not displaying anything in python\
|
Raw print to sys . __stdout__ otherwise identical interface to print () .
|
cosqa-train-16660
|
def raw_print(*args, **kw):
"""Raw print to sys.__stdout__, otherwise identical interface to print()."""
print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
file=sys.__stdout__)
sys.__stdout__.flush()
|
def page_guiref ( arg_s = None ) : from IPython . core import page page . page ( gui_reference , auto_html = True )
| 0 |
scintillanet autocomplete and calltip for ironpython
|
Show a basic reference about the GUI Console .
|
cosqa-train-16661
|
def page_guiref(arg_s=None):
"""Show a basic reference about the GUI Console."""
from IPython.core import page
page.page(gui_reference, auto_html=True)
|
def pprint_for_ordereddict ( ) : od_saved = OrderedDict . __repr__ try : OrderedDict . __repr__ = dict . __repr__ yield finally : OrderedDict . __repr__ = od_saved
| 1 |
print ordered dict python
|
Context manager that causes pprint () to print OrderedDict objects as nicely as standard Python dictionary objects .
|
cosqa-train-16662
|
def pprint_for_ordereddict():
"""
Context manager that causes pprint() to print OrderedDict objects as nicely
as standard Python dictionary objects.
"""
od_saved = OrderedDict.__repr__
try:
OrderedDict.__repr__ = dict.__repr__
yield
finally:
OrderedDict.__repr__ = od_saved
|
def ex ( self , cmd ) : with self . builtin_trap : exec cmd in self . user_global_ns , self . user_ns
| 0 |
scope of embedded python function
|
Execute a normal python statement in user namespace .
|
cosqa-train-16663
|
def ex(self, cmd):
"""Execute a normal python statement in user namespace."""
with self.builtin_trap:
exec cmd in self.user_global_ns, self.user_ns
|
def geturl ( self ) : if self . retries is not None and len ( self . retries . history ) : return self . retries . history [ - 1 ] . redirect_location else : return self . _request_url
| 0 |
print original url before redirect python requests
|
Returns the URL that was the source of this response . If the request that generated this response redirected this method will return the final redirect location .
|
cosqa-train-16664
|
def geturl(self):
"""
Returns the URL that was the source of this response.
If the request that generated this response redirected, this method
will return the final redirect location.
"""
if self.retries is not None and len(self.retries.history):
return self.retries.history[-1].redirect_location
else:
return self._request_url
|
def _elapsed ( self ) : self . last_time = time . time ( ) return self . last_time - self . start
| 0 |
seconds ago minus current python
|
Returns elapsed time at update .
|
cosqa-train-16665
|
def _elapsed(self):
""" Returns elapsed time at update. """
self.last_time = time.time()
return self.last_time - self.start
|
def PythonPercentFormat ( format_str ) : if format_str . startswith ( 'printf ' ) : fmt = format_str [ len ( 'printf ' ) : ] return lambda value : fmt % value else : return None
| 0 |
print percent sign in format string python
|
Use Python % format strings as template format specifiers .
|
cosqa-train-16666
|
def PythonPercentFormat(format_str):
"""Use Python % format strings as template format specifiers."""
if format_str.startswith('printf '):
fmt = format_str[len('printf '):]
return lambda value: fmt % value
else:
return None
|
def rowlenselect ( table , n , complement = False ) : where = lambda row : len ( row ) == n return select ( table , where , complement = complement )
| 1 |
select a certain number of cells in python sql access database
|
Select rows of length n .
|
cosqa-train-16667
|
def rowlenselect(table, n, complement=False):
"""Select rows of length `n`."""
where = lambda row: len(row) == n
return select(table, where, complement=complement)
|
def _get_pretty_string ( obj ) : sio = StringIO ( ) pprint . pprint ( obj , stream = sio ) return sio . getvalue ( )
| 1 |
print the contents of an object in python
|
Return a prettier version of obj
|
cosqa-train-16668
|
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 _pick_attrs ( attrs , keys ) : return dict ( ( k , v ) for k , v in attrs . items ( ) if k in keys )
| 0 |
select a set of keys in a dictionary python
|
Return attrs with keys in keys list
|
cosqa-train-16669
|
def _pick_attrs(attrs, keys):
""" Return attrs with keys in keys list
"""
return dict((k, v) for k, v in attrs.items() if k in keys)
|
def _screen ( self , s , newline = False ) : if self . verbose : if newline : print ( s ) else : print ( s , end = ' ' )
| 0 |
printing without ( in python 3
|
Print something on screen when self . verbose == True
|
cosqa-train-16670
|
def _screen(self, s, newline=False):
"""Print something on screen when self.verbose == True"""
if self.verbose:
if newline:
print(s)
else:
print(s, end=' ')
|
def gen_text ( env : TextIOBase , package : str , tmpl : str ) : if env : env_args = json_datetime . load ( env ) else : env_args = { } jinja_env = template . setup ( package ) echo ( jinja_env . get_template ( tmpl ) . render ( * * env_args ) )
| 0 |
sending an email with python using jinja template
|
Create output from Jinja template .
|
cosqa-train-16671
|
def gen_text(env: TextIOBase, package: str, tmpl: str):
"""Create output from Jinja template."""
if env:
env_args = json_datetime.load(env)
else:
env_args = {}
jinja_env = template.setup(package)
echo(jinja_env.get_template(tmpl).render(**env_args))
|
def dot_v3 ( v , w ) : return sum ( [ x * y for x , y in zip ( v , w ) ] )
| 0 |
product of elements of a vector python
|
Return the dotproduct of two vectors .
|
cosqa-train-16672
|
def dot_v3(v, w):
"""Return the dotproduct of two vectors."""
return sum([x * y for x, y in zip(v, w)])
|
def _get_url ( url ) : try : data = HTTP_SESSION . get ( url , stream = True ) data . raise_for_status ( ) except requests . exceptions . RequestException as exc : raise FetcherException ( exc ) return data
| 0 |
session get requests not working python
|
Retrieve requested URL
|
cosqa-train-16673
|
def _get_url(url):
"""Retrieve requested URL"""
try:
data = HTTP_SESSION.get(url, stream=True)
data.raise_for_status()
except requests.exceptions.RequestException as exc:
raise FetcherException(exc)
return data
|
def image_set_aspect ( aspect = 1.0 , axes = "gca" ) : if axes is "gca" : axes = _pylab . gca ( ) e = axes . get_images ( ) [ 0 ] . get_extent ( ) axes . set_aspect ( abs ( ( e [ 1 ] - e [ 0 ] ) / ( e [ 3 ] - e [ 2 ] ) ) / aspect )
| 0 |
set aspect ratio of image python
|
sets the aspect ratio of the current zoom level of the imshow image
|
cosqa-train-16674
|
def image_set_aspect(aspect=1.0, axes="gca"):
"""
sets the aspect ratio of the current zoom level of the imshow image
"""
if axes is "gca": axes = _pylab.gca()
e = axes.get_images()[0].get_extent()
axes.set_aspect(abs((e[1]-e[0])/(e[3]-e[2]))/aspect)
|
def string_input ( prompt = '' ) : v = sys . version [ 0 ] if v == '3' : return input ( prompt ) else : return raw_input ( prompt )
| 1 |
prompt user input python3
|
Python 3 input () / Python 2 raw_input ()
|
cosqa-train-16675
|
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 b ( s ) : return s if isinstance ( s , bytes ) else s . encode ( locale . getpreferredencoding ( ) )
| 0 |
set default encode python
|
Encodes Unicode strings to byte strings if necessary .
|
cosqa-train-16676
|
def b(s):
""" Encodes Unicode strings to byte strings, if necessary. """
return s if isinstance(s, bytes) else s.encode(locale.getpreferredencoding())
|
def MessageToDict ( message , including_default_value_fields = False , preserving_proto_field_name = False ) : printer = _Printer ( including_default_value_fields , preserving_proto_field_name ) # pylint: disable=protected-access return printer . _MessageToJsonObject ( message )
| 1 |
protobuf python dictionary of dictionary
|
Converts protobuf message to a JSON dictionary .
|
cosqa-train-16677
|
def MessageToDict(message,
including_default_value_fields=False,
preserving_proto_field_name=False):
"""Converts protobuf message to a JSON dictionary.
Args:
message: The protocol buffers message instance to serialize.
including_default_value_fields: If True, singular primitive fields,
repeated fields, and map fields will always be serialized. If
False, only serialize non-empty fields. Singular message fields
and oneof fields are not affected by this option.
preserving_proto_field_name: If True, use the original proto field
names as defined in the .proto file. If False, convert the field
names to lowerCamelCase.
Returns:
A dict representation of the JSON formatted protocol buffer message.
"""
printer = _Printer(including_default_value_fields,
preserving_proto_field_name)
# pylint: disable=protected-access
return printer._MessageToJsonObject(message)
|
def setPixel ( self , x , y , color ) : return _fitz . Pixmap_setPixel ( self , x , y , color )
| 0 |
set pixels in a color in python
|
Set the pixel at ( x y ) to the integers in sequence color .
|
cosqa-train-16678
|
def setPixel(self, x, y, color):
"""Set the pixel at (x,y) to the integers in sequence 'color'."""
return _fitz.Pixmap_setPixel(self, x, y, color)
|
def _GetFieldByName ( message_descriptor , field_name ) : try : return message_descriptor . fields_by_name [ field_name ] except KeyError : raise ValueError ( 'Protocol message %s has no "%s" field.' % ( message_descriptor . name , field_name ) )
| 1 |
protobuf python get filed by name
|
Returns a field descriptor by field name .
|
cosqa-train-16679
|
def _GetFieldByName(message_descriptor, field_name):
"""Returns a field descriptor by field name.
Args:
message_descriptor: A Descriptor describing all fields in message.
field_name: The name of the field to retrieve.
Returns:
The field descriptor associated with the field name.
"""
try:
return message_descriptor.fields_by_name[field_name]
except KeyError:
raise ValueError('Protocol message %s has no "%s" field.' %
(message_descriptor.name, field_name))
|
def _prepare_proxy ( self , conn ) : conn . set_tunnel ( self . _proxy_host , self . port , self . proxy_headers ) conn . connect ( )
| 0 |
set proxy tunnel for urllib python
|
Establish tunnel connection early because otherwise httplib would improperly set Host : header to proxy s IP : port .
|
cosqa-train-16680
|
def _prepare_proxy(self, conn):
"""
Establish tunnel connection early, because otherwise httplib
would improperly set Host: header to proxy's IP:port.
"""
conn.set_tunnel(self._proxy_host, self.port, self.proxy_headers)
conn.connect()
|
def toJson ( protoObject , indent = None ) : # Using the internal method because this way we can reformat the JSON js = json_format . MessageToDict ( protoObject , False ) return json . dumps ( js , indent = indent )
| 0 |
protobuf python pass grpc dict
|
Serialises a protobuf object as json
|
cosqa-train-16681
|
def toJson(protoObject, indent=None):
"""
Serialises a protobuf object as json
"""
# Using the internal method because this way we can reformat the JSON
js = json_format.MessageToDict(protoObject, False)
return json.dumps(js, indent=indent)
|
def clear_matplotlib_ticks ( self , axis = "both" ) : ax = self . get_axes ( ) plotting . clear_matplotlib_ticks ( ax = ax , axis = axis )
| 0 |
set tickhow to keep one of axes empty python
|
Clears the default matplotlib ticks .
|
cosqa-train-16682
|
def clear_matplotlib_ticks(self, axis="both"):
"""Clears the default matplotlib ticks."""
ax = self.get_axes()
plotting.clear_matplotlib_ticks(ax=ax, axis=axis)
|
def newest_file ( file_iterable ) : return max ( file_iterable , key = lambda fname : os . path . getmtime ( fname ) )
| 0 |
pulling most recent file from directory python
|
Returns the name of the newest file given an iterable of file names .
|
cosqa-train-16683
|
def newest_file(file_iterable):
"""
Returns the name of the newest file given an iterable of file names.
"""
return max(file_iterable, key=lambda fname: os.path.getmtime(fname))
|
def update ( self , * * kwargs ) : for key , value in kwargs . items ( ) : setattr ( self , key , value )
| 0 |
setattr in python using kwargs
|
Creates or updates a property for the instance for each parameter .
|
cosqa-train-16684
|
def update(self, **kwargs):
"""Creates or updates a property for the instance for each parameter."""
for key, value in kwargs.items():
setattr(self, key, value)
|
def _add_hash ( source ) : source = '\n' . join ( '# ' + line . rstrip ( ) for line in source . splitlines ( ) ) return source
| 0 |
putting a hashtag on each line in python
|
Add a leading hash # at the beginning of every line in the source .
|
cosqa-train-16685
|
def _add_hash(source):
"""Add a leading hash '#' at the beginning of every line in the source."""
source = '\n'.join('# ' + line.rstrip()
for line in source.splitlines())
return source
|
def hline ( self , x , y , width , color ) : self . rect ( x , y , width , 1 , color , fill = True )
| 0 |
shaded rectangle in lines in python
|
Draw a horizontal line up to a given length .
|
cosqa-train-16686
|
def hline(self, x, y, width, color):
"""Draw a horizontal line up to a given length."""
self.rect(x, y, width, 1, color, fill=True)
|
def make_unique_ngrams ( s , n ) : return set ( s [ i : i + n ] for i in range ( len ( s ) - n + 1 ) )
| 1 |
putting a string into a set number of characters in python
|
Make a set of unique n - grams from a string .
|
cosqa-train-16687
|
def make_unique_ngrams(s, n):
"""Make a set of unique n-grams from a string."""
return set(s[i:i + n] for i in range(len(s) - n + 1))
|
def _repr ( obj ) : vals = ", " . join ( "{}={!r}" . format ( name , getattr ( obj , name ) ) for name in obj . _attribs ) if vals : t = "{}(name={}, {})" . format ( obj . __class__ . __name__ , obj . name , vals ) else : t = "{}(name={})" . format ( obj . __class__ . __name__ , obj . name ) return t
| 1 |
show attributes of python object
|
Show the received object as precise as possible .
|
cosqa-train-16688
|
def _repr(obj):
"""Show the received object as precise as possible."""
vals = ", ".join("{}={!r}".format(
name, getattr(obj, name)) for name in obj._attribs)
if vals:
t = "{}(name={}, {})".format(obj.__class__.__name__, obj.name, vals)
else:
t = "{}(name={})".format(obj.__class__.__name__, obj.name)
return t
|
def objectproxy_realaddress ( obj ) : voidp = QROOT . TPython . ObjectProxy_AsVoidPtr ( obj ) return C . addressof ( C . c_char . from_buffer ( voidp ) )
| 0 |
pybind11 get address of c++ object from python
|
Obtain a real address as an integer from an objectproxy .
|
cosqa-train-16689
|
def objectproxy_realaddress(obj):
"""
Obtain a real address as an integer from an objectproxy.
"""
voidp = QROOT.TPython.ObjectProxy_AsVoidPtr(obj)
return C.addressof(C.c_char.from_buffer(voidp))
|
def finish_plot ( ) : plt . legend ( ) plt . grid ( color = '0.7' ) plt . xlabel ( 'x' ) plt . ylabel ( 'y' ) plt . show ( )
| 0 |
show legend for matplotlib in python
|
Helper for plotting .
|
cosqa-train-16690
|
def finish_plot():
"""Helper for plotting."""
plt.legend()
plt.grid(color='0.7')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
|
def resources ( self ) : return [ self . pdf . getPage ( i ) for i in range ( self . pdf . getNumPages ( ) ) ]
| 0 |
pypdf2 reading all pdf pages python
|
Retrieve contents of each page of PDF
|
cosqa-train-16691
|
def resources(self):
"""Retrieve contents of each page of PDF"""
return [self.pdf.getPage(i) for i in range(self.pdf.getNumPages())]
|
def smallest_signed_angle ( source , target ) : dth = target - source dth = ( dth + np . pi ) % ( 2.0 * np . pi ) - np . pi return dth
| 0 |
signed angle between vectors python
|
Find the smallest angle going from angle source to angle target .
|
cosqa-train-16692
|
def smallest_signed_angle(source, target):
"""Find the smallest angle going from angle `source` to angle `target`."""
dth = target - source
dth = (dth + np.pi) % (2.0 * np.pi) - np.pi
return dth
|
def closeEvent ( self , event ) : if self . closing ( True ) : event . accept ( ) else : event . ignore ( )
| 1 |
pyside python close event
|
closeEvent reimplementation
|
cosqa-train-16693
|
def closeEvent(self, event):
"""closeEvent reimplementation"""
if self.closing(True):
event.accept()
else:
event.ignore()
|
def distance_to_line ( a , b , p ) : return distance ( closest_point ( a , b , p ) , p )
| 0 |
simplest way to calculate l2 distance between two points in python
|
Closest distance between a line segment and a point
|
cosqa-train-16694
|
def distance_to_line(a, b, p):
"""Closest distance between a line segment and a point
Args:
a ([float, float]): x and y coordinates. Line start
b ([float, float]): x and y coordinates. Line end
p ([float, float]): x and y coordinates. Point to compute the distance
Returns:
float
"""
return distance(closest_point(a, b, p), p)
|
def dump_json ( obj ) : return simplejson . dumps ( obj , ignore_nan = True , default = json_util . default )
| 0 |
python 'jsonify' is not defined
|
Dump Python object as JSON string .
|
cosqa-train-16695
|
def dump_json(obj):
"""Dump Python object as JSON string."""
return simplejson.dumps(obj, ignore_nan=True, default=json_util.default)
|
def sine_wave ( frequency ) : xs = tf . reshape ( tf . range ( _samples ( ) , dtype = tf . float32 ) , [ 1 , _samples ( ) , 1 ] ) ts = xs / FLAGS . sample_rate return tf . sin ( 2 * math . pi * frequency * ts )
| 0 |
sine wave with python
|
Emit a sine wave at the given frequency .
|
cosqa-train-16696
|
def sine_wave(frequency):
"""Emit a sine wave at the given frequency."""
xs = tf.reshape(tf.range(_samples(), dtype=tf.float32), [1, _samples(), 1])
ts = xs / FLAGS.sample_rate
return tf.sin(2 * math.pi * frequency * ts)
|
def string_input ( prompt = '' ) : v = sys . version [ 0 ] if v == '3' : return input ( prompt ) else : return raw_input ( prompt )
| 1 |
python 'prompt' is not defined
|
Python 3 input () / Python 2 raw_input ()
|
cosqa-train-16697
|
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 full_s ( self ) : x = np . zeros ( ( self . shape ) , dtype = np . float32 ) x [ : self . s . shape [ 0 ] , : self . s . shape [ 0 ] ] = self . s . as_2d s = Matrix ( x = x , row_names = self . row_names , col_names = self . col_names , isdiagonal = False , autoalign = False ) return s
| 1 |
singular matrixsingular matrix in python
|
Get the full singular value matrix of self
|
cosqa-train-16698
|
def full_s(self):
""" Get the full singular value matrix of self
Returns
-------
Matrix : Matrix
"""
x = np.zeros((self.shape),dtype=np.float32)
x[:self.s.shape[0],:self.s.shape[0]] = self.s.as_2d
s = Matrix(x=x, row_names=self.row_names,
col_names=self.col_names, isdiagonal=False,
autoalign=False)
return s
|
def bound_symbols ( self ) : try : lhs_syms = self . lhs . bound_symbols except AttributeError : lhs_syms = set ( ) try : rhs_syms = self . rhs . bound_symbols except AttributeError : rhs_syms = set ( ) return lhs_syms | rhs_syms
| 0 |
python 'symbol' object is not subscriptable
|
Set of bound SymPy symbols contained within the equation .
|
cosqa-train-16699
|
def bound_symbols(self):
"""Set of bound SymPy symbols contained within the equation."""
try:
lhs_syms = self.lhs.bound_symbols
except AttributeError:
lhs_syms = set()
try:
rhs_syms = self.rhs.bound_symbols
except AttributeError:
rhs_syms = set()
return lhs_syms | rhs_syms
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.