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 |
|---|---|---|---|---|---|---|---|---|---|
17c247d872a2ce97303b2a27028810bf58a096f6865c666916206af703395bd5 | def execute(self):
' Method to actually start execution of the test. Must be called from the test_<name>\n method of the test class. '
try:
if self.run_live:
print('RUN LIVE: {}'.format(self.test_name))
self._execute_live_or_recording()
elif self.playback:
print('PLAYBACK: {}'.format(self.test_name))
self._execute_playback()
else:
print('RECORDING: {}'.format(self.test_name))
self._execute_live_or_recording()
except Exception as ex:
traceback.print_exc()
raise ex
finally:
if ((not self.success) and (not self.playback) and os.path.isfile(self.cassette_path)):
print('DISCARDING RECORDING: {}'.format(self.cassette_path))
os.remove(self.cassette_path)
elif (self.success and (not self.playback) and os.path.isfile(self.cassette_path)):
try:
self._post_recording_scrub()
except Exception as ex:
print('DISCARDING RECORDING: {} before of exception thrown during post recording scrub {}.'.format(self.cassette_path, ex))
os.remove(self.cassette_path) | Method to actually start execution of the test. Must be called from the test_<name>
method of the test class. | src/azure-cli-testsdk/azure/cli/testsdk/vcr_test_base.py | execute | viananth/azure-cli | 0 | python | def execute(self):
' Method to actually start execution of the test. Must be called from the test_<name>\n method of the test class. '
try:
if self.run_live:
print('RUN LIVE: {}'.format(self.test_name))
self._execute_live_or_recording()
elif self.playback:
print('PLAYBACK: {}'.format(self.test_name))
self._execute_playback()
else:
print('RECORDING: {}'.format(self.test_name))
self._execute_live_or_recording()
except Exception as ex:
traceback.print_exc()
raise ex
finally:
if ((not self.success) and (not self.playback) and os.path.isfile(self.cassette_path)):
print('DISCARDING RECORDING: {}'.format(self.cassette_path))
os.remove(self.cassette_path)
elif (self.success and (not self.playback) and os.path.isfile(self.cassette_path)):
try:
self._post_recording_scrub()
except Exception as ex:
print('DISCARDING RECORDING: {} before of exception thrown during post recording scrub {}.'.format(self.cassette_path, ex))
os.remove(self.cassette_path) | def execute(self):
' Method to actually start execution of the test. Must be called from the test_<name>\n method of the test class. '
try:
if self.run_live:
print('RUN LIVE: {}'.format(self.test_name))
self._execute_live_or_recording()
elif self.playback:
print('PLAYBACK: {}'.format(self.test_name))
self._execute_playback()
else:
print('RECORDING: {}'.format(self.test_name))
self._execute_live_or_recording()
except Exception as ex:
traceback.print_exc()
raise ex
finally:
if ((not self.success) and (not self.playback) and os.path.isfile(self.cassette_path)):
print('DISCARDING RECORDING: {}'.format(self.cassette_path))
os.remove(self.cassette_path)
elif (self.success and (not self.playback) and os.path.isfile(self.cassette_path)):
try:
self._post_recording_scrub()
except Exception as ex:
print('DISCARDING RECORDING: {} before of exception thrown during post recording scrub {}.'.format(self.cassette_path, ex))
os.remove(self.cassette_path)<|docstring|>Method to actually start execution of the test. Must be called from the test_<name>
method of the test class.<|endoftext|> |
996acd6bcc43c6e236bceb5541b61b8ef535b7e792f768758eb615d524044df0 | def findSum(nums, target):
'nums is a (finite) sorted tuple of numbers, target is a number\n '
if ((nums, target) in memo):
return memo[(nums, target)]
elif (sum(nums) == target):
memo[(nums, target)] = nums
return nums
else:
for i in range(len(nums)):
newNums = (nums[:i] + nums[(i + 1):])
result = findSum(newNums, target)
if (result is not None):
memo[(nums, target)] = result
return result
memo[(nums, target)] = None
return None | nums is a (finite) sorted tuple of numbers, target is a number | python/targetSum.py | findSum | quasarbright/quasarbright.github.io | 1 | python | def findSum(nums, target):
'\n '
if ((nums, target) in memo):
return memo[(nums, target)]
elif (sum(nums) == target):
memo[(nums, target)] = nums
return nums
else:
for i in range(len(nums)):
newNums = (nums[:i] + nums[(i + 1):])
result = findSum(newNums, target)
if (result is not None):
memo[(nums, target)] = result
return result
memo[(nums, target)] = None
return None | def findSum(nums, target):
'\n '
if ((nums, target) in memo):
return memo[(nums, target)]
elif (sum(nums) == target):
memo[(nums, target)] = nums
return nums
else:
for i in range(len(nums)):
newNums = (nums[:i] + nums[(i + 1):])
result = findSum(newNums, target)
if (result is not None):
memo[(nums, target)] = result
return result
memo[(nums, target)] = None
return None<|docstring|>nums is a (finite) sorted tuple of numbers, target is a number<|endoftext|> |
0d941f0732348c91f31130a9eda8bc10ab52b6bf403b9ccedec14aecb4d599dd | def train(env, hyperparameters):
' Train a sarsa lambda agent in the requested environment\n\n Arguments:\n hyperparameters dictionary containing:\n - env_name\n - n zero value\n '
agent = LinearMonteCarlo(env, hyperparameters['learning_rate'], hyperparameters['n_zero'], hyperparameters['gamma'], hyperparameters['min_eps'])
env_name = hyperparameters['env_name']
log_filename = f'log_{env_name}_{time()}.csv'
with open(log_filename, 'a') as f:
f.write('\n'.join(map(','.join, {str(key): str(value) for (key, value) in hyperparameters.items()}.items())))
f.write('\n')
f.write('Episode,Step,Total Reward,q_value_table_length\n')
step = 0
for episode in range(int(10000.0)):
total_reward = 0.0
(states, actions, rewards) = ([], [], [])
observation = env.reset()
state = linear_parse_observation_to_state(observation)
action = agent.get_new_action_e_greedly(state)
done = False
while (not done):
(observation, reward, done, info) = env.step(action)
next_state = linear_parse_observation_to_state(observation)
total_reward += reward
next_action = agent.get_new_action_e_greedly(next_state)
states.append(state)
actions.append(action)
rewards.append(reward)
state = next_state
action = next_action
if done:
with open(log_filename, 'a') as f:
f.write(f'''{episode},{step},{total_reward},{agent.q_value_table.__len__()}
''')
if (((episode % 100) == 0) and (episode != 0)):
print(f'episode {episode}')
play(env, agent, linear_parse_observation_to_state)
step += 1
agent.update(states, actions, rewards)
env.close()
return agent | Train a sarsa lambda agent in the requested environment
Arguments:
hyperparameters dictionary containing:
- env_name
- n zero value | project_RL/linear_monte_carlo/train.py | train | Ronnypetson/gym-minigrid | 0 | python | def train(env, hyperparameters):
' Train a sarsa lambda agent in the requested environment\n\n Arguments:\n hyperparameters dictionary containing:\n - env_name\n - n zero value\n '
agent = LinearMonteCarlo(env, hyperparameters['learning_rate'], hyperparameters['n_zero'], hyperparameters['gamma'], hyperparameters['min_eps'])
env_name = hyperparameters['env_name']
log_filename = f'log_{env_name}_{time()}.csv'
with open(log_filename, 'a') as f:
f.write('\n'.join(map(','.join, {str(key): str(value) for (key, value) in hyperparameters.items()}.items())))
f.write('\n')
f.write('Episode,Step,Total Reward,q_value_table_length\n')
step = 0
for episode in range(int(10000.0)):
total_reward = 0.0
(states, actions, rewards) = ([], [], [])
observation = env.reset()
state = linear_parse_observation_to_state(observation)
action = agent.get_new_action_e_greedly(state)
done = False
while (not done):
(observation, reward, done, info) = env.step(action)
next_state = linear_parse_observation_to_state(observation)
total_reward += reward
next_action = agent.get_new_action_e_greedly(next_state)
states.append(state)
actions.append(action)
rewards.append(reward)
state = next_state
action = next_action
if done:
with open(log_filename, 'a') as f:
f.write(f'{episode},{step},{total_reward},{agent.q_value_table.__len__()}
')
if (((episode % 100) == 0) and (episode != 0)):
print(f'episode {episode}')
play(env, agent, linear_parse_observation_to_state)
step += 1
agent.update(states, actions, rewards)
env.close()
return agent | def train(env, hyperparameters):
' Train a sarsa lambda agent in the requested environment\n\n Arguments:\n hyperparameters dictionary containing:\n - env_name\n - n zero value\n '
agent = LinearMonteCarlo(env, hyperparameters['learning_rate'], hyperparameters['n_zero'], hyperparameters['gamma'], hyperparameters['min_eps'])
env_name = hyperparameters['env_name']
log_filename = f'log_{env_name}_{time()}.csv'
with open(log_filename, 'a') as f:
f.write('\n'.join(map(','.join, {str(key): str(value) for (key, value) in hyperparameters.items()}.items())))
f.write('\n')
f.write('Episode,Step,Total Reward,q_value_table_length\n')
step = 0
for episode in range(int(10000.0)):
total_reward = 0.0
(states, actions, rewards) = ([], [], [])
observation = env.reset()
state = linear_parse_observation_to_state(observation)
action = agent.get_new_action_e_greedly(state)
done = False
while (not done):
(observation, reward, done, info) = env.step(action)
next_state = linear_parse_observation_to_state(observation)
total_reward += reward
next_action = agent.get_new_action_e_greedly(next_state)
states.append(state)
actions.append(action)
rewards.append(reward)
state = next_state
action = next_action
if done:
with open(log_filename, 'a') as f:
f.write(f'{episode},{step},{total_reward},{agent.q_value_table.__len__()}
')
if (((episode % 100) == 0) and (episode != 0)):
print(f'episode {episode}')
play(env, agent, linear_parse_observation_to_state)
step += 1
agent.update(states, actions, rewards)
env.close()
return agent<|docstring|>Train a sarsa lambda agent in the requested environment
Arguments:
hyperparameters dictionary containing:
- env_name
- n zero value<|endoftext|> |
58b1e33df6fa659e21678301ef2842f1efbecdf80757965378dfc0c09f4d7ef8 | @staticmethod
def search_form(omwcgi='wn-grid.cgi', lemma='', langlist=[], interfacelang='eng', langstring='Lang: ', lang2='eng', resize=100):
'Prints the html block of the OMW Search form and\n a dropdown for a list of available languages.\n The interface language is selected by default.'
html = ('<form method="post" style="display: inline-block"\n title="search for a word β \'word\'\nor pattern β \'[wW]ord*\' (using sqlite GLOB)\nor synset-id β \'06286395-n\'\nor a pattern in a definition β \'def::*word*\' (using sqlite GLOB)"\n id="newquery" action="%s">\n <span style="font-size: %s%%">\n <input style="font-size: %s%%" \n type="text" name="lemma" value="%s" \n size=8 maxlength=50>\n\n <button class="small"> <a href="javascript:{}"\n onclick="document.getElementById(\'newquery\').submit(); \n return false;"><span title="Search">\n <span style="color: #4D99E0;"><i class=\'icon-search\'></i>\n </span></span></a></button>\n \n <strong>%s</strong><select name="lang" size="1" \n style="font-size: %s%%"\n onchange="if(this.value == \'showmore\') \n toggle_visibility(\'langselect\');">\n ' % (omwcgi, resize, resize, lemma, langstring, resize))
for l in langlist:
if (interfacelang == l):
html += ("<option value ='%s' selected>%s\n " % (l, omwlang.trans(l, interfacelang)))
else:
html += ("<option value ='%s'>%s\n " % (l, omwlang.trans(l, interfacelang)))
html += '<option value="showmore">More...</option>'
html += ('</select><select name="lang2" style="font-size: %s%%"\n title="backoff language" size="1" \n onchange="if(this.value == \'showmore\') \n toggle_visibility(\'langselect\');">' % resize)
for l in langlist:
if (l == lang2):
html += ("<option value ='%s' selected>%s\n " % (l, omwlang.trans(l, interfacelang)))
else:
html += ("<option value ='%s'>%s\n " % (l, omwlang.trans(l, interfacelang)))
html += '<option value="showmore">More...</option>'
html += '</select></span></form>'
return html | Prints the html block of the OMW Search form and
a dropdown for a list of available languages.
The interface language is selected by default. | www/cgi-bin/ntumc_webkit.py | search_form | bond-lab/IMI | 0 | python | @staticmethod
def search_form(omwcgi='wn-grid.cgi', lemma=, langlist=[], interfacelang='eng', langstring='Lang: ', lang2='eng', resize=100):
'Prints the html block of the OMW Search form and\n a dropdown for a list of available languages.\n The interface language is selected by default.'
html = ('<form method="post" style="display: inline-block"\n title="search for a word β \'word\'\nor pattern β \'[wW]ord*\' (using sqlite GLOB)\nor synset-id β \'06286395-n\'\nor a pattern in a definition β \'def::*word*\' (using sqlite GLOB)"\n id="newquery" action="%s">\n <span style="font-size: %s%%">\n <input style="font-size: %s%%" \n type="text" name="lemma" value="%s" \n size=8 maxlength=50>\n\n <button class="small"> <a href="javascript:{}"\n onclick="document.getElementById(\'newquery\').submit(); \n return false;"><span title="Search">\n <span style="color: #4D99E0;"><i class=\'icon-search\'></i>\n </span></span></a></button>\n \n <strong>%s</strong><select name="lang" size="1" \n style="font-size: %s%%"\n onchange="if(this.value == \'showmore\') \n toggle_visibility(\'langselect\');">\n ' % (omwcgi, resize, resize, lemma, langstring, resize))
for l in langlist:
if (interfacelang == l):
html += ("<option value ='%s' selected>%s\n " % (l, omwlang.trans(l, interfacelang)))
else:
html += ("<option value ='%s'>%s\n " % (l, omwlang.trans(l, interfacelang)))
html += '<option value="showmore">More...</option>'
html += ('</select><select name="lang2" style="font-size: %s%%"\n title="backoff language" size="1" \n onchange="if(this.value == \'showmore\') \n toggle_visibility(\'langselect\');">' % resize)
for l in langlist:
if (l == lang2):
html += ("<option value ='%s' selected>%s\n " % (l, omwlang.trans(l, interfacelang)))
else:
html += ("<option value ='%s'>%s\n " % (l, omwlang.trans(l, interfacelang)))
html += '<option value="showmore">More...</option>'
html += '</select></span></form>'
return html | @staticmethod
def search_form(omwcgi='wn-grid.cgi', lemma=, langlist=[], interfacelang='eng', langstring='Lang: ', lang2='eng', resize=100):
'Prints the html block of the OMW Search form and\n a dropdown for a list of available languages.\n The interface language is selected by default.'
html = ('<form method="post" style="display: inline-block"\n title="search for a word β \'word\'\nor pattern β \'[wW]ord*\' (using sqlite GLOB)\nor synset-id β \'06286395-n\'\nor a pattern in a definition β \'def::*word*\' (using sqlite GLOB)"\n id="newquery" action="%s">\n <span style="font-size: %s%%">\n <input style="font-size: %s%%" \n type="text" name="lemma" value="%s" \n size=8 maxlength=50>\n\n <button class="small"> <a href="javascript:{}"\n onclick="document.getElementById(\'newquery\').submit(); \n return false;"><span title="Search">\n <span style="color: #4D99E0;"><i class=\'icon-search\'></i>\n </span></span></a></button>\n \n <strong>%s</strong><select name="lang" size="1" \n style="font-size: %s%%"\n onchange="if(this.value == \'showmore\') \n toggle_visibility(\'langselect\');">\n ' % (omwcgi, resize, resize, lemma, langstring, resize))
for l in langlist:
if (interfacelang == l):
html += ("<option value ='%s' selected>%s\n " % (l, omwlang.trans(l, interfacelang)))
else:
html += ("<option value ='%s'>%s\n " % (l, omwlang.trans(l, interfacelang)))
html += '<option value="showmore">More...</option>'
html += ('</select><select name="lang2" style="font-size: %s%%"\n title="backoff language" size="1" \n onchange="if(this.value == \'showmore\') \n toggle_visibility(\'langselect\');">' % resize)
for l in langlist:
if (l == lang2):
html += ("<option value ='%s' selected>%s\n " % (l, omwlang.trans(l, interfacelang)))
else:
html += ("<option value ='%s'>%s\n " % (l, omwlang.trans(l, interfacelang)))
html += '<option value="showmore">More...</option>'
html += '</select></span></form>'
return html<|docstring|>Prints the html block of the OMW Search form and
a dropdown for a list of available languages.
The interface language is selected by default.<|endoftext|> |
83021537a635256958d27ae49abfe8c3255d5eab8c1c1c293939f8ff6ad651c0 | @staticmethod
def language_selection(langselect, langlist=[], omwcgi='wn-grid.cgi', interfacelang='eng'):
'Prints the html block of a hidden language selection\n with a list of all available languages. This is used to \n restrict the number of languages displayed.\n The interface language is selected by default.'
html = '<a onclick="toggle_visibility(\'langselect\');">\n <i class="icon-wrench"></i> Preferences</a>'
html += '<div id="langselect" style="display: none">'
html += '<span style="color: #4D99E0;display: inline-block; \n float:right">'
html += '\n <a href="javascript:{}"\n onclick="document.getElementById(\'langselection\').submit(); \n return false;"><span title="Update Language Selection">\n Update Language Selection\n </span></a></span><br>'
html += '<span style="color: #4D99E0;display: inline-block; \n float:right">'
html += '<input type="checkbox" \n onclick="for(c in document.getElementsByName(\'langselect[]\')) \n document.getElementsByName(\'langselect[]\').item(c).checked \n = this.checked";> Select All/None</span>'
html += ('<h6>Language Selection</h6>\n <form method="post" action="%s" \n id="langselection">' % omwcgi)
html += '<table>'
for (i, l) in enumerate(sorted(langlist)):
if ((i % 5) == 0):
html += '</tr><tr>'
if (l in langselect):
html += ('<td><input type="checkbox" \n name="langselect[]" value="%s" checked> %s</td>\n ' % (l, omwlang.trans(l, interfacelang)))
else:
html += ('<td><input type="checkbox" \n name="langselect[]" value="%s"> %s</td>\n ' % (l, omwlang.trans(l, interfacelang)))
html += '</table>'
html += '<a href="javascript:{}"\n onclick="document.getElementById(\'langselection\').submit(); \n return false;"><span title="Update Language Selection"\n style="display: inline-block; float:right">\n <span style="color: #4D99E0;">Update Language Selection\n </span></span></a>'
html += '</form>'
html += '</div>'
return html | Prints the html block of a hidden language selection
with a list of all available languages. This is used to
restrict the number of languages displayed.
The interface language is selected by default. | www/cgi-bin/ntumc_webkit.py | language_selection | bond-lab/IMI | 0 | python | @staticmethod
def language_selection(langselect, langlist=[], omwcgi='wn-grid.cgi', interfacelang='eng'):
'Prints the html block of a hidden language selection\n with a list of all available languages. This is used to \n restrict the number of languages displayed.\n The interface language is selected by default.'
html = '<a onclick="toggle_visibility(\'langselect\');">\n <i class="icon-wrench"></i> Preferences</a>'
html += '<div id="langselect" style="display: none">'
html += '<span style="color: #4D99E0;display: inline-block; \n float:right">'
html += '\n <a href="javascript:{}"\n onclick="document.getElementById(\'langselection\').submit(); \n return false;"><span title="Update Language Selection">\n Update Language Selection\n </span></a></span><br>'
html += '<span style="color: #4D99E0;display: inline-block; \n float:right">'
html += '<input type="checkbox" \n onclick="for(c in document.getElementsByName(\'langselect[]\')) \n document.getElementsByName(\'langselect[]\').item(c).checked \n = this.checked";> Select All/None</span>'
html += ('<h6>Language Selection</h6>\n <form method="post" action="%s" \n id="langselection">' % omwcgi)
html += '<table>'
for (i, l) in enumerate(sorted(langlist)):
if ((i % 5) == 0):
html += '</tr><tr>'
if (l in langselect):
html += ('<td><input type="checkbox" \n name="langselect[]" value="%s" checked> %s</td>\n ' % (l, omwlang.trans(l, interfacelang)))
else:
html += ('<td><input type="checkbox" \n name="langselect[]" value="%s"> %s</td>\n ' % (l, omwlang.trans(l, interfacelang)))
html += '</table>'
html += '<a href="javascript:{}"\n onclick="document.getElementById(\'langselection\').submit(); \n return false;"><span title="Update Language Selection"\n style="display: inline-block; float:right">\n <span style="color: #4D99E0;">Update Language Selection\n </span></span></a>'
html += '</form>'
html += '</div>'
return html | @staticmethod
def language_selection(langselect, langlist=[], omwcgi='wn-grid.cgi', interfacelang='eng'):
'Prints the html block of a hidden language selection\n with a list of all available languages. This is used to \n restrict the number of languages displayed.\n The interface language is selected by default.'
html = '<a onclick="toggle_visibility(\'langselect\');">\n <i class="icon-wrench"></i> Preferences</a>'
html += '<div id="langselect" style="display: none">'
html += '<span style="color: #4D99E0;display: inline-block; \n float:right">'
html += '\n <a href="javascript:{}"\n onclick="document.getElementById(\'langselection\').submit(); \n return false;"><span title="Update Language Selection">\n Update Language Selection\n </span></a></span><br>'
html += '<span style="color: #4D99E0;display: inline-block; \n float:right">'
html += '<input type="checkbox" \n onclick="for(c in document.getElementsByName(\'langselect[]\')) \n document.getElementsByName(\'langselect[]\').item(c).checked \n = this.checked";> Select All/None</span>'
html += ('<h6>Language Selection</h6>\n <form method="post" action="%s" \n id="langselection">' % omwcgi)
html += '<table>'
for (i, l) in enumerate(sorted(langlist)):
if ((i % 5) == 0):
html += '</tr><tr>'
if (l in langselect):
html += ('<td><input type="checkbox" \n name="langselect[]" value="%s" checked> %s</td>\n ' % (l, omwlang.trans(l, interfacelang)))
else:
html += ('<td><input type="checkbox" \n name="langselect[]" value="%s"> %s</td>\n ' % (l, omwlang.trans(l, interfacelang)))
html += '</table>'
html += '<a href="javascript:{}"\n onclick="document.getElementById(\'langselection\').submit(); \n return false;"><span title="Update Language Selection"\n style="display: inline-block; float:right">\n <span style="color: #4D99E0;">Update Language Selection\n </span></span></a>'
html += '</form>'
html += '</div>'
return html<|docstring|>Prints the html block of a hidden language selection
with a list of all available languages. This is used to
restrict the number of languages displayed.
The interface language is selected by default.<|endoftext|> |
b38014f6418c7d482fe0a62a328f10b25a7e96e512604b516bcdb0a0f1eae92d | @staticmethod
def show_change_user_bttn(usrname, cgi='login.cgi?action=logout&target=tag-lexs.cgi'):
'Prints the user status message, along \n With a button to change it.\n The default cgi to refresh to is tag-lexs, \n but it can be changed.'
html = ''
if usrname:
html += ('<form method=post target="_parent" \n style="display: inline-block" action="%s">\n <strong>Current user:</strong>\n <font color="#3EA055">%s</font> \n <input type ="hidden" name="usrname_cgi" value = "unknown">\n <input type = "submit" value = "Change"></form>\n ' % (cgi, usrname))
else:
html += ('<form method = post target = "_parent" \n style="display: inline-block" action = "%s">\n <strong>Current user:</strong>\n <font color="#CC0000">unknown</font>\n <input type ="hidden" name="usrname_cgi" value = "unknown">\n <input type = "submit" value = "Change"></form>\n ' % cgi)
return html | Prints the user status message, along
With a button to change it.
The default cgi to refresh to is tag-lexs,
but it can be changed. | www/cgi-bin/ntumc_webkit.py | show_change_user_bttn | bond-lab/IMI | 0 | python | @staticmethod
def show_change_user_bttn(usrname, cgi='login.cgi?action=logout&target=tag-lexs.cgi'):
'Prints the user status message, along \n With a button to change it.\n The default cgi to refresh to is tag-lexs, \n but it can be changed.'
html =
if usrname:
html += ('<form method=post target="_parent" \n style="display: inline-block" action="%s">\n <strong>Current user:</strong>\n <font color="#3EA055">%s</font> \n <input type ="hidden" name="usrname_cgi" value = "unknown">\n <input type = "submit" value = "Change"></form>\n ' % (cgi, usrname))
else:
html += ('<form method = post target = "_parent" \n style="display: inline-block" action = "%s">\n <strong>Current user:</strong>\n <font color="#CC0000">unknown</font>\n <input type ="hidden" name="usrname_cgi" value = "unknown">\n <input type = "submit" value = "Change"></form>\n ' % cgi)
return html | @staticmethod
def show_change_user_bttn(usrname, cgi='login.cgi?action=logout&target=tag-lexs.cgi'):
'Prints the user status message, along \n With a button to change it.\n The default cgi to refresh to is tag-lexs, \n but it can be changed.'
html =
if usrname:
html += ('<form method=post target="_parent" \n style="display: inline-block" action="%s">\n <strong>Current user:</strong>\n <font color="#3EA055">%s</font> \n <input type ="hidden" name="usrname_cgi" value = "unknown">\n <input type = "submit" value = "Change"></form>\n ' % (cgi, usrname))
else:
html += ('<form method = post target = "_parent" \n style="display: inline-block" action = "%s">\n <strong>Current user:</strong>\n <font color="#CC0000">unknown</font>\n <input type ="hidden" name="usrname_cgi" value = "unknown">\n <input type = "submit" value = "Change"></form>\n ' % cgi)
return html<|docstring|>Prints the user status message, along
With a button to change it.
The default cgi to refresh to is tag-lexs,
but it can be changed.<|endoftext|> |
2c29a9be32ea50e0be7a5c423d0d5454eabdb097a4ab973d5fd958cf257c3640 | @staticmethod
def status_bar(user, position='right', message='', text=False):
'Prints a floating status bar (in the top right corner).\n This will display an Info Button, the User Status, and \n a Home button.'
html = ''
dashboardcgi = 'dashboard.cgi'
html += ('<span style="display: inline-block; float:%s">\n <ul class="button-bar">' % position)
if (user in valid_usernames):
html += ('<li><a disabled><span style="color: #4D99E0;">\n <i class="icon-user"></i>%s</a></span></li> ' % user)
else:
html += '<li><a title="Invalid User" disabled><span style="color: #bc5847;">\n <i class="icon-user"></i></a></span></li> '
html += f'''<li><a title='Go to Dashboard' href='{dashboardcgi}'><span style="color: #4D99E0;">
<i class="icon-home"></i></a></span></li>'''
html += '</ul>'
html += message
html += '</span>'
if text:
html = f'''<p><a href='{dashboardcgi}'>Go to Dashboard ({user})</a>
'''
return html | Prints a floating status bar (in the top right corner).
This will display an Info Button, the User Status, and
a Home button. | www/cgi-bin/ntumc_webkit.py | status_bar | bond-lab/IMI | 0 | python | @staticmethod
def status_bar(user, position='right', message=, text=False):
'Prints a floating status bar (in the top right corner).\n This will display an Info Button, the User Status, and \n a Home button.'
html =
dashboardcgi = 'dashboard.cgi'
html += ('<span style="display: inline-block; float:%s">\n <ul class="button-bar">' % position)
if (user in valid_usernames):
html += ('<li><a disabled><span style="color: #4D99E0;">\n <i class="icon-user"></i>%s</a></span></li> ' % user)
else:
html += '<li><a title="Invalid User" disabled><span style="color: #bc5847;">\n <i class="icon-user"></i></a></span></li> '
html += f'<li><a title='Go to Dashboard' href='{dashboardcgi}'><span style="color: #4D99E0;">
<i class="icon-home"></i></a></span></li>'
html += '</ul>'
html += message
html += '</span>'
if text:
html = f'<p><a href='{dashboardcgi}'>Go to Dashboard ({user})</a>
'
return html | @staticmethod
def status_bar(user, position='right', message=, text=False):
'Prints a floating status bar (in the top right corner).\n This will display an Info Button, the User Status, and \n a Home button.'
html =
dashboardcgi = 'dashboard.cgi'
html += ('<span style="display: inline-block; float:%s">\n <ul class="button-bar">' % position)
if (user in valid_usernames):
html += ('<li><a disabled><span style="color: #4D99E0;">\n <i class="icon-user"></i>%s</a></span></li> ' % user)
else:
html += '<li><a title="Invalid User" disabled><span style="color: #bc5847;">\n <i class="icon-user"></i></a></span></li> '
html += f'<li><a title='Go to Dashboard' href='{dashboardcgi}'><span style="color: #4D99E0;">
<i class="icon-home"></i></a></span></li>'
html += '</ul>'
html += message
html += '</span>'
if text:
html = f'<p><a href='{dashboardcgi}'>Go to Dashboard ({user})</a>
'
return html<|docstring|>Prints a floating status bar (in the top right corner).
This will display an Info Button, the User Status, and
a Home button.<|endoftext|> |
23767799ed006b33c0a73b694adf0d8d4afbb7481bbf5bdb786a202f02be398e | @staticmethod
def ne_bttn(string2print='<i class="icon-plus"></i>NE'):
'Prints the Add New Named Entity button,\n taking as argument a username and an optional \n string to be printed on the button.'
tooltip = 'Add a new Named Entity (quick entry).'
addnecgi = 'addne.cgi'
html = ('<form method= "post" style="display: inline-block; \n margin: 0px; padding: 0px;" id="newNE"\n action="%s"><a href="javascript:{}" style="text-decoration: none;"\n onclick="document.getElementById(\'newNE\').submit(); \n return false;"><span class=\'tooltip mainColor\' title="%s">\n %s</span></a></form>\n ' % (addnecgi, tooltip, string2print))
return html | Prints the Add New Named Entity button,
taking as argument a username and an optional
string to be printed on the button. | www/cgi-bin/ntumc_webkit.py | ne_bttn | bond-lab/IMI | 0 | python | @staticmethod
def ne_bttn(string2print='<i class="icon-plus"></i>NE'):
'Prints the Add New Named Entity button,\n taking as argument a username and an optional \n string to be printed on the button.'
tooltip = 'Add a new Named Entity (quick entry).'
addnecgi = 'addne.cgi'
html = ('<form method= "post" style="display: inline-block; \n margin: 0px; padding: 0px;" id="newNE"\n action="%s"><a href="javascript:{}" style="text-decoration: none;"\n onclick="document.getElementById(\'newNE\').submit(); \n return false;"><span class=\'tooltip mainColor\' title="%s">\n %s</span></a></form>\n ' % (addnecgi, tooltip, string2print))
return html | @staticmethod
def ne_bttn(string2print='<i class="icon-plus"></i>NE'):
'Prints the Add New Named Entity button,\n taking as argument a username and an optional \n string to be printed on the button.'
tooltip = 'Add a new Named Entity (quick entry).'
addnecgi = 'addne.cgi'
html = ('<form method= "post" style="display: inline-block; \n margin: 0px; padding: 0px;" id="newNE"\n action="%s"><a href="javascript:{}" style="text-decoration: none;"\n onclick="document.getElementById(\'newNE\').submit(); \n return false;"><span class=\'tooltip mainColor\' title="%s">\n %s</span></a></form>\n ' % (addnecgi, tooltip, string2print))
return html<|docstring|>Prints the Add New Named Entity button,
taking as argument a username and an optional
string to be printed on the button.<|endoftext|> |
da77b925ac173845b23b9820e36ce513c353aef612d820158de36dc5865f492e | @staticmethod
def hiderow_bttn(rowid, s="<i class='icon-eye-close'></i>"):
'Prints the Hide row button,\n taking as argument the rowid and an optional \n string to be printed on the button.'
tooltip = f'Hide the row for {rowid[3:]}.'
html = f'''<a href="javascript:{{}}"
onclick="togglecol('{rowid}')">
<span title="{tooltip}" style="color:#4D99E0;">{s}</a>
'''
return html | Prints the Hide row button,
taking as argument the rowid and an optional
string to be printed on the button. | www/cgi-bin/ntumc_webkit.py | hiderow_bttn | bond-lab/IMI | 0 | python | @staticmethod
def hiderow_bttn(rowid, s="<i class='icon-eye-close'></i>"):
'Prints the Hide row button,\n taking as argument the rowid and an optional \n string to be printed on the button.'
tooltip = f'Hide the row for {rowid[3:]}.'
html = f'<a href="javascript:{{}}"
onclick="togglecol('{rowid}')">
<span title="{tooltip}" style="color:#4D99E0;">{s}</a>
'
return html | @staticmethod
def hiderow_bttn(rowid, s="<i class='icon-eye-close'></i>"):
'Prints the Hide row button,\n taking as argument the rowid and an optional \n string to be printed on the button.'
tooltip = f'Hide the row for {rowid[3:]}.'
html = f'<a href="javascript:{{}}"
onclick="togglecol('{rowid}')">
<span title="{tooltip}" style="color:#4D99E0;">{s}</a>
'
return html<|docstring|>Prints the Hide row button,
taking as argument the rowid and an optional
string to be printed on the button.<|endoftext|> |
819d59ddabdd828c6a5469d87373b63b332d9a96caa84f56172bc1bae306c3aa | @staticmethod
def hideRowsByClass_bttn(c, s):
'Prints a button that hides all rows with specific POS class'
string2print = ("<i class='icon-eye-close'></i>%s" % s)
tooltip = ('Hide/Show rows for %s ' % c)
html = ('<a href=\'javascript:{}\' class=\'tooltip-bottom\' title=\'%s\'\n onclick="toggleRowsByClass(\'%s\');"\n style="text-decoration: none;">%s</a>\n ' % (tooltip, c, string2print))
return html | Prints a button that hides all rows with specific POS class | www/cgi-bin/ntumc_webkit.py | hideRowsByClass_bttn | bond-lab/IMI | 0 | python | @staticmethod
def hideRowsByClass_bttn(c, s):
string2print = ("<i class='icon-eye-close'></i>%s" % s)
tooltip = ('Hide/Show rows for %s ' % c)
html = ('<a href=\'javascript:{}\' class=\'tooltip-bottom\' title=\'%s\'\n onclick="toggleRowsByClass(\'%s\');"\n style="text-decoration: none;">%s</a>\n ' % (tooltip, c, string2print))
return html | @staticmethod
def hideRowsByClass_bttn(c, s):
string2print = ("<i class='icon-eye-close'></i>%s" % s)
tooltip = ('Hide/Show rows for %s ' % c)
html = ('<a href=\'javascript:{}\' class=\'tooltip-bottom\' title=\'%s\'\n onclick="toggleRowsByClass(\'%s\');"\n style="text-decoration: none;">%s</a>\n ' % (tooltip, c, string2print))
return html<|docstring|>Prints a button that hides all rows with specific POS class<|endoftext|> |
863d7b3a4df1430af285d720e7d404fefc2a317529a5f04663f0e841f62103b8 | @staticmethod
def showOnlyRowsByClass_bttn(c, s):
'Prints a button that shows only rows with a specific POS class'
string2print = ('%s' % s)
tooltip = ('Show only rows for %s ' % c)
html = ('<a href=\'javascript:{}\' class=\'tooltip-bottom\' title=\'%s\'\n onclick="showOnlyRowsByClass(\'%s\');" \n style="text-decoration: none;">%s</a>\n ' % (tooltip, c, string2print))
return html | Prints a button that shows only rows with a specific POS class | www/cgi-bin/ntumc_webkit.py | showOnlyRowsByClass_bttn | bond-lab/IMI | 0 | python | @staticmethod
def showOnlyRowsByClass_bttn(c, s):
string2print = ('%s' % s)
tooltip = ('Show only rows for %s ' % c)
html = ('<a href=\'javascript:{}\' class=\'tooltip-bottom\' title=\'%s\'\n onclick="showOnlyRowsByClass(\'%s\');" \n style="text-decoration: none;">%s</a>\n ' % (tooltip, c, string2print))
return html | @staticmethod
def showOnlyRowsByClass_bttn(c, s):
string2print = ('%s' % s)
tooltip = ('Show only rows for %s ' % c)
html = ('<a href=\'javascript:{}\' class=\'tooltip-bottom\' title=\'%s\'\n onclick="showOnlyRowsByClass(\'%s\');" \n style="text-decoration: none;">%s</a>\n ' % (tooltip, c, string2print))
return html<|docstring|>Prints a button that shows only rows with a specific POS class<|endoftext|> |
7fc37b3ccb55442f16ef3bd44ec6c2229f9354bc02cfc6678cdbfcd30cef7000 | @staticmethod
def showallunder_bttn(elementid, s):
'Prints the Show All button,\n taking as argument the element id that it on top of every\n other node to be displayed and an optional \n string to be printed on the button.'
string2print = ("<i class='icon-eye-open'></i> %s" % s)
tooltip = 'Show hidden rows.'
html = ('<a href="javascript:{}" class=\'tooltip-bottom\' \n onclick="showallunder(\'%s\')" title="%s"\n style="text-decoration: none;">%s</a>\n ' % (elementid, tooltip, string2print))
return html | Prints the Show All button,
taking as argument the element id that it on top of every
other node to be displayed and an optional
string to be printed on the button. | www/cgi-bin/ntumc_webkit.py | showallunder_bttn | bond-lab/IMI | 0 | python | @staticmethod
def showallunder_bttn(elementid, s):
'Prints the Show All button,\n taking as argument the element id that it on top of every\n other node to be displayed and an optional \n string to be printed on the button.'
string2print = ("<i class='icon-eye-open'></i> %s" % s)
tooltip = 'Show hidden rows.'
html = ('<a href="javascript:{}" class=\'tooltip-bottom\' \n onclick="showallunder(\'%s\')" title="%s"\n style="text-decoration: none;">%s</a>\n ' % (elementid, tooltip, string2print))
return html | @staticmethod
def showallunder_bttn(elementid, s):
'Prints the Show All button,\n taking as argument the element id that it on top of every\n other node to be displayed and an optional \n string to be printed on the button.'
string2print = ("<i class='icon-eye-open'></i> %s" % s)
tooltip = 'Show hidden rows.'
html = ('<a href="javascript:{}" class=\'tooltip-bottom\' \n onclick="showallunder(\'%s\')" title="%s"\n style="text-decoration: none;">%s</a>\n ' % (elementid, tooltip, string2print))
return html<|docstring|>Prints the Show All button,
taking as argument the element id that it on top of every
other node to be displayed and an optional
string to be printed on the button.<|endoftext|> |
13592f7ebe5b4a0f8a27c9c1e6a7dae60ad75a5e7e8a4832ba699fdc1cf3c3b5 | @staticmethod
def newdef_bttn(synset='', wndb='wn-ntumc', string2print='<i class="icon-plus-sign"></i> '):
'Prints the Add New Definition button.'
tooltip = 'Add a new definition to Wordnet.'
addnewcgi = 'wn-add-def.cgi'
html = ('<a class="largefancybox fancybox.iframe" \n href="%s?synset=%s&wndb=%s"><span title="%s"\n style="color:white;">\n <i class=\'icon-plus-sign\'></i>\n </span></a>' % (addnewcgi, synset, wndb, tooltip))
return html | Prints the Add New Definition button. | www/cgi-bin/ntumc_webkit.py | newdef_bttn | bond-lab/IMI | 0 | python | @staticmethod
def newdef_bttn(synset=, wndb='wn-ntumc', string2print='<i class="icon-plus-sign"></i> '):
tooltip = 'Add a new definition to Wordnet.'
addnewcgi = 'wn-add-def.cgi'
html = ('<a class="largefancybox fancybox.iframe" \n href="%s?synset=%s&wndb=%s"><span title="%s"\n style="color:white;">\n <i class=\'icon-plus-sign\'></i>\n </span></a>' % (addnewcgi, synset, wndb, tooltip))
return html | @staticmethod
def newdef_bttn(synset=, wndb='wn-ntumc', string2print='<i class="icon-plus-sign"></i> '):
tooltip = 'Add a new definition to Wordnet.'
addnewcgi = 'wn-add-def.cgi'
html = ('<a class="largefancybox fancybox.iframe" \n href="%s?synset=%s&wndb=%s"><span title="%s"\n style="color:white;">\n <i class=\'icon-plus-sign\'></i>\n </span></a>' % (addnewcgi, synset, wndb, tooltip))
return html<|docstring|>Prints the Add New Definition button.<|endoftext|> |
37ea5b75f8c43a7fb1affd4af4944af6e659e718c6d629093e812b8dcecd64a7 | @staticmethod
def newsynset_bttn(synset='', string2print='<i class="icon-plus-sign"></i> '):
'Prints the Add New Synset button,\n taking as argument a username, an optional related synset, \n and an optional string to be printed on the button.'
tooltip = ''
if (synset == ''):
tooltip = 'Add a new synset to Wordnet.'
else:
tooltip = ('Add a new synset linked to %s.' % synset)
addnewcgi = 'addnew.cgi'
html = ('<form method="post" style="display: inline-block; \n margin: 0px; padding: 0px;" id="newss%s" action="%s">\n <input type="hidden" name="synset" value="%s">\n <a href="javascript:{}" style="text-decoration:none;"\n onclick="document.getElementById(\'newss%s\').submit(); \n return false;"><span class=\'tooltip mainColor\' title="%s">\n %s</span></a></form>' % (synset, addnewcgi, synset, synset, tooltip, string2print))
return html | Prints the Add New Synset button,
taking as argument a username, an optional related synset,
and an optional string to be printed on the button. | www/cgi-bin/ntumc_webkit.py | newsynset_bttn | bond-lab/IMI | 0 | python | @staticmethod
def newsynset_bttn(synset=, string2print='<i class="icon-plus-sign"></i> '):
'Prints the Add New Synset button,\n taking as argument a username, an optional related synset, \n and an optional string to be printed on the button.'
tooltip =
if (synset == ):
tooltip = 'Add a new synset to Wordnet.'
else:
tooltip = ('Add a new synset linked to %s.' % synset)
addnewcgi = 'addnew.cgi'
html = ('<form method="post" style="display: inline-block; \n margin: 0px; padding: 0px;" id="newss%s" action="%s">\n <input type="hidden" name="synset" value="%s">\n <a href="javascript:{}" style="text-decoration:none;"\n onclick="document.getElementById(\'newss%s\').submit(); \n return false;"><span class=\'tooltip mainColor\' title="%s">\n %s</span></a></form>' % (synset, addnewcgi, synset, synset, tooltip, string2print))
return html | @staticmethod
def newsynset_bttn(synset=, string2print='<i class="icon-plus-sign"></i> '):
'Prints the Add New Synset button,\n taking as argument a username, an optional related synset, \n and an optional string to be printed on the button.'
tooltip =
if (synset == ):
tooltip = 'Add a new synset to Wordnet.'
else:
tooltip = ('Add a new synset linked to %s.' % synset)
addnewcgi = 'addnew.cgi'
html = ('<form method="post" style="display: inline-block; \n margin: 0px; padding: 0px;" id="newss%s" action="%s">\n <input type="hidden" name="synset" value="%s">\n <a href="javascript:{}" style="text-decoration:none;"\n onclick="document.getElementById(\'newss%s\').submit(); \n return false;"><span class=\'tooltip mainColor\' title="%s">\n %s</span></a></form>' % (synset, addnewcgi, synset, synset, tooltip, string2print))
return html<|docstring|>Prints the Add New Synset button,
taking as argument a username, an optional related synset,
and an optional string to be printed on the button.<|endoftext|> |
72de5296638d234e037bc59ee9d58c635fa418fcbda933aaaabc908c3d19da70 | @staticmethod
def editsynset_bttn(usrname, synset, string2print='<i class="icon-edit"></i>'):
'Prints the Edit Synset button,\n taking as argument a username, an optional related synset, \n and an optional string to be printed on the button.'
tooltip = ('Edit %s (add lemmas, defs, etc.)' % synset)
editcgi = 'annot-gridx.cgi'
html = ('<form method= "post" style="display: inline-block; \n margin: 0px; padding: 0px;" id="editss%s"\n action="%s?usrname=%s&synset=%s"><a href="javascript:{}"\n onclick="document.getElementById(\'editss%s\').submit(); \n return false;">\n <span title="%s">%s</span></a>\n </form>' % (synset, editcgi, usrname, synset, synset, tooltip, string2print))
return html | Prints the Edit Synset button,
taking as argument a username, an optional related synset,
and an optional string to be printed on the button. | www/cgi-bin/ntumc_webkit.py | editsynset_bttn | bond-lab/IMI | 0 | python | @staticmethod
def editsynset_bttn(usrname, synset, string2print='<i class="icon-edit"></i>'):
'Prints the Edit Synset button,\n taking as argument a username, an optional related synset, \n and an optional string to be printed on the button.'
tooltip = ('Edit %s (add lemmas, defs, etc.)' % synset)
editcgi = 'annot-gridx.cgi'
html = ('<form method= "post" style="display: inline-block; \n margin: 0px; padding: 0px;" id="editss%s"\n action="%s?usrname=%s&synset=%s"><a href="javascript:{}"\n onclick="document.getElementById(\'editss%s\').submit(); \n return false;">\n <span title="%s">%s</span></a>\n </form>' % (synset, editcgi, usrname, synset, synset, tooltip, string2print))
return html | @staticmethod
def editsynset_bttn(usrname, synset, string2print='<i class="icon-edit"></i>'):
'Prints the Edit Synset button,\n taking as argument a username, an optional related synset, \n and an optional string to be printed on the button.'
tooltip = ('Edit %s (add lemmas, defs, etc.)' % synset)
editcgi = 'annot-gridx.cgi'
html = ('<form method= "post" style="display: inline-block; \n margin: 0px; padding: 0px;" id="editss%s"\n action="%s?usrname=%s&synset=%s"><a href="javascript:{}"\n onclick="document.getElementById(\'editss%s\').submit(); \n return false;">\n <span title="%s">%s</span></a>\n </form>' % (synset, editcgi, usrname, synset, synset, tooltip, string2print))
return html<|docstring|>Prints the Edit Synset button,
taking as argument a username, an optional related synset,
and an optional string to be printed on the button.<|endoftext|> |
7484396e0ab27ef81aadba71867a84212dbceb4b5fca0654d88846c18849cc8a | @staticmethod
def multidict_bttn(lang1, lemma, string2print='<i class="icon-book"></i> '):
'Prints the Multidict button.\n Must have a language and a lemma as arguments. \n The optional string2print will replace the value of the button'
tooltip = ("Search '%s' in multiple dictionaries" % lemma)
multidictcgi = 'multidict.cgi'
html = ('<form method= "post" style="display: inline-block; \n margin: 0px; padding: 0px;" id="multidict"\n target="_blank" action="%s?lg1=%s&lemma1=%s">\n <a href="javascript:{}" style="text-decoration: none;"\n onclick="document.getElementById(\'multidict\').submit(); \n return false;"><span title="%s" \n style="color:#4D99E0;">%s</span></a>\n </form>' % (multidictcgi, lang1, lemma, tooltip, string2print))
return html | Prints the Multidict button.
Must have a language and a lemma as arguments.
The optional string2print will replace the value of the button | www/cgi-bin/ntumc_webkit.py | multidict_bttn | bond-lab/IMI | 0 | python | @staticmethod
def multidict_bttn(lang1, lemma, string2print='<i class="icon-book"></i> '):
'Prints the Multidict button.\n Must have a language and a lemma as arguments. \n The optional string2print will replace the value of the button'
tooltip = ("Search '%s' in multiple dictionaries" % lemma)
multidictcgi = 'multidict.cgi'
html = ('<form method= "post" style="display: inline-block; \n margin: 0px; padding: 0px;" id="multidict"\n target="_blank" action="%s?lg1=%s&lemma1=%s">\n <a href="javascript:{}" style="text-decoration: none;"\n onclick="document.getElementById(\'multidict\').submit(); \n return false;"><span title="%s" \n style="color:#4D99E0;">%s</span></a>\n </form>' % (multidictcgi, lang1, lemma, tooltip, string2print))
return html | @staticmethod
def multidict_bttn(lang1, lemma, string2print='<i class="icon-book"></i> '):
'Prints the Multidict button.\n Must have a language and a lemma as arguments. \n The optional string2print will replace the value of the button'
tooltip = ("Search '%s' in multiple dictionaries" % lemma)
multidictcgi = 'multidict.cgi'
html = ('<form method= "post" style="display: inline-block; \n margin: 0px; padding: 0px;" id="multidict"\n target="_blank" action="%s?lg1=%s&lemma1=%s">\n <a href="javascript:{}" style="text-decoration: none;"\n onclick="document.getElementById(\'multidict\').submit(); \n return false;"><span title="%s" \n style="color:#4D99E0;">%s</span></a>\n </form>' % (multidictcgi, lang1, lemma, tooltip, string2print))
return html<|docstring|>Prints the Multidict button.
Must have a language and a lemma as arguments.
The optional string2print will replace the value of the button<|endoftext|> |
ee3651150f68789a72fb7dc6cd438e13533a41469564d1120d8130ecd768b21c | @staticmethod
def ntumc_tagdoc(short=False):
'\n link to the tagging documentation\n '
if short:
anchor = 'Tag Doc'
else:
anchor = 'Tagging Documentation'
html = f"<a title = 'Tagging Documentation' href='https://bond-lab.github.io/IMI/tagdoc.html'>{anchor}</a>"
return html | link to the tagging documentation | www/cgi-bin/ntumc_webkit.py | ntumc_tagdoc | bond-lab/IMI | 0 | python | @staticmethod
def ntumc_tagdoc(short=False):
'\n \n '
if short:
anchor = 'Tag Doc'
else:
anchor = 'Tagging Documentation'
html = f"<a title = 'Tagging Documentation' href='https://bond-lab.github.io/IMI/tagdoc.html'>{anchor}</a>"
return html | @staticmethod
def ntumc_tagdoc(short=False):
'\n \n '
if short:
anchor = 'Tag Doc'
else:
anchor = 'Tagging Documentation'
html = f"<a title = 'Tagging Documentation' href='https://bond-lab.github.io/IMI/tagdoc.html'>{anchor}</a>"
return html<|docstring|>link to the tagging documentation<|endoftext|> |
b3b568b8262a8fb32cf33d97f6f8dfbb4aaa3d092a886f6eaa94d3c2ca91552f | @staticmethod
def show_sid_bttn(corpus, sid, lemma):
'Prints a sid: clickable to jump to context'
corpus2 = 'eng'
window = 6
html = f'''<a class='sid largefancybox fancybox.iframe'
title='show more context'
href='show-sent.cgi?corpus={corpus}&corpus2={corpus2}&sid={sid}&window={window}'>{sid}</a>
<a title = 'fix corpus' href='fix-corpus.cgi?corpus={corpus}&sid_edit={sid}'>*</a>'''
return html | Prints a sid: clickable to jump to context | www/cgi-bin/ntumc_webkit.py | show_sid_bttn | bond-lab/IMI | 0 | python | @staticmethod
def show_sid_bttn(corpus, sid, lemma):
corpus2 = 'eng'
window = 6
html = f'<a class='sid largefancybox fancybox.iframe'
title='show more context'
href='show-sent.cgi?corpus={corpus}&corpus2={corpus2}&sid={sid}&window={window}'>{sid}</a>
<a title = 'fix corpus' href='fix-corpus.cgi?corpus={corpus}&sid_edit={sid}'>*</a>'
return html | @staticmethod
def show_sid_bttn(corpus, sid, lemma):
corpus2 = 'eng'
window = 6
html = f'<a class='sid largefancybox fancybox.iframe'
title='show more context'
href='show-sent.cgi?corpus={corpus}&corpus2={corpus2}&sid={sid}&window={window}'>{sid}</a>
<a title = 'fix corpus' href='fix-corpus.cgi?corpus={corpus}&sid_edit={sid}'>*</a>'
return html<|docstring|>Prints a sid: clickable to jump to context<|endoftext|> |
2a2b98fa9f1e4d16a255e8051b4cb546ce6508e29648b3fbfc39b1899105364e | @staticmethod
def edit_sid_bttn(lang, sid, string2print="<i class='icon-edit'></i>"):
'Gives button to jump to the sentence in the edit interface'
corpus = ('../db/%s.db' % lang)
html = ('<a target=\'_blank\' style="text-decoration:none;\n color:black;font-size:12px;" \n href="%s?db_edit=%s&sid_edit=%s">%s</a>' % ('fix-corpus.cgi', corpus, sid, string2print))
return html | Gives button to jump to the sentence in the edit interface | www/cgi-bin/ntumc_webkit.py | edit_sid_bttn | bond-lab/IMI | 0 | python | @staticmethod
def edit_sid_bttn(lang, sid, string2print="<i class='icon-edit'></i>"):
corpus = ('../db/%s.db' % lang)
html = ('<a target=\'_blank\' style="text-decoration:none;\n color:black;font-size:12px;" \n href="%s?db_edit=%s&sid_edit=%s">%s</a>' % ('fix-corpus.cgi', corpus, sid, string2print))
return html | @staticmethod
def edit_sid_bttn(lang, sid, string2print="<i class='icon-edit'></i>"):
corpus = ('../db/%s.db' % lang)
html = ('<a target=\'_blank\' style="text-decoration:none;\n color:black;font-size:12px;" \n href="%s?db_edit=%s&sid_edit=%s">%s</a>' % ('fix-corpus.cgi', corpus, sid, string2print))
return html<|docstring|>Gives button to jump to the sentence in the edit interface<|endoftext|> |
daa652bc36d674a88141f91b142f8b5d1f59b6130bba33a3f9dbaaf845777247 | @staticmethod
def googlespeech_text(lang, text):
'This function takes some text, and outputs an HTML\n code that will use googlespeech to speak it when cliked.\n '
if (lang == 'eng'):
l = 'en'
else:
return text
html = ('<span>\n <audio controls="controls" style="display:none;" autoplay="autoplay">\n <source src="http://translate.google.com/translate_tts?tl=%s&q=%s" type="audio/mpeg"/></audio></span>' % (l, text))
return html | This function takes some text, and outputs an HTML
code that will use googlespeech to speak it when cliked. | www/cgi-bin/ntumc_webkit.py | googlespeech_text | bond-lab/IMI | 0 | python | @staticmethod
def googlespeech_text(lang, text):
'This function takes some text, and outputs an HTML\n code that will use googlespeech to speak it when cliked.\n '
if (lang == 'eng'):
l = 'en'
else:
return text
html = ('<span>\n <audio controls="controls" style="display:none;" autoplay="autoplay">\n <source src="http://translate.google.com/translate_tts?tl=%s&q=%s" type="audio/mpeg"/></audio></span>' % (l, text))
return html | @staticmethod
def googlespeech_text(lang, text):
'This function takes some text, and outputs an HTML\n code that will use googlespeech to speak it when cliked.\n '
if (lang == 'eng'):
l = 'en'
else:
return text
html = ('<span>\n <audio controls="controls" style="display:none;" autoplay="autoplay">\n <source src="http://translate.google.com/translate_tts?tl=%s&q=%s" type="audio/mpeg"/></audio></span>' % (l, text))
return html<|docstring|>This function takes some text, and outputs an HTML
code that will use googlespeech to speak it when cliked.<|endoftext|> |
bd744bca0f45e53d3aec1394a69b7c7c62c50389e12b15efe4c6ea45b3ded9e2 | @staticmethod
def read_user_cookie(username=None, expire_hrs=6):
"Checks for a cookie object with user info, \n if it fails to find, returns a cookie object\n where the user is set to 'unknown'.\n It takes a username argument (if available).\n The optional argument sets the expiration time\n for the cookie - the default is 6hrs.\n In order to work, this cookie must also be \n written before the html header."
if ('HTTP_COOKIE' in os.environ):
cookie_string = os.environ.get('HTTP_COOKIE')
user_cookie = http.cookies.SimpleCookie()
user_cookie.load(cookie_string)
if username:
user_cookie['user_name'] = username
user_cookie['user_name']['expires'] = ((expire_hrs * 60) * 60)
else:
user_cookie = http.cookies.SimpleCookie()
user_cookie['user_name'] = 'unknown'
return user_cookie | Checks for a cookie object with user info,
if it fails to find, returns a cookie object
where the user is set to 'unknown'.
It takes a username argument (if available).
The optional argument sets the expiration time
for the cookie - the default is 6hrs.
In order to work, this cookie must also be
written before the html header. | www/cgi-bin/ntumc_webkit.py | read_user_cookie | bond-lab/IMI | 0 | python | @staticmethod
def read_user_cookie(username=None, expire_hrs=6):
"Checks for a cookie object with user info, \n if it fails to find, returns a cookie object\n where the user is set to 'unknown'.\n It takes a username argument (if available).\n The optional argument sets the expiration time\n for the cookie - the default is 6hrs.\n In order to work, this cookie must also be \n written before the html header."
if ('HTTP_COOKIE' in os.environ):
cookie_string = os.environ.get('HTTP_COOKIE')
user_cookie = http.cookies.SimpleCookie()
user_cookie.load(cookie_string)
if username:
user_cookie['user_name'] = username
user_cookie['user_name']['expires'] = ((expire_hrs * 60) * 60)
else:
user_cookie = http.cookies.SimpleCookie()
user_cookie['user_name'] = 'unknown'
return user_cookie | @staticmethod
def read_user_cookie(username=None, expire_hrs=6):
"Checks for a cookie object with user info, \n if it fails to find, returns a cookie object\n where the user is set to 'unknown'.\n It takes a username argument (if available).\n The optional argument sets the expiration time\n for the cookie - the default is 6hrs.\n In order to work, this cookie must also be \n written before the html header."
if ('HTTP_COOKIE' in os.environ):
cookie_string = os.environ.get('HTTP_COOKIE')
user_cookie = http.cookies.SimpleCookie()
user_cookie.load(cookie_string)
if username:
user_cookie['user_name'] = username
user_cookie['user_name']['expires'] = ((expire_hrs * 60) * 60)
else:
user_cookie = http.cookies.SimpleCookie()
user_cookie['user_name'] = 'unknown'
return user_cookie<|docstring|>Checks for a cookie object with user info,
if it fails to find, returns a cookie object
where the user is set to 'unknown'.
It takes a username argument (if available).
The optional argument sets the expiration time
for the cookie - the default is 6hrs.
In order to work, this cookie must also be
written before the html header.<|endoftext|> |
40bcfa7e9eeb5a88cf99d0d680778fa03eb24f87145a60fcef49269d4deec6c8 | @staticmethod
def secure(cookie):
'\n Adds secure=True to all cookies\n '
for k in cookie:
cookie[k]['secure'] = True
return cookie | Adds secure=True to all cookies | www/cgi-bin/ntumc_webkit.py | secure | bond-lab/IMI | 0 | python | @staticmethod
def secure(cookie):
'\n \n '
for k in cookie:
cookie[k]['secure'] = True
return cookie | @staticmethod
def secure(cookie):
'\n \n '
for k in cookie:
cookie[k]['secure'] = True
return cookie<|docstring|>Adds secure=True to all cookies<|endoftext|> |
6a0d9f5175b6153f82cab13011c993a74c0f17dc602f7c894d5ee5c5177cfbab | def columnCount(self, parent=None):
"Returns 1 because lists do not have multiple columns.\n\n Note:\n This method overrides the virtual function of it's parent.\n\n "
return 1 | Returns 1 because lists do not have multiple columns.
Note:
This method overrides the virtual function of it's parent. | pythonicqt/models/listmodel.py | columnCount | Digirolamo/pythonicqt | 1 | python | def columnCount(self, parent=None):
"Returns 1 because lists do not have multiple columns.\n\n Note:\n This method overrides the virtual function of it's parent.\n\n "
return 1 | def columnCount(self, parent=None):
"Returns 1 because lists do not have multiple columns.\n\n Note:\n This method overrides the virtual function of it's parent.\n\n "
return 1<|docstring|>Returns 1 because lists do not have multiple columns.
Note:
This method overrides the virtual function of it's parent.<|endoftext|> |
776caf7a9520dae5fdd39baa94c7f3154b81795f3be7735689c3204386c2f403 | def rowCount(self, parent=None):
"Returns the length of the underlying list.\n\n Note:\n This method overrides the virtual function of it's parent.\n\n "
if (parent is None):
return 0
return len(self._container) | Returns the length of the underlying list.
Note:
This method overrides the virtual function of it's parent. | pythonicqt/models/listmodel.py | rowCount | Digirolamo/pythonicqt | 1 | python | def rowCount(self, parent=None):
"Returns the length of the underlying list.\n\n Note:\n This method overrides the virtual function of it's parent.\n\n "
if (parent is None):
return 0
return len(self._container) | def rowCount(self, parent=None):
"Returns the length of the underlying list.\n\n Note:\n This method overrides the virtual function of it's parent.\n\n "
if (parent is None):
return 0
return len(self._container)<|docstring|>Returns the length of the underlying list.
Note:
This method overrides the virtual function of it's parent.<|endoftext|> |
decdf99922021aeec9b96874d7686b8c711ed95ca406da41c312b2050b4ab32f | def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
"Just retuerns the section of the header, lists do not usually have headers.\n\n Note:\n This method overrides the virtual function of it's parent.\n\n "
return unicode(section) | Just retuerns the section of the header, lists do not usually have headers.
Note:
This method overrides the virtual function of it's parent. | pythonicqt/models/listmodel.py | headerData | Digirolamo/pythonicqt | 1 | python | def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
"Just retuerns the section of the header, lists do not usually have headers.\n\n Note:\n This method overrides the virtual function of it's parent.\n\n "
return unicode(section) | def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
"Just retuerns the section of the header, lists do not usually have headers.\n\n Note:\n This method overrides the virtual function of it's parent.\n\n "
return unicode(section)<|docstring|>Just retuerns the section of the header, lists do not usually have headers.
Note:
This method overrides the virtual function of it's parent.<|endoftext|> |
1c679d93ea294523c923ec025888584f88144bfcd1e49d1b96fe2046b0288e80 | def setData(self, index, value, role=QtCore.Qt.EditRole):
"Sets the data of a role at a specific index of the list.\n If the role is DisplayRole or EditRole, sets the value located\n in the underlying list at the index. Else sets the role of the\n individual item specifically.\n\n This method is expanded to also accept a new role, you can set item\n flags by passing in the role QtCore.Qt.ItemFlags.\n\n Args:\n index (QModelIndex):\n role (Optional[ItemRole]):\n\n Note:\n This method overrides the virtual function of it's parent.\n\n Raises:\n TypeError: if role is not a instance of ItemDataRole or specifically QtCore.Qt.ItemFlags\n\n "
if (not index.isValid()):
return None
row = index.row()
self._container[row][role] = value
self.dataChanged.emit(index, index)
return True | Sets the data of a role at a specific index of the list.
If the role is DisplayRole or EditRole, sets the value located
in the underlying list at the index. Else sets the role of the
individual item specifically.
This method is expanded to also accept a new role, you can set item
flags by passing in the role QtCore.Qt.ItemFlags.
Args:
index (QModelIndex):
role (Optional[ItemRole]):
Note:
This method overrides the virtual function of it's parent.
Raises:
TypeError: if role is not a instance of ItemDataRole or specifically QtCore.Qt.ItemFlags | pythonicqt/models/listmodel.py | setData | Digirolamo/pythonicqt | 1 | python | def setData(self, index, value, role=QtCore.Qt.EditRole):
"Sets the data of a role at a specific index of the list.\n If the role is DisplayRole or EditRole, sets the value located\n in the underlying list at the index. Else sets the role of the\n individual item specifically.\n\n This method is expanded to also accept a new role, you can set item\n flags by passing in the role QtCore.Qt.ItemFlags.\n\n Args:\n index (QModelIndex):\n role (Optional[ItemRole]):\n\n Note:\n This method overrides the virtual function of it's parent.\n\n Raises:\n TypeError: if role is not a instance of ItemDataRole or specifically QtCore.Qt.ItemFlags\n\n "
if (not index.isValid()):
return None
row = index.row()
self._container[row][role] = value
self.dataChanged.emit(index, index)
return True | def setData(self, index, value, role=QtCore.Qt.EditRole):
"Sets the data of a role at a specific index of the list.\n If the role is DisplayRole or EditRole, sets the value located\n in the underlying list at the index. Else sets the role of the\n individual item specifically.\n\n This method is expanded to also accept a new role, you can set item\n flags by passing in the role QtCore.Qt.ItemFlags.\n\n Args:\n index (QModelIndex):\n role (Optional[ItemRole]):\n\n Note:\n This method overrides the virtual function of it's parent.\n\n Raises:\n TypeError: if role is not a instance of ItemDataRole or specifically QtCore.Qt.ItemFlags\n\n "
if (not index.isValid()):
return None
row = index.row()
self._container[row][role] = value
self.dataChanged.emit(index, index)
return True<|docstring|>Sets the data of a role at a specific index of the list.
If the role is DisplayRole or EditRole, sets the value located
in the underlying list at the index. Else sets the role of the
individual item specifically.
This method is expanded to also accept a new role, you can set item
flags by passing in the role QtCore.Qt.ItemFlags.
Args:
index (QModelIndex):
role (Optional[ItemRole]):
Note:
This method overrides the virtual function of it's parent.
Raises:
TypeError: if role is not a instance of ItemDataRole or specifically QtCore.Qt.ItemFlags<|endoftext|> |
486c88fe439c7f38b1c29e5b6108a0558e32738577217f73d6fe5ec25b305951 | def data(self, index, role=QtCore.Qt.DisplayRole):
"Returns the data of a role at a specific index of the list.\n If the role is DisplayRole or EditRole, returns the value located\n in the underlying list at the index. Else returns the role of the\n individual item if the user has set it. Else returns the default\n role data located in the class attribute if it exists.\n\n Args:\n index (QModelIndex):\n role (Optional[ItemRole]):\n\n Note:\n This method overrides the virtual function of it's parent.\n\n "
if (not index.isValid()):
return None
(row, column) = (index.row(), index.column())
try:
return self._container[row][role]
except KeyError as e:
return None | Returns the data of a role at a specific index of the list.
If the role is DisplayRole or EditRole, returns the value located
in the underlying list at the index. Else returns the role of the
individual item if the user has set it. Else returns the default
role data located in the class attribute if it exists.
Args:
index (QModelIndex):
role (Optional[ItemRole]):
Note:
This method overrides the virtual function of it's parent. | pythonicqt/models/listmodel.py | data | Digirolamo/pythonicqt | 1 | python | def data(self, index, role=QtCore.Qt.DisplayRole):
"Returns the data of a role at a specific index of the list.\n If the role is DisplayRole or EditRole, returns the value located\n in the underlying list at the index. Else returns the role of the\n individual item if the user has set it. Else returns the default\n role data located in the class attribute if it exists.\n\n Args:\n index (QModelIndex):\n role (Optional[ItemRole]):\n\n Note:\n This method overrides the virtual function of it's parent.\n\n "
if (not index.isValid()):
return None
(row, column) = (index.row(), index.column())
try:
return self._container[row][role]
except KeyError as e:
return None | def data(self, index, role=QtCore.Qt.DisplayRole):
"Returns the data of a role at a specific index of the list.\n If the role is DisplayRole or EditRole, returns the value located\n in the underlying list at the index. Else returns the role of the\n individual item if the user has set it. Else returns the default\n role data located in the class attribute if it exists.\n\n Args:\n index (QModelIndex):\n role (Optional[ItemRole]):\n\n Note:\n This method overrides the virtual function of it's parent.\n\n "
if (not index.isValid()):
return None
(row, column) = (index.row(), index.column())
try:
return self._container[row][role]
except KeyError as e:
return None<|docstring|>Returns the data of a role at a specific index of the list.
If the role is DisplayRole or EditRole, returns the value located
in the underlying list at the index. Else returns the role of the
individual item if the user has set it. Else returns the default
role data located in the class attribute if it exists.
Args:
index (QModelIndex):
role (Optional[ItemRole]):
Note:
This method overrides the virtual function of it's parent.<|endoftext|> |
977d4ce5d2854f01218c62d692294c2b4bd90f9caaea1974987e050d10071c68 | def flags(self, index):
"Returns the QtCore.Qt.ItemFlags of the item at the index.\n\n You can set item flags using the setData method.\n \n Note:\n This method overrides the virtual function of it's parent.\n\n "
if (not index.isValid()):
return None
(row, column) = (index.row(), index.column())
try:
return self._container[row][QtCore.Qt.ItemFlags]
except KeyError as e:
return None | Returns the QtCore.Qt.ItemFlags of the item at the index.
You can set item flags using the setData method.
Note:
This method overrides the virtual function of it's parent. | pythonicqt/models/listmodel.py | flags | Digirolamo/pythonicqt | 1 | python | def flags(self, index):
"Returns the QtCore.Qt.ItemFlags of the item at the index.\n\n You can set item flags using the setData method.\n \n Note:\n This method overrides the virtual function of it's parent.\n\n "
if (not index.isValid()):
return None
(row, column) = (index.row(), index.column())
try:
return self._container[row][QtCore.Qt.ItemFlags]
except KeyError as e:
return None | def flags(self, index):
"Returns the QtCore.Qt.ItemFlags of the item at the index.\n\n You can set item flags using the setData method.\n \n Note:\n This method overrides the virtual function of it's parent.\n\n "
if (not index.isValid()):
return None
(row, column) = (index.row(), index.column())
try:
return self._container[row][QtCore.Qt.ItemFlags]
except KeyError as e:
return None<|docstring|>Returns the QtCore.Qt.ItemFlags of the item at the index.
You can set item flags using the setData method.
Note:
This method overrides the virtual function of it's parent.<|endoftext|> |
589fd6e5cb6e7cc174c4cc378f011316195e2df2392e0e19e3dffb071d529f32 | def __copy__(self, deep_copy_memo=None):
'Makes a shallow copy of the list and returns a new model of it.\n \n Keyword Args:\n deep_copy_memo (Optional[dict]): Only to be used by a __deepcopy__\n implimentation. If deep_copy_memo is not None, it should be the \n memo argument of __deep__ copy. \n\n '
cls = self.__class__
if (deep_copy_memo is None):
container = copy.copy(self._container)
else:
container = copy.deepcopy(self._container, deep_copy_memo)
new_instance = cls(self._container)
return new_instance | Makes a shallow copy of the list and returns a new model of it.
Keyword Args:
deep_copy_memo (Optional[dict]): Only to be used by a __deepcopy__
implimentation. If deep_copy_memo is not None, it should be the
memo argument of __deep__ copy. | pythonicqt/models/listmodel.py | __copy__ | Digirolamo/pythonicqt | 1 | python | def __copy__(self, deep_copy_memo=None):
'Makes a shallow copy of the list and returns a new model of it.\n \n Keyword Args:\n deep_copy_memo (Optional[dict]): Only to be used by a __deepcopy__\n implimentation. If deep_copy_memo is not None, it should be the \n memo argument of __deep__ copy. \n\n '
cls = self.__class__
if (deep_copy_memo is None):
container = copy.copy(self._container)
else:
container = copy.deepcopy(self._container, deep_copy_memo)
new_instance = cls(self._container)
return new_instance | def __copy__(self, deep_copy_memo=None):
'Makes a shallow copy of the list and returns a new model of it.\n \n Keyword Args:\n deep_copy_memo (Optional[dict]): Only to be used by a __deepcopy__\n implimentation. If deep_copy_memo is not None, it should be the \n memo argument of __deep__ copy. \n\n '
cls = self.__class__
if (deep_copy_memo is None):
container = copy.copy(self._container)
else:
container = copy.deepcopy(self._container, deep_copy_memo)
new_instance = cls(self._container)
return new_instance<|docstring|>Makes a shallow copy of the list and returns a new model of it.
Keyword Args:
deep_copy_memo (Optional[dict]): Only to be used by a __deepcopy__
implimentation. If deep_copy_memo is not None, it should be the
memo argument of __deep__ copy.<|endoftext|> |
c990cc1c8468a162431d0effadf712f069813942fa4c6784fccae920f441a284 | def __deepcopy__(self, memo):
'Makes a deepcopy of the list and returns a new model of it.'
return self.__copy__(deep_copy_memo=memo) | Makes a deepcopy of the list and returns a new model of it. | pythonicqt/models/listmodel.py | __deepcopy__ | Digirolamo/pythonicqt | 1 | python | def __deepcopy__(self, memo):
return self.__copy__(deep_copy_memo=memo) | def __deepcopy__(self, memo):
return self.__copy__(deep_copy_memo=memo)<|docstring|>Makes a deepcopy of the list and returns a new model of it.<|endoftext|> |
b01c344a6b03edca093058df94587855fa4b03fc2132fa17da703a1391ba99be | def _convert_idx(self, idx):
'To be compatable with Qt objects, ensure the index is a positive number.\n Used for python index operations.'
if isinstance(idx, slice):
raise NotImplementedError('No slice setting functionality yet.')
if (idx < 0):
idx = (len(self) + idx)
return idx | To be compatable with Qt objects, ensure the index is a positive number.
Used for python index operations. | pythonicqt/models/listmodel.py | _convert_idx | Digirolamo/pythonicqt | 1 | python | def _convert_idx(self, idx):
'To be compatable with Qt objects, ensure the index is a positive number.\n Used for python index operations.'
if isinstance(idx, slice):
raise NotImplementedError('No slice setting functionality yet.')
if (idx < 0):
idx = (len(self) + idx)
return idx | def _convert_idx(self, idx):
'To be compatable with Qt objects, ensure the index is a positive number.\n Used for python index operations.'
if isinstance(idx, slice):
raise NotImplementedError('No slice setting functionality yet.')
if (idx < 0):
idx = (len(self) + idx)
return idx<|docstring|>To be compatable with Qt objects, ensure the index is a positive number.
Used for python index operations.<|endoftext|> |
4609a4b9d4aa6efd73071231ba70cf1efd0b8b7dac59f536632a0251e16c4178 | def __getitem__(self, idx):
'Gets the data located the the index or slice in the underlying list.\n \n Note:\n This method is an abstract method required for MutableSequence.\n '
return self._container.__getitem__(idx).data | Gets the data located the the index or slice in the underlying list.
Note:
This method is an abstract method required for MutableSequence. | pythonicqt/models/listmodel.py | __getitem__ | Digirolamo/pythonicqt | 1 | python | def __getitem__(self, idx):
'Gets the data located the the index or slice in the underlying list.\n \n Note:\n This method is an abstract method required for MutableSequence.\n '
return self._container.__getitem__(idx).data | def __getitem__(self, idx):
'Gets the data located the the index or slice in the underlying list.\n \n Note:\n This method is an abstract method required for MutableSequence.\n '
return self._container.__getitem__(idx).data<|docstring|>Gets the data located the the index or slice in the underlying list.
Note:
This method is an abstract method required for MutableSequence.<|endoftext|> |
f3a38865e53af8e9e762f2bde00da6d1a58a4a7534213c91016f3c22db1d9f57 | def __setitem__(self, idx, value):
'Sets the data located the the index or slice in the underlying list.\n \n Note:\n This method is an abstract method required for MutableSequence.\n '
idx = self._convert_idx(idx)
index = self.index(idx, 0)
previous = self._container[idx].data
self.setData(index, value)
self.ListChanged.emit(idx, previous)
return | Sets the data located the the index or slice in the underlying list.
Note:
This method is an abstract method required for MutableSequence. | pythonicqt/models/listmodel.py | __setitem__ | Digirolamo/pythonicqt | 1 | python | def __setitem__(self, idx, value):
'Sets the data located the the index or slice in the underlying list.\n \n Note:\n This method is an abstract method required for MutableSequence.\n '
idx = self._convert_idx(idx)
index = self.index(idx, 0)
previous = self._container[idx].data
self.setData(index, value)
self.ListChanged.emit(idx, previous)
return | def __setitem__(self, idx, value):
'Sets the data located the the index or slice in the underlying list.\n \n Note:\n This method is an abstract method required for MutableSequence.\n '
idx = self._convert_idx(idx)
index = self.index(idx, 0)
previous = self._container[idx].data
self.setData(index, value)
self.ListChanged.emit(idx, previous)
return<|docstring|>Sets the data located the the index or slice in the underlying list.
Note:
This method is an abstract method required for MutableSequence.<|endoftext|> |
8c04e55ce6e7eae2bbf3a19f6cec84a24941bf5de3c9a503184247e8d417ee3c | def __delitem__(self, idx):
'Deletes an item from the underlying list and any associated metadata,\n then updates the model.\n \n Note:\n This method is an abstract method required for MutableSequence.\n '
idx = self._convert_idx(idx)
previous = self._container[idx].data
parent = QtCore.QModelIndex()
self.beginRemoveRows(parent, idx, idx)
ret_value = self._container.__delitem__(idx)
self.endRemoveRows()
self.ListChanged.emit(idx, previous)
return ret_value | Deletes an item from the underlying list and any associated metadata,
then updates the model.
Note:
This method is an abstract method required for MutableSequence. | pythonicqt/models/listmodel.py | __delitem__ | Digirolamo/pythonicqt | 1 | python | def __delitem__(self, idx):
'Deletes an item from the underlying list and any associated metadata,\n then updates the model.\n \n Note:\n This method is an abstract method required for MutableSequence.\n '
idx = self._convert_idx(idx)
previous = self._container[idx].data
parent = QtCore.QModelIndex()
self.beginRemoveRows(parent, idx, idx)
ret_value = self._container.__delitem__(idx)
self.endRemoveRows()
self.ListChanged.emit(idx, previous)
return ret_value | def __delitem__(self, idx):
'Deletes an item from the underlying list and any associated metadata,\n then updates the model.\n \n Note:\n This method is an abstract method required for MutableSequence.\n '
idx = self._convert_idx(idx)
previous = self._container[idx].data
parent = QtCore.QModelIndex()
self.beginRemoveRows(parent, idx, idx)
ret_value = self._container.__delitem__(idx)
self.endRemoveRows()
self.ListChanged.emit(idx, previous)
return ret_value<|docstring|>Deletes an item from the underlying list and any associated metadata,
then updates the model.
Note:
This method is an abstract method required for MutableSequence.<|endoftext|> |
8df14bdcfa755d2829323f84c54034fe2adce3589b878aedd1dd22ecba5acbfe | def __len__(self, *args):
'Returns the length of the underlying list.\n \n Note:\n This method is an abstract method required for MutableSequence.\n '
return self._container.__len__(*args) | Returns the length of the underlying list.
Note:
This method is an abstract method required for MutableSequence. | pythonicqt/models/listmodel.py | __len__ | Digirolamo/pythonicqt | 1 | python | def __len__(self, *args):
'Returns the length of the underlying list.\n \n Note:\n This method is an abstract method required for MutableSequence.\n '
return self._container.__len__(*args) | def __len__(self, *args):
'Returns the length of the underlying list.\n \n Note:\n This method is an abstract method required for MutableSequence.\n '
return self._container.__len__(*args)<|docstring|>Returns the length of the underlying list.
Note:
This method is an abstract method required for MutableSequence.<|endoftext|> |
c839eae222f6b732ee6d3e8e2cbaee3b90af9ab91fd883e998d2fb001437d129 | def insert(self, idx, value):
'Inserts data into the underlying list.\n\n Note:\n This method is an abstract method required for MutableSequence.'
previous = None
try:
previous = self._container[idx].data
except IndexError:
pass
parent = QtCore.QModelIndex()
self.beginInsertRows(parent, idx, idx)
ret_value = self._container.insert(idx, self._item_factory(value))
self.endInsertRows()
self.ListChanged.emit(idx, previous)
return ret_value | Inserts data into the underlying list.
Note:
This method is an abstract method required for MutableSequence. | pythonicqt/models/listmodel.py | insert | Digirolamo/pythonicqt | 1 | python | def insert(self, idx, value):
'Inserts data into the underlying list.\n\n Note:\n This method is an abstract method required for MutableSequence.'
previous = None
try:
previous = self._container[idx].data
except IndexError:
pass
parent = QtCore.QModelIndex()
self.beginInsertRows(parent, idx, idx)
ret_value = self._container.insert(idx, self._item_factory(value))
self.endInsertRows()
self.ListChanged.emit(idx, previous)
return ret_value | def insert(self, idx, value):
'Inserts data into the underlying list.\n\n Note:\n This method is an abstract method required for MutableSequence.'
previous = None
try:
previous = self._container[idx].data
except IndexError:
pass
parent = QtCore.QModelIndex()
self.beginInsertRows(parent, idx, idx)
ret_value = self._container.insert(idx, self._item_factory(value))
self.endInsertRows()
self.ListChanged.emit(idx, previous)
return ret_value<|docstring|>Inserts data into the underlying list.
Note:
This method is an abstract method required for MutableSequence.<|endoftext|> |
2d7b330e6700c09884180a13110cf02a73798005478d495cd46cf6415a6a947b | def index(self, row, column, parent=QtCore.QModelIndex()):
'Returns the QModelIndex from the underlying model.\n \n Note:\n This method overrides the virtual function of QAbstractListModel.\n This is not the MutableSequence.index method. That is index_of.\n '
return QtCore.QAbstractListModel.index(self, row, column, parent=parent) | Returns the QModelIndex from the underlying model.
Note:
This method overrides the virtual function of QAbstractListModel.
This is not the MutableSequence.index method. That is index_of. | pythonicqt/models/listmodel.py | index | Digirolamo/pythonicqt | 1 | python | def index(self, row, column, parent=QtCore.QModelIndex()):
'Returns the QModelIndex from the underlying model.\n \n Note:\n This method overrides the virtual function of QAbstractListModel.\n This is not the MutableSequence.index method. That is index_of.\n '
return QtCore.QAbstractListModel.index(self, row, column, parent=parent) | def index(self, row, column, parent=QtCore.QModelIndex()):
'Returns the QModelIndex from the underlying model.\n \n Note:\n This method overrides the virtual function of QAbstractListModel.\n This is not the MutableSequence.index method. That is index_of.\n '
return QtCore.QAbstractListModel.index(self, row, column, parent=parent)<|docstring|>Returns the QModelIndex from the underlying model.
Note:
This method overrides the virtual function of QAbstractListModel.
This is not the MutableSequence.index method. That is index_of.<|endoftext|> |
d9aeac60475f2f463f0ca3de17fb019389c6224ac2529ca480b4782d8aa97e68 | def index_of(self, item):
'Calls the python version of list.index.\n Returns the index of the item that matches first.'
return super(ListModel, self).index(item) | Calls the python version of list.index.
Returns the index of the item that matches first. | pythonicqt/models/listmodel.py | index_of | Digirolamo/pythonicqt | 1 | python | def index_of(self, item):
'Calls the python version of list.index.\n Returns the index of the item that matches first.'
return super(ListModel, self).index(item) | def index_of(self, item):
'Calls the python version of list.index.\n Returns the index of the item that matches first.'
return super(ListModel, self).index(item)<|docstring|>Calls the python version of list.index.
Returns the index of the item that matches first.<|endoftext|> |
bd7550fe701d030285442f04699a35923ecb0eb35ba250531439561d02e833cf | def clear(self):
'Clears entire model and emits layout changed'
self.layoutAboutToBeChanged.emit()
self._container = self._container[:]
self.layoutChanged.emit()
self.ListCleared.emit() | Clears entire model and emits layout changed | pythonicqt/models/listmodel.py | clear | Digirolamo/pythonicqt | 1 | python | def clear(self):
self.layoutAboutToBeChanged.emit()
self._container = self._container[:]
self.layoutChanged.emit()
self.ListCleared.emit() | def clear(self):
self.layoutAboutToBeChanged.emit()
self._container = self._container[:]
self.layoutChanged.emit()
self.ListCleared.emit()<|docstring|>Clears entire model and emits layout changed<|endoftext|> |
39922d6d20205538b3a52a3d05f9b87e73c708aee26b596b40bd075667c83fb5 | def __str__(self):
'Returns the __str__ of the underlying list.'
return list(self).__str__() | Returns the __str__ of the underlying list. | pythonicqt/models/listmodel.py | __str__ | Digirolamo/pythonicqt | 1 | python | def __str__(self):
return list(self).__str__() | def __str__(self):
return list(self).__str__()<|docstring|>Returns the __str__ of the underlying list.<|endoftext|> |
b8af4f8f206edff71dc6a021aa112ed6da8d96788c21dcc0030962bb5207b946 | def __repr__(self):
'The representation of the object, does not include any of the metadata\n such as flags and roles.'
class_name = self.__class__.__name__
list_repr = list(self).__repr__()
factory_name = self._item_factory.__name__
return '{}({}, item_factory={})'.format(class_name, list_repr, factory_name) | The representation of the object, does not include any of the metadata
such as flags and roles. | pythonicqt/models/listmodel.py | __repr__ | Digirolamo/pythonicqt | 1 | python | def __repr__(self):
'The representation of the object, does not include any of the metadata\n such as flags and roles.'
class_name = self.__class__.__name__
list_repr = list(self).__repr__()
factory_name = self._item_factory.__name__
return '{}({}, item_factory={})'.format(class_name, list_repr, factory_name) | def __repr__(self):
'The representation of the object, does not include any of the metadata\n such as flags and roles.'
class_name = self.__class__.__name__
list_repr = list(self).__repr__()
factory_name = self._item_factory.__name__
return '{}({}, item_factory={})'.format(class_name, list_repr, factory_name)<|docstring|>The representation of the object, does not include any of the metadata
such as flags and roles.<|endoftext|> |
d005ae0fb686930546f392aa041a01b4093e579619606452d1e867d93bf2f8c0 | def __eq__(self, *args):
'Returns whether the underlying list equals another list.'
return list(self).__eq__(*args) | Returns whether the underlying list equals another list. | pythonicqt/models/listmodel.py | __eq__ | Digirolamo/pythonicqt | 1 | python | def __eq__(self, *args):
return list(self).__eq__(*args) | def __eq__(self, *args):
return list(self).__eq__(*args)<|docstring|>Returns whether the underlying list equals another list.<|endoftext|> |
b4921034f66bb5001ae1187c426561758c1ba43be1481e7cf186af3188cf69c6 | def __ne__(self, *args):
'Returns whether the underlying list is not equal to another list.'
return list(self).__ne__(*args) | Returns whether the underlying list is not equal to another list. | pythonicqt/models/listmodel.py | __ne__ | Digirolamo/pythonicqt | 1 | python | def __ne__(self, *args):
return list(self).__ne__(*args) | def __ne__(self, *args):
return list(self).__ne__(*args)<|docstring|>Returns whether the underlying list is not equal to another list.<|endoftext|> |
039e95424c5c767691b9f342697dbc13e6c8451a6c49d221cc7085a47ab42fdb | def no_redirect(pattern, locale_prefix=True, re_flags=None):
'\n Return a url matcher that will stop the redirect middleware and force\n Django to continue with regular URL matching. For use when you have a URL pattern\n you want to serve, and a broad catch-all pattern you want to redirect.\n :param pattern: regex URL patter that will definitely not redirect.\n :param locale_prefix: prepend the locale matching pattern.\n :param re_flags: a string of any of the characters: "iLmsux". Will modify the `pattern` regex\n based on the documented meaning of the flags (see python re module docs).\n :return:\n '
if locale_prefix:
pattern = pattern.lstrip('^/')
pattern = (LOCALE_RE + pattern)
if re_flags:
pattern = ('(?{})'.format(re_flags) + pattern)
def _view(request, *args, **kwargs):
return None
return url(pattern, _view) | Return a url matcher that will stop the redirect middleware and force
Django to continue with regular URL matching. For use when you have a URL pattern
you want to serve, and a broad catch-all pattern you want to redirect.
:param pattern: regex URL patter that will definitely not redirect.
:param locale_prefix: prepend the locale matching pattern.
:param re_flags: a string of any of the characters: "iLmsux". Will modify the `pattern` regex
based on the documented meaning of the flags (see python re module docs).
:return: | redirect_urls/utils.py | no_redirect | jayvdb/django-redirect-urls | 17 | python | def no_redirect(pattern, locale_prefix=True, re_flags=None):
'\n Return a url matcher that will stop the redirect middleware and force\n Django to continue with regular URL matching. For use when you have a URL pattern\n you want to serve, and a broad catch-all pattern you want to redirect.\n :param pattern: regex URL patter that will definitely not redirect.\n :param locale_prefix: prepend the locale matching pattern.\n :param re_flags: a string of any of the characters: "iLmsux". Will modify the `pattern` regex\n based on the documented meaning of the flags (see python re module docs).\n :return:\n '
if locale_prefix:
pattern = pattern.lstrip('^/')
pattern = (LOCALE_RE + pattern)
if re_flags:
pattern = ('(?{})'.format(re_flags) + pattern)
def _view(request, *args, **kwargs):
return None
return url(pattern, _view) | def no_redirect(pattern, locale_prefix=True, re_flags=None):
'\n Return a url matcher that will stop the redirect middleware and force\n Django to continue with regular URL matching. For use when you have a URL pattern\n you want to serve, and a broad catch-all pattern you want to redirect.\n :param pattern: regex URL patter that will definitely not redirect.\n :param locale_prefix: prepend the locale matching pattern.\n :param re_flags: a string of any of the characters: "iLmsux". Will modify the `pattern` regex\n based on the documented meaning of the flags (see python re module docs).\n :return:\n '
if locale_prefix:
pattern = pattern.lstrip('^/')
pattern = (LOCALE_RE + pattern)
if re_flags:
pattern = ('(?{})'.format(re_flags) + pattern)
def _view(request, *args, **kwargs):
return None
return url(pattern, _view)<|docstring|>Return a url matcher that will stop the redirect middleware and force
Django to continue with regular URL matching. For use when you have a URL pattern
you want to serve, and a broad catch-all pattern you want to redirect.
:param pattern: regex URL patter that will definitely not redirect.
:param locale_prefix: prepend the locale matching pattern.
:param re_flags: a string of any of the characters: "iLmsux". Will modify the `pattern` regex
based on the documented meaning of the flags (see python re module docs).
:return:<|endoftext|> |
fda85d790cb2cf8fbec88f5c01f866ea2347b3f6855c6e266b69aed1fba28a87 | def redirect(pattern, to, permanent=True, locale_prefix=True, anchor=None, name=None, query=None, vary=None, cache_timeout=12, decorators=None, re_flags=None, to_args=None, to_kwargs=None, prepend_locale=True, merge_query=False):
'\n Return a url matcher suited for urlpatterns.\n\n pattern: the regex against which to match the requested URL.\n to: either a url name that `reverse` will find, a url that will simply be returned,\n or a function that will be given the request and url captures, and return the\n destination.\n permanent: boolean whether to send a 301 or 302 response.\n locale_prefix: automatically prepend `pattern` with a regex for an optional locale\n in the url. This locale (or None) will show up in captured kwargs as \'locale\'.\n anchor: if set it will be appended to the destination url after a \'#\'.\n name: if used in a `urls.py` the redirect URL will be available as the name\n for use in calls to `reverse()`. Does _NOT_ work if used in a `redirects.py` file.\n query: a dict of query params to add to the destination url.\n vary: if you used an HTTP header to decide where to send users you should include that\n header\'s name in the `vary` arg.\n cache_timeout: number of hours to cache this redirect. just sets the proper `cache-control`\n and `expires` headers.\n decorators: a callable (or list of callables) that will wrap the view used to redirect\n the user. equivalent to adding a decorator to any other view.\n re_flags: a string of any of the characters: "iLmsux". Will modify the `pattern` regex\n based on the documented meaning of the flags (see python re module docs).\n to_args: a tuple or list of args to pass to reverse if `to` is a url name.\n to_kwargs: a dict of keyword args to pass to reverse if `to` is a url name.\n prepend_locale: if true the redirect URL will be prepended with the locale from the\n requested URL.\n merge_query: merge the requested query params from the `query` arg with any query params\n from the request.\n\n Usage:\n urlpatterns = [\n redirect(r\'projects/$\', \'mozorg.product\'),\n redirect(r\'^projects/seamonkey$\', \'mozorg.product\', locale_prefix=False),\n redirect(r\'apps/$\', \'https://marketplace.firefox.com\'),\n redirect(r\'firefox/$\', \'firefox.new\', name=\'firefox\'),\n redirect(r\'the/dude$\', \'abides\', query={\'aggression\': \'not_stand\'}),\n ]\n '
if permanent:
redirect_class = HttpResponsePermanentRedirect
else:
redirect_class = HttpResponseRedirect
if locale_prefix:
pattern = pattern.lstrip('^/')
pattern = (LOCALE_RE + pattern)
if re_flags:
pattern = ('(?{})'.format(re_flags) + pattern)
view_decorators = []
if (cache_timeout is not None):
view_decorators.append(cache_control_expires(cache_timeout))
if vary:
if isinstance(vary, basestring):
vary = [vary]
view_decorators.append(vary_on_headers(*vary))
if decorators:
if callable(decorators):
view_decorators.append(decorators)
else:
view_decorators.extend(decorators)
def _view(request, *args, **kwargs):
kwargs = {k: (v or '') for (k, v) in kwargs.items()}
args = [(x or '') for x in args]
if callable(to):
to_value = to(request, *args, **kwargs)
else:
to_value = to
if (to_value.startswith('/') or HTTP_RE.match(to_value)):
redirect_url = to_value
else:
try:
redirect_url = reverse(to_value, args=to_args, kwargs=to_kwargs)
except NoReverseMatch:
redirect_url = to_value
if (prepend_locale and redirect_url.startswith('/') and kwargs.get('locale')):
redirect_url = ('/{locale}' + redirect_url.lstrip('/'))
if (args or kwargs):
redirect_url = strip_tags(force_text(redirect_url).format(*args, **kwargs))
if query:
if merge_query:
req_query = parse_qs(request.META.get('QUERY_STRING'))
req_query.update(query)
querystring = urlencode(req_query, doseq=True)
else:
querystring = urlencode(query, doseq=True)
elif (query is None):
querystring = request.META.get('QUERY_STRING')
else:
querystring = ''
if querystring:
redirect_url = '?'.join([redirect_url, querystring])
if anchor:
redirect_url = '#'.join([redirect_url, anchor])
if PROTOCOL_RELATIVE_RE.match(redirect_url):
redirect_url = ('/' + redirect_url.lstrip('/'))
return redirect_class(redirect_url)
try:
for decorator in reversed(view_decorators):
_view = decorator(_view)
except TypeError:
log.exception('decorators not iterable or does not contain callable items')
return url(pattern, _view, name=name) | Return a url matcher suited for urlpatterns.
pattern: the regex against which to match the requested URL.
to: either a url name that `reverse` will find, a url that will simply be returned,
or a function that will be given the request and url captures, and return the
destination.
permanent: boolean whether to send a 301 or 302 response.
locale_prefix: automatically prepend `pattern` with a regex for an optional locale
in the url. This locale (or None) will show up in captured kwargs as 'locale'.
anchor: if set it will be appended to the destination url after a '#'.
name: if used in a `urls.py` the redirect URL will be available as the name
for use in calls to `reverse()`. Does _NOT_ work if used in a `redirects.py` file.
query: a dict of query params to add to the destination url.
vary: if you used an HTTP header to decide where to send users you should include that
header's name in the `vary` arg.
cache_timeout: number of hours to cache this redirect. just sets the proper `cache-control`
and `expires` headers.
decorators: a callable (or list of callables) that will wrap the view used to redirect
the user. equivalent to adding a decorator to any other view.
re_flags: a string of any of the characters: "iLmsux". Will modify the `pattern` regex
based on the documented meaning of the flags (see python re module docs).
to_args: a tuple or list of args to pass to reverse if `to` is a url name.
to_kwargs: a dict of keyword args to pass to reverse if `to` is a url name.
prepend_locale: if true the redirect URL will be prepended with the locale from the
requested URL.
merge_query: merge the requested query params from the `query` arg with any query params
from the request.
Usage:
urlpatterns = [
redirect(r'projects/$', 'mozorg.product'),
redirect(r'^projects/seamonkey$', 'mozorg.product', locale_prefix=False),
redirect(r'apps/$', 'https://marketplace.firefox.com'),
redirect(r'firefox/$', 'firefox.new', name='firefox'),
redirect(r'the/dude$', 'abides', query={'aggression': 'not_stand'}),
] | redirect_urls/utils.py | redirect | jayvdb/django-redirect-urls | 17 | python | def redirect(pattern, to, permanent=True, locale_prefix=True, anchor=None, name=None, query=None, vary=None, cache_timeout=12, decorators=None, re_flags=None, to_args=None, to_kwargs=None, prepend_locale=True, merge_query=False):
'\n Return a url matcher suited for urlpatterns.\n\n pattern: the regex against which to match the requested URL.\n to: either a url name that `reverse` will find, a url that will simply be returned,\n or a function that will be given the request and url captures, and return the\n destination.\n permanent: boolean whether to send a 301 or 302 response.\n locale_prefix: automatically prepend `pattern` with a regex for an optional locale\n in the url. This locale (or None) will show up in captured kwargs as \'locale\'.\n anchor: if set it will be appended to the destination url after a \'#\'.\n name: if used in a `urls.py` the redirect URL will be available as the name\n for use in calls to `reverse()`. Does _NOT_ work if used in a `redirects.py` file.\n query: a dict of query params to add to the destination url.\n vary: if you used an HTTP header to decide where to send users you should include that\n header\'s name in the `vary` arg.\n cache_timeout: number of hours to cache this redirect. just sets the proper `cache-control`\n and `expires` headers.\n decorators: a callable (or list of callables) that will wrap the view used to redirect\n the user. equivalent to adding a decorator to any other view.\n re_flags: a string of any of the characters: "iLmsux". Will modify the `pattern` regex\n based on the documented meaning of the flags (see python re module docs).\n to_args: a tuple or list of args to pass to reverse if `to` is a url name.\n to_kwargs: a dict of keyword args to pass to reverse if `to` is a url name.\n prepend_locale: if true the redirect URL will be prepended with the locale from the\n requested URL.\n merge_query: merge the requested query params from the `query` arg with any query params\n from the request.\n\n Usage:\n urlpatterns = [\n redirect(r\'projects/$\', \'mozorg.product\'),\n redirect(r\'^projects/seamonkey$\', \'mozorg.product\', locale_prefix=False),\n redirect(r\'apps/$\', \'https://marketplace.firefox.com\'),\n redirect(r\'firefox/$\', \'firefox.new\', name=\'firefox\'),\n redirect(r\'the/dude$\', \'abides\', query={\'aggression\': \'not_stand\'}),\n ]\n '
if permanent:
redirect_class = HttpResponsePermanentRedirect
else:
redirect_class = HttpResponseRedirect
if locale_prefix:
pattern = pattern.lstrip('^/')
pattern = (LOCALE_RE + pattern)
if re_flags:
pattern = ('(?{})'.format(re_flags) + pattern)
view_decorators = []
if (cache_timeout is not None):
view_decorators.append(cache_control_expires(cache_timeout))
if vary:
if isinstance(vary, basestring):
vary = [vary]
view_decorators.append(vary_on_headers(*vary))
if decorators:
if callable(decorators):
view_decorators.append(decorators)
else:
view_decorators.extend(decorators)
def _view(request, *args, **kwargs):
kwargs = {k: (v or ) for (k, v) in kwargs.items()}
args = [(x or ) for x in args]
if callable(to):
to_value = to(request, *args, **kwargs)
else:
to_value = to
if (to_value.startswith('/') or HTTP_RE.match(to_value)):
redirect_url = to_value
else:
try:
redirect_url = reverse(to_value, args=to_args, kwargs=to_kwargs)
except NoReverseMatch:
redirect_url = to_value
if (prepend_locale and redirect_url.startswith('/') and kwargs.get('locale')):
redirect_url = ('/{locale}' + redirect_url.lstrip('/'))
if (args or kwargs):
redirect_url = strip_tags(force_text(redirect_url).format(*args, **kwargs))
if query:
if merge_query:
req_query = parse_qs(request.META.get('QUERY_STRING'))
req_query.update(query)
querystring = urlencode(req_query, doseq=True)
else:
querystring = urlencode(query, doseq=True)
elif (query is None):
querystring = request.META.get('QUERY_STRING')
else:
querystring =
if querystring:
redirect_url = '?'.join([redirect_url, querystring])
if anchor:
redirect_url = '#'.join([redirect_url, anchor])
if PROTOCOL_RELATIVE_RE.match(redirect_url):
redirect_url = ('/' + redirect_url.lstrip('/'))
return redirect_class(redirect_url)
try:
for decorator in reversed(view_decorators):
_view = decorator(_view)
except TypeError:
log.exception('decorators not iterable or does not contain callable items')
return url(pattern, _view, name=name) | def redirect(pattern, to, permanent=True, locale_prefix=True, anchor=None, name=None, query=None, vary=None, cache_timeout=12, decorators=None, re_flags=None, to_args=None, to_kwargs=None, prepend_locale=True, merge_query=False):
'\n Return a url matcher suited for urlpatterns.\n\n pattern: the regex against which to match the requested URL.\n to: either a url name that `reverse` will find, a url that will simply be returned,\n or a function that will be given the request and url captures, and return the\n destination.\n permanent: boolean whether to send a 301 or 302 response.\n locale_prefix: automatically prepend `pattern` with a regex for an optional locale\n in the url. This locale (or None) will show up in captured kwargs as \'locale\'.\n anchor: if set it will be appended to the destination url after a \'#\'.\n name: if used in a `urls.py` the redirect URL will be available as the name\n for use in calls to `reverse()`. Does _NOT_ work if used in a `redirects.py` file.\n query: a dict of query params to add to the destination url.\n vary: if you used an HTTP header to decide where to send users you should include that\n header\'s name in the `vary` arg.\n cache_timeout: number of hours to cache this redirect. just sets the proper `cache-control`\n and `expires` headers.\n decorators: a callable (or list of callables) that will wrap the view used to redirect\n the user. equivalent to adding a decorator to any other view.\n re_flags: a string of any of the characters: "iLmsux". Will modify the `pattern` regex\n based on the documented meaning of the flags (see python re module docs).\n to_args: a tuple or list of args to pass to reverse if `to` is a url name.\n to_kwargs: a dict of keyword args to pass to reverse if `to` is a url name.\n prepend_locale: if true the redirect URL will be prepended with the locale from the\n requested URL.\n merge_query: merge the requested query params from the `query` arg with any query params\n from the request.\n\n Usage:\n urlpatterns = [\n redirect(r\'projects/$\', \'mozorg.product\'),\n redirect(r\'^projects/seamonkey$\', \'mozorg.product\', locale_prefix=False),\n redirect(r\'apps/$\', \'https://marketplace.firefox.com\'),\n redirect(r\'firefox/$\', \'firefox.new\', name=\'firefox\'),\n redirect(r\'the/dude$\', \'abides\', query={\'aggression\': \'not_stand\'}),\n ]\n '
if permanent:
redirect_class = HttpResponsePermanentRedirect
else:
redirect_class = HttpResponseRedirect
if locale_prefix:
pattern = pattern.lstrip('^/')
pattern = (LOCALE_RE + pattern)
if re_flags:
pattern = ('(?{})'.format(re_flags) + pattern)
view_decorators = []
if (cache_timeout is not None):
view_decorators.append(cache_control_expires(cache_timeout))
if vary:
if isinstance(vary, basestring):
vary = [vary]
view_decorators.append(vary_on_headers(*vary))
if decorators:
if callable(decorators):
view_decorators.append(decorators)
else:
view_decorators.extend(decorators)
def _view(request, *args, **kwargs):
kwargs = {k: (v or ) for (k, v) in kwargs.items()}
args = [(x or ) for x in args]
if callable(to):
to_value = to(request, *args, **kwargs)
else:
to_value = to
if (to_value.startswith('/') or HTTP_RE.match(to_value)):
redirect_url = to_value
else:
try:
redirect_url = reverse(to_value, args=to_args, kwargs=to_kwargs)
except NoReverseMatch:
redirect_url = to_value
if (prepend_locale and redirect_url.startswith('/') and kwargs.get('locale')):
redirect_url = ('/{locale}' + redirect_url.lstrip('/'))
if (args or kwargs):
redirect_url = strip_tags(force_text(redirect_url).format(*args, **kwargs))
if query:
if merge_query:
req_query = parse_qs(request.META.get('QUERY_STRING'))
req_query.update(query)
querystring = urlencode(req_query, doseq=True)
else:
querystring = urlencode(query, doseq=True)
elif (query is None):
querystring = request.META.get('QUERY_STRING')
else:
querystring =
if querystring:
redirect_url = '?'.join([redirect_url, querystring])
if anchor:
redirect_url = '#'.join([redirect_url, anchor])
if PROTOCOL_RELATIVE_RE.match(redirect_url):
redirect_url = ('/' + redirect_url.lstrip('/'))
return redirect_class(redirect_url)
try:
for decorator in reversed(view_decorators):
_view = decorator(_view)
except TypeError:
log.exception('decorators not iterable or does not contain callable items')
return url(pattern, _view, name=name)<|docstring|>Return a url matcher suited for urlpatterns.
pattern: the regex against which to match the requested URL.
to: either a url name that `reverse` will find, a url that will simply be returned,
or a function that will be given the request and url captures, and return the
destination.
permanent: boolean whether to send a 301 or 302 response.
locale_prefix: automatically prepend `pattern` with a regex for an optional locale
in the url. This locale (or None) will show up in captured kwargs as 'locale'.
anchor: if set it will be appended to the destination url after a '#'.
name: if used in a `urls.py` the redirect URL will be available as the name
for use in calls to `reverse()`. Does _NOT_ work if used in a `redirects.py` file.
query: a dict of query params to add to the destination url.
vary: if you used an HTTP header to decide where to send users you should include that
header's name in the `vary` arg.
cache_timeout: number of hours to cache this redirect. just sets the proper `cache-control`
and `expires` headers.
decorators: a callable (or list of callables) that will wrap the view used to redirect
the user. equivalent to adding a decorator to any other view.
re_flags: a string of any of the characters: "iLmsux". Will modify the `pattern` regex
based on the documented meaning of the flags (see python re module docs).
to_args: a tuple or list of args to pass to reverse if `to` is a url name.
to_kwargs: a dict of keyword args to pass to reverse if `to` is a url name.
prepend_locale: if true the redirect URL will be prepended with the locale from the
requested URL.
merge_query: merge the requested query params from the `query` arg with any query params
from the request.
Usage:
urlpatterns = [
redirect(r'projects/$', 'mozorg.product'),
redirect(r'^projects/seamonkey$', 'mozorg.product', locale_prefix=False),
redirect(r'apps/$', 'https://marketplace.firefox.com'),
redirect(r'firefox/$', 'firefox.new', name='firefox'),
redirect(r'the/dude$', 'abides', query={'aggression': 'not_stand'}),
]<|endoftext|> |
b8ad842bb3e922cf7d908e6de196639a126068564c4d7d46ac2630c3de24be9f | def gone(pattern):
'Return a url matcher suitable for urlpatterns that returns a 410.'
return url(pattern, gone_view) | Return a url matcher suitable for urlpatterns that returns a 410. | redirect_urls/utils.py | gone | jayvdb/django-redirect-urls | 17 | python | def gone(pattern):
return url(pattern, gone_view) | def gone(pattern):
return url(pattern, gone_view)<|docstring|>Return a url matcher suitable for urlpatterns that returns a 410.<|endoftext|> |
0fc671c98af35f7fb754ef864aa05aa6f563817f84b54de12b10a89958322332 | def __init__(self, ht_id=None, **kwargs):
'\n Initialize HTCoreTeam instance\n\n :param ht_id: team Hattrick ID (if none, fetch the primary club of connected user), defaults to None\n :key chpp: CHPP instance of connected user\n :type ht_id: int, optional\n :type chpp: CHPP\n '
if ((not isinstance(ht_id, int)) and (ht_id is not None)):
raise ValueError('ht_id must be an integer')
super().__init__(**kwargs) | Initialize HTCoreTeam instance
:param ht_id: team Hattrick ID (if none, fetch the primary club of connected user), defaults to None
:key chpp: CHPP instance of connected user
:type ht_id: int, optional
:type chpp: CHPP | pychpp/ht_team.py | __init__ | DioPires/pychpp | 0 | python | def __init__(self, ht_id=None, **kwargs):
'\n Initialize HTCoreTeam instance\n\n :param ht_id: team Hattrick ID (if none, fetch the primary club of connected user), defaults to None\n :key chpp: CHPP instance of connected user\n :type ht_id: int, optional\n :type chpp: CHPP\n '
if ((not isinstance(ht_id, int)) and (ht_id is not None)):
raise ValueError('ht_id must be an integer')
super().__init__(**kwargs) | def __init__(self, ht_id=None, **kwargs):
'\n Initialize HTCoreTeam instance\n\n :param ht_id: team Hattrick ID (if none, fetch the primary club of connected user), defaults to None\n :key chpp: CHPP instance of connected user\n :type ht_id: int, optional\n :type chpp: CHPP\n '
if ((not isinstance(ht_id, int)) and (ht_id is not None)):
raise ValueError('ht_id must be an integer')
super().__init__(**kwargs)<|docstring|>Initialize HTCoreTeam instance
:param ht_id: team Hattrick ID (if none, fetch the primary club of connected user), defaults to None
:key chpp: CHPP instance of connected user
:type ht_id: int, optional
:type chpp: CHPP<|endoftext|> |
6432d3cdaee835770ed045c23807c04a6b9814b4bdc415be1493a675348d4807 | def __init__(self, **kwargs):
'\n Initialize HTTeam instance\n\n :key ht_id: team Hattrick ID (if none, fetch the primary club of connected user), defaults to None\n :key chpp: CHPP instance of connected user\n :type ht_id: int, optional\n :type chpp: CHPP\n '
self._REQUEST_ARGS = dict()
if (kwargs.get('ht_id', None) is not None):
self._REQUEST_ARGS['teamID'] = kwargs['ht_id']
super().__init__(**kwargs) | Initialize HTTeam instance
:key ht_id: team Hattrick ID (if none, fetch the primary club of connected user), defaults to None
:key chpp: CHPP instance of connected user
:type ht_id: int, optional
:type chpp: CHPP | pychpp/ht_team.py | __init__ | DioPires/pychpp | 0 | python | def __init__(self, **kwargs):
'\n Initialize HTTeam instance\n\n :key ht_id: team Hattrick ID (if none, fetch the primary club of connected user), defaults to None\n :key chpp: CHPP instance of connected user\n :type ht_id: int, optional\n :type chpp: CHPP\n '
self._REQUEST_ARGS = dict()
if (kwargs.get('ht_id', None) is not None):
self._REQUEST_ARGS['teamID'] = kwargs['ht_id']
super().__init__(**kwargs) | def __init__(self, **kwargs):
'\n Initialize HTTeam instance\n\n :key ht_id: team Hattrick ID (if none, fetch the primary club of connected user), defaults to None\n :key chpp: CHPP instance of connected user\n :type ht_id: int, optional\n :type chpp: CHPP\n '
self._REQUEST_ARGS = dict()
if (kwargs.get('ht_id', None) is not None):
self._REQUEST_ARGS['teamID'] = kwargs['ht_id']
super().__init__(**kwargs)<|docstring|>Initialize HTTeam instance
:key ht_id: team Hattrick ID (if none, fetch the primary club of connected user), defaults to None
:key chpp: CHPP instance of connected user
:type ht_id: int, optional
:type chpp: CHPP<|endoftext|> |
f71a5fcc62ada3b3bfd828a499f789b3d600c49efcd84adf51f9cb8451738c31 | @property
def user(self):
'Owner of the current team'
return ht_user.HTUser(chpp=self._chpp, ht_id=self.user_ht_id) | Owner of the current team | pychpp/ht_team.py | user | DioPires/pychpp | 0 | python | @property
def user(self):
return ht_user.HTUser(chpp=self._chpp, ht_id=self.user_ht_id) | @property
def user(self):
return ht_user.HTUser(chpp=self._chpp, ht_id=self.user_ht_id)<|docstring|>Owner of the current team<|endoftext|> |
e15496d9e2269bcabba3c3c2f1b78e19108ee6b6fb4775e05111278363f75ba3 | @property
def players(self):
'Players list of current team'
data = self._chpp.request(file='players', version='2.4', actionType='view', teamID=self.ht_id).find('Team').find('PlayerList')
return [ht_player.HTPlayer(chpp=self._chpp, data=p_data, team_ht_id=self.ht_id) for p_data in data.findall('Player')] | Players list of current team | pychpp/ht_team.py | players | DioPires/pychpp | 0 | python | @property
def players(self):
data = self._chpp.request(file='players', version='2.4', actionType='view', teamID=self.ht_id).find('Team').find('PlayerList')
return [ht_player.HTPlayer(chpp=self._chpp, data=p_data, team_ht_id=self.ht_id) for p_data in data.findall('Player')] | @property
def players(self):
data = self._chpp.request(file='players', version='2.4', actionType='view', teamID=self.ht_id).find('Team').find('PlayerList')
return [ht_player.HTPlayer(chpp=self._chpp, data=p_data, team_ht_id=self.ht_id) for p_data in data.findall('Player')]<|docstring|>Players list of current team<|endoftext|> |
7b9a65a8d36dec237c547731ebacf30ee8d81cc390ff1b256c25f9b5c5298c48 | @property
def youth_team(self):
'Youth team of current team'
return (HTYouthTeam(chpp=self._chpp, ht_id=self.youth_team_ht_id) if (self.youth_team_ht_id != 0) else None) | Youth team of current team | pychpp/ht_team.py | youth_team | DioPires/pychpp | 0 | python | @property
def youth_team(self):
return (HTYouthTeam(chpp=self._chpp, ht_id=self.youth_team_ht_id) if (self.youth_team_ht_id != 0) else None) | @property
def youth_team(self):
return (HTYouthTeam(chpp=self._chpp, ht_id=self.youth_team_ht_id) if (self.youth_team_ht_id != 0) else None)<|docstring|>Youth team of current team<|endoftext|> |
96fb59fba6fb592b0199083e9797f2b4d7a99d78243cbd97748e5f498d92491c | @property
def arena(self):
'Team arena'
return ht_arena.HTArena(chpp=self._chpp, ht_id=self.arena_ht_id) | Team arena | pychpp/ht_team.py | arena | DioPires/pychpp | 0 | python | @property
def arena(self):
return ht_arena.HTArena(chpp=self._chpp, ht_id=self.arena_ht_id) | @property
def arena(self):
return ht_arena.HTArena(chpp=self._chpp, ht_id=self.arena_ht_id)<|docstring|>Team arena<|endoftext|> |
0057996b335a8c770b8a9a5e36601978731fe0efb3ac2648b3725be0ba501a45 | def __init__(self, **kwargs):
'\n Initialize HTYouthTeam instance\n\n :key chpp: CHPP instance of connected user\n :key ht_id: team Hattrick ID (if none, fetch the primary club of connected user), defaults to None\n :type chpp: CHPP\n :type ht_id: int, optional\n '
self._REQUEST_ARGS = dict()
if (kwargs.get('ht_id', None) is not None):
self._REQUEST_ARGS['youthTeamId'] = kwargs['ht_id']
super().__init__(**kwargs) | Initialize HTYouthTeam instance
:key chpp: CHPP instance of connected user
:key ht_id: team Hattrick ID (if none, fetch the primary club of connected user), defaults to None
:type chpp: CHPP
:type ht_id: int, optional | pychpp/ht_team.py | __init__ | DioPires/pychpp | 0 | python | def __init__(self, **kwargs):
'\n Initialize HTYouthTeam instance\n\n :key chpp: CHPP instance of connected user\n :key ht_id: team Hattrick ID (if none, fetch the primary club of connected user), defaults to None\n :type chpp: CHPP\n :type ht_id: int, optional\n '
self._REQUEST_ARGS = dict()
if (kwargs.get('ht_id', None) is not None):
self._REQUEST_ARGS['youthTeamId'] = kwargs['ht_id']
super().__init__(**kwargs) | def __init__(self, **kwargs):
'\n Initialize HTYouthTeam instance\n\n :key chpp: CHPP instance of connected user\n :key ht_id: team Hattrick ID (if none, fetch the primary club of connected user), defaults to None\n :type chpp: CHPP\n :type ht_id: int, optional\n '
self._REQUEST_ARGS = dict()
if (kwargs.get('ht_id', None) is not None):
self._REQUEST_ARGS['youthTeamId'] = kwargs['ht_id']
super().__init__(**kwargs)<|docstring|>Initialize HTYouthTeam instance
:key chpp: CHPP instance of connected user
:key ht_id: team Hattrick ID (if none, fetch the primary club of connected user), defaults to None
:type chpp: CHPP
:type ht_id: int, optional<|endoftext|> |
170ccb843955bc31f0573ddc125df6e5528726e00e71a051d6f9f0492e712755 | @property
def players(self):
'Players list of current team'
data = self._chpp.request(file='youthplayerlist', version='2.4', actionType='details', youthTeamID=self.ht_id).find('PlayerList')
if (self._data is None):
self._fetch()
return [ht_player.HTYouthPlayer(chpp=self._chpp, data=p_data, team_ht_id=self.ht_id) for p_data in data.findall('YouthPlayer')] | Players list of current team | pychpp/ht_team.py | players | DioPires/pychpp | 0 | python | @property
def players(self):
data = self._chpp.request(file='youthplayerlist', version='2.4', actionType='details', youthTeamID=self.ht_id).find('PlayerList')
if (self._data is None):
self._fetch()
return [ht_player.HTYouthPlayer(chpp=self._chpp, data=p_data, team_ht_id=self.ht_id) for p_data in data.findall('YouthPlayer')] | @property
def players(self):
data = self._chpp.request(file='youthplayerlist', version='2.4', actionType='details', youthTeamID=self.ht_id).find('PlayerList')
if (self._data is None):
self._fetch()
return [ht_player.HTYouthPlayer(chpp=self._chpp, data=p_data, team_ht_id=self.ht_id) for p_data in data.findall('YouthPlayer')]<|docstring|>Players list of current team<|endoftext|> |
945ccc5490c3ec855768a48992751995d97389f29b025a154990a88e3022f698 | @memoized
def is_square(n: int) -> bool:
'Memoized wrapper for the is_square function.'
return seqs.is_square(n) | Memoized wrapper for the is_square function. | py/problem_086.py | is_square | curtislb/ProjectEuler | 0 | python | @memoized
def is_square(n: int) -> bool:
return seqs.is_square(n) | @memoized
def is_square(n: int) -> bool:
return seqs.is_square(n)<|docstring|>Memoized wrapper for the is_square function.<|endoftext|> |
6ecba08556567f2f60acefc78c509fedc80392e649cef5254138ff6bfd3f0b18 | @foreach_cnx()
def test_is_connected(self):
'Check connection to MySQL Server'
self.assertEqual(True, self.cnx.is_connected())
self.cnx.disconnect()
self.assertEqual(False, self.cnx.is_connected()) | Check connection to MySQL Server | database/support/mysql-connector-python-2.1.3/tests/test_abstracts.py | test_is_connected | aprilsanchez/ictf-framework | 110 | python | @foreach_cnx()
def test_is_connected(self):
self.assertEqual(True, self.cnx.is_connected())
self.cnx.disconnect()
self.assertEqual(False, self.cnx.is_connected()) | @foreach_cnx()
def test_is_connected(self):
self.assertEqual(True, self.cnx.is_connected())
self.cnx.disconnect()
self.assertEqual(False, self.cnx.is_connected())<|docstring|>Check connection to MySQL Server<|endoftext|> |
3a03e3a663cb0ce022c63c4aeaf88266d34285010fed449764a5b835b0c58d28 | def test():
'test the flickering leds effect'
leds = [KeyboardLed(number, indicator) for (number, indicator) in get_available_leds()]
import time
for i in range(3):
time.sleep(0.2)
flash_leds_synced(leds) | test the flickering leds effect | flashOnKeystroke.py | test | guywhataguy/keyboardleds | 0 | python | def test():
leds = [KeyboardLed(number, indicator) for (number, indicator) in get_available_leds()]
import time
for i in range(3):
time.sleep(0.2)
flash_leds_synced(leds) | def test():
leds = [KeyboardLed(number, indicator) for (number, indicator) in get_available_leds()]
import time
for i in range(3):
time.sleep(0.2)
flash_leds_synced(leds)<|docstring|>test the flickering leds effect<|endoftext|> |
142509aa634c1071986e30fbc873fcaf0521f04dfee17a0d5af69cd9d671cfc5 | def main():
'hook the keboard and flicker the led lights on keystrokes'
leds = [KeyboardLed(number, indicator) for (number, indicator) in get_available_leds()]
keyboard_hook = pyxhook.HookManager()
keyboard_hook.KeyDown = (lambda event: flash_leds_synced(leds))
keyboard_hook.HookKeyboard()
keyboard_hook.start() | hook the keboard and flicker the led lights on keystrokes | flashOnKeystroke.py | main | guywhataguy/keyboardleds | 0 | python | def main():
leds = [KeyboardLed(number, indicator) for (number, indicator) in get_available_leds()]
keyboard_hook = pyxhook.HookManager()
keyboard_hook.KeyDown = (lambda event: flash_leds_synced(leds))
keyboard_hook.HookKeyboard()
keyboard_hook.start() | def main():
leds = [KeyboardLed(number, indicator) for (number, indicator) in get_available_leds()]
keyboard_hook = pyxhook.HookManager()
keyboard_hook.KeyDown = (lambda event: flash_leds_synced(leds))
keyboard_hook.HookKeyboard()
keyboard_hook.start()<|docstring|>hook the keboard and flicker the led lights on keystrokes<|endoftext|> |
23927b6f5181a0dee9eb06cc55953b02538d5fe1d0d2f3aa3599a2f10ab4f4b8 | def adjusted_r2_score(y_true, y_pred, model):
' calculate adjusted R2\n Input:\n y_true: actual values\n y_pred: predicted values\n model: predictive model\n '
n = len(y_pred)
p = len(model.coef_)
if (p >= (n - 1)):
return 0
r2 = r2_score(y_true, y_pred)
return (1 - (((1 - r2) * (n - 1)) / ((n - p) - 1))) | calculate adjusted R2
Input:
y_true: actual values
y_pred: predicted values
model: predictive model | src/dmba/metric.py | adjusted_r2_score | gedeck/dmba | 29 | python | def adjusted_r2_score(y_true, y_pred, model):
' calculate adjusted R2\n Input:\n y_true: actual values\n y_pred: predicted values\n model: predictive model\n '
n = len(y_pred)
p = len(model.coef_)
if (p >= (n - 1)):
return 0
r2 = r2_score(y_true, y_pred)
return (1 - (((1 - r2) * (n - 1)) / ((n - p) - 1))) | def adjusted_r2_score(y_true, y_pred, model):
' calculate adjusted R2\n Input:\n y_true: actual values\n y_pred: predicted values\n model: predictive model\n '
n = len(y_pred)
p = len(model.coef_)
if (p >= (n - 1)):
return 0
r2 = r2_score(y_true, y_pred)
return (1 - (((1 - r2) * (n - 1)) / ((n - p) - 1)))<|docstring|>calculate adjusted R2
Input:
y_true: actual values
y_pred: predicted values
model: predictive model<|endoftext|> |
aa3ff6cfef996c7c1cc66e7fa181e4509138e8d4436e73e330be2991768a255b | def AIC_score(y_true, y_pred, model=None, df=None):
' calculate Akaike Information Criterion (AIC) \n Input:\n y_true: actual values\n y_pred: predicted values\n model (optional): predictive model\n df (optional): degrees of freedom of model\n\n One of model or df is requried\n '
if ((df is None) and (model is None)):
raise ValueError('You need to provide either model or df')
n = len(y_pred)
p = ((len(model.coef_) + 1) if (df is None) else df)
resid = (np.array(y_true) - np.array(y_pred))
sse = np.sum((resid ** 2))
constant = (n + (n * np.log((2 * np.pi))))
return (((n * math.log((sse / n))) + constant) + (2 * (p + 1))) | calculate Akaike Information Criterion (AIC)
Input:
y_true: actual values
y_pred: predicted values
model (optional): predictive model
df (optional): degrees of freedom of model
One of model or df is requried | src/dmba/metric.py | AIC_score | gedeck/dmba | 29 | python | def AIC_score(y_true, y_pred, model=None, df=None):
' calculate Akaike Information Criterion (AIC) \n Input:\n y_true: actual values\n y_pred: predicted values\n model (optional): predictive model\n df (optional): degrees of freedom of model\n\n One of model or df is requried\n '
if ((df is None) and (model is None)):
raise ValueError('You need to provide either model or df')
n = len(y_pred)
p = ((len(model.coef_) + 1) if (df is None) else df)
resid = (np.array(y_true) - np.array(y_pred))
sse = np.sum((resid ** 2))
constant = (n + (n * np.log((2 * np.pi))))
return (((n * math.log((sse / n))) + constant) + (2 * (p + 1))) | def AIC_score(y_true, y_pred, model=None, df=None):
' calculate Akaike Information Criterion (AIC) \n Input:\n y_true: actual values\n y_pred: predicted values\n model (optional): predictive model\n df (optional): degrees of freedom of model\n\n One of model or df is requried\n '
if ((df is None) and (model is None)):
raise ValueError('You need to provide either model or df')
n = len(y_pred)
p = ((len(model.coef_) + 1) if (df is None) else df)
resid = (np.array(y_true) - np.array(y_pred))
sse = np.sum((resid ** 2))
constant = (n + (n * np.log((2 * np.pi))))
return (((n * math.log((sse / n))) + constant) + (2 * (p + 1)))<|docstring|>calculate Akaike Information Criterion (AIC)
Input:
y_true: actual values
y_pred: predicted values
model (optional): predictive model
df (optional): degrees of freedom of model
One of model or df is requried<|endoftext|> |
4a5a8b2fdc602a0b572ef2cf9a275b6edb182df61be4d0ddf2785b61c0c76333 | def BIC_score(y_true, y_pred, model=None, df=None):
" calculate Schwartz's Bayesian Information Criterion (AIC) \n Input:\n y_true: actual values\n y_pred: predicted values\n model: predictive model\n df (optional): degrees of freedom of model\n "
aic = AIC_score(y_true, y_pred, model=model, df=df)
p = ((len(model.coef_) + 1) if (df is None) else df)
n = len(y_pred)
return ((aic - (2 * (p + 1))) + (math.log(n) * (p + 1))) | calculate Schwartz's Bayesian Information Criterion (AIC)
Input:
y_true: actual values
y_pred: predicted values
model: predictive model
df (optional): degrees of freedom of model | src/dmba/metric.py | BIC_score | gedeck/dmba | 29 | python | def BIC_score(y_true, y_pred, model=None, df=None):
" calculate Schwartz's Bayesian Information Criterion (AIC) \n Input:\n y_true: actual values\n y_pred: predicted values\n model: predictive model\n df (optional): degrees of freedom of model\n "
aic = AIC_score(y_true, y_pred, model=model, df=df)
p = ((len(model.coef_) + 1) if (df is None) else df)
n = len(y_pred)
return ((aic - (2 * (p + 1))) + (math.log(n) * (p + 1))) | def BIC_score(y_true, y_pred, model=None, df=None):
" calculate Schwartz's Bayesian Information Criterion (AIC) \n Input:\n y_true: actual values\n y_pred: predicted values\n model: predictive model\n df (optional): degrees of freedom of model\n "
aic = AIC_score(y_true, y_pred, model=model, df=df)
p = ((len(model.coef_) + 1) if (df is None) else df)
n = len(y_pred)
return ((aic - (2 * (p + 1))) + (math.log(n) * (p + 1)))<|docstring|>calculate Schwartz's Bayesian Information Criterion (AIC)
Input:
y_true: actual values
y_pred: predicted values
model: predictive model
df (optional): degrees of freedom of model<|endoftext|> |
3f63cee1b6312b272833a91ecfde1cdddb622abbb09f61ca1b49fec0278382da | def regressionSummary(y_true, y_pred):
' print regression performance metrics \n\n Input:\n y_true: actual values\n y_pred: predicted values\n '
y_true = _toArray(y_true)
y_pred = _toArray(y_pred)
y_res = (y_true - y_pred)
metrics = [('Mean Error (ME)', (sum(y_res) / len(y_res))), ('Root Mean Squared Error (RMSE)', math.sqrt(mean_squared_error(y_true, y_pred))), ('Mean Absolute Error (MAE)', (sum(abs(y_res)) / len(y_res)))]
if all(((yt != 0) for yt in y_true)):
metrics.extend([('Mean Percentage Error (MPE)', ((100 * sum((y_res / y_true))) / len(y_res))), ('Mean Absolute Percentage Error (MAPE)', (100 * sum((abs((y_res / y_true)) / len(y_res)))))])
fmt1 = '{{:>{}}} : {{:.4f}}'.format(max((len(m[0]) for m in metrics)))
print('\nRegression statistics\n')
for (metric, value) in metrics:
print(fmt1.format(metric, value)) | print regression performance metrics
Input:
y_true: actual values
y_pred: predicted values | src/dmba/metric.py | regressionSummary | gedeck/dmba | 29 | python | def regressionSummary(y_true, y_pred):
' print regression performance metrics \n\n Input:\n y_true: actual values\n y_pred: predicted values\n '
y_true = _toArray(y_true)
y_pred = _toArray(y_pred)
y_res = (y_true - y_pred)
metrics = [('Mean Error (ME)', (sum(y_res) / len(y_res))), ('Root Mean Squared Error (RMSE)', math.sqrt(mean_squared_error(y_true, y_pred))), ('Mean Absolute Error (MAE)', (sum(abs(y_res)) / len(y_res)))]
if all(((yt != 0) for yt in y_true)):
metrics.extend([('Mean Percentage Error (MPE)', ((100 * sum((y_res / y_true))) / len(y_res))), ('Mean Absolute Percentage Error (MAPE)', (100 * sum((abs((y_res / y_true)) / len(y_res)))))])
fmt1 = '{{:>{}}} : {{:.4f}}'.format(max((len(m[0]) for m in metrics)))
print('\nRegression statistics\n')
for (metric, value) in metrics:
print(fmt1.format(metric, value)) | def regressionSummary(y_true, y_pred):
' print regression performance metrics \n\n Input:\n y_true: actual values\n y_pred: predicted values\n '
y_true = _toArray(y_true)
y_pred = _toArray(y_pred)
y_res = (y_true - y_pred)
metrics = [('Mean Error (ME)', (sum(y_res) / len(y_res))), ('Root Mean Squared Error (RMSE)', math.sqrt(mean_squared_error(y_true, y_pred))), ('Mean Absolute Error (MAE)', (sum(abs(y_res)) / len(y_res)))]
if all(((yt != 0) for yt in y_true)):
metrics.extend([('Mean Percentage Error (MPE)', ((100 * sum((y_res / y_true))) / len(y_res))), ('Mean Absolute Percentage Error (MAPE)', (100 * sum((abs((y_res / y_true)) / len(y_res)))))])
fmt1 = '{{:>{}}} : {{:.4f}}'.format(max((len(m[0]) for m in metrics)))
print('\nRegression statistics\n')
for (metric, value) in metrics:
print(fmt1.format(metric, value))<|docstring|>print regression performance metrics
Input:
y_true: actual values
y_pred: predicted values<|endoftext|> |
6ab3a7b84783f29b23c9e286b7c165059ed75d68058368665825f4f1e912f328 | def classificationSummary(y_true, y_pred, class_names=None):
' Print a summary of classification performance\n\n Input:\n y_true: actual values\n y_pred: predicted values\n class_names (optional): list of class names\n '
confusionMatrix = confusion_matrix(y_true, y_pred)
accuracy = accuracy_score(y_true, y_pred)
print('Confusion Matrix (Accuracy {:.4f})\n'.format(accuracy))
cm = confusionMatrix
labels = class_names
if (labels is None):
labels = [str(i) for i in range(len(cm))]
cm = [[str(i) for i in row] for row in cm]
labels = [str(i) for i in labels]
prediction = 'Prediction'
actual = 'Actual'
labelWidth = max((len(s) for s in labels))
cmWidth = (max(max((len(s) for row in cm for s in row)), labelWidth) + 1)
labelWidth = max(labelWidth, len(actual))
fmt1 = '{{:>{}}}'.format(labelWidth)
fmt2 = ('{{:>{}}}'.format(cmWidth) * len(labels))
print(((fmt1.format(' ') + ' ') + prediction))
print(fmt1.format(actual), end='')
print(fmt2.format(*labels))
for (cls, row) in zip(labels, cm):
print(fmt1.format(cls), end='')
print(fmt2.format(*row)) | Print a summary of classification performance
Input:
y_true: actual values
y_pred: predicted values
class_names (optional): list of class names | src/dmba/metric.py | classificationSummary | gedeck/dmba | 29 | python | def classificationSummary(y_true, y_pred, class_names=None):
' Print a summary of classification performance\n\n Input:\n y_true: actual values\n y_pred: predicted values\n class_names (optional): list of class names\n '
confusionMatrix = confusion_matrix(y_true, y_pred)
accuracy = accuracy_score(y_true, y_pred)
print('Confusion Matrix (Accuracy {:.4f})\n'.format(accuracy))
cm = confusionMatrix
labels = class_names
if (labels is None):
labels = [str(i) for i in range(len(cm))]
cm = [[str(i) for i in row] for row in cm]
labels = [str(i) for i in labels]
prediction = 'Prediction'
actual = 'Actual'
labelWidth = max((len(s) for s in labels))
cmWidth = (max(max((len(s) for row in cm for s in row)), labelWidth) + 1)
labelWidth = max(labelWidth, len(actual))
fmt1 = '{{:>{}}}'.format(labelWidth)
fmt2 = ('{{:>{}}}'.format(cmWidth) * len(labels))
print(((fmt1.format(' ') + ' ') + prediction))
print(fmt1.format(actual), end=)
print(fmt2.format(*labels))
for (cls, row) in zip(labels, cm):
print(fmt1.format(cls), end=)
print(fmt2.format(*row)) | def classificationSummary(y_true, y_pred, class_names=None):
' Print a summary of classification performance\n\n Input:\n y_true: actual values\n y_pred: predicted values\n class_names (optional): list of class names\n '
confusionMatrix = confusion_matrix(y_true, y_pred)
accuracy = accuracy_score(y_true, y_pred)
print('Confusion Matrix (Accuracy {:.4f})\n'.format(accuracy))
cm = confusionMatrix
labels = class_names
if (labels is None):
labels = [str(i) for i in range(len(cm))]
cm = [[str(i) for i in row] for row in cm]
labels = [str(i) for i in labels]
prediction = 'Prediction'
actual = 'Actual'
labelWidth = max((len(s) for s in labels))
cmWidth = (max(max((len(s) for row in cm for s in row)), labelWidth) + 1)
labelWidth = max(labelWidth, len(actual))
fmt1 = '{{:>{}}}'.format(labelWidth)
fmt2 = ('{{:>{}}}'.format(cmWidth) * len(labels))
print(((fmt1.format(' ') + ' ') + prediction))
print(fmt1.format(actual), end=)
print(fmt2.format(*labels))
for (cls, row) in zip(labels, cm):
print(fmt1.format(cls), end=)
print(fmt2.format(*row))<|docstring|>Print a summary of classification performance
Input:
y_true: actual values
y_pred: predicted values
class_names (optional): list of class names<|endoftext|> |
dbe0a1266360ce07dcbf0b5a3e1c6d0ca9276e8520fc234fd20a9da30a94fd84 | def load_meteorol(timeslots, fname=os.path.join(DATAPATH, 'TaxiBJ', 'BJ_Meteorology.h5')):
'\n timeslots: the predicted timeslots\n In real-world, we dont have the meteorol data in the predicted timeslot, instead, we use the meteoral at previous timeslots, i.e., slot = predicted_slot - timeslot (you can use predicted meteorol data as well)\n '
f = h5py.File(fname, 'r')
Timeslot = f['date'].value
WindSpeed = f['WindSpeed'].value
Weather = f['Weather'].value
Temperature = f['Temperature'].value
f.close()
M = dict()
for (i, slot) in enumerate(Timeslot):
M[slot] = i
WS = []
WR = []
TE = []
for slot in timeslots:
predicted_id = M[slot]
cur_id = (predicted_id - 1)
WS.append(WindSpeed[cur_id])
WR.append(Weather[cur_id])
TE.append(Temperature[cur_id])
WS = np.asarray(WS)
WR = np.asarray(WR)
TE = np.asarray(TE)
WS = ((1.0 * (WS - WS.min())) / (WS.max() - WS.min()))
TE = ((1.0 * (TE - TE.min())) / (TE.max() - TE.min()))
print('shape: ', WS.shape, WR.shape, TE.shape)
merge_data = np.hstack([WR, WS[(:, None)], TE[(:, None)]])
return merge_data | timeslots: the predicted timeslots
In real-world, we dont have the meteorol data in the predicted timeslot, instead, we use the meteoral at previous timeslots, i.e., slot = predicted_slot - timeslot (you can use predicted meteorol data as well) | deepst/datasets/TaxiBJ.py | load_meteorol | gunarto90/DeepST | 29 | python | def load_meteorol(timeslots, fname=os.path.join(DATAPATH, 'TaxiBJ', 'BJ_Meteorology.h5')):
'\n timeslots: the predicted timeslots\n In real-world, we dont have the meteorol data in the predicted timeslot, instead, we use the meteoral at previous timeslots, i.e., slot = predicted_slot - timeslot (you can use predicted meteorol data as well)\n '
f = h5py.File(fname, 'r')
Timeslot = f['date'].value
WindSpeed = f['WindSpeed'].value
Weather = f['Weather'].value
Temperature = f['Temperature'].value
f.close()
M = dict()
for (i, slot) in enumerate(Timeslot):
M[slot] = i
WS = []
WR = []
TE = []
for slot in timeslots:
predicted_id = M[slot]
cur_id = (predicted_id - 1)
WS.append(WindSpeed[cur_id])
WR.append(Weather[cur_id])
TE.append(Temperature[cur_id])
WS = np.asarray(WS)
WR = np.asarray(WR)
TE = np.asarray(TE)
WS = ((1.0 * (WS - WS.min())) / (WS.max() - WS.min()))
TE = ((1.0 * (TE - TE.min())) / (TE.max() - TE.min()))
print('shape: ', WS.shape, WR.shape, TE.shape)
merge_data = np.hstack([WR, WS[(:, None)], TE[(:, None)]])
return merge_data | def load_meteorol(timeslots, fname=os.path.join(DATAPATH, 'TaxiBJ', 'BJ_Meteorology.h5')):
'\n timeslots: the predicted timeslots\n In real-world, we dont have the meteorol data in the predicted timeslot, instead, we use the meteoral at previous timeslots, i.e., slot = predicted_slot - timeslot (you can use predicted meteorol data as well)\n '
f = h5py.File(fname, 'r')
Timeslot = f['date'].value
WindSpeed = f['WindSpeed'].value
Weather = f['Weather'].value
Temperature = f['Temperature'].value
f.close()
M = dict()
for (i, slot) in enumerate(Timeslot):
M[slot] = i
WS = []
WR = []
TE = []
for slot in timeslots:
predicted_id = M[slot]
cur_id = (predicted_id - 1)
WS.append(WindSpeed[cur_id])
WR.append(Weather[cur_id])
TE.append(Temperature[cur_id])
WS = np.asarray(WS)
WR = np.asarray(WR)
TE = np.asarray(TE)
WS = ((1.0 * (WS - WS.min())) / (WS.max() - WS.min()))
TE = ((1.0 * (TE - TE.min())) / (TE.max() - TE.min()))
print('shape: ', WS.shape, WR.shape, TE.shape)
merge_data = np.hstack([WR, WS[(:, None)], TE[(:, None)]])
return merge_data<|docstring|>timeslots: the predicted timeslots
In real-world, we dont have the meteorol data in the predicted timeslot, instead, we use the meteoral at previous timeslots, i.e., slot = predicted_slot - timeslot (you can use predicted meteorol data as well)<|endoftext|> |
3503f18d28b84ba31ccf2f8535a5e21673985637dc08530d2224413b614d4712 | def _generate_model(self):
'to generate the bounding boxes'
weights_path = os.path.expanduser(self.weights_path)
assert weights_path.endswith('.h5'), 'Keras model or weights must be a .h5 file.'
num_classes = len(self.class_names)
if (self.tiny is True):
self.num_channels = 128
hourglass_model = get_hourglass_model(num_classes, self.num_stacks, self.num_channels, model_input_shape=self.model_input_shape, mobile=self.mobile)
hourglass_model.load_weights(weights_path, by_name=False)
hourglass_model.summary()
return hourglass_model | to generate the bounding boxes | multi_person_demo.py | _generate_model | david8862/tf-keras-stacked-hourglass-keypoint-detection | 17 | python | def _generate_model(self):
weights_path = os.path.expanduser(self.weights_path)
assert weights_path.endswith('.h5'), 'Keras model or weights must be a .h5 file.'
num_classes = len(self.class_names)
if (self.tiny is True):
self.num_channels = 128
hourglass_model = get_hourglass_model(num_classes, self.num_stacks, self.num_channels, model_input_shape=self.model_input_shape, mobile=self.mobile)
hourglass_model.load_weights(weights_path, by_name=False)
hourglass_model.summary()
return hourglass_model | def _generate_model(self):
weights_path = os.path.expanduser(self.weights_path)
assert weights_path.endswith('.h5'), 'Keras model or weights must be a .h5 file.'
num_classes = len(self.class_names)
if (self.tiny is True):
self.num_channels = 128
hourglass_model = get_hourglass_model(num_classes, self.num_stacks, self.num_channels, model_input_shape=self.model_input_shape, mobile=self.mobile)
hourglass_model.load_weights(weights_path, by_name=False)
hourglass_model.summary()
return hourglass_model<|docstring|>to generate the bounding boxes<|endoftext|> |
86ab8ba2e9507c1f60a1718d75e4c4da08995ff8ef154c990ae9c759b62c5e99 | def get_square_box(self, box, image_size):
'expand person bbox to square, for further keypoint input'
(xmin, ymin, xmax, ymax) = map(int, box)
center_x = ((xmin + xmax) // 2)
center_y = ((ymin + ymax) // 2)
length = max((xmax - xmin), (ymax - ymin))
square_xmin = max((center_x - (length // 2)), 0)
square_xmax = min((center_x + (length // 2)), image_size[0])
square_ymin = max((center_y - (length // 2)), 0)
square_ymax = min((center_y + (length // 2)), image_size[1])
return (square_xmin, square_ymin, square_xmax, square_ymax) | expand person bbox to square, for further keypoint input | multi_person_demo.py | get_square_box | david8862/tf-keras-stacked-hourglass-keypoint-detection | 17 | python | def get_square_box(self, box, image_size):
(xmin, ymin, xmax, ymax) = map(int, box)
center_x = ((xmin + xmax) // 2)
center_y = ((ymin + ymax) // 2)
length = max((xmax - xmin), (ymax - ymin))
square_xmin = max((center_x - (length // 2)), 0)
square_xmax = min((center_x + (length // 2)), image_size[0])
square_ymin = max((center_y - (length // 2)), 0)
square_ymax = min((center_y + (length // 2)), image_size[1])
return (square_xmin, square_ymin, square_xmax, square_ymax) | def get_square_box(self, box, image_size):
(xmin, ymin, xmax, ymax) = map(int, box)
center_x = ((xmin + xmax) // 2)
center_y = ((ymin + ymax) // 2)
length = max((xmax - xmin), (ymax - ymin))
square_xmin = max((center_x - (length // 2)), 0)
square_xmax = min((center_x + (length // 2)), image_size[0])
square_ymin = max((center_y - (length // 2)), 0)
square_ymax = min((center_y + (length // 2)), image_size[1])
return (square_xmin, square_ymin, square_xmax, square_ymax)<|docstring|>expand person bbox to square, for further keypoint input<|endoftext|> |
eecd136b2a9e22f79c7f01d6f025bb535403abd99dcb25a1082dc841b73f0d0a | def detect_image_batch(self, image):
'\n run batch inference on keypoint model for multi person inputs\n '
image_array = np.array(image, dtype='uint8')
start = time.time()
(person_boxes, person_scores) = detect_person(image, self.det_model, self.det_anchors, self.det_class_names, self.det_model_input_shape)
batch_image_data = []
batch_scale = []
batch_raw_box = []
batch_box = []
for (box, score) in zip(person_boxes, person_scores):
(raw_xmin, raw_ymin, raw_xmax, raw_ymax) = map(int, box)
(xmin, ymin, xmax, ymax) = self.get_square_box(box, image.size)
person_image = Image.fromarray(image_array[(ymin:ymax, xmin:xmax)])
person_array = np.array(person_image, dtype='uint8')
image_data = preprocess_image(person_image, self.model_input_shape)
image_size = person_image.size
scale = (((image_size[0] * 1.0) / self.model_input_shape[1]), ((image_size[1] * 1.0) / self.model_input_shape[0]))
batch_scale.append(scale)
batch_raw_box.append((raw_xmin, raw_ymin, raw_xmax, raw_ymax))
batch_box.append((xmin, ymin, xmax, ymax))
batch_image_data.append(image_data[0])
if (len(batch_image_data) == 0):
return Image.fromarray(image_array)
batch_image_data = np.array(batch_image_data)
batch_keypoints = self.batch_predict(batch_image_data)
for (i, keypoints) in enumerate(batch_keypoints):
scale = batch_scale[i]
(raw_xmin, raw_ymin, raw_xmax, raw_ymax) = batch_raw_box[i]
(xmin, ymin, xmax, ymax) = batch_box[i]
keypoints_dict = dict()
for (j, keypoint) in enumerate(keypoints):
keypoints_dict[self.class_names[j]] = ((((keypoint[0] * scale[0]) * HG_OUTPUT_STRIDE) + xmin), (((keypoint[1] * scale[1]) * HG_OUTPUT_STRIDE) + ymin), keypoint[2])
cv2.rectangle(image_array, (raw_xmin, raw_ymin), (raw_xmax, raw_ymax), (255, 0, 0), 1, cv2.LINE_AA)
image_array = render_skeleton(image_array, keypoints_dict, self.skeleton_lines, self.conf_threshold)
end = time.time()
print('Inference time: {:.8f}s'.format((end - start)))
return Image.fromarray(image_array) | run batch inference on keypoint model for multi person inputs | multi_person_demo.py | detect_image_batch | david8862/tf-keras-stacked-hourglass-keypoint-detection | 17 | python | def detect_image_batch(self, image):
'\n \n '
image_array = np.array(image, dtype='uint8')
start = time.time()
(person_boxes, person_scores) = detect_person(image, self.det_model, self.det_anchors, self.det_class_names, self.det_model_input_shape)
batch_image_data = []
batch_scale = []
batch_raw_box = []
batch_box = []
for (box, score) in zip(person_boxes, person_scores):
(raw_xmin, raw_ymin, raw_xmax, raw_ymax) = map(int, box)
(xmin, ymin, xmax, ymax) = self.get_square_box(box, image.size)
person_image = Image.fromarray(image_array[(ymin:ymax, xmin:xmax)])
person_array = np.array(person_image, dtype='uint8')
image_data = preprocess_image(person_image, self.model_input_shape)
image_size = person_image.size
scale = (((image_size[0] * 1.0) / self.model_input_shape[1]), ((image_size[1] * 1.0) / self.model_input_shape[0]))
batch_scale.append(scale)
batch_raw_box.append((raw_xmin, raw_ymin, raw_xmax, raw_ymax))
batch_box.append((xmin, ymin, xmax, ymax))
batch_image_data.append(image_data[0])
if (len(batch_image_data) == 0):
return Image.fromarray(image_array)
batch_image_data = np.array(batch_image_data)
batch_keypoints = self.batch_predict(batch_image_data)
for (i, keypoints) in enumerate(batch_keypoints):
scale = batch_scale[i]
(raw_xmin, raw_ymin, raw_xmax, raw_ymax) = batch_raw_box[i]
(xmin, ymin, xmax, ymax) = batch_box[i]
keypoints_dict = dict()
for (j, keypoint) in enumerate(keypoints):
keypoints_dict[self.class_names[j]] = ((((keypoint[0] * scale[0]) * HG_OUTPUT_STRIDE) + xmin), (((keypoint[1] * scale[1]) * HG_OUTPUT_STRIDE) + ymin), keypoint[2])
cv2.rectangle(image_array, (raw_xmin, raw_ymin), (raw_xmax, raw_ymax), (255, 0, 0), 1, cv2.LINE_AA)
image_array = render_skeleton(image_array, keypoints_dict, self.skeleton_lines, self.conf_threshold)
end = time.time()
print('Inference time: {:.8f}s'.format((end - start)))
return Image.fromarray(image_array) | def detect_image_batch(self, image):
'\n \n '
image_array = np.array(image, dtype='uint8')
start = time.time()
(person_boxes, person_scores) = detect_person(image, self.det_model, self.det_anchors, self.det_class_names, self.det_model_input_shape)
batch_image_data = []
batch_scale = []
batch_raw_box = []
batch_box = []
for (box, score) in zip(person_boxes, person_scores):
(raw_xmin, raw_ymin, raw_xmax, raw_ymax) = map(int, box)
(xmin, ymin, xmax, ymax) = self.get_square_box(box, image.size)
person_image = Image.fromarray(image_array[(ymin:ymax, xmin:xmax)])
person_array = np.array(person_image, dtype='uint8')
image_data = preprocess_image(person_image, self.model_input_shape)
image_size = person_image.size
scale = (((image_size[0] * 1.0) / self.model_input_shape[1]), ((image_size[1] * 1.0) / self.model_input_shape[0]))
batch_scale.append(scale)
batch_raw_box.append((raw_xmin, raw_ymin, raw_xmax, raw_ymax))
batch_box.append((xmin, ymin, xmax, ymax))
batch_image_data.append(image_data[0])
if (len(batch_image_data) == 0):
return Image.fromarray(image_array)
batch_image_data = np.array(batch_image_data)
batch_keypoints = self.batch_predict(batch_image_data)
for (i, keypoints) in enumerate(batch_keypoints):
scale = batch_scale[i]
(raw_xmin, raw_ymin, raw_xmax, raw_ymax) = batch_raw_box[i]
(xmin, ymin, xmax, ymax) = batch_box[i]
keypoints_dict = dict()
for (j, keypoint) in enumerate(keypoints):
keypoints_dict[self.class_names[j]] = ((((keypoint[0] * scale[0]) * HG_OUTPUT_STRIDE) + xmin), (((keypoint[1] * scale[1]) * HG_OUTPUT_STRIDE) + ymin), keypoint[2])
cv2.rectangle(image_array, (raw_xmin, raw_ymin), (raw_xmax, raw_ymax), (255, 0, 0), 1, cv2.LINE_AA)
image_array = render_skeleton(image_array, keypoints_dict, self.skeleton_lines, self.conf_threshold)
end = time.time()
print('Inference time: {:.8f}s'.format((end - start)))
return Image.fromarray(image_array)<|docstring|>run batch inference on keypoint model for multi person inputs<|endoftext|> |
d550ae03e57b3214d10bc3750cdeebf0ff9c950ff464e58c0c71d404ec303cbf | def check_samplesheet(file_in, file_out):
'\n This function checks that the samplesheet follows the following structure:\n sample,fastq1,fastq2,bam,bai,gff,fasta,bed,mart_export\n '
input_extensions = []
sample_info_list = []
with open(file_in, 'r') as fin:
MIN_COLS = 8
HEADER = ['sample', 'fastq1', 'fastq2', 'bam', 'bai', 'gff', 'fasta', 'bed', 'mart_export']
header = fin.readline().strip().split(',')
if (header[:len(HEADER)] != HEADER):
print('ERROR: Please check samplesheet header -> {} != {}'.format(','.join(header), ','.join(HEADER)))
sys.exit(1)
for line in fin:
lspl = [x.strip() for x in line.strip().split(',')]
if (len(lspl) < len(HEADER)):
print_error('Invalid number of columns (minimum = {})!'.format(len(HEADER)), 'Line', line)
num_cols = len([x for x in lspl if x])
if (num_cols < MIN_COLS):
print_error('Invalid number of populated columns (minimum = {})!'.format(MIN_COLS), 'Line', line)
(sample, fastq1, fastq2, bam, bai, gff, fasta, bed, mart_export) = lspl[:len(HEADER)]
if sample:
if (sample.find(' ') != (- 1)):
print_error('Sample entry contains spaces!', 'Line', line)
else:
print_error('Sample entry has not been specified!', 'Line', line)
if fastq1:
if (fastq1.find(' ') != (- 1)):
print_error('fastq1 contains spaces!', 'Line', line)
if ((not fastq1.endswith('.fastq')) and (not fastq1.endswith('.fastq.gz'))):
print_error("fastq1 does not have extension '.fastq' or '.fastq.gz'", 'Line', line)
if fastq2:
if (fastq2.find(' ') != (- 1)):
print_error('fastq2 contains spaces!', 'Line', line)
if ((not fastq2.endswith('.fastq')) and (not fastq2.endswith('.fastq.gz'))):
print_error("fastq2 does not have extension '.fastq' or '.fastq.gz'", 'Line', line)
if bam:
if (bam.find(' ') != (- 1)):
print_error('bam contains spaces!', 'Line', line)
if (not bam.endswith('.bam')):
print_error("bam does not have extension 'bam'", 'Line', line)
if gff:
if (gff.find(' ') != (- 1)):
print_error('gff contains spaces!', 'Line', line)
if (not gff.endswith('.gff3')):
print_error("gff does not have extension '.gff3'", 'Line', line)
if fasta:
if (fasta.find(' ') != (- 1)):
print_error('fasta entry contains spaces!', 'Line', line)
if (len(fasta.split('.')) > 1):
if ((fasta[(- 6):] != '.fasta') and (fasta[(- 3):] != '.fa') and (fasta[(- 9):] != '.fasta.gz') and (fasta[(- 6):] != '.fa.gz')):
print_error("Genome entry does not have extension '.fasta', '.fa', '.fasta.gz' or '.fa.gz'!", 'Line', line)
if bed:
if (bed.find(' ') != (- 1)):
print_error('bed contains spaces!', 'Line', line)
if (not bed.endswith('.bed')):
print_error("bed does not have extension '.bed'", 'Line', line)
sample_info = [sample, fastq1, fastq2, bam, bai, gff, fasta, bed, mart_export]
sample_info_list.append(sample_info)
if (len(sample_info_list) > 0):
out_dir = os.path.dirname(file_out)
make_dir(out_dir)
with open(file_out, 'w') as fout:
fout.write((','.join(['sample', 'fastq1', 'fastq2', 'bam', 'bai', 'gff', 'fasta', 'bed', 'mart_export']) + '\n'))
for sample_info in sample_info_list:
fout.write((','.join(sample_info) + '\n')) | This function checks that the samplesheet follows the following structure:
sample,fastq1,fastq2,bam,bai,gff,fasta,bed,mart_export | tests/pilot_benchmark/nextflow_dsl2/bin/check_samplesheet.py | check_samplesheet | chilampoon/APAeval | 9 | python | def check_samplesheet(file_in, file_out):
'\n This function checks that the samplesheet follows the following structure:\n sample,fastq1,fastq2,bam,bai,gff,fasta,bed,mart_export\n '
input_extensions = []
sample_info_list = []
with open(file_in, 'r') as fin:
MIN_COLS = 8
HEADER = ['sample', 'fastq1', 'fastq2', 'bam', 'bai', 'gff', 'fasta', 'bed', 'mart_export']
header = fin.readline().strip().split(',')
if (header[:len(HEADER)] != HEADER):
print('ERROR: Please check samplesheet header -> {} != {}'.format(','.join(header), ','.join(HEADER)))
sys.exit(1)
for line in fin:
lspl = [x.strip() for x in line.strip().split(',')]
if (len(lspl) < len(HEADER)):
print_error('Invalid number of columns (minimum = {})!'.format(len(HEADER)), 'Line', line)
num_cols = len([x for x in lspl if x])
if (num_cols < MIN_COLS):
print_error('Invalid number of populated columns (minimum = {})!'.format(MIN_COLS), 'Line', line)
(sample, fastq1, fastq2, bam, bai, gff, fasta, bed, mart_export) = lspl[:len(HEADER)]
if sample:
if (sample.find(' ') != (- 1)):
print_error('Sample entry contains spaces!', 'Line', line)
else:
print_error('Sample entry has not been specified!', 'Line', line)
if fastq1:
if (fastq1.find(' ') != (- 1)):
print_error('fastq1 contains spaces!', 'Line', line)
if ((not fastq1.endswith('.fastq')) and (not fastq1.endswith('.fastq.gz'))):
print_error("fastq1 does not have extension '.fastq' or '.fastq.gz'", 'Line', line)
if fastq2:
if (fastq2.find(' ') != (- 1)):
print_error('fastq2 contains spaces!', 'Line', line)
if ((not fastq2.endswith('.fastq')) and (not fastq2.endswith('.fastq.gz'))):
print_error("fastq2 does not have extension '.fastq' or '.fastq.gz'", 'Line', line)
if bam:
if (bam.find(' ') != (- 1)):
print_error('bam contains spaces!', 'Line', line)
if (not bam.endswith('.bam')):
print_error("bam does not have extension 'bam'", 'Line', line)
if gff:
if (gff.find(' ') != (- 1)):
print_error('gff contains spaces!', 'Line', line)
if (not gff.endswith('.gff3')):
print_error("gff does not have extension '.gff3'", 'Line', line)
if fasta:
if (fasta.find(' ') != (- 1)):
print_error('fasta entry contains spaces!', 'Line', line)
if (len(fasta.split('.')) > 1):
if ((fasta[(- 6):] != '.fasta') and (fasta[(- 3):] != '.fa') and (fasta[(- 9):] != '.fasta.gz') and (fasta[(- 6):] != '.fa.gz')):
print_error("Genome entry does not have extension '.fasta', '.fa', '.fasta.gz' or '.fa.gz'!", 'Line', line)
if bed:
if (bed.find(' ') != (- 1)):
print_error('bed contains spaces!', 'Line', line)
if (not bed.endswith('.bed')):
print_error("bed does not have extension '.bed'", 'Line', line)
sample_info = [sample, fastq1, fastq2, bam, bai, gff, fasta, bed, mart_export]
sample_info_list.append(sample_info)
if (len(sample_info_list) > 0):
out_dir = os.path.dirname(file_out)
make_dir(out_dir)
with open(file_out, 'w') as fout:
fout.write((','.join(['sample', 'fastq1', 'fastq2', 'bam', 'bai', 'gff', 'fasta', 'bed', 'mart_export']) + '\n'))
for sample_info in sample_info_list:
fout.write((','.join(sample_info) + '\n')) | def check_samplesheet(file_in, file_out):
'\n This function checks that the samplesheet follows the following structure:\n sample,fastq1,fastq2,bam,bai,gff,fasta,bed,mart_export\n '
input_extensions = []
sample_info_list = []
with open(file_in, 'r') as fin:
MIN_COLS = 8
HEADER = ['sample', 'fastq1', 'fastq2', 'bam', 'bai', 'gff', 'fasta', 'bed', 'mart_export']
header = fin.readline().strip().split(',')
if (header[:len(HEADER)] != HEADER):
print('ERROR: Please check samplesheet header -> {} != {}'.format(','.join(header), ','.join(HEADER)))
sys.exit(1)
for line in fin:
lspl = [x.strip() for x in line.strip().split(',')]
if (len(lspl) < len(HEADER)):
print_error('Invalid number of columns (minimum = {})!'.format(len(HEADER)), 'Line', line)
num_cols = len([x for x in lspl if x])
if (num_cols < MIN_COLS):
print_error('Invalid number of populated columns (minimum = {})!'.format(MIN_COLS), 'Line', line)
(sample, fastq1, fastq2, bam, bai, gff, fasta, bed, mart_export) = lspl[:len(HEADER)]
if sample:
if (sample.find(' ') != (- 1)):
print_error('Sample entry contains spaces!', 'Line', line)
else:
print_error('Sample entry has not been specified!', 'Line', line)
if fastq1:
if (fastq1.find(' ') != (- 1)):
print_error('fastq1 contains spaces!', 'Line', line)
if ((not fastq1.endswith('.fastq')) and (not fastq1.endswith('.fastq.gz'))):
print_error("fastq1 does not have extension '.fastq' or '.fastq.gz'", 'Line', line)
if fastq2:
if (fastq2.find(' ') != (- 1)):
print_error('fastq2 contains spaces!', 'Line', line)
if ((not fastq2.endswith('.fastq')) and (not fastq2.endswith('.fastq.gz'))):
print_error("fastq2 does not have extension '.fastq' or '.fastq.gz'", 'Line', line)
if bam:
if (bam.find(' ') != (- 1)):
print_error('bam contains spaces!', 'Line', line)
if (not bam.endswith('.bam')):
print_error("bam does not have extension 'bam'", 'Line', line)
if gff:
if (gff.find(' ') != (- 1)):
print_error('gff contains spaces!', 'Line', line)
if (not gff.endswith('.gff3')):
print_error("gff does not have extension '.gff3'", 'Line', line)
if fasta:
if (fasta.find(' ') != (- 1)):
print_error('fasta entry contains spaces!', 'Line', line)
if (len(fasta.split('.')) > 1):
if ((fasta[(- 6):] != '.fasta') and (fasta[(- 3):] != '.fa') and (fasta[(- 9):] != '.fasta.gz') and (fasta[(- 6):] != '.fa.gz')):
print_error("Genome entry does not have extension '.fasta', '.fa', '.fasta.gz' or '.fa.gz'!", 'Line', line)
if bed:
if (bed.find(' ') != (- 1)):
print_error('bed contains spaces!', 'Line', line)
if (not bed.endswith('.bed')):
print_error("bed does not have extension '.bed'", 'Line', line)
sample_info = [sample, fastq1, fastq2, bam, bai, gff, fasta, bed, mart_export]
sample_info_list.append(sample_info)
if (len(sample_info_list) > 0):
out_dir = os.path.dirname(file_out)
make_dir(out_dir)
with open(file_out, 'w') as fout:
fout.write((','.join(['sample', 'fastq1', 'fastq2', 'bam', 'bai', 'gff', 'fasta', 'bed', 'mart_export']) + '\n'))
for sample_info in sample_info_list:
fout.write((','.join(sample_info) + '\n'))<|docstring|>This function checks that the samplesheet follows the following structure:
sample,fastq1,fastq2,bam,bai,gff,fasta,bed,mart_export<|endoftext|> |
f8ea2c897efb9e2fa2eba448621660c5c5449e2e39e47f5d7415d39ea9d437c3 | def __init__(self, time_seq, lat_seq, lon_seq, silence_level=0):
'\n Initialize an instance of GeoGrid.\n\n :type time_seq: 1D Numpy array [time]\n :arg time_seq: The increasing sequence of temporal sampling points.\n\n :type lat_seq: 1D Numpy array [index]\n :arg lat_seq: The sequence of latitudinal sampling points.\n\n :type lon_seq: 1D Numpy array [index]\n :arg lon_seq: The sequence of longitudinal sampling points.\n\n :type silence_level: number (int)\n :arg silence_level: The inverse level of verbosity of the object.\n '
Grid.__init__(self, time_seq, np.vstack((lat_seq, lon_seq)), silence_level)
self._angular_distance = None
self._angular_distance_cached = False | Initialize an instance of GeoGrid.
:type time_seq: 1D Numpy array [time]
:arg time_seq: The increasing sequence of temporal sampling points.
:type lat_seq: 1D Numpy array [index]
:arg lat_seq: The sequence of latitudinal sampling points.
:type lon_seq: 1D Numpy array [index]
:arg lon_seq: The sequence of longitudinal sampling points.
:type silence_level: number (int)
:arg silence_level: The inverse level of verbosity of the object. | pyunicorn/core/geo_grid.py | __init__ | lenas95/pyunicorn | 168 | python | def __init__(self, time_seq, lat_seq, lon_seq, silence_level=0):
'\n Initialize an instance of GeoGrid.\n\n :type time_seq: 1D Numpy array [time]\n :arg time_seq: The increasing sequence of temporal sampling points.\n\n :type lat_seq: 1D Numpy array [index]\n :arg lat_seq: The sequence of latitudinal sampling points.\n\n :type lon_seq: 1D Numpy array [index]\n :arg lon_seq: The sequence of longitudinal sampling points.\n\n :type silence_level: number (int)\n :arg silence_level: The inverse level of verbosity of the object.\n '
Grid.__init__(self, time_seq, np.vstack((lat_seq, lon_seq)), silence_level)
self._angular_distance = None
self._angular_distance_cached = False | def __init__(self, time_seq, lat_seq, lon_seq, silence_level=0):
'\n Initialize an instance of GeoGrid.\n\n :type time_seq: 1D Numpy array [time]\n :arg time_seq: The increasing sequence of temporal sampling points.\n\n :type lat_seq: 1D Numpy array [index]\n :arg lat_seq: The sequence of latitudinal sampling points.\n\n :type lon_seq: 1D Numpy array [index]\n :arg lon_seq: The sequence of longitudinal sampling points.\n\n :type silence_level: number (int)\n :arg silence_level: The inverse level of verbosity of the object.\n '
Grid.__init__(self, time_seq, np.vstack((lat_seq, lon_seq)), silence_level)
self._angular_distance = None
self._angular_distance_cached = False<|docstring|>Initialize an instance of GeoGrid.
:type time_seq: 1D Numpy array [time]
:arg time_seq: The increasing sequence of temporal sampling points.
:type lat_seq: 1D Numpy array [index]
:arg lat_seq: The sequence of latitudinal sampling points.
:type lon_seq: 1D Numpy array [index]
:arg lon_seq: The sequence of longitudinal sampling points.
:type silence_level: number (int)
:arg silence_level: The inverse level of verbosity of the object.<|endoftext|> |
381c64e4d170d6d810212c6177bf8ab160cf4422e866588ce99bcc80289804cb | def __str__(self):
'\n Return a string representation of the GeoGrid object.\n '
return ('GeoGrid: %i grid points, %i timesteps.' % (self._grid_size['space'], self._grid_size['time'])) | Return a string representation of the GeoGrid object. | pyunicorn/core/geo_grid.py | __str__ | lenas95/pyunicorn | 168 | python | def __str__(self):
'\n \n '
return ('GeoGrid: %i grid points, %i timesteps.' % (self._grid_size['space'], self._grid_size['time'])) | def __str__(self):
'\n \n '
return ('GeoGrid: %i grid points, %i timesteps.' % (self._grid_size['space'], self._grid_size['time']))<|docstring|>Return a string representation of the GeoGrid object.<|endoftext|> |
1388ce4afbcd5c2529756d329e08dd1601503dd65159c3dadd2bb9f3174fde6f | def clear_cache(self):
'\n Clean up cache.\n\n Is reversible, since all cached information can be recalculated from\n basic data.\n '
if self._angular_distance_cached:
del self._angular_distance
self._angular_distance_cached = False | Clean up cache.
Is reversible, since all cached information can be recalculated from
basic data. | pyunicorn/core/geo_grid.py | clear_cache | lenas95/pyunicorn | 168 | python | def clear_cache(self):
'\n Clean up cache.\n\n Is reversible, since all cached information can be recalculated from\n basic data.\n '
if self._angular_distance_cached:
del self._angular_distance
self._angular_distance_cached = False | def clear_cache(self):
'\n Clean up cache.\n\n Is reversible, since all cached information can be recalculated from\n basic data.\n '
if self._angular_distance_cached:
del self._angular_distance
self._angular_distance_cached = False<|docstring|>Clean up cache.
Is reversible, since all cached information can be recalculated from
basic data.<|endoftext|> |
2cb4bce4b40a6a48d7c8ab5877a3fcfa495ee58c26c9d912d6f0031833649461 | def save_txt(self, filename):
'\n Save the GeoGrid object to text files.\n\n The latitude, longitude and time sequences are stored in three separate\n text files.\n\n :arg str filename: The name of the files where Grid object is stored\n (excluding ending).\n '
lat_seq = self.lat_sequence()
lon_seq = self.lon_sequence()
time_seq = self.grid()['time']
try:
np.savetxt((filename + '_lat.txt'), lat_seq)
np.savetxt((filename + '_lon.txt'), lon_seq)
np.savetxt((filename + '_time.txt'), time_seq)
except IOError:
print(f'An error occurred while saving Grid instance to text files {filename}') | Save the GeoGrid object to text files.
The latitude, longitude and time sequences are stored in three separate
text files.
:arg str filename: The name of the files where Grid object is stored
(excluding ending). | pyunicorn/core/geo_grid.py | save_txt | lenas95/pyunicorn | 168 | python | def save_txt(self, filename):
'\n Save the GeoGrid object to text files.\n\n The latitude, longitude and time sequences are stored in three separate\n text files.\n\n :arg str filename: The name of the files where Grid object is stored\n (excluding ending).\n '
lat_seq = self.lat_sequence()
lon_seq = self.lon_sequence()
time_seq = self.grid()['time']
try:
np.savetxt((filename + '_lat.txt'), lat_seq)
np.savetxt((filename + '_lon.txt'), lon_seq)
np.savetxt((filename + '_time.txt'), time_seq)
except IOError:
print(f'An error occurred while saving Grid instance to text files {filename}') | def save_txt(self, filename):
'\n Save the GeoGrid object to text files.\n\n The latitude, longitude and time sequences are stored in three separate\n text files.\n\n :arg str filename: The name of the files where Grid object is stored\n (excluding ending).\n '
lat_seq = self.lat_sequence()
lon_seq = self.lon_sequence()
time_seq = self.grid()['time']
try:
np.savetxt((filename + '_lat.txt'), lat_seq)
np.savetxt((filename + '_lon.txt'), lon_seq)
np.savetxt((filename + '_time.txt'), time_seq)
except IOError:
print(f'An error occurred while saving Grid instance to text files {filename}')<|docstring|>Save the GeoGrid object to text files.
The latitude, longitude and time sequences are stored in three separate
text files.
:arg str filename: The name of the files where Grid object is stored
(excluding ending).<|endoftext|> |
5dc30e63cfca257f009450bf3a88ab2ca38a85ce39c5c8ec0b303f7ec438d73c | @staticmethod
def LoadTXT(filename):
'\n Return a GeoGrid object stored in text files.\n\n The latitude, longitude and time sequences are loaded from three\n separate text files.\n\n :arg str filename: The name of the files where the GeoGrid object is\n stored (excluding endings).\n :rtype: Grid object\n :return: :class:`GeoGrid` instance.\n '
try:
lat_seq = np.loadtxt((filename + '_lat.txt'))
lon_seq = np.loadtxt((filename + '_lon.txt'))
time_seq = np.loadtxt((filename + '_time.txt'))
except IOError:
print(f'An error occurred while loading Grid instance from text files {filename}')
return GeoGrid(time_seq, lat_seq, lon_seq) | Return a GeoGrid object stored in text files.
The latitude, longitude and time sequences are loaded from three
separate text files.
:arg str filename: The name of the files where the GeoGrid object is
stored (excluding endings).
:rtype: Grid object
:return: :class:`GeoGrid` instance. | pyunicorn/core/geo_grid.py | LoadTXT | lenas95/pyunicorn | 168 | python | @staticmethod
def LoadTXT(filename):
'\n Return a GeoGrid object stored in text files.\n\n The latitude, longitude and time sequences are loaded from three\n separate text files.\n\n :arg str filename: The name of the files where the GeoGrid object is\n stored (excluding endings).\n :rtype: Grid object\n :return: :class:`GeoGrid` instance.\n '
try:
lat_seq = np.loadtxt((filename + '_lat.txt'))
lon_seq = np.loadtxt((filename + '_lon.txt'))
time_seq = np.loadtxt((filename + '_time.txt'))
except IOError:
print(f'An error occurred while loading Grid instance from text files {filename}')
return GeoGrid(time_seq, lat_seq, lon_seq) | @staticmethod
def LoadTXT(filename):
'\n Return a GeoGrid object stored in text files.\n\n The latitude, longitude and time sequences are loaded from three\n separate text files.\n\n :arg str filename: The name of the files where the GeoGrid object is\n stored (excluding endings).\n :rtype: Grid object\n :return: :class:`GeoGrid` instance.\n '
try:
lat_seq = np.loadtxt((filename + '_lat.txt'))
lon_seq = np.loadtxt((filename + '_lon.txt'))
time_seq = np.loadtxt((filename + '_time.txt'))
except IOError:
print(f'An error occurred while loading Grid instance from text files {filename}')
return GeoGrid(time_seq, lat_seq, lon_seq)<|docstring|>Return a GeoGrid object stored in text files.
The latitude, longitude and time sequences are loaded from three
separate text files.
:arg str filename: The name of the files where the GeoGrid object is
stored (excluding endings).
:rtype: Grid object
:return: :class:`GeoGrid` instance.<|endoftext|> |
62cd81ebe61e5ded6f669d74c223a5421d99a5cd4eae93f088ca9be3e0b2827d | @staticmethod
def SmallTestGrid():
'\n Return test grid of 6 spatial grid points with 10 temporal sampling\n points each.\n\n :rtype: GeoGrid instance\n :return: a GeoGrid instance for testing purposes.\n '
return GeoGrid(time_seq=np.arange(10), lat_seq=np.array([0, 5, 10, 15, 20, 25]), lon_seq=np.array([2.5, 5.0, 7.5, 10.0, 12.5, 15.0]), silence_level=2) | Return test grid of 6 spatial grid points with 10 temporal sampling
points each.
:rtype: GeoGrid instance
:return: a GeoGrid instance for testing purposes. | pyunicorn/core/geo_grid.py | SmallTestGrid | lenas95/pyunicorn | 168 | python | @staticmethod
def SmallTestGrid():
'\n Return test grid of 6 spatial grid points with 10 temporal sampling\n points each.\n\n :rtype: GeoGrid instance\n :return: a GeoGrid instance for testing purposes.\n '
return GeoGrid(time_seq=np.arange(10), lat_seq=np.array([0, 5, 10, 15, 20, 25]), lon_seq=np.array([2.5, 5.0, 7.5, 10.0, 12.5, 15.0]), silence_level=2) | @staticmethod
def SmallTestGrid():
'\n Return test grid of 6 spatial grid points with 10 temporal sampling\n points each.\n\n :rtype: GeoGrid instance\n :return: a GeoGrid instance for testing purposes.\n '
return GeoGrid(time_seq=np.arange(10), lat_seq=np.array([0, 5, 10, 15, 20, 25]), lon_seq=np.array([2.5, 5.0, 7.5, 10.0, 12.5, 15.0]), silence_level=2)<|docstring|>Return test grid of 6 spatial grid points with 10 temporal sampling
points each.
:rtype: GeoGrid instance
:return: a GeoGrid instance for testing purposes.<|endoftext|> |
22c55ba23f51d02adf828dd7a6402bd9821d5a2bcc09ee77fbd8adec79927939 | @staticmethod
def RegularGrid(time_seq, lat_grid, lon_grid, silence_level=0):
'\n Initialize an instance of a regular grid.\n\n **Examples:**\n\n >>> GeoGrid.RegularGrid(\n ... time_seq=np.arange(2), lat_grid=np.array([0.,5.]),\n ... lon_grid=np.array([1.,2.]), silence_level=2).lat_sequence()\n array([ 0., 0., 5., 5.], dtype=float32)\n >>> GeoGrid.RegularGrid(\n ... time_seq=np.arange(2), lat_grid=np.array([0.,5.]),\n ... lon_grid=np.array([1.,2.]), silence_level=2).lon_sequence()\n array([ 1., 2., 1., 2.], dtype=float32)\n\n :type time_seq: 1D Numpy array [time]\n :arg time_seq: The increasing sequence of temporal sampling points.\n\n :type lat_grid: 1D Numpy array [n_lat]\n :arg lat_grid: The latitudinal grid.\n\n :type lon_grid: 1D Numpy array [n_lon]\n :arg lon_grid: The longitudinal grid.\n\n :type silence_level: number (int)\n :arg silence_level: The inverse level of verbosity of the object.\n\n :rtype: GeoGrid object\n :return: :class:`GeoGrid` instance.\n '
(lat_seq, lon_seq) = GeoGrid.coord_sequence_from_rect_grid(lat_grid, lon_grid)
return GeoGrid(time_seq, lat_seq, lon_seq, silence_level) | Initialize an instance of a regular grid.
**Examples:**
>>> GeoGrid.RegularGrid(
... time_seq=np.arange(2), lat_grid=np.array([0.,5.]),
... lon_grid=np.array([1.,2.]), silence_level=2).lat_sequence()
array([ 0., 0., 5., 5.], dtype=float32)
>>> GeoGrid.RegularGrid(
... time_seq=np.arange(2), lat_grid=np.array([0.,5.]),
... lon_grid=np.array([1.,2.]), silence_level=2).lon_sequence()
array([ 1., 2., 1., 2.], dtype=float32)
:type time_seq: 1D Numpy array [time]
:arg time_seq: The increasing sequence of temporal sampling points.
:type lat_grid: 1D Numpy array [n_lat]
:arg lat_grid: The latitudinal grid.
:type lon_grid: 1D Numpy array [n_lon]
:arg lon_grid: The longitudinal grid.
:type silence_level: number (int)
:arg silence_level: The inverse level of verbosity of the object.
:rtype: GeoGrid object
:return: :class:`GeoGrid` instance. | pyunicorn/core/geo_grid.py | RegularGrid | lenas95/pyunicorn | 168 | python | @staticmethod
def RegularGrid(time_seq, lat_grid, lon_grid, silence_level=0):
'\n Initialize an instance of a regular grid.\n\n **Examples:**\n\n >>> GeoGrid.RegularGrid(\n ... time_seq=np.arange(2), lat_grid=np.array([0.,5.]),\n ... lon_grid=np.array([1.,2.]), silence_level=2).lat_sequence()\n array([ 0., 0., 5., 5.], dtype=float32)\n >>> GeoGrid.RegularGrid(\n ... time_seq=np.arange(2), lat_grid=np.array([0.,5.]),\n ... lon_grid=np.array([1.,2.]), silence_level=2).lon_sequence()\n array([ 1., 2., 1., 2.], dtype=float32)\n\n :type time_seq: 1D Numpy array [time]\n :arg time_seq: The increasing sequence of temporal sampling points.\n\n :type lat_grid: 1D Numpy array [n_lat]\n :arg lat_grid: The latitudinal grid.\n\n :type lon_grid: 1D Numpy array [n_lon]\n :arg lon_grid: The longitudinal grid.\n\n :type silence_level: number (int)\n :arg silence_level: The inverse level of verbosity of the object.\n\n :rtype: GeoGrid object\n :return: :class:`GeoGrid` instance.\n '
(lat_seq, lon_seq) = GeoGrid.coord_sequence_from_rect_grid(lat_grid, lon_grid)
return GeoGrid(time_seq, lat_seq, lon_seq, silence_level) | @staticmethod
def RegularGrid(time_seq, lat_grid, lon_grid, silence_level=0):
'\n Initialize an instance of a regular grid.\n\n **Examples:**\n\n >>> GeoGrid.RegularGrid(\n ... time_seq=np.arange(2), lat_grid=np.array([0.,5.]),\n ... lon_grid=np.array([1.,2.]), silence_level=2).lat_sequence()\n array([ 0., 0., 5., 5.], dtype=float32)\n >>> GeoGrid.RegularGrid(\n ... time_seq=np.arange(2), lat_grid=np.array([0.,5.]),\n ... lon_grid=np.array([1.,2.]), silence_level=2).lon_sequence()\n array([ 1., 2., 1., 2.], dtype=float32)\n\n :type time_seq: 1D Numpy array [time]\n :arg time_seq: The increasing sequence of temporal sampling points.\n\n :type lat_grid: 1D Numpy array [n_lat]\n :arg lat_grid: The latitudinal grid.\n\n :type lon_grid: 1D Numpy array [n_lon]\n :arg lon_grid: The longitudinal grid.\n\n :type silence_level: number (int)\n :arg silence_level: The inverse level of verbosity of the object.\n\n :rtype: GeoGrid object\n :return: :class:`GeoGrid` instance.\n '
(lat_seq, lon_seq) = GeoGrid.coord_sequence_from_rect_grid(lat_grid, lon_grid)
return GeoGrid(time_seq, lat_seq, lon_seq, silence_level)<|docstring|>Initialize an instance of a regular grid.
**Examples:**
>>> GeoGrid.RegularGrid(
... time_seq=np.arange(2), lat_grid=np.array([0.,5.]),
... lon_grid=np.array([1.,2.]), silence_level=2).lat_sequence()
array([ 0., 0., 5., 5.], dtype=float32)
>>> GeoGrid.RegularGrid(
... time_seq=np.arange(2), lat_grid=np.array([0.,5.]),
... lon_grid=np.array([1.,2.]), silence_level=2).lon_sequence()
array([ 1., 2., 1., 2.], dtype=float32)
:type time_seq: 1D Numpy array [time]
:arg time_seq: The increasing sequence of temporal sampling points.
:type lat_grid: 1D Numpy array [n_lat]
:arg lat_grid: The latitudinal grid.
:type lon_grid: 1D Numpy array [n_lon]
:arg lon_grid: The longitudinal grid.
:type silence_level: number (int)
:arg silence_level: The inverse level of verbosity of the object.
:rtype: GeoGrid object
:return: :class:`GeoGrid` instance.<|endoftext|> |
17d802152cb390475c5f8fd7fe05f5c28aa241793e26b8a60c402f6a0064233e | @staticmethod
def coord_sequence_from_rect_grid(lat_grid, lon_grid):
"\n Return the sequences of latitude and longitude for a regular and\n rectangular grid.\n\n **Example:**\n\n >>> GeoGrid.coord_sequence_from_rect_grid(\n ... lat_grid=np.array([0.,5.]), lon_grid=np.array([1.,2.]))\n (array([ 0., 0., 5., 5.]), array([ 1., 2., 1., 2.]))\n\n :type lat_grid: 1D Numpy array [lat]\n :arg lat_grid: The grid's latitudinal sampling points.\n\n :type lon_grid: 1D Numpy array [lon]\n :arg lon_grid: The grid's longitudinal sampling points.\n\n :rtype: tuple of two 1D Numpy arrays [index]\n :return: the coordinates of all nodes in the grid.\n "
space_seq = Grid.coord_sequence_from_rect_grid([lat_grid, lon_grid])
return (space_seq[0], space_seq[1]) | Return the sequences of latitude and longitude for a regular and
rectangular grid.
**Example:**
>>> GeoGrid.coord_sequence_from_rect_grid(
... lat_grid=np.array([0.,5.]), lon_grid=np.array([1.,2.]))
(array([ 0., 0., 5., 5.]), array([ 1., 2., 1., 2.]))
:type lat_grid: 1D Numpy array [lat]
:arg lat_grid: The grid's latitudinal sampling points.
:type lon_grid: 1D Numpy array [lon]
:arg lon_grid: The grid's longitudinal sampling points.
:rtype: tuple of two 1D Numpy arrays [index]
:return: the coordinates of all nodes in the grid. | pyunicorn/core/geo_grid.py | coord_sequence_from_rect_grid | lenas95/pyunicorn | 168 | python | @staticmethod
def coord_sequence_from_rect_grid(lat_grid, lon_grid):
"\n Return the sequences of latitude and longitude for a regular and\n rectangular grid.\n\n **Example:**\n\n >>> GeoGrid.coord_sequence_from_rect_grid(\n ... lat_grid=np.array([0.,5.]), lon_grid=np.array([1.,2.]))\n (array([ 0., 0., 5., 5.]), array([ 1., 2., 1., 2.]))\n\n :type lat_grid: 1D Numpy array [lat]\n :arg lat_grid: The grid's latitudinal sampling points.\n\n :type lon_grid: 1D Numpy array [lon]\n :arg lon_grid: The grid's longitudinal sampling points.\n\n :rtype: tuple of two 1D Numpy arrays [index]\n :return: the coordinates of all nodes in the grid.\n "
space_seq = Grid.coord_sequence_from_rect_grid([lat_grid, lon_grid])
return (space_seq[0], space_seq[1]) | @staticmethod
def coord_sequence_from_rect_grid(lat_grid, lon_grid):
"\n Return the sequences of latitude and longitude for a regular and\n rectangular grid.\n\n **Example:**\n\n >>> GeoGrid.coord_sequence_from_rect_grid(\n ... lat_grid=np.array([0.,5.]), lon_grid=np.array([1.,2.]))\n (array([ 0., 0., 5., 5.]), array([ 1., 2., 1., 2.]))\n\n :type lat_grid: 1D Numpy array [lat]\n :arg lat_grid: The grid's latitudinal sampling points.\n\n :type lon_grid: 1D Numpy array [lon]\n :arg lon_grid: The grid's longitudinal sampling points.\n\n :rtype: tuple of two 1D Numpy arrays [index]\n :return: the coordinates of all nodes in the grid.\n "
space_seq = Grid.coord_sequence_from_rect_grid([lat_grid, lon_grid])
return (space_seq[0], space_seq[1])<|docstring|>Return the sequences of latitude and longitude for a regular and
rectangular grid.
**Example:**
>>> GeoGrid.coord_sequence_from_rect_grid(
... lat_grid=np.array([0.,5.]), lon_grid=np.array([1.,2.]))
(array([ 0., 0., 5., 5.]), array([ 1., 2., 1., 2.]))
:type lat_grid: 1D Numpy array [lat]
:arg lat_grid: The grid's latitudinal sampling points.
:type lon_grid: 1D Numpy array [lon]
:arg lon_grid: The grid's longitudinal sampling points.
:rtype: tuple of two 1D Numpy arrays [index]
:return: the coordinates of all nodes in the grid.<|endoftext|> |
48ca04dbb3327c3f763738adfc78d78763a3345f552e4cec875b94ca8d1e955f | def lat_sequence(self):
'\n Return the sequence of latitudes for all nodes.\n\n **Example:**\n\n >>> GeoGrid.SmallTestGrid().lat_sequence()\n array([ 0., 5., 10., 15., 20., 25.], dtype=float32)\n\n :rtype: 1D Numpy array [index]\n :return: the sequence of latitudes for all nodes.\n '
return self.sequence(0) | Return the sequence of latitudes for all nodes.
**Example:**
>>> GeoGrid.SmallTestGrid().lat_sequence()
array([ 0., 5., 10., 15., 20., 25.], dtype=float32)
:rtype: 1D Numpy array [index]
:return: the sequence of latitudes for all nodes. | pyunicorn/core/geo_grid.py | lat_sequence | lenas95/pyunicorn | 168 | python | def lat_sequence(self):
'\n Return the sequence of latitudes for all nodes.\n\n **Example:**\n\n >>> GeoGrid.SmallTestGrid().lat_sequence()\n array([ 0., 5., 10., 15., 20., 25.], dtype=float32)\n\n :rtype: 1D Numpy array [index]\n :return: the sequence of latitudes for all nodes.\n '
return self.sequence(0) | def lat_sequence(self):
'\n Return the sequence of latitudes for all nodes.\n\n **Example:**\n\n >>> GeoGrid.SmallTestGrid().lat_sequence()\n array([ 0., 5., 10., 15., 20., 25.], dtype=float32)\n\n :rtype: 1D Numpy array [index]\n :return: the sequence of latitudes for all nodes.\n '
return self.sequence(0)<|docstring|>Return the sequence of latitudes for all nodes.
**Example:**
>>> GeoGrid.SmallTestGrid().lat_sequence()
array([ 0., 5., 10., 15., 20., 25.], dtype=float32)
:rtype: 1D Numpy array [index]
:return: the sequence of latitudes for all nodes.<|endoftext|> |
7cc9a175e88bd8464926be18fc1fe4bc19f6be153f6a1aed3a962dac90d87603 | def lon_sequence(self):
'\n Return the sequence of longitudes for all nodes.\n\n **Example:**\n\n >>> GeoGrid.SmallTestGrid().lon_sequence()\n array([ 2.5, 5. , 7.5, 10. , 12.5, 15. ], dtype=float32)\n\n :rtype: 1D Numpy array [index]\n :return: the sequence of longitudes for all nodes.\n '
return self.sequence(1) | Return the sequence of longitudes for all nodes.
**Example:**
>>> GeoGrid.SmallTestGrid().lon_sequence()
array([ 2.5, 5. , 7.5, 10. , 12.5, 15. ], dtype=float32)
:rtype: 1D Numpy array [index]
:return: the sequence of longitudes for all nodes. | pyunicorn/core/geo_grid.py | lon_sequence | lenas95/pyunicorn | 168 | python | def lon_sequence(self):
'\n Return the sequence of longitudes for all nodes.\n\n **Example:**\n\n >>> GeoGrid.SmallTestGrid().lon_sequence()\n array([ 2.5, 5. , 7.5, 10. , 12.5, 15. ], dtype=float32)\n\n :rtype: 1D Numpy array [index]\n :return: the sequence of longitudes for all nodes.\n '
return self.sequence(1) | def lon_sequence(self):
'\n Return the sequence of longitudes for all nodes.\n\n **Example:**\n\n >>> GeoGrid.SmallTestGrid().lon_sequence()\n array([ 2.5, 5. , 7.5, 10. , 12.5, 15. ], dtype=float32)\n\n :rtype: 1D Numpy array [index]\n :return: the sequence of longitudes for all nodes.\n '
return self.sequence(1)<|docstring|>Return the sequence of longitudes for all nodes.
**Example:**
>>> GeoGrid.SmallTestGrid().lon_sequence()
array([ 2.5, 5. , 7.5, 10. , 12.5, 15. ], dtype=float32)
:rtype: 1D Numpy array [index]
:return: the sequence of longitudes for all nodes.<|endoftext|> |
e3f6cacce8a5c9f76139b7f23ea591b1e6c23a73bbb632c7cfacbcc33f5b4e98 | def convert_lon_coordinates(self, lon_seq):
'\n Return longitude coordinates in the system\n -180 deg W <= lon <= +180 deg O for all nodes.\n\n Accepts longitude coordinates in the system 0 deg <= lon <= 360 deg.\n 0 deg corresponds to Greenwich, England.\n\n **Example:**\n\n >>> GeoGrid.SmallTestGrid().convert_lon_coordinates(\n ... np.array([10.,350.,20.,340.,170.,190.]))\n array([ 10., -10., 20., -20., 170., -170.])\n\n :type lon_seq: 1D Numpy array [index]\n :arg lon_seq: Sequence of longitude coordinates.\n\n :rtype: 1D Numpy array [index]\n :return: the converted longitude coordinates for all nodes.\n '
new_lon_grid = np.empty(self.N)
for i in range(self.N):
if (lon_seq[i] > 180.0):
new_lon_grid[i] = (lon_seq[i] - 360.0)
else:
new_lon_grid[i] = lon_seq[i]
return new_lon_grid | Return longitude coordinates in the system
-180 deg W <= lon <= +180 deg O for all nodes.
Accepts longitude coordinates in the system 0 deg <= lon <= 360 deg.
0 deg corresponds to Greenwich, England.
**Example:**
>>> GeoGrid.SmallTestGrid().convert_lon_coordinates(
... np.array([10.,350.,20.,340.,170.,190.]))
array([ 10., -10., 20., -20., 170., -170.])
:type lon_seq: 1D Numpy array [index]
:arg lon_seq: Sequence of longitude coordinates.
:rtype: 1D Numpy array [index]
:return: the converted longitude coordinates for all nodes. | pyunicorn/core/geo_grid.py | convert_lon_coordinates | lenas95/pyunicorn | 168 | python | def convert_lon_coordinates(self, lon_seq):
'\n Return longitude coordinates in the system\n -180 deg W <= lon <= +180 deg O for all nodes.\n\n Accepts longitude coordinates in the system 0 deg <= lon <= 360 deg.\n 0 deg corresponds to Greenwich, England.\n\n **Example:**\n\n >>> GeoGrid.SmallTestGrid().convert_lon_coordinates(\n ... np.array([10.,350.,20.,340.,170.,190.]))\n array([ 10., -10., 20., -20., 170., -170.])\n\n :type lon_seq: 1D Numpy array [index]\n :arg lon_seq: Sequence of longitude coordinates.\n\n :rtype: 1D Numpy array [index]\n :return: the converted longitude coordinates for all nodes.\n '
new_lon_grid = np.empty(self.N)
for i in range(self.N):
if (lon_seq[i] > 180.0):
new_lon_grid[i] = (lon_seq[i] - 360.0)
else:
new_lon_grid[i] = lon_seq[i]
return new_lon_grid | def convert_lon_coordinates(self, lon_seq):
'\n Return longitude coordinates in the system\n -180 deg W <= lon <= +180 deg O for all nodes.\n\n Accepts longitude coordinates in the system 0 deg <= lon <= 360 deg.\n 0 deg corresponds to Greenwich, England.\n\n **Example:**\n\n >>> GeoGrid.SmallTestGrid().convert_lon_coordinates(\n ... np.array([10.,350.,20.,340.,170.,190.]))\n array([ 10., -10., 20., -20., 170., -170.])\n\n :type lon_seq: 1D Numpy array [index]\n :arg lon_seq: Sequence of longitude coordinates.\n\n :rtype: 1D Numpy array [index]\n :return: the converted longitude coordinates for all nodes.\n '
new_lon_grid = np.empty(self.N)
for i in range(self.N):
if (lon_seq[i] > 180.0):
new_lon_grid[i] = (lon_seq[i] - 360.0)
else:
new_lon_grid[i] = lon_seq[i]
return new_lon_grid<|docstring|>Return longitude coordinates in the system
-180 deg W <= lon <= +180 deg O for all nodes.
Accepts longitude coordinates in the system 0 deg <= lon <= 360 deg.
0 deg corresponds to Greenwich, England.
**Example:**
>>> GeoGrid.SmallTestGrid().convert_lon_coordinates(
... np.array([10.,350.,20.,340.,170.,190.]))
array([ 10., -10., 20., -20., 170., -170.])
:type lon_seq: 1D Numpy array [index]
:arg lon_seq: Sequence of longitude coordinates.
:rtype: 1D Numpy array [index]
:return: the converted longitude coordinates for all nodes.<|endoftext|> |
825e291c9345d0f98ae41975cacba1250e5ac7921a08b8d37f0d4f21007a5961 | def node_number(self, lat_node, lon_node):
"\n Return the index of the closest node given geographical coordinates.\n\n **Example:**\n\n >>> GeoGrid.SmallTestGrid().node_number(lat_node=14., lon_node=9.)\n 3\n\n :type lat_node: number (float)\n :arg lat_node: The latitude coordinate.\n\n :type lon_node: number (float)\n :arg lon_node: The longitude coordinate.\n\n :rtype: number (int)\n :return: the closest node's index.\n "
cos_lat = self.cos_lat()
sin_lat = self.sin_lat()
cos_lon = self.cos_lon()
sin_lon = self.sin_lon()
sin_lat_v = np.sin(((lat_node * np.pi) / 180))
cos_lat_v = np.cos(((lat_node * np.pi) / 180))
sin_lon_v = np.sin(((lon_node * np.pi) / 180))
cos_lon_v = np.cos(((lon_node * np.pi) / 180))
expr = ((sin_lat * sin_lat_v) + ((cos_lat * cos_lat_v) * ((sin_lon * sin_lon_v) + (cos_lon * cos_lon_v))))
expr[(expr < (- 1.0))] = (- 1.0)
expr[(expr > 1.0)] = 1.0
angdist = np.arccos(expr)
n_node = angdist.argmin()
return n_node | Return the index of the closest node given geographical coordinates.
**Example:**
>>> GeoGrid.SmallTestGrid().node_number(lat_node=14., lon_node=9.)
3
:type lat_node: number (float)
:arg lat_node: The latitude coordinate.
:type lon_node: number (float)
:arg lon_node: The longitude coordinate.
:rtype: number (int)
:return: the closest node's index. | pyunicorn/core/geo_grid.py | node_number | lenas95/pyunicorn | 168 | python | def node_number(self, lat_node, lon_node):
"\n Return the index of the closest node given geographical coordinates.\n\n **Example:**\n\n >>> GeoGrid.SmallTestGrid().node_number(lat_node=14., lon_node=9.)\n 3\n\n :type lat_node: number (float)\n :arg lat_node: The latitude coordinate.\n\n :type lon_node: number (float)\n :arg lon_node: The longitude coordinate.\n\n :rtype: number (int)\n :return: the closest node's index.\n "
cos_lat = self.cos_lat()
sin_lat = self.sin_lat()
cos_lon = self.cos_lon()
sin_lon = self.sin_lon()
sin_lat_v = np.sin(((lat_node * np.pi) / 180))
cos_lat_v = np.cos(((lat_node * np.pi) / 180))
sin_lon_v = np.sin(((lon_node * np.pi) / 180))
cos_lon_v = np.cos(((lon_node * np.pi) / 180))
expr = ((sin_lat * sin_lat_v) + ((cos_lat * cos_lat_v) * ((sin_lon * sin_lon_v) + (cos_lon * cos_lon_v))))
expr[(expr < (- 1.0))] = (- 1.0)
expr[(expr > 1.0)] = 1.0
angdist = np.arccos(expr)
n_node = angdist.argmin()
return n_node | def node_number(self, lat_node, lon_node):
"\n Return the index of the closest node given geographical coordinates.\n\n **Example:**\n\n >>> GeoGrid.SmallTestGrid().node_number(lat_node=14., lon_node=9.)\n 3\n\n :type lat_node: number (float)\n :arg lat_node: The latitude coordinate.\n\n :type lon_node: number (float)\n :arg lon_node: The longitude coordinate.\n\n :rtype: number (int)\n :return: the closest node's index.\n "
cos_lat = self.cos_lat()
sin_lat = self.sin_lat()
cos_lon = self.cos_lon()
sin_lon = self.sin_lon()
sin_lat_v = np.sin(((lat_node * np.pi) / 180))
cos_lat_v = np.cos(((lat_node * np.pi) / 180))
sin_lon_v = np.sin(((lon_node * np.pi) / 180))
cos_lon_v = np.cos(((lon_node * np.pi) / 180))
expr = ((sin_lat * sin_lat_v) + ((cos_lat * cos_lat_v) * ((sin_lon * sin_lon_v) + (cos_lon * cos_lon_v))))
expr[(expr < (- 1.0))] = (- 1.0)
expr[(expr > 1.0)] = 1.0
angdist = np.arccos(expr)
n_node = angdist.argmin()
return n_node<|docstring|>Return the index of the closest node given geographical coordinates.
**Example:**
>>> GeoGrid.SmallTestGrid().node_number(lat_node=14., lon_node=9.)
3
:type lat_node: number (float)
:arg lat_node: The latitude coordinate.
:type lon_node: number (float)
:arg lon_node: The longitude coordinate.
:rtype: number (int)
:return: the closest node's index.<|endoftext|> |
babd7918ee1c9bfad3ea11412bfc83cf782b37e2f45db42d46957e257b0fce48 | def cos_lat(self):
'\n Return the sequence of cosines of latitude for all nodes.\n\n **Example:**\n\n >>> r(GeoGrid.SmallTestGrid().cos_lat()[:2])\n array([ 1. , 0.9962])\n\n :rtype: 1D Numpy array [index]\n :return: the cosine of latitudes for all nodes.\n '
return np.cos(((self.lat_sequence() * np.pi) / 180)) | Return the sequence of cosines of latitude for all nodes.
**Example:**
>>> r(GeoGrid.SmallTestGrid().cos_lat()[:2])
array([ 1. , 0.9962])
:rtype: 1D Numpy array [index]
:return: the cosine of latitudes for all nodes. | pyunicorn/core/geo_grid.py | cos_lat | lenas95/pyunicorn | 168 | python | def cos_lat(self):
'\n Return the sequence of cosines of latitude for all nodes.\n\n **Example:**\n\n >>> r(GeoGrid.SmallTestGrid().cos_lat()[:2])\n array([ 1. , 0.9962])\n\n :rtype: 1D Numpy array [index]\n :return: the cosine of latitudes for all nodes.\n '
return np.cos(((self.lat_sequence() * np.pi) / 180)) | def cos_lat(self):
'\n Return the sequence of cosines of latitude for all nodes.\n\n **Example:**\n\n >>> r(GeoGrid.SmallTestGrid().cos_lat()[:2])\n array([ 1. , 0.9962])\n\n :rtype: 1D Numpy array [index]\n :return: the cosine of latitudes for all nodes.\n '
return np.cos(((self.lat_sequence() * np.pi) / 180))<|docstring|>Return the sequence of cosines of latitude for all nodes.
**Example:**
>>> r(GeoGrid.SmallTestGrid().cos_lat()[:2])
array([ 1. , 0.9962])
:rtype: 1D Numpy array [index]
:return: the cosine of latitudes for all nodes.<|endoftext|> |
d847bb144bb68983cb256127f7d2dce00aa21ca4490337fdb5078cf075a9cee2 | def sin_lat(self):
'\n Return the sequence of sines of latitude for all nodes.\n\n **Example:**\n\n >>> r(GeoGrid.SmallTestGrid().sin_lat()[:2])\n array([ 0. , 0.0872])\n\n :rtype: 1D Numpy array [index]\n :return: the sine of latitudes for all nodes.\n '
return np.sin(((self.lat_sequence() * np.pi) / 180)) | Return the sequence of sines of latitude for all nodes.
**Example:**
>>> r(GeoGrid.SmallTestGrid().sin_lat()[:2])
array([ 0. , 0.0872])
:rtype: 1D Numpy array [index]
:return: the sine of latitudes for all nodes. | pyunicorn/core/geo_grid.py | sin_lat | lenas95/pyunicorn | 168 | python | def sin_lat(self):
'\n Return the sequence of sines of latitude for all nodes.\n\n **Example:**\n\n >>> r(GeoGrid.SmallTestGrid().sin_lat()[:2])\n array([ 0. , 0.0872])\n\n :rtype: 1D Numpy array [index]\n :return: the sine of latitudes for all nodes.\n '
return np.sin(((self.lat_sequence() * np.pi) / 180)) | def sin_lat(self):
'\n Return the sequence of sines of latitude for all nodes.\n\n **Example:**\n\n >>> r(GeoGrid.SmallTestGrid().sin_lat()[:2])\n array([ 0. , 0.0872])\n\n :rtype: 1D Numpy array [index]\n :return: the sine of latitudes for all nodes.\n '
return np.sin(((self.lat_sequence() * np.pi) / 180))<|docstring|>Return the sequence of sines of latitude for all nodes.
**Example:**
>>> r(GeoGrid.SmallTestGrid().sin_lat()[:2])
array([ 0. , 0.0872])
:rtype: 1D Numpy array [index]
:return: the sine of latitudes for all nodes.<|endoftext|> |
f6473224904f4f97767f3ed7ce8bdb2476e70cde7db9f3793cba0141ad011d5c | def cos_lon(self):
'\n Return the sequence of cosines of longitude for all nodes.\n\n **Example:**\n\n >>> r(GeoGrid.SmallTestGrid().cos_lon()[:2])\n array([ 0.999 , 0.9962])\n\n :rtype: 1D Numpy array [index]\n :return: the cosine of longitudes for all nodes.\n '
return np.cos(((self.lon_sequence() * np.pi) / 180)) | Return the sequence of cosines of longitude for all nodes.
**Example:**
>>> r(GeoGrid.SmallTestGrid().cos_lon()[:2])
array([ 0.999 , 0.9962])
:rtype: 1D Numpy array [index]
:return: the cosine of longitudes for all nodes. | pyunicorn/core/geo_grid.py | cos_lon | lenas95/pyunicorn | 168 | python | def cos_lon(self):
'\n Return the sequence of cosines of longitude for all nodes.\n\n **Example:**\n\n >>> r(GeoGrid.SmallTestGrid().cos_lon()[:2])\n array([ 0.999 , 0.9962])\n\n :rtype: 1D Numpy array [index]\n :return: the cosine of longitudes for all nodes.\n '
return np.cos(((self.lon_sequence() * np.pi) / 180)) | def cos_lon(self):
'\n Return the sequence of cosines of longitude for all nodes.\n\n **Example:**\n\n >>> r(GeoGrid.SmallTestGrid().cos_lon()[:2])\n array([ 0.999 , 0.9962])\n\n :rtype: 1D Numpy array [index]\n :return: the cosine of longitudes for all nodes.\n '
return np.cos(((self.lon_sequence() * np.pi) / 180))<|docstring|>Return the sequence of cosines of longitude for all nodes.
**Example:**
>>> r(GeoGrid.SmallTestGrid().cos_lon()[:2])
array([ 0.999 , 0.9962])
:rtype: 1D Numpy array [index]
:return: the cosine of longitudes for all nodes.<|endoftext|> |
4582fd5926c5ccd885c31fb86217ee573a3050f2efde571da916be908a789c2f | def sin_lon(self):
'\n Return the sequence of sines of longitude for all nodes.\n\n **Example:**\n\n >>> r(GeoGrid.SmallTestGrid().sin_lon()[:2])\n array([ 0.0436, 0.0872])\n\n :rtype: 1D Numpy array [index]\n :return: the sine of longitudes for all nodes.\n '
return np.sin(((self.lon_sequence() * np.pi) / 180)) | Return the sequence of sines of longitude for all nodes.
**Example:**
>>> r(GeoGrid.SmallTestGrid().sin_lon()[:2])
array([ 0.0436, 0.0872])
:rtype: 1D Numpy array [index]
:return: the sine of longitudes for all nodes. | pyunicorn/core/geo_grid.py | sin_lon | lenas95/pyunicorn | 168 | python | def sin_lon(self):
'\n Return the sequence of sines of longitude for all nodes.\n\n **Example:**\n\n >>> r(GeoGrid.SmallTestGrid().sin_lon()[:2])\n array([ 0.0436, 0.0872])\n\n :rtype: 1D Numpy array [index]\n :return: the sine of longitudes for all nodes.\n '
return np.sin(((self.lon_sequence() * np.pi) / 180)) | def sin_lon(self):
'\n Return the sequence of sines of longitude for all nodes.\n\n **Example:**\n\n >>> r(GeoGrid.SmallTestGrid().sin_lon()[:2])\n array([ 0.0436, 0.0872])\n\n :rtype: 1D Numpy array [index]\n :return: the sine of longitudes for all nodes.\n '
return np.sin(((self.lon_sequence() * np.pi) / 180))<|docstring|>Return the sequence of sines of longitude for all nodes.
**Example:**
>>> r(GeoGrid.SmallTestGrid().sin_lon()[:2])
array([ 0.0436, 0.0872])
:rtype: 1D Numpy array [index]
:return: the sine of longitudes for all nodes.<|endoftext|> |
89fc3ccb02916b4bec925e50e46d06fbffcc1eed59af98879df35c3c24da93d5 | def distance(self):
'\n Calculate and return the standard distance matrix of the corresponding\n grid type\n\n :rtype: 2D Numpy array [index, index]\n :return: the distance matrix.\n '
return self.angular_distance() | Calculate and return the standard distance matrix of the corresponding
grid type
:rtype: 2D Numpy array [index, index]
:return: the distance matrix. | pyunicorn/core/geo_grid.py | distance | lenas95/pyunicorn | 168 | python | def distance(self):
'\n Calculate and return the standard distance matrix of the corresponding\n grid type\n\n :rtype: 2D Numpy array [index, index]\n :return: the distance matrix.\n '
return self.angular_distance() | def distance(self):
'\n Calculate and return the standard distance matrix of the corresponding\n grid type\n\n :rtype: 2D Numpy array [index, index]\n :return: the distance matrix.\n '
return self.angular_distance()<|docstring|>Calculate and return the standard distance matrix of the corresponding
grid type
:rtype: 2D Numpy array [index, index]
:return: the distance matrix.<|endoftext|> |
4809be201d8c60c84aaf75a26d357bfb2e7ca8466a608dc10d889ce04d4a21d8 | def _calculate_angular_distance(self):
'\n Calculate and return the angular great circle distance matrix.\n\n **No normalization applied anymore!** Return values are in the range\n 0 to Pi.\n\n :rtype: 2D Numpy array [index, index]\n :return: the angular great circle distance matrix (unit radians).\n '
if (self.silence_level <= 1):
print('Calculating angular great circle distance using Cython...')
N = self.N
cos_lat = self.cos_lat()
sin_lat = self.sin_lat()
cos_lon = self.cos_lon()
sin_lon = self.sin_lon()
cosangdist = np.zeros((N, N), dtype='float32')
_cy_calculate_angular_distance(cos_lat, sin_lat, cos_lon, sin_lon, cosangdist, N)
return np.arccos(cosangdist) | Calculate and return the angular great circle distance matrix.
**No normalization applied anymore!** Return values are in the range
0 to Pi.
:rtype: 2D Numpy array [index, index]
:return: the angular great circle distance matrix (unit radians). | pyunicorn/core/geo_grid.py | _calculate_angular_distance | lenas95/pyunicorn | 168 | python | def _calculate_angular_distance(self):
'\n Calculate and return the angular great circle distance matrix.\n\n **No normalization applied anymore!** Return values are in the range\n 0 to Pi.\n\n :rtype: 2D Numpy array [index, index]\n :return: the angular great circle distance matrix (unit radians).\n '
if (self.silence_level <= 1):
print('Calculating angular great circle distance using Cython...')
N = self.N
cos_lat = self.cos_lat()
sin_lat = self.sin_lat()
cos_lon = self.cos_lon()
sin_lon = self.sin_lon()
cosangdist = np.zeros((N, N), dtype='float32')
_cy_calculate_angular_distance(cos_lat, sin_lat, cos_lon, sin_lon, cosangdist, N)
return np.arccos(cosangdist) | def _calculate_angular_distance(self):
'\n Calculate and return the angular great circle distance matrix.\n\n **No normalization applied anymore!** Return values are in the range\n 0 to Pi.\n\n :rtype: 2D Numpy array [index, index]\n :return: the angular great circle distance matrix (unit radians).\n '
if (self.silence_level <= 1):
print('Calculating angular great circle distance using Cython...')
N = self.N
cos_lat = self.cos_lat()
sin_lat = self.sin_lat()
cos_lon = self.cos_lon()
sin_lon = self.sin_lon()
cosangdist = np.zeros((N, N), dtype='float32')
_cy_calculate_angular_distance(cos_lat, sin_lat, cos_lon, sin_lon, cosangdist, N)
return np.arccos(cosangdist)<|docstring|>Calculate and return the angular great circle distance matrix.
**No normalization applied anymore!** Return values are in the range
0 to Pi.
:rtype: 2D Numpy array [index, index]
:return: the angular great circle distance matrix (unit radians).<|endoftext|> |
463efb6c0751ae01ecff523a9895729c8b59d972ed8f417819110daccaeb54e5 | def angular_distance(self):
"\n Return the angular great circle distance matrix.\n\n **No normalization applied anymore!** Return values are in the range\n 0 to Pi.\n\n **Example:**\n\n >>> rr(GeoGrid.SmallTestGrid().angular_distance(), 2)\n [['0' '0.1' '0.19' '0.29' '0.39' '0.48']\n ['0.1' '0' '0.1' '0.19' '0.29' '0.39']\n ['0.19' '0.1' '0' '0.1' '0.19' '0.29']\n ['0.29' '0.19' '0.1' '0' '0.1' '0.19']\n ['0.39' '0.29' '0.19' '0.1' '0' '0.1']\n ['0.48' '0.39' '0.29' '0.19' '0.1' '0']]\n\n :rtype: 2D Numpy array [index, index]\n :return: the angular great circle distance matrix.\n "
if (not self._angular_distance_cached):
self._angular_distance = self._calculate_angular_distance()
self._angular_distance_cached = True
return self._angular_distance | Return the angular great circle distance matrix.
**No normalization applied anymore!** Return values are in the range
0 to Pi.
**Example:**
>>> rr(GeoGrid.SmallTestGrid().angular_distance(), 2)
[['0' '0.1' '0.19' '0.29' '0.39' '0.48']
['0.1' '0' '0.1' '0.19' '0.29' '0.39']
['0.19' '0.1' '0' '0.1' '0.19' '0.29']
['0.29' '0.19' '0.1' '0' '0.1' '0.19']
['0.39' '0.29' '0.19' '0.1' '0' '0.1']
['0.48' '0.39' '0.29' '0.19' '0.1' '0']]
:rtype: 2D Numpy array [index, index]
:return: the angular great circle distance matrix. | pyunicorn/core/geo_grid.py | angular_distance | lenas95/pyunicorn | 168 | python | def angular_distance(self):
"\n Return the angular great circle distance matrix.\n\n **No normalization applied anymore!** Return values are in the range\n 0 to Pi.\n\n **Example:**\n\n >>> rr(GeoGrid.SmallTestGrid().angular_distance(), 2)\n [['0' '0.1' '0.19' '0.29' '0.39' '0.48']\n ['0.1' '0' '0.1' '0.19' '0.29' '0.39']\n ['0.19' '0.1' '0' '0.1' '0.19' '0.29']\n ['0.29' '0.19' '0.1' '0' '0.1' '0.19']\n ['0.39' '0.29' '0.19' '0.1' '0' '0.1']\n ['0.48' '0.39' '0.29' '0.19' '0.1' '0']]\n\n :rtype: 2D Numpy array [index, index]\n :return: the angular great circle distance matrix.\n "
if (not self._angular_distance_cached):
self._angular_distance = self._calculate_angular_distance()
self._angular_distance_cached = True
return self._angular_distance | def angular_distance(self):
"\n Return the angular great circle distance matrix.\n\n **No normalization applied anymore!** Return values are in the range\n 0 to Pi.\n\n **Example:**\n\n >>> rr(GeoGrid.SmallTestGrid().angular_distance(), 2)\n [['0' '0.1' '0.19' '0.29' '0.39' '0.48']\n ['0.1' '0' '0.1' '0.19' '0.29' '0.39']\n ['0.19' '0.1' '0' '0.1' '0.19' '0.29']\n ['0.29' '0.19' '0.1' '0' '0.1' '0.19']\n ['0.39' '0.29' '0.19' '0.1' '0' '0.1']\n ['0.48' '0.39' '0.29' '0.19' '0.1' '0']]\n\n :rtype: 2D Numpy array [index, index]\n :return: the angular great circle distance matrix.\n "
if (not self._angular_distance_cached):
self._angular_distance = self._calculate_angular_distance()
self._angular_distance_cached = True
return self._angular_distance<|docstring|>Return the angular great circle distance matrix.
**No normalization applied anymore!** Return values are in the range
0 to Pi.
**Example:**
>>> rr(GeoGrid.SmallTestGrid().angular_distance(), 2)
[['0' '0.1' '0.19' '0.29' '0.39' '0.48']
['0.1' '0' '0.1' '0.19' '0.29' '0.39']
['0.19' '0.1' '0' '0.1' '0.19' '0.29']
['0.29' '0.19' '0.1' '0' '0.1' '0.19']
['0.39' '0.29' '0.19' '0.1' '0' '0.1']
['0.48' '0.39' '0.29' '0.19' '0.1' '0']]
:rtype: 2D Numpy array [index, index]
:return: the angular great circle distance matrix.<|endoftext|> |
8848494671f4fdaf515d5fc110c4f486458505ec1341e1986ff76e2e7197b828 | def boundaries(self):
'\n Return the spatio-temporal grid boundaries.\n\n Structure of the returned dictionary:\n - boundaries = {"time_min": self._boundaries["time_min"],\n "time_max": self._boundaries["time_max"],\n "lat_min": self._boundaries["space_min"][0],\n "lat_max": self._boundaries["space_max"][1],\n "lon_min": self._boundaries["space_min"][0],\n "lon_max": self._boundaries["space_max"][1]}\n\n :rtype: dictionary\n :return: the spatio-temporal grid boundaries.\n '
boundaries = {'time_min': self._boundaries['time_min'], 'time_max': self._boundaries['time_max'], 'lat_min': self._boundaries['space_min'][0], 'lat_max': self._boundaries['space_max'][0], 'lon_min': self._boundaries['space_min'][1], 'lon_max': self._boundaries['space_max'][1]}
return boundaries | Return the spatio-temporal grid boundaries.
Structure of the returned dictionary:
- boundaries = {"time_min": self._boundaries["time_min"],
"time_max": self._boundaries["time_max"],
"lat_min": self._boundaries["space_min"][0],
"lat_max": self._boundaries["space_max"][1],
"lon_min": self._boundaries["space_min"][0],
"lon_max": self._boundaries["space_max"][1]}
:rtype: dictionary
:return: the spatio-temporal grid boundaries. | pyunicorn/core/geo_grid.py | boundaries | lenas95/pyunicorn | 168 | python | def boundaries(self):
'\n Return the spatio-temporal grid boundaries.\n\n Structure of the returned dictionary:\n - boundaries = {"time_min": self._boundaries["time_min"],\n "time_max": self._boundaries["time_max"],\n "lat_min": self._boundaries["space_min"][0],\n "lat_max": self._boundaries["space_max"][1],\n "lon_min": self._boundaries["space_min"][0],\n "lon_max": self._boundaries["space_max"][1]}\n\n :rtype: dictionary\n :return: the spatio-temporal grid boundaries.\n '
boundaries = {'time_min': self._boundaries['time_min'], 'time_max': self._boundaries['time_max'], 'lat_min': self._boundaries['space_min'][0], 'lat_max': self._boundaries['space_max'][0], 'lon_min': self._boundaries['space_min'][1], 'lon_max': self._boundaries['space_max'][1]}
return boundaries | def boundaries(self):
'\n Return the spatio-temporal grid boundaries.\n\n Structure of the returned dictionary:\n - boundaries = {"time_min": self._boundaries["time_min"],\n "time_max": self._boundaries["time_max"],\n "lat_min": self._boundaries["space_min"][0],\n "lat_max": self._boundaries["space_max"][1],\n "lon_min": self._boundaries["space_min"][0],\n "lon_max": self._boundaries["space_max"][1]}\n\n :rtype: dictionary\n :return: the spatio-temporal grid boundaries.\n '
boundaries = {'time_min': self._boundaries['time_min'], 'time_max': self._boundaries['time_max'], 'lat_min': self._boundaries['space_min'][0], 'lat_max': self._boundaries['space_max'][0], 'lon_min': self._boundaries['space_min'][1], 'lon_max': self._boundaries['space_max'][1]}
return boundaries<|docstring|>Return the spatio-temporal grid boundaries.
Structure of the returned dictionary:
- boundaries = {"time_min": self._boundaries["time_min"],
"time_max": self._boundaries["time_max"],
"lat_min": self._boundaries["space_min"][0],
"lat_max": self._boundaries["space_max"][1],
"lon_min": self._boundaries["space_min"][0],
"lon_max": self._boundaries["space_max"][1]}
:rtype: dictionary
:return: the spatio-temporal grid boundaries.<|endoftext|> |
edeab18c70104191561a8b73bf862002d276f8fd9e46a861bcd2d70925a82f74 | def print_boundaries(self):
'\n Pretty print the spatio-temporal grid boundaries.\n\n **Example:**\n\n >>> print(GeoGrid.SmallTestGrid().print_boundaries())\n time lat lon\n min 0.0 0.00 2.50\n max 9.0 25.00 15.00\n\n :rtype: string\n :return: printable string for the spatio-temporal grid boundaries\n '
return ' time lat lon\n min {time_min:6.1f} {lat_min: 7.2f} {lon_min: 7.2f}\n max {time_max:6.1f} {lat_max: 7.2f} {lon_max: 7.2f}'.format(**self.boundaries()) | Pretty print the spatio-temporal grid boundaries.
**Example:**
>>> print(GeoGrid.SmallTestGrid().print_boundaries())
time lat lon
min 0.0 0.00 2.50
max 9.0 25.00 15.00
:rtype: string
:return: printable string for the spatio-temporal grid boundaries | pyunicorn/core/geo_grid.py | print_boundaries | lenas95/pyunicorn | 168 | python | def print_boundaries(self):
'\n Pretty print the spatio-temporal grid boundaries.\n\n **Example:**\n\n >>> print(GeoGrid.SmallTestGrid().print_boundaries())\n time lat lon\n min 0.0 0.00 2.50\n max 9.0 25.00 15.00\n\n :rtype: string\n :return: printable string for the spatio-temporal grid boundaries\n '
return ' time lat lon\n min {time_min:6.1f} {lat_min: 7.2f} {lon_min: 7.2f}\n max {time_max:6.1f} {lat_max: 7.2f} {lon_max: 7.2f}'.format(**self.boundaries()) | def print_boundaries(self):
'\n Pretty print the spatio-temporal grid boundaries.\n\n **Example:**\n\n >>> print(GeoGrid.SmallTestGrid().print_boundaries())\n time lat lon\n min 0.0 0.00 2.50\n max 9.0 25.00 15.00\n\n :rtype: string\n :return: printable string for the spatio-temporal grid boundaries\n '
return ' time lat lon\n min {time_min:6.1f} {lat_min: 7.2f} {lon_min: 7.2f}\n max {time_max:6.1f} {lat_max: 7.2f} {lon_max: 7.2f}'.format(**self.boundaries())<|docstring|>Pretty print the spatio-temporal grid boundaries.
**Example:**
>>> print(GeoGrid.SmallTestGrid().print_boundaries())
time lat lon
min 0.0 0.00 2.50
max 9.0 25.00 15.00
:rtype: string
:return: printable string for the spatio-temporal grid boundaries<|endoftext|> |
35268e4504ef484acd26f7109347ac173437968ea0cb859a1d5bf20dcb1153d5 | def grid(self):
'\n Return the grid\'s spatio-temporal sampling points.\n\n Structure of the returned dictionary:\n - grid = {"time": self._grid["time"],\n "lat": self._grid["space"][0],\n "lon": self._grid["space"][1]}\n\n **Examples:**\n\n >>> Grid.SmallTestGrid().grid()["space"][0]\n array([ 0., 5., 10., 15., 20., 25.], dtype=float32)\n >>> Grid.SmallTestGrid().grid()["space"][0][5]\n 15.0\n\n :rtype: dictionary\n :return: the grid\'s spatio-temporal sampling points.\n '
grid = {'time': self._grid['time'], 'lat': self._grid['space'][0], 'lon': self._grid['space'][1]}
return grid | Return the grid's spatio-temporal sampling points.
Structure of the returned dictionary:
- grid = {"time": self._grid["time"],
"lat": self._grid["space"][0],
"lon": self._grid["space"][1]}
**Examples:**
>>> Grid.SmallTestGrid().grid()["space"][0]
array([ 0., 5., 10., 15., 20., 25.], dtype=float32)
>>> Grid.SmallTestGrid().grid()["space"][0][5]
15.0
:rtype: dictionary
:return: the grid's spatio-temporal sampling points. | pyunicorn/core/geo_grid.py | grid | lenas95/pyunicorn | 168 | python | def grid(self):
'\n Return the grid\'s spatio-temporal sampling points.\n\n Structure of the returned dictionary:\n - grid = {"time": self._grid["time"],\n "lat": self._grid["space"][0],\n "lon": self._grid["space"][1]}\n\n **Examples:**\n\n >>> Grid.SmallTestGrid().grid()["space"][0]\n array([ 0., 5., 10., 15., 20., 25.], dtype=float32)\n >>> Grid.SmallTestGrid().grid()["space"][0][5]\n 15.0\n\n :rtype: dictionary\n :return: the grid\'s spatio-temporal sampling points.\n '
grid = {'time': self._grid['time'], 'lat': self._grid['space'][0], 'lon': self._grid['space'][1]}
return grid | def grid(self):
'\n Return the grid\'s spatio-temporal sampling points.\n\n Structure of the returned dictionary:\n - grid = {"time": self._grid["time"],\n "lat": self._grid["space"][0],\n "lon": self._grid["space"][1]}\n\n **Examples:**\n\n >>> Grid.SmallTestGrid().grid()["space"][0]\n array([ 0., 5., 10., 15., 20., 25.], dtype=float32)\n >>> Grid.SmallTestGrid().grid()["space"][0][5]\n 15.0\n\n :rtype: dictionary\n :return: the grid\'s spatio-temporal sampling points.\n '
grid = {'time': self._grid['time'], 'lat': self._grid['space'][0], 'lon': self._grid['space'][1]}
return grid<|docstring|>Return the grid's spatio-temporal sampling points.
Structure of the returned dictionary:
- grid = {"time": self._grid["time"],
"lat": self._grid["space"][0],
"lon": self._grid["space"][1]}
**Examples:**
>>> Grid.SmallTestGrid().grid()["space"][0]
array([ 0., 5., 10., 15., 20., 25.], dtype=float32)
>>> Grid.SmallTestGrid().grid()["space"][0][5]
15.0
:rtype: dictionary
:return: the grid's spatio-temporal sampling points.<|endoftext|> |
346a47f84ae1d0b7470ac591efd1f2021c02141179972809390d2724f3651a32 | def region_indices(self, region):
'\n Returns a boolean array of nodes with True values when the node\n is inside the region.\n\n **Example:**\n\n >>> GeoGrid.SmallTestGrid().region_indices(\n ... np.array([0.,0.,0.,11.,11.,11.,11.,0.])).astype(int)\n array([0, 1, 1, 0, 0, 0])\n\n :type region: 1D Numpy array [n_polygon_nodes]\n :arg region: array of lon, lat, lon, lat, ...\n [-80.2, 5., -82.4, 5.3, ...] as copied from Google Earth\n Polygon file\n :rtype: 1D bool array [index]\n :return: bool array with True for nodes inside region\n '
remapped_region = region.reshape((len(region) // 2), 2)
if (self._grid['space'][1].min() >= 0):
remapped_region[((remapped_region[(:, 0)] < 0), 0)] = (360 + remapped_region[((remapped_region[(:, 0)] < 0), 0)])
lat_lon_map = np.column_stack((self._grid['space'][1], self._grid['space'][0]))
return path.Path(remapped_region).contains_points(lat_lon_map) | Returns a boolean array of nodes with True values when the node
is inside the region.
**Example:**
>>> GeoGrid.SmallTestGrid().region_indices(
... np.array([0.,0.,0.,11.,11.,11.,11.,0.])).astype(int)
array([0, 1, 1, 0, 0, 0])
:type region: 1D Numpy array [n_polygon_nodes]
:arg region: array of lon, lat, lon, lat, ...
[-80.2, 5., -82.4, 5.3, ...] as copied from Google Earth
Polygon file
:rtype: 1D bool array [index]
:return: bool array with True for nodes inside region | pyunicorn/core/geo_grid.py | region_indices | lenas95/pyunicorn | 168 | python | def region_indices(self, region):
'\n Returns a boolean array of nodes with True values when the node\n is inside the region.\n\n **Example:**\n\n >>> GeoGrid.SmallTestGrid().region_indices(\n ... np.array([0.,0.,0.,11.,11.,11.,11.,0.])).astype(int)\n array([0, 1, 1, 0, 0, 0])\n\n :type region: 1D Numpy array [n_polygon_nodes]\n :arg region: array of lon, lat, lon, lat, ...\n [-80.2, 5., -82.4, 5.3, ...] as copied from Google Earth\n Polygon file\n :rtype: 1D bool array [index]\n :return: bool array with True for nodes inside region\n '
remapped_region = region.reshape((len(region) // 2), 2)
if (self._grid['space'][1].min() >= 0):
remapped_region[((remapped_region[(:, 0)] < 0), 0)] = (360 + remapped_region[((remapped_region[(:, 0)] < 0), 0)])
lat_lon_map = np.column_stack((self._grid['space'][1], self._grid['space'][0]))
return path.Path(remapped_region).contains_points(lat_lon_map) | def region_indices(self, region):
'\n Returns a boolean array of nodes with True values when the node\n is inside the region.\n\n **Example:**\n\n >>> GeoGrid.SmallTestGrid().region_indices(\n ... np.array([0.,0.,0.,11.,11.,11.,11.,0.])).astype(int)\n array([0, 1, 1, 0, 0, 0])\n\n :type region: 1D Numpy array [n_polygon_nodes]\n :arg region: array of lon, lat, lon, lat, ...\n [-80.2, 5., -82.4, 5.3, ...] as copied from Google Earth\n Polygon file\n :rtype: 1D bool array [index]\n :return: bool array with True for nodes inside region\n '
remapped_region = region.reshape((len(region) // 2), 2)
if (self._grid['space'][1].min() >= 0):
remapped_region[((remapped_region[(:, 0)] < 0), 0)] = (360 + remapped_region[((remapped_region[(:, 0)] < 0), 0)])
lat_lon_map = np.column_stack((self._grid['space'][1], self._grid['space'][0]))
return path.Path(remapped_region).contains_points(lat_lon_map)<|docstring|>Returns a boolean array of nodes with True values when the node
is inside the region.
**Example:**
>>> GeoGrid.SmallTestGrid().region_indices(
... np.array([0.,0.,0.,11.,11.,11.,11.,0.])).astype(int)
array([0, 1, 1, 0, 0, 0])
:type region: 1D Numpy array [n_polygon_nodes]
:arg region: array of lon, lat, lon, lat, ...
[-80.2, 5., -82.4, 5.3, ...] as copied from Google Earth
Polygon file
:rtype: 1D bool array [index]
:return: bool array with True for nodes inside region<|endoftext|> |
334fb3c85329c71648846fceb8f27e9ba02d2d9a8f15b6194eaf205c1f6a179f | @staticmethod
def region(name):
'Return some standard regions.'
if (name == 'ENSO'):
return np.array([(- 79.28273150749884), (- 10.49311965331937), (- 79.29849791038734), 10.12527300655218, (- 174.9221853596061), 10.07293121423917, (- 174.8362810586096), (- 10.46407198776264), (- 80.13229308153623), (- 10.36724072894785), (- 79.28273150749884), (- 10.49311965331937)])
elif (name == 'NINO34'):
return np.array([(- 118.6402427933005), 7.019906838300821, (- 171.0067408177714), 6.215022481004243, (- 171.0364908514962), (- 5.768616252424354), (- 119.245702264066), (- 5.836385150138187), (- 118.6402427933005), 7.019906838300821])
else:
return None | Return some standard regions. | pyunicorn/core/geo_grid.py | region | lenas95/pyunicorn | 168 | python | @staticmethod
def region(name):
if (name == 'ENSO'):
return np.array([(- 79.28273150749884), (- 10.49311965331937), (- 79.29849791038734), 10.12527300655218, (- 174.9221853596061), 10.07293121423917, (- 174.8362810586096), (- 10.46407198776264), (- 80.13229308153623), (- 10.36724072894785), (- 79.28273150749884), (- 10.49311965331937)])
elif (name == 'NINO34'):
return np.array([(- 118.6402427933005), 7.019906838300821, (- 171.0067408177714), 6.215022481004243, (- 171.0364908514962), (- 5.768616252424354), (- 119.245702264066), (- 5.836385150138187), (- 118.6402427933005), 7.019906838300821])
else:
return None | @staticmethod
def region(name):
if (name == 'ENSO'):
return np.array([(- 79.28273150749884), (- 10.49311965331937), (- 79.29849791038734), 10.12527300655218, (- 174.9221853596061), 10.07293121423917, (- 174.8362810586096), (- 10.46407198776264), (- 80.13229308153623), (- 10.36724072894785), (- 79.28273150749884), (- 10.49311965331937)])
elif (name == 'NINO34'):
return np.array([(- 118.6402427933005), 7.019906838300821, (- 171.0067408177714), 6.215022481004243, (- 171.0364908514962), (- 5.768616252424354), (- 119.245702264066), (- 5.836385150138187), (- 118.6402427933005), 7.019906838300821])
else:
return None<|docstring|>Return some standard regions.<|endoftext|> |
4f4592f03eb5ebafd28b83b7d601606f1e106ebb881e7f64d7520fce6c88d6a8 | def download_image_with_local_cache(url: str, cache_folder: Path):
"\n Download an image file locally if it doesn't already exist.\n :param url: Image url to download\n :param cache_folder: Where to cache the image\n :return: The local path of the image (either downloaded or previously cached)\n "
cache_folder.mkdir(parents=True, exist_ok=True)
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', 'medium_to_ghost post exporter')]
urllib.request.install_opener(opener)
logging.info(f'Downloading {url} to {cache_folder}')
filename = url.split('/')[(- 1)]
filename = filename.replace('*', '-')
local_destination = (cache_folder / filename)
if local_destination.exists():
logging.info(f'{local_destination} already exists. Using cached copy.')
else:
try:
(local_filename, headers) = urllib.request.urlretrieve(url, local_destination)
except HTTPError as e:
logging.error(f'Download failed for {local_destination}. Error Message: {e.msg}')
return local_destination | Download an image file locally if it doesn't already exist.
:param url: Image url to download
:param cache_folder: Where to cache the image
:return: The local path of the image (either downloaded or previously cached) | medium_to_ghost/image_downloader.py | download_image_with_local_cache | Q42/medium_to_ghost | 120 | python | def download_image_with_local_cache(url: str, cache_folder: Path):
"\n Download an image file locally if it doesn't already exist.\n :param url: Image url to download\n :param cache_folder: Where to cache the image\n :return: The local path of the image (either downloaded or previously cached)\n "
cache_folder.mkdir(parents=True, exist_ok=True)
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', 'medium_to_ghost post exporter')]
urllib.request.install_opener(opener)
logging.info(f'Downloading {url} to {cache_folder}')
filename = url.split('/')[(- 1)]
filename = filename.replace('*', '-')
local_destination = (cache_folder / filename)
if local_destination.exists():
logging.info(f'{local_destination} already exists. Using cached copy.')
else:
try:
(local_filename, headers) = urllib.request.urlretrieve(url, local_destination)
except HTTPError as e:
logging.error(f'Download failed for {local_destination}. Error Message: {e.msg}')
return local_destination | def download_image_with_local_cache(url: str, cache_folder: Path):
"\n Download an image file locally if it doesn't already exist.\n :param url: Image url to download\n :param cache_folder: Where to cache the image\n :return: The local path of the image (either downloaded or previously cached)\n "
cache_folder.mkdir(parents=True, exist_ok=True)
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', 'medium_to_ghost post exporter')]
urllib.request.install_opener(opener)
logging.info(f'Downloading {url} to {cache_folder}')
filename = url.split('/')[(- 1)]
filename = filename.replace('*', '-')
local_destination = (cache_folder / filename)
if local_destination.exists():
logging.info(f'{local_destination} already exists. Using cached copy.')
else:
try:
(local_filename, headers) = urllib.request.urlretrieve(url, local_destination)
except HTTPError as e:
logging.error(f'Download failed for {local_destination}. Error Message: {e.msg}')
return local_destination<|docstring|>Download an image file locally if it doesn't already exist.
:param url: Image url to download
:param cache_folder: Where to cache the image
:return: The local path of the image (either downloaded or previously cached)<|endoftext|> |
0f3a3179d168215d108433bfab6e73d046b5d6a33246eeb5aca7ae16d48deebc | def create_system_groups(self):
"If AgencyGroups corresponding to the SYSTEM_GROUPS don't exist,\n create them. Also, populate self.system_groups"
for (slug, name) in SYSTEM_GROUPS.items():
group = AgencyGroup.objects.filter(slug=slug).first()
if (not group):
with reversion.create_revision():
group = AgencyGroup.objects.create(slug=slug, name=name)
self.system_groups[slug] = group | If AgencyGroups corresponding to the SYSTEM_GROUPS don't exist,
create them. Also, populate self.system_groups | api/reqs/management/commands/sync_agencies.py | create_system_groups | 18F/omb-eregs | 10 | python | def create_system_groups(self):
"If AgencyGroups corresponding to the SYSTEM_GROUPS don't exist,\n create them. Also, populate self.system_groups"
for (slug, name) in SYSTEM_GROUPS.items():
group = AgencyGroup.objects.filter(slug=slug).first()
if (not group):
with reversion.create_revision():
group = AgencyGroup.objects.create(slug=slug, name=name)
self.system_groups[slug] = group | def create_system_groups(self):
"If AgencyGroups corresponding to the SYSTEM_GROUPS don't exist,\n create them. Also, populate self.system_groups"
for (slug, name) in SYSTEM_GROUPS.items():
group = AgencyGroup.objects.filter(slug=slug).first()
if (not group):
with reversion.create_revision():
group = AgencyGroup.objects.create(slug=slug, name=name)
self.system_groups[slug] = group<|docstring|>If AgencyGroups corresponding to the SYSTEM_GROUPS don't exist,
create them. Also, populate self.system_groups<|endoftext|> |
ce1e4cf4ac3f03d19863576f7c0689dbfbbdf9fe0e96f678300e44b5ded11733 | def sync_row(self, row):
'Create/update a single agency from itdashboard.gov'
agency = Agency.objects.filter(omb_agency_code=row['agencyCode']).first()
agency = (agency or Agency(omb_agency_code=row['agencyCode']))
agency.name = row['agencyName']
agency.abbr = (row['agencyAbbreviation'] or agency.abbr)
with reversion.create_revision():
agency.save()
agency.groups.add(self.system_groups['all-agencies'])
if (row['agencyType'] != '5-Other Branches'):
self.system_groups['executive'].agencies.add(agency)
if row['CFO_Act']:
self.system_groups['cfo-act'].agencies.add(agency)
if row['CIO_Council']:
self.system_groups['cio-council'].agencies.add(agency) | Create/update a single agency from itdashboard.gov | api/reqs/management/commands/sync_agencies.py | sync_row | 18F/omb-eregs | 10 | python | def sync_row(self, row):
agency = Agency.objects.filter(omb_agency_code=row['agencyCode']).first()
agency = (agency or Agency(omb_agency_code=row['agencyCode']))
agency.name = row['agencyName']
agency.abbr = (row['agencyAbbreviation'] or agency.abbr)
with reversion.create_revision():
agency.save()
agency.groups.add(self.system_groups['all-agencies'])
if (row['agencyType'] != '5-Other Branches'):
self.system_groups['executive'].agencies.add(agency)
if row['CFO_Act']:
self.system_groups['cfo-act'].agencies.add(agency)
if row['CIO_Council']:
self.system_groups['cio-council'].agencies.add(agency) | def sync_row(self, row):
agency = Agency.objects.filter(omb_agency_code=row['agencyCode']).first()
agency = (agency or Agency(omb_agency_code=row['agencyCode']))
agency.name = row['agencyName']
agency.abbr = (row['agencyAbbreviation'] or agency.abbr)
with reversion.create_revision():
agency.save()
agency.groups.add(self.system_groups['all-agencies'])
if (row['agencyType'] != '5-Other Branches'):
self.system_groups['executive'].agencies.add(agency)
if row['CFO_Act']:
self.system_groups['cfo-act'].agencies.add(agency)
if row['CIO_Council']:
self.system_groups['cio-council'].agencies.add(agency)<|docstring|>Create/update a single agency from itdashboard.gov<|endoftext|> |
4f8b8c6f85295dd8ea08fc55c1c23883be94acff846a905ed84d61c49357f8df | def create_group_revision(self):
"Rather than create a revision for every agency that's added to the\n system groups, we'll create one revision that covers all of the\n additions."
with reversion.create_revision():
for group in self.system_groups.values():
group.save() | Rather than create a revision for every agency that's added to the
system groups, we'll create one revision that covers all of the
additions. | api/reqs/management/commands/sync_agencies.py | create_group_revision | 18F/omb-eregs | 10 | python | def create_group_revision(self):
"Rather than create a revision for every agency that's added to the\n system groups, we'll create one revision that covers all of the\n additions."
with reversion.create_revision():
for group in self.system_groups.values():
group.save() | def create_group_revision(self):
"Rather than create a revision for every agency that's added to the\n system groups, we'll create one revision that covers all of the\n additions."
with reversion.create_revision():
for group in self.system_groups.values():
group.save()<|docstring|>Rather than create a revision for every agency that's added to the
system groups, we'll create one revision that covers all of the
additions.<|endoftext|> |
f11898951d1aa41095cb6b15926cf769cb60046cd1039e3d1a1b19e7da15b58b | def vue_spatial_convolution(self, *args):
'\n Use astropy convolution machinery to smooth the spatial dimensions of\n the data cube.\n '
size = float(self.stddev)
label = f'Smoothed {self._selected_data.label} spatial stddev {size}'
if (label in self.data_collection):
snackbar_message = SnackbarMessage('Data with selected stddev already exists, canceling operation.', color='error', sender=self)
self.hub.broadcast(snackbar_message)
return
attribute = self._selected_data.main_components[0]
cube = self._selected_data.get_object(cls=Spectrum1D, attribute=attribute, statistic=None)
flux_unit = cube.flux.unit
kernel = np.expand_dims(Gaussian2DKernel(size), 2)
snackbar_message = SnackbarMessage('Smoothing spatial slices of cube...', loading=True, timeout=0, sender=self)
self.hub.broadcast(snackbar_message)
convolved_data = convolve(cube, kernel)
newcube = Spectrum1D(flux=(convolved_data * flux_unit), wcs=cube.wcs)
self.app.add_data(newcube, label)
if (self.selected_viewer != 'None'):
self.app.add_data_to_viewer(self.viewer_to_id.get(self.selected_viewer), label, clear_other_data=True)
snackbar_message = SnackbarMessage(f"Data set '{self._selected_data.label}' smoothed successfully.", color='success', sender=self)
self.hub.broadcast(snackbar_message) | Use astropy convolution machinery to smooth the spatial dimensions of
the data cube. | jdaviz/configs/default/plugins/gaussian_smooth/gaussian_smooth.py | vue_spatial_convolution | kecnry/jdaviz | 0 | python | def vue_spatial_convolution(self, *args):
'\n Use astropy convolution machinery to smooth the spatial dimensions of\n the data cube.\n '
size = float(self.stddev)
label = f'Smoothed {self._selected_data.label} spatial stddev {size}'
if (label in self.data_collection):
snackbar_message = SnackbarMessage('Data with selected stddev already exists, canceling operation.', color='error', sender=self)
self.hub.broadcast(snackbar_message)
return
attribute = self._selected_data.main_components[0]
cube = self._selected_data.get_object(cls=Spectrum1D, attribute=attribute, statistic=None)
flux_unit = cube.flux.unit
kernel = np.expand_dims(Gaussian2DKernel(size), 2)
snackbar_message = SnackbarMessage('Smoothing spatial slices of cube...', loading=True, timeout=0, sender=self)
self.hub.broadcast(snackbar_message)
convolved_data = convolve(cube, kernel)
newcube = Spectrum1D(flux=(convolved_data * flux_unit), wcs=cube.wcs)
self.app.add_data(newcube, label)
if (self.selected_viewer != 'None'):
self.app.add_data_to_viewer(self.viewer_to_id.get(self.selected_viewer), label, clear_other_data=True)
snackbar_message = SnackbarMessage(f"Data set '{self._selected_data.label}' smoothed successfully.", color='success', sender=self)
self.hub.broadcast(snackbar_message) | def vue_spatial_convolution(self, *args):
'\n Use astropy convolution machinery to smooth the spatial dimensions of\n the data cube.\n '
size = float(self.stddev)
label = f'Smoothed {self._selected_data.label} spatial stddev {size}'
if (label in self.data_collection):
snackbar_message = SnackbarMessage('Data with selected stddev already exists, canceling operation.', color='error', sender=self)
self.hub.broadcast(snackbar_message)
return
attribute = self._selected_data.main_components[0]
cube = self._selected_data.get_object(cls=Spectrum1D, attribute=attribute, statistic=None)
flux_unit = cube.flux.unit
kernel = np.expand_dims(Gaussian2DKernel(size), 2)
snackbar_message = SnackbarMessage('Smoothing spatial slices of cube...', loading=True, timeout=0, sender=self)
self.hub.broadcast(snackbar_message)
convolved_data = convolve(cube, kernel)
newcube = Spectrum1D(flux=(convolved_data * flux_unit), wcs=cube.wcs)
self.app.add_data(newcube, label)
if (self.selected_viewer != 'None'):
self.app.add_data_to_viewer(self.viewer_to_id.get(self.selected_viewer), label, clear_other_data=True)
snackbar_message = SnackbarMessage(f"Data set '{self._selected_data.label}' smoothed successfully.", color='success', sender=self)
self.hub.broadcast(snackbar_message)<|docstring|>Use astropy convolution machinery to smooth the spatial dimensions of
the data cube.<|endoftext|> |
13d2fadb214814a63ad2cb784a577f4fc3df7ed3738124912c65e02c67d9f8e3 | @singledispatch
def dump_param(val):
'dump a query param value'
return str(val) | dump a query param value | examples/github/query.py | dump_param | theendsofinvention/snug | 123 | python | @singledispatch
def dump_param(val):
return str(val) | @singledispatch
def dump_param(val):
return str(val)<|docstring|>dump a query param value<|endoftext|> |
c722609112a04d3df17d27c68cfeb53f19b4b85195e1ed501698635796d40bcd | def prepare_params(request):
'prepare request parameters'
return request.replace(params={key: dump_param(val) for (key, val) in request.params.items() if (val is not None)}) | prepare request parameters | examples/github/query.py | prepare_params | theendsofinvention/snug | 123 | python | def prepare_params(request):
return request.replace(params={key: dump_param(val) for (key, val) in request.params.items() if (val is not None)}) | def prepare_params(request):
return request.replace(params={key: dump_param(val) for (key, val) in request.params.items() if (val is not None)})<|docstring|>prepare request parameters<|endoftext|> |
0bc87578ef1b18b329d9783f5e520c4f1c3be4934228d66e2e5a2d493f2fc634 | @staticmethod
def parse(response):
'check for errors'
if (response.status_code == 400):
try:
msg = json.loads(response.content)['message']
except (KeyError, ValueError):
msg = ''
raise ApiError(msg)
return response | check for errors | examples/github/query.py | parse | theendsofinvention/snug | 123 | python | @staticmethod
def parse(response):
if (response.status_code == 400):
try:
msg = json.loads(response.content)['message']
except (KeyError, ValueError):
msg =
raise ApiError(msg)
return response | @staticmethod
def parse(response):
if (response.status_code == 400):
try:
msg = json.loads(response.content)['message']
except (KeyError, ValueError):
msg =
raise ApiError(msg)
return response<|docstring|>check for errors<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.