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 forceupdate ( self , * args , * * kw ) : self . _update ( False , self . _ON_DUP_OVERWRITE , * args , * * kw )
| 0 |
python sql server bulk update
|
Like a bulk : meth : forceput .
|
cosqa-train-16200
|
def forceupdate(self, *args, **kw):
"""Like a bulk :meth:`forceput`."""
self._update(False, self._ON_DUP_OVERWRITE, *args, **kw)
|
def rotateImage ( image , angle ) : image = [ list ( row ) for row in image ] for n in range ( angle % 4 ) : image = list ( zip ( * image [ : : - 1 ] ) ) return image
| 1 |
how to rotate an array 90 degrees in python
|
rotates a 2d array to a multiple of 90 deg . 0 = default 1 = 90 deg . cw 2 = 180 deg . 3 = 90 deg . ccw
|
cosqa-train-16201
|
def rotateImage(image, angle):
"""
rotates a 2d array to a multiple of 90 deg.
0 = default
1 = 90 deg. cw
2 = 180 deg.
3 = 90 deg. ccw
"""
image = [list(row) for row in image]
for n in range(angle % 4):
image = list(zip(*image[::-1]))
return image
|
def _shutdown_transport ( self ) : if self . sock is not None : try : unwrap = self . sock . unwrap except AttributeError : return try : self . sock = unwrap ( ) except ValueError : # Failure within SSL might mean unwrap exists but socket is not # deemed wrapped pass
| 0 |
python sslconnection reset by peer
|
Unwrap a Python 2 . 6 SSL socket so we can call shutdown ()
|
cosqa-train-16202
|
def _shutdown_transport(self):
"""Unwrap a Python 2.6 SSL socket, so we can call shutdown()"""
if self.sock is not None:
try:
unwrap = self.sock.unwrap
except AttributeError:
return
try:
self.sock = unwrap()
except ValueError:
# Failure within SSL might mean unwrap exists but socket is not
# deemed wrapped
pass
|
def rotateImage ( img , angle ) : imgR = scipy . ndimage . rotate ( img , angle , reshape = False ) return imgR
| 1 |
how to rotate an image clockwise in python
|
cosqa-train-16203
|
def rotateImage(img, angle):
"""
querries scipy.ndimage.rotate routine
:param img: image to be rotated
:param angle: angle to be rotated (radian)
:return: rotated image
"""
imgR = scipy.ndimage.rotate(img, angle, reshape=False)
return imgR
|
|
def column_stack_2d ( data ) : return list ( list ( itt . chain . from_iterable ( _ ) ) for _ in zip ( * data ) )
| 0 |
python stack multiple datasets together
|
Perform column - stacking on a list of 2d data blocks .
|
cosqa-train-16204
|
def column_stack_2d(data):
"""Perform column-stacking on a list of 2d data blocks."""
return list(list(itt.chain.from_iterable(_)) for _ in zip(*data))
|
def round_figures ( x , n ) : return round ( x , int ( n - math . ceil ( math . log10 ( abs ( x ) ) ) ) )
| 0 |
how to round significant figures in python
|
Returns x rounded to n significant figures .
|
cosqa-train-16205
|
def round_figures(x, n):
"""Returns x rounded to n significant figures."""
return round(x, int(n - math.ceil(math.log10(abs(x)))))
|
def start ( ) : global app bottle . run ( app , host = conf . WebHost , port = conf . WebPort , debug = conf . WebAutoReload , reloader = conf . WebAutoReload , quiet = conf . WebQuiet )
| 0 |
python start bottle server in background
|
Starts the web server .
|
cosqa-train-16206
|
def start():
"""Starts the web server."""
global app
bottle.run(app, host=conf.WebHost, port=conf.WebPort,
debug=conf.WebAutoReload, reloader=conf.WebAutoReload,
quiet=conf.WebQuiet)
|
def round_sig ( x , sig ) : return round ( x , sig - int ( floor ( log10 ( abs ( x ) ) ) ) - 1 )
| 1 |
how to round to certain number of sig figs in python
|
Round the number to the specified number of significant figures
|
cosqa-train-16207
|
def round_sig(x, sig):
"""Round the number to the specified number of significant figures"""
return round(x, sig - int(floor(log10(abs(x)))) - 1)
|
def _callable_once ( func ) : def once ( * args , * * kwargs ) : if not once . called : once . called = True return func ( * args , * * kwargs ) once . called = False return once
| 0 |
python stop a function from calling twice
|
Returns a function that is only callable once ; any other call will do nothing
|
cosqa-train-16208
|
def _callable_once(func):
""" Returns a function that is only callable once; any other call will do nothing """
def once(*args, **kwargs):
if not once.called:
once.called = True
return func(*args, **kwargs)
once.called = False
return once
|
def getFunction ( self ) : return functionFactory ( self . code , self . name , self . defaults , self . globals , self . imports , )
| 0 |
python store a function as variable
|
Called by remote workers . Useful to populate main module globals () for interactive shells . Retrieves the serialized function .
|
cosqa-train-16209
|
def getFunction(self):
"""Called by remote workers. Useful to populate main module globals()
for interactive shells. Retrieves the serialized function."""
return functionFactory(
self.code,
self.name,
self.defaults,
self.globals,
self.imports,
)
|
def get_code ( module ) : fp = open ( module . path ) try : return compile ( fp . read ( ) , str ( module . name ) , 'exec' ) finally : fp . close ( )
| 0 |
how to run a python compiled file
|
Compile and return a Module s code object .
|
cosqa-train-16210
|
def get_code(module):
"""
Compile and return a Module's code object.
"""
fp = open(module.path)
try:
return compile(fp.read(), str(module.name), 'exec')
finally:
fp.close()
|
def _session_set ( self , key , value ) : self . session [ self . _session_key ( key ) ] = value
| 1 |
python storing session based information
|
Saves a value to session .
|
cosqa-train-16211
|
def _session_set(self, key, value):
"""
Saves a value to session.
"""
self.session[self._session_key(key)] = value
|
def test ( ) : import unittest tests = unittest . TestLoader ( ) . discover ( 'tests' ) unittest . TextTestRunner ( verbosity = 2 ) . run ( tests )
| 1 |
how to run python unittests
|
Run the unit tests .
|
cosqa-train-16212
|
def test():
"""Run the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
|
def __str__ ( self ) : if not hasattr ( self , '_str' ) : self . _str = self . function ( * self . args , * * self . kwargs ) return self . _str
| 0 |
python str object not callable
|
Executes self . function to convert LazyString instance to a real str .
|
cosqa-train-16213
|
def __str__(self):
"""Executes self.function to convert LazyString instance to a real
str."""
if not hasattr(self, '_str'):
self._str=self.function(*self.args, **self.kwargs)
return self._str
|
def write_json_corpus ( documents , fnm ) : with codecs . open ( fnm , 'wb' , 'ascii' ) as f : for document in documents : f . write ( json . dumps ( document ) + '\n' ) return documents
| 1 |
how to save a corpus in python
|
Write a lisst of Text instances as JSON corpus on disk . A JSON corpus contains one document per line encoded in JSON .
|
cosqa-train-16214
|
def write_json_corpus(documents, fnm):
"""Write a lisst of Text instances as JSON corpus on disk.
A JSON corpus contains one document per line, encoded in JSON.
Parameters
----------
documents: iterable of estnltk.text.Text
The documents of the corpus
fnm: str
The path to save the corpus.
"""
with codecs.open(fnm, 'wb', 'ascii') as f:
for document in documents:
f.write(json.dumps(document) + '\n')
return documents
|
def quote ( self , s ) : if six . PY2 : from pipes import quote else : from shlex import quote return quote ( s )
| 0 |
python str pass to shell lost quote
|
Return a shell - escaped version of the string s .
|
cosqa-train-16215
|
def quote(self, s):
"""Return a shell-escaped version of the string s."""
if six.PY2:
from pipes import quote
else:
from shlex import quote
return quote(s)
|
def save_keras_definition ( keras_model , path ) : model_json = keras_model . to_json ( ) with open ( path , "w" ) as json_file : json_file . write ( model_json )
| 0 |
how to save a keras model in python
|
Save a Keras model definition to JSON with given path
|
cosqa-train-16216
|
def save_keras_definition(keras_model, path):
"""
Save a Keras model definition to JSON with given path
"""
model_json = keras_model.to_json()
with open(path, "w") as json_file:
json_file.write(model_json)
|
def strip_accents ( text ) : normalized_str = unicodedata . normalize ( 'NFD' , text ) return '' . join ( [ c for c in normalized_str if unicodedata . category ( c ) != 'Mn' ] )
| 0 |
python str remove all non allowed character
|
Strip agents from a string .
|
cosqa-train-16217
|
def strip_accents(text):
"""
Strip agents from a string.
"""
normalized_str = unicodedata.normalize('NFD', text)
return ''.join([
c for c in normalized_str if unicodedata.category(c) != 'Mn'])
|
def save ( variable , filename ) : fileObj = open ( filename , 'wb' ) pickle . dump ( variable , fileObj ) fileObj . close ( )
| 1 |
how to save a python variable as a text file
|
Save variable on given path using Pickle Args : variable : what to save path ( str ) : path of the output
|
cosqa-train-16218
|
def save(variable, filename):
"""Save variable on given path using Pickle
Args:
variable: what to save
path (str): path of the output
"""
fileObj = open(filename, 'wb')
pickle.dump(variable, fileObj)
fileObj.close()
|
def get_connection ( self , host , port , db ) : return redis . StrictRedis ( host = host , port = port , db = db , decode_responses = True )
| 1 |
python strictredis redis password
|
Returns a StrictRedis connection instance .
|
cosqa-train-16219
|
def get_connection(self, host, port, db):
"""
Returns a ``StrictRedis`` connection instance.
"""
return redis.StrictRedis(
host=host,
port=port,
db=db,
decode_responses=True
)
|
def file_to_png ( fp ) : import PIL . Image # pylint: disable=import-error with io . BytesIO ( ) as dest : PIL . Image . open ( fp ) . save ( dest , "PNG" , optimize = True ) return dest . getvalue ( )
| 1 |
how to save an image back into file python
|
Convert an image to PNG format with Pillow . : arg file - like fp : The image file . : rtype : bytes
|
cosqa-train-16220
|
def file_to_png(fp):
"""Convert an image to PNG format with Pillow.
:arg file-like fp: The image file.
:rtype: bytes
"""
import PIL.Image # pylint: disable=import-error
with io.BytesIO() as dest:
PIL.Image.open(fp).save(dest, "PNG", optimize=True)
return dest.getvalue()
|
def str_dict ( some_dict ) : return { str ( k ) : str ( v ) for k , v in some_dict . items ( ) }
| 0 |
python string converts dict
|
Convert dict of ascii str / unicode to dict of str if necessary
|
cosqa-train-16221
|
def str_dict(some_dict):
"""Convert dict of ascii str/unicode to dict of str, if necessary"""
return {str(k): str(v) for k, v in some_dict.items()}
|
def is_cached ( file_name ) : gml_file_path = join ( join ( expanduser ( '~' ) , OCTOGRID_DIRECTORY ) , file_name ) return isfile ( gml_file_path )
| 0 |
how to see if a value exists in python fcache
|
Check if a given file is available in the cache or not
|
cosqa-train-16222
|
def is_cached(file_name):
"""
Check if a given file is available in the cache or not
"""
gml_file_path = join(join(expanduser('~'), OCTOGRID_DIRECTORY), file_name)
return isfile(gml_file_path)
|
def clean_float ( v ) : if v is None or not str ( v ) . strip ( ) : return None return float ( str ( v ) . replace ( ',' , '' ) )
| 0 |
python string formatting null or float
|
Remove commas from a float
|
cosqa-train-16223
|
def clean_float(v):
"""Remove commas from a float"""
if v is None or not str(v).strip():
return None
return float(str(v).replace(',', ''))
|
def test ( ) : from spyder . utils . qthelpers import qapplication app = qapplication ( ) dlg = ProjectDialog ( None ) dlg . show ( ) sys . exit ( app . exec_ ( ) )
| 0 |
how to see python code in spyder
|
Local test .
|
cosqa-train-16224
|
def test():
"""Local test."""
from spyder.utils.qthelpers import qapplication
app = qapplication()
dlg = ProjectDialog(None)
dlg.show()
sys.exit(app.exec_())
|
def findLastCharIndexMatching ( text , func ) : for i in range ( len ( text ) - 1 , - 1 , - 1 ) : if func ( text [ i ] ) : return i
| 0 |
python string last match index
|
Return index of last character in string for which func ( char ) evaluates to True .
|
cosqa-train-16225
|
def findLastCharIndexMatching(text, func):
""" Return index of last character in string for which func(char) evaluates to True. """
for i in range(len(text) - 1, -1, -1):
if func(text[i]):
return i
|
def select_from_array ( cls , array , identifier ) : base_array = np . zeros ( array . shape ) array_coords = np . where ( array == identifier ) base_array [ array_coords ] = 1 return cls ( base_array )
| 1 |
how to select region in array python
|
Return a region from a numpy array . : param array : : class : numpy . ndarray : param identifier : value representing the region to select in the array : returns : : class : jicimagelib . region . Region
|
cosqa-train-16226
|
def select_from_array(cls, array, identifier):
"""Return a region from a numpy array.
:param array: :class:`numpy.ndarray`
:param identifier: value representing the region to select in the array
:returns: :class:`jicimagelib.region.Region`
"""
base_array = np.zeros(array.shape)
array_coords = np.where(array == identifier)
base_array[array_coords] = 1
return cls(base_array)
|
def md5_string ( s ) : m = hashlib . md5 ( ) m . update ( s ) return str ( m . hexdigest ( ) )
| 0 |
python string md5 hashing
|
Shortcut to create md5 hash : param s : : return :
|
cosqa-train-16227
|
def md5_string(s):
"""
Shortcut to create md5 hash
:param s:
:return:
"""
m = hashlib.md5()
m.update(s)
return str(m.hexdigest())
|
def unique_element ( ll ) : seen = { } result = [ ] for item in ll : if item in seen : continue seen [ item ] = 1 result . append ( item ) return result
| 0 |
how to select unique elements froma list in python
|
returns unique elements from a list preserving the original order
|
cosqa-train-16228
|
def unique_element(ll):
""" returns unique elements from a list preserving the original order """
seen = {}
result = []
for item in ll:
if item in seen:
continue
seen[item] = 1
result.append(item)
return result
|
def _count_leading_whitespace ( text ) : idx = 0 for idx , char in enumerate ( text ) : if not char . isspace ( ) : return idx return idx + 1
| 1 |
python string method to count whitespace
|
Returns the number of characters at the beginning of text that are whitespace .
|
cosqa-train-16229
|
def _count_leading_whitespace(text):
"""Returns the number of characters at the beginning of text that are whitespace."""
idx = 0
for idx, char in enumerate(text):
if not char.isspace():
return idx
return idx + 1
|
def close ( self ) : if self . _subprocess is not None : os . killpg ( self . _subprocess . pid , signal . SIGTERM ) self . _subprocess = None
| 1 |
how to self close process in python
|
Close child subprocess
|
cosqa-train-16230
|
def close(self):
"""Close child subprocess"""
if self._subprocess is not None:
os.killpg(self._subprocess.pid, signal.SIGTERM)
self._subprocess = None
|
def _convert_to_float_if_possible ( s ) : try : ret = float ( s ) except ( ValueError , TypeError ) : ret = s return ret
| 0 |
python string to float or nan
|
A small helper function to convert a string to a numeric value if appropriate
|
cosqa-train-16231
|
def _convert_to_float_if_possible(s):
"""
A small helper function to convert a string to a numeric value
if appropriate
:param s: the string to be converted
:type s: str
"""
try:
ret = float(s)
except (ValueError, TypeError):
ret = s
return ret
|
def add_to_js ( self , name , var ) : frame = self . page ( ) . mainFrame ( ) frame . addToJavaScriptWindowObject ( name , var )
| 0 |
how to send a javascript object to python
|
Add an object to Javascript .
|
cosqa-train-16232
|
def add_to_js(self, name, var):
"""Add an object to Javascript."""
frame = self.page().mainFrame()
frame.addToJavaScriptWindowObject(name, var)
|
def lin_interp ( x , rangeX , rangeY ) : s = ( x - rangeX [ 0 ] ) / mag ( rangeX [ 1 ] - rangeX [ 0 ] ) y = rangeY [ 0 ] * ( 1 - s ) + rangeY [ 1 ] * s return y
| 0 |
python string to interpolation
|
Interpolate linearly variable x in rangeX onto rangeY .
|
cosqa-train-16233
|
def lin_interp(x, rangeX, rangeY):
"""
Interpolate linearly variable x in rangeX onto rangeY.
"""
s = (x - rangeX[0]) / mag(rangeX[1] - rangeX[0])
y = rangeY[0] * (1 - s) + rangeY[1] * s
return y
|
def process_kill ( pid , sig = None ) : sig = sig or signal . SIGTERM os . kill ( pid , sig )
| 0 |
how to send signal to kill a process in python
|
Send signal to process .
|
cosqa-train-16234
|
def process_kill(pid, sig=None):
"""Send signal to process.
"""
sig = sig or signal.SIGTERM
os.kill(pid, sig)
|
def parse_case_snake_to_camel ( snake , upper_first = True ) : snake = snake . split ( '_' ) first_part = snake [ 0 ] if upper_first : first_part = first_part . title ( ) return first_part + '' . join ( word . title ( ) for word in snake [ 1 : ] )
| 0 |
python string uppercase first letter
|
Convert a string from snake_case to CamelCase .
|
cosqa-train-16235
|
def parse_case_snake_to_camel(snake, upper_first=True):
"""
Convert a string from snake_case to CamelCase.
:param str snake: The snake_case string to convert.
:param bool upper_first: Whether or not to capitalize the first
character of the string.
:return: The CamelCase version of string.
:rtype: str
"""
snake = snake.split('_')
first_part = snake[0]
if upper_first:
first_part = first_part.title()
return first_part + ''.join(word.title() for word in snake[1:])
|
def destroy ( self ) : if self . session_type == 'bash' : # TODO: does this work/handle already being logged out/logged in deep OK? self . logout ( ) elif self . session_type == 'vagrant' : # TODO: does this work/handle already being logged out/logged in deep OK? self . logout ( )
| 0 |
how to session log in python
|
Finish up a session .
|
cosqa-train-16236
|
def destroy(self):
"""Finish up a session.
"""
if self.session_type == 'bash':
# TODO: does this work/handle already being logged out/logged in deep OK?
self.logout()
elif self.session_type == 'vagrant':
# TODO: does this work/handle already being logged out/logged in deep OK?
self.logout()
|
def get_stripped_file_lines ( filename ) : try : lines = open ( filename ) . readlines ( ) except FileNotFoundError : fatal ( "Could not open file: {!r}" . format ( filename ) ) return [ line . strip ( ) for line in lines ]
| 1 |
python strip new lines while reading file
|
Return lines of a file with whitespace removed
|
cosqa-train-16237
|
def get_stripped_file_lines(filename):
"""
Return lines of a file with whitespace removed
"""
try:
lines = open(filename).readlines()
except FileNotFoundError:
fatal("Could not open file: {!r}".format(filename))
return [line.strip() for line in lines]
|
def text_remove_empty_lines ( text ) : lines = [ line . rstrip ( ) for line in text . splitlines ( ) if line . strip ( ) ] return "\n" . join ( lines )
| 1 |
python strip non space whitespace
|
Whitespace normalization :
|
cosqa-train-16238
|
def text_remove_empty_lines(text):
"""
Whitespace normalization:
- Strip empty lines
- Strip trailing whitespace
"""
lines = [ line.rstrip() for line in text.splitlines() if line.strip() ]
return "\n".join(lines)
|
def ylim ( self , low , high , index = 1 ) : self . layout [ 'yaxis' + str ( index ) ] [ 'range' ] = [ low , high ] return self
| 0 |
how to set axis range in python plot
|
Set yaxis limits .
|
cosqa-train-16239
|
def ylim(self, low, high, index=1):
"""Set yaxis limits.
Parameters
----------
low : number
high : number
index : int, optional
Returns
-------
Chart
"""
self.layout['yaxis' + str(index)]['range'] = [low, high]
return self
|
def _repr_strip ( mystring ) : r = repr ( mystring ) if r . startswith ( "'" ) and r . endswith ( "'" ) : return r [ 1 : - 1 ] else : return r
| 0 |
python strip single quote from string output
|
Returns the string without any initial or final quotes .
|
cosqa-train-16240
|
def _repr_strip(mystring):
"""
Returns the string without any initial or final quotes.
"""
r = repr(mystring)
if r.startswith("'") and r.endswith("'"):
return r[1:-1]
else:
return r
|
def ylim ( self , low , high , index = 1 ) : self . layout [ 'yaxis' + str ( index ) ] [ 'range' ] = [ low , high ] return self
| 1 |
how to set axis range on graphs in python
|
Set yaxis limits .
|
cosqa-train-16241
|
def ylim(self, low, high, index=1):
"""Set yaxis limits.
Parameters
----------
low : number
high : number
index : int, optional
Returns
-------
Chart
"""
self.layout['yaxis' + str(index)]['range'] = [low, high]
return self
|
def barray ( iterlines ) : lst = [ line . encode ( 'utf-8' ) for line in iterlines ] arr = numpy . array ( lst ) return arr
| 0 |
python style multiline array
|
Array of bytes
|
cosqa-train-16242
|
def barray(iterlines):
"""
Array of bytes
"""
lst = [line.encode('utf-8') for line in iterlines]
arr = numpy.array(lst)
return arr
|
def set_gradclip_const ( self , min_value , max_value ) : callBigDlFunc ( self . bigdl_type , "setConstantClip" , self . value , min_value , max_value )
| 0 |
how to set clipping thresholds automatcally python
|
Configure constant clipping settings .
|
cosqa-train-16243
|
def set_gradclip_const(self, min_value, max_value):
"""
Configure constant clipping settings.
:param min_value: the minimum value to clip by
:param max_value: the maxmimum value to clip by
"""
callBigDlFunc(self.bigdl_type, "setConstantClip", self.value, min_value, max_value)
|
def show_xticklabels ( self , row , column ) : subplot = self . get_subplot_at ( row , column ) subplot . show_xticklabels ( )
| 0 |
python subplot no padding for xticks
|
Show the x - axis tick labels for a subplot .
|
cosqa-train-16244
|
def show_xticklabels(self, row, column):
"""Show the x-axis tick labels for a subplot.
:param row,column: specify the subplot.
"""
subplot = self.get_subplot_at(row, column)
subplot.show_xticklabels()
|
def connect ( self ) : self . socket = socket . create_connection ( self . address , self . timeout )
| 0 |
how to set connection timeout in python
|
Connects to the given host
|
cosqa-train-16245
|
def connect(self):
"""Connects to the given host"""
self.socket = socket.create_connection(self.address, self.timeout)
|
def kill_all ( self , kill_signal , kill_shell = False ) : for key in self . processes . keys ( ) : self . kill_process ( key , kill_signal , kill_shell )
| 0 |
python subprocess kill all the processes
|
Kill all running processes .
|
cosqa-train-16246
|
def kill_all(self, kill_signal, kill_shell=False):
"""Kill all running processes."""
for key in self.processes.keys():
self.kill_process(key, kill_signal, kill_shell)
|
def set_cursor_position ( self , position ) : position = self . get_position ( position ) cursor = self . textCursor ( ) cursor . setPosition ( position ) self . setTextCursor ( cursor ) self . ensureCursorVisible ( )
| 0 |
how to set cursor location in python
|
Set cursor position
|
cosqa-train-16247
|
def set_cursor_position(self, position):
"""Set cursor position"""
position = self.get_position(position)
cursor = self.textCursor()
cursor.setPosition(position)
self.setTextCursor(cursor)
self.ensureCursorVisible()
|
def _finish ( self ) : if self . _process . returncode is None : self . _process . stdin . flush ( ) self . _process . stdin . close ( ) self . _process . wait ( ) self . closed = True
| 0 |
python subprocess open can not kill
|
Closes and waits for subprocess to exit .
|
cosqa-train-16248
|
def _finish(self):
"""
Closes and waits for subprocess to exit.
"""
if self._process.returncode is None:
self._process.stdin.flush()
self._process.stdin.close()
self._process.wait()
self.closed = True
|
def _set_axis_limits ( self , which , lims , d , scale , reverse = False ) : setattr ( self . limits , which + 'lims' , lims ) setattr ( self . limits , 'd' + which , d ) setattr ( self . limits , which + 'scale' , scale ) if reverse : setattr ( self . limits , 'reverse_' + which + '_axis' , True ) return
| 1 |
how to set limits on axis in python
|
Private method for setting axis limits .
|
cosqa-train-16249
|
def _set_axis_limits(self, which, lims, d, scale, reverse=False):
"""Private method for setting axis limits.
Sets the axis limits on each axis for an individual plot.
Args:
which (str): The indicator of which part of the plots
to adjust. This currently handles `x` and `y`.
lims (len-2 list of floats): The limits for the axis.
d (float): Amount to increment by between the limits.
scale (str): Scale of the axis. Either `log` or `lin`.
reverse (bool, optional): If True, reverse the axis tick marks. Default is False.
"""
setattr(self.limits, which + 'lims', lims)
setattr(self.limits, 'd' + which, d)
setattr(self.limits, which + 'scale', scale)
if reverse:
setattr(self.limits, 'reverse_' + which + '_axis', True)
return
|
def downsample_with_striding ( array , factor ) : return array [ tuple ( np . s_ [ : : f ] for f in factor ) ]
| 0 |
python subsample replaced with strides
|
Downsample x by factor using striding .
|
cosqa-train-16250
|
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 relative_path ( path ) : return os . path . join ( os . path . dirname ( __file__ ) , path )
| 1 |
how to set path of a file in python
|
Return the given path relative to this file .
|
cosqa-train-16251
|
def relative_path(path):
"""
Return the given path relative to this file.
"""
return os.path.join(os.path.dirname(__file__), path)
|
def dropna ( self , subset = None ) : subset = check_and_obtain_subset_columns ( subset , self ) not_nas = [ v . notna ( ) for v in self [ subset ] . _iter ( ) ] and_filter = reduce ( lambda x , y : x & y , not_nas ) return self [ and_filter ]
| 0 |
python subset of a column not missing values and not zero
|
Remove missing values according to Baloo s convention .
|
cosqa-train-16252
|
def dropna(self, subset=None):
"""Remove missing values according to Baloo's convention.
Parameters
----------
subset : list of str, optional
Which columns to check for missing values in.
Returns
-------
DataFrame
DataFrame with no null values in columns.
"""
subset = check_and_obtain_subset_columns(subset, self)
not_nas = [v.notna() for v in self[subset]._iter()]
and_filter = reduce(lambda x, y: x & y, not_nas)
return self[and_filter]
|
def GetPythonLibraryDirectoryPath ( ) : path = sysconfig . get_python_lib ( True ) _ , _ , path = path . rpartition ( sysconfig . PREFIX ) if path . startswith ( os . sep ) : path = path [ 1 : ] return path
| 1 |
how to set python libary path on linux
|
Retrieves the Python library directory path .
|
cosqa-train-16253
|
def GetPythonLibraryDirectoryPath():
"""Retrieves the Python library directory path."""
path = sysconfig.get_python_lib(True)
_, _, path = path.rpartition(sysconfig.PREFIX)
if path.startswith(os.sep):
path = path[1:]
return path
|
def dump_parent ( self , obj ) : if not self . _is_parent ( obj ) : return self . _dump_relative ( obj . pid ) return None
| 0 |
python super get parent attribute
|
Dump the parent of a PID .
|
cosqa-train-16254
|
def dump_parent(self, obj):
"""Dump the parent of a PID."""
if not self._is_parent(obj):
return self._dump_relative(obj.pid)
return None
|
def title ( msg ) : if sys . platform . startswith ( "win" ) : ctypes . windll . kernel32 . SetConsoleTitleW ( tounicode ( msg ) )
| 0 |
how to set title of window in python in windows 10
|
Sets the title of the console window .
|
cosqa-train-16255
|
def title(msg):
"""Sets the title of the console window."""
if sys.platform.startswith("win"):
ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg))
|
def disown ( cmd ) : subprocess . Popen ( cmd , stdout = subprocess . DEVNULL , stderr = subprocess . DEVNULL )
| 0 |
python suppress subprocess stor dont print
|
Call a system command in the background disown it and hide it s output .
|
cosqa-train-16256
|
def disown(cmd):
"""Call a system command in the background,
disown it and hide it's output."""
subprocess.Popen(cmd,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
|
def sort_fn_list ( fn_list ) : dt_list = get_dt_list ( fn_list ) fn_list_sort = [ fn for ( dt , fn ) in sorted ( zip ( dt_list , fn_list ) ) ] return fn_list_sort
| 0 |
how to sort a list of datetime in python
|
Sort input filename list by datetime
|
cosqa-train-16257
|
def sort_fn_list(fn_list):
"""Sort input filename list by datetime
"""
dt_list = get_dt_list(fn_list)
fn_list_sort = [fn for (dt,fn) in sorted(zip(dt_list,fn_list))]
return fn_list_sort
|
def test_SVD ( pca ) : _ = pca rec = N . dot ( _ . U , N . dot ( _ . sigma , _ . V ) ) assert N . allclose ( _ . arr , rec )
| 0 |
python svd failing because of numpy dependcies
|
Function to test the validity of singular value decomposition by reconstructing original data .
|
cosqa-train-16258
|
def test_SVD(pca):
"""
Function to test the validity of singular
value decomposition by reconstructing original
data.
"""
_ = pca
rec = N.dot(_.U,N.dot(_.sigma,_.V))
assert N.allclose(_.arr,rec)
|
def sort_data ( data , cols ) : return data . sort_values ( cols ) [ cols + [ 'value' ] ] . reset_index ( drop = True )
| 1 |
how to sort data within a column python
|
Sort data rows and order columns
|
cosqa-train-16259
|
def sort_data(data, cols):
"""Sort `data` rows and order columns"""
return data.sort_values(cols)[cols + ['value']].reset_index(drop=True)
|
def inside_softimage ( ) : try : import maya return False except ImportError : pass try : from win32com . client import Dispatch as disp disp ( 'XSI.Application' ) return True except : return False
| 1 |
python syas im running win32
|
Returns a boolean indicating if the code is executed inside softimage .
|
cosqa-train-16260
|
def inside_softimage():
"""Returns a boolean indicating if the code is executed inside softimage."""
try:
import maya
return False
except ImportError:
pass
try:
from win32com.client import Dispatch as disp
disp('XSI.Application')
return True
except:
return False
|
def set_float ( self , option , value ) : if not isinstance ( value , float ) : raise TypeError ( "Value must be a float" ) self . options [ option ] = value
| 1 |
how to specify a float number python
|
Set a float option .
|
cosqa-train-16261
|
def set_float(self, option, value):
"""Set a float option.
Args:
option (str): name of option.
value (float): value of the option.
Raises:
TypeError: Value must be a float.
"""
if not isinstance(value, float):
raise TypeError("Value must be a float")
self.options[option] = value
|
def symbols ( ) : symbols = [ ] for line in symbols_stream ( ) : symbols . append ( line . decode ( 'utf-8' ) . strip ( ) ) return symbols
| 0 |
python symbols and what do they do
|
Return a list of symbols .
|
cosqa-train-16262
|
def symbols():
"""Return a list of symbols."""
symbols = []
for line in symbols_stream():
symbols.append(line.decode('utf-8').strip())
return symbols
|
def tokenize_list ( self , text ) : return [ self . get_record_token ( record ) for record in self . analyze ( text ) ]
| 0 |
how to split list into words in python
|
Split a text into separate words .
|
cosqa-train-16263
|
def tokenize_list(self, text):
"""
Split a text into separate words.
"""
return [self.get_record_token(record) for record in self.analyze(text)]
|
def split_multiline ( value ) : return [ element for element in ( line . strip ( ) for line in value . split ( '\n' ) ) if element ]
| 1 |
how to split multiple lines of strings in python
|
Split a multiline string into a list excluding blank lines .
|
cosqa-train-16264
|
def split_multiline(value):
"""Split a multiline string into a list, excluding blank lines."""
return [element for element in (line.strip() for line in value.split('\n'))
if element]
|
def main ( argv = None ) : args = parse_arguments ( sys . argv if argv is None else argv ) tf . logging . set_verbosity ( tf . logging . INFO ) learn_runner . run ( experiment_fn = get_experiment_fn ( args ) , output_dir = args . job_dir )
| 0 |
python tensorflow suppress logging
|
Run a Tensorflow model on the Iris dataset .
|
cosqa-train-16265
|
def main(argv=None):
"""Run a Tensorflow model on the Iris dataset."""
args = parse_arguments(sys.argv if argv is None else argv)
tf.logging.set_verbosity(tf.logging.INFO)
learn_runner.run(
experiment_fn=get_experiment_fn(args),
output_dir=args.job_dir)
|
def column_stack_2d ( data ) : return list ( list ( itt . chain . from_iterable ( _ ) ) for _ in zip ( * data ) )
| 1 |
how to stack column arrays in python
|
Perform column - stacking on a list of 2d data blocks .
|
cosqa-train-16266
|
def column_stack_2d(data):
"""Perform column-stacking on a list of 2d data blocks."""
return list(list(itt.chain.from_iterable(_)) for _ in zip(*data))
|
def is_integer ( obj ) : if PYTHON3 : return isinstance ( obj , int ) return isinstance ( obj , ( int , long ) )
| 0 |
python testing the type of an object instance
|
Is this an integer .
|
cosqa-train-16267
|
def is_integer(obj):
"""Is this an integer.
:param object obj:
:return:
"""
if PYTHON3:
return isinstance(obj, int)
return isinstance(obj, (int, long))
|
def server ( port ) : args = [ 'python' , 'manage.py' , 'runserver' ] if port : args . append ( port ) run . main ( args )
| 0 |
how to start django in python
|
Start the Django dev server .
|
cosqa-train-16268
|
def server(port):
"""Start the Django dev server."""
args = ['python', 'manage.py', 'runserver']
if port:
args.append(port)
run.main(args)
|
def _writable_dir ( path ) : return os . path . isdir ( path ) and os . access ( path , os . W_OK )
| 1 |
python testing to see if a directory is writeable
|
Whether path is a directory to which the user has write access .
|
cosqa-train-16269
|
def _writable_dir(path):
"""Whether `path` is a directory, to which the user has write access."""
return os.path.isdir(path) and os.access(path, os.W_OK)
|
def timeout_thread_handler ( timeout , stop_event ) : stop_happened = stop_event . wait ( timeout ) if stop_happened is False : print ( "Killing program due to %f second timeout" % timeout ) os . _exit ( 2 )
| 1 |
how to stop running a infinite loop without closing program python
|
A background thread to kill the process if it takes too long .
|
cosqa-train-16270
|
def timeout_thread_handler(timeout, stop_event):
"""A background thread to kill the process if it takes too long.
Args:
timeout (float): The number of seconds to wait before killing
the process.
stop_event (Event): An optional event to cleanly stop the background
thread if required during testing.
"""
stop_happened = stop_event.wait(timeout)
if stop_happened is False:
print("Killing program due to %f second timeout" % timeout)
os._exit(2)
|
def remove_stopped_threads ( self ) : self . threads = [ t for t in self . threads if t . is_alive ( ) ]
| 0 |
python thread list won't clear
|
Remove the stopped threads from the internal thread list .
|
cosqa-train-16271
|
def remove_stopped_threads (self):
"""Remove the stopped threads from the internal thread list."""
self.threads = [t for t in self.threads if t.is_alive()]
|
def open_store_variable ( self , name , var ) : data = indexing . LazilyOuterIndexedArray ( CDMArrayWrapper ( name , self ) ) return Variable ( var . dimensions , data , { a : getattr ( var , a ) for a in var . ncattrs ( ) } )
| 0 |
how to store a list slice as a varable python numpy
|
Turn CDMRemote variable into something like a numpy . ndarray .
|
cosqa-train-16272
|
def open_store_variable(self, name, var):
"""Turn CDMRemote variable into something like a numpy.ndarray."""
data = indexing.LazilyOuterIndexedArray(CDMArrayWrapper(name, self))
return Variable(var.dimensions, data, {a: getattr(var, a) for a in var.ncattrs()})
|
def normalize_time ( timestamp ) : offset = timestamp . utcoffset ( ) if offset is None : return timestamp return timestamp . replace ( tzinfo = None ) - offset
| 0 |
python time adjust timezone
|
Normalize time in arbitrary timezone to UTC naive object .
|
cosqa-train-16273
|
def normalize_time(timestamp):
"""Normalize time in arbitrary timezone to UTC naive object."""
offset = timestamp.utcoffset()
if offset is None:
return timestamp
return timestamp.replace(tzinfo=None) - offset
|
def on_error ( e ) : # pragma: no cover exname = { 'RuntimeError' : 'Runtime error' , 'Value Error' : 'Value error' } sys . stderr . write ( '{}: {}\n' . format ( exname [ e . __class__ . __name__ ] , str ( e ) ) ) sys . stderr . write ( 'See file slam_error.log for additional details.\n' ) sys . exit ( 1 )
| 0 |
how to store all my python errors in a log file
|
Error handler
|
cosqa-train-16274
|
def on_error(e): # pragma: no cover
"""Error handler
RuntimeError or ValueError exceptions raised by commands will be handled
by this function.
"""
exname = {'RuntimeError': 'Runtime error', 'Value Error': 'Value error'}
sys.stderr.write('{}: {}\n'.format(exname[e.__class__.__name__], str(e)))
sys.stderr.write('See file slam_error.log for additional details.\n')
sys.exit(1)
|
def prevmonday ( num ) : today = get_today ( ) lastmonday = today - timedelta ( days = today . weekday ( ) , weeks = num ) return lastmonday
| 0 |
python time get the previous monday
|
Return unix SECOND timestamp of num mondays ago
|
cosqa-train-16275
|
def prevmonday(num):
"""
Return unix SECOND timestamp of "num" mondays ago
"""
today = get_today()
lastmonday = today - timedelta(days=today.weekday(), weeks=num)
return lastmonday
|
def _listify ( collection ) : new_list = [ ] for index in range ( len ( collection ) ) : new_list . append ( collection [ index ] ) return new_list
| 0 |
how to store list of arrays in python
|
This is a workaround where Collections are no longer iterable when using JPype .
|
cosqa-train-16276
|
def _listify(collection):
"""This is a workaround where Collections are no longer iterable
when using JPype."""
new_list = []
for index in range(len(collection)):
new_list.append(collection[index])
return new_list
|
def _shutdown_proc ( p , timeout ) : freq = 10 # how often to check per second for _ in range ( 1 + timeout * freq ) : ret = p . poll ( ) if ret is not None : logging . info ( "Shutdown gracefully." ) return ret time . sleep ( 1 / freq ) logging . warning ( "Killing the process." ) p . kill ( ) return p . wait ( )
| 1 |
python time limit to kill the process
|
Wait for a proc to shut down then terminate or kill it after timeout .
|
cosqa-train-16277
|
def _shutdown_proc(p, timeout):
"""Wait for a proc to shut down, then terminate or kill it after `timeout`."""
freq = 10 # how often to check per second
for _ in range(1 + timeout * freq):
ret = p.poll()
if ret is not None:
logging.info("Shutdown gracefully.")
return ret
time.sleep(1 / freq)
logging.warning("Killing the process.")
p.kill()
return p.wait()
|
def strip_accents ( string ) : return u'' . join ( ( character for character in unicodedata . normalize ( 'NFD' , string ) if unicodedata . category ( character ) != 'Mn' ) )
| 0 |
how to strip non alphanumeric characters python
|
Strip all the accents from the string
|
cosqa-train-16278
|
def strip_accents(string):
"""
Strip all the accents from the string
"""
return u''.join(
(character for character in unicodedata.normalize('NFD', string)
if unicodedata.category(character) != 'Mn'))
|
def to_unix ( cls , timestamp ) : if not isinstance ( timestamp , datetime . datetime ) : raise TypeError ( 'Time.milliseconds expects a datetime object' ) base = time . mktime ( timestamp . timetuple ( ) ) return base
| 1 |
python time struct to unix time
|
Wrapper over time module to produce Unix epoch time as a float
|
cosqa-train-16279
|
def to_unix(cls, timestamp):
""" Wrapper over time module to produce Unix epoch time as a float """
if not isinstance(timestamp, datetime.datetime):
raise TypeError('Time.milliseconds expects a datetime object')
base = time.mktime(timestamp.timetuple())
return base
|
def _repr_strip ( mystring ) : r = repr ( mystring ) if r . startswith ( "'" ) and r . endswith ( "'" ) : return r [ 1 : - 1 ] else : return r
| 0 |
how to strip single quote python
|
Returns the string without any initial or final quotes .
|
cosqa-train-16280
|
def _repr_strip(mystring):
"""
Returns the string without any initial or final quotes.
"""
r = repr(mystring)
if r.startswith("'") and r.endswith("'"):
return r[1:-1]
else:
return r
|
def normalize_time ( timestamp ) : offset = timestamp . utcoffset ( ) if offset is None : return timestamp return timestamp . replace ( tzinfo = None ) - offset
| 1 |
python time zone offset
|
Normalize time in arbitrary timezone to UTC naive object .
|
cosqa-train-16281
|
def normalize_time(timestamp):
"""Normalize time in arbitrary timezone to UTC naive object."""
offset = timestamp.utcoffset()
if offset is None:
return timestamp
return timestamp.replace(tzinfo=None) - offset
|
def split ( s ) : l = [ _split ( x ) for x in _SPLIT_RE . split ( s ) ] return [ item for sublist in l for item in sublist ]
| 0 |
how to strip spaces from string python
|
Uses dynamic programming to infer the location of spaces in a string without spaces .
|
cosqa-train-16282
|
def split(s):
"""Uses dynamic programming to infer the location of spaces in a string without spaces."""
l = [_split(x) for x in _SPLIT_RE.split(s)]
return [item for sublist in l for item in sublist]
|
def to_snake_case ( s ) : return re . sub ( '([^_A-Z])([A-Z])' , lambda m : m . group ( 1 ) + '_' + m . group ( 2 ) . lower ( ) , s )
| 0 |
how to swap letter cases in python
|
Converts camel - case identifiers to snake - case .
|
cosqa-train-16283
|
def to_snake_case(s):
"""Converts camel-case identifiers to snake-case."""
return re.sub('([^_A-Z])([A-Z])', lambda m: m.group(1) + '_' + m.group(2).lower(), s)
|
def keyReleaseEvent ( self , event ) : self . keyboard_event ( event . key ( ) , self . keys . ACTION_RELEASE , 0 )
| 1 |
python tkinter event keyrelease
|
Pyqt specific key release callback function . Translates and forwards events to : py : func : keyboard_event .
|
cosqa-train-16284
|
def keyReleaseEvent(self, event):
"""
Pyqt specific key release callback function.
Translates and forwards events to :py:func:`keyboard_event`.
"""
self.keyboard_event(event.key(), self.keys.ACTION_RELEASE, 0)
|
def _swap_rows ( self , i , j ) : L = np . eye ( 3 , dtype = 'intc' ) L [ i , i ] = 0 L [ j , j ] = 0 L [ i , j ] = 1 L [ j , i ] = 1 self . _L . append ( L . copy ( ) ) self . _A = np . dot ( L , self . _A )
| 0 |
how to swap rows and columns of a matrix in python
|
Swap i and j rows
|
cosqa-train-16285
|
def _swap_rows(self, i, j):
"""Swap i and j rows
As the side effect, determinant flips.
"""
L = np.eye(3, dtype='intc')
L[i, i] = 0
L[j, j] = 0
L[i, j] = 1
L[j, i] = 1
self._L.append(L.copy())
self._A = np.dot(L, self._A)
|
def _set_scroll_v ( self , * args ) : self . _canvas_categories . yview ( * args ) self . _canvas_scroll . yview ( * args )
| 1 |
python tkinter how to create scrollable canvas
|
Scroll both categories Canvas and scrolling container
|
cosqa-train-16286
|
def _set_scroll_v(self, *args):
"""Scroll both categories Canvas and scrolling container"""
self._canvas_categories.yview(*args)
self._canvas_scroll.yview(*args)
|
def input ( self , prompt , default = None , show_default = True ) : return click . prompt ( prompt , default = default , show_default = show_default )
| 0 |
how to switch the python prompt
|
Provide a command prompt .
|
cosqa-train-16287
|
def input(self, prompt, default=None, show_default=True):
"""Provide a command prompt."""
return click.prompt(prompt, default=default, show_default=show_default)
|
def askopenfilename ( * * kwargs ) : try : from Tkinter import Tk import tkFileDialog as filedialog except ImportError : from tkinter import Tk , filedialog root = Tk ( ) root . withdraw ( ) root . update ( ) filenames = filedialog . askopenfilename ( * * kwargs ) root . destroy ( ) return filenames
| 0 |
python tkinter open file dialog
|
Return file name ( s ) from Tkinter s file open dialog .
|
cosqa-train-16288
|
def askopenfilename(**kwargs):
"""Return file name(s) from Tkinter's file open dialog."""
try:
from Tkinter import Tk
import tkFileDialog as filedialog
except ImportError:
from tkinter import Tk, filedialog
root = Tk()
root.withdraw()
root.update()
filenames = filedialog.askopenfilename(**kwargs)
root.destroy()
return filenames
|
def get_dt_list ( fn_list ) : dt_list = np . array ( [ fn_getdatetime ( fn ) for fn in fn_list ] ) return dt_list
| 0 |
how to take date as array in python
|
Get list of datetime objects extracted from a filename
|
cosqa-train-16289
|
def get_dt_list(fn_list):
"""Get list of datetime objects, extracted from a filename
"""
dt_list = np.array([fn_getdatetime(fn) for fn in fn_list])
return dt_list
|
def toggle_word_wrap ( self ) : self . setWordWrapMode ( not self . wordWrapMode ( ) and QTextOption . WordWrap or QTextOption . NoWrap ) return True
| 0 |
python tkinter prevent text wrapping
|
Toggles document word wrap .
|
cosqa-train-16290
|
def toggle_word_wrap(self):
"""
Toggles document word wrap.
:return: Method success.
:rtype: bool
"""
self.setWordWrapMode(not self.wordWrapMode() and QTextOption.WordWrap or QTextOption.NoWrap)
return True
|
def unique_inverse ( item_list ) : import utool as ut unique_items = ut . unique ( item_list ) inverse = list_alignment ( unique_items , item_list ) return unique_items , inverse
| 0 |
how to take the inverse of a list in python
|
Like np . unique ( item_list return_inverse = True )
|
cosqa-train-16291
|
def unique_inverse(item_list):
"""
Like np.unique(item_list, return_inverse=True)
"""
import utool as ut
unique_items = ut.unique(item_list)
inverse = list_alignment(unique_items, item_list)
return unique_items, inverse
|
def hide ( self ) : self . tk . withdraw ( ) self . _visible = False if self . _modal : self . tk . grab_release ( )
| 0 |
python tkinter prevent window update
|
Hide the window .
|
cosqa-train-16292
|
def hide(self):
"""Hide the window."""
self.tk.withdraw()
self._visible = False
if self._modal:
self.tk.grab_release()
|
def forward ( self , step ) : x = self . pos_x + math . cos ( math . radians ( self . rotation ) ) * step y = self . pos_y + math . sin ( math . radians ( self . rotation ) ) * step prev_brush_state = self . brush_on self . brush_on = True self . move ( x , y ) self . brush_on = prev_brush_state
| 0 |
how to tell turtle python to move and draw
|
Move the turtle forward .
|
cosqa-train-16293
|
def forward(self, step):
"""Move the turtle forward.
:param step: Integer. Distance to move forward.
"""
x = self.pos_x + math.cos(math.radians(self.rotation)) * step
y = self.pos_y + math.sin(math.radians(self.rotation)) * step
prev_brush_state = self.brush_on
self.brush_on = True
self.move(x, y)
self.brush_on = prev_brush_state
|
def empty ( self ) : for k in list ( self . children . keys ( ) ) : self . remove_child ( self . children [ k ] )
| 0 |
python tkinter remove all existing widgets without destroying window
|
remove all children from the widget
|
cosqa-train-16294
|
def empty(self):
"""remove all children from the widget"""
for k in list(self.children.keys()):
self.remove_child(self.children[k])
|
def set_stop_handler ( self ) : signal . signal ( signal . SIGTERM , self . graceful_stop ) signal . signal ( signal . SIGABRT , self . graceful_stop ) signal . signal ( signal . SIGINT , self . graceful_stop )
| 0 |
how to terminate whole program in python from middle
|
Initializes functions that are invoked when the user or OS wants to kill this process . : return :
|
cosqa-train-16295
|
def set_stop_handler(self):
"""
Initializes functions that are invoked when the user or OS wants to kill this process.
:return:
"""
signal.signal(signal.SIGTERM, self.graceful_stop)
signal.signal(signal.SIGABRT, self.graceful_stop)
signal.signal(signal.SIGINT, self.graceful_stop)
|
def __init__ ( self , master = None , compound = tk . RIGHT , autohidescrollbar = True , * * kwargs ) : ttk . Frame . __init__ ( self , master ) self . columnconfigure ( 1 , weight = 1 ) self . rowconfigure ( 0 , weight = 1 ) self . listbox = tk . Listbox ( self , * * kwargs ) if autohidescrollbar : self . scrollbar = AutoHideScrollbar ( self , orient = tk . VERTICAL , command = self . listbox . yview ) else : self . scrollbar = ttk . Scrollbar ( self , orient = tk . VERTICAL , command = self . listbox . yview ) self . config_listbox ( yscrollcommand = self . scrollbar . set ) if compound is not tk . LEFT and compound is not tk . RIGHT : raise ValueError ( "Invalid compound value passed: {0}" . format ( compound ) ) self . __compound = compound self . _grid_widgets ( )
| 0 |
python tkinter scrollbar listbox grid
|
Create a Listbox with a vertical scrollbar .
|
cosqa-train-16296
|
def __init__(self, master=None, compound=tk.RIGHT, autohidescrollbar=True, **kwargs):
"""
Create a Listbox with a vertical scrollbar.
:param master: master widget
:type master: widget
:param compound: side for the Scrollbar to be on (:obj:`tk.LEFT` or :obj:`tk.RIGHT`)
:type compound: str
:param autohidescrollbar: whether to use an :class:`~ttkwidgets.AutoHideScrollbar` or a :class:`ttk.Scrollbar`
:type autohidescrollbar: bool
:param kwargs: keyword arguments passed on to the :class:`tk.Listbox` initializer
"""
ttk.Frame.__init__(self, master)
self.columnconfigure(1, weight=1)
self.rowconfigure(0, weight=1)
self.listbox = tk.Listbox(self, **kwargs)
if autohidescrollbar:
self.scrollbar = AutoHideScrollbar(self, orient=tk.VERTICAL, command=self.listbox.yview)
else:
self.scrollbar = ttk.Scrollbar(self, orient=tk.VERTICAL, command=self.listbox.yview)
self.config_listbox(yscrollcommand=self.scrollbar.set)
if compound is not tk.LEFT and compound is not tk.RIGHT:
raise ValueError("Invalid compound value passed: {0}".format(compound))
self.__compound = compound
self._grid_widgets()
|
def is_same_file ( filename1 , filename2 ) : if filename1 == filename2 : return True if os . name == 'posix' : return os . path . samefile ( filename1 , filename2 ) return is_same_filename ( filename1 , filename2 )
| 1 |
how to test if two files are the same in python
|
Check if filename1 and filename2 point to the same file object . There can be false negatives ie . the result is False but it is the same file anyway . Reason is that network filesystems can create different paths to the same physical file .
|
cosqa-train-16297
|
def is_same_file (filename1, filename2):
"""Check if filename1 and filename2 point to the same file object.
There can be false negatives, ie. the result is False, but it is
the same file anyway. Reason is that network filesystems can create
different paths to the same physical file.
"""
if filename1 == filename2:
return True
if os.name == 'posix':
return os.path.samefile(filename1, filename2)
return is_same_filename(filename1, filename2)
|
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 )
| 1 |
how to test not equal list in python
|
Returns true if all of the elements in the list are equal .
|
cosqa-train-16298
|
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 get_host_power_status ( self ) : sushy_system = self . _get_sushy_system ( PROLIANT_SYSTEM_ID ) return GET_POWER_STATE_MAP . get ( sushy_system . power_state )
| 1 |
python to check device power state
|
Request the power state of the server .
|
cosqa-train-16299
|
def get_host_power_status(self):
"""Request the power state of the server.
:returns: Power State of the server, 'ON' or 'OFF'
:raises: IloError, on an error from iLO.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
return GET_POWER_STATE_MAP.get(sushy_system.power_state)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.