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 mean_date ( dt_list ) : dt_list_sort = sorted ( dt_list ) dt_list_sort_rel = [ dt - dt_list_sort [ 0 ] for dt in dt_list_sort ] avg_timedelta = sum ( dt_list_sort_rel , timedelta ( ) ) / len ( dt_list_sort_rel ) return dt_list_sort [ 0 ] + avg_timedelta | 0 | calculate average value over datetime python | Calcuate mean datetime from datetime list | cosqa-train-100 | def mean_date(dt_list):
"""Calcuate mean datetime from datetime list
"""
dt_list_sort = sorted(dt_list)
dt_list_sort_rel = [dt - dt_list_sort[0] for dt in dt_list_sort]
avg_timedelta = sum(dt_list_sort_rel, timedelta())/len(dt_list_sort_rel)
return dt_list_sort[0] + avg_timedelta |
def rotate_img ( im , deg , mode = cv2 . BORDER_CONSTANT , interpolation = cv2 . INTER_AREA ) : r , c , * _ = im . shape M = cv2 . getRotationMatrix2D ( ( c // 2 , r // 2 ) , deg , 1 ) return cv2 . warpAffine ( im , M , ( c , r ) , borderMode = mode , flags = cv2 . WARP_FILL_OUTLIERS + interpolation ) | 0 | python cv2 rotate image | Rotates an image by deg degrees | cosqa-train-101 | def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA):
""" Rotates an image by deg degrees
Arguments:
deg (float): degree to rotate.
"""
r,c,*_ = im.shape
M = cv2.getRotationMatrix2D((c//2,r//2),deg,1)
return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv2.WARP_FILL_OUTLIERS+interpolation) |
def similarity ( self , other ) : if self . magnitude == 0 or other . magnitude == 0 : return 0 return self . dot ( other ) / self . magnitude | 0 | calculate cosine similarity between two document vectors python | Calculates the cosine similarity between this vector and another vector . | cosqa-train-102 | def similarity(self, other):
"""Calculates the cosine similarity between this vector and another
vector."""
if self.magnitude == 0 or other.magnitude == 0:
return 0
return self.dot(other) / self.magnitude |
def rotate_img ( im , deg , mode = cv2 . BORDER_CONSTANT , interpolation = cv2 . INTER_AREA ) : r , c , * _ = im . shape M = cv2 . getRotationMatrix2D ( ( c // 2 , r // 2 ) , deg , 1 ) return cv2 . warpAffine ( im , M , ( c , r ) , borderMode = mode , flags = cv2 . WARP_FILL_OUTLIERS + interpolation ) | 1 | python cv2 rotate image 90 degrees | Rotates an image by deg degrees | cosqa-train-103 | def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA):
""" Rotates an image by deg degrees
Arguments:
deg (float): degree to rotate.
"""
r,c,*_ = im.shape
M = cv2.getRotationMatrix2D((c//2,r//2),deg,1)
return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv2.WARP_FILL_OUTLIERS+interpolation) |
def _calculate_distance ( latlon1 , latlon2 ) : lat1 , lon1 = latlon1 lat2 , lon2 = latlon2 dlon = lon2 - lon1 dlat = lat2 - lat1 R = 6371 # radius of the earth in kilometers a = np . sin ( dlat / 2 ) ** 2 + np . cos ( lat1 ) * np . cos ( lat2 ) * ( np . sin ( dlon / 2 ) ) ** 2 c = 2 * np . pi * R * np . arctan2 ( np . sqrt ( a ) , np . sqrt ( 1 - a ) ) / 180 return c | 1 | calculate distance between two coorinates python | Calculates the distance between two points on earth . | cosqa-train-104 | def _calculate_distance(latlon1, latlon2):
"""Calculates the distance between two points on earth.
"""
lat1, lon1 = latlon1
lat2, lon2 = latlon2
dlon = lon2 - lon1
dlat = lat2 - lat1
R = 6371 # radius of the earth in kilometers
a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2
c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180
return c |
def screen_cv2 ( self ) : pil_image = self . screen . convert ( 'RGB' ) cv2_image = np . array ( pil_image ) pil_image . close ( ) # Convert RGB to BGR
cv2_image = cv2_image [ : , : , : : - 1 ] return cv2_image | 0 | python cv2 show image in same window | cv2 Image of current window screen | cosqa-train-105 | def screen_cv2(self):
"""cv2 Image of current window screen"""
pil_image = self.screen.convert('RGB')
cv2_image = np.array(pil_image)
pil_image.close()
# Convert RGB to BGR
cv2_image = cv2_image[:, :, ::-1]
return cv2_image |
def direct2dDistance ( self , point ) : if not isinstance ( point , MapPoint ) : return 0.0 return ( ( self . x - point . x ) ** 2 + ( self . y - point . y ) ** 2 ) ** ( 0.5 ) # simple distance formula | 0 | calculate distance between two points on a map on python | consider the distance between two mapPoints ignoring all terrain pathing issues | cosqa-train-106 | def direct2dDistance(self, point):
"""consider the distance between two mapPoints, ignoring all terrain, pathing issues"""
if not isinstance(point, MapPoint): return 0.0
return ((self.x-point.x)**2 + (self.y-point.y)**2)**(0.5) # simple distance formula |
def _model_unique ( ins ) : unique = [ ] for t in ins . tables : for c in t . constraints : if isinstance ( c , UniqueConstraint ) : unique . append ( tuple ( col . key for col in c . columns ) ) return unique | 0 | python cycle through each column name that is obejct type and show the unique values in each | Get unique constraints info | cosqa-train-107 | def _model_unique(ins):
""" Get unique constraints info
:type ins: sqlalchemy.orm.mapper.Mapper
:rtype: list[tuple[str]]
"""
unique = []
for t in ins.tables:
for c in t.constraints:
if isinstance(c, UniqueConstraint):
unique.append(tuple(col.key for col in c.columns))
return unique |
def horz_dpi ( self ) : pHYs = self . _chunks . pHYs if pHYs is None : return 72 return self . _dpi ( pHYs . units_specifier , pHYs . horz_px_per_unit ) | 0 | calculate dpi of image python | Integer dots per inch for the width of this image . Defaults to 72 when not present in the file as is often the case . | cosqa-train-108 | def horz_dpi(self):
"""
Integer dots per inch for the width of this image. Defaults to 72
when not present in the file, as is often the case.
"""
pHYs = self._chunks.pHYs
if pHYs is None:
return 72
return self._dpi(pHYs.units_specifier, pHYs.horz_px_per_unit) |
def parse ( self , s ) : return datetime . datetime . strptime ( s , self . date_format ) . date ( ) | 1 | python date parser without format | Parses a date string formatted like YYYY - MM - DD . | cosqa-train-109 | def parse(self, s):
"""
Parses a date string formatted like ``YYYY-MM-DD``.
"""
return datetime.datetime.strptime(s, self.date_format).date() |
def estimate_complexity ( self , x , y , z , n ) : num_calculations = x * y * z * n run_time = num_calculations / 100000 # a 2014 PC does about 100k calcs in a second (guess based on prior logs) return self . show_time_as_short_string ( run_time ) | 0 | calculate time complexity in python | calculates a rough guess of runtime based on product of parameters | cosqa-train-110 | def estimate_complexity(self, x,y,z,n):
"""
calculates a rough guess of runtime based on product of parameters
"""
num_calculations = x * y * z * n
run_time = num_calculations / 100000 # a 2014 PC does about 100k calcs in a second (guess based on prior logs)
return self.show_time_as_short_string(run_time) |
def weekly ( date = datetime . date . today ( ) ) : return date - datetime . timedelta ( days = date . weekday ( ) ) | 0 | python date plus one week | Weeks start are fixes at Monday for now . | cosqa-train-111 | def weekly(date=datetime.date.today()):
"""
Weeks start are fixes at Monday for now.
"""
return date - datetime.timedelta(days=date.weekday()) |
def inh ( table ) : t = [ ] for i in table : t . append ( np . ndarray . tolist ( np . arcsinh ( i ) ) ) return t | 0 | calculateinverse of a matrix in python | inverse hyperbolic sine transformation | cosqa-train-112 | def inh(table):
"""
inverse hyperbolic sine transformation
"""
t = []
for i in table:
t.append(np.ndarray.tolist(np.arcsinh(i)))
return t |
def daterange ( start , end , delta = timedelta ( days = 1 ) , lower = Interval . CLOSED , upper = Interval . OPEN ) : date_interval = Interval ( lower = lower , lower_value = start , upper_value = end , upper = upper ) current = start if start in date_interval else start + delta while current in date_interval : yield current current = current + delta | 0 | python date range iterator | Returns a generator which creates the next value in the range on demand | cosqa-train-113 | def daterange(start, end, delta=timedelta(days=1), lower=Interval.CLOSED, upper=Interval.OPEN):
"""Returns a generator which creates the next value in the range on demand"""
date_interval = Interval(lower=lower, lower_value=start, upper_value=end, upper=upper)
current = start if start in date_interval else start + delta
while current in date_interval:
yield current
current = current + delta |
async def _thread_coro ( self , * args ) : return await self . _loop . run_in_executor ( self . _executor , self . _function , * args ) | 0 | call async function in python from another thread | Coroutine called by MapAsync . It s wrapping the call of run_in_executor to run the synchronous function as thread | cosqa-train-114 | async def _thread_coro(self, *args):
""" Coroutine called by MapAsync. It's wrapping the call of
run_in_executor to run the synchronous function as thread """
return await self._loop.run_in_executor(
self._executor, self._function, *args) |
def start_of_month ( val ) : if type ( val ) == date : val = datetime . fromordinal ( val . toordinal ( ) ) return start_of_day ( val ) . replace ( day = 1 ) | 0 | python dateime adjust date by month | Return a new datetime . datetime object with values that represent a start of a month . : param val : Date to ... : type val : datetime . datetime | datetime . date : rtype : datetime . datetime | cosqa-train-115 | def start_of_month(val):
"""
Return a new datetime.datetime object with values that represent
a start of a month.
:param val: Date to ...
:type val: datetime.datetime | datetime.date
:rtype: datetime.datetime
"""
if type(val) == date:
val = datetime.fromordinal(val.toordinal())
return start_of_day(val).replace(day=1) |
def check_output ( args , env = None , sp = subprocess ) : log . debug ( 'calling %s with env %s' , args , env ) output = sp . check_output ( args = args , env = env ) log . debug ( 'output: %r' , output ) return output | 0 | call external command and get output from python | Call an external binary and return its stdout . | cosqa-train-116 | def check_output(args, env=None, sp=subprocess):
"""Call an external binary and return its stdout."""
log.debug('calling %s with env %s', args, env)
output = sp.check_output(args=args, env=env)
log.debug('output: %r', output)
return output |
def datetime_to_ms ( dt ) : seconds = calendar . timegm ( dt . utctimetuple ( ) ) return seconds * 1000 + int ( dt . microsecond / 1000 ) | 0 | python datetime calculate millisec | Converts a datetime to a millisecond accuracy timestamp | cosqa-train-117 | def datetime_to_ms(dt):
"""
Converts a datetime to a millisecond accuracy timestamp
"""
seconds = calendar.timegm(dt.utctimetuple())
return seconds * 1000 + int(dt.microsecond / 1000) |
def retry_on_signal ( function ) : while True : try : return function ( ) except EnvironmentError , e : if e . errno != errno . EINTR : raise | 0 | call function in the try condition python | Retries function until it doesn t raise an EINTR error | cosqa-train-118 | def retry_on_signal(function):
"""Retries function until it doesn't raise an EINTR error"""
while True:
try:
return function()
except EnvironmentError, e:
if e.errno != errno.EINTR:
raise |
def datetime_to_timezone ( date , tz = "UTC" ) : if not date . tzinfo : date = date . replace ( tzinfo = timezone ( get_timezone ( ) ) ) return date . astimezone ( timezone ( tz ) ) | 0 | python datetime covert to timezone | convert naive datetime to timezone - aware datetime | cosqa-train-119 | def datetime_to_timezone(date, tz="UTC"):
""" convert naive datetime to timezone-aware datetime """
if not date.tzinfo:
date = date.replace(tzinfo=timezone(get_timezone()))
return date.astimezone(timezone(tz)) |
def test ( * args ) : subprocess . call ( [ "py.test-2.7" ] + list ( args ) ) subprocess . call ( [ "py.test-3.4" ] + list ( args ) ) | 0 | call python tests from robotframework | Run unit tests . | cosqa-train-120 | def test(*args):
"""
Run unit tests.
"""
subprocess.call(["py.test-2.7"] + list(args))
subprocess.call(["py.test-3.4"] + list(args)) |
def ToDatetime ( self ) : return datetime . utcfromtimestamp ( self . seconds + self . nanos / float ( _NANOS_PER_SECOND ) ) | 0 | python datetime drop microseconds | Converts Timestamp to datetime . | cosqa-train-121 | def ToDatetime(self):
"""Converts Timestamp to datetime."""
return datetime.utcfromtimestamp(
self.seconds + self.nanos / float(_NANOS_PER_SECOND)) |
def sortable_title ( instance ) : title = plone_sortable_title ( instance ) if safe_callable ( title ) : title = title ( ) return title . lower ( ) | 1 | callable title objects in python | Uses the default Plone sortable_text index lower - case | cosqa-train-122 | def sortable_title(instance):
"""Uses the default Plone sortable_text index lower-case
"""
title = plone_sortable_title(instance)
if safe_callable(title):
title = title()
return title.lower() |
def localize ( dt ) : if dt . tzinfo is UTC : return ( dt + LOCAL_UTC_OFFSET ) . replace ( tzinfo = None ) # No TZ info so not going to assume anything, return as-is. return dt | 0 | python datetime get local time zone | Localize a datetime object to local time . | cosqa-train-123 | def localize(dt):
"""Localize a datetime object to local time."""
if dt.tzinfo is UTC:
return (dt + LOCAL_UTC_OFFSET).replace(tzinfo=None)
# No TZ info so not going to assume anything, return as-is.
return dt |
def percent_cb ( name , complete , total ) : logger . debug ( "{}: {} transferred out of {}" . format ( name , sizeof_fmt ( complete ) , sizeof_fmt ( total ) ) ) progress . update_target ( name , complete , total ) | 0 | callbacks for progress bars in python | Callback for updating target progress | cosqa-train-124 | def percent_cb(name, complete, total):
""" Callback for updating target progress """
logger.debug(
"{}: {} transferred out of {}".format(
name, sizeof_fmt(complete), sizeof_fmt(total)
)
)
progress.update_target(name, complete, total) |
def now ( self ) : if self . use_utc : return datetime . datetime . utcnow ( ) else : return datetime . datetime . now ( ) | 0 | python datetime has no attribute utcnow | Return a : py : class : datetime . datetime instance representing the current time . | cosqa-train-125 | def now(self):
"""
Return a :py:class:`datetime.datetime` instance representing the current time.
:rtype: :py:class:`datetime.datetime`
"""
if self.use_utc:
return datetime.datetime.utcnow()
else:
return datetime.datetime.now() |
def to_pascal_case ( s ) : return re . sub ( r'(?!^)_([a-zA-Z])' , lambda m : m . group ( 1 ) . upper ( ) , s . capitalize ( ) ) | 0 | camel case to upper and underscore python | Transform underscore separated string to pascal case | cosqa-train-126 | def to_pascal_case(s):
"""Transform underscore separated string to pascal case
"""
return re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), s.capitalize()) |
def now ( self ) : if self . use_utc : return datetime . datetime . utcnow ( ) else : return datetime . datetime . now ( ) | 0 | python datetime now as timezone | Return a : py : class : datetime . datetime instance representing the current time . | cosqa-train-127 | def now(self):
"""
Return a :py:class:`datetime.datetime` instance representing the current time.
:rtype: :py:class:`datetime.datetime`
"""
if self.use_utc:
return datetime.datetime.utcnow()
else:
return datetime.datetime.now() |
def _convert_date_to_dict ( field_date ) : return { DAY : field_date . day , MONTH : field_date . month , YEAR : field_date . year } | 0 | can a datetime object be a dictionary key python 3 | Convert native python datetime . date object to a format supported by the API | cosqa-train-128 | def _convert_date_to_dict(field_date):
"""
Convert native python ``datetime.date`` object to a format supported by the API
"""
return {DAY: field_date.day, MONTH: field_date.month, YEAR: field_date.year} |
def ToDatetime ( self ) : return datetime . utcfromtimestamp ( self . seconds + self . nanos / float ( _NANOS_PER_SECOND ) ) | 0 | python datetime round microseconds as object | Converts Timestamp to datetime . | cosqa-train-129 | def ToDatetime(self):
"""Converts Timestamp to datetime."""
return datetime.utcfromtimestamp(
self.seconds + self.nanos / float(_NANOS_PER_SECOND)) |
def convert_array ( array ) : out = io . BytesIO ( array ) out . seek ( 0 ) return np . load ( out ) | 0 | can i change an arraylist to a list in python | Converts an ARRAY string stored in the database back into a Numpy array . | cosqa-train-130 | def convert_array(array):
"""
Converts an ARRAY string stored in the database back into a Numpy array.
Parameters
----------
array: ARRAY
The array object to be converted back into a Numpy array.
Returns
-------
array
The converted Numpy array.
"""
out = io.BytesIO(array)
out.seek(0)
return np.load(out) |
def parse_timestamp ( timestamp ) : dt = dateutil . parser . parse ( timestamp ) return dt . astimezone ( dateutil . tz . tzutc ( ) ) | 0 | python datetime timezone iso | Parse ISO8601 timestamps given by github API . | cosqa-train-131 | def parse_timestamp(timestamp):
"""Parse ISO8601 timestamps given by github API."""
dt = dateutil.parser.parse(timestamp)
return dt.astimezone(dateutil.tz.tzutc()) |
def add_to_js ( self , name , var ) : frame = self . page ( ) . mainFrame ( ) frame . addToJavaScriptWindowObject ( name , var ) | 0 | can i use javascript in python | Add an object to Javascript . | cosqa-train-132 | def add_to_js(self, name, var):
"""Add an object to Javascript."""
frame = self.page().mainFrame()
frame.addToJavaScriptWindowObject(name, var) |
def fromtimestamp ( cls , timestamp ) : d = cls . utcfromtimestamp ( timestamp ) return d . astimezone ( localtz ( ) ) | 0 | python datetime utcfromtimestamp local time zone | Returns a datetime object of a given timestamp ( in local tz ) . | cosqa-train-133 | def fromtimestamp(cls, timestamp):
"""Returns a datetime object of a given timestamp (in local tz)."""
d = cls.utcfromtimestamp(timestamp)
return d.astimezone(localtz()) |
def print_latex ( o ) : if can_print_latex ( o ) : s = latex ( o , mode = 'plain' ) s = s . replace ( '\\dag' , '\\dagger' ) s = s . strip ( '$' ) return '$$%s$$' % s # Fallback to the string printer return None | 0 | can latex compile documents from python code | A function to generate the latex representation of sympy expressions . | cosqa-train-134 | def print_latex(o):
"""A function to generate the latex representation of sympy
expressions."""
if can_print_latex(o):
s = latex(o, mode='plain')
s = s.replace('\\dag','\\dagger')
s = s.strip('$')
return '$$%s$$' % s
# Fallback to the string printer
return None |
def datetime64_to_datetime ( dt ) : dt64 = np . datetime64 ( dt ) ts = ( dt64 - np . datetime64 ( '1970-01-01T00:00:00' ) ) / np . timedelta64 ( 1 , 's' ) return datetime . datetime . utcfromtimestamp ( ts ) | 0 | python datetime64 ns separate | convert numpy s datetime64 to datetime | cosqa-train-135 | def datetime64_to_datetime(dt):
""" convert numpy's datetime64 to datetime """
dt64 = np.datetime64(dt)
ts = (dt64 - np.datetime64('1970-01-01T00:00:00')) / np.timedelta64(1, 's')
return datetime.datetime.utcfromtimestamp(ts) |
def batch_tensor ( self , name ) : if name in self . transition_tensors : return tensor_util . merge_first_two_dims ( self . transition_tensors [ name ] ) else : return self . rollout_tensors [ name ] | 0 | can python merge with tensorflow | A buffer of a given value in a flat ( minibatch - indexed ) format | cosqa-train-136 | def batch_tensor(self, name):
""" A buffer of a given value in a 'flat' (minibatch-indexed) format """
if name in self.transition_tensors:
return tensor_util.merge_first_two_dims(self.transition_tensors[name])
else:
return self.rollout_tensors[name] |
def isInteractive ( ) : if sys . stdout . isatty ( ) and os . name != 'nt' : #Hopefully everything but ms supports '\r' try : import threading except ImportError : return False else : return True else : return False | 0 | python decide interactive mode | A basic check of if the program is running in interactive mode | cosqa-train-137 | def isInteractive():
"""
A basic check of if the program is running in interactive mode
"""
if sys.stdout.isatty() and os.name != 'nt':
#Hopefully everything but ms supports '\r'
try:
import threading
except ImportError:
return False
else:
return True
else:
return False |
def create_symlink ( source , link_name ) : os_symlink = getattr ( os , "symlink" , None ) if isinstance ( os_symlink , collections . Callable ) : os_symlink ( source , link_name ) else : import ctypes csl = ctypes . windll . kernel32 . CreateSymbolicLinkW csl . argtypes = ( ctypes . c_wchar_p , ctypes . c_wchar_p , ctypes . c_uint32 ) csl . restype = ctypes . c_ubyte flags = 1 if os . path . isdir ( source ) else 0 if csl ( link_name , source , flags ) == 0 : raise ctypes . WinError ( ) | 0 | can python open windows symbolic links | Creates symbolic link for either operating system . http : // stackoverflow . com / questions / 6260149 / os - symlink - support - in - windows | cosqa-train-138 | def create_symlink(source, link_name):
"""
Creates symbolic link for either operating system.
http://stackoverflow.com/questions/6260149/os-symlink-support-in-windows
"""
os_symlink = getattr(os, "symlink", None)
if isinstance(os_symlink, collections.Callable):
os_symlink(source, link_name)
else:
import ctypes
csl = ctypes.windll.kernel32.CreateSymbolicLinkW
csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)
csl.restype = ctypes.c_ubyte
flags = 1 if os.path.isdir(source) else 0
if csl(link_name, source, flags) == 0:
raise ctypes.WinError() |
def export ( defn ) : globals ( ) [ defn . __name__ ] = defn __all__ . append ( defn . __name__ ) return defn | 0 | python decorate builtin methods | Decorator to explicitly mark functions that are exposed in a lib . | cosqa-train-139 | def export(defn):
"""Decorator to explicitly mark functions that are exposed in a lib."""
globals()[defn.__name__] = defn
__all__.append(defn.__name__)
return defn |
def parse ( source , remove_comments = True , * * kw ) : return ElementTree . parse ( source , SourceLineParser ( ) , * * kw ) | 0 | can python xml parser parse comments | Thin wrapper around ElementTree . parse | cosqa-train-140 | def parse(source, remove_comments=True, **kw):
"""Thin wrapper around ElementTree.parse"""
return ElementTree.parse(source, SourceLineParser(), **kw) |
def decorator ( func ) : def wrapper ( __decorated__ = None , * Args , * * KwArgs ) : if __decorated__ is None : # the decorator has some optional arguments. return lambda _func : func ( _func , * Args , * * KwArgs ) else : return func ( __decorated__ , * Args , * * KwArgs ) return wrap ( wrapper , func ) | 0 | python decorate function with optional | r Makes the passed decorators to support optional args . | cosqa-train-141 | def decorator(func):
r"""Makes the passed decorators to support optional args.
"""
def wrapper(__decorated__=None, *Args, **KwArgs):
if __decorated__ is None: # the decorator has some optional arguments.
return lambda _func: func(_func, *Args, **KwArgs)
else:
return func(__decorated__, *Args, **KwArgs)
return wrap(wrapper, func) |
def show_image ( self , key ) : data = self . model . get_data ( ) data [ key ] . show ( ) | 1 | can we access img in django python | Show image ( item is a PIL image ) | cosqa-train-142 | def show_image(self, key):
"""Show image (item is a PIL image)"""
data = self.model.get_data()
data[key].show() |
def get_default_args ( func ) : args , varargs , keywords , defaults = getargspec_no_self ( func ) return dict ( zip ( args [ - len ( defaults ) : ] , defaults ) ) | 0 | python default input values for a function | returns a dictionary of arg_name : default_values for the input function | cosqa-train-143 | def get_default_args(func):
"""
returns a dictionary of arg_name:default_values for the input function
"""
args, varargs, keywords, defaults = getargspec_no_self(func)
return dict(zip(args[-len(defaults):], defaults)) |
def _interval_to_bound_points ( array ) : array_boundaries = np . array ( [ x . left for x in array ] ) array_boundaries = np . concatenate ( ( array_boundaries , np . array ( [ array [ - 1 ] . right ] ) ) ) return array_boundaries | 0 | can you create an array with different intervals in python | Helper function which returns an array with the Intervals boundaries . | cosqa-train-144 | def _interval_to_bound_points(array):
"""
Helper function which returns an array
with the Intervals' boundaries.
"""
array_boundaries = np.array([x.left for x in array])
array_boundaries = np.concatenate(
(array_boundaries, np.array([array[-1].right])))
return array_boundaries |
def closing_plugin ( self , cancelable = False ) : self . dialog_manager . close_all ( ) self . shell . exit_interpreter ( ) return True | 0 | python delay before closing a popup | Perform actions before parent main window is closed | cosqa-train-145 | def closing_plugin(self, cancelable=False):
"""Perform actions before parent main window is closed"""
self.dialog_manager.close_all()
self.shell.exit_interpreter()
return True |
def test ( ) : from spyder . utils . qthelpers import qapplication app = qapplication ( ) dlg = ProjectDialog ( None ) dlg . show ( ) sys . exit ( app . exec_ ( ) ) | 0 | can you make a gui in spyder using python | Local test . | cosqa-train-146 | def test():
"""Local test."""
from spyder.utils.qthelpers import qapplication
app = qapplication()
dlg = ProjectDialog(None)
dlg.show()
sys.exit(app.exec_()) |
def del_label ( self , name ) : labels_tag = self . root [ 0 ] labels_tag . remove ( self . _find_label ( name ) ) | 0 | python delete a label | Delete a label by name . | cosqa-train-147 | def del_label(self, name):
"""Delete a label by name."""
labels_tag = self.root[0]
labels_tag.remove(self._find_label(name)) |
def mixedcase ( path ) : words = path . split ( '_' ) return words [ 0 ] + '' . join ( word . title ( ) for word in words [ 1 : ] ) | 0 | capitalize an arguement in python | Removes underscores and capitalizes the neighbouring character | cosqa-train-148 | def mixedcase(path):
"""Removes underscores and capitalizes the neighbouring character"""
words = path.split('_')
return words[0] + ''.join(word.title() for word in words[1:]) |
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 | python delete egg file | delete all the eggs in the directory specified | cosqa-train-149 | 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 get_system_cpu_times ( ) : user , nice , system , idle = _psutil_osx . get_system_cpu_times ( ) return _cputimes_ntuple ( user , nice , system , idle ) | 0 | capture the cpu utilisation by using python | Return system CPU times as a namedtuple . | cosqa-train-150 | def get_system_cpu_times():
"""Return system CPU times as a namedtuple."""
user, nice, system, idle = _psutil_osx.get_system_cpu_times()
return _cputimes_ntuple(user, nice, system, idle) |
def remove ( self , document_id , namespace , timestamp ) : self . solr . delete ( id = u ( document_id ) , commit = ( self . auto_commit_interval == 0 ) ) | 0 | python delete solr doc | Removes documents from Solr | cosqa-train-151 | def remove(self, document_id, namespace, timestamp):
"""Removes documents from Solr
The input is a python dictionary that represents a mongo document.
"""
self.solr.delete(id=u(document_id),
commit=(self.auto_commit_interval == 0)) |
def update_hash_from_str ( hsh , str_input ) : byte_input = str ( str_input ) . encode ( "UTF-8" ) hsh . update ( byte_input ) | 0 | cast hash to string python | Convert a str to object supporting buffer API and update a hash with it . | cosqa-train-152 | def update_hash_from_str(hsh, str_input):
"""
Convert a str to object supporting buffer API and update a hash with it.
"""
byte_input = str(str_input).encode("UTF-8")
hsh.update(byte_input) |
def make_regex ( separator ) : return re . compile ( r'(?:' + re . escape ( separator ) + r')?((?:[^' + re . escape ( separator ) + r'\\]|\\.)+)' ) | 0 | python delimit for regular expression | Utility function to create regexp for matching escaped separators in strings . | cosqa-train-153 | def make_regex(separator):
"""Utility function to create regexp for matching escaped separators
in strings.
"""
return re.compile(r'(?:' + re.escape(separator) + r')?((?:[^' +
re.escape(separator) + r'\\]|\\.)+)') |
def dictify ( a_named_tuple ) : return dict ( ( s , getattr ( a_named_tuple , s ) ) for s in a_named_tuple . _fields ) | 0 | cast nametuple to dictionary python | Transform a named tuple into a dictionary | cosqa-train-154 | def dictify(a_named_tuple):
"""Transform a named tuple into a dictionary"""
return dict((s, getattr(a_named_tuple, s)) for s in a_named_tuple._fields) |
def _py2_and_3_joiner ( sep , joinable ) : if ISPY3 : sep = bytes ( sep , DEFAULT_ENCODING ) joined = sep . join ( joinable ) return joined . decode ( DEFAULT_ENCODING ) if ISPY3 else joined | 0 | python delimited join strings | Allow \ n . join ( ... ) statements to work in Py2 and Py3 . : param sep : : param joinable : : return : | cosqa-train-155 | def _py2_and_3_joiner(sep, joinable):
"""
Allow '\n'.join(...) statements to work in Py2 and Py3.
:param sep:
:param joinable:
:return:
"""
if ISPY3:
sep = bytes(sep, DEFAULT_ENCODING)
joined = sep.join(joinable)
return joined.decode(DEFAULT_ENCODING) if ISPY3 else joined |
def c_str ( string ) : if not isinstance ( string , str ) : string = string . decode ( 'ascii' ) return ctypes . c_char_p ( string . encode ( 'utf-8' ) ) | 0 | cast python string to c string | Convert a python string to C string . | cosqa-train-156 | def c_str(string):
""""Convert a python string to C string."""
if not isinstance(string, str):
string = string.decode('ascii')
return ctypes.c_char_p(string.encode('utf-8')) |
def endline_semicolon_check ( self , original , loc , tokens ) : return self . check_strict ( "semicolon at end of line" , original , loc , tokens ) | 0 | python delimiter check for a file | Check for semicolons at the end of lines . | cosqa-train-157 | def endline_semicolon_check(self, original, loc, tokens):
"""Check for semicolons at the end of lines."""
return self.check_strict("semicolon at end of line", original, loc, tokens) |
def _datetime_to_date ( arg ) : _arg = parse ( arg ) if isinstance ( _arg , datetime . datetime ) : _arg = _arg . date ( ) return _arg | 0 | cast to datetime object python | convert datetime / str to date : param arg : : return : | cosqa-train-158 | def _datetime_to_date(arg):
"""
convert datetime/str to date
:param arg:
:return:
"""
_arg = parse(arg)
if isinstance(_arg, datetime.datetime):
_arg = _arg.date()
return _arg |
def get ( self ) : with self . _mutex : entry = self . _queue . pop ( ) del self . _block_map [ entry [ 2 ] ] return entry [ 2 ] | 0 | python deque pop block empty | Get the highest priority Processing Block from the queue . | cosqa-train-159 | def get(self):
"""Get the highest priority Processing Block from the queue."""
with self._mutex:
entry = self._queue.pop()
del self._block_map[entry[2]]
return entry[2] |
def center_text ( text , width = 80 ) : centered = [ ] for line in text . splitlines ( ) : centered . append ( line . center ( width ) ) return "\n" . join ( centered ) | 1 | center align text python | Center all lines of the text . It is assumed that all lines width is smaller then B { width } because the line width will not be checked . Args : text ( str ) : Text to wrap . width ( int ) : Maximum number of characters per line . Returns : str : Centered text . | cosqa-train-160 | def center_text(text, width=80):
"""Center all lines of the text.
It is assumed that all lines width is smaller then B{width}, because the
line width will not be checked.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
str: Centered text.
"""
centered = []
for line in text.splitlines():
centered.append(line.center(width))
return "\n".join(centered) |
def from_json ( cls , json_str ) : d = json . loads ( json_str ) return cls . from_dict ( d ) | 0 | python deserializingjson to object | Deserialize the object from a JSON string . | cosqa-train-161 | def from_json(cls, json_str):
"""Deserialize the object from a JSON string."""
d = json.loads(json_str)
return cls.from_dict(d) |
def update ( kernel = False ) : manager = MANAGER cmds = { 'yum -y --color=never' : { False : '--exclude=kernel* update' , True : 'update' } } cmd = cmds [ manager ] [ kernel ] run_as_root ( "%(manager)s %(cmd)s" % locals ( ) ) | 0 | centos yum remove python | Upgrade all packages skip obsoletes if obsoletes = 0 in yum . conf . | cosqa-train-162 | def update(kernel=False):
"""
Upgrade all packages, skip obsoletes if ``obsoletes=0`` in ``yum.conf``.
Exclude *kernel* upgrades by default.
"""
manager = MANAGER
cmds = {'yum -y --color=never': {False: '--exclude=kernel* update', True: 'update'}}
cmd = cmds[manager][kernel]
run_as_root("%(manager)s %(cmd)s" % locals()) |
def guess_encoding ( text , default = DEFAULT_ENCODING ) : result = chardet . detect ( text ) return normalize_result ( result , default = default ) | 0 | python detect encoding in text | Guess string encoding . | cosqa-train-163 | def guess_encoding(text, default=DEFAULT_ENCODING):
"""Guess string encoding.
Given a piece of text, apply character encoding detection to
guess the appropriate encoding of the text.
"""
result = chardet.detect(text)
return normalize_result(result, default=default) |
def commajoin_as_strings ( iterable ) : return _ ( u',' ) . join ( ( six . text_type ( i ) for i in iterable ) ) | 0 | chain iterable python one element followed by comma | Join the given iterable with | cosqa-train-164 | def commajoin_as_strings(iterable):
""" Join the given iterable with ',' """
return _(u',').join((six.text_type(i) for i in iterable)) |
def supports_color ( ) : unsupported_platform = ( sys . platform in ( 'win32' , 'Pocket PC' ) ) # isatty is not always implemented, #6223. is_a_tty = hasattr ( sys . stdout , 'isatty' ) and sys . stdout . isatty ( ) if unsupported_platform or not is_a_tty : return False return True | 0 | python detect if color is on screen | Returns True if the running system s terminal supports color and False otherwise . | cosqa-train-165 | def supports_color():
"""
Returns True if the running system's terminal supports color, and False
otherwise.
"""
unsupported_platform = (sys.platform in ('win32', 'Pocket PC'))
# isatty is not always implemented, #6223.
is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
if unsupported_platform or not is_a_tty:
return False
return True |
def seconds_to_hms ( seconds ) : hours = int ( seconds / 3600.0 ) minutes = int ( ( seconds / 60.0 ) % 60.0 ) secs = float ( seconds % 60.0 ) return "{0:02d}:{1:02d}:{2:02.6f}" . format ( hours , minutes , secs ) | 0 | change hhmmss format to seconds from midngiht in python | Converts seconds float to hh : mm : ss . ssssss format . | cosqa-train-166 | def seconds_to_hms(seconds):
"""
Converts seconds float to 'hh:mm:ss.ssssss' format.
"""
hours = int(seconds / 3600.0)
minutes = int((seconds / 60.0) % 60.0)
secs = float(seconds % 60.0)
return "{0:02d}:{1:02d}:{2:02.6f}".format(hours, minutes, secs) |
def __contains__ ( self , key ) : k = self . _real_key ( key ) return k in self . _data | 0 | python detect if key is in dictionary | Invoked when determining whether a specific key is in the dictionary using key in d . | cosqa-train-167 | def __contains__(self, key):
"""
Invoked when determining whether a specific key is in the dictionary
using `key in d`.
The key is looked up case-insensitively.
"""
k = self._real_key(key)
return k in self._data |
def get_truetype ( value ) : if value in [ "true" , "True" , "y" , "Y" , "yes" ] : return True if value in [ "false" , "False" , "n" , "N" , "no" ] : return False if value . isdigit ( ) : return int ( value ) return str ( value ) | 0 | change nonetype to int python | Convert a string to a pythonized parameter . | cosqa-train-168 | def get_truetype(value):
"""Convert a string to a pythonized parameter."""
if value in ["true", "True", "y", "Y", "yes"]:
return True
if value in ["false", "False", "n", "N", "no"]:
return False
if value.isdigit():
return int(value)
return str(value) |
def Serializable ( o ) : if isinstance ( o , ( str , dict , int ) ) : return o else : try : json . dumps ( o ) return o except Exception : LOG . debug ( "Got a non-serilizeable object: %s" % o ) return o . __repr__ ( ) | 0 | python detect not json serializable | Make sure an object is JSON - serializable Use this to return errors and other info that does not need to be deserialized or does not contain important app data . Best for returning error info and such | cosqa-train-169 | def Serializable(o):
"""Make sure an object is JSON-serializable
Use this to return errors and other info that does not need to be
deserialized or does not contain important app data. Best for returning
error info and such"""
if isinstance(o, (str, dict, int)):
return o
else:
try:
json.dumps(o)
return o
except Exception:
LOG.debug("Got a non-serilizeable object: %s" % o)
return o.__repr__() |
def timed_rotating_file_handler ( name , logname , filename , when = 'h' , interval = 1 , backupCount = 0 , encoding = None , delay = False , utc = False ) : return wrap_log_handler ( logging . handlers . TimedRotatingFileHandler ( filename , when = when , interval = interval , backupCount = backupCount , encoding = encoding , delay = delay , utc = utc ) ) | 1 | change path of log files using python rotatingfilehandler | A Bark logging handler logging output to a named file . At intervals specified by the when the file will be rotated under control of backupCount . | cosqa-train-170 | def timed_rotating_file_handler(name, logname, filename, when='h',
interval=1, backupCount=0,
encoding=None, delay=False, utc=False):
"""
A Bark logging handler logging output to a named file. At
intervals specified by the 'when', the file will be rotated, under
control of 'backupCount'.
Similar to logging.handlers.TimedRotatingFileHandler.
"""
return wrap_log_handler(logging.handlers.TimedRotatingFileHandler(
filename, when=when, interval=interval, backupCount=backupCount,
encoding=encoding, delay=delay, utc=utc)) |
def is_identifier ( string ) : matched = PYTHON_IDENTIFIER_RE . match ( string ) return bool ( matched ) and not keyword . iskeyword ( string ) | 1 | python deter is an invalid keyword | Check if string could be a valid python identifier | cosqa-train-171 | def is_identifier(string):
"""Check if string could be a valid python identifier
:param string: string to be tested
:returns: True if string can be a python identifier, False otherwise
:rtype: bool
"""
matched = PYTHON_IDENTIFIER_RE.match(string)
return bool(matched) and not keyword.iskeyword(string) |
def uniform_iterator ( sequence ) : if isinstance ( sequence , abc . Mapping ) : return six . iteritems ( sequence ) else : return enumerate ( sequence ) | 0 | change python enumerate iterator | Uniform ( key value ) iteration on a dict or ( idx value ) on a list . | cosqa-train-172 | def uniform_iterator(sequence):
"""Uniform (key, value) iteration on a `dict`,
or (idx, value) on a `list`."""
if isinstance(sequence, abc.Mapping):
return six.iteritems(sequence)
else:
return enumerate(sequence) |
def _guess_type ( val ) : if isinstance ( val , bool ) : return "choice" elif isinstance ( val , int ) : return "number" elif isinstance ( val , float ) : return "number" elif isinstance ( val , str ) : return "text" elif hasattr ( val , 'read' ) : return "file" else : return "text" | 0 | python determine the type of a user input | Guess the input type of the parameter based off the default value if unknown use text | cosqa-train-173 | def _guess_type(val):
"""Guess the input type of the parameter based off the default value, if unknown use text"""
if isinstance(val, bool):
return "choice"
elif isinstance(val, int):
return "number"
elif isinstance(val, float):
return "number"
elif isinstance(val, str):
return "text"
elif hasattr(val, 'read'):
return "file"
else:
return "text" |
def _to_corrected_pandas_type ( dt ) : import numpy as np if type ( dt ) == ByteType : return np . int8 elif type ( dt ) == ShortType : return np . int16 elif type ( dt ) == IntegerType : return np . int32 elif type ( dt ) == FloatType : return np . float32 else : return None | 0 | change the data type in data frame in python | When converting Spark SQL records to Pandas DataFrame the inferred data type may be wrong . This method gets the corrected data type for Pandas if that type may be inferred uncorrectly . | cosqa-train-174 | def _to_corrected_pandas_type(dt):
"""
When converting Spark SQL records to Pandas DataFrame, the inferred data type may be wrong.
This method gets the corrected data type for Pandas if that type may be inferred uncorrectly.
"""
import numpy as np
if type(dt) == ByteType:
return np.int8
elif type(dt) == ShortType:
return np.int16
elif type(dt) == IntegerType:
return np.int32
elif type(dt) == FloatType:
return np.float32
else:
return None |
def _platform_is_windows ( platform = sys . platform ) : matched = platform in ( 'cygwin' , 'win32' , 'win64' ) if matched : error_msg = "Windows isn't supported yet" raise OSError ( error_msg ) return matched | 1 | python determine whether windows or linux | Is the current OS a Windows? | cosqa-train-175 | def _platform_is_windows(platform=sys.platform):
"""Is the current OS a Windows?"""
matched = platform in ('cygwin', 'win32', 'win64')
if matched:
error_msg = "Windows isn't supported yet"
raise OSError(error_msg)
return matched |
def _xls2col_widths ( self , worksheet , tab ) : for col in xrange ( worksheet . ncols ) : try : xls_width = worksheet . colinfo_map [ col ] . width pys_width = self . xls_width2pys_width ( xls_width ) self . code_array . col_widths [ col , tab ] = pys_width except KeyError : pass | 0 | change width of columns in all sheets python | Updates col_widths in code_array | cosqa-train-176 | def _xls2col_widths(self, worksheet, tab):
"""Updates col_widths in code_array"""
for col in xrange(worksheet.ncols):
try:
xls_width = worksheet.colinfo_map[col].width
pys_width = self.xls_width2pys_width(xls_width)
self.code_array.col_widths[col, tab] = pys_width
except KeyError:
pass |
def keys_to_snake_case ( camel_case_dict ) : return dict ( ( to_snake_case ( key ) , value ) for ( key , value ) in camel_case_dict . items ( ) ) | 0 | python dict case insensitive | Make a copy of a dictionary with all keys converted to snake case . This is just calls to_snake_case on each of the keys in the dictionary and returns a new dictionary . | cosqa-train-177 | def keys_to_snake_case(camel_case_dict):
"""
Make a copy of a dictionary with all keys converted to snake case. This is just calls to_snake_case on
each of the keys in the dictionary and returns a new dictionary.
:param camel_case_dict: Dictionary with the keys to convert.
:type camel_case_dict: Dictionary.
:return: Dictionary with the keys converted to snake case.
"""
return dict((to_snake_case(key), value) for (key, value) in camel_case_dict.items()) |
def _bytes_to_json ( value ) : if isinstance ( value , bytes ) : value = base64 . standard_b64encode ( value ) . decode ( "ascii" ) return value | 0 | changes bytes obj to json python | Coerce value to an JSON - compatible representation . | cosqa-train-178 | def _bytes_to_json(value):
"""Coerce 'value' to an JSON-compatible representation."""
if isinstance(value, bytes):
value = base64.standard_b64encode(value).decode("ascii")
return value |
def dict_hash ( dct ) : dct_s = json . dumps ( dct , sort_keys = True ) try : m = md5 ( dct_s ) except TypeError : m = md5 ( dct_s . encode ( ) ) return m . hexdigest ( ) | 0 | python dict get hash | Return a hash of the contents of a dictionary | cosqa-train-179 | def dict_hash(dct):
"""Return a hash of the contents of a dictionary"""
dct_s = json.dumps(dct, sort_keys=True)
try:
m = md5(dct_s)
except TypeError:
m = md5(dct_s.encode())
return m.hexdigest() |
def int_to_date ( date ) : year = date // 10 ** 4 month = date % 10 ** 4 // 10 ** 2 day = date % 10 ** 2 return datetime . date ( year , month , day ) | 0 | changing date from int to date in python | Convert an int of form yyyymmdd to a python date object . | cosqa-train-180 | def int_to_date(date):
"""
Convert an int of form yyyymmdd to a python date object.
"""
year = date // 10**4
month = date % 10**4 // 10**2
day = date % 10**2
return datetime.date(year, month, day) |
def hasattrs ( object , * names ) : for name in names : if not hasattr ( object , name ) : return False return True | 1 | check all attributes in an object python | Takes in an object and a variable length amount of named attributes and checks to see if the object has each property . If any of the attributes are missing this returns false . | cosqa-train-181 | def hasattrs(object, *names):
"""
Takes in an object and a variable length amount of named attributes,
and checks to see if the object has each property. If any of the
attributes are missing, this returns false.
:param object: an object that may or may not contain the listed attributes
:param names: a variable amount of attribute names to check for
:return: True if the object contains each named attribute, false otherwise
"""
for name in names:
if not hasattr(object, name):
return False
return True |
def dict_update_newkeys ( dict_ , dict2 ) : for key , val in six . iteritems ( dict2 ) : if key not in dict_ : dict_ [ key ] = val | 0 | python dict update none | Like dict . update but does not overwrite items | cosqa-train-182 | def dict_update_newkeys(dict_, dict2):
""" Like dict.update, but does not overwrite items """
for key, val in six.iteritems(dict2):
if key not in dict_:
dict_[key] = val |
def numpy_aware_eq ( a , b ) : if isinstance ( a , np . ndarray ) or isinstance ( b , np . ndarray ) : return np . array_equal ( a , b ) if ( ( isinstance ( a , Iterable ) and isinstance ( b , Iterable ) ) and not isinstance ( a , str ) and not isinstance ( b , str ) ) : if len ( a ) != len ( b ) : return False return all ( numpy_aware_eq ( x , y ) for x , y in zip ( a , b ) ) return a == b | 1 | check equality between arrays python | Return whether two objects are equal via recursion using : func : numpy . array_equal for comparing numpy arays . | cosqa-train-183 | def numpy_aware_eq(a, b):
"""Return whether two objects are equal via recursion, using
:func:`numpy.array_equal` for comparing numpy arays.
"""
if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):
return np.array_equal(a, b)
if ((isinstance(a, Iterable) and isinstance(b, Iterable)) and
not isinstance(a, str) and not isinstance(b, str)):
if len(a) != len(b):
return False
return all(numpy_aware_eq(x, y) for x, y in zip(a, b))
return a == b |
def update ( self , other_dict ) : for key , value in iter_multi_items ( other_dict ) : MultiDict . add ( self , key , value ) | 0 | python dictionary add one by one or | update () extends rather than replaces existing key lists . | cosqa-train-184 | def update(self, other_dict):
"""update() extends rather than replaces existing key lists."""
for key, value in iter_multi_items(other_dict):
MultiDict.add(self, key, value) |
def _internet_on ( address ) : try : urllib2 . urlopen ( address , timeout = 1 ) return True except urllib2 . URLError as err : return False | 0 | check for internet connection python | Check to see if the internet is on by pinging a set address . : param address : the IP or address to hit : return : a boolean - true if can be reached false if not . | cosqa-train-185 | def _internet_on(address):
"""
Check to see if the internet is on by pinging a set address.
:param address: the IP or address to hit
:return: a boolean - true if can be reached, false if not.
"""
try:
urllib2.urlopen(address, timeout=1)
return True
except urllib2.URLError as err:
return False |
def _defaultdict ( dct , fallback = _illegal_character ) : out = defaultdict ( lambda : fallback ) for k , v in six . iteritems ( dct ) : out [ k ] = v return out | 0 | python dictionary if key not in dict make a default value | Wraps the given dictionary such that the given fallback function will be called when a nonexistent key is accessed . | cosqa-train-186 | def _defaultdict(dct, fallback=_illegal_character):
"""Wraps the given dictionary such that the given fallback function will be called when a nonexistent key is
accessed.
"""
out = defaultdict(lambda: fallback)
for k, v in six.iteritems(dct):
out[k] = v
return out |
def is_json_file ( filename , show_warnings = False ) : try : config_dict = load_config ( filename , file_type = "json" ) is_json = True except : is_json = False return ( is_json ) | 0 | check for json python | Check configuration file type is JSON Return a boolean indicating wheather the file is JSON format or not | cosqa-train-187 | def is_json_file(filename, show_warnings = False):
"""Check configuration file type is JSON
Return a boolean indicating wheather the file is JSON format or not
"""
try:
config_dict = load_config(filename, file_type = "json")
is_json = True
except:
is_json = False
return(is_json) |
def _remove_dict_keys_with_value ( dict_ , val ) : return { k : v for k , v in dict_ . items ( ) if v is not val } | 0 | python dictionary remove key with value | Removes dict keys which have have self as value . | cosqa-train-188 | def _remove_dict_keys_with_value(dict_, val):
"""Removes `dict` keys which have have `self` as value."""
return {k: v for k, v in dict_.items() if v is not val} |
def post_commit_hook ( argv ) : _ , stdout , _ = run ( "git log -1 --format=%B HEAD" ) message = "\n" . join ( stdout ) options = { "allow_empty" : True } if not _check_message ( message , options ) : click . echo ( "Commit message errors (fix with 'git commit --amend')." , file = sys . stderr ) return 1 # it should not fail with exit return 0 | 0 | check git commit messages python | Hook : for checking commit message . | cosqa-train-189 | def post_commit_hook(argv):
"""Hook: for checking commit message."""
_, stdout, _ = run("git log -1 --format=%B HEAD")
message = "\n".join(stdout)
options = {"allow_empty": True}
if not _check_message(message, options):
click.echo(
"Commit message errors (fix with 'git commit --amend').",
file=sys.stderr)
return 1 # it should not fail with exit
return 0 |
def setdefaults ( dct , defaults ) : for key in defaults : dct . setdefault ( key , defaults [ key ] ) return dct | 0 | python dictionary setdefault nested | Given a target dct and a dict of { key : default value } pairs calls setdefault for all of those pairs . | cosqa-train-190 | def setdefaults(dct, defaults):
"""Given a target dct and a dict of {key:default value} pairs,
calls setdefault for all of those pairs."""
for key in defaults:
dct.setdefault(key, defaults[key])
return dct |
def is_image_file_valid ( file_path_name ) : # Image.verify is only implemented for PNG images, and it only verifies # the CRC checksum in the image. The only way to check from within # Pillow is to load the image in a try/except and check the error. If # as much info as possible is from the image is needed, # ``ImageFile.LOAD_TRUNCATED_IMAGES=True`` needs to bet set and it # will attempt to parse as much as possible. try : with Image . open ( file_path_name ) as image : image . load ( ) except IOError : return False return True | 0 | check if a file is a valid image python | Indicate whether the specified image file is valid or not . | cosqa-train-191 | def is_image_file_valid(file_path_name):
"""
Indicate whether the specified image file is valid or not.
@param file_path_name: absolute path and file name of an image.
@return: ``True`` if the image file is valid, ``False`` if the file is
truncated or does not correspond to a supported image.
"""
# Image.verify is only implemented for PNG images, and it only verifies
# the CRC checksum in the image. The only way to check from within
# Pillow is to load the image in a try/except and check the error. If
# as much info as possible is from the image is needed,
# ``ImageFile.LOAD_TRUNCATED_IMAGES=True`` needs to bet set and it
# will attempt to parse as much as possible.
try:
with Image.open(file_path_name) as image:
image.load()
except IOError:
return False
return True |
def dict_to_html_attrs ( dict_ ) : res = ' ' . join ( '%s="%s"' % ( k , v ) for k , v in dict_ . items ( ) ) return res | 0 | python dictionary to html | Banana banana | cosqa-train-192 | def dict_to_html_attrs(dict_):
"""
Banana banana
"""
res = ' '.join('%s="%s"' % (k, v) for k, v in dict_.items())
return res |
def is_binary ( filename ) : with open ( filename , 'rb' ) as fp : data = fp . read ( 1024 ) if not data : return False if b'\0' in data : return True return False | 0 | check if a file is binary python | Returns True if the file is binary | cosqa-train-193 | def is_binary(filename):
""" Returns True if the file is binary
"""
with open(filename, 'rb') as fp:
data = fp.read(1024)
if not data:
return False
if b'\0' in data:
return True
return False |
def dict_to_querystring ( dictionary ) : s = u"" for d in dictionary . keys ( ) : s = unicode . format ( u"{0}{1}={2}&" , s , d , dictionary [ d ] ) return s [ : - 1 ] | 0 | python dictionary to query string | Converts a dict to a querystring suitable to be appended to a URL . | cosqa-train-194 | def dict_to_querystring(dictionary):
"""Converts a dict to a querystring suitable to be appended to a URL."""
s = u""
for d in dictionary.keys():
s = unicode.format(u"{0}{1}={2}&", s, d, dictionary[d])
return s[:-1] |
def _check_elements_equal ( lst ) : assert isinstance ( lst , list ) , "Input value must be a list." return not lst or lst . count ( lst [ 0 ] ) == len ( lst ) | 0 | check if all elements in a list are the same python | Returns true if all of the elements in the list are equal . | cosqa-train-195 | def _check_elements_equal(lst):
"""
Returns true if all of the elements in the list are equal.
"""
assert isinstance(lst, list), "Input value must be a list."
return not lst or lst.count(lst[0]) == len(lst) |
def dict_to_querystring ( dictionary ) : s = u"" for d in dictionary . keys ( ) : s = unicode . format ( u"{0}{1}={2}&" , s , d , dictionary [ d ] ) return s [ : - 1 ] | 0 | python dictionary to querystring | Converts a dict to a querystring suitable to be appended to a URL . | cosqa-train-196 | def dict_to_querystring(dictionary):
"""Converts a dict to a querystring suitable to be appended to a URL."""
s = u""
for d in dictionary.keys():
s = unicode.format(u"{0}{1}={2}&", s, d, dictionary[d])
return s[:-1] |
def _check_elements_equal ( lst ) : assert isinstance ( lst , list ) , "Input value must be a list." return not lst or lst . count ( lst [ 0 ] ) == len ( lst ) | 0 | check if all elements in list are same python | Returns true if all of the elements in the list are equal . | cosqa-train-197 | def _check_elements_equal(lst):
"""
Returns true if all of the elements in the list are equal.
"""
assert isinstance(lst, list), "Input value must be a list."
return not lst or lst.count(lst[0]) == len(lst) |
def nonull_dict ( self ) : return { k : v for k , v in six . iteritems ( self . dict ) if v and k != '_codes' } | 0 | python dictionary with keys but no values | Like dict but does not hold any null values . | cosqa-train-198 | def nonull_dict(self):
"""Like dict, but does not hold any null values.
:return:
"""
return {k: v for k, v in six.iteritems(self.dict) if v and k != '_codes'} |
def updateFromKwargs ( self , properties , kwargs , collector , * * unused ) : properties [ self . name ] = self . getFromKwargs ( kwargs ) | 0 | python dictonary as kwargs | Primary entry point to turn kwargs into properties | cosqa-train-199 | def updateFromKwargs(self, properties, kwargs, collector, **unused):
"""Primary entry point to turn 'kwargs' into 'properties'"""
properties[self.name] = self.getFromKwargs(kwargs) |