query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
The function of this decorator is to return some fallback value in case an exception was raised during a function call. | def fallback_return_value(
fallback_value: Any,
exceptions: Union[Type[Exception], Tuple[Type[Exception]]] = Exception,
) -> Any:
def decorator(func: Callable) -> Callable:
@functools.wraps(func)
def inner(*args: Any, **kwargs: Any) -> Any:
try:
return func(*args... | [
"def None_if_exception(f, val):\n def decorated_f(*args, **kwargs):\n try:\n x = f(*args, **kwargs)\n except Exception:\n return None\n else:\n return x\n return decorated_f",
"def fallback_call(function):\n def wrapper(self, *args, **kwd):\n \... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Short name for ``linestyle_generator``. To be compatible with previous versions. | def linestyles(colors=_colors, lines=_lines,
markers=_markers, hollow_styles=_marker_types):
return linestyle_generator(colors, lines, markers, hollow_styles) | [
"def line_style(self, *args, **kwargs):\n return _qtgui_swig.const_sink_c_sptr_line_style(self, *args, **kwargs)",
"def line_style(self, *args, **kwargs):\n return _qtgui_swig.freq_sink_f_sptr_line_style(self, *args, **kwargs)",
"def line_style(self, *args, **kwargs):\n return _qtgui_swig.c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the inception score of the generated images imgs imgs Torch dataset of (3xHxW) numpy images normalized in the range [1, 1] cuda whether or not to run on GPU batch_size batch size for feeding into Inception v3 splits number of splits | def inception_score(imgPth, cuda=True, batch_size=32, resize=False, splits=1):
_path = pathlib.Path(imgPth)
N = len(list(_path.glob('*/*.png')))
assert batch_size > 0
assert N > batch_size
# Set up dtype
if cuda:
dtype = torch.cuda.FloatTensor
else:
if torch.cu... | [
"def inception_score(imgs, cuda=True, batch_size=32, resize=False, splits=1):\n N = len(imgs)\n\n assert batch_size > 0\n assert N > batch_size\n\n # Set up dtype\n if cuda:\n dtype = torch.cuda.FloatTensor\n else:\n if torch.cuda.is_available():\n print(\"WARNING: You hav... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Estimates the size of the validator population by computing the average wait time and the average local mean used by the winning validator. Since the entire population should be computing from the same local mean based on history of certificates and we know that the minimum value drawn from a population of size N of ex... | def _compute_population_estimate(cls, certificates):
assert isinstance(certificates, list)
assert len(certificates) >= cls.certificate_sample_length
sum_means = 0
sum_waits = 0
for certificate in certificates[:cls.certificate_sample_length]:
sum_waits += certificate.... | [
"def compute_local_mean(cls, certificates):\n if not isinstance(certificates, (list, tuple)):\n raise TypeError\n\n count = len(certificates)\n if count < cls.fixed_duration_blocks:\n ratio = 1.0 * count / cls.fixed_duration_blocks\n local_mean = \\\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a wait timer in the enclave and then constructs a WaitTimer object. | def create_wait_timer(cls,
validator_address,
certificates):
local_mean = cls.compute_local_mean(certificates)
previous_certificate_id = \
certificates[-1].identifier if certificates else NullIdentifier
# Create an enclave timer o... | [
"def _SessionWaitTimer(self):\n self.start_session_timeout = None\n self.session = cwmp_session.CwmpSession(\n acs_url=self.cpe_management_server.URL, ioloop=self.ioloop)\n self.Run()",
"def timer_setup(self):\n pass",
"def test_timer_manager():\n sc = _client()\n\n with sc.timer('f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the local mean wait time based on the certificate history. | def compute_local_mean(cls, certificates):
if not isinstance(certificates, (list, tuple)):
raise TypeError
count = len(certificates)
if count < cls.fixed_duration_blocks:
ratio = 1.0 * count / cls.fixed_duration_blocks
local_mean = \
(cls.targ... | [
"def _compute_population_estimate(cls, certificates):\n assert isinstance(certificates, list)\n assert len(certificates) >= cls.certificate_sample_length\n\n sum_means = 0\n sum_waits = 0\n for certificate in certificates[:cls.certificate_sample_length]:\n sum_waits += ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Serializes the underlying enclave wait timer | def serialize(self):
if self._serialized_timer is None:
self._serialized_timer = self._enclave_wait_timer.serialize()
return self._serialized_timer | [
"def test_timers():\n timer = Timer('timer', ['sec0', 'sec1'])\n pkl_obj = pickle.dumps(timer)\n new_obj = pickle.loads(pkl_obj)\n assert new_obj.name == timer.name\n assert new_obj.sections == timer.sections\n assert new_obj.value._obj.sec0 == timer.value._obj.sec0 == 0.0\n assert new_obj.valu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make a HTTP request to collect tweets according the search string given. | def request_data(self, search_query=None, app_index=0):
tweet_obj_fields = utils.tweet_object_fields()
tweet_fields = ','.join(tweet_obj_fields["twitter_fields"])
params = {'query': search_query,
'tweet.fields': tweet_fields}
if search_query is None:
raise... | [
"def tweet_search():\n # Connect to Twitter\n api = tweepy.API(getAuth())\n user = api.me()\n\n # Returned variables\n found_tweets = []\n tweet_sentiments = {}\n search_data = []\n query = \"\"\n\n # Process search query\n if request.method == 'GET' and 'q' in request.args:\n q... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" 由 sub_db_id 和 rawid 得到 lngid。 case_insensitive 标识源网站的 rawid 是否区分大小写 | def GetLngid(sub_db_id, rawid, case_insensitive=False):
uppercase_rawid = '' # 大写版 rawid
if case_insensitive: # 源网站的 rawid 区分大小写
for ch in rawid:
if ch.upper() == ch:
uppercase_rawid += ch
else:
uppercase_rawid += ch.upper() + '_'
else:
... | [
"def get_actual_id(translated):",
"def get_primary_id(self):",
"def get_drugbank_id_from_db_id(db_ns, db_id):\n return db_to_drugbank.get((db_ns, db_id))",
"def get_identifier(self):",
"def getLocaleID(self):\n id = self.id\n pieces = filter(None,\n (id.language, id.s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Matrix multiplication between user and product embedding vectors. | def forward(self, user, item):
item_emb = self.product_factors(item.view(-1)) + self.product_bias(
item.view(-1)
)
user_emb = self.user_factors(user.view(-1)) + self.user_bias(user.view(-1))
mat_mult = (item_emb * user_emb).sum(1)
return mat_mult | [
"def matrix_vector_prod(m,u):\n each_product = []\n for v in m:\n each_product.append(dot_prod(v, u))\n return each_product",
"def dot_product_scores(cls, query_vectors, passage_vectors):\n dot_product = torch.matmul(query_vectors, torch.transpose(passage_vectors, 0, 1))\n return dot... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert the probabilities from the final activation into a binary classification. | def _prob_to_class(self, forward):
predict_pos = self.activation(forward)
predict_neg = 1 - predict_pos
return torch.stack((predict_neg, predict_pos)).argmax(0).float() | [
"def predict(self):\n probabilities = self.probability_array()\n # THIS ASSUMES the classifiers are in order: 0th column of the\n # probabilities corresponds to label = 0, ..., 9th col is for 9.\n classes = np.argmax(probabilities, axis=1)\n return classes",
"def convert_prob_in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pull the readme contents for the package properties. | def readme():
with open('README.md') as readme_file:
return readme_file.read() | [
"def readme(self):\n return self.data.get(\"README\", None)",
"def get_long_description():\n\n return read('README.md')",
"def get_description():\n with open('README.rst', 'r', encoding='utf-8') as f:\n return f.read()",
"def readme():\n with open('README.rst') as f:\n return f.r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates matrix data and creates the config objects | def validate_matrix(self, data, **kwargs):
validate_matrix(data.get("params")) | [
"def setup_board(self):\n\n # Load users config file and the schema into vars\n try:\n with open(self.config_dir + '/clue.json', encoding='UTF-8') as file:\n data = json.loads(file.read())\n with open(os.path.dirname(__file__) + '/resources/json/clue-schema.json', ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a ssh key from passed file to user's authorized_keys on server. | def ssh_add_key(self, pub_key_file):
with open(os.path.normpath(pub_key_file), 'rt') as f:
ssh_key = f.read()
if fab.env.user == 'root':
ssh_dir = '/root/.ssh'
else:
if 'home_dir' in fab.env:
ssh_dir = _('%(home_dir)s/.ssh')
else:
... | [
"def ci_userdata_add_authorized_ssh_key(userdata_file, ssh_id_file):\n append_data = {}\n with open(ssh_id_file, encoding=\"utf-8\") as f:\n append_data[\"ssh_authorized_keys\"] = [f.read().strip()]\n\n with open(userdata_file, \"a\") as f:\n yaml.safe_dump(append_data, f,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Saves the given instance of the project or creates a new one if no ID was provided. | def save(self, project_id=None):
if project_id is not None:
project = Project.objects.get(pk=int(project_id))
else:
project = Project()
# Fill out the data of the given project and prepare it
# for saving into database.
project.Name = self.cleaned_d... | [
"def create_project(self, **kwargs):\n save = kwargs.get('save', True) \n if kwargs.has_key('save'):\n del(kwargs['save'])\n\n index = self.object_index()\n defaults = dict(slug = \"test-project-%s\" % index,\n basecamp_url = \"https://foo.basecamphq.com/projects/%s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a list. Returns the item at index i Allows dynamin list indexing in templates | def index(a_list, i):
try:
return a_list[int(i)]
except IndexError:
return None | [
"def get_from_list(self,list_,index):\r\n\r\n\r\n try:\r\n return list_[self._index_to_int(index)]\r\n except IndexError:\r\n self._index_error(list_,index)",
"def __getitem__(self,i):\n return self._items[i]",
"def get_from_list(self, list_, index):\n self._val... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle value with unit. | def handle(self, value, context):
if not isinstance(value, self.data_type):
try:
value = self.data_type(value)
except ValueError:
self.report(value, context)
return
if isinstance(value, Decimal):
value = round_decimal(va... | [
"def unit(self, value):\n\n if value is None: value = ''\n if not isinstance(value, str): raise TypeError('unit type \"%s\" is not a string' % type(value))\n self.__unit = value.strip()",
"def _get_unit(self, value):\n unit = h5attr(value, u'units')\n if unit is None:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
serialize data, currently assuming only one photo | def serialize(self):
return {
"id": self.id,
"title": self.title,
"price": str(self.price),
"description": self.description,
"location": self.location,
"listing_owner": self.listing_owner,
"photos": [photo.serialize() for photo ... | [
"def create_json(self):\n base64im = base64_im.Base64Im()\n base64im.convert(self.file)\n\n file_string = base64im.image\n self.attachment = {\n \"thumbnail\": file_string,\n \"caption\": self.file,\n \"datasetId\": self.pid\n }",
"def serialize(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ex1,d) Определить функцию manhattan(A, B) для нахождения манхэттенского расстояния между точками A и B. | def manhattan(a, b):
return math.fabs(a[0] - b[0]) + math.fabs(a[1] - b[1]) | [
"def manhattan(a, b):\n return abs(a[0] - b[0]) + abs(a[1] - b[1])",
"def manhattan_distance(x, y):\n return abs(x) + abs(y)",
"def manhattan_distance(x, y):\n return abs(x[0] - y[0]) + abs(x[1] - y[1])",
"def _manhattan(pos1, pos2):\n return sum(abs(val1 - val2) for val1, val2 in zip(pos1, pos2))... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get user's tribes. Get full info about all tribes user in which user is editor, manager\ or member. Results can be filtered by the role in tribes. Accessing data of another user is forbidden. | def get(self, user_id):
# Users can fetch only their own teams
if current_user.id != int(user_id):
abort(403)
user = User.get_if_exists(user_id)
tribes = set()
if 'role' not in request.args:
tribes.update(user.editing)
tribes.update([l.team.... | [
"def tribe(self, instance):\r\n return instance.user.profile.tribe",
"async def get_trophies(\n self, user: discord.User,\n pb=False, brawler_name: str = None\n ):\n\n brawlers = await self.get_player_stat(user, \"brawlers\")\n\n stat = \"trophies\" if not pb else \"pb\"\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Divide string list into equally sized parts for inline column placement. The order goes from column to column (vertically). | async def divide_into_vertical_columns(content_list, column_amount):
base_column_size, extras = divmod(len(content_list), column_amount)
column_strings = []
content_list_index = 0
for i in range(column_amount):
column_size = base_column_size
if extras > i:
column_size += 1
... | [
"async def divide_into_horizontal_columns(content_list, column_amount):\n column_strings = []\n for i, content in enumerate(content_list):\n column_index = i % column_amount\n if len(column_strings) < column_amount:\n column_strings.append(content)\n else:\n column_s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Divide string list into equally sized parts for inline column placement. The order goes from row to row (horizontally). | async def divide_into_horizontal_columns(content_list, column_amount):
column_strings = []
for i, content in enumerate(content_list):
column_index = i % column_amount
if len(column_strings) < column_amount:
column_strings.append(content)
else:
column_strings[colum... | [
"async def divide_into_vertical_columns(content_list, column_amount):\n base_column_size, extras = divmod(len(content_list), column_amount)\n\n column_strings = []\n content_list_index = 0\n for i in range(column_amount):\n column_size = base_column_size\n if extras > i:\n colum... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get Monthly Profile. Plot the monthly profile of a given variable (or category of variables) grouped by a given condition (or set of conditions). | def monthly_profile(metdat, catinfo, category=None, basecolor='cycle'):
if category is None:
print('not sure what to plot...')
pass
months = utils.monthnames()
colors = utils.get_colors(len(months), basecolor=basecolor)
colnames, vertlocs, ind = utils.get_vertical_locations(catinfo['co... | [
"def monthly_stability_profiles(metdat, catinfo, category=None, vertloc=80, basecolor='span'):\n\n if category is None:\n print('not sure what to plot...')\n pass\n\n stab, stabloc, ind = utils.get_vertical_locations(catinfo['columns']['stability flag'], location=vertloc)\n\n plotdat = metdat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get Stability Profile. Plot the stability profile of a given variable (or category of variables) grouped by a given condition (or set of conditions). | def stability_profile(metdat, catinfo, category=None, vertloc=80, basecolor='cycle'):
if category is None:
print('not sure what to plot...')
pass
stab, stabloc, ind = utils.get_vertical_locations(catinfo['columns']['stability flag'], location=vertloc)
colors = utils.get_colors(5,basecolor=... | [
"def plot_profile_statistics():",
"def plot_stability_function(self,bounds=[-20,1]):\n import matplotlib.pyplot as plt\n p,q=self.stability_function()\n xx=np.arange(bounds[0], bounds[1], 0.01)\n yy=p(xx)/q(xx)\n fig, = plt.plot(xx,yy)\n plt.draw()",
"def plot_stability... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get Monthly Stability Profile. Plot the monthly stability profile of a given variable (or category of variables) grouped by a given condition (or set of conditions). | def monthly_stability_profiles(metdat, catinfo, category=None, vertloc=80, basecolor='span'):
if category is None:
print('not sure what to plot...')
pass
stab, stabloc, ind = utils.get_vertical_locations(catinfo['columns']['stability flag'], location=vertloc)
plotdat = metdat.groupby([met... | [
"def stability_profile(metdat, catinfo, category=None, vertloc=80, basecolor='cycle'):\n\n if category is None:\n print('not sure what to plot...')\n pass\n\n stab, stabloc, ind = utils.get_vertical_locations(catinfo['columns']['stability flag'], location=vertloc)\n colors = utils.get_colors(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get Hourly Averaged Profile. Plot the hourly averaged profile of a given variable (or category of variables) grouped by a given condition (or set of conditions). | def hourlyplot(metdat, catinfo, category=None, basecolor='span'):
if category is None:
print('not sure what to plot...')
pass
colors = utils.get_colors(len(catinfo['columns'][category]), basecolor=basecolor, reverse=True)
colnames, vertlocs, ind = utils.get_vertical_locations(catinfo['colu... | [
"def plot_profile_statistics():",
"def stability_profile(metdat, catinfo, category=None, vertloc=80, basecolor='cycle'):\n\n if category is None:\n print('not sure what to plot...')\n pass\n\n stab, stabloc, ind = utils.get_vertical_locations(catinfo['columns']['stability flag'], location=vert... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get Monthly Wind Rose Figure. Plot the monthly wind rose of a given variable (or category of variables) grouped by a given condition (or set of conditions). | def monthly_rose_fig(metdat, catinfo, category=None, vertloc=80, bins=6, nsector=36, ylim=None, noleg=False):
# set up data
dircol, _, _= utils.get_vertical_locations(catinfo['columns']['direction'], location=vertloc)
varcol, vertloc, _= utils.get_vertical_locations(catinfo['columns'][category], locati... | [
"def make_daily_rad_plot(ctx):\n # Get clear sky theory\n theory = meteorology.clearsky_shortwave_irradiance_year(\n ctx['_nt'].sts[ctx['station']]['lat'],\n ctx['_nt'].sts[ctx['station']]['elevation'])\n\n icursor = ctx['pgconn'].cursor(cursor_factory=psycopg2.extras.DictCurs... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get Wind Direction Scatter Figure. Plot the wind direction scatter of a given variable (or category of variables) grouped by a given condition (or set of conditions). | def winddir_scatter(metdat, catinfo, category, vertloc=80, basecolor='red', exclude_angles=[(46, 228)]):
# set up data
dircol, _, _= utils.get_vertical_locations(catinfo['columns']['direction'], location=vertloc)
varcol, vertloc, _= utils.get_vertical_locations(catinfo['columns'][category], location=vertl... | [
"def plot_scatter_wdir(x_wdir_series, y_wdir_series, x_label=None, y_label=None,\n x_limits=(0, 360), y_limits=(0, 360)):\n if x_label is None:\n x_label = x_wdir_series.name + ' [°]'\n if y_label is None:\n y_label = y_wdir_series.name + ' [°]'\n scat_plot = plot_scatter... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get Wind Direction Stability Scatter Figure. Plot the wind direction stability scatter of a given variable (or category of variables) grouped by a given condition (or set of conditions). | def stability_winddir_scatter(metdat, catinfo, category, vertloc=80, basecolor='red', exclude_angles=[(46, 228)]):
stabconds = utils.get_stabconds()
colors = utils.get_colors(len(stabconds),basecolor='span')
nrelcolors = utils.get_nrelcolors()
# Set up data
dircol, _, _= utils.get_vertical_lo... | [
"def plot_scatter_wdir(x_wdir_series, y_wdir_series, x_label=None, y_label=None,\n x_limits=(0, 360), y_limits=(0, 360)):\n if x_label is None:\n x_label = x_wdir_series.name + ' [°]'\n if y_label is None:\n y_label = y_wdir_series.name + ' [°]'\n scat_plot = plot_scatter... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get Monthly Histogram Figure. Plot the monthly histogram of a given variable (or category of variables) grouped by a given condition (or set of conditions). | def monthly_hist(metdat, catinfo, category, vertloc=80, basecolor='blue'):
colors = utils.get_nrelcolors()
color = colors[basecolor][0]
months = utils.monthnames()
# set up data
varcol, vertloc, _= utils.get_vertical_locations(catinfo['columns'][category], location=vertloc)
temp = met... | [
"def monthlyhist(t,y,ylim=0.1,xlabel='',ylabel='',title='',**kwargs):\r\n month = othertime.getMonth(t)\r\n fig=plt.gcf()\r\n \r\n for m in range(1,13):\r\n \r\n # Find the values\r\n ind = np.argwhere(month==m)\r\n data=y[ind]\r\n \r\n ax=plt.subplot(6,2,m)\r\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get Stability Grouped Histogram Figure. Plot the stability grouped histogram of a given variable (or category of variables) grouped by a given condition (or set of conditions). | def hist_by_stability(metdat, catinfo, category, vertloc=80, basecolor='span'):
stabconds = utils.get_stabconds()
stabcol, _, _= utils.get_vertical_locations(catinfo['columns']['stability flag'], location=vertloc)
varcol, vertloc, _= utils.get_vertical_locations(catinfo['columns'][category], location=vertl... | [
"def stacked_hist_by_stability(metdat, catinfo, category, vertloc=80):\n\n stabconds = utils.get_stabconds()\n stabcol, _, _= utils.get_vertical_locations(catinfo['columns']['stability flag'], location=vertloc)\n varcol, vertloc, _= utils.get_vertical_locations(catinfo['columns'][category], location=vertlo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get Stacked Stability Grouped Histogram Figure. Plot the stacked stability grouped histogram of a given variable (or category of variables) grouped by a given condition (or set of conditions). | def stacked_hist_by_stability(metdat, catinfo, category, vertloc=80):
stabconds = utils.get_stabconds()
stabcol, _, _= utils.get_vertical_locations(catinfo['columns']['stability flag'], location=vertloc)
varcol, vertloc, _= utils.get_vertical_locations(catinfo['columns'][category], location=vertloc)
co... | [
"def monthly_stacked_hist_by_stability(metdat, catinfo, category, vertloc=80):\n\n stabconds = utils.get_stabconds()\n stabcol, _, _= utils.get_vertical_locations(catinfo['columns']['stability flag'], location=vertloc)\n varcol, vertloc, _= utils.get_vertical_locations(catinfo['columns'][category], locatio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get Monthly Stacked Stability Grouped Histogram Figure. Plot the monthly stacked stability grouped histogram of a given variable (or category of variables) grouped by a given condition (or set of conditions). | def monthly_stacked_hist_by_stability(metdat, catinfo, category, vertloc=80):
stabconds = utils.get_stabconds()
stabcol, _, _= utils.get_vertical_locations(catinfo['columns']['stability flag'], location=vertloc)
varcol, vertloc, _= utils.get_vertical_locations(catinfo['columns'][category], location=vertloc... | [
"def stacked_hist_by_stability(metdat, catinfo, category, vertloc=80):\n\n stabconds = utils.get_stabconds()\n stabcol, _, _= utils.get_vertical_locations(catinfo['columns']['stability flag'], location=vertloc)\n varcol, vertloc, _= utils.get_vertical_locations(catinfo['columns'][category], location=vertlo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get Normalized Monthly Stability Grouped Histogram Figure. Plot the normalized monthly stability grouped histogram of a given variable (or category of variables) grouped by a given condition (or set of conditions). | def normalized_monthly_hist_by_stability(metdat, catinfo, vertloc=80):
months = utils.monthnames()
hours = np.arange(24)
stabcol, _, _= utils.get_vertical_locations(catinfo['columns']['stability flag'], location=vertloc)
stabconds = utils.get_stabconds()
colors = utils.get_colors(5,basecolor='span'... | [
"def monthly_stacked_hist_by_stability(metdat, catinfo, category, vertloc=80):\n\n stabconds = utils.get_stabconds()\n stabcol, _, _= utils.get_vertical_locations(catinfo['columns']['stability flag'], location=vertloc)\n varcol, vertloc, _= utils.get_vertical_locations(catinfo['columns'][category], locatio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the label associated with an instance's note_type. | def get_note_type_label(self):
id, note_type = self.NOTE_TYPE_CHOICES[self.note_type]
return note_type | [
"def get_label (typ):\n return Label (fli._get_label (typ))",
"def label_type(self) -> str:\n return pulumi.get(self, \"label_type\")",
"def label(self):\n if self._label is not None:\n return str(self._label)\n else:\n return self.__class__.__name__",
"def get_la... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the label associated with an instance's variant_type. | def get_variant_type_label(self):
id, variant_type = self.VARIANT_TYPE_CHOICES[self.variant_type]
return variant_type | [
"def label_type(self) -> str:\n return pulumi.get(self, \"label_type\")",
"def get_label (typ):\n return Label (fli._get_label (typ))",
"def label(self):\n if self._label is not None:\n return str(self._label)\n else:\n return self.__class__.__name__",
"def get_la... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Override the create method. Create or get the single object. If one already exists, delete it and create a new one so we autoincrement the id. | def create(self, *args, **kwargs):
obj, created = self.get_or_create(stub=self.model.STUB_DEFAULT)
if not created:
with transaction.atomic():
obj.delete()
obj = self.create(stub=self.model.STUB_DEFAULT)
return obj | [
"def fetch_or_create_id(self):\n if not self.id:\n obj = self.get(self.value, self.scheme)\n if obj:\n self = obj\n else:\n self.id = uuid.uuid4()\n return self",
"def fetch_or_create_id(self):\n self.source = self.source.fetch_or... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates counts of Name objects by Name Type. Statistics are based off of the queryset returned by visible. The total number is calculated using the count method. All additional figures are calculated using Python to reduce the number of queries. | def active_type_counts(self):
names = self.visible()
return {
'total': names.count(),
'personal': len([n for n in names if n.is_personal()]),
'organization': len([n for n in names if n.is_organization()]),
'event': len([n for n in names if n.is_event()]),
... | [
"def count_by_typename(self):\n return self.count_by(lambda obj: type(obj).__name__)",
"def count(self, types=(), path=None, filterPermissions=True):\n\n if not self.is_model_catalog_enabled():\n return None\n\n if path is None:\n path = '/'.join(self.context.getPhysical... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the number of Names by month according to the date_column passed in. This will return a ValueQuerySet where each element is in the form of { | def _counts_per_month(self, date_column):
def grouper(name):
return (getattr(name, date_column).year,
getattr(name, date_column).month)
def convert_key(year, month):
datetime_obj = datetime(year=year, month=month, day=1)
tzinfo = timezone.get_curr... | [
"def get_docs_by_month(self):\n docs_by_month = self.get_revisions().annotate(\n year=Extract('received_date', what_to_extract='year'),\n month=Extract('received_date', what_to_extract='month')\n ).values('year', 'month').annotate(Count('pk'))\n return format_results(docs_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of the number of Names created per month. | def created_stats(self):
return self._counts_per_month('date_created') | [
"def orders_per_month():\n months = []\n month = 1\n for _ in range(12):\n months.append(Order.objects.filter(created__month=f'{month}').count())\n month += 1\n return months",
"def get_months(self):\n months = mcache.get_months()\n if months is not None:\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of the number of Names modified per month. | def modified_stats(self):
return self._counts_per_month('last_modified') | [
"def get_months(self):\n months = mcache.get_months()\n if months is not None:\n return months\n\n posts = self.base_query().fetch()\n names = []\n for post in posts:\n names.append('%d/%02d' % (post.date_published.year, post.date_published.month))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the absolute url to the Name detail page. | def get_absolute_url(self):
return reverse('name:detail', args=[self.name_id]) | [
"def get_absolute_url(self):\n return reverse('character-detail', args=[str(self.name)])",
"def get_absolute_url(self):\n return reverse('armor-detail', args=[str(self.name)])",
"def get_absolute_url(self):\n return reverse('spell-detail', args=[str(self.name)])",
"def get_absolute_url(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the appropriate schema url based on the name type. | def get_schema_url(self):
return self.NAME_TYPE_SCHEMAS.get(self.name_type, None) | [
"def resolver(schema):\n name = schema.__name__\n if name.endswith(\"Schema\"):\n return name[:-6] or name\n return name",
"def get_object_type_url(schema_obj):\n\n if (isinstance(schema_obj, schema.Command) or\n isinstance(schema_obj, schema.CommandResponse) or\n isinstance(schema_obj,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the date display labels according to the Name's name type See Name.DATE_DISPLAY_LABELS | def get_date_display(self):
return self.DATE_DISPLAY_LABELS.get(self.name_type) | [
"def index_label(frequency):\n return {'D': 'date',\n 'M': 'month'}[frequency]",
"def search_display_date(self):\n return ''",
"def day_name(self, locale=None) -> npt.NDArray[np.object_]:\n values = self._local_timestamps()\n\n result = fields.get_date_name_field(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
True if the Name has a current location in the location_set. | def has_current_location(self):
return self.location_set.current_location is not None | [
"def has_location_info(self):\n return bool(self.venue_name or self.room_name)",
"def has_geocode(self):\n if self.location_set.count():\n return True\n else:\n return False",
"def has_set(self, name: str) -> bool:\n return name in self.set_list()",
"def has_l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
True if the instance has one or more related Locations. | def has_geocode(self):
if self.location_set.count():
return True
else:
return False | [
"def has_location_info(self):\n return bool(self.venue_name or self.room_name)",
"def contains_locations_with_fire(self):\r\n return any(\r\n location.fire_cntr for location in self.locations_list\r\n )",
"def has_current_location(self):\n return self.location_set.current_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
True if the instance has a schema url. | def has_schema_url(self):
return self.get_schema_url() is not None | [
"def _has_schema(self):\n return self.get_attr('_has_schema', False)",
"def check_schema_uri(self):\n import asdf\n\n if self.schema_uri is not None:\n with log.augment_exception(\"Invalid ASDF schema URI:\", self.schema_uri):\n asdf.schema.load_schema(self.schema_ur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test if the instance of Name is a certain Name Type. Accepts the id of the Name Type, and returns a boolean. | def _is_name_type(self, type_id):
return type_id == self.name_type | [
"def is_type(self, type_name):\n\n return type_name in self._symtab",
"def has_name(self, name):\r\n return name in self.classes",
"def has_name(self, name):\n return name in self.classes",
"def has_name(self, name):\n\t\treturn name in self.classes",
"def explore_type(name, datatype, is_ch... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
True if the Name has the Name Type Personal. | def is_personal(self):
return self._is_name_type(self.PERSONAL) | [
"def _is_name_type(self, type_id):\n return type_id == self.name_type",
"def knownAs(self, name):\n name = name.lower()\n mine = self.name.lower()\n return name == mine or name in mine.split()",
"def HasBookName(self) -> bool:",
"def is_named(self):\n return self._name != \"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
True if the Name has the Name Type Organization. | def is_organization(self):
return self._is_name_type(self.ORGANIZATION) | [
"def is_organization(self):\n return self.user_id is None",
"def isSetOrganization(self):\n return _libsbml.ModelCreator_isSetOrganization(self)",
"def test_organization_valid_name(self):\n hufflepuffs = models.Organization(name='hufflepuffs', title='Huffle Puffs')\n self.assertFalse... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
True if the Name has the Name Type Event. | def is_event(self):
return self._is_name_type(self.EVENT) | [
"def _is_name_type(self, type_id):\n return type_id == self.name_type",
"def test_has_name(self):\n for klass in Event.__subclasses__():\n self.assertTrue(hasattr(klass, 'NAME'),\n f'{klass.__name__} is missing attribute NAME')",
"def isSetName(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
True if the Name has the Name Type Software. | def is_software(self):
return self._is_name_type(self.SOFTWARE) | [
"def __contains__(self, name_or_package):\n for package, wool in self.wools.items():\n if name_or_package == package or (\n name_or_package.lower() == wool.id()):\n return True\n\n return False",
"def is_valid_license_type(self):\n clean = self.lic... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
True if the Name has the Name Type Building. | def is_building(self):
return self._is_name_type(self.BUILDING) | [
"def _is_name_type(self, type_id):\n return type_id == self.name_type",
"def is_type(self, type_name):\n\n return type_name in self._symtab",
"def has_name(self, name):\r\n return name in self.classes",
"def hasname(self):\n\t\treturn self.name is not None",
"def has_name(self, name):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test if the instance of Name has a particular record_status. Accepts the id of the Name Type, and returns a boolean. | def _is_record_status(self, status_id):
return status_id == self.record_status | [
"def is_record(filename, recordname):\n logger = logging.getLogger(__name__)\n logger.debug('Checking if {} is a record defined in {}'.format(recordname, filename))\n if os.path.isfile(filename):\n with open(filename, 'r') as filehandler:\n for line in filehandler:\n if 're... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
True if the Name has the Deleted status. | def is_deleted(self):
return self._is_record_status(self.DELETED) | [
"def is_deleted(self):\n if self.file_name_length == DIRENT_DELETED:\n return True\n return False",
"def is_deleted(self):\n return self.state == TrackState.Deleted",
"def deleted(self) -> bool:\n return pulumi.get(self, \"deleted\")",
"def is_deleted(file):\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
True if the Name has the Suppressed status. | def is_suppressed(self):
return self._is_record_status(self.SUPPRESSED) | [
"def is_settled(self):\n status_bits = self._status_bits\n mask = 0x00002000\n return bool(status_bits & mask)",
"def any_held(self) -> bool:\n return self.counts()[JobStatus.HELD] > 0",
"def did_not_address_topic(self, name):\n return not any(t for t in self.topics_addressed ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Render the Markdown biography to HTML. | def render_biography(self):
return markdown2.markdown(self.biography) | [
"def _render_markdown(self, caller=None):\n if not caller:\n return ''\n output = caller().strip()\n return markdown(self.environment, output)",
"def rendered_description(self):\n return markdown(self.description)",
"def html(c: str):\n markdown(c)",
"def __html__(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Normalize the name attribute and assign it the normalized_name attribute. | def __normalize_name(self):
self.normalized_name = normalizeSimplified(self.name) | [
"def _normalize_name(name):\n if name:\n return name",
"def normalize_name(cls, name):\n\t\treturn ' '.join(name.lower().strip().split())",
"def normalize(self, attr_name): # DONE\n self.data[attr_name] = (self.data[attr_name] - self.data[attr_name].mean()) / self.data[attr_name].std()"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use the normalized_name attribute and the Location.URL to attempt to find the instance's location. A location is only attached if the server responds with a single result. | def __find_location(self):
URL_RESOURCE = 'http://maps.googleapis.com/maps/api/geocode/json'
URL_QUERY_TEMPLATE = '?address={address}&sensor=true'
URL = URL_RESOURCE + URL_QUERY_TEMPLATE
url = URL.format(address=quote(self.normalized_name))
payload = json.load(urlopen(url))
... | [
"def get_location(self):\n return self.request({\n \"path\": \"/\" + UUID + \"/location\"\n })",
"def founding_location(self) -> object:\n return self._founding_location",
"def location(self):\n # if the input was a string, we do a google lookup\n if isinstance(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use the BaseTicketing object to assign a name_id. | def __assign_name_id(self):
if not self.name_id:
self.name_id = str(BaseTicketing.objects.create()) | [
"def id_name(self, id_name):\n self._id_name = id_name",
"def _set_name_id(session, name_id):\n session['_saml2_session_name_id'] = code(name_id)",
"def setName(self, name):\n self.name = name\n self.setAt_id(name.strip())",
"def ticket_id(self, ticket_id):\n self._ticket_id = t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Filters through a Name object's related locations and returns the one marked as current. | def _get_current_location(self):
return self.get_queryset().filter(status=self.model.CURRENT).first() | [
"def current_name(self):\n return self.name_set.order_by('-vote')[0]",
"def lookin(self, location):",
"def get_location_by_name(name):\n\n return Location.query.filter(Location.name == name).first()",
"def founding_location(self) -> object:\n return self._founding_location",
"def get_canoni... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
True if the Location has a status of Current. | def is_current(self):
return self.CURRENT == self.status | [
"def has_current_location(self):\n return self.location_set.current_location is not None",
"def is_current(self) -> Optional[bool]:\n return pulumi.get(self, \"is_current\")",
"def is_current(self) -> Optional[pulumi.Input[bool]]:\n return pulumi.get(self, \"is_current\")",
"def is_alive(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clone the project repository into a host instance. | def clone(context, instance, user=get_local_user(), branch=BRANCH):
local = False
no_stack = None
no_compose = False
env_path = f"{HOST_PATH}/{instance}/.envs"
env_file = f"{instance}.tar.gz"
command = f"tar czvf .envs/{env_file} .envs/.{instance}"
run_command(context, user, local, instanc... | [
"def git_clone_target_repo(self):\r\n self.repo = git.Repo.clone_from(self.target_repo_url, self.local_gitlab_runner_repo)\r\n print(\"Cloning Repo - completed ....\")",
"def clone_project(project):\n print(project.url + \".git\")\n dirname = ''.join(random.choice(string.ascii_uppercase + stri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the magic string method on a full board works. | def test_str(self):
board = self.board_class()
board.place_token(1, 1, 'X')
board.place_token(0, 0, 'O')
board.place_token(1, 0, 'X')
assert str(board) == 'O|X| \n |X| \n | | \n' | [
"def test_string(self):\n expected_empty_board_string = ' | | \\n---------\\n | | \\n---------\\n | | '\n self.assertEqual(str(self.game), expected_empty_board_string)\n\n for row in range(self.game._dim):\n for col in range(self.game._dim):\n self.game._bo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that calculating a winner returns None when no winner. | def test_calc_winner_none(self):
board = self.board_class()
board.place_token(1, 1, 'X')
board.place_token(0, 0, 'O')
board.place_token(1, 0, 'X')
board.place_token(0, 2, 'O')
assert board.calc_winner() is None | [
"def test_is_winner_is_incorrect(self):\n assert not Bet.is_winner(3, 5)",
"def test_game_no_winner(self):\n gs = GameState()\n state = gs.reset()\n self.assertEquals(gs.getWinner(state),None)\n\n state = [1,1,-1,0,0,0,0,0,0]\n self.assertEquals(gs.getWinner(stat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that calculating a winner returns the winner. | def test_winner_won(self):
board = self.board_class()
board.place_token(1, 1, 'X')
board.place_token(0, 0, 'O')
board.place_token(1, 0, 'X')
board.place_token(0, 2, 'O')
board.place_token(1, 2, 'X')
assert board.calc_winner() == 'X' | [
"def test_calculate_net_as_winner(self):\n assert 45 == Bet.calculate_net(5, 9.0, True)",
"def test_determine_payout_as_winner(self):\n assert 9.0 == Bet.determine_payout(9.0, True)",
"def test_is_winner_is_incorrect(self):\n assert not Bet.is_winner(3, 5)",
"def winner(strategy0, strateg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Key The key to search for Value A value to check equality for Path The path in the spec to search True if the spec doc has the key. If value is passed in, True only if key is present and equal to value | def specifies(self, key, value=None, path=None):
try:
if path != None and isDict(multiIndex(self.current_state, path)):
target = multiIndex(self.current_state, path)
logging.debug("Specification found: ")
logging.debug("Key : " + key)
... | [
"def check_key(self, path: str) -> bool:",
"def contains(self, k: _MultiValueMap__K, v: _MultiValueMap__V) -> bool:\n ...",
"def search(self, key, value):\n\n if key == 'source':\n return value in self._sources.values()\n elif key == 'title':\n value = value.replace(' ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Train ocr for a number of steps. | def train():
with tf.Graph().as_default():
global_step = tf.contrib.framework.get_or_create_global_step()
# Get images and labels for ocr.
print("Preparing input")
# with tf.device('/cpu:0'):
images, labels, seq_lengths = ocr.distorted_inputs()
# Build a Graph that ... | [
"def train(self):\n self.run_epoch()",
"def train(self, total_iter, path1, path2):\n print(\"***pre-train***\")\n for i in range(total_iter):\n self.trainW()\n if i == total_iter - 1:\n self.output(path1, self.wordsVec)\n print(\"***fine-turning***\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Explain one or more input instances. | def explain_instance(self, *argv, **kwargs):
return (self.explainer.shap_values(*argv, **kwargs)) | [
"def test_explain_instance_errors(self):\n explain_class_value_error1 = ('The *{}* explained class name was not '\n 'recognised. The following class names '\n 'are allowed: {}.')\n explain_class_value_error2 = ('The explained cl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Explain one or more input instances. | def explain_instance(self, *argv, **kwargs):
return (self.explainer.shap_values(*argv, **kwargs)) | [
"def test_explain_instance_errors(self):\n explain_class_value_error1 = ('The *{}* explained class name was not '\n 'recognised. The following class names '\n 'are allowed: {}.')\n explain_class_value_error2 = ('The explained cl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns words sorted by cosine distance to a given vector, most similar first | def sorted_by_similarity(words: List[Word], base_vector: Vector) -> List[Tuple[float, Word]]:
words_with_distance = [(cosine_similarity(base_vector, w.vector), w) for w in words]
# We want cosine similarity to be as large as possible (close to 1)
return sorted(words_with_distance, key=lambda t: t[0], revers... | [
"def search_by_cosine(query_vector, index, doc_lengths):\r\n scores = defaultdict(lambda: 0)\r\n for query_term, query_weight in query_vector.items():\r\n for doc_id in index[query_term]['posting']:\r\n scores[doc_id[0]] += query_weight * doc_id[1] \r\n for doc_id in scores:\r\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
object containing photometric point information based on flux and effective wavelength. | def get_photopoint(flux=None,var=None,
datacounts=None, bkgdcounts=None, exptime=None,
lbda=None, zp=None,bandname=None,mjd=None,
source=None, instrument_name=None,**kwargs):
# -------------
# - Parser
if "wavelength" in kwargs.keys() and lbda is None... | [
"def _aperture_to_photopoint_(self, *args, **kwargs):\n\n if not self.has_sky():\n return super(GALEX,self)._aperture_to_photopoint_( *args, **kwargs )\n\n datacps, bkgdcps = args\n datacounts = datacps[0]*self.exposuretime\n bkgdcounts = bkgdcps[0]*self.exposuretime\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This fuctions enable to convert a dictionnary into a list of photopoints. This uses 'photopoint' to load the list. | def dictsource_2_photopoints(dictsource,**kwargs):
if type(dictsource) is not dict:
raise TypeError("'dictsource' must be a dictionnary")
# - Does is have the requiered basic information:
for musthave in ["fluxes","variances","lbda"]:
if musthave not in dictsource.keys():
ra... | [
"def _aperture_to_photopoint_(self, *args, **kwargs):\n\n if not self.has_sky():\n return super(GALEX,self)._aperture_to_photopoint_( *args, **kwargs )\n\n datacps, bkgdcps = args\n datacounts = datacps[0]*self.exposuretime\n bkgdcounts = bkgdcps[0]*self.exposuretime\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Change the slicing of the data. This will update the background, variance and the wcs solution's offset. If you had an sepobjects loaded, this will update it. | def reload_data(self, dataslice0, dataslice1,
variance=None,background=None,mask=None):
rawdata = self.fits[self._build_properties["data_index"]].data[
dataslice0[0]:dataslice0[1],
dataslice1[0]:dataslice1[1]]
# -- no more sepobject attached
reload_sep... | [
"def test_slice_will_set_the_data_attributes_on_camera(self):\n # check the scene render resolution first\n dres = pm.PyNode('defaultResolution')\n dres.width.set(960)\n dres.height.set(540)\n\n rs = RenderSlicer(camera=self.camera)\n rs.slice(10, 20)\n\n self.assert... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Change (or create) an object associated to the given image. This function will test if the object (the target) is withing the image boundaries (expect if 'test_inclusion' is set to False). Set 'newtarget' to None to remove the association between this object and a target. Return Void | def set_target(self, newtarget, test_inclusion=True):
if newtarget is None:
self._side_properties['target'] = None
return
# -- Input Test -- #
if newtarget.__nature__ != "AstroTarget":
raise TypeError("'newtarget' should be (or inherite) an AstroTarge... | [
"def builder_should_create_target_image(self, builder, target, image_id, template, parameters):",
"def replace(self, newPathOrImage):\r\n if newPathOrImage == '': #Create an empty image\r\n self.rect = pygame.Rect(0, 0, 0, 0)\r\n size = self.rect.size\r\n self.originalImag... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Attach a wcs solution to the current object | def set_wcs(self,wcs,force_it=False):
super(Image, self).set_wcs(wcs, force_it=force_it)
if self.has_wcs():
self.wcs.set_offset(*self._dataslicing) | [
"def set_wcs(self, wcs, force_it=False):\n if self.has_wcs() and not force_it:\n raise AttributeError(\"A wcs solution is already loaded.\"\\\n \" Set force_it to True if you really known what you are doing\")\n from .astrometry import get_wcs\n self._side_properti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
attach a catalogue to the current instance. you can then access it through 'self.catalogue'. The current instance's wcs solution is passed to the calague. If the current instance has an sepobjects, sepobjects gains the catalogue and a matching is run. | def set_catalogue(self, catalogue, force_it=False,
match_angsep=3, **kwargs):
super(Image, self).set_catalogue(catalogue, force_it=force_it, **kwargs)
# -- Lets save the pixel values
if self.has_catalogue() and self.has_sepobjects():
self.sepobjects.set_catalog... | [
"def set_catalogue(self, catalogue, force_it=False,\n fast_setup=False):\n from .catalogue.basecatalogue import Catalogue\n\n if not fast_setup:\n if self.has_catalogue() and force_it is False:\n raise AttributeError(\"'catalogue' already defined\"+\\\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
value is the value of the fwhm. If no units is provided (astropy units) arcsec will be assumed. | def set_fwhm(self, value, force_it=True):
if self.has_fwhm() and not force_it:
raise AttributeError("'fwhm' is already defined."+\
" Set force_it to True if you really known what you are doing")
if value<0:
raise ValueError("the 'fwhm' must be positive")
... | [
"def _get_unit(self, value):\n unit = h5attr(value, u'units')\n if unit is None:\n unit = h5attr(value, u'unit')\n # Convert the unit formats\n if unit == \"1/A\":\n unit = \"A^{-1}\"\n elif unit == \"1/cm\":\n unit = \"cm^{-1}\"\n return un... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mask array for ellipse annulus (based on sep) (True for pixels inside the elliptical annulus) Prameters | def get_ellipann_mask(self, x, y, a, b, theta, rin, rout):
from sep import mask_ellipse
ellipsemask_o = np.asarray(np.zeros((self.height,self.width)),dtype="bool")
ellipsemask_i = np.asarray(np.zeros((self.height,self.width)),dtype="bool")
mask_ellipse( ellipsemask_o, x, y, a, b, the... | [
"def derive_sepmask(self, r):\n if not self.has_sepobjects():\n raise AttributeError(\"No sepobjects loaded. Run sep_extract\")\n return self.sepobjects.get_ellipse_mask(self.width,self.height,r=r)",
"def get_ellipse_mask(ellipse, img_shape, offset=0):\n # create image\n mask = np.z... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If a target is loaded, this will get the target coords and run 'get_aperture'. | def get_target_aperture(self,radius,runits="pixels",aptype="circle",subpix=5,
**kwargs):
if self.target is None:
raise AttributeError("No 'target' loaded")
xpix, ypix = self.coords_to_pixel(self.target.ra,self.target.dec)
return self.get_aperture(xpix,ypix... | [
"def __load_target_cloud(self):\n try:\n self.target_cloud = QFileDialog.getOpenFileName(self,\n 'Open file',\n os.getcwd(),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
if a target is loaded, and sep_extract has successfully ran, this returns the idx of the nearest galaxy. (This is build upon the sepobject's get_host_idx() method. It first searches galaxies in a given radius and then returns the index of the one minimizing the elliptical radius (not necesseraly the nearest in angular ... | def get_host_idx(self, scaleup=2.5,
radius=30, runits="kpc",
max_galdist=2., catid=None):
if not self.has_target():
raise AttributeError("No 'target' loaded")
if not self.has_sepobjects():
raise AttributeError("No 'sep... | [
"def __nearest_index(self, array, target_value):\n nparray = np.array(array)\n differences = np.abs(nparray - target_value)\n min_difference = differences.min()\n index = np.nonzero(differences == min_difference)[0][0]\n return index",
"def calc_nearest_ind(self, robot_pose):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
if a target is loaded, this get the aperture of the nearest galaxy. This is build upon the sepobject's get_host_idx() method. It first searches galaxies in a given radius and then returns the index of the one minimizing the elliptical radius (not necesseraly the nearest in angular distance). The aperture photometry fol... | def get_host_aperture(self, scaleup=2.5,
radius=30, runits="kpc",
max_galdist=2., catid=None, **kwargs):
idx = self.get_host_idx(scaleup=scaleup, radius=radius, runits=runits,
max_galdist=max_galdist, catid=catid)
if idx... | [
"def find_host(sources, initialGuess=(2090/2.0, 2108/2.0), searchRadius=200):\n #todo(this fails. It is not selecting the right thing at all.)\n # Where, in array `soucres`, are the objects close to initialGuess?\n\n #make a holding varriable\n centerIDs = []\n #loop through `sources` and save if its... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Measure the aperture photometry on the "noise" part of the image. The "noise" is defined as area remaining after maskingout of the SEP detected object with a scaling up of "scaleup". | def _get_noise_aperture_prop_(self, ncall=1000,
sourcemask=None, edge=10,
rangex=None, rangey=None, scaleup=4):
if sourcemask is None:
sourcemask = self.derive_sepmask( r=scaleup )
# - Range parsing
if range... | [
"def test_aperture_photometry_with_outlier_rejection(reject):\n fake_CCDimage = FakeCCDImage()\n sources = fake_CCDimage.sources\n aperture = sources['aperture'][0]\n inner_annulus = 2 * aperture\n outer_annulus = 3 * aperture\n image = fake_CCDimage.data\n\n found_sources = source_detection(fa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
give the index [list of] of an sep's object(s) and extract the aperture at this location. | def get_idx_aperture(self, idx, scaleup=2.5, **kwargs):
if not self.has_sepobjects():
raise AttributeError("sepobjects has not been set. Run sep_extract()")
x, y, a, b, theta = self.sepobjects.get(["x","y","a","b","theta"], mask=np.atleast_1d(idx)).T
return self.get_aper... | [
"def _set_aperture_elements(self):\n if hasattr(self, 'a'):\n w = self.w\n a = self.a\n b = self.b\n h = self.h\n theta = self.theta\n elif hasattr(self, 'a_in'): # annulus\n w = self.w\n a = self.a_out\n b = self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
units should be a parsable string or a astropy units. Uses the wcs method units_to_pixels() In addition, you have access to the 'psf [==fwhm]' unit | def units_to_pixels(self,units_):
if type(units_) == str and units_.lower() in ["fwhm","psf"]:
units_ = self.fwhm
return super(Image, self).units_to_pixels(units_, target=self.target) | [
"def units_to_pixels(self,units_, target=None):\n if self.has_wcs() is False:\n raise AttributeError(\"no wcs solution loaded.\")\n \n return self.wcs.units_to_pixels(units_,target=target)",
"def wcs_unit_scale(unit):\n for wu in WCS_UNIT_DICT.values():\n if wu.is_equ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this will be used as a default threshold for sep_extract | def _get_sep_extract_threshold_(self):
#print "_get_sep_extract_threshold_ called"
if not hasattr(self,"_sepbackground"):
_ = self.get_sep_background(update_background=False)
return self._sepbackground.globalrms*1.5 | [
"def analyze(self, word_count_thresh):",
"def global_threshold(img, threshold_method):\n pass",
"def medthresh(data,threshold=4):\n return threshold*np.median(np.abs(data)/0.6745)",
"def getThreshold(self): # real signature unknown; restored from __doc__\n pass",
"def _compute_threshold(self,z=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pixel size in arcsec. Based on wcs solution | def pixel_size_arcsec(self):
from astropy import units
if type(self.pixel_size_deg) is not units.quantity.Quantity:
return [ps.to("arcsec") for ps in self.pixel_size_deg]
return self.pixel_size_deg.to("arcsec") | [
"def angular_size_from_wcs(wcs_obj):\n # Get the footprint\n fp = SkyCoord(wcs_obj.calc_footprint(), unit=u.deg) # Clockwise from bottom-left corner\n # Get width (RA)\n width = fp[1].separation(fp[2])\n # Get height (Dec)\n height = fp[0].separation(fp[1])\n return width, height",
"def get_p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
area where SEP detected an object scaled up by `r`. See derive_sepmask | def derive_sepmask(self, r):
if not self.has_sepobjects():
raise AttributeError("No sepobjects loaded. Run sep_extract")
return self.sepobjects.get_ellipse_mask(self.width,self.height,r=r) | [
"def surface_area(r: float) -> float:\r\n result = round(4 * math.pi * r ** 2, 2)\r\n return result",
"def approx_shoulders(upper_body_roi):\n height = upper_body_roi.shape[0]; width = upper_body_roi.shape[1]\n return (int(width / 6), int((height / 4) * 3)), (int((width / 6) * 5), int((height / 4) * 3... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
full width half maximum in arcsec. If you did not set it manually, this will use sepobjects' get_fwhm_pxl() method to set it. | def fwhm(self):
if not self.has_fwhm():
if self.has_sepobjects():
fwhm_pxl = self.sepobjects.get_fwhm_pxl(isolated_only=True,
stars_only=True)
self.set_fwhm(fwhm_pxl/self.units_to_pixels("arcsec").value*\
... | [
"def half_high(self):\r\n\r\n return round(0.1 + self.thickness / 2)",
"def half_low(self):\r\n\r\n return self.thickness // 2",
"def x_lin_half_width(self):\n #This property's name does not mention symlog so that the property \n #could also be used with arcsinh scaled axes in the fu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize the Samplers. Remark that all flux, fluxerr and lbda are requested to draw the samplers | def __init__(self, fluxsamples, lbda=None, empty=False, negative_fluxmag=None):
self.__build__()
if empty:
return
self.set_samplers(fluxsamples)
if lbda is not None:
self.set_lbda(lbda, negative_fluxmag=negative_fluxmag) | [
"def load_samplers(self):\n for sampler in self.gltf.samplers:\n # Use a sane default sampler if the sampler data is empty\n # Samplers can simply just be json data: \"{}\"\n if sampler.minFilter is sampler.magFilter is None:\n self.samplers.append(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
AB magnitude samples derived from the input fluxes (samplers) | def _magsamples(self):
if self._derived_properties["magsamples"] is None:
if self.lbda is None:
raise AttributeError("lbda not set.")
self.derive_magsamples()
return self._derived_properties["magsamples"] | [
"def getABMagnitudes(self):\n if self.sdssFilterCurves is None:\n # Perform one-time initialization of sdssFilterCurves and sdssFilterRates.\n self.sdssFilterCurves = loadSDSSFilterCurves()\n # Tabulate the AB reference spectrum in units of 1e-17 erg/(s*cm^2*Ang) on a ~1 Ang ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
correct the flux and variance for the given extinction. if embv is negative, this will remove flux (i.e. simulate dust absorption). use a positive ebmv to correct for dust extinction. The resulting flux will be higher. | def apply_extinction(self, ebmv, r_v=3.1, law="fitzpatrick99"):
# - Do you have extinction installed
try:
import extinction
except ImportError:
raise ImportError("install the python library 'extinction', pip install extinction. See http://extinction.readthedocs.io")
... | [
"def extinction_correction(filter, EBV, RV=3.1, max_wave=None, required=True):\n # Read in filter in Table\n path_to_filters = os.path.join(resource_filename('frb', 'data'), 'analysis', 'CIGALE')\n # Hack for LRIS which does not differentiate between cameras\n if 'LRIS' in filter:\n _filter = 'LR... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
reset the derived and recorded properties | def _reset_derived_prop_(self):
self._derived_properties["photosamplers"] = None | [
"def reset(self):\r\n instdict = self.__dict__\r\n classdict = self.__class__.__dict__\r\n # To reset them, we simply remove them from the instance dict. At that\r\n # point, it's as if they had never been computed. On the next access,\r\n # the accessor function from the parent... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Define the flux of the photopoint. This defines the rest of the object | def set_flux(self, flux, var):
self._properties["flux"] = np.float(flux)
self._properties["var"] = np.float(var) if var is not None else np.NaN
self._reset_derived_prop_() | [
"def flux(self, x):\n return self.cal_spec.get_flux(self(x))",
"def magnetic_flux(self, *args):\n\t\tarea = self.area(*args)\n\t\tfield = self.los_corr(*args)\n\t\tif isinstance(args[0], np.ndarray):\n\t\t\tself.mgnt_flux = area*field\n\t\treturn area*field",
"def addFluxcal():\n # Overall\n i = s.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Change the name of the bandname. | def set_bandname(self,value):
if value is not None:
if type(value) != str and type(value) != np.string_:
raise TypeError("The bandname must be a string", type(value))
self._properties["bandname"] = value | [
"def ChangeBandname(self, new_bandname):\n self.bandname = new_bandname",
"def set_band_names(self, band_names, imagename=None):\n self.set_option_for_imagename('band_names', imagename, band_names)",
"def bandname(self):\n if self._properties['bandname'] is None:\n self._properti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shift of the magnitude given the target distance (requires target set.) => return `self.mag 5( np.log10(self.target.distmpc1.e6) 1)` | def magabs(self):
if not self.has_target():
raise AttributeError("No target defined, I can't get the distance")
return self.mag - 5*( np.log10(self.target.distmpc*1.e6) - 1) | [
"def calc_new_magnitude(mag_current, distance_current, distance_new):\n\n # Calculate the apparent magnitude of a star given another reference star\n mag_new = mag_current + 5.0 * (np.log10(distance_new/10.0) - np.log10(distance_current/10.0))\n\n return mag_new",
"def set_mag(self, target_mag):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the photosamplers object defining the number of samples available. | def draw_photosamplers(self, nsamplers=5000, negative_fluxmag=None):
self._derived_properties["photosamplers"] = \
PhotoSamplers( np.random.normal(loc=self.flux, scale=np.sqrt(self.var), size=nsamplers),
lbda = self.lbda, negative_fluxmag=negative_fluxmag) | [
"def set_samplers(self, samplers):\n self._derived_properties[\"samplers\"] = samplers\n self.nsamplers = len(self.samplers)",
"def _set_samples(self, value: int) -> None:\n self._samples = value",
"def load_samplers(self):\n for sampler in self.gltf.samplers:\n # Use a sa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this flux quantity will be removed from the current flux | def remove_flux(self, flux, var=None):
self.set_flux(self._properties["flux"] - flux,
self._properties["var"] - var if var is not None else\
self.var) | [
"def subtract_quantity(self, num_of_products=1):\n self.quantity -= num_of_products",
"def decrement_quantity(self, quantity = 1):\n\t\tself.quantity[0] -= quantity",
"def _handleRemoveAction(self):\n \n scene = self.scene()\n if scene != None:\n scene.removeItem(self)\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
converts counts into flux | def cps_to_flux(self, counts):
return counts * 10**(-(2.406+self.zp) / 2.5 ) / (self.lbda**2) | [
"def convert_counts(self):\n \n return self.time_series*self.counts_to_mv_conversion",
"def convert_counts(self):\n \n return self.time_series*self._counts_to_mv_conversion",
"def transform(self, counts):\n return self.transformation_func(counts)",
"def count(self) -> \"Stre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sum of the data and background counts | def totalcounts(self):
return self.datacounts + self.bkgdcounts | [
"def prep_bgd_sums(X,background):\n num_data, data_length, num_features = X.shape\n bgd_sums = np.zeros((num_data,\n data_length))\n log_bgd_inv_prob = np.log(1-background)\n log_bgd_odds = np.log(background) -log_bgd_inv_prob\n for datum_id, x in enumerate(X):\n likes ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |