body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1
value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
7d902204e1fc491288da87c85dc6b203c2324b020ecf3be1c2fca36879f74bd3 | def negL_rhoomega_viaHDPTopicUtil(rho=None, omega=None, nDoc=0, sumLogPiActiveVec=None, sumLogPiRemVec=None, alpha=0.5, gamma=1.0, **kwargs):
' Compute minimization objective another way, using utility funcs.\n\n This allows verifying that our negL_rhoomega function is correct.\n\n Returns\n -------\n n... | Compute minimization objective another way, using utility funcs.
This allows verifying that our negL_rhoomega function is correct.
Returns
-------
negL : -1 * L(rho, omega, ...)
Should be the same value as negL_rhoomega. | bnpy/allocmodel/topics/OptimizerRhoOmegaBetter.py | negL_rhoomega_viaHDPTopicUtil | tinnguyen96/bnpy | 184 | python | def negL_rhoomega_viaHDPTopicUtil(rho=None, omega=None, nDoc=0, sumLogPiActiveVec=None, sumLogPiRemVec=None, alpha=0.5, gamma=1.0, **kwargs):
' Compute minimization objective another way, using utility funcs.\n\n This allows verifying that our negL_rhoomega function is correct.\n\n Returns\n -------\n n... | def negL_rhoomega_viaHDPTopicUtil(rho=None, omega=None, nDoc=0, sumLogPiActiveVec=None, sumLogPiRemVec=None, alpha=0.5, gamma=1.0, **kwargs):
' Compute minimization objective another way, using utility funcs.\n\n This allows verifying that our negL_rhoomega function is correct.\n\n Returns\n -------\n n... |
58b24c87ccef453e25661567f2b0ca723fcd8a95d49b06444a4630f01ea4e721 | def __init__(self, name, Q, x_initial, P_initial, dim_main, dim_main_err, N=0, dim_augment=0, dim_augment_err=0, maha_test_kinds=[]):
'\n Generates process function and all\n observation functions for the kalman\n filter.\n '
if (N > 0):
self.msckf = True
else:
self.msckf = False... | Generates process function and all
observation functions for the kalman
filter. | examples/kalman/ekf_sym.py | __init__ | spectatorearth/laika | 116 | python | def __init__(self, name, Q, x_initial, P_initial, dim_main, dim_main_err, N=0, dim_augment=0, dim_augment_err=0, maha_test_kinds=[]):
'\n Generates process function and all\n observation functions for the kalman\n filter.\n '
if (N > 0):
self.msckf = True
else:
self.msckf = False... | def __init__(self, name, Q, x_initial, P_initial, dim_main, dim_main_err, N=0, dim_augment=0, dim_augment_err=0, maha_test_kinds=[]):
'\n Generates process function and all\n observation functions for the kalman\n filter.\n '
if (N > 0):
self.msckf = True
else:
self.msckf = False... |
4404359376efac51f8ed4e3269a3e7dc681ae569ee6b8207e1f0bc986bded956 | def _predict_and_update_batch(self, t, kind, z, R, extra_args, augment=False):
'The main kalman filter function\n Predicts the state and then updates a batch of observations\n\n dim_x: dimensionality of the state space\n dim_z: dimensionality of the observation and depends on kind\n n: number of observa... | The main kalman filter function
Predicts the state and then updates a batch of observations
dim_x: dimensionality of the state space
dim_z: dimensionality of the observation and depends on kind
n: number of observations
Args:
t (float): Time of observation
kind (int): Type of observ... | examples/kalman/ekf_sym.py | _predict_and_update_batch | spectatorearth/laika | 116 | python | def _predict_and_update_batch(self, t, kind, z, R, extra_args, augment=False):
'The main kalman filter function\n Predicts the state and then updates a batch of observations\n\n dim_x: dimensionality of the state space\n dim_z: dimensionality of the observation and depends on kind\n n: number of observa... | def _predict_and_update_batch(self, t, kind, z, R, extra_args, augment=False):
'The main kalman filter function\n Predicts the state and then updates a batch of observations\n\n dim_x: dimensionality of the state space\n dim_z: dimensionality of the observation and depends on kind\n n: number of observa... |
77c0f648a8667e7c099e8cca28fc97bb5e647b71d91f6784306d080471b3dd31 | def rts_smooth(self, estimates, norm_quats=False):
'\n Returns rts smoothed results of\n kalman filter estimates\n\n If the kalman state is augmented with\n old states only the main state is smoothed\n '
xk_n = estimates[(- 1)][0]
Pk_n = estimates[(- 1)][2]
Fk_1 = np.zeros(Pk_n.shape, dty... | Returns rts smoothed results of
kalman filter estimates
If the kalman state is augmented with
old states only the main state is smoothed | examples/kalman/ekf_sym.py | rts_smooth | spectatorearth/laika | 116 | python | def rts_smooth(self, estimates, norm_quats=False):
'\n Returns rts smoothed results of\n kalman filter estimates\n\n If the kalman state is augmented with\n old states only the main state is smoothed\n '
xk_n = estimates[(- 1)][0]
Pk_n = estimates[(- 1)][2]
Fk_1 = np.zeros(Pk_n.shape, dty... | def rts_smooth(self, estimates, norm_quats=False):
'\n Returns rts smoothed results of\n kalman filter estimates\n\n If the kalman state is augmented with\n old states only the main state is smoothed\n '
xk_n = estimates[(- 1)][0]
Pk_n = estimates[(- 1)][2]
Fk_1 = np.zeros(Pk_n.shape, dty... |
3b7ed0af9deec8eaf12aa117b4f3d5bdd3e40e848a0790f48ad1d204f1edeecc | def test_invalid_user_credentials(self):
'\n Test get token pair view with invalid user credentials.\n '
response = self.client.post(reverse('paseto_auth:get_token_pair'), data={'username': 'testuser', 'password': '1234'})
self.assertEqual(response.status_code, 401)
self.assertEqual(respon... | Test get token pair view with invalid user credentials. | tests/test_views.py | test_invalid_user_credentials | moiseshiraldo/django-rest-paseto-auth | 7 | python | def test_invalid_user_credentials(self):
'\n \n '
response = self.client.post(reverse('paseto_auth:get_token_pair'), data={'username': 'testuser', 'password': '1234'})
self.assertEqual(response.status_code, 401)
self.assertEqual(response.json()['detail'], 'Incorrect authentication credenti... | def test_invalid_user_credentials(self):
'\n \n '
response = self.client.post(reverse('paseto_auth:get_token_pair'), data={'username': 'testuser', 'password': '1234'})
self.assertEqual(response.status_code, 401)
self.assertEqual(response.json()['detail'], 'Incorrect authentication credenti... |
5f7c4bc04636ebc2be6ac12e869aec52f6e186dc9670c7e255493c83962986a5 | def test_get_token_pair(self):
'\n Test get token pair view with valid user credentials.\n '
response = self.client.post(reverse('paseto_auth:get_token_pair'), data=self.user_credentials)
self.assertEqual(response.status_code, 200)
self.assertTrue(response.json().get('refresh_token'))
... | Test get token pair view with valid user credentials. | tests/test_views.py | test_get_token_pair | moiseshiraldo/django-rest-paseto-auth | 7 | python | def test_get_token_pair(self):
'\n \n '
response = self.client.post(reverse('paseto_auth:get_token_pair'), data=self.user_credentials)
self.assertEqual(response.status_code, 200)
self.assertTrue(response.json().get('refresh_token'))
self.assertTrue(response.json().get('access_token'))
... | def test_get_token_pair(self):
'\n \n '
response = self.client.post(reverse('paseto_auth:get_token_pair'), data=self.user_credentials)
self.assertEqual(response.status_code, 200)
self.assertTrue(response.json().get('refresh_token'))
self.assertTrue(response.json().get('access_token'))
... |
a22ed3df67feae56ab1d9bfa1123efd62b07c2ecbdefce76ed5de1d57a1132b2 | def test_invalid_refresh_token(self):
'\n Test get access token view with invalid refresh token.\n '
response = self.client.post(reverse('paseto_auth:get_access_token'), data={'refresh_token': 'qwerty'})
self.assertEqual(response.status_code, 401)
self.assertEqual(response.json()['detail']... | Test get access token view with invalid refresh token. | tests/test_views.py | test_invalid_refresh_token | moiseshiraldo/django-rest-paseto-auth | 7 | python | def test_invalid_refresh_token(self):
'\n \n '
response = self.client.post(reverse('paseto_auth:get_access_token'), data={'refresh_token': 'qwerty'})
self.assertEqual(response.status_code, 401)
self.assertEqual(response.json()['detail'], 'Invalid refresh token.') | def test_invalid_refresh_token(self):
'\n \n '
response = self.client.post(reverse('paseto_auth:get_access_token'), data={'refresh_token': 'qwerty'})
self.assertEqual(response.status_code, 401)
self.assertEqual(response.json()['detail'], 'Invalid refresh token.')<|docstring|>Test get acces... |
60bb9b393c9981f8617a9795123025c3b5fbb3e5fb2830e84d5139b7a934b925 | def test_expired_refresh_token(self):
'\n Test get access token view with expired refresh token.\n '
data = {'model': 'user', 'pk': self.user.pk, 'key': 'qwerty', 'type': tokens.REFRESH, 'exp': pendulum.now().subtract(seconds=10).to_atom_string()}
refresh_token = paseto.create(key=bytes.fromhe... | Test get access token view with expired refresh token. | tests/test_views.py | test_expired_refresh_token | moiseshiraldo/django-rest-paseto-auth | 7 | python | def test_expired_refresh_token(self):
'\n \n '
data = {'model': 'user', 'pk': self.user.pk, 'key': 'qwerty', 'type': tokens.REFRESH, 'exp': pendulum.now().subtract(seconds=10).to_atom_string()}
refresh_token = paseto.create(key=bytes.fromhex(AUTH_SETTINGS['SECRET_KEY']), purpose='local', claim... | def test_expired_refresh_token(self):
'\n \n '
data = {'model': 'user', 'pk': self.user.pk, 'key': 'qwerty', 'type': tokens.REFRESH, 'exp': pendulum.now().subtract(seconds=10).to_atom_string()}
refresh_token = paseto.create(key=bytes.fromhex(AUTH_SETTINGS['SECRET_KEY']), purpose='local', claim... |
165a169990744fc71cccebd6fd383b298535bb21a7f78d018f7aa23973e8c865 | def test_get_access_token(self):
'\n Test get access token view.\n '
response = self.client.post(reverse('paseto_auth:get_token_pair'), data=self.user_credentials)
refresh_token = response.json()['refresh_token']
response = self.client.post(reverse('paseto_auth:get_access_token'), data={'r... | Test get access token view. | tests/test_views.py | test_get_access_token | moiseshiraldo/django-rest-paseto-auth | 7 | python | def test_get_access_token(self):
'\n \n '
response = self.client.post(reverse('paseto_auth:get_token_pair'), data=self.user_credentials)
refresh_token = response.json()['refresh_token']
response = self.client.post(reverse('paseto_auth:get_access_token'), data={'refresh_token': refresh_toke... | def test_get_access_token(self):
'\n \n '
response = self.client.post(reverse('paseto_auth:get_token_pair'), data=self.user_credentials)
refresh_token = response.json()['refresh_token']
response = self.client.post(reverse('paseto_auth:get_access_token'), data={'refresh_token': refresh_toke... |
7502671c11b48096bc3ca27147dabebe1094cbbfa7ed6dcf80aaa736dc586e3b | def __init__(self, emr_client, cache_filepath, cache_file_ttl, list_frequency=_DEFAULT_CACHE_LIST_FREQUENCY_SECONDS):
'Init cluster cache.\n\n :param emr_client: boto3 EMR client to use for list and describe calls\n :param cache_filepath: absolute local path to the cluster cache\n :param cache_... | Init cluster cache.
:param emr_client: boto3 EMR client to use for list and describe calls
:param cache_filepath: absolute local path to the cluster cache
:param cache_file_ttl: expire (truncate) the cache after this many days
:param list_frequency: list at most only every this many seconds | mrjob/cache.py | __init__ | Affirm/mrjob | 4 | python | def __init__(self, emr_client, cache_filepath, cache_file_ttl, list_frequency=_DEFAULT_CACHE_LIST_FREQUENCY_SECONDS):
'Init cluster cache.\n\n :param emr_client: boto3 EMR client to use for list and describe calls\n :param cache_filepath: absolute local path to the cluster cache\n :param cache_... | def __init__(self, emr_client, cache_filepath, cache_file_ttl, list_frequency=_DEFAULT_CACHE_LIST_FREQUENCY_SECONDS):
'Init cluster cache.\n\n :param emr_client: boto3 EMR client to use for list and describe calls\n :param cache_filepath: absolute local path to the cluster cache\n :param cache_... |
1744d02d5919279d649feb5eafa4da8e877733ecbac80a1fd78ab7d76589f6ff | def _emr_cluster_describe(self, cluster_id):
'Describe the cluster and get the instance group/fleet info.'
cluster_info = self._emr_client.describe_cluster(ClusterId=cluster_id)['Cluster']
collect_type = cluster_info.get('InstanceCollectionType', None)
if (collect_type == 'INSTANCE_FLEET'):
inst... | Describe the cluster and get the instance group/fleet info. | mrjob/cache.py | _emr_cluster_describe | Affirm/mrjob | 4 | python | def _emr_cluster_describe(self, cluster_id):
cluster_info = self._emr_client.describe_cluster(ClusterId=cluster_id)['Cluster']
collect_type = cluster_info.get('InstanceCollectionType', None)
if (collect_type == 'INSTANCE_FLEET'):
instance_info = list(_boto3_paginate('InstanceFleets', self._emr_... | def _emr_cluster_describe(self, cluster_id):
cluster_info = self._emr_client.describe_cluster(ClusterId=cluster_id)['Cluster']
collect_type = cluster_info.get('InstanceCollectionType', None)
if (collect_type == 'INSTANCE_FLEET'):
instance_info = list(_boto3_paginate('InstanceFleets', self._emr_... |
035074c9fec5cbaf6af1947fd33f1778e457ef2f6cc9ef2e78d175222d7a687e | def describe_cluster(self, cluster_id):
'Describes an EMR cluster from the given ID. Also describes and\n caches the instance group/fleet info.\n\n If cluster info for this ID exists in the cache return this data;\n otherwise make an EMR API call to retry this data. Since mrjob clusters\n ... | Describes an EMR cluster from the given ID. Also describes and
caches the instance group/fleet info.
If cluster info for this ID exists in the cache return this data;
otherwise make an EMR API call to retry this data. Since mrjob clusters
should never be modified, this cached data will always be valid except
cluster s... | mrjob/cache.py | describe_cluster | Affirm/mrjob | 4 | python | def describe_cluster(self, cluster_id):
'Describes an EMR cluster from the given ID. Also describes and\n caches the instance group/fleet info.\n\n If cluster info for this ID exists in the cache return this data;\n otherwise make an EMR API call to retry this data. Since mrjob clusters\n ... | def describe_cluster(self, cluster_id):
'Describes an EMR cluster from the given ID. Also describes and\n caches the instance group/fleet info.\n\n If cluster info for this ID exists in the cache return this data;\n otherwise make an EMR API call to retry this data. Since mrjob clusters\n ... |
473653a1f5eaba2e1eca74a57e85499a33e8292e897afce01ea1dd396e47a139 | def list_clusters_and_populate_cache(self, states, force_relist=False):
'Lists EMR clusters with specified state and populates the cache\n with their info.\n\n Only lists the clusters if the list marker file is older than the list\n frequency. Only describes the cluster info if the ID does not ... | Lists EMR clusters with specified state and populates the cache
with their info.
Only lists the clusters if the list marker file is older than the list
frequency. Only describes the cluster info if the ID does not exist in
the cache.
Additionally, we only put entries in the cache if their state matches
the specified ... | mrjob/cache.py | list_clusters_and_populate_cache | Affirm/mrjob | 4 | python | def list_clusters_and_populate_cache(self, states, force_relist=False):
'Lists EMR clusters with specified state and populates the cache\n with their info.\n\n Only lists the clusters if the list marker file is older than the list\n frequency. Only describes the cluster info if the ID does not ... | def list_clusters_and_populate_cache(self, states, force_relist=False):
'Lists EMR clusters with specified state and populates the cache\n with their info.\n\n Only lists the clusters if the list marker file is older than the list\n frequency. Only describes the cluster info if the ID does not ... |
f8234fb5e35ad1c014b66d00fb77b9df7faa945c04ee1fb912e51b7bcc513277 | @primitive_field(str)
def install_arguments(self):
'\n Optional arguments passed to the :code:`pip install` command created for the plugin installation.\n \n :rtype: str \n ' | Optional arguments passed to the :code:`pip install` command created for the plugin installation.
:rtype: str | src/cloudify/aria_extension_cloudify/v1_1/misc.py | install_arguments | tliron/aria-ng | 0 | python | @primitive_field(str)
def install_arguments(self):
'\n Optional arguments passed to the :code:`pip install` command created for the plugin installation.\n \n :rtype: str \n ' | @primitive_field(str)
def install_arguments(self):
'\n Optional arguments passed to the :code:`pip install` command created for the plugin installation.\n \n :rtype: str \n '<|docstring|>Optional arguments passed to the :code:`pip install` command created for the plugin installati... |
55af65df8ec80a34404a4f197932975d85426c32f93d15f07460373dc3aeff76 | @client.command()
async def challenge(ctx: discord.ext.commands.Context):
'Challenges user to a match'
global match_requests
message = ctx.message
challenger = message.author
member = message.mentions[0]
match_requests.append(chessgame.ChessGame(challenger, member))
(await ctx.send('User {0.... | Challenges user to a match | heroku-bot.py | challenge | Kaweees/Discord-Chess-Bot | 6 | python | @client.command()
async def challenge(ctx: discord.ext.commands.Context):
global match_requests
message = ctx.message
challenger = message.author
member = message.mentions[0]
match_requests.append(chessgame.ChessGame(challenger, member))
(await ctx.send('User {0.display_name}#{0.discriminat... | @client.command()
async def challenge(ctx: discord.ext.commands.Context):
global match_requests
message = ctx.message
challenger = message.author
member = message.mentions[0]
match_requests.append(chessgame.ChessGame(challenger, member))
(await ctx.send('User {0.display_name}#{0.discriminat... |
4ae278203479a6b58c4a163d0eebf02699717a148baa0b91bc601d27767d028a | @client.command()
async def accept(ctx: discord.ext.commands.Context):
"Accepts a user's request"
global match_requests
global matches
message = ctx.message
found = False
for request in match_requests:
if (request.players[1].id == message.author.id):
svg = request.board_to_sv... | Accepts a user's request | heroku-bot.py | accept | Kaweees/Discord-Chess-Bot | 6 | python | @client.command()
async def accept(ctx: discord.ext.commands.Context):
global match_requests
global matches
message = ctx.message
found = False
for request in match_requests:
if (request.players[1].id == message.author.id):
svg = request.board_to_svg()
with open(... | @client.command()
async def accept(ctx: discord.ext.commands.Context):
global match_requests
global matches
message = ctx.message
found = False
for request in match_requests:
if (request.players[1].id == message.author.id):
svg = request.board_to_svg()
with open(... |
cd86a74a5fdecf0679d97095616adec0dadcbb4ebf614389a3690ed1e90ff6f4 | @client.command()
async def move(ctx: discord.ext.commands.Context):
'Makes move'
global matches
message = ctx.message
move = message.content.split(' ')[1]
found = False
for match in matches:
if (match.player.id == message.author.id):
found = True
(valid, result) ... | Makes move | heroku-bot.py | move | Kaweees/Discord-Chess-Bot | 6 | python | @client.command()
async def move(ctx: discord.ext.commands.Context):
global matches
message = ctx.message
move = message.content.split(' ')[1]
found = False
for match in matches:
if (match.player.id == message.author.id):
found = True
(valid, result) = match.make... | @client.command()
async def move(ctx: discord.ext.commands.Context):
global matches
message = ctx.message
move = message.content.split(' ')[1]
found = False
for match in matches:
if (match.player.id == message.author.id):
found = True
(valid, result) = match.make... |
e6d0f03964379a631a41503fdf35dedab054f6040363630decf8458271461ab5 | @client.command()
async def end(ctx: discord.ext.commands.Context):
'Ends match, what a loser'
global matches
message = ctx.message
found = False
for match in matches:
if (match.player.id == message.author.id):
found = True
matches.remove(match)
(await ctx... | Ends match, what a loser | heroku-bot.py | end | Kaweees/Discord-Chess-Bot | 6 | python | @client.command()
async def end(ctx: discord.ext.commands.Context):
global matches
message = ctx.message
found = False
for match in matches:
if (match.player.id == message.author.id):
found = True
matches.remove(match)
(await ctx.send('Match forfeited.'))... | @client.command()
async def end(ctx: discord.ext.commands.Context):
global matches
message = ctx.message
found = False
for match in matches:
if (match.player.id == message.author.id):
found = True
matches.remove(match)
(await ctx.send('Match forfeited.'))... |
72091a5c5bea1735a4df27ba146b48f2aa0e0bb431056d52dd2fcd46582940b5 | @client.command()
async def server(ctx):
'Shows server info'
channel = ctx.message.channel
embed = discord.Embed(title="Kaweees's Player Stats", url='https://google.com')
embed.title = server.name
embed.description = 'Server Info'
embed.color = 8365648
embed.title = server.name
(await ct... | Shows server info | heroku-bot.py | server | Kaweees/Discord-Chess-Bot | 6 | python | @client.command()
async def server(ctx):
channel = ctx.message.channel
embed = discord.Embed(title="Kaweees's Player Stats", url='https://google.com')
embed.title = server.name
embed.description = 'Server Info'
embed.color = 8365648
embed.title = server.name
(await ctx.send(embed=embed)... | @client.command()
async def server(ctx):
channel = ctx.message.channel
embed = discord.Embed(title="Kaweees's Player Stats", url='https://google.com')
embed.title = server.name
embed.description = 'Server Info'
embed.color = 8365648
embed.title = server.name
(await ctx.send(embed=embed)... |
61b06c7cc99cc76c8fceee61a7bfe476116965730f4f22e4fa10e6c6083adcca | def fit_predict(self, X, y, X_test, **kwargs):
'重写继承即可\n :return: clf, score, test_preds\n '
clf = LGBMClassifier()
clf.fit(X, y)
score = roc_auc_score(y, clf.predict_proba(X)[(:, 1)])
test_preds = clf.predict_proba(X_test)
return (clf, score, test_preds) | 重写继承即可
:return: clf, score, test_preds | tql/ml/semi/pseudo.py | fit_predict | Jie-Yuan/1_DataMining | 14 | python | def fit_predict(self, X, y, X_test, **kwargs):
'重写继承即可\n :return: clf, score, test_preds\n '
clf = LGBMClassifier()
clf.fit(X, y)
score = roc_auc_score(y, clf.predict_proba(X)[(:, 1)])
test_preds = clf.predict_proba(X_test)
return (clf, score, test_preds) | def fit_predict(self, X, y, X_test, **kwargs):
'重写继承即可\n :return: clf, score, test_preds\n '
clf = LGBMClassifier()
clf.fit(X, y)
score = roc_auc_score(y, clf.predict_proba(X)[(:, 1)])
test_preds = clf.predict_proba(X_test)
return (clf, score, test_preds)<|docstring|>重写继承即可
:return... |
01af9b8b3a15865a79d46bb03d36785b081fa789840f85446b9c7e091cc16a20 | def _create_cmd(self):
'Return full command to install AFNI.'
comment = '#--------------------\n# Install AFNI {}\n#--------------------'.format(self.version)
if self.use_binaries:
chunks = [comment, self.install_binaries()]
else:
raise ValueError('`use_binaries=True` is the only availab... | Return full command to install AFNI. | neurodocker/interfaces/afni.py | _create_cmd | giovtorres/neurodocker | 1 | python | def _create_cmd(self):
comment = '#--------------------\n# Install AFNI {}\n#--------------------'.format(self.version)
if self.use_binaries:
chunks = [comment, self.install_binaries()]
else:
raise ValueError('`use_binaries=True` is the only available option at this time.')
return '... | def _create_cmd(self):
comment = '#--------------------\n# Install AFNI {}\n#--------------------'.format(self.version)
if self.use_binaries:
chunks = [comment, self.install_binaries()]
else:
raise ValueError('`use_binaries=True` is the only available option at this time.')
return '... |
d1d6286aaa5b5ad42850203801dcc33abe1ab766a8b10cae8706cf4ed09a0d87 | def install_binaries(self):
'Return Dockerfile instructions to download and install AFNI\n binaries.\n '
url = self._get_binaries_urls(self.version)
if self.check_urls:
check_url(url)
pkgs = self._get_binaries_dependencies()
cmd = '{install}\n&& libs_path=/usr/lib/x86_64-linux-... | Return Dockerfile instructions to download and install AFNI
binaries. | neurodocker/interfaces/afni.py | install_binaries | giovtorres/neurodocker | 1 | python | def install_binaries(self):
'Return Dockerfile instructions to download and install AFNI\n binaries.\n '
url = self._get_binaries_urls(self.version)
if self.check_urls:
check_url(url)
pkgs = self._get_binaries_dependencies()
cmd = '{install}\n&& libs_path=/usr/lib/x86_64-linux-... | def install_binaries(self):
'Return Dockerfile instructions to download and install AFNI\n binaries.\n '
url = self._get_binaries_urls(self.version)
if self.check_urls:
check_url(url)
pkgs = self._get_binaries_dependencies()
cmd = '{install}\n&& libs_path=/usr/lib/x86_64-linux-... |
acfe4e65faa300c2061082144d516c6011ef50676888e2f3d9179037d619e6f1 | def flatten(list_of_lists):
'[[a, b], [c, d]] -> [a, b, c, d]'
for lst in list_of_lists:
for elem in lst:
(yield elem) | [[a, b], [c, d]] -> [a, b, c, d] | src/mesher/voxel.py | flatten | fhennecker/semiteleporter | 0 | python | def flatten(list_of_lists):
for lst in list_of_lists:
for elem in lst:
(yield elem) | def flatten(list_of_lists):
for lst in list_of_lists:
for elem in lst:
(yield elem)<|docstring|>[[a, b], [c, d]] -> [a, b, c, d]<|endoftext|> |
5838709307436e1d1f52fd833138adfcf5f27c6d44ac225cdcd0c5035e3b8671 | def combine(Xrange, Yrange, Zrange):
'\n\tGenerate all possible combinations of x,y,z\n\t'
for x in Xrange:
for y in Yrange:
for z in Zrange:
(yield (x, y, z)) | Generate all possible combinations of x,y,z | src/mesher/voxel.py | combine | fhennecker/semiteleporter | 0 | python | def combine(Xrange, Yrange, Zrange):
'\n\t\n\t'
for x in Xrange:
for y in Yrange:
for z in Zrange:
(yield (x, y, z)) | def combine(Xrange, Yrange, Zrange):
'\n\t\n\t'
for x in Xrange:
for y in Yrange:
for z in Zrange:
(yield (x, y, z))<|docstring|>Generate all possible combinations of x,y,z<|endoftext|> |
d146b3daa552ced32ff1d4229afd5e07bf8891432b790f2dea2369650b2e6e97 | def voxelIndexForPoint(self, point):
' Returns the index of the voxel the point x, y, z belongs to '
fl = (lambda x: int(floor(x)))
xVoxel = fl((point.x / self.voxelSize))
yVoxel = fl((point.y / self.voxelSize))
zVoxel = fl((point.z / self.voxelSize))
return (xVoxel, yVoxel, zVoxel) | Returns the index of the voxel the point x, y, z belongs to | src/mesher/voxel.py | voxelIndexForPoint | fhennecker/semiteleporter | 0 | python | def voxelIndexForPoint(self, point):
' '
fl = (lambda x: int(floor(x)))
xVoxel = fl((point.x / self.voxelSize))
yVoxel = fl((point.y / self.voxelSize))
zVoxel = fl((point.z / self.voxelSize))
return (xVoxel, yVoxel, zVoxel) | def voxelIndexForPoint(self, point):
' '
fl = (lambda x: int(floor(x)))
xVoxel = fl((point.x / self.voxelSize))
yVoxel = fl((point.y / self.voxelSize))
zVoxel = fl((point.z / self.voxelSize))
return (xVoxel, yVoxel, zVoxel)<|docstring|>Returns the index of the voxel the point x, y, z belongs to... |
515dd1e16f3995dd7c5f5884f41524330dcb66fddd26c397200d38c86705a26f | def addPoints(self, pointsList):
' Adds a list of points in this format (lists can be changed to tuples):\n\t\t\t[[x1, y1, z1], [x2, y2, z2], ...] '
for point in pointsList:
self.addPoint(point) | Adds a list of points in this format (lists can be changed to tuples):
[[x1, y1, z1], [x2, y2, z2], ...] | src/mesher/voxel.py | addPoints | fhennecker/semiteleporter | 0 | python | def addPoints(self, pointsList):
' Adds a list of points in this format (lists can be changed to tuples):\n\t\t\t[[x1, y1, z1], [x2, y2, z2], ...] '
for point in pointsList:
self.addPoint(point) | def addPoints(self, pointsList):
' Adds a list of points in this format (lists can be changed to tuples):\n\t\t\t[[x1, y1, z1], [x2, y2, z2], ...] '
for point in pointsList:
self.addPoint(point)<|docstring|>Adds a list of points in this format (lists can be changed to tuples):
[[x1, y1, z1], [x2, y2, z2... |
2d0899acfea42d8d73600ab176318491d1843eff4595ee4793c941e2baf7870b | def allPoints(self):
' Returns a list of all points contained in the VoxelSpace '
res = []
for voxel in self.voxels:
res += self.voxels[voxel]
return res | Returns a list of all points contained in the VoxelSpace | src/mesher/voxel.py | allPoints | fhennecker/semiteleporter | 0 | python | def allPoints(self):
' '
res = []
for voxel in self.voxels:
res += self.voxels[voxel]
return res | def allPoints(self):
' '
res = []
for voxel in self.voxels:
res += self.voxels[voxel]
return res<|docstring|>Returns a list of all points contained in the VoxelSpace<|endoftext|> |
5f32ee13027e0612f5c99d5a8d6bb525db44ad79bf956c705d0709a84ee7ac78 | def pointsInCube(self, vx, vy, vz, neighbours=0):
'\n\t\tReturns a list of all points within a cube centered on vx,vy,vz\n\t\textended to neighbours\n\t\t'
return self.pointsInVoxels(self.voxelsInLayer(vx, vy, vz, 0, neighbours)) | Returns a list of all points within a cube centered on vx,vy,vz
extended to neighbours | src/mesher/voxel.py | pointsInCube | fhennecker/semiteleporter | 0 | python | def pointsInCube(self, vx, vy, vz, neighbours=0):
'\n\t\tReturns a list of all points within a cube centered on vx,vy,vz\n\t\textended to neighbours\n\t\t'
return self.pointsInVoxels(self.voxelsInLayer(vx, vy, vz, 0, neighbours)) | def pointsInCube(self, vx, vy, vz, neighbours=0):
'\n\t\tReturns a list of all points within a cube centered on vx,vy,vz\n\t\textended to neighbours\n\t\t'
return self.pointsInVoxels(self.voxelsInLayer(vx, vy, vz, 0, neighbours))<|docstring|>Returns a list of all points within a cube centered on vx,vy,vz
extend... |
8e2f6b38ccf4b0a881d4a5399c7be29cbc7deb0eed07448d92dec394e0dfb19e | def voxelsInLayer(self, vx, vy, vz, inner=1, outer=2):
'\n\t\tReturns a list of all voxels containing points within a hollow voxel cube.\n\t\t'
(xmin, xmax, ymin, ymax) = (((vx - outer) + 1), (vx + outer), ((vy - outer) + 1), (vy + outer))
voxels = list(self.range3D(xmin, xmax, ymin, ymax, ((vz - outer) + 1... | Returns a list of all voxels containing points within a hollow voxel cube. | src/mesher/voxel.py | voxelsInLayer | fhennecker/semiteleporter | 0 | python | def voxelsInLayer(self, vx, vy, vz, inner=1, outer=2):
'\n\t\t\n\t\t'
(xmin, xmax, ymin, ymax) = (((vx - outer) + 1), (vx + outer), ((vy - outer) + 1), (vy + outer))
voxels = list(self.range3D(xmin, xmax, ymin, ymax, ((vz - outer) + 1), ((vz - inner) + 1)))
voxels += list(self.range3D(xmin, xmax, ymin, ... | def voxelsInLayer(self, vx, vy, vz, inner=1, outer=2):
'\n\t\t\n\t\t'
(xmin, xmax, ymin, ymax) = (((vx - outer) + 1), (vx + outer), ((vy - outer) + 1), (vy + outer))
voxels = list(self.range3D(xmin, xmax, ymin, ymax, ((vz - outer) + 1), ((vz - inner) + 1)))
voxels += list(self.range3D(xmin, xmax, ymin, ... |
c6f0809e47fd3a1e3bea06257753c6664ff5533dbe887338d47127587e9ae19f | def voxelsInRegion(self, cornerA, cornerB):
' Returns all voxels within the parallelepipedic \n\t\t\tregion defined by the two corners in argument '
def rangeBuilder(a, b):
if (a < b):
return (a, (b + 1))
else:
return (b, (a + 1))
args = ((rangeBuilder(cornerA[0], co... | Returns all voxels within the parallelepipedic
region defined by the two corners in argument | src/mesher/voxel.py | voxelsInRegion | fhennecker/semiteleporter | 0 | python | def voxelsInRegion(self, cornerA, cornerB):
' Returns all voxels within the parallelepipedic \n\t\t\tregion defined by the two corners in argument '
def rangeBuilder(a, b):
if (a < b):
return (a, (b + 1))
else:
return (b, (a + 1))
args = ((rangeBuilder(cornerA[0], co... | def voxelsInRegion(self, cornerA, cornerB):
' Returns all voxels within the parallelepipedic \n\t\t\tregion defined by the two corners in argument '
def rangeBuilder(a, b):
if (a < b):
return (a, (b + 1))
else:
return (b, (a + 1))
args = ((rangeBuilder(cornerA[0], co... |
5fa08b324344375341fd69b30b6a03024ca69486bb0baeae18ae4426ec94bfc6 | def closestPointsToEdge(self, a, b, distanceLimit):
' Finds the k closest points to edge a, b, with a voxel distance limit '
aVoxel = self.voxelIndexForPoint(a)
bVoxel = self.voxelIndexForPoint(b)
distance = (lambda p: (norm3D((a - p)) + norm3D((b - p))))
eligible = (lambda p: (p not in (a, b)))
... | Finds the k closest points to edge a, b, with a voxel distance limit | src/mesher/voxel.py | closestPointsToEdge | fhennecker/semiteleporter | 0 | python | def closestPointsToEdge(self, a, b, distanceLimit):
' '
aVoxel = self.voxelIndexForPoint(a)
bVoxel = self.voxelIndexForPoint(b)
distance = (lambda p: (norm3D((a - p)) + norm3D((b - p))))
eligible = (lambda p: (p not in (a, b)))
points = self.pointsInVoxels(self.voxelsInRegion(aVoxel, bVoxel))
... | def closestPointsToEdge(self, a, b, distanceLimit):
' '
aVoxel = self.voxelIndexForPoint(a)
bVoxel = self.voxelIndexForPoint(b)
distance = (lambda p: (norm3D((a - p)) + norm3D((b - p))))
eligible = (lambda p: (p not in (a, b)))
points = self.pointsInVoxels(self.voxelsInRegion(aVoxel, bVoxel))
... |
50e2a1d026cd946db398d073301bf7fe1e77e37694bc2d29d2c2514f57005630 | def closestPointTo(self, point, distanceLimit=10, requiresDifferent=False):
" Finds and returns the closest point to (x, y z) \n\t\t\twe'll only look in voxels within distanceLimit (distance in voxels)"
(cx, cy, cz) = self.voxelIndexForPoint(point)
for i in xrange(distanceLimit):
points = self.point... | Finds and returns the closest point to (x, y z)
we'll only look in voxels within distanceLimit (distance in voxels) | src/mesher/voxel.py | closestPointTo | fhennecker/semiteleporter | 0 | python | def closestPointTo(self, point, distanceLimit=10, requiresDifferent=False):
" Finds and returns the closest point to (x, y z) \n\t\t\twe'll only look in voxels within distanceLimit (distance in voxels)"
(cx, cy, cz) = self.voxelIndexForPoint(point)
for i in xrange(distanceLimit):
points = self.point... | def closestPointTo(self, point, distanceLimit=10, requiresDifferent=False):
" Finds and returns the closest point to (x, y z) \n\t\t\twe'll only look in voxels within distanceLimit (distance in voxels)"
(cx, cy, cz) = self.voxelIndexForPoint(point)
for i in xrange(distanceLimit):
points = self.point... |
5b6d80eba48a6b9289c56418f2f0af704d5e92d6b045926600e94272efc4b12f | def _resource_from_cache_prefix(resource, cache):
'\n Combine the resource name with the cache prefix (if any)\n '
if getattr(cache, 'key_prefix', None):
name = '{} {}'.format(resource, cache.key_prefix)
else:
name = resource
return name.lower() | Combine the resource name with the cache prefix (if any) | ddtrace/contrib/flask_cache/utils.py | _resource_from_cache_prefix | mastizada/dd-trace-py | 308 | python | def _resource_from_cache_prefix(resource, cache):
'\n \n '
if getattr(cache, 'key_prefix', None):
name = '{} {}'.format(resource, cache.key_prefix)
else:
name = resource
return name.lower() | def _resource_from_cache_prefix(resource, cache):
'\n \n '
if getattr(cache, 'key_prefix', None):
name = '{} {}'.format(resource, cache.key_prefix)
else:
name = resource
return name.lower()<|docstring|>Combine the resource name with the cache prefix (if any)<|endoftext|> |
20af02246489561131c946fa6ce8f8544326e52773fb3b59bf6a64124649501a | def _extract_client(cache, write=False):
'\n Get the client from the cache instance according to the current operation\n '
client = getattr(cache, '_client', None)
if (client is None):
client = getattr(cache, ('_write_client' if write else '_read_clients'), None)
return client | Get the client from the cache instance according to the current operation | ddtrace/contrib/flask_cache/utils.py | _extract_client | mastizada/dd-trace-py | 308 | python | def _extract_client(cache, write=False):
'\n \n '
client = getattr(cache, '_client', None)
if (client is None):
client = getattr(cache, ('_write_client' if write else '_read_clients'), None)
return client | def _extract_client(cache, write=False):
'\n \n '
client = getattr(cache, '_client', None)
if (client is None):
client = getattr(cache, ('_write_client' if write else '_read_clients'), None)
return client<|docstring|>Get the client from the cache instance according to the current operation... |
6ebc36610aa38347ec60c6067185153a14f0e0d84d2c313afbe8aee9e8c37fd5 | def _extract_conn_tags(client):
'\n For the given client extracts connection tags\n '
tags = {}
if hasattr(client, 'servers'):
if (isinstance(client.servers, list) and (len(client.servers) > 0)):
contact_point = client.servers[0].address
tags[net.TARGET_HOST] = contact_... | For the given client extracts connection tags | ddtrace/contrib/flask_cache/utils.py | _extract_conn_tags | mastizada/dd-trace-py | 308 | python | def _extract_conn_tags(client):
'\n \n '
tags = {}
if hasattr(client, 'servers'):
if (isinstance(client.servers, list) and (len(client.servers) > 0)):
contact_point = client.servers[0].address
tags[net.TARGET_HOST] = contact_point[0]
tags[net.TARGET_PORT] = ... | def _extract_conn_tags(client):
'\n \n '
tags = {}
if hasattr(client, 'servers'):
if (isinstance(client.servers, list) and (len(client.servers) > 0)):
contact_point = client.servers[0].address
tags[net.TARGET_HOST] = contact_point[0]
tags[net.TARGET_PORT] = ... |
1dcd48a5441e5202d60b7a866ca703fef1b4e9bc610d3cc8418a62c2a6b0f594 | def __init__(self, memory_size, alpha):
' Prioritized experience replay buffer initialization.\n\n Parameters\n ----------\n memory_size : int\n sample size to be stored\n batch_size : int\n batch size to be selected by `select` method\n alpha: float\n ... | Prioritized experience replay buffer initialization.
Parameters
----------
memory_size : int
sample size to be stored
batch_size : int
batch size to be selected by `select` method
alpha: float
exponent determine how much prioritization.
Prob_i \sim priority_i**alpha/sum(priority**alpha) | teachDRL/teachers/algos/LPReplayBuffer.py | __init__ | flowersteam/meta-acl | 2 | python | def __init__(self, memory_size, alpha):
' Prioritized experience replay buffer initialization.\n\n Parameters\n ----------\n memory_size : int\n sample size to be stored\n batch_size : int\n batch size to be selected by `select` method\n alpha: float\n ... | def __init__(self, memory_size, alpha):
' Prioritized experience replay buffer initialization.\n\n Parameters\n ----------\n memory_size : int\n sample size to be stored\n batch_size : int\n batch size to be selected by `select` method\n alpha: float\n ... |
03fd6d610faf66df4d95cef9552ea1edbd5de58b3046018f66e030839d036b87 | def add(self, data, priority):
" Add new sample.\n\n Parameters\n ----------\n data : object\n new sample\n priority : float\n sample's priority\n "
if (((priority / 100) >= self.bonus_priority) and (self.alpha != 0.0)):
print('WARNING, YOUR BONUS... | Add new sample.
Parameters
----------
data : object
new sample
priority : float
sample's priority | teachDRL/teachers/algos/LPReplayBuffer.py | add | flowersteam/meta-acl | 2 | python | def add(self, data, priority):
" Add new sample.\n\n Parameters\n ----------\n data : object\n new sample\n priority : float\n sample's priority\n "
if (((priority / 100) >= self.bonus_priority) and (self.alpha != 0.0)):
print('WARNING, YOUR BONUS... | def add(self, data, priority):
" Add new sample.\n\n Parameters\n ----------\n data : object\n new sample\n priority : float\n sample's priority\n "
if (((priority / 100) >= self.bonus_priority) and (self.alpha != 0.0)):
print('WARNING, YOUR BONUS... |
d06178b5dacf142e0d69e0ae82a45c1210c6a9d26bd90ec39b533bd67ddeec49 | def select(self, batch_size):
' The method return samples randomly.\n\n Parameters\n ----------\n beta : float\n\n Returns\n -------\n out :\n list of samples\n weights:\n list of weight\n indices:\n list of sample indices\n ... | The method return samples randomly.
Parameters
----------
beta : float
Returns
-------
out :
list of samples
weights:
list of weight
indices:
list of sample indices
The indices indicate sample positions in a sum tree. | teachDRL/teachers/algos/LPReplayBuffer.py | select | flowersteam/meta-acl | 2 | python | def select(self, batch_size):
' The method return samples randomly.\n\n Parameters\n ----------\n beta : float\n\n Returns\n -------\n out :\n list of samples\n weights:\n list of weight\n indices:\n list of sample indices\n ... | def select(self, batch_size):
' The method return samples randomly.\n\n Parameters\n ----------\n beta : float\n\n Returns\n -------\n out :\n list of samples\n weights:\n list of weight\n indices:\n list of sample indices\n ... |
5160890ef1ef07a8a88f1551ea3540bfd943accd26d29b56faace5f24aacc022 | def priority_update(self, indices, priorities):
" The methods update samples's priority.\n\n Parameters\n ----------\n indices :\n list of sample indices\n "
for (i, p) in zip(indices, priorities):
self.tree.val_update(i, (p ** self.alpha)) | The methods update samples's priority.
Parameters
----------
indices :
list of sample indices | teachDRL/teachers/algos/LPReplayBuffer.py | priority_update | flowersteam/meta-acl | 2 | python | def priority_update(self, indices, priorities):
" The methods update samples's priority.\n\n Parameters\n ----------\n indices :\n list of sample indices\n "
for (i, p) in zip(indices, priorities):
self.tree.val_update(i, (p ** self.alpha)) | def priority_update(self, indices, priorities):
" The methods update samples's priority.\n\n Parameters\n ----------\n indices :\n list of sample indices\n "
for (i, p) in zip(indices, priorities):
self.tree.val_update(i, (p ** self.alpha))<|docstring|>The methods ... |
07d7fd20eedc087c8e48a85d4b9cbf32b18b781677cc71547c2637634e6f3c01 | def reset_alpha(self, alpha):
' Reset a exponent alpha.\n Parameters\n ----------\n alpha : float\n '
(self.alpha, old_alpha) = (alpha, self.alpha)
priorities = [(self.tree.get_val(i) ** (- old_alpha)) for i in range(self.tree.filled_size())]
self.priority_update(range(self.t... | Reset a exponent alpha.
Parameters
----------
alpha : float | teachDRL/teachers/algos/LPReplayBuffer.py | reset_alpha | flowersteam/meta-acl | 2 | python | def reset_alpha(self, alpha):
' Reset a exponent alpha.\n Parameters\n ----------\n alpha : float\n '
(self.alpha, old_alpha) = (alpha, self.alpha)
priorities = [(self.tree.get_val(i) ** (- old_alpha)) for i in range(self.tree.filled_size())]
self.priority_update(range(self.t... | def reset_alpha(self, alpha):
' Reset a exponent alpha.\n Parameters\n ----------\n alpha : float\n '
(self.alpha, old_alpha) = (alpha, self.alpha)
priorities = [(self.tree.get_val(i) ** (- old_alpha)) for i in range(self.tree.filled_size())]
self.priority_update(range(self.t... |
da9fcb3b0c8030780ba01b8d7b7ca5e3dba2930f51c6171fc291d646ac5e3332 | def create_model(name: str, version: Optional[int]=None, metrics: Optional[dict]=None, description: Optional[str]=None, input_example: Optional[Union[(pandas.DataFrame, pandas.Series, numpy.ndarray, list)]]=None, model_schema: Optional[ModelSchema]=None):
'Create an SkLearn model metadata object.\n\n !!! note "L... | Create an SkLearn model metadata object.
!!! note "Lazy"
This method is lazy and does not persist any metadata or uploads model artifacts in the
model registry on its own. To save the model object and the model artifacts, call the `save()` method with a
local file path to the directory containing the model... | python/hsml/sklearn/signature.py | create_model | javierdlrm/machine-learning-api | 8 | python | def create_model(name: str, version: Optional[int]=None, metrics: Optional[dict]=None, description: Optional[str]=None, input_example: Optional[Union[(pandas.DataFrame, pandas.Series, numpy.ndarray, list)]]=None, model_schema: Optional[ModelSchema]=None):
'Create an SkLearn model metadata object.\n\n !!! note "L... | def create_model(name: str, version: Optional[int]=None, metrics: Optional[dict]=None, description: Optional[str]=None, input_example: Optional[Union[(pandas.DataFrame, pandas.Series, numpy.ndarray, list)]]=None, model_schema: Optional[ModelSchema]=None):
'Create an SkLearn model metadata object.\n\n !!! note "L... |
2811c5c87d3f5c36782f1ffb572b8821ac9f4a5b0769c8540fca8bab4e02e826 | def data_labels(data_path, label):
'\n Filters files with the appropriate label from the data csv file\n :param data_path:\n :param label: data label default values is gender: possible values includes [gender, age, country]\n :return:\n '
label_data = pd.read_csv(os.path.join(data_path, 'data.csv... | Filters files with the appropriate label from the data csv file
:param data_path:
:param label: data label default values is gender: possible values includes [gender, age, country]
:return: | audio_model/preprocessing/mp3_parser.py | data_labels | dachosen1/Common-Voice | 11 | python | def data_labels(data_path, label):
'\n Filters files with the appropriate label from the data csv file\n :param data_path:\n :param label: data label default values is gender: possible values includes [gender, age, country]\n :return:\n '
label_data = pd.read_csv(os.path.join(data_path, 'data.csv... | def data_labels(data_path, label):
'\n Filters files with the appropriate label from the data csv file\n :param data_path:\n :param label: data label default values is gender: possible values includes [gender, age, country]\n :return:\n '
label_data = pd.read_csv(os.path.join(data_path, 'data.csv... |
1281fd6756e9e42d275e0533104e2212539653cd28ab53414ac0b563fd4114fa | @command_component(environment='../conda.yaml')
def basic_module(port1: str, param1: int):
' module run logic goes here '
return port1 | module run logic goes here | sdk/ml/azure-ai-ml/tests/test_configs/dsl_component/dsl_component_with_env/inner_folder/basic_component.py | basic_module | jalauzon-msft/azure-sdk-for-python | 1 | python | @command_component(environment='../conda.yaml')
def basic_module(port1: str, param1: int):
' '
return port1 | @command_component(environment='../conda.yaml')
def basic_module(port1: str, param1: int):
' '
return port1<|docstring|>module run logic goes here<|endoftext|> |
8002010d963d7b9fb7539777c5c80baaaec7d2e24e51ac812af37be62a5d3709 | def test_longArrays():
'\n Test config saving and loading of long arrays.\n '
tmp = tempfile.mktemp('.cfg')
arr = np.arange(20)
configfile.writeConfigFile({'arr': arr}, tmp)
config = configfile.readConfigFile(tmp)
assert all((config['arr'] == arr))
os.remove(tmp) | Test config saving and loading of long arrays. | pyqtgraph/tests/test_configparser.py | test_longArrays | 3mrrrx/slim2voice | 150 | python | def test_longArrays():
'\n \n '
tmp = tempfile.mktemp('.cfg')
arr = np.arange(20)
configfile.writeConfigFile({'arr': arr}, tmp)
config = configfile.readConfigFile(tmp)
assert all((config['arr'] == arr))
os.remove(tmp) | def test_longArrays():
'\n \n '
tmp = tempfile.mktemp('.cfg')
arr = np.arange(20)
configfile.writeConfigFile({'arr': arr}, tmp)
config = configfile.readConfigFile(tmp)
assert all((config['arr'] == arr))
os.remove(tmp)<|docstring|>Test config saving and loading of long arrays.<|endoftex... |
23a2886326c86750efd2cf0cb45e9ed5ec4ff978f537f3c41be4a8845d24825f | def test_multipleParameters():
'\n Test config saving and loading of multiple parameters.\n '
tmp = tempfile.mktemp('.cfg')
par1 = [1, 2, 3]
par2 = 'Test'
par3 = {'a': 3, 'b': 'c'}
configfile.writeConfigFile({'par1': par1, 'par2': par2, 'par3': par3}, tmp)
config = configfile.readConfi... | Test config saving and loading of multiple parameters. | pyqtgraph/tests/test_configparser.py | test_multipleParameters | 3mrrrx/slim2voice | 150 | python | def test_multipleParameters():
'\n \n '
tmp = tempfile.mktemp('.cfg')
par1 = [1, 2, 3]
par2 = 'Test'
par3 = {'a': 3, 'b': 'c'}
configfile.writeConfigFile({'par1': par1, 'par2': par2, 'par3': par3}, tmp)
config = configfile.readConfigFile(tmp)
assert (config['par1'] == par1)
ass... | def test_multipleParameters():
'\n \n '
tmp = tempfile.mktemp('.cfg')
par1 = [1, 2, 3]
par2 = 'Test'
par3 = {'a': 3, 'b': 'c'}
configfile.writeConfigFile({'par1': par1, 'par2': par2, 'par3': par3}, tmp)
config = configfile.readConfigFile(tmp)
assert (config['par1'] == par1)
ass... |
bbe7adf5acbf5b8af5048a035c4b155074392d9a57f290e22501cf2cf436fa26 | @classmethod
def get_elements(cls):
'\n Store singleton instance on IO to speed up retrieval after first call.\n '
if (not hasattr(cls, '_cache')):
cls._cache = cls()
return cls._cache | Store singleton instance on IO to speed up retrieval after first call. | climata/snotel/__init__.py | get_elements | gauchm/climata | 67 | python | @classmethod
def get_elements(cls):
'\n \n '
if (not hasattr(cls, '_cache')):
cls._cache = cls()
return cls._cache | @classmethod
def get_elements(cls):
'\n \n '
if (not hasattr(cls, '_cache')):
cls._cache = cls()
return cls._cache<|docstring|>Store singleton instance on IO to speed up retrieval after first call.<|endoftext|> |
487209f3d9fe5affdad487629ae4244e4915d972ddd0bd9d451f4b044c904b8f | @staticmethod
def inject_into(target_object: Any, target_function_name: str) -> Callable:
'inject_into(target_object, target_function_name)\n\n .. warning:: This function is DEPRECATED. Use :func:`~inject_safely_into` instead.\n\n '
return CommonInjectionUtils.inject_safely_into(None, t... | inject_into(target_object, target_function_name)
.. warning:: This function is DEPRECATED. Use :func:`~inject_safely_into` instead. | src/sims4communitylib/utils/common_injection_utils.py | inject_into | velocist/TS4CheatsInfo | 0 | python | @staticmethod
def inject_into(target_object: Any, target_function_name: str) -> Callable:
'inject_into(target_object, target_function_name)\n\n .. warning:: This function is DEPRECATED. Use :func:`~inject_safely_into` instead.\n\n '
return CommonInjectionUtils.inject_safely_into(None, t... | @staticmethod
def inject_into(target_object: Any, target_function_name: str) -> Callable:
'inject_into(target_object, target_function_name)\n\n .. warning:: This function is DEPRECATED. Use :func:`~inject_safely_into` instead.\n\n '
return CommonInjectionUtils.inject_safely_into(None, t... |
3c580eeca31f5b5de7987c751b43fffa1fc8c3d208727ed20c6e718fcf690cb3 | @staticmethod
def inject_safely_into(mod_identity: CommonModIdentity, target_object: Any, target_function_name: str, handle_exceptions: bool=True) -> Callable:
"inject_safely_into(mod_identity, target_object, target_function_name, handle_exceptions=True)\n\n A decorator used to inject code into a function.\n... | inject_safely_into(mod_identity, target_object, target_function_name, handle_exceptions=True)
A decorator used to inject code into a function.
It will run the original function should any problems occur.
If handle_exceptions is True, it will catch and log exceptions.
:Example of cls usage:
.. highlight:: python
.. c... | src/sims4communitylib/utils/common_injection_utils.py | inject_safely_into | velocist/TS4CheatsInfo | 0 | python | @staticmethod
def inject_safely_into(mod_identity: CommonModIdentity, target_object: Any, target_function_name: str, handle_exceptions: bool=True) -> Callable:
"inject_safely_into(mod_identity, target_object, target_function_name, handle_exceptions=True)\n\n A decorator used to inject code into a function.\n... | @staticmethod
def inject_safely_into(mod_identity: CommonModIdentity, target_object: Any, target_function_name: str, handle_exceptions: bool=True) -> Callable:
"inject_safely_into(mod_identity, target_object, target_function_name, handle_exceptions=True)\n\n A decorator used to inject code into a function.\n... |
4cb499aeeafcfcbd3fa20dab9ccf21d47351a687eefdbe068782d4efbb0309bc | def get_modified_date(parsed, raw):
'Return best possible guess to post modification timestamp.'
if parsed:
return feedparser_ts(parsed)
if (not raw):
return None
(ts, val) = (None, raw.replace('_', ' '))
if (not ts):
from subprocess import Popen, PIPE
with open(os.de... | Return best possible guess to post modification timestamp. | feedjack/fjupdate.py | get_modified_date | allo-/feedjack | 2 | python | def get_modified_date(parsed, raw):
if parsed:
return feedparser_ts(parsed)
if (not raw):
return None
(ts, val) = (None, raw.replace('_', ' '))
if (not ts):
from subprocess import Popen, PIPE
with open(os.devnull, 'w') as devnull:
proc = Popen(['date', '+... | def get_modified_date(parsed, raw):
if parsed:
return feedparser_ts(parsed)
if (not raw):
return None
(ts, val) = (None, raw.replace('_', ' '))
if (not ts):
from subprocess import Popen, PIPE
with open(os.devnull, 'w') as devnull:
proc = Popen(['date', '+... |
df94e7b574c7fc35fde9e99af4b24ec6ba276339d85b2624827a4da34bb81485 | def process_entry(self, entry):
'Construct a Post from a feedparser entry and save/update it in db'
from feedjack.models import Post, Tag
post = Post(feed=self.feed)
post.link = entry.get('link', self.feed.link)
post.title = entry.get('title', post.link)
post.guid = self._get_guid(entry)
if ... | Construct a Post from a feedparser entry and save/update it in db | feedjack/fjupdate.py | process_entry | allo-/feedjack | 2 | python | def process_entry(self, entry):
from feedjack.models import Post, Tag
post = Post(feed=self.feed)
post.link = entry.get('link', self.feed.link)
post.title = entry.get('title', post.link)
post.guid = self._get_guid(entry)
if ('author_detail' in entry):
post.author = entry.author_deta... | def process_entry(self, entry):
from feedjack.models import Post, Tag
post = Post(feed=self.feed)
post.link = entry.get('link', self.feed.link)
post.title = entry.get('title', post.link)
post.guid = self._get_guid(entry)
if ('author_detail' in entry):
post.author = entry.author_deta... |
460ee6eef6393ed6cce787943889149ae0e7e1909f52871592e2713afb89a132 | def _process(self):
'Downloads and parses a feed.'
ret_values = {ENTRY_NEW: 0, ENTRY_UPDATED: 0, ENTRY_SAME: 0, ENTRY_ERR: 0}
report_errors = ((not self.options.report_after) or (not self.feed.last_checked) or ((self.feed.last_checked + self.options.report_after) < timezone.now()))
feedparser_kws = dict... | Downloads and parses a feed. | feedjack/fjupdate.py | _process | allo-/feedjack | 2 | python | def _process(self):
ret_values = {ENTRY_NEW: 0, ENTRY_UPDATED: 0, ENTRY_SAME: 0, ENTRY_ERR: 0}
report_errors = ((not self.options.report_after) or (not self.feed.last_checked) or ((self.feed.last_checked + self.options.report_after) < timezone.now()))
feedparser_kws = dict()
if ((sys.hexversion >= ... | def _process(self):
ret_values = {ENTRY_NEW: 0, ENTRY_UPDATED: 0, ENTRY_SAME: 0, ENTRY_ERR: 0}
report_errors = ((not self.options.report_after) or (not self.feed.last_checked) or ((self.feed.last_checked + self.options.report_after) < timezone.now()))
feedparser_kws = dict()
if ((sys.hexversion >= ... |
e1c16077645decc8cb1c4fc4be1287799d54ad0e7dd679a9df588710bb4c8dfe | def compute_last_header(prev_header, hashes):
'Compute the last filter header from a starting header and a sequence of filter hashes.'
header = ser_uint256(prev_header)
for filter_hash in hashes:
header = hash256((ser_uint256(filter_hash) + header))
return uint256_from_str(header) | Compute the last filter header from a starting header and a sequence of filter hashes. | test/functional/p2p_blockfilters.py | compute_last_header | daodaoshi/bitcoin-abc | 1,266 | python | def compute_last_header(prev_header, hashes):
header = ser_uint256(prev_header)
for filter_hash in hashes:
header = hash256((ser_uint256(filter_hash) + header))
return uint256_from_str(header) | def compute_last_header(prev_header, hashes):
header = ser_uint256(prev_header)
for filter_hash in hashes:
header = hash256((ser_uint256(filter_hash) + header))
return uint256_from_str(header)<|docstring|>Compute the last filter header from a starting header and a sequence of filter hashes.<|en... |
805153c5f7dd7fb8b78f7e505c67208315dfde881df3a9f87dadb1f393276208 | def on_cfilter(self, message):
'Store cfilters received in a list.'
self.cfilters.append(message) | Store cfilters received in a list. | test/functional/p2p_blockfilters.py | on_cfilter | daodaoshi/bitcoin-abc | 1,266 | python | def on_cfilter(self, message):
self.cfilters.append(message) | def on_cfilter(self, message):
self.cfilters.append(message)<|docstring|>Store cfilters received in a list.<|endoftext|> |
4cb599286d24bde0eff6571039c4447a60a85890120515d329ad7854c13c5332 | def lens(lists):
'Returns the sizes of lists in a list.'
return list(map(len, lists)) | Returns the sizes of lists in a list. | open_spiel/python/algorithms/double_oracle.py | lens | tvanekeris/open_spiel | 3,167 | python | def lens(lists):
return list(map(len, lists)) | def lens(lists):
return list(map(len, lists))<|docstring|>Returns the sizes of lists in a list.<|endoftext|> |
ee32531125761fa840d009d24d07d69e73f5dd7ebbc22965d2a8f62100f9846e | def solve_subgame(subgame_payoffs):
"Solves the subgame using OpenSpiel's LP solver."
(p0_sol, p1_sol, _, _) = lp_solver.solve_zero_sum_matrix_game(pyspiel.create_matrix_game(*subgame_payoffs))
(p0_sol, p1_sol) = (np.asarray(p0_sol), np.asarray(p1_sol))
return [(p0_sol / p0_sol.sum()), (p1_sol / p1_sol.... | Solves the subgame using OpenSpiel's LP solver. | open_spiel/python/algorithms/double_oracle.py | solve_subgame | tvanekeris/open_spiel | 3,167 | python | def solve_subgame(subgame_payoffs):
(p0_sol, p1_sol, _, _) = lp_solver.solve_zero_sum_matrix_game(pyspiel.create_matrix_game(*subgame_payoffs))
(p0_sol, p1_sol) = (np.asarray(p0_sol), np.asarray(p1_sol))
return [(p0_sol / p0_sol.sum()), (p1_sol / p1_sol.sum())] | def solve_subgame(subgame_payoffs):
(p0_sol, p1_sol, _, _) = lp_solver.solve_zero_sum_matrix_game(pyspiel.create_matrix_game(*subgame_payoffs))
(p0_sol, p1_sol) = (np.asarray(p0_sol), np.asarray(p1_sol))
return [(p0_sol / p0_sol.sum()), (p1_sol / p1_sol.sum())]<|docstring|>Solves the subgame using Open... |
6fe1ba739463ae9a38ea016e3db1ec52ec98dd97e09d0bdd1595a7a82185181f | def __init__(self, game, enforce_symmetry=False):
"Initializes the Double Oracle solver.\n\n Args:\n game: pyspiel.MatrixGame (zero-sum).\n enforce_symmetry: If True, enforces symmetry in the strategies appended by\n each player, by using the first player's best response for the second\n ... | Initializes the Double Oracle solver.
Args:
game: pyspiel.MatrixGame (zero-sum).
enforce_symmetry: If True, enforces symmetry in the strategies appended by
each player, by using the first player's best response for the second
player as well; also asserts the game is symmetric and that players are
seede... | open_spiel/python/algorithms/double_oracle.py | __init__ | tvanekeris/open_spiel | 3,167 | python | def __init__(self, game, enforce_symmetry=False):
"Initializes the Double Oracle solver.\n\n Args:\n game: pyspiel.MatrixGame (zero-sum).\n enforce_symmetry: If True, enforces symmetry in the strategies appended by\n each player, by using the first player's best response for the second\n ... | def __init__(self, game, enforce_symmetry=False):
"Initializes the Double Oracle solver.\n\n Args:\n game: pyspiel.MatrixGame (zero-sum).\n enforce_symmetry: If True, enforces symmetry in the strategies appended by\n each player, by using the first player's best response for the second\n ... |
bdd24b5329c9e6be03819d98026f6e660165c57802236b6ec6f249321add69e0 | def oracle(self, subgame_solution):
'Computes the best responses.\n\n Args:\n subgame_solution: List of subgame solution policies.\n\n Returns:\n best_response: For both players from the original set of pure strategies.\n best_response_utility: Corresponding utility for both players.\n '
... | Computes the best responses.
Args:
subgame_solution: List of subgame solution policies.
Returns:
best_response: For both players from the original set of pure strategies.
best_response_utility: Corresponding utility for both players. | open_spiel/python/algorithms/double_oracle.py | oracle | tvanekeris/open_spiel | 3,167 | python | def oracle(self, subgame_solution):
'Computes the best responses.\n\n Args:\n subgame_solution: List of subgame solution policies.\n\n Returns:\n best_response: For both players from the original set of pure strategies.\n best_response_utility: Corresponding utility for both players.\n '
... | def oracle(self, subgame_solution):
'Computes the best responses.\n\n Args:\n subgame_solution: List of subgame solution policies.\n\n Returns:\n best_response: For both players from the original set of pure strategies.\n best_response_utility: Corresponding utility for both players.\n '
... |
e8ca4f7b16f0126882ad39133c84b2b02c3df708ccfb9bc2d76d78304418cbde | def step(self):
'Performs one iteration.'
subgame_payoffs = self.subgame_payoffs()
subgame_solution = solve_subgame(subgame_payoffs)
(best_response, best_response_utility) = self.oracle(subgame_solution)
self.subgame_strategies = [sorted(set((strategies + [br]))) for (strategies, br) in zip(self.sub... | Performs one iteration. | open_spiel/python/algorithms/double_oracle.py | step | tvanekeris/open_spiel | 3,167 | python | def step(self):
subgame_payoffs = self.subgame_payoffs()
subgame_solution = solve_subgame(subgame_payoffs)
(best_response, best_response_utility) = self.oracle(subgame_solution)
self.subgame_strategies = [sorted(set((strategies + [br]))) for (strategies, br) in zip(self.subgame_strategies, best_res... | def step(self):
subgame_payoffs = self.subgame_payoffs()
subgame_solution = solve_subgame(subgame_payoffs)
(best_response, best_response_utility) = self.oracle(subgame_solution)
self.subgame_strategies = [sorted(set((strategies + [br]))) for (strategies, br) in zip(self.subgame_strategies, best_res... |
08f52bd9afd886e6b7ae2539a18a1d9ed34f5a48eafed4b5b686bbf71438419a | def solve_yield(self, initial_strategies, max_steps, tolerance, verbose, yield_subgame=False):
'Solves game using Double Oracle, yielding intermediate results.\n\n Args:\n initial_strategies: List of pure strategies for both players, optional.\n max_steps: Maximum number of iterations, default: 20.\n ... | Solves game using Double Oracle, yielding intermediate results.
Args:
initial_strategies: List of pure strategies for both players, optional.
max_steps: Maximum number of iterations, default: 20.
tolerance: Stop if the estimated value of the game is below the tolerance.
verbose: If False, no warning is shown, ... | open_spiel/python/algorithms/double_oracle.py | solve_yield | tvanekeris/open_spiel | 3,167 | python | def solve_yield(self, initial_strategies, max_steps, tolerance, verbose, yield_subgame=False):
'Solves game using Double Oracle, yielding intermediate results.\n\n Args:\n initial_strategies: List of pure strategies for both players, optional.\n max_steps: Maximum number of iterations, default: 20.\n ... | def solve_yield(self, initial_strategies, max_steps, tolerance, verbose, yield_subgame=False):
'Solves game using Double Oracle, yielding intermediate results.\n\n Args:\n initial_strategies: List of pure strategies for both players, optional.\n max_steps: Maximum number of iterations, default: 20.\n ... |
d078c2a44ff011a661425317bb9de9fbbaa5d8b205dc6e6af7fdf1cd6168ada7 | def solve(self, initial_strategies=None, max_steps=20, tolerance=5e-05, verbose=True):
'Solves the game using Double Oracle, returning the final solution.'
(solution, iteration, value) = (None, None, None)
generator = self.solve_yield(initial_strategies, max_steps, tolerance, verbose, yield_subgame=False)
... | Solves the game using Double Oracle, returning the final solution. | open_spiel/python/algorithms/double_oracle.py | solve | tvanekeris/open_spiel | 3,167 | python | def solve(self, initial_strategies=None, max_steps=20, tolerance=5e-05, verbose=True):
(solution, iteration, value) = (None, None, None)
generator = self.solve_yield(initial_strategies, max_steps, tolerance, verbose, yield_subgame=False)
for (solution, iteration, value, _) in generator:
pass
... | def solve(self, initial_strategies=None, max_steps=20, tolerance=5e-05, verbose=True):
(solution, iteration, value) = (None, None, None)
generator = self.solve_yield(initial_strategies, max_steps, tolerance, verbose, yield_subgame=False)
for (solution, iteration, value, _) in generator:
pass
... |
02863c6a29bc2ce03d843e39dfc95c7dd321fa8cd6c41b468dca5bb947ecaae6 | def _message_to_pb(message: Message):
'\n Turns the given message to a protocol buffer\n '
if message.is_normal_message:
return conversations_pb2.Message(message_id=message.id, author_user_id=message.author_id, time=Timestamp_from_datetime(message.time), text=conversations_pb2.MessageContentText(t... | Turns the given message to a protocol buffer | app/backend/src/couchers/servicers/conversations.py | _message_to_pb | dieterpankratz/couchers | 226 | python | def _message_to_pb(message: Message):
'\n \n '
if message.is_normal_message:
return conversations_pb2.Message(message_id=message.id, author_user_id=message.author_id, time=Timestamp_from_datetime(message.time), text=conversations_pb2.MessageContentText(text=message.text))
else:
return ... | def _message_to_pb(message: Message):
'\n \n '
if message.is_normal_message:
return conversations_pb2.Message(message_id=message.id, author_user_id=message.author_id, time=Timestamp_from_datetime(message.time), text=conversations_pb2.MessageContentText(text=message.text))
else:
return ... |
5d240f3a5e28c87fbd3a84c69a6cc6acdc307214e4d9d5c1984d62929f553dd0 | def _get_visible_members_for_subscription(subscription):
"\n If a user leaves a group chat, they shouldn't be able to see who's added\n after they left\n "
if (not subscription.left):
return [sub.user_id for sub in subscription.group_chat.subscriptions.where((GroupChatSubscription.left == None)... | If a user leaves a group chat, they shouldn't be able to see who's added
after they left | app/backend/src/couchers/servicers/conversations.py | _get_visible_members_for_subscription | dieterpankratz/couchers | 226 | python | def _get_visible_members_for_subscription(subscription):
"\n If a user leaves a group chat, they shouldn't be able to see who's added\n after they left\n "
if (not subscription.left):
return [sub.user_id for sub in subscription.group_chat.subscriptions.where((GroupChatSubscription.left == None)... | def _get_visible_members_for_subscription(subscription):
"\n If a user leaves a group chat, they shouldn't be able to see who's added\n after they left\n "
if (not subscription.left):
return [sub.user_id for sub in subscription.group_chat.subscriptions.where((GroupChatSubscription.left == None)... |
49ab5cec10d5af5f1268f32f86535b5eb7dec45afa37d91931872f0248c7ca0d | def _get_visible_admins_for_subscription(subscription):
"\n If a user leaves a group chat, they shouldn't be able to see who's added\n after they left\n "
if (not subscription.left):
return [sub.user_id for sub in subscription.group_chat.subscriptions.where((GroupChatSubscription.left == None))... | If a user leaves a group chat, they shouldn't be able to see who's added
after they left | app/backend/src/couchers/servicers/conversations.py | _get_visible_admins_for_subscription | dieterpankratz/couchers | 226 | python | def _get_visible_admins_for_subscription(subscription):
"\n If a user leaves a group chat, they shouldn't be able to see who's added\n after they left\n "
if (not subscription.left):
return [sub.user_id for sub in subscription.group_chat.subscriptions.where((GroupChatSubscription.left == None))... | def _get_visible_admins_for_subscription(subscription):
"\n If a user leaves a group chat, they shouldn't be able to see who's added\n after they left\n "
if (not subscription.left):
return [sub.user_id for sub in subscription.group_chat.subscriptions.where((GroupChatSubscription.left == None))... |
4065bd4fdc746feab3e7ec5564c2b0fa6353de66c8795affb5dce47265fad766 | def _add_message_to_subscription(session, subscription, **kwargs):
'\n Creates a new message for a subscription, from the user whose subscription that is. Updates last seen message id\n\n Specify the keyword args for Message\n '
message = Message(conversation=subscription.group_chat.conversation, autho... | Creates a new message for a subscription, from the user whose subscription that is. Updates last seen message id
Specify the keyword args for Message | app/backend/src/couchers/servicers/conversations.py | _add_message_to_subscription | dieterpankratz/couchers | 226 | python | def _add_message_to_subscription(session, subscription, **kwargs):
'\n Creates a new message for a subscription, from the user whose subscription that is. Updates last seen message id\n\n Specify the keyword args for Message\n '
message = Message(conversation=subscription.group_chat.conversation, autho... | def _add_message_to_subscription(session, subscription, **kwargs):
'\n Creates a new message for a subscription, from the user whose subscription that is. Updates last seen message id\n\n Specify the keyword args for Message\n '
message = Message(conversation=subscription.group_chat.conversation, autho... |
185ee779b742815c7015aaa8dc41a8f7b92316349a27cdc5fd41e8e86531a5aa | def RemoveGroupChatUser(self, request, context):
"\n 1. Get admin info and check it's correct\n 2. Get user data, check it's correct and remove user\n "
with session_scope() as session:
your_subscription = session.execute(select(GroupChatSubscription).where((GroupChatSubscription.gr... | 1. Get admin info and check it's correct
2. Get user data, check it's correct and remove user | app/backend/src/couchers/servicers/conversations.py | RemoveGroupChatUser | dieterpankratz/couchers | 226 | python | def RemoveGroupChatUser(self, request, context):
"\n 1. Get admin info and check it's correct\n 2. Get user data, check it's correct and remove user\n "
with session_scope() as session:
your_subscription = session.execute(select(GroupChatSubscription).where((GroupChatSubscription.gr... | def RemoveGroupChatUser(self, request, context):
"\n 1. Get admin info and check it's correct\n 2. Get user data, check it's correct and remove user\n "
with session_scope() as session:
your_subscription = session.execute(select(GroupChatSubscription).where((GroupChatSubscription.gr... |
63e3a6b8a3412f173137ac192fd0fa0008e5269a7f42783d47d2021a130b9d6e | def disk(d=60, h=10, maxh=5.0, relaxed=True, name='normal_modes_nanodisk', A=1.3e-11, H_ext_relax=[100000.0, 1000.0, 0], H_ext_ringdown=[100000.0, 0, 0], demag_solver='FK', demag_solver_type=None, force_relaxation=False):
'\n Permalloy nanodisk with diameter d=60 nm, height h=10 nm and mesh\n discretisation m... | Permalloy nanodisk with diameter d=60 nm, height h=10 nm and mesh
discretisation maxh=5.0. An external field of strength 100 kA/m is
applied along the x-axis, with a small (1 kA/m) y-component for
the relaxation which is then removed for the ringdown phase. | src/finmag/example/normal_modes/disk.py | disk | davidcortesortuno/finmag | 10 | python | def disk(d=60, h=10, maxh=5.0, relaxed=True, name='normal_modes_nanodisk', A=1.3e-11, H_ext_relax=[100000.0, 1000.0, 0], H_ext_ringdown=[100000.0, 0, 0], demag_solver='FK', demag_solver_type=None, force_relaxation=False):
'\n Permalloy nanodisk with diameter d=60 nm, height h=10 nm and mesh\n discretisation m... | def disk(d=60, h=10, maxh=5.0, relaxed=True, name='normal_modes_nanodisk', A=1.3e-11, H_ext_relax=[100000.0, 1000.0, 0], H_ext_ringdown=[100000.0, 0, 0], demag_solver='FK', demag_solver_type=None, force_relaxation=False):
'\n Permalloy nanodisk with diameter d=60 nm, height h=10 nm and mesh\n discretisation m... |
39350e102b9e52a8a46c76aaaea5600ac4a219f0ba85458ac20335cca8253f15 | def ignore_aiohttp_ssl_error(loop):
'Ignore aiohttp #3535 / cpython #13548 issue with SSL data after close\n\n There is an issue in Python 3.7 up to 3.7.3 that over-reports a\n ssl.SSLError fatal error (ssl.SSLError: [SSL: KRB5_S_INIT] application data\n after close notify (_ssl.c:2609)) after we are alrea... | Ignore aiohttp #3535 / cpython #13548 issue with SSL data after close
There is an issue in Python 3.7 up to 3.7.3 that over-reports a
ssl.SSLError fatal error (ssl.SSLError: [SSL: KRB5_S_INIT] application data
after close notify (_ssl.c:2609)) after we are already done with the
connection. See GitHub issues aio-libs/a... | script/calc-reps.py | ignore_aiohttp_ssl_error | Joohansson/nanoticker | 6 | python | def ignore_aiohttp_ssl_error(loop):
'Ignore aiohttp #3535 / cpython #13548 issue with SSL data after close\n\n There is an issue in Python 3.7 up to 3.7.3 that over-reports a\n ssl.SSLError fatal error (ssl.SSLError: [SSL: KRB5_S_INIT] application data\n after close notify (_ssl.c:2609)) after we are alrea... | def ignore_aiohttp_ssl_error(loop):
'Ignore aiohttp #3535 / cpython #13548 issue with SSL data after close\n\n There is an issue in Python 3.7 up to 3.7.3 that over-reports a\n ssl.SSLError fatal error (ssl.SSLError: [SSL: KRB5_S_INIT] application data\n after close notify (_ssl.c:2609)) after we are alrea... |
43c51cb7eb7945b97fc4c9ed1c9173170046bf16d38d661c08223d287c3115ae | def chunks(l, n):
'Yield successive n-sized chunks from l'
for i in range(0, len(l), n):
(yield l[i:(i + n)]) | Yield successive n-sized chunks from l | script/calc-reps.py | chunks | Joohansson/nanoticker | 6 | python | def chunks(l, n):
for i in range(0, len(l), n):
(yield l[i:(i + n)]) | def chunks(l, n):
for i in range(0, len(l), n):
(yield l[i:(i + n)])<|docstring|>Yield successive n-sized chunks from l<|endoftext|> |
4644a3f72ee917b62b3c2820efa8dd2abe730e6e704f47f222ce41d9b8541aad | def forward(self, x: torch.Tensor) -> Tuple[(torch.Tensor, torch.Tensor, torch.Tensor)]:
'\n :param x: (batch size, channels, height, width)\n :return: (batch size, class), (batch size, class), heatmap (batch size, 1, height, width)\n '
origin_feature = self.feature_extractor(x)[(- 1)]
... | :param x: (batch size, channels, height, width)
:return: (batch size, class), (batch size, class), heatmap (batch size, 1, height, width) | deepext_with_lightning/models/classification/abn/modules.py | forward | pei223/deepext_with_lightning | 1 | python | def forward(self, x: torch.Tensor) -> Tuple[(torch.Tensor, torch.Tensor, torch.Tensor)]:
'\n :param x: (batch size, channels, height, width)\n :return: (batch size, class), (batch size, class), heatmap (batch size, 1, height, width)\n '
origin_feature = self.feature_extractor(x)[(- 1)]
... | def forward(self, x: torch.Tensor) -> Tuple[(torch.Tensor, torch.Tensor, torch.Tensor)]:
'\n :param x: (batch size, channels, height, width)\n :return: (batch size, class), (batch size, class), heatmap (batch size, 1, height, width)\n '
origin_feature = self.feature_extractor(x)[(- 1)]
... |
6cb4c00b86cbb35b74766b1f1d8589d0c3cfe42b59ed191bd48c2114c364a7df | def load_tests(*_):
'Load doctests as unittest test suite.\n\n For the parameters, see :mod:`unittest`. The parameters are unused here.\n '
suite = TestSuite()
suite.addTests(DocTestSuite('COT.helpers.helper'))
return suite | Load doctests as unittest test suite.
For the parameters, see :mod:`unittest`. The parameters are unused here. | COT/helpers/tests/test_doctests.py | load_tests | morneaup/cot | 81 | python | def load_tests(*_):
'Load doctests as unittest test suite.\n\n For the parameters, see :mod:`unittest`. The parameters are unused here.\n '
suite = TestSuite()
suite.addTests(DocTestSuite('COT.helpers.helper'))
return suite | def load_tests(*_):
'Load doctests as unittest test suite.\n\n For the parameters, see :mod:`unittest`. The parameters are unused here.\n '
suite = TestSuite()
suite.addTests(DocTestSuite('COT.helpers.helper'))
return suite<|docstring|>Load doctests as unittest test suite.
For the parameters, see... |
ce8f6434b0cd2a780df2e69b928172a0e9d3db0cd70d664a3a666fcca1a1be45 | def get_LOC_entity(tag_seq, char_seq):
'\n 这里需要对输出序列进行判断,对连续序列进行拼接\n :param tag_seq:\n :param char_seq:\n :return:\n '
length = len(char_seq)
LOC = []
location = []
for (i, (char, tag)) in enumerate(zip(char_seq, tag_seq)):
if (tag == 'B-LOC'):
if ('loc' in locals(... | 这里需要对输出序列进行判断,对连续序列进行拼接
:param tag_seq:
:param char_seq:
:return: | Chatbot_Model/Info_Extraction/Entity_Extraction/utils.py | get_LOC_entity | daniellibin/Chatbot_CN | 8 | python | def get_LOC_entity(tag_seq, char_seq):
'\n 这里需要对输出序列进行判断,对连续序列进行拼接\n :param tag_seq:\n :param char_seq:\n :return:\n '
length = len(char_seq)
LOC = []
location = []
for (i, (char, tag)) in enumerate(zip(char_seq, tag_seq)):
if (tag == 'B-LOC'):
if ('loc' in locals(... | def get_LOC_entity(tag_seq, char_seq):
'\n 这里需要对输出序列进行判断,对连续序列进行拼接\n :param tag_seq:\n :param char_seq:\n :return:\n '
length = len(char_seq)
LOC = []
location = []
for (i, (char, tag)) in enumerate(zip(char_seq, tag_seq)):
if (tag == 'B-LOC'):
if ('loc' in locals(... |
4a8b86d2da5f01fce855d62a59a0167ff3be086f4c65ad521ed12b81a0fc3990 | def get_TIM_entity(tag_seq, char_seq):
'\n 获取时间实体\n :param tag_seq:\n :param char_seq:\n :return:\n '
length = len(char_seq)
TIM = []
try:
for (i, (char, tag)) in enumerate(zip(char_seq, tag_seq)):
if (tag == 'B-TIM'):
if ('tim' in locals().keys()):
... | 获取时间实体
:param tag_seq:
:param char_seq:
:return: | Chatbot_Model/Info_Extraction/Entity_Extraction/utils.py | get_TIM_entity | daniellibin/Chatbot_CN | 8 | python | def get_TIM_entity(tag_seq, char_seq):
'\n 获取时间实体\n :param tag_seq:\n :param char_seq:\n :return:\n '
length = len(char_seq)
TIM = []
try:
for (i, (char, tag)) in enumerate(zip(char_seq, tag_seq)):
if (tag == 'B-TIM'):
if ('tim' in locals().keys()):
... | def get_TIM_entity(tag_seq, char_seq):
'\n 获取时间实体\n :param tag_seq:\n :param char_seq:\n :return:\n '
length = len(char_seq)
TIM = []
try:
for (i, (char, tag)) in enumerate(zip(char_seq, tag_seq)):
if (tag == 'B-TIM'):
if ('tim' in locals().keys()):
... |
a9165b87a3270f321218e392cef7b86f18c91dd902979cab0cb543ae0ebe12f4 | def get_MON_entity(text):
'\n 获取金额实体\n :param text:\n :return:\n '
M = []
MON = []
tr = proprecess_money.wash_data(text)
sent = proprecess_money.split_sentence(tr)
for sentence in sent:
money = proprecess_money.get_properties_and_values(sentence)
M.append(money)
... | 获取金额实体
:param text:
:return: | Chatbot_Model/Info_Extraction/Entity_Extraction/utils.py | get_MON_entity | daniellibin/Chatbot_CN | 8 | python | def get_MON_entity(text):
'\n 获取金额实体\n :param text:\n :return:\n '
M = []
MON = []
tr = proprecess_money.wash_data(text)
sent = proprecess_money.split_sentence(tr)
for sentence in sent:
money = proprecess_money.get_properties_and_values(sentence)
M.append(money)
... | def get_MON_entity(text):
'\n 获取金额实体\n :param text:\n :return:\n '
M = []
MON = []
tr = proprecess_money.wash_data(text)
sent = proprecess_money.split_sentence(tr)
for sentence in sent:
money = proprecess_money.get_properties_and_values(sentence)
M.append(money)
... |
b607dc40081536ecf5a5c4ec0fa3070f12e7bba801c1f76a22f24b78403547da | def __init__(self, cfg):
' extractor regional features from the shared conv layers '
super(FeatExtractor, self).__init__()
self.cfg = cfg
(self.out_height, self.out_width) = self.cfg.MODEL.FM_ROI_POOL_SIZE
model_info = model_factory[self.cfg.MODEL.BACKBONE]
self.feat_name_list = self.cfg.MODEL.F... | extractor regional features from the shared conv layers | siam_tracker/spm_tracker/modules/spm_tracker_fm.py | __init__ | Bhaskers-Blu-Org2/SPM-Tracker | 32 | python | def __init__(self, cfg):
' '
super(FeatExtractor, self).__init__()
self.cfg = cfg
(self.out_height, self.out_width) = self.cfg.MODEL.FM_ROI_POOL_SIZE
model_info = model_factory[self.cfg.MODEL.BACKBONE]
self.feat_name_list = self.cfg.MODEL.FM_FEAT_NAME_LIST
self.nc_list = model_info.infer_ch... | def __init__(self, cfg):
' '
super(FeatExtractor, self).__init__()
self.cfg = cfg
(self.out_height, self.out_width) = self.cfg.MODEL.FM_ROI_POOL_SIZE
model_info = model_factory[self.cfg.MODEL.BACKBONE]
self.feat_name_list = self.cfg.MODEL.FM_FEAT_NAME_LIST
self.nc_list = model_info.infer_ch... |
1d027c3b846ccd95d840e34b71c472972bf6930fdd32f31827fbf21ff81707b5 | def get_random_user_agent():
'\n Get a random user agent string.\n\n :rtype: str\n :return: Random user agent string.\n '
return random.choice(user_agents_list) | Get a random user agent string.
:rtype: str
:return: Random user agent string. | googlesearch/sometest.py | get_random_user_agent | Octoberr/swm0920 | 2 | python | def get_random_user_agent():
'\n Get a random user agent string.\n\n :rtype: str\n :return: Random user agent string.\n '
return random.choice(user_agents_list) | def get_random_user_agent():
'\n Get a random user agent string.\n\n :rtype: str\n :return: Random user agent string.\n '
return random.choice(user_agents_list)<|docstring|>Get a random user agent string.
:rtype: str
:return: Random user agent string.<|endoftext|> |
efd4c2ed2fb78f80f50e7791e028cf71948c3483dd38576a61fd1c91921b8bdf | @staticmethod
def add_args(parser):
'Add task-specific arguments to the parser.'
TranslationTask.add_args(parser)
parser.add_argument('--noise', default='random_delete', choices=['random_delete', 'random_mask', 'no_noise', 'full_mask']) | Add task-specific arguments to the parser. | fairseq/tasks/translation_lev.py | add_args | wangqi1996/cmlm | 0 | python | @staticmethod
def add_args(parser):
TranslationTask.add_args(parser)
parser.add_argument('--noise', default='random_delete', choices=['random_delete', 'random_mask', 'no_noise', 'full_mask']) | @staticmethod
def add_args(parser):
TranslationTask.add_args(parser)
parser.add_argument('--noise', default='random_delete', choices=['random_delete', 'random_mask', 'no_noise', 'full_mask'])<|docstring|>Add task-specific arguments to the parser.<|endoftext|> |
15b61e04609fecf0dbf09f342efe6d11e3795ec6fc9eb8d58c979b22dba449a3 | def load_dataset(self, split, epoch=1, combine=False, **kwargs):
'Load a given dataset split.\n\n Args:\n split (str): name of the split (e.g., train, valid, test)\n '
paths = utils.split_paths(self.args.data)
assert (len(paths) > 0)
data_path = paths[((epoch - 1) % len(paths))]... | Load a given dataset split.
Args:
split (str): name of the split (e.g., train, valid, test) | fairseq/tasks/translation_lev.py | load_dataset | wangqi1996/cmlm | 0 | python | def load_dataset(self, split, epoch=1, combine=False, **kwargs):
'Load a given dataset split.\n\n Args:\n split (str): name of the split (e.g., train, valid, test)\n '
paths = utils.split_paths(self.args.data)
assert (len(paths) > 0)
data_path = paths[((epoch - 1) % len(paths))]... | def load_dataset(self, split, epoch=1, combine=False, **kwargs):
'Load a given dataset split.\n\n Args:\n split (str): name of the split (e.g., train, valid, test)\n '
paths = utils.split_paths(self.args.data)
assert (len(paths) > 0)
data_path = paths[((epoch - 1) % len(paths))]... |
31d1873574d35758070d4fcad1c7dbf1733f05cc6e4e0df93e3093ad9f004c99 | def fit(time_event, censoring, labx, verbose=3):
"\n\n Parameters\n ----------\n time_event: [FLOAT]: Numpy array with survival-time in years/months/days (not a datetime!)\n\n censoring: [INT]: numpy array with censoring (1=event, 0=ongoing)\n At the time you want to make inf... | Parameters
----------
time_event: [FLOAT]: Numpy array with survival-time in years/months/days (not a datetime!)
censoring: [INT]: numpy array with censoring (1=event, 0=ongoing)
At the time you want to make inferences about durations, it is possible, likely true, that not all the death events... | kaplanmeier/kaplanmeier.py | fit | bskienhvqy/kaplanmeier | 0 | python | def fit(time_event, censoring, labx, verbose=3):
"\n\n Parameters\n ----------\n time_event: [FLOAT]: Numpy array with survival-time in years/months/days (not a datetime!)\n\n censoring: [INT]: numpy array with censoring (1=event, 0=ongoing)\n At the time you want to make inf... | def fit(time_event, censoring, labx, verbose=3):
"\n\n Parameters\n ----------\n time_event: [FLOAT]: Numpy array with survival-time in years/months/days (not a datetime!)\n\n censoring: [INT]: numpy array with censoring (1=event, 0=ongoing)\n At the time you want to make inf... |
5a0599f34e9331a9d63bfee193ccf5de478b2d46cd8f37f637308505772e68e0 | def plot(out, fontsize=12, savepath='', width=10, height=6, cmap='Set1', cii_alpha=0.05, cii_lines='dense', methodtype='lifeline', title='Survival function', full_ylim=False, y_percentage=False):
"\n \n\n Parameters\n ----------\n out : [dict] Dictionary derived from the fit function.\n\n fonts... | Parameters
----------
out : [dict] Dictionary derived from the fit function.
fontsize : [INT], Font size for the graph
default is 12.
savepath: [STRING], Path to store the figure
width: [INT], Width of the figure
10 (default)
height: [INT], Width of the figure
... | kaplanmeier/kaplanmeier.py | plot | bskienhvqy/kaplanmeier | 0 | python | def plot(out, fontsize=12, savepath=, width=10, height=6, cmap='Set1', cii_alpha=0.05, cii_lines='dense', methodtype='lifeline', title='Survival function', full_ylim=False, y_percentage=False):
"\n \n\n Parameters\n ----------\n out : [dict] Dictionary derived from the fit function.\n\n fontsiz... | def plot(out, fontsize=12, savepath=, width=10, height=6, cmap='Set1', cii_alpha=0.05, cii_lines='dense', methodtype='lifeline', title='Survival function', full_ylim=False, y_percentage=False):
"\n \n\n Parameters\n ----------\n out : [dict] Dictionary derived from the fit function.\n\n fontsiz... |
260e662e114f7d74ffff36688b586708f19de9e35002c8c7ce523f03b889ccf9 | def test_pac_callstack_limit(self):
'\n Try to load a PAC file that hits the Duktape call stack limit.\n '
pac_js = 'function FindProxyForURL(url, host) {function b() {a();} function a() {b();}; a(); return "DIRECT";}'
with pytest.raises(MalformedPacError) as e:
PACFile(pac_js)
ass... | Try to load a PAC file that hits the Duktape call stack limit. | tests/test_parser.py | test_pac_callstack_limit | zanachka/pypac | 47 | python | def test_pac_callstack_limit(self):
'\n \n '
pac_js = 'function FindProxyForURL(url, host) {function b() {a();} function a() {b();}; a(); return "DIRECT";}'
with pytest.raises(MalformedPacError) as e:
PACFile(pac_js)
assert ('callstack limit' in str(e.value)) | def test_pac_callstack_limit(self):
'\n \n '
pac_js = 'function FindProxyForURL(url, host) {function b() {a();} function a() {b();}; a(); return "DIRECT";}'
with pytest.raises(MalformedPacError) as e:
PACFile(pac_js)
assert ('callstack limit' in str(e.value))<|docstring|>Try to loa... |
ca55fb85c1750dd5d46dcd860543218be6698f681004f7c112c682235e27b692 | def test_dnsResolve_propagation(self):
'\n dnsResolve must return an empty string now we use dukpy, otherwise\n None value causes dukpy error as it propagates\n '
parser = PACFile((dummy_js % 'isInNet(dnsResolve(host), "10.1.1.0", "255.255.255.0")'))
assert (parser.find_proxy_for_url('$... | dnsResolve must return an empty string now we use dukpy, otherwise
None value causes dukpy error as it propagates | tests/test_parser.py | test_dnsResolve_propagation | zanachka/pypac | 47 | python | def test_dnsResolve_propagation(self):
'\n dnsResolve must return an empty string now we use dukpy, otherwise\n None value causes dukpy error as it propagates\n '
parser = PACFile((dummy_js % 'isInNet(dnsResolve(host), "10.1.1.0", "255.255.255.0")'))
assert (parser.find_proxy_for_url('$... | def test_dnsResolve_propagation(self):
'\n dnsResolve must return an empty string now we use dukpy, otherwise\n None value causes dukpy error as it propagates\n '
parser = PACFile((dummy_js % 'isInNet(dnsResolve(host), "10.1.1.0", "255.255.255.0")'))
assert (parser.find_proxy_for_url('$... |
d955afa5b1d345dc41899c99260d66d5fd1d963c2ec3a7efc727500a74c8146d | def is_initial_tag(self, current_tag_version: str, is_yes: bool=False) -> bool:
'Check if reading the whole git tree up to HEAD is needed.'
is_initial = False
if (not git.tag_exist(current_tag_version)):
if is_yes:
is_initial = True
else:
out.info(f'Tag {current_tag_v... | Check if reading the whole git tree up to HEAD is needed. | commitizen/commands/bump.py | is_initial_tag | dariemp/commitizen | 0 | python | def is_initial_tag(self, current_tag_version: str, is_yes: bool=False) -> bool:
is_initial = False
if (not git.tag_exist(current_tag_version)):
if is_yes:
is_initial = True
else:
out.info(f'Tag {current_tag_version} could not be found. ')
out.info("Possib... | def is_initial_tag(self, current_tag_version: str, is_yes: bool=False) -> bool:
is_initial = False
if (not git.tag_exist(current_tag_version)):
if is_yes:
is_initial = True
else:
out.info(f'Tag {current_tag_version} could not be found. ')
out.info("Possib... |
88ed0bec0dc4221d2748c3a2803b3753e948505d0ef1b9c939d4011f897c8b60 | def __call__(self):
'Steps executed to bump.'
try:
current_version_instance: Version = Version(self.parameters['version'])
except TypeError:
out.error('[NO_VERSION_SPECIFIED]')
out.error('Check if current version is specified in config file, like:')
out.error('version = 0.4.3... | Steps executed to bump. | commitizen/commands/bump.py | __call__ | dariemp/commitizen | 0 | python | def __call__(self):
try:
current_version_instance: Version = Version(self.parameters['version'])
except TypeError:
out.error('[NO_VERSION_SPECIFIED]')
out.error('Check if current version is specified in config file, like:')
out.error('version = 0.4.3')
raise SystemEx... | def __call__(self):
try:
current_version_instance: Version = Version(self.parameters['version'])
except TypeError:
out.error('[NO_VERSION_SPECIFIED]')
out.error('Check if current version is specified in config file, like:')
out.error('version = 0.4.3')
raise SystemEx... |
8ad00375b7250ab282e7c1cbb308ad6f7a057c745d09fa48f0d5a5d21435cefb | def __init__(self, manager: PathToolManagerT):
'\n Args:\n manager: Description\n '
super(AbstractPathTool, self).__init__(None)
self.manager: PathToolManagerT = manager
self._window: DocT = manager.window
self._active: bool = False
self._last_location = None
self._r... | Args:
manager: Description | cadnano/views/pathview/tools/abstractpathtool.py | __init__ | sherwoodyao/cadnano2.5 | 69 | python | def __init__(self, manager: PathToolManagerT):
'\n Args:\n manager: Description\n '
super(AbstractPathTool, self).__init__(None)
self.manager: PathToolManagerT = manager
self._window: DocT = manager.window
self._active: bool = False
self._last_location = None
self._r... | def __init__(self, manager: PathToolManagerT):
'\n Args:\n manager: Description\n '
super(AbstractPathTool, self).__init__(None)
self.manager: PathToolManagerT = manager
self._window: DocT = manager.window
self._active: bool = False
self._last_location = None
self._r... |
6e26a2914bd668f42d65a9cd52c40b0663971c4c17686ed2565680dc04ea2783 | def paint(self, painter: QPainter, option: QStyleOptionGraphicsItem, widget: QWidget=None):
'\n Args:\n painter: Description\n option: Description\n widget: Default is ``None``\n '
painter.setPen(self._pen)
painter.setBrush(_BRUSH)
painter.drawRect(_TOOL_RE... | Args:
painter: Description
option: Description
widget: Default is ``None`` | cadnano/views/pathview/tools/abstractpathtool.py | paint | sherwoodyao/cadnano2.5 | 69 | python | def paint(self, painter: QPainter, option: QStyleOptionGraphicsItem, widget: QWidget=None):
'\n Args:\n painter: Description\n option: Description\n widget: Default is ``None``\n '
painter.setPen(self._pen)
painter.setBrush(_BRUSH)
painter.drawRect(_TOOL_RE... | def paint(self, painter: QPainter, option: QStyleOptionGraphicsItem, widget: QWidget=None):
'\n Args:\n painter: Description\n option: Description\n widget: Default is ``None``\n '
painter.setPen(self._pen)
painter.setBrush(_BRUSH)
painter.drawRect(_TOOL_RE... |
e29e0af3fe2356de67858d711cb5b2c32a685e75f21aadbbd2bf8d9dc0c571c1 | def boundingRect(self) -> QRectF:
'Returns:\n bounding rectangle\n '
return self._rect | Returns:
bounding rectangle | cadnano/views/pathview/tools/abstractpathtool.py | boundingRect | sherwoodyao/cadnano2.5 | 69 | python | def boundingRect(self) -> QRectF:
'Returns:\n bounding rectangle\n '
return self._rect | def boundingRect(self) -> QRectF:
'Returns:\n bounding rectangle\n '
return self._rect<|docstring|>Returns:
bounding rectangle<|endoftext|> |
4ae0ec84a87f2b9938f880b2053a3e5e38e6ced8489972f93d38087489d8ba9f | def updateLocation(self, virtual_helix_item: PathVirtualHelixItemT, scene_pos: QPointF, *args):
"Takes care of caching the location so that a tool switch\n outside the context of an event will know where to\n position the new tool and snaps self's pos to the upper\n left hand corner of the base... | Takes care of caching the location so that a tool switch
outside the context of an event will know where to
position the new tool and snaps self's pos to the upper
left hand corner of the base the user is mousing over.
Args:
virtual_helix_item: PathVirtualHelixItem
scene_pos: point in the scene
*args: DESC... | cadnano/views/pathview/tools/abstractpathtool.py | updateLocation | sherwoodyao/cadnano2.5 | 69 | python | def updateLocation(self, virtual_helix_item: PathVirtualHelixItemT, scene_pos: QPointF, *args):
"Takes care of caching the location so that a tool switch\n outside the context of an event will know where to\n position the new tool and snaps self's pos to the upper\n left hand corner of the base... | def updateLocation(self, virtual_helix_item: PathVirtualHelixItemT, scene_pos: QPointF, *args):
"Takes care of caching the location so that a tool switch\n outside the context of an event will know where to\n position the new tool and snaps self's pos to the upper\n left hand corner of the base... |
c5b30acb4f54f6123601402dac0913f24f9c2e754699d92468a97dfca3770d79 | def lastLocation(self) -> Optional[Tuple[(PathVirtualHelixItemT, QPointF)]]:
"A tool's last_location consists of a :class`PathVirtualHelixItem` and\n a scene pos (:class:`QPoint`) representing the last known location of\n the mouse.\n\n It can be used to provide visual continuity when switching... | A tool's last_location consists of a :class`PathVirtualHelixItem` and
a scene pos (:class:`QPoint`) representing the last known location of
the mouse.
It can be used to provide visual continuity when switching tools.
When the new tool is selected, this method will be invoked by
calling `updateLocation(*old_tool.lastLo... | cadnano/views/pathview/tools/abstractpathtool.py | lastLocation | sherwoodyao/cadnano2.5 | 69 | python | def lastLocation(self) -> Optional[Tuple[(PathVirtualHelixItemT, QPointF)]]:
"A tool's last_location consists of a :class`PathVirtualHelixItem` and\n a scene pos (:class:`QPoint`) representing the last known location of\n the mouse.\n\n It can be used to provide visual continuity when switching... | def lastLocation(self) -> Optional[Tuple[(PathVirtualHelixItemT, QPointF)]]:
"A tool's last_location consists of a :class`PathVirtualHelixItem` and\n a scene pos (:class:`QPoint`) representing the last known location of\n the mouse.\n\n It can be used to provide visual continuity when switching... |
c60965a2b6ee05524ec409d9e4fc5242404b1d3ec68d56f9795182cd17c21e5d | def setActive(self, will_be_active: bool, old_tool=None):
'\n Called by PathToolManager.setActiveTool when the tool becomes\n active. Used, for example, to show/hide tool-specific ui elements.\n\n Args:\n will_be_active (TYPE): Description\n old_tool (None, optional): Desc... | Called by PathToolManager.setActiveTool when the tool becomes
active. Used, for example, to show/hide tool-specific ui elements.
Args:
will_be_active (TYPE): Description
old_tool (None, optional): Description | cadnano/views/pathview/tools/abstractpathtool.py | setActive | sherwoodyao/cadnano2.5 | 69 | python | def setActive(self, will_be_active: bool, old_tool=None):
'\n Called by PathToolManager.setActiveTool when the tool becomes\n active. Used, for example, to show/hide tool-specific ui elements.\n\n Args:\n will_be_active (TYPE): Description\n old_tool (None, optional): Desc... | def setActive(self, will_be_active: bool, old_tool=None):
'\n Called by PathToolManager.setActiveTool when the tool becomes\n active. Used, for example, to show/hide tool-specific ui elements.\n\n Args:\n will_be_active (TYPE): Description\n old_tool (None, optional): Desc... |
555ca1dac1912efb9b690674e1fe16b5fa26604cd10d71689773c0dd7f797463 | def deactivate(self):
'Summary\n\n Returns:\n TYPE: Description\n '
self.hide() | Summary
Returns:
TYPE: Description | cadnano/views/pathview/tools/abstractpathtool.py | deactivate | sherwoodyao/cadnano2.5 | 69 | python | def deactivate(self):
'Summary\n\n Returns:\n TYPE: Description\n '
self.hide() | def deactivate(self):
'Summary\n\n Returns:\n TYPE: Description\n '
self.hide()<|docstring|>Summary
Returns:
TYPE: Description<|endoftext|> |
7a67927d3e07c8b8ef05fc03f3cd1638c9420fa2e2f40aba02d03ca7bc0f151f | def isActive(self) -> bool:
'Returns isActive\n '
return self._active | Returns isActive | cadnano/views/pathview/tools/abstractpathtool.py | isActive | sherwoodyao/cadnano2.5 | 69 | python | def isActive(self) -> bool:
'\n '
return self._active | def isActive(self) -> bool:
'\n '
return self._active<|docstring|>Returns isActive<|endoftext|> |
a4734ef807fdc6e19c0a1bec70df497dd3add9a40eb0df711ac7f1f809fe0690 | def widgetClicked(self):
'Called every time a widget representing self gets clicked,\n not just when changing tools.\n ' | Called every time a widget representing self gets clicked,
not just when changing tools. | cadnano/views/pathview/tools/abstractpathtool.py | widgetClicked | sherwoodyao/cadnano2.5 | 69 | python | def widgetClicked(self):
'Called every time a widget representing self gets clicked,\n not just when changing tools.\n ' | def widgetClicked(self):
'Called every time a widget representing self gets clicked,\n not just when changing tools.\n '<|docstring|>Called every time a widget representing self gets clicked,
not just when changing tools.<|endoftext|> |
8d171907726aa8b79eb1ea9d506b9fb1c8016b03b766afbf03d818bfd12677bd | def baseAtPoint(self, virtual_helix_item: PathVirtualHelixItemT, pt: QPointF) -> Tuple[(bool, int, int)]:
'Returns the ``(is_fwd, base_idx, strand_idx)`` corresponding\n to pt in virtual_helix_item.\n\n Args:\n virtual_helix_item: :class:`PathVirtualHelixItem`\n pt: Point on heli... | Returns the ``(is_fwd, base_idx, strand_idx)`` corresponding
to pt in virtual_helix_item.
Args:
virtual_helix_item: :class:`PathVirtualHelixItem`
pt: Point on helix | cadnano/views/pathview/tools/abstractpathtool.py | baseAtPoint | sherwoodyao/cadnano2.5 | 69 | python | def baseAtPoint(self, virtual_helix_item: PathVirtualHelixItemT, pt: QPointF) -> Tuple[(bool, int, int)]:
'Returns the ``(is_fwd, base_idx, strand_idx)`` corresponding\n to pt in virtual_helix_item.\n\n Args:\n virtual_helix_item: :class:`PathVirtualHelixItem`\n pt: Point on heli... | def baseAtPoint(self, virtual_helix_item: PathVirtualHelixItemT, pt: QPointF) -> Tuple[(bool, int, int)]:
'Returns the ``(is_fwd, base_idx, strand_idx)`` corresponding\n to pt in virtual_helix_item.\n\n Args:\n virtual_helix_item: :class:`PathVirtualHelixItem`\n pt: Point on heli... |
baa44910ad315e64c2a5007eed2fe3481ba027b4958debd31300e4c665b64706 | def helixIndex(self, point: QPointF) -> Vec2T:
'Returns the (row, col) of the base which point lies within.\n\n Returns:\n point (tuple) in virtual_helix_item coordinates\n\n Args:\n point (TYPE): Description\n '
x = int((int(point.x()) / _BW))
y = int((int(point.y... | Returns the (row, col) of the base which point lies within.
Returns:
point (tuple) in virtual_helix_item coordinates
Args:
point (TYPE): Description | cadnano/views/pathview/tools/abstractpathtool.py | helixIndex | sherwoodyao/cadnano2.5 | 69 | python | def helixIndex(self, point: QPointF) -> Vec2T:
'Returns the (row, col) of the base which point lies within.\n\n Returns:\n point (tuple) in virtual_helix_item coordinates\n\n Args:\n point (TYPE): Description\n '
x = int((int(point.x()) / _BW))
y = int((int(point.y... | def helixIndex(self, point: QPointF) -> Vec2T:
'Returns the (row, col) of the base which point lies within.\n\n Returns:\n point (tuple) in virtual_helix_item coordinates\n\n Args:\n point (TYPE): Description\n '
x = int((int(point.x()) / _BW))
y = int((int(point.y... |
6fcd29ace9ebdf25e380808a35d8b1d18f4b16b8e1b218726a93b729bcc82ecb | def helixPos(self, point):
'\n Snaps a point to the upper left corner of the base\n it is within.\n point is in virtual_helix_item coordinates\n\n Args:\n point (TYPE): Description\n '
col = int((int(point.x()) / _BW))
row = int((int(point.y()) / _BW))
if ((... | Snaps a point to the upper left corner of the base
it is within.
point is in virtual_helix_item coordinates
Args:
point (TYPE): Description | cadnano/views/pathview/tools/abstractpathtool.py | helixPos | sherwoodyao/cadnano2.5 | 69 | python | def helixPos(self, point):
'\n Snaps a point to the upper left corner of the base\n it is within.\n point is in virtual_helix_item coordinates\n\n Args:\n point (TYPE): Description\n '
col = int((int(point.x()) / _BW))
row = int((int(point.y()) / _BW))
if ((... | def helixPos(self, point):
'\n Snaps a point to the upper left corner of the base\n it is within.\n point is in virtual_helix_item coordinates\n\n Args:\n point (TYPE): Description\n '
col = int((int(point.x()) / _BW))
row = int((int(point.y()) / _BW))
if ((... |
3636fe242f124e93e13e2396dc2c8eb721bb6562bac9dd824bd8906fdd499a69 | def hoverLeaveEvent(self, event):
'\n flag is for the case where an item in the path also needs to\n implement the hover method\n\n Args:\n event (TYPE): Description\n '
self.hide() | flag is for the case where an item in the path also needs to
implement the hover method
Args:
event (TYPE): Description | cadnano/views/pathview/tools/abstractpathtool.py | hoverLeaveEvent | sherwoodyao/cadnano2.5 | 69 | python | def hoverLeaveEvent(self, event):
'\n flag is for the case where an item in the path also needs to\n implement the hover method\n\n Args:\n event (TYPE): Description\n '
self.hide() | def hoverLeaveEvent(self, event):
'\n flag is for the case where an item in the path also needs to\n implement the hover method\n\n Args:\n event (TYPE): Description\n '
self.hide()<|docstring|>flag is for the case where an item in the path also needs to
implement the hove... |
ab4384e1c948c5140bf89424599b6126a4a8d9558b658efe18f5be53aaf26687 | def __init__(self, pool_size):
'\n Initialize the ImagePool class\n\n Parameters\n ----------\n pool_size : int\n The size of image buffer, if pool_size=0, no buffer will be created\n '
self.pool_size = pool_size
if (self.pool_size > 0):
self.num_imgs = ... | Initialize the ImagePool class
Parameters
----------
pool_size : int
The size of image buffer, if pool_size=0, no buffer will be created | pytorch_3T27T/utils/image_pool.py | __init__ | HechengJin0/pytorch_3T27T | 0 | python | def __init__(self, pool_size):
'\n Initialize the ImagePool class\n\n Parameters\n ----------\n pool_size : int\n The size of image buffer, if pool_size=0, no buffer will be created\n '
self.pool_size = pool_size
if (self.pool_size > 0):
self.num_imgs = ... | def __init__(self, pool_size):
'\n Initialize the ImagePool class\n\n Parameters\n ----------\n pool_size : int\n The size of image buffer, if pool_size=0, no buffer will be created\n '
self.pool_size = pool_size
if (self.pool_size > 0):
self.num_imgs = ... |
d5c86d3ce4c8fe5830f154ff5eeedc5b620ff4dd36bd6a4a27e6b13863ff269c | def query(self, images):
'\n Return an image from the pool.\n\n Parameters\n ----------\n images : torch.Tensor\n The latest generated images from the generator\n\n Returns\n -------\n return_images : torch.Tensor\n Images from the buffer. If bu... | Return an image from the pool.
Parameters
----------
images : torch.Tensor
The latest generated images from the generator
Returns
-------
return_images : torch.Tensor
Images from the buffer. If buffer is not full, will return the
given input image. Else, wth 50% chance, a previously stored image
in th... | pytorch_3T27T/utils/image_pool.py | query | HechengJin0/pytorch_3T27T | 0 | python | def query(self, images):
'\n Return an image from the pool.\n\n Parameters\n ----------\n images : torch.Tensor\n The latest generated images from the generator\n\n Returns\n -------\n return_images : torch.Tensor\n Images from the buffer. If bu... | def query(self, images):
'\n Return an image from the pool.\n\n Parameters\n ----------\n images : torch.Tensor\n The latest generated images from the generator\n\n Returns\n -------\n return_images : torch.Tensor\n Images from the buffer. If bu... |
e38984ae0da95ba862854a7194507b33d708c6ac612346c7762b32c93efe0575 | @property
def password(self):
'\n password属性函数\n 不允许直接读取原始值\n '
return '密码不是可读形式!' | password属性函数
不允许直接读取原始值 | app/orm/User.py | password | sevenZz/CouponStatistic | 0 | python | @property
def password(self):
'\n password属性函数\n 不允许直接读取原始值\n '
return '密码不是可读形式!' | @property
def password(self):
'\n password属性函数\n 不允许直接读取原始值\n '
return '密码不是可读形式!'<|docstring|>password属性函数
不允许直接读取原始值<|endoftext|> |
f1e8b6f7a9eecc71288ec22439801f8e0385975ca561c3835168739b8f8f222f | @password.setter
def password(self, password):
'\n 设置密码hash值\n '
self.password_hash = werkzeug.security.generate_password_hash(password) | 设置密码hash值 | app/orm/User.py | password | sevenZz/CouponStatistic | 0 | python | @password.setter
def password(self, password):
'\n \n '
self.password_hash = werkzeug.security.generate_password_hash(password) | @password.setter
def password(self, password):
'\n \n '
self.password_hash = werkzeug.security.generate_password_hash(password)<|docstring|>设置密码hash值<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.