id
stringlengths
11
16
language
stringclasses
2 values
question
stringlengths
13
844
answer
stringlengths
1
900
code
stringlengths
162
27.4k
code_original
stringlengths
162
26k
code_word_count
int64
51
5.96k
python-test-1239
python
What does the code create ?
a list with tree nodes for which the < filter > function returned true in a post order fashion
def post order list node filter func no filter l stack [] [] poped index 0 0 while node if filter func node if node children and not poped stack append node index index 0node node children[ 0 ]else l append node index + 1try node stack[ -1 ][ 0 ] children[index]except Index Error node Noneelse node Nonepoped 0if node i...
def post_order_list node filter_func no_filter l stack [] [] poped index 0 0 while node if filter_func node if node children and not poped stack append node index index 0node node children[0]else l append node index + 1try node stack[ -1 ][0] children[index]except IndexError node Noneelse node Nonepoped 0if node is Non...
71
python-test-1240
python
How did the < filter > function return true for which ?
in a post order fashion
def post order list node filter func no filter l stack [] [] poped index 0 0 while node if filter func node if node children and not poped stack append node index index 0node node children[ 0 ]else l append node index + 1try node stack[ -1 ][ 0 ] children[index]except Index Error node Noneelse node Nonepoped 0if node i...
def post_order_list node filter_func no_filter l stack [] [] poped index 0 0 while node if filter_func node if node children and not poped stack append node index index 0node node children[0]else l append node index + 1try node stack[ -1 ][0] children[index]except IndexError node Noneelse node Nonepoped 0if node is Non...
71
python-test-1242
python
What triggers a deprecationwarning or pendingdeprecationwarning ?
calling func
def deprecated call func None *args **kwargs if not func return Warnings Checker expected warning Deprecation Warning categories []def warn explicit message category *args **kwargs categories append category old warn explicit message category *args **kwargs def warn message category None *args **kwargs if isinstance me...
def deprecated_call func None *args **kwargs if not func return WarningsChecker expected_warning DeprecationWarning categories []def warn_explicit message category *args **kwargs categories append category old_warn_explicit message category *args **kwargs def warn message category None *args **kwargs if isinstance mess...
117
python-test-1243
python
What do calling func trigger ?
a deprecationwarning or pendingdeprecationwarning
def deprecated call func None *args **kwargs if not func return Warnings Checker expected warning Deprecation Warning categories []def warn explicit message category *args **kwargs categories append category old warn explicit message category *args **kwargs def warn message category None *args **kwargs if isinstance me...
def deprecated_call func None *args **kwargs if not func return WarningsChecker expected_warning DeprecationWarning categories []def warn_explicit message category *args **kwargs categories append category old_warn_explicit message category *args **kwargs def warn message category None *args **kwargs if isinstance mess...
117
python-test-1248
python
What does the code generate ?
a long random password that comply to linode requirements
def randompass import randomimport stringrandom seed lower '' join random choice string ascii lowercase for x in range 6 upper '' join random choice string ascii uppercase for x in range 6 number '' join random choice string digits for x in range 6 punct '' join random choice string punctuation for x in range 6 p lower...
def randompass import randomimport stringrandom seed lower '' join random choice string ascii_lowercase for x in range 6 upper '' join random choice string ascii_uppercase for x in range 6 number '' join random choice string digits for x in range 6 punct '' join random choice string punctuation for x in range 6 p lower...
72
python-test-1249
python
What do a long random password comply ?
to linode requirements
def randompass import randomimport stringrandom seed lower '' join random choice string ascii lowercase for x in range 6 upper '' join random choice string ascii uppercase for x in range 6 number '' join random choice string digits for x in range 6 punct '' join random choice string punctuation for x in range 6 p lower...
def randompass import randomimport stringrandom seed lower '' join random choice string ascii_lowercase for x in range 6 upper '' join random choice string ascii_uppercase for x in range 6 number '' join random choice string digits for x in range 6 punct '' join random choice string punctuation for x in range 6 p lower...
72
python-test-1250
python
What comply to linode requirements ?
a long random password
def randompass import randomimport stringrandom seed lower '' join random choice string ascii lowercase for x in range 6 upper '' join random choice string ascii uppercase for x in range 6 number '' join random choice string digits for x in range 6 punct '' join random choice string punctuation for x in range 6 p lower...
def randompass import randomimport stringrandom seed lower '' join random choice string ascii_lowercase for x in range 6 upper '' join random choice string ascii_uppercase for x in range 6 number '' join random choice string digits for x in range 6 punct '' join random choice string punctuation for x in range 6 p lower...
72
python-test-1253
python
What do rsaobj construct ?
an rsa object
def construct tuple obj RS Aobj if len tuple not in [2 3 5 6] raise error 'argumentforconstruct wronglength'for i in range len tuple field obj keydata[i]setattr obj field tuple[i] if len tuple > 5 if obj p > obj q obj p obj q obj q obj p if len tuple 5 obj u pubkey inverse obj p obj q return obj
def construct tuple obj RSAobj if len tuple not in [2 3 5 6] raise error 'argumentforconstruct wronglength'for i in range len tuple field obj keydata[i]setattr obj field tuple[i] if len tuple > 5 if obj p > obj q obj p obj q obj q obj p if len tuple 5 obj u pubkey inverse obj p obj q return obj
63
python-test-1254
python
What constructs an rsa object ?
rsaobj
def construct tuple obj RS Aobj if len tuple not in [2 3 5 6] raise error 'argumentforconstruct wronglength'for i in range len tuple field obj keydata[i]setattr obj field tuple[i] if len tuple > 5 if obj p > obj q obj p obj q obj q obj p if len tuple 5 obj u pubkey inverse obj p obj q return obj
def construct tuple obj RSAobj if len tuple not in [2 3 5 6] raise error 'argumentforconstruct wronglength'for i in range len tuple field obj keydata[i]setattr obj field tuple[i] if len tuple > 5 if obj p > obj q obj p obj q obj q obj p if len tuple 5 obj u pubkey inverse obj p obj q return obj
63
python-test-1255
python
What does the code take ?
a new snapshot of the disk image
def vm disk snapshot create name kwargs None call None if call 'action' raise Salt Cloud System Exit ' Thevm disk snapshot createactionmustbecalledwith-aor--action ' if kwargs is None kwargs {}disk id kwargs get 'disk id' None description kwargs get 'description' None if disk id is None or description is None raise Sal...
def vm_disk_snapshot_create name kwargs None call None if call 'action' raise SaltCloudSystemExit 'Thevm_disk_snapshot_createactionmustbecalledwith-aor--action ' if kwargs is None kwargs {}disk_id kwargs get 'disk_id' None description kwargs get 'description' None if disk_id is None or description is None raise SaltClo...
114
python-test-1258
python
In which direction does this encode a unicode string ?
back to byte - representation
def to str obj encoding 'utf- 8 ' force string False if force string and not isinstance obj basestring try obj str obj except Exception obj unicode obj if isinstance obj basestring and isinstance obj unicode try obj obj encode encoding return objexcept Unicode Encode Error for alt encoding in ENCODINGS try obj obj enco...
def to_str obj encoding 'utf-8' force_string False if force_string and not isinstance obj basestring try obj str obj except Exception obj unicode obj if isinstance obj basestring and isinstance obj unicode try obj obj encode encoding return objexcept UnicodeEncodeError for alt_encoding in ENCODINGS try obj obj encode a...
85
python-test-1259
python
What does the code show ?
a chain of object references
def show chain *chains **kw backrefs kw pop 'backrefs' True chains [chain for chain in chains if chain]def in chains x ids set map id itertools chain *chains return id x in ids max depth max map len chains - 1 if backrefs show backrefs [chain[ -1 ] for chain in chains] max depth max depth filter in chains **kw else sho...
def show_chain *chains **kw backrefs kw pop 'backrefs' True chains [chain for chain in chains if chain]def in_chains x ids set map id itertools chain *chains return id x in ids max_depth max map len chains - 1 if backrefs show_backrefs [chain[ -1 ] for chain in chains] max_depth max_depth filter in_chains **kw else sho...
78
python-test-1264
python
What does the code compare ?
swarms
def compare torrents torrent 1 torrent 2 files 1 [files for files in torrent 1['metainfo'] get files with length if files[ 1 ] > 1024 * 1024 ]files 2 [files for files in torrent 2['metainfo'] get files with length if files[ 1 ] > 1024 * 1024 ]if len files 1 len files 2 for ft 1 in files 1 for ft 2 in files 2 if ft 1 [ ...
def compare_torrents torrent_1 torrent_2 files1 [files for files in torrent_1['metainfo'] get_files_with_length if files[1] > 1024 * 1024 ]files2 [files for files in torrent_2['metainfo'] get_files_with_length if files[1] > 1024 * 1024 ]if len files1 len files2 for ft1 in files1 for ft2 in files2 if ft1[1] ft2[1] or le...
97
python-test-1268
python
What does helper method convert to amazon elastic mapreduce instancegroupconfig data type in create - cluster and add - instance - groups ?
--instance - groups option value
def build instance groups parsed instance groups instance groups []for instance group in parsed instance groups ig config {}keys instance group keys if ' Name' in keys ig config[' Name'] instance group[' Name']else ig config[' Name'] instance group[' Instance Group Type']ig config[' Instance Type'] instance group[' Ins...
def build_instance_groups parsed_instance_groups instance_groups []for instance_group in parsed_instance_groups ig_config {}keys instance_group keys if 'Name' in keys ig_config['Name'] instance_group['Name']else ig_config['Name'] instance_group['InstanceGroupType']ig_config['InstanceType'] instance_group['InstanceType'...
126
python-test-1269
python
Where does helper method convert --instance - groups option value to amazon elastic mapreduce instancegroupconfig data type ?
in create - cluster and add - instance - groups
def build instance groups parsed instance groups instance groups []for instance group in parsed instance groups ig config {}keys instance group keys if ' Name' in keys ig config[' Name'] instance group[' Name']else ig config[' Name'] instance group[' Instance Group Type']ig config[' Instance Type'] instance group[' Ins...
def build_instance_groups parsed_instance_groups instance_groups []for instance_group in parsed_instance_groups ig_config {}keys instance_group keys if 'Name' in keys ig_config['Name'] instance_group['Name']else ig_config['Name'] instance_group['InstanceGroupType']ig_config['InstanceType'] instance_group['InstanceType'...
126
python-test-1271
python
When do circular references between an event on an instance and the handling delegate nt release ?
too soon
@skip 'silverlight' def test event lifetime def keep alive o passdef test runner import weakrefglobal calledcalled 0a Iron Python Test Events def foo global calledcalled + 1foo abc aa Instance Test + fooa Call Instance Are Equal called 1 ret val weakref ref foo keep alive foo import gcfor i in xrange 10 gc collect a Ca...
@skip 'silverlight' def test_event_lifetime def keep_alive o passdef test_runner import _weakrefglobal calledcalled 0a IronPythonTest Events def foo global calledcalled + 1foo abc aa InstanceTest + fooa CallInstance AreEqual called 1 ret_val _weakref ref foo keep_alive foo import gcfor i in xrange 10 gc collect a CallI...
91
python-test-1272
python
Does circular references between an event on an instance and the handling delegate call leaks ?
No
@skip 'silverlight' def test event lifetime def keep alive o passdef test runner import weakrefglobal calledcalled 0a Iron Python Test Events def foo global calledcalled + 1foo abc aa Instance Test + fooa Call Instance Are Equal called 1 ret val weakref ref foo keep alive foo import gcfor i in xrange 10 gc collect a Ca...
@skip 'silverlight' def test_event_lifetime def keep_alive o passdef test_runner import _weakrefglobal calledcalled 0a IronPythonTest Events def foo global calledcalled + 1foo abc aa InstanceTest + fooa CallInstance AreEqual called 1 ret_val _weakref ref foo keep_alive foo import gcfor i in xrange 10 gc collect a CallI...
91
python-test-1273
python
What does circular references between an event on an instance and the handling delegate nt call ?
leaks
@skip 'silverlight' def test event lifetime def keep alive o passdef test runner import weakrefglobal calledcalled 0a Iron Python Test Events def foo global calledcalled + 1foo abc aa Instance Test + fooa Call Instance Are Equal called 1 ret val weakref ref foo keep alive foo import gcfor i in xrange 10 gc collect a Ca...
@skip 'silverlight' def test_event_lifetime def keep_alive o passdef test_runner import _weakrefglobal calledcalled 0a IronPythonTest Events def foo global calledcalled + 1foo abc aa InstanceTest + fooa CallInstance AreEqual called 1 ret_val _weakref ref foo keep_alive foo import gcfor i in xrange 10 gc collect a CallI...
91
python-test-1274
python
What nt calls leaks ?
circular references between an event on an instance and the handling delegate
@skip 'silverlight' def test event lifetime def keep alive o passdef test runner import weakrefglobal calledcalled 0a Iron Python Test Events def foo global calledcalled + 1foo abc aa Instance Test + fooa Call Instance Are Equal called 1 ret val weakref ref foo keep alive foo import gcfor i in xrange 10 gc collect a Ca...
@skip 'silverlight' def test_event_lifetime def keep_alive o passdef test_runner import _weakrefglobal calledcalled 0a IronPythonTest Events def foo global calledcalled + 1foo abc aa InstanceTest + fooa CallInstance AreEqual called 1 ret_val _weakref ref foo keep_alive foo import gcfor i in xrange 10 gc collect a CallI...
91
python-test-1275
python
What does the code verify ?
a challenging hmac signature against a string / shared - secret
def hmac signature string shared secret challenge hmac if six PY 3 msg salt utils to bytes string key salt utils to bytes shared secret challenge salt utils to bytes challenge hmac else msg stringkey shared secretchallenge challenge hmachmac hash hmac new key msg hashlib sha 256 valid hmac base 64 b64 encode hmac hash ...
def hmac_signature string shared_secret challenge_hmac if six PY3 msg salt utils to_bytes string key salt utils to_bytes shared_secret challenge salt utils to_bytes challenge_hmac else msg stringkey shared_secretchallenge challenge_hmachmac_hash hmac new key msg hashlib sha256 valid_hmac base64 b64encode hmac_hash dige...
60
python-test-1278
python
How is this called ?
by branding
@csrf exemptdef ssl login request if not settings FEATURES['AUTH USE CERTIFICATES'] return Http Response Forbidden cert ssl get cert from request request if not cert return student views index request user email fullname ssl dn extract info cert redirect to get next url for login page request retfun functools partial r...
@csrf_exemptdef ssl_login request if not settings FEATURES['AUTH_USE_CERTIFICATES'] return HttpResponseForbidden cert ssl_get_cert_from_request request if not cert return student views index request _user email fullname _ssl_dn_extract_info cert redirect_to get_next_url_for_login_page request retfun functools partial r...
74
python-test-1279
python
What does the code take ?
a soundcloud playlist item
def format playlist playlist show url True out '\x 02 {}\x 02 ' format playlist['title'] if playlist['description'] out + ' "{}"' format formatting truncate playlist['description'] if playlist['genre'] out + '-\x 02 {}\x 02 ' format playlist['genre'] out + '-by\x 02 {}\x 02 ' format playlist['user']['username'] if not ...
def format_playlist playlist show_url True out '\x02{}\x02' format playlist['title'] if playlist['description'] out + ' "{}"' format formatting truncate playlist['description'] if playlist['genre'] out + '-\x02{}\x02' format playlist['genre'] out + '-by\x02{}\x02' format playlist['user']['username'] if not playlist['tr...
89
python-test-1281
python
What does the code generate ?
a set of hub sequences
def generate Hub Sequences n Coinc 10 hubs [2 6] seq Length [5 6 7] n Seq 100 coinc List range n Coinc for hub in hubs coinc List remove hub seq List []for i in xrange n Seq length random choice seq Length - 1 seq random sample coinc List length seq insert length // 2 random choice hubs seq List append seq return seq L...
def generateHubSequences nCoinc 10 hubs [2 6] seqLength [5 6 7] nSeq 100 coincList range nCoinc for hub in hubs coincList remove hub seqList []for i in xrange nSeq length random choice seqLength - 1 seq random sample coincList length seq insert length // 2 random choice hubs seqList append seq return seqList
67
python-test-1282
python
What does the code open in a temporary directory ?
a copy of a repo
def open repo name temp dir None if temp dir is None temp dir tempfile mkdtemp repo dir os path join os path dirname file 'data' 'repos' name temp repo dir os path join temp dir name shutil copytree repo dir temp repo dir symlinks True return Repo temp repo dir
def open_repo name temp_dir None if temp_dir is None temp_dir tempfile mkdtemp repo_dir os path join os path dirname __file__ 'data' 'repos' name temp_repo_dir os path join temp_dir name shutil copytree repo_dir temp_repo_dir symlinks True return Repo temp_repo_dir
51
python-test-1291
python
What does the code let ?
the user choose one
def explore account c while True printfolderflags {}data c list folders for flags delimiter name in data folderflags[name] flagsfor name in sorted folderflags keys print '%- 30 s%s' % name '' join folderflags[name] printreply raw input ' Typeafoldername or"q"toquit ' strip if reply lower startswith 'q' breakif reply in...
def explore_account c while True printfolderflags {}data c list_folders for flags delimiter name in data folderflags[name] flagsfor name in sorted folderflags keys print '%-30s%s' % name '' join folderflags[name] printreply raw_input 'Typeafoldername or"q"toquit ' strip if reply lower startswith 'q' breakif reply in fo...
61
python-test-1293
python
What does the code create ?
the start command to run the python application server
def create python 27 start cmd app name login ip port load balancer host xmpp ip db location DATASTORE PAT Hcmd ['/usr/bin/python 2 ' constants APPSCALE HOME + '/ App Server/dev appserver py' '--port' + str port '--admin port' + str port + 10000 '--login server' + login ip '--skip sdk update check' '--nginx host' + str...
def create_python27_start_cmd app_name login_ip port load_balancer_host xmpp_ip db_location DATASTORE_PATHcmd ['/usr/bin/python2' constants APPSCALE_HOME + '/AppServer/dev_appserver py' '--port' + str port '--admin_port' + str port + 10000 '--login_server' + login_ip '--skip_sdk_update_check' '--nginx_host' + str load_...
133
python-test-1294
python
How does an undirected graph return ?
using the duplication - divergence model
def duplication divergence graph n p seed None if p > 1 or p < 0 msg ' Network X Errorp {0 }isnotin[ 0 1] ' format p raise nx Network X Error msg if n < 2 msg 'nmustbegreaterthanorequalto 2 'raise nx Network X Error msg if seed is not None random seed seed G nx Graph G name 'duplication divergence graph {} {} ' format ...
def duplication_divergence_graph n p seed None if p > 1 or p < 0 msg 'NetworkXErrorp {0}isnotin[0 1] ' format p raise nx NetworkXError msg if n < 2 msg 'nmustbegreaterthanorequalto2'raise nx NetworkXError msg if seed is not None random seed seed G nx Graph G name 'duplication_divergence_graph {} {} ' format n p G add_e...
120
python-test-1295
python
What do an undirected graph use ?
the duplication - divergence model
def duplication divergence graph n p seed None if p > 1 or p < 0 msg ' Network X Errorp {0 }isnotin[ 0 1] ' format p raise nx Network X Error msg if n < 2 msg 'nmustbegreaterthanorequalto 2 'raise nx Network X Error msg if seed is not None random seed seed G nx Graph G name 'duplication divergence graph {} {} ' format ...
def duplication_divergence_graph n p seed None if p > 1 or p < 0 msg 'NetworkXErrorp {0}isnotin[0 1] ' format p raise nx NetworkXError msg if n < 2 msg 'nmustbegreaterthanorequalto2'raise nx NetworkXError msg if seed is not None random seed seed G nx Graph G name 'duplication_divergence_graph {} {} ' format n p G add_e...
120
python-test-1297
python
What converts into image and diff batch ?
image sequence batch
def Sequence To Image And Diff images image diff list []image seq tf unstack images axis 1 for size in [32 64 128 256 ] resized images [tf image resize images i [size size] for i in image seq]diffs []for i in xrange 0 len resized images - 1 diffs append resized images[ i + 1 ] - resized images[i] image diff list append...
def SequenceToImageAndDiff images image_diff_list []image_seq tf unstack images axis 1 for size in [32 64 128 256] resized_images [tf image resize_images i [size size] for i in image_seq]diffs []for i in xrange 0 len resized_images - 1 diffs append resized_images[ i + 1 ] - resized_images[i] image_diff_list append tf c...
79
python-test-1298
python
What do image sequence batch convert ?
into image and diff batch
def Sequence To Image And Diff images image diff list []image seq tf unstack images axis 1 for size in [32 64 128 256 ] resized images [tf image resize images i [size size] for i in image seq]diffs []for i in xrange 0 len resized images - 1 diffs append resized images[ i + 1 ] - resized images[i] image diff list append...
def SequenceToImageAndDiff images image_diff_list []image_seq tf unstack images axis 1 for size in [32 64 128 256] resized_images [tf image resize_images i [size size] for i in image_seq]diffs []for i in xrange 0 len resized_images - 1 diffs append resized_images[ i + 1 ] - resized_images[i] image_diff_list append tf c...
79
python-test-1299
python
What sets to be unused ?
the vlanid state
def release vlanid vlan id LOG debug 'release vlanid called' session db get session try vlanid session query network models v2 Vlan ID filter by vlan id vlan id one vlanid['vlan used'] Falsesession merge vlanid session flush return vlanid['vlan used']except exc No Result Found raise c exc Vlan ID Not Found vlan id vlan...
def release_vlanid vlan_id LOG debug _ 'release_vlanid called' session db get_session try vlanid session query network_models_v2 VlanID filter_by vlan_id vlan_id one vlanid['vlan_used'] Falsesession merge vlanid session flush return vlanid['vlan_used']except exc NoResultFound raise c_exc VlanIDNotFound vlan_id vlan_id ...
56
python-test-1300
python
What does the vlanid state set ?
to be unused
def release vlanid vlan id LOG debug 'release vlanid called' session db get session try vlanid session query network models v2 Vlan ID filter by vlan id vlan id one vlanid['vlan used'] Falsesession merge vlanid session flush return vlanid['vlan used']except exc No Result Found raise c exc Vlan ID Not Found vlan id vlan...
def release_vlanid vlan_id LOG debug _ 'release_vlanid called' session db get_session try vlanid session query network_models_v2 VlanID filter_by vlan_id vlan_id one vlanid['vlan_used'] Falsesession merge vlanid session flush return vlanid['vlan_used']except exc NoResultFound raise c_exc VlanIDNotFound vlan_id vlan_id ...
56
python-test-1301
python
What does the code make ?
sure memory reallocation works okay when the number of rows is large
@pytest mark parametrize 'parallel' [ True False] def test many rows parallel read basic text 'ABC\n'for i in range 500 text + '' join [str i for i in range 3 ] text + '\n'table read basic text parallel parallel expected Table [ [0 ] * 500 [1 ] * 500 [2 ] * 500 ] names 'A' 'B' 'C' assert table equal table expected
@pytest mark parametrize 'parallel' [True False] def test_many_rows parallel read_basic text 'ABC\n'for i in range 500 text + '' join [str i for i in range 3 ] text + '\n'table read_basic text parallel parallel expected Table [ [0] * 500 [1] * 500 [2] * 500 ] names 'A' 'B' 'C' assert_table_equal table expected
65
python-test-1303
python
What do a database support ?
all of gis_lookups
def skip Unless GIS Lookup *gis lookups def decorator test func @wraps test func def skip wrapper *args **kwargs if any key not in connection ops gis operators for key in gis lookups raise unittest Skip Test " Databasedoesn'tsupportallthelookups %s" % ' ' join gis lookups return test func *args **kwargs return skip wra...
def skipUnlessGISLookup *gis_lookups def decorator test_func @wraps test_func def skip_wrapper *args **kwargs if any key not in connection ops gis_operators for key in gis_lookups raise unittest SkipTest "Databasedoesn'tsupportallthelookups %s" % ' ' join gis_lookups return test_func *args **kwargs return skip_wrapperr...
55
python-test-1308
python
What creates in a temporary directory ?
a style sheet
@contextmanagerdef temp style style name settings None if not settings settings DUMMY SETTING Stemp file u'%s %s' % style name STYLE EXTENSION tempdir tempfile mkdtemp with open os path join tempdir temp file u'w' as f for k v in six iteritems settings f write u'%s %s' % k v USER LIBRARY PATHS append tempdir style relo...
@contextmanagerdef temp_style style_name settings None if not settings settings DUMMY_SETTINGStemp_file u'%s %s' % style_name STYLE_EXTENSION tempdir tempfile mkdtemp with open os path join tempdir temp_file u'w' as f for k v in six iteritems settings f write u'%s %s' % k v USER_LIBRARY_PATHS append tempdir style reloa...
67
python-test-1317
python
What does the code find ?
the class registered to the alias
def load class alias try return CLASS CACHE[alias]except Key Error passfor loader in CLASS LOADERS klass loader alias if klass is None continueif isinstance klass python class types return register class klass alias elif isinstance klass Class Alias CLASS CACHE[klass alias] klass CLASS CACHE[klass klass] klassreturn kl...
def load_class alias try return CLASS_CACHE[alias]except KeyError passfor loader in CLASS_LOADERS klass loader alias if klass is None continueif isinstance klass python class_types return register_class klass alias elif isinstance klass ClassAlias CLASS_CACHE[klass alias] klassCLASS_CACHE[klass klass] klassreturn klass...
131
python-test-1320
python
What do the default output state configure ?
to push its document to a session on a bokeh server
def output server session id None url 'default' app path '/' deprecated 0 12 3 'bokeh io output server ' '\nbokeh clientsessionsasdescribedathttp //bokeh pydata org/en/latest/docs/user guide/server html#connecting-with-bokeh-client"\n' from client import DEFAULT SESSION I Dif session id is None session id DEFAULT SESSI...
def output_server session_id None url 'default' app_path '/' deprecated 0 12 3 'bokeh io output_server ' '\nbokeh clientsessionsasdescribedathttp //bokeh pydata org/en/latest/docs/user_guide/server html#connecting-with-bokeh-client"\n' from client import DEFAULT_SESSION_IDif session_id is None session_id DEFAULT_SESSIO...
56
python-test-1321
python
What do the default output state push to a session on a bokeh server ?
its document
def output server session id None url 'default' app path '/' deprecated 0 12 3 'bokeh io output server ' '\nbokeh clientsessionsasdescribedathttp //bokeh pydata org/en/latest/docs/user guide/server html#connecting-with-bokeh-client"\n' from client import DEFAULT SESSION I Dif session id is None session id DEFAULT SESSI...
def output_server session_id None url 'default' app_path '/' deprecated 0 12 3 'bokeh io output_server ' '\nbokeh clientsessionsasdescribedathttp //bokeh pydata org/en/latest/docs/user_guide/server html#connecting-with-bokeh-client"\n' from client import DEFAULT_SESSION_IDif session_id is None session_id DEFAULT_SESSIO...
56
python-test-1330
python
What does the code get ?
vlm_media instance chapter number by name or instance i d
def libvlc vlm get media instance chapter p instance psz name i instance f Cfunctions get 'libvlc vlm get media instance chapter' None or Cfunction 'libvlc vlm get media instance chapter' 1 1 1 None ctypes c int Instance ctypes c char p ctypes c int return f p instance psz name i instance
def libvlc_vlm_get_media_instance_chapter p_instance psz_name i_instance f _Cfunctions get 'libvlc_vlm_get_media_instance_chapter' None or _Cfunction 'libvlc_vlm_get_media_instance_chapter' 1 1 1 None ctypes c_int Instance ctypes c_char_p ctypes c_int return f p_instance psz_name i_instance
54
python-test-1334
python
What does the django orm create ?
new instances of objects for each db request
def write Django Object obj encoder None s obj pkif s is None encoder write Object obj returndjango objects get Django Objects encoder context kls obj class try referenced object django objects get Class Key kls s except Key Error referenced object objdjango objects add Class Key kls s obj encoder write Object referenc...
def writeDjangoObject obj encoder None s obj pkif s is None encoder writeObject obj returndjango_objects getDjangoObjects encoder context kls obj __class__try referenced_object django_objects getClassKey kls s except KeyError referenced_object objdjango_objects addClassKey kls s obj encoder writeObject referenced_objec...
55
python-test-1335
python
What creates new instances of objects for each db request ?
the django orm
def write Django Object obj encoder None s obj pkif s is None encoder write Object obj returndjango objects get Django Objects encoder context kls obj class try referenced object django objects get Class Key kls s except Key Error referenced object objdjango objects add Class Key kls s obj encoder write Object referenc...
def writeDjangoObject obj encoder None s obj pkif s is None encoder writeObject obj returndjango_objects getDjangoObjects encoder context kls obj __class__try referenced_object django_objects getClassKey kls s except KeyError referenced_object objdjango_objects addClassKey kls s obj encoder writeObject referenced_objec...
55
python-test-1336
python
How does a form field render ?
using bootstraps prepended or appended text : : { % crispy_addon form
@register simple tag def crispy addon field append '' prepend '' form show labels True if field context Context {'field' field 'form show errors' True 'form show labels' form show labels} template loader get template '%s/layout/prepended appended text html' % get template pack context['crispy prepended text'] prependco...
@register simple_tag def crispy_addon field append '' prepend '' form_show_labels True if field context Context {'field' field 'form_show_errors' True 'form_show_labels' form_show_labels} template loader get_template '%s/layout/prepended_appended_text html' % get_template_pack context['crispy_prepended_text'] prependco...
67
python-test-1339
python
What does generator yield ?
all ckan python source files
def walk python files def is dir ignored root d if d startswith u' ' return Truereturn os path join rel root d in IGNORED DIRS for abs root dirnames filenames in os walk PROJECT ROOT rel root os path relpath abs root PROJECT ROOT if rel root u' ' rel root u''dirnames[ ] [d for d in dirnames if not is dir ignored rel ro...
def walk_python_files def _is_dir_ignored root d if d startswith u' ' return Truereturn os path join rel_root d in IGNORED_DIRS for abs_root dirnames filenames in os walk PROJECT_ROOT rel_root os path relpath abs_root PROJECT_ROOT if rel_root u' ' rel_root u''dirnames[ ] [d for d in dirnames if not _is_dir_ignored rel_...
98
python-test-1343
python
What does the code get ?
a list of all ebs volumes
def get all volumes volume ids None filters None return objs False region None key None keyid None profile None conn get conn region region key key keyid keyid profile profile try ret conn get all volumes volume ids volume ids filters filters return ret if return objs else [r id for r in ret] except boto exception Boto...
def get_all_volumes volume_ids None filters None return_objs False region None key None keyid None profile None conn _get_conn region region key key keyid keyid profile profile try ret conn get_all_volumes volume_ids volume_ids filters filters return ret if return_objs else [r id for r in ret] except boto exception Bot...
68
python-test-1344
python
What did the code set ?
a simple main loop for progress bar tests
def setup mainloop extension iteration scheme None features [numpy array f dtype theano config float X for f in [[ 1 2]] * 101 ]dataset Iterable Dataset dict features features data stream Data Stream dataset iteration scheme iteration scheme W shared floatx [0 0] name 'W' x tensor vector 'features' cost tensor sum x - ...
def setup_mainloop extension iteration_scheme None features [numpy array f dtype theano config floatX for f in [[1 2]] * 101 ]dataset IterableDataset dict features features data_stream DataStream dataset iteration_scheme iteration_scheme W shared_floatx [0 0] name 'W' x tensor vector 'features' cost tensor sum x - W **...
96
python-test-1349
python
What does the code get from the rrrather api ?
a entry
def get wyr headers r requests get url API URL headers headers data r json data['title'] data['title'] strip capitalize rstrip ' ? ' data['choicea'] data['choicea'] strip lower rstrip ' ? ' lstrip ' ' data['choiceb'] data['choiceb'] strip lower rstrip ' ? ' lstrip ' ' if data['tags'] data['tags'] data['tags'] lower spl...
def get_wyr headers r requests get url API_URL headers headers data r json data['title'] data['title'] strip capitalize rstrip ' ? ' data['choicea'] data['choicea'] strip lower rstrip ' ? ' lstrip ' ' data['choiceb'] data['choiceb'] strip lower rstrip ' ? ' lstrip ' ' if data['tags'] data['tags'] data['tags'] lower spl...
62
python-test-1351
python
What do a function accept ?
an environment dict
def compile marker try return cache[marker]except Key Error passif not marker strip def marker fn environment None override None ''return Trueelse compiled marker compile marker parse marker marker def marker fn environment None override None 'overrideupdatesenvironment'if override is None override {}if environment is ...
def compile marker try return _cache[marker]except KeyError passif not marker strip def marker_fn environment None override None ''return Trueelse compiled_marker compile_marker parse_marker marker def marker_fn environment None override None 'overrideupdatesenvironment'if override is None override {}if environment is ...
63
python-test-1353
python
What does the code calculate ?
the standard error of the mean of the values in the input array
def sem a axis 0 ddof 1 nan policy 'propagate' a axis chk asarray a axis contains nan nan policy contains nan a nan policy if contains nan and nan policy 'omit' a ma masked invalid a return mstats basic sem a axis ddof n a shape[axis]s np std a axis axis ddof ddof / np sqrt n return s
def sem a axis 0 ddof 1 nan_policy 'propagate' a axis _chk_asarray a axis contains_nan nan_policy _contains_nan a nan_policy if contains_nan and nan_policy 'omit' a ma masked_invalid a return mstats_basic sem a axis ddof n a shape[axis]s np std a axis axis ddof ddof / np sqrt n return s
60
python-test-1354
python
What does the code find ?
the op - local identifier for this xrd : service element
def find OP Local Identifier service element type uris local id tags []if OPENID 1 1 TYPE in type uris or OPENID 1 0 TYPE in type uris local id tags append ns Tag OPENID 1 0 NS ' Delegate' if OPENID 2 0 TYPE in type uris local id tags append ns Tag XRD NS 2 0 ' Local ID' local id Nonefor local id tag in local id tags f...
def findOPLocalIdentifier service_element type_uris local_id_tags []if OPENID_1_1_TYPE in type_uris or OPENID_1_0_TYPE in type_uris local_id_tags append nsTag OPENID_1_0_NS 'Delegate' if OPENID_2_0_TYPE in type_uris local_id_tags append nsTag XRD_NS_2_0 'LocalID' local_id Nonefor local_id_tag in local_id_tags for local...
115
python-test-1361
python
What does the code get by name ?
a document class
def get document name doc document registry get name None if not doc single end name split ' ' [ -1 ]compound end ' %s' % single end possible match [k for k in document registry keys if k endswith compound end or k single end ]if len possible match 1 doc document registry get possible match pop None if not doc raise No...
def get_document name doc _document_registry get name None if not doc single_end name split ' ' [ -1 ]compound_end ' %s' % single_end possible_match [k for k in _document_registry keys if k endswith compound_end or k single_end ]if len possible_match 1 doc _document_registry get possible_match pop None if not doc raise...
74
python-test-1364
python
What does the code update ?
the date / time on the given host or list of host_names
@depends HAS PYVMOMI def update host datetime host username password protocol None port None host names None service instance salt utils vmware get service instance host host username username password password protocol protocol port port host names check hosts service instance host host names ret {}for host name in ho...
@depends HAS_PYVMOMI def update_host_datetime host username password protocol None port None host_names None service_instance salt utils vmware get_service_instance host host username username password password protocol protocol port port host_names _check_hosts service_instance host host_names ret {}for host_name in h...
123
python-test-1378
python
What does json contain ?
a html formatted grade summary
@require POST@ensure csrf cookie@cache control no cache True no store True must revalidate True @require level 'staff' def get grading config request course id course id Slash Separated Course Key from deprecated string course id course get course with access request user 'staff' course id depth None grading config sum...
@require_POST@ensure_csrf_cookie@cache_control no_cache True no_store True must_revalidate True @require_level 'staff' def get_grading_config request course_id course_id SlashSeparatedCourseKey from_deprecated_string course_id course get_course_with_access request user 'staff' course_id depth None grading_config_summar...
76
python-test-1384
python
What does helper function render ?
the purchase form
def render report form start str end str start letter end letter report type total count error False date fmt error False context {'total count error' total count error 'date fmt error' date fmt error 'start date' start str 'end date' end str 'start letter' start letter 'end letter' end letter 'requested report' report...
def _render_report_form start_str end_str start_letter end_letter report_type total_count_error False date_fmt_error False context {'total_count_error' total_count_error 'date_fmt_error' date_fmt_error 'start_date' start_str 'end_date' end_str 'start_letter' start_letter 'end_letter' end_letter 'requested_report' repor...
62
python-test-1389
python
What prints in json ?
the output data
def output data **kwargs try if 'output indent' not in opts return json dumps data default repr indent 4 indent opts get 'output indent' sort keys Falseif indent is None indent Noneelif indent 'pretty' indent 4sort keys Trueelif isinstance indent int if indent > 0 indent indentelse indent Nonereturn json dumps data def...
def output data **kwargs try if 'output_indent' not in __opts__ return json dumps data default repr indent 4 indent __opts__ get 'output_indent' sort_keys Falseif indent is None indent Noneelif indent 'pretty' indent 4sort_keys Trueelif isinstance indent int if indent > 0 indent indentelse indent Nonereturn json dumps ...
95
python-test-1392
python
What was called in any of the given methods ?
the func
def called in methods func klass methods if not isinstance func astroid Function return Falsefor method in methods try infered klass getattr method except astroid Not Found Error continuefor infer method in infered for callfunc in infer method nodes of class astroid Call Func try bound next callfunc func infer except a...
def _called_in_methods func klass methods if not isinstance func astroid Function return Falsefor method in methods try infered klass getattr method except astroid NotFoundError continuefor infer_method in infered for callfunc in infer_method nodes_of_class astroid CallFunc try bound next callfunc func infer except ast...
86
python-test-1393
python
Where was the func called ?
in any of the given methods
def called in methods func klass methods if not isinstance func astroid Function return Falsefor method in methods try infered klass getattr method except astroid Not Found Error continuefor infer method in infered for callfunc in infer method nodes of class astroid Call Func try bound next callfunc func infer except a...
def _called_in_methods func klass methods if not isinstance func astroid Function return Falsefor method in methods try infered klass getattr method except astroid NotFoundError continuefor infer_method in infered for callfunc in infer_method nodes_of_class astroid CallFunc try bound next callfunc func infer except ast...
86
python-test-1397
python
What did the code set ?
a single config value in the master
def set master service conn type private 'y' unpriv 'y' chroot 'y' wakeup 'n' maxproc '100 ' command '' write conf True path MASTER CF conf dict conf list parse master path new conf []dict key '{ 0 }{ 1 }' format service conn type new line format master service conn type private unpriv chroot wakeup maxproc command for...
def set_master service conn_type private 'y' unpriv 'y' chroot 'y' wakeup 'n' maxproc '100' command '' write_conf True path MASTER_CF conf_dict conf_list _parse_master path new_conf []dict_key '{0}{1}' format service conn_type new_line _format_master service conn_type private unpriv chroot wakeup maxproc command for li...
117
python-test-1398
python
What sends to unfollow ?
http request
def new unfollow self user id user name url unfollow self url unfollow % user id try unfollow self s post url unfollow if unfollow status code 200 self unfollow counter + 1log string ' Unfollow %s#%i ' % user name self unfollow counter self write log log string return unfollowexcept self write log ' Exeptonunfollow ' r...
def new_unfollow self user_id user_name url_unfollow self url_unfollow % user_id try unfollow self s post url_unfollow if unfollow status_code 200 self unfollow_counter + 1log_string 'Unfollow %s#%i ' % user_name self unfollow_counter self write_log log_string return unfollowexcept self write_log 'Exeptonunfollow ' ret...
59
python-test-1399
python
What do http request send ?
to unfollow
def new unfollow self user id user name url unfollow self url unfollow % user id try unfollow self s post url unfollow if unfollow status code 200 self unfollow counter + 1log string ' Unfollow %s#%i ' % user name self unfollow counter self write log log string return unfollowexcept self write log ' Exeptonunfollow ' r...
def new_unfollow self user_id user_name url_unfollow self url_unfollow % user_id try unfollow self s post url_unfollow if unfollow status_code 200 self unfollow_counter + 1log_string 'Unfollow %s#%i ' % user_name self unfollow_counter self write_log log_string return unfollowexcept self write_log 'Exeptonunfollow ' ret...
59
python-test-1405
python
What does the code create ?
a function useful to handle text[::optional_note ] values
def make Text Notes replace Txt Notes def replacer s out S replace Txt Notesif not isinstance s unicode str return sssplit s split ' ' 1 text ssplit[ 0 ]keys Dict {}if text keys Dict['text'] Trueout S out S replace '% text s' text if len ssplit 2 keys Dict['notes'] Trueout S out S replace '% notes s' ssplit[ 1 ] else o...
def makeTextNotes replaceTxtNotes def _replacer s outS replaceTxtNotesif not isinstance s unicode str return sssplit s split ' ' 1 text ssplit[0]keysDict {}if text keysDict['text'] TrueoutS outS replace '% text s' text if len ssplit 2 keysDict['notes'] TrueoutS outS replace '% notes s' ssplit[1] else outS outS replace ...
109
python-test-1409
python
What does the code generate ?
a word rank - based probabilistic sampling table
def make sampling table size sampling factor 1e- 05 gamma 0 577 rank np array list range size rank[ 0 ] 1inv fq rank * np log rank + gamma + 0 5 - 1 0 / 12 0 * rank f sampling factor * inv fq return np minimum 1 0 f / np sqrt f
def make_sampling_table size sampling_factor 1e-05 gamma 0 577rank np array list range size rank[0] 1inv_fq rank * np log rank + gamma + 0 5 - 1 0 / 12 0 * rank f sampling_factor * inv_fq return np minimum 1 0 f / np sqrt f
57
python-test-1410
python
What does the code run ?
a script file
def run script scriptfile try f open scriptfile mode 'r' except Exception returnmpstate console writeln ' Runningscript%s' % scriptfile for line in f line line strip if line '' or line startswith '#' continueif line startswith '@' line line[ 1 ]else mpstate console writeln '->%s' % line process stdin line f close
def run_script scriptfile try f open scriptfile mode 'r' except Exception returnmpstate console writeln 'Runningscript%s' % scriptfile for line in f line line strip if line '' or line startswith '#' continueif line startswith '@' line line[1 ]else mpstate console writeln '->%s' % line process_stdin line f close
52
python-test-1411
python
What do dict of hosts monitor at a time ?
to popen objects a line
def pmonitor popens timeoutms 500 readline True readmax 1024 poller poll fd To Host {}for host popen in popens iteritems fd popen stdout fileno fd To Host[fd] hostpoller register fd POLLIN if not readline flags fcntl fd F GETFL fcntl fd F SETFL flags O NONBLOCK while popens fds poller poll timeoutms if fds for fd event...
def pmonitor popens timeoutms 500 readline True readmax 1024 poller poll fdToHost {}for host popen in popens iteritems fd popen stdout fileno fdToHost[fd] hostpoller register fd POLLIN if not readline flags fcntl fd F_GETFL fcntl fd F_SETFL flags O_NONBLOCK while popens fds poller poll timeoutms if fds for fd event in ...
94
python-test-1412
python
What monitors to popen objects a line at a time ?
dict of hosts
def pmonitor popens timeoutms 500 readline True readmax 1024 poller poll fd To Host {}for host popen in popens iteritems fd popen stdout fileno fd To Host[fd] hostpoller register fd POLLIN if not readline flags fcntl fd F GETFL fcntl fd F SETFL flags O NONBLOCK while popens fds poller poll timeoutms if fds for fd event...
def pmonitor popens timeoutms 500 readline True readmax 1024 poller poll fdToHost {}for host popen in popens iteritems fd popen stdout fileno fdToHost[fd] hostpoller register fd POLLIN if not readline flags fcntl fd F_GETFL fcntl fd F_SETFL flags O_NONBLOCK while popens fds poller poll timeoutms if fds for fd event in ...
94
python-test-1415
python
What does this function perform ?
one - step of hybrid monte - carlo sampling
def hmc move s rng positions energy fn stepsize n steps initial vel s rng normal size positions shape final pos final vel simulate dynamics initial pos positions initial vel initial vel stepsize stepsize n steps n steps energy fn energy fn accept metropolis hastings accept energy prev hamiltonian positions initial vel ...
def hmc_move s_rng positions energy_fn stepsize n_steps initial_vel s_rng normal size positions shape final_pos final_vel simulate_dynamics initial_pos positions initial_vel initial_vel stepsize stepsize n_steps n_steps energy_fn energy_fn accept metropolis_hastings_accept energy_prev hamiltonian positions initial_vel ...
71
python-test-1419
python
What gives label index as bth unique value ?
x[a][b
def make grid to short label dataset unique values [sorted list frozenset column for column in dataset y[ 5] transpose ]category index dataset label name to index['category']unique categories unique values[category index]category to name dataset label to value funcs[category index]if any category to name category 'blan...
def _make_grid_to_short_label dataset unique_values [sorted list frozenset column for column in dataset y[ 5] transpose ]category_index dataset label_name_to_index['category']unique_categories unique_values[category_index]category_to_name dataset label_to_value_funcs[category_index]if any category_to_name category 'bla...
79
python-test-1420
python
What does x[a][b give as bth unique value ?
label index
def make grid to short label dataset unique values [sorted list frozenset column for column in dataset y[ 5] transpose ]category index dataset label name to index['category']unique categories unique values[category index]category to name dataset label to value funcs[category index]if any category to name category 'blan...
def _make_grid_to_short_label dataset unique_values [sorted list frozenset column for column in dataset y[ 5] transpose ]category_index dataset label_name_to_index['category']unique_categories unique_values[category_index]category_to_name dataset label_to_value_funcs[category_index]if any category_to_name category 'bla...
79
python-test-1421
python
For what purpose does x[a][b give label index ?
as bth unique value
def make grid to short label dataset unique values [sorted list frozenset column for column in dataset y[ 5] transpose ]category index dataset label name to index['category']unique categories unique values[category index]category to name dataset label to value funcs[category index]if any category to name category 'blan...
def _make_grid_to_short_label dataset unique_values [sorted list frozenset column for column in dataset y[ 5] transpose ]category_index dataset label_name_to_index['category']unique_categories unique_values[category_index]category_to_name dataset label_to_value_funcs[category_index]if any category_to_name category 'bla...
79
python-test-1423
python
How does the code obtain foreignkey instances ?
via the cache
def cache model model timeout None if hasattr model 'get cached' returndef clear cache sender instance *args **kwargs '\n Clearsthecacheforthegiveninstance \n'delete instance sender instance post save connect clear cache sender model weak False post delete connect clear cache sender model weak False @classmethoddef get...
def cache_model model timeout None if hasattr model 'get_cached' returndef clear_cache sender instance *args **kwargs '\nClearsthecacheforthegiveninstance \n'delete_instance sender instance post_save connect clear_cache sender model weak False post_delete connect clear_cache sender model weak False @classmethoddef get ...
67
python-test-1424
python
What does the code add to the given model to obtain foreignkey instances via the cache ?
utility methods
def cache model model timeout None if hasattr model 'get cached' returndef clear cache sender instance *args **kwargs '\n Clearsthecacheforthegiveninstance \n'delete instance sender instance post save connect clear cache sender model weak False post delete connect clear cache sender model weak False @classmethoddef get...
def cache_model model timeout None if hasattr model 'get_cached' returndef clear_cache sender instance *args **kwargs '\nClearsthecacheforthegiveninstance \n'delete_instance sender instance post_save connect clear_cache sender model weak False post_delete connect clear_cache sender model weak False @classmethoddef get ...
67
python-test-1425
python
For what purpose does the code add utility methods to the given model ?
to obtain foreignkey instances via the cache
def cache model model timeout None if hasattr model 'get cached' returndef clear cache sender instance *args **kwargs '\n Clearsthecacheforthegiveninstance \n'delete instance sender instance post save connect clear cache sender model weak False post delete connect clear cache sender model weak False @classmethoddef get...
def cache_model model timeout None if hasattr model 'get_cached' returndef clear_cache sender instance *args **kwargs '\nClearsthecacheforthegiveninstance \n'delete_instance sender instance post_save connect clear_cache sender model weak False post_delete connect clear_cache sender model weak False @classmethoddef get ...
67
python-test-1426
python
What does the code obtain via the cache ?
foreignkey instances
def cache model model timeout None if hasattr model 'get cached' returndef clear cache sender instance *args **kwargs '\n Clearsthecacheforthegiveninstance \n'delete instance sender instance post save connect clear cache sender model weak False post delete connect clear cache sender model weak False @classmethoddef get...
def cache_model model timeout None if hasattr model 'get_cached' returndef clear_cache sender instance *args **kwargs '\nClearsthecacheforthegiveninstance \n'delete_instance sender instance post_save connect clear_cache sender model weak False post_delete connect clear_cache sender model weak False @classmethoddef get ...
67
python-test-1427
python
What does the code execute ?
the main body of the script
def main args None parser argparse Argument Parser description ' Loada YAM Lfilewithoutperforminganytraining ' parser add argument 'yaml file' type argparse File Type 'r' help ' The YAM Lfiletoload ' parser add argument '-N' '--no-instantiate' action 'store const' default False const True help ' Onlyverifythatthe YAM L...
def main args None parser argparse ArgumentParser description 'LoadaYAMLfilewithoutperforminganytraining ' parser add_argument 'yaml_file' type argparse FileType 'r' help 'TheYAMLfiletoload ' parser add_argument '-N' '--no-instantiate' action 'store_const' default False const True help 'OnlyverifythattheYAMLparsescorre...
92
python-test-1428
python
What is using the python cprofile module ?
spatialpooler
def profile SP sp Class sp Dim n Runs in Dim [10000 1 1]col Dim [sp Dim 1 1]sp sp Class input Dimensions in Dim column Dimensions col Dim potential Radius 3 potential Pct 0 5 global Inhibition False local Area Density -1 0 num Active Columns Per Inh Area 3 stimulus Threshold 1 syn Perm Inactive Dec 0 01 syn Perm Active...
def profileSP spClass spDim nRuns inDim [10000 1 1]colDim [spDim 1 1]sp spClass inputDimensions inDim columnDimensions colDim potentialRadius 3 potentialPct 0 5 globalInhibition False localAreaDensity -1 0 numActiveColumnsPerInhArea 3 stimulusThreshold 1 synPermInactiveDec 0 01 synPermActiveInc 0 1 synPermConnected 0 1...
131
python-test-1429
python
What do spatialpooler use ?
the python cprofile module
def profile SP sp Class sp Dim n Runs in Dim [10000 1 1]col Dim [sp Dim 1 1]sp sp Class input Dimensions in Dim column Dimensions col Dim potential Radius 3 potential Pct 0 5 global Inhibition False local Area Density -1 0 num Active Columns Per Inh Area 3 stimulus Threshold 1 syn Perm Inactive Dec 0 01 syn Perm Active...
def profileSP spClass spDim nRuns inDim [10000 1 1]colDim [spDim 1 1]sp spClass inputDimensions inDim columnDimensions colDim potentialRadius 3 potentialPct 0 5 globalInhibition False localAreaDensity -1 0 numActiveColumnsPerInhArea 3 stimulusThreshold 1 synPermInactiveDec 0 01 synPermActiveInc 0 1 synPermConnected 0 1...
131
python-test-1430
python
What does the code retrieve ?
the data of a scan
@get '/scan/<taskid>/data' def scan data taskid json data message list json errors message list if taskid not in Data Store tasks logger warning '[%s] Invalidtask I Dprovidedtoscan data ' % taskid return jsonize {'success' False 'message' ' Invalidtask ID'} for status content type value in Data Store current db execute...
@get '/scan/<taskid>/data' def scan_data taskid json_data_message list json_errors_message list if taskid not in DataStore tasks logger warning '[%s]InvalidtaskIDprovidedtoscan_data ' % taskid return jsonize {'success' False 'message' 'InvalidtaskID'} for status content_type value in DataStore current_db execute 'SELEC...
117
python-test-1431
python
What does the code get from mercurial ?
the list of changed or added files
@status ' Gettingthelistoffilesthathavebeenadded/changed' info lambda x n files str len x def changed files if not os path isdir os path join SRCDIR ' hg' sys exit 'needacheckouttogetmodifiedfiles' cmd 'hgstatus--added--modified--no-status'if mq patches applied cmd + '--revqparent'with subprocess Popen cmd split stdout...
@status 'Gettingthelistoffilesthathavebeenadded/changed' info lambda x n_files_str len x def changed_files if not os path isdir os path join SRCDIR ' hg' sys exit 'needacheckouttogetmodifiedfiles' cmd 'hgstatus--added--modified--no-status'if mq_patches_applied cmd + '--revqparent'with subprocess Popen cmd split stdout ...
54
python-test-1432
python
What does the code remove ?
references to any sdks not available
def check for unavailable sdk config vars cflags config vars get 'CFLAGS' '' m re search '-isysroot\\s+ \\S+ ' cflags if m is not None sdk m group 1 if not os path exists sdk for cv in UNIVERSAL CONFIG VARS if cv in config vars and cv not in os environ flags config vars[cv]flags re sub '-isysroot\\s+\\S+ ? \\s $ ' '' f...
def _check_for_unavailable_sdk _config_vars cflags _config_vars get 'CFLAGS' '' m re search '-isysroot\\s+ \\S+ ' cflags if m is not None sdk m group 1 if not os path exists sdk for cv in _UNIVERSAL_CONFIG_VARS if cv in _config_vars and cv not in os environ flags _config_vars[cv]flags re sub '-isysroot\\s+\\S+ ? \\s $ ...
74
python-test-1433
python
What does the code get ?
the location of the config file
def matplotlib fname if six PY 2 cwd os getcwdu else cwd os getcwd fname os path join cwd u'matplotlibrc' if os path exists fname return fnameif u'MATPLOTLIBRC' in os environ path os environ[u'MATPLOTLIBRC']if os path exists path if os path isfile path return pathfname os path join path u'matplotlibrc' if os path exist...
def matplotlib_fname if six PY2 cwd os getcwdu else cwd os getcwd fname os path join cwd u'matplotlibrc' if os path exists fname return fnameif u'MATPLOTLIBRC' in os environ path os environ[u'MATPLOTLIBRC']if os path exists path if os path isfile path return pathfname os path join path u'matplotlibrc' if os path exists...
99
python-test-1434
python
What does the code remove ?
the values that match the predicate from this property
def remove property value prop predicate removed vals []removed vals filter predicate prop property Value if len removed vals len prop property Value prop parent remove Property prop name else x prop property Value css Textfor v in removed vals x x replace v css Text u'' strip prop property Value css Text xreturn bool ...
def remove_property_value prop predicate removed_vals []removed_vals filter predicate prop propertyValue if len removed_vals len prop propertyValue prop parent removeProperty prop name else x prop propertyValue cssTextfor v in removed_vals x x replace v cssText u'' strip prop propertyValue cssText xreturn bool removed_...
57
python-test-1435
python
What do the values match ?
the predicate from this property
def remove property value prop predicate removed vals []removed vals filter predicate prop property Value if len removed vals len prop property Value prop parent remove Property prop name else x prop property Value css Textfor v in removed vals x x replace v css Text u'' strip prop property Value css Text xreturn bool ...
def remove_property_value prop predicate removed_vals []removed_vals filter predicate prop propertyValue if len removed_vals len prop propertyValue prop parent removeProperty prop name else x prop propertyValue cssTextfor v in removed_vals x x replace v cssText u'' strip prop propertyValue cssText xreturn bool removed_...
57
python-test-1436
python
In which direction do tars dir ?
into file
def tar file dir expression '^ +$' filenames None exclude content from None tar tarfile Tar File file 'w' try if filenames is None filenames listdir dir expression add dirs True exclude content from exclude content from for file in filenames tar add os path join dir file file False finally tar close
def tar file dir expression '^ +$' filenames None exclude_content_from None tar tarfile TarFile file 'w' try if filenames is None filenames listdir dir expression add_dirs True exclude_content_from exclude_content_from for file in filenames tar add os path join dir file file False finally tar close
53
python-test-1437
python
What has the same md5 hash as the one on disk ?
src_file
def md 5 sum is current src file src md 5 get md 5 sum src file src md 5 file src file + ' md 5 ' if os path exists src md 5 file with open src md 5 file 'r' as file checksum ref md 5 file checksum read return src md 5 ref md 5 return False
def md5sum_is_current src_file src_md5 get_md5sum src_file src_md5_file src_file + ' md5' if os path exists src_md5_file with open src_md5_file 'r' as file_checksum ref_md5 file_checksum read return src_md5 ref_md5 return False
61
python-test-1438
python
What does src_file have ?
the same md5 hash as the one on disk
def md 5 sum is current src file src md 5 get md 5 sum src file src md 5 file src file + ' md 5 ' if os path exists src md 5 file with open src md 5 file 'r' as file checksum ref md 5 file checksum read return src md 5 ref md 5 return False
def md5sum_is_current src_file src_md5 get_md5sum src_file src_md5_file src_file + ' md5' if os path exists src_md5_file with open src_md5_file 'r' as file_checksum ref_md5 file_checksum read return src_md5 ref_md5 return False
61
python-test-1446
python
What does the code evaluate ?
wether a file
def is python interpreter filename real filename os path realpath filename if not osp isfile real filename or encoding is text file real filename or not is python interpreter valid name filename return Falsetry proc run program filename ['-h'] output to text string proc communicate [0 ] valid ' Optionsandarguments andc...
def is_python_interpreter filename real_filename os path realpath filename if not osp isfile real_filename or encoding is_text_file real_filename or not is_python_interpreter_valid_name filename return Falsetry proc run_program filename ['-h'] output to_text_string proc communicate [0] valid 'Optionsandarguments andcor...
66
python-test-1467
python
What does the code convert into a human readable form in bytes ?
a size
def human readable size sep '' divisor suffix 1 'B' for i candidate in enumerate 'B' 'KB' 'MB' 'GB' 'TB' 'PB' 'EB' if size < 1 << i + 1 * 10 divisor suffix 1 << i * 10 candidate breaksize str float size / divisor if size find ' ' > -1 size size[ size find ' ' + 2 ]if size endswith ' 0' size size[ -2 ]return size + sep ...
def human_readable size sep '' divisor suffix 1 'B' for i candidate in enumerate 'B' 'KB' 'MB' 'GB' 'TB' 'PB' 'EB' if size < 1 << i + 1 * 10 divisor suffix 1 << i * 10 candidate breaksize str float size / divisor if size find ' ' > -1 size size[ size find ' ' + 2 ]if size endswith ' 0' size size[ -2 ]return size + sep ...
75
python-test-1469
python
What did internal method use ?
to create asset key from string and remove asset by calling delete_asset method of assets module
def delete asset course key asset key string if asset key string try asset key Asset Key from string asset key string except Invalid Key Error if '/' asset key string[ 0 ] asset key string asset key string[ 1 ]try asset key Asset Key from string asset key string except Invalid Key Error LOGGER info ' Incourse%r unablet...
def _delete_asset course_key asset_key_string if asset_key_string try asset_key AssetKey from_string asset_key_string except InvalidKeyError if '/' asset_key_string[0] asset_key_string asset_key_string[1 ]try asset_key AssetKey from_string asset_key_string except InvalidKeyError LOGGER info 'Incourse%r unabletoparseass...
92
python-test-1470
python
In which direction did asset key create by calling delete_asset method of assets module ?
from string
def delete asset course key asset key string if asset key string try asset key Asset Key from string asset key string except Invalid Key Error if '/' asset key string[ 0 ] asset key string asset key string[ 1 ]try asset key Asset Key from string asset key string except Invalid Key Error LOGGER info ' Incourse%r unablet...
def _delete_asset course_key asset_key_string if asset_key_string try asset_key AssetKey from_string asset_key_string except InvalidKeyError if '/' asset_key_string[0] asset_key_string asset_key_string[1 ]try asset_key AssetKey from_string asset_key_string except InvalidKeyError LOGGER info 'Incourse%r unabletoparseass...
92
python-test-1472
python
What did the code extend ?
euclidean algorithm of f and g
@publicdef gcdex f g *gens **args options allowed flags args ['auto' 'polys'] try F G opt parallel poly from expr f g *gens **args except Polification Failed as exc domain a b construct domain exc exprs try s t h domain gcdex a b except Not Implemented Error raise Computation Failed 'gcdex' 2 exc else return domain to ...
@publicdef gcdex f g *gens **args options allowed_flags args ['auto' 'polys'] try F G opt parallel_poly_from_expr f g *gens **args except PolificationFailed as exc domain a b construct_domain exc exprs try s t h domain gcdex a b except NotImplementedError raise ComputationFailed 'gcdex' 2 exc else return domain to_symp...
96
python-test-1475
python
What does the code calculate ?
a sobel filter
@docfillerdef sobel input axis -1 output None mode 'reflect' cval 0 0 input numpy asarray input axis ni support check axis axis input ndim output return value ni support get output output input modes ni support normalize sequence mode input ndim correlate 1 d input [ -1 0 1] axis output modes[axis] cval 0 axes [ii for ...
@docfillerdef sobel input axis -1 output None mode 'reflect' cval 0 0 input numpy asarray input axis _ni_support _check_axis axis input ndim output return_value _ni_support _get_output output input modes _ni_support _normalize_sequence mode input ndim correlate1d input [ -1 0 1] axis output modes[axis] cval 0 axes [ii ...
84
python-test-1479
python
What does the code return using a bilinear transform ?
a digital filter
def zpkbilinear z p k fs z atleast 1d z p atleast 1d p degree relative degree z p fs 2 2 * fs z z fs 2 + z / fs 2 - z p z fs 2 + p / fs 2 - p z z append z z - ones degree k z k * real prod fs 2 - z / prod fs 2 - p return z z p z k z
def _zpkbilinear z p k fs z atleast_1d z p atleast_1d p degree _relative_degree z p fs2 2 * fs z_z fs2 + z / fs2 - z p_z fs2 + p / fs2 - p z_z append z_z - ones degree k_z k * real prod fs2 - z / prod fs2 - p return z_z p_z k_z
77
python-test-1480
python
For what purpose do shapes generate ?
to test casting
def gencastshapes for n in range 32 yield [n] ndim randrange 4 6 minshape 1 if randrange 100 > 80 else 2 yield [randrange minshape 5 for in range ndim ] ndim randrange 2 4 minshape 1 if randrange 100 > 80 else 2 yield [randrange minshape 5 for in range ndim ]
def gencastshapes for n in range 32 yield [n] ndim randrange 4 6 minshape 1 if randrange 100 > 80 else 2 yield [randrange minshape 5 for _ in range ndim ] ndim randrange 2 4 minshape 1 if randrange 100 > 80 else 2 yield [randrange minshape 5 for _ in range ndim ]
53
python-test-1482
python
What did the code set ?
the hydroquebec sensor
def setup platform hass config add devices discovery info None username config get CONF USERNAME password config get CONF PASSWORD try hydroquebec data Hydroquebec Data username password hydroquebec data update except requests exceptions HTTP Error as error LOGGER error error return Falsename config get CONF NAME senso...
def setup_platform hass config add_devices discovery_info None username config get CONF_USERNAME password config get CONF_PASSWORD try hydroquebec_data HydroquebecData username password hydroquebec_data update except requests exceptions HTTPError as error _LOGGER error error return Falsename config get CONF_NAME sensor...
65
python-test-1485
python
What does the code form to form the weighted geometric mean t < = x^p ?
the internal cxvpy constraints
def gm constrs t x list p assert is weight p w dyad completion p tree decompose w d defaultdict lambda lu create var t size d[w] tif len x list < len w x list + [t]assert len x list len w for i p v in enumerate zip w x list if p > 0 tmp [0 ] * len w tmp[i] 1d[tuple tmp ] vconstraints []for elem children in tree items i...
def gm_constrs t x_list p assert is_weight p w dyad_completion p tree decompose w d defaultdict lambda lu create_var t size d[w] tif len x_list < len w x_list + [t]assert len x_list len w for i p v in enumerate zip w x_list if p > 0 tmp [0] * len w tmp[i] 1d[tuple tmp ] vconstraints []for elem children in tree items if...
91
python-test-1486
python
For what purpose does the code form the internal cxvpy constraints ?
to form the weighted geometric mean t < = x^p
def gm constrs t x list p assert is weight p w dyad completion p tree decompose w d defaultdict lambda lu create var t size d[w] tif len x list < len w x list + [t]assert len x list len w for i p v in enumerate zip w x list if p > 0 tmp [0 ] * len w tmp[i] 1d[tuple tmp ] vconstraints []for elem children in tree items i...
def gm_constrs t x_list p assert is_weight p w dyad_completion p tree decompose w d defaultdict lambda lu create_var t size d[w] tif len x_list < len w x_list + [t]assert len x_list len w for i p v in enumerate zip w x_list if p > 0 tmp [0] * len w tmp[i] 1d[tuple tmp ] vconstraints []for elem children in tree items if...
91
python-test-1488
python
What does the code find ?
the changes between two playlists
def find playlist changes orig tracks modified tracks s pairs get id pairs orig tracks d pairs get id pairs modified tracks s count Counter s pairs d count Counter d pairs to del s count - d count to add d count - s count to keep set s count & d count return to del to add to keep
def find_playlist_changes orig_tracks modified_tracks s_pairs get_id_pairs orig_tracks d_pairs get_id_pairs modified_tracks s_count Counter s_pairs d_count Counter d_pairs to_del s_count - d_count to_add d_count - s_count to_keep set s_count & d_count return to_del to_add to_keep
61
python-test-1494
python
What do the ldev meet ?
the criteria for being managed by the driver
def check ldev ldev info ldev existing ref if ldev info['sts'] NORMAL STS msg utils output log MSG INVALID LDEV FOR MANAGE raise exception Manage Existing Invalid Reference existing ref existing ref reason msg vol attr set ldev info['vol attr'] if not ldev info['vol type'] startswith 'OPEN-V' or len vol attr < 2 or not...
def _check_ldev ldev_info ldev existing_ref if ldev_info['sts'] NORMAL_STS msg utils output_log MSG INVALID_LDEV_FOR_MANAGE raise exception ManageExistingInvalidReference existing_ref existing_ref reason msg vol_attr set ldev_info['vol_attr'] if not ldev_info['vol_type'] startswith 'OPEN-V' or len vol_attr < 2 or not v...
151
python-test-1495
python
What meets the criteria for being managed by the driver ?
the ldev
def check ldev ldev info ldev existing ref if ldev info['sts'] NORMAL STS msg utils output log MSG INVALID LDEV FOR MANAGE raise exception Manage Existing Invalid Reference existing ref existing ref reason msg vol attr set ldev info['vol attr'] if not ldev info['vol type'] startswith 'OPEN-V' or len vol attr < 2 or not...
def _check_ldev ldev_info ldev existing_ref if ldev_info['sts'] NORMAL_STS msg utils output_log MSG INVALID_LDEV_FOR_MANAGE raise exception ManageExistingInvalidReference existing_ref existing_ref reason msg vol_attr set ldev_info['vol_attr'] if not ldev_info['vol_type'] startswith 'OPEN-V' or len vol_attr < 2 or not v...
151
python-test-1496
python
What does the code send to the recipient ?
a copy of this draft
def send draft copy account draft custom body recipient response on success encode draft response on success['body'] custom bodyresponse on success API Encoder jsonify response on success try sendmail client get sendmail client account sendmail client send custom draft custom body [recipient] except Send Mail Exception...
def send_draft_copy account draft custom_body recipient response_on_success encode draft response_on_success['body'] custom_bodyresponse_on_success APIEncoder jsonify response_on_success try sendmail_client get_sendmail_client account sendmail_client send_custom draft custom_body [recipient] except SendMailException as...
74
python-test-1498
python
Who marks them with overlap = -1 ?
proposals
def filter crowd proposals roidb crowd thresh for ix entry in enumerate roidb overlaps entry['gt overlaps'] toarray crowd inds np where overlaps max axis 1 -1 [0 ]non gt inds np where entry['gt classes'] 0 [0 ]if len crowd inds 0 or len non gt inds 0 continueiscrowd [int True for in xrange len crowd inds ]crowd boxes d...
def _filter_crowd_proposals roidb crowd_thresh for ix entry in enumerate roidb overlaps entry['gt_overlaps'] toarray crowd_inds np where overlaps max axis 1 -1 [0]non_gt_inds np where entry['gt_classes'] 0 [0]if len crowd_inds 0 or len non_gt_inds 0 continueiscrowd [int True for _ in xrange len crowd_inds ]crowd_boxes ...
115