query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Get the image size the highest magnification image would have to be resized to get an equivalent magnification
def get_size_for_mag(slide, mag): max_size = slide.dimensions max_mag = highest_mag(slide) downsample = max_mag/mag return [np.int(np.round(dim/downsample)) for dim in max_size]
[ "def _get_scaled_image_size(self):\n unscaled_size = self._get_original_image_size()\n return (unscaled_size[0] * self.scale, unscaled_size[1] * self.scale)", "def getZoomFactor(imageSize, maxW, maxH):\n\timageW, imageH = imageSize\n\tzoomW = float(imageW) / float(maxW)\n\tzoomH = float(imageH) / fl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds 5 latest blog posts as `latest_articles`, 5 latest comments as `latest_comments`, and all tags (annotated with `num_articles` field) as `tags` to the context, regardless of `request`.
def latest_content(request): latest_articles = Article.published_articles()[:5] latest_comments = Comment.objects.all().order_by('-pub_date')[:5] tags = Tag.objects.annotate(num_articles=Count('article')).order_by( '-num_articles') contributors = Contributor.objects.annotate( num_article...
[ "def recent_blogs_view(self, request):\n\n return self.render(\n request,\n context_overrides={\n \"title\": \"Latest News\",\n \"blogs\": self.recent_blogs(),\n },\n )", "def last_five(request):\n flag_five = True\n topics = (\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Format a Roku Channel name.
def format_channel_name(channel_number: str, channel_name: str | None = None) -> str: if channel_name is not None and channel_name != "": return f"{channel_name} ({channel_number})" return channel_number
[ "def channel_name(radio_id: int, channel_id: int) -> str:\n return f\"COMM{radio_id} Ch {channel_id}\"", "def gen_channel_name_v2(shotnr: int, channel_rg: str):\n return f\"{shotnr:05d}_ch{channel_rg:s}\"", "def format_channel(discord_id: int) -> str:\n return format_discord_str(discord_id, '#')", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fetcher.get_projects() should return a list of projects.
def test_get_projects_returns_projects(fc: fetcher.Fetcher): projects = fc.get_projects() assert isinstance(projects, list) assert isinstance(projects[0], models.Project)
[ "def get_projects(self):\n projects = []\n page = 1\n while not len(projects) % 100:\n projects += self._get('/projects?{0}'.format(urllib.urlencode({'per_page': 100, 'page': page})))\n if not projects:\n break\n page += 1\n return projects...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fetchet.get_projects() should be able to filter on project.
def test_get_projects_filters(fc: fetcher.Fetcher, test_project_name): projects = fc.get_projects(test_project_name) assert isinstance(projects, list) assert len(projects) == 1 assert projects[0].name == test_project_name
[ "def test_get_projects(self):\n pass", "def test_list_project_request(self):\n pass", "def test_list_projects(self):\n pass", "def test_get_projects_returns_projects(fc: fetcher.Fetcher):\n projects = fc.get_projects()\n assert isinstance(projects, list)\n assert isinstance(proje...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fetcher.get_models() should return a list of models.
def test_get_models_returns_models(fc: fetcher.Fetcher): ml = fc.get_models() assert isinstance(ml, list) assert isinstance(ml[0], models.LookmlModel)
[ "def get_models(self):\n self.load()\n return self._models", "def _get_models():\n from . import models\n return models", "def get_models(self):\n\n base = self.get_base()\n return getattr(base, self.resource).json[\"api_declaration\"][\"models\"]", "def get_models(make):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fetcher.get_models() should be able to filter on project or model.
def test_get_models_filters(fc: fetcher.Fetcher, test_project_name, test_model): ml = fc.get_models(project=test_project_name) assert all(m.project_name == test_project_name for m in ml) ml = fc.get_models(model=test_model["name"]) assert all(m.name == test_model["name"] for m in ml) ml = fc.get_m...
[ "def query_models(\n cls,\n project_name=None, # type: Optional[str]\n model_name=None, # type: Optional[str]\n tags=None, # type: Optional[Sequence[str]]\n only_published=False, # type: bool\n include_archived=False, # type: bool\n max_results=None, # type: Op...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fetcher.get_models() should throw if a model is not found.
def test_get_models_throws_if_model_does_not_exist(fc: fetcher.Fetcher, project, model): with pytest.raises(exceptions.NotFoundError) as exc: fc.get_models(project=project, model=model) assert "An error occured while getting models." in str(exc.value)
[ "def test_get_models_returns_models(fc: fetcher.Fetcher):\n ml = fc.get_models()\n assert isinstance(ml, list)\n assert isinstance(ml[0], models.LookmlModel)", "def _get_models():\n from . import models\n return models", "def test_get_model_method_with_missing_model(self):\n # arrange\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fetcher.get_used_models() should return models that have queries against them.
def test_get_used_models(fc: fetcher.Fetcher, test_model): used_models = fc.get_used_models() assert isinstance(used_models, dict) assert len(used_models) > 0 assert all(type(model_name) == str for model_name in used_models.keys()) assert all(type(query_count) == int for query_count in used_models.v...
[ "def get_loaded_models():\n global loaded_models\n if loaded_models is None:\n loaded_models = get_modules(NETWORKS_DIR)\n\n return loaded_models", "def get_available_models():\n modelpath = os.path.join(os.path.dirname(__file__), \"train\", \"model\")\n models = sorted(item.name.rep...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fetcher.get_explores() should return a list of explores.
def test_get_explores(fc: fetcher.Fetcher): explores = fc.get_explores() assert isinstance(explores, list) assert len(explores) > 0 assert isinstance(explores[0], models.LookmlModelExplore)
[ "def test_get_explores_filters(fc: fetcher.Fetcher):\n explores = fc.get_explores(model=\"henry_dusty\")\n assert all(e.model_name == \"henry_dusty\" for e in explores)\n\n explores = fc.get_explores(model=\"henry_qa\", explore=\"explore_2_joins_all_used\")\n assert all(\n e.model_name == \"henry...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fetcher.get_explores() should be able to filter on model and/or explore.
def test_get_explores_filters(fc: fetcher.Fetcher): explores = fc.get_explores(model="henry_dusty") assert all(e.model_name == "henry_dusty" for e in explores) explores = fc.get_explores(model="henry_qa", explore="explore_2_joins_all_used") assert all( e.model_name == "henry_qa" and e.name == "...
[ "def test_get_explores(fc: fetcher.Fetcher):\n explores = fc.get_explores()\n assert isinstance(explores, list)\n assert len(explores) > 0\n assert isinstance(explores[0], models.LookmlModelExplore)", "def get_explores_from_model(client, model_name, log=LOGGER):\n try:\n return [explore.name...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fetcher.get_explores() should throw if an explore/model is not found.
def test_get_explores_throws_if_model_or_explore_does_not_exist( fc: fetcher.Fetcher, model: Optional[str], explore: Optional[str], msg: str ): with pytest.raises(exceptions.NotFoundError) as exc: fc.get_explores(model=model, explore=explore) assert msg in str(exc.value)
[ "def test_get_explores(fc: fetcher.Fetcher):\n explores = fc.get_explores()\n assert isinstance(explores, list)\n assert len(explores) > 0\n assert isinstance(explores[0], models.LookmlModelExplore)", "def get_explores_from_model(client, model_name, log=LOGGER):\n try:\n return [explore.name...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fetcher.get_used_explores() should return all used explores.
def test_get_used_explores(fc: fetcher.Fetcher, test_model, test_used_explore_names): used_explores = fc.get_used_explores(model=test_model["name"]) assert isinstance(used_explores, dict) assert all(e in test_used_explore_names for e in used_explores)
[ "def test_get_unused_explores(fc: fetcher.Fetcher, test_model, test_unused_explores):\n unused_explores = fc.get_unused_explores(model=test_model[\"name\"])\n assert all(e in test_unused_explores for e in unused_explores)", "def test_get_explores_filters(fc: fetcher.Fetcher):\n explores = fc.get_explores...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fetcher.get_unused_explores() should return all unused explores.
def test_get_unused_explores(fc: fetcher.Fetcher, test_model, test_unused_explores): unused_explores = fc.get_unused_explores(model=test_model["name"]) assert all(e in test_unused_explores for e in unused_explores)
[ "def test_get_used_explores(fc: fetcher.Fetcher, test_model, test_used_explore_names):\n used_explores = fc.get_used_explores(model=test_model[\"name\"])\n assert isinstance(used_explores, dict)\n assert all(e in test_used_explore_names for e in used_explores)", "def unused_exits(self):\n return self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fetcher.get_explore_fields() should return an explores fields.
def test_get_explore_fields_gets_fields( fc: fetcher.Fetcher, test_model, test_explores_stats ): test_explore = test_explores_stats[0] explore = fc.get_explores(model=test_model["name"], explore=test_explore["name"]) assert isinstance(explore, list) explore = explore[0] assert isinstance(explore...
[ "def test_get_explore_fields_gets_fields_for_dimension_or_measure_only_explores(\n fc: fetcher.Fetcher, test_model, test_dimensions_or_measures_only_explores\n):\n expected = test_dimensions_or_measures_only_explores[0]\n explore = fc.get_explores(model=test_model[\"name\"], explore=expected[\"name\"])\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fetcher.get_explore_fields() should return when an explore has only dimensions or only measures.
def test_get_explore_fields_gets_fields_for_dimension_or_measure_only_explores( fc: fetcher.Fetcher, test_model, test_dimensions_or_measures_only_explores ): expected = test_dimensions_or_measures_only_explores[0] explore = fc.get_explores(model=test_model["name"], explore=expected["name"]) assert isins...
[ "def test_get_explore_fields_gets_fields(\n fc: fetcher.Fetcher, test_model, test_explores_stats\n):\n test_explore = test_explores_stats[0]\n explore = fc.get_explores(model=test_model[\"name\"], explore=test_explore[\"name\"])\n assert isinstance(explore, list)\n explore = explore[0]\n assert is...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fetcher.get_explore_field_stats() should get the stats of all fields in an explore.
def test_get_explore_field_stats( fc: fetcher.Fetcher, looker_sdk: methods.Looker40SDK, test_model, test_used_explore_names, test_explores_stats, ): explore = fc.get_explores( model=test_model["name"], explore=test_used_explore_names[0] )[0] actual_stats = fc.get_explore_field_st...
[ "def test_get_explore_fields_gets_fields(\n fc: fetcher.Fetcher, test_model, test_explores_stats\n):\n test_explore = test_explores_stats[0]\n explore = fc.get_explores(model=test_model[\"name\"], explore=test_explore[\"name\"])\n assert isinstance(explore, list)\n explore = explore[0]\n assert is...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fetcher.get_explore_join_stats() should return the stats of all joins in an explore.
def test_get_explore_join_stats(fc: fetcher.Fetcher, test_model): explore = fc.get_explores( model=test_model["name"], explore="explore_2_joins_1_used" )[0] field_stats = { "explore_2_joins_1_used.d1": 10, "explore_2_joins_1_used.d2": 5, "explore_2_joins_1_used.d3": 0, ...
[ "async def getRecentJoins(self, ctx):\n if not await self.has_perms(ctx.author):\n return\n recent_joins = \"__Recent Member Joins:__\"\n tracked_joins = 0\n for name, join_data in self.recently_joined_members[ctx.guild].items():\n num_joins = len(join_data['members...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Normalize audio file to range [1, 1]
def normalize(audio): norm = audio/max(audio) return norm
[ "def NormalizeAudio(data: np.ndarray) -> np.ndarray:\n return data / np.max(np.abs(data))", "def normalize_audio(file_name: str) -> None:\n os.system(f'ffmpeg-normalize \"{file_name}\" -of output -c:a libmp3lame -ext mp3 -q')\n os.remove(file_name)", "def normalize_audio(audio_path: str, output_path: s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load an audio file and segment into 10s increments Save each segment to the target directory. Append the gender of the speaker and the segment index to the filename.
def segment_audio(filename, y_value, split='train', clf='gender'): filepath = 'recordings/recordings/' + filename + '.mp3' audio, sr = librosa.load(filepath, sr=16000) audio = normalize(audio) # Add gender label to filename for later processing sex = y_value if sex == 'female': filenam...
[ "def file_generator(files: list,\n segment_duration: float,\n sampleRate: int,\n db_thr: float or None = None,\n frame_length: int = 512,\n hop_length: int = 128,\n ) -> None:\n\n I = 0\n J = 0\n\n s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load an audio file (or segment). Add random noise to the file and save with new filename.
def noisy_data(filename, split='train', clf='gender'): filepath = 'data/{}/{}/{}o.wav'.format(clf, split, filename) audio, sr = librosa.load(filepath, sr=16000) # Add noise noisy = add_noise(audio) # Write noise to file sf.write('data/{}/{}/{}n.wav'.format(clf, split, filename), noisy, sr) ...
[ "def create_random_wav(file_name):\n sample_rate = 44100.0\n sound_length = 50\n duration = 3000 #MS\n sounds_arr = create_sounds_arr(sample_rate, duration, sound_length)\n wav_file = create_wav_file(file_name)\n save_wav(sounds_arr, wav_file, sample_rate, sound_length)", "def add_silence(self):\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Release a lock on the bus
def bus_release(self): self._bus_lock.release()
[ "def release_lock(self):\n self._multistore._unlock()", "def unlock(lock):\n lock.release()", "def release_lock(cls, obj):\n try:\n obj.__lock.release()\n except AttributeError:\n pass\n except ValueError as ex: # lock release failed (maybe not acquired)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decorator to be used in apimethods to serve the swaggerdocumentation for this api.
def api_documentation(api: str, summary: str, in_model: BaseModel, out_model: BaseModel, out_description: str) -> Callable: for model, name in ((in_model, 'Input'), (out_model, 'Output')): doc.Object( make_dataclass( f'Api{api[1:].title()}{name}', ...
[ "def index():\n definition = {\n \"swagger\": \"2.0\",\n \"info\": {\n \"title\": flask.current_app.config.get(\"APPNAME\", \"Not specified\"),\n \"version\": flask.current_app.config.get(\"VERSION\", \"Not specified\"),\n },\n \"host\": request.host,\n \"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decorator to be used in apimethods to convert the requestdata to an instance of the passed `model`. This instance is passed to the decorated apiendpoint as the parameter `service_params`.
def api_inputmodel(api: str, model: BaseModel, servicename: str, service_logger: logger) -> Callable: def decorator(func): @wraps(func) async def function_wrapper(request, *args, **kwargs): try: service_params = model.parse_raw(request.body) ...
[ "def api_outputmodel(api: str, model: BaseModel, servicename: str,\n service_logger: logger) -> Callable:\n\n def decorator(func):\n @wraps(func)\n async def function_wrapper(request, *args, **kwargs):\n service_result = await func(request, *args, **kwargs)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decorator to be used in apimethods to convert the responsedata of the decorated apimethod to a json based on the passed `model`.
def api_outputmodel(api: str, model: BaseModel, servicename: str, service_logger: logger) -> Callable: def decorator(func): @wraps(func) async def function_wrapper(request, *args, **kwargs): service_result = await func(request, *args, **kwargs) try: ...
[ "def json_view(func):\n @wraps(func)\n def _inner(*args, **kwargs):\n ret = func(*args, **kwargs)\n\n if isinstance(ret, HttpResponse):\n return ret\n\n status_code = 200\n\n if isinstance(ret, tuple) and len(ret) == 2:\n ret, status_code = ret\n\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update attempt to update branch to the given SHA.
def update_branch(self, name, sha): branch_info = { 'sha': sha, } resp = self.patch('git/refs/heads/{}'.format(name), json=branch_info) try: resp.raise_for_status() except Exception: logger.error(resp.json()) raise return ...
[ "def update_latest_branch (product, which, main_branch):\n\n name = \"Latest_ACE7TAO3_\" + which\n\n vprint ('Fast-forwarding', name, 'to', main_branch)\n ex (\"cd $DOC_ROOT/\" + product + \" && git fetch . \" + main_branch + \":\" + name)", "def update(branch='master'):\n\n with cd('/srv/git/mapstor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verify that the release is actually read to be released If the release is new (corresponds to a release branch), then we check that the release is merged into master. If we can not find the release branch, we assume that it is a hotfix and we verify that the major version number matches the latest release.
def check_release_status(self, release_name, release_branch): logger.debug('GitHubAPI.check_release_status args: {}; {}'.format( release_name, release_branch) ) release_version = extract_release_branch_version(release_name) release_branch_base = build_release_base_name(get_co...
[ "def check(self) -> None:\n latest_release_version = self.github_release.get_version()\n local_version = self.executable.get_version()\n\n if latest_release_version and local_version:\n\n if latest_release_version > local_version:\n self.updatable = True\n\n if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads in audio file, processes it
def process_audio_file(self, file_name): sig, sr = librosa.load(file_name, mono=True) return self._extract_function(sig, sr)
[ "def audioRead(path):\n data, samplerate = sf.read(path)\n frames = data.shape[0]\n channels = len(data.shape)\n duration = 1/samplerate*frames\n return data, samplerate, path, duration, frames, channels", "def read_sound(self, inFile):\n\n # Python can natively only read \"wav\" files. To b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Return ``n`` independent symbolic matrices in dimension ``d``.
def symbolic_max_plus_matrices(d, n, ch=None, typ='sym'): d = int(d) n = int(n) if d <= 0: raise ValueError("d (= {}) must be postive".format(d)) nvar = n * d * d V = FreeModule(ZZ, nvar) B = ((b,) for b in V.basis()) matrices = [] if d == 1: typ = 'full' if typ ...
[ "def basis(d, symbolic=True):\n X = sym.symbols('X')\n if d == 0:\n phi_sym = [1]\n else:\n if symbolic:\n h = sym.Rational(1, d) # node spacing\n nodes = [2*i*h - 1 for i in range(d+1)]\n else:\n nodes = np.linspace(-1, 1, d+1)\n \n phi_sym = [Lagrange_poly...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Return a string that describes the convex hull engine.
def convex_hull_engine(self): return self.convex_hull._name
[ "def _repr_(self):\n desc = ''\n if self.n_vertices()==0:\n desc += 'The empty polyhedron'\n else:\n desc += 'A ' + repr(self.dim()) + '-dimensional polyhedron'\n desc += ' in '\n if self.field()==QQ: desc += 'QQ'\n else: desc += 'RDF'\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Return the list of equal coefficients between self and other.
def equal_coefficients(self, other): d = self._d return [(i,j) for i in range(d) for j in range(d) \ if self[i][j] == other[i][j]]
[ "def __xor__(self, other):\n\n sym_diff = [value for value in self if value not in other]\n sym_diff.extend([value for value in other if value not in self])\n\n return sym_diff", "def GetEqualConstrains(self):\n return _gmat_py.Spacecraft_GetEqualConstrains(self)", "def coefficients(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Evaluates this symbolic matrix at the integer point ``p``.
def eval(self, p): from max_plus.max_plus_int import minus_infinity, IntegerMaxPlusMatrix F = FreeModule(ZZ, self._nvars) p = F(p) mat = [] d = self.dim() for i in range(d): row = [] for j in range(d): pts = self[i,j] ...
[ "def eval_poly(self, p):\n A = self\n m, n = A.shape\n\n if m != n:\n raise DMNonSquareMatrixError(\"Matrix must be square\")\n\n if not p:\n return self.zeros(self.shape, self.domain)\n elif len(p) == 1:\n return p[0] * self.eye(self.shape, self.d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Perform a cyclic swap on the vertices. This is used in multiplication of symbolic upper matrices. Currently it is suboptimal but on the other hand, this cost much less than whatever convex hull computation.
def vertex_cyclic_swap(nvars, l, i): if i == 0 or not l: return l ll = [] F = l[0].parent() for v in l: assert not v[-i:] ll.append(F(tuple(v[-i:]) + tuple(v[:-i]))) for v in ll: v.set_immutable() return tuple(ll)
[ "def swap_vertices(self, i, j):\r\n store_vertex_i = self.vertices[i]\r\n store_vertex_j = self.vertices[j]\r\n self.vertices[j] = store_vertex_i\r\n self.vertices[i] = store_vertex_j\r\n for k in range(len(self.vertices)):\r\n for swap_list in [self.vertices[k].childre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a dashboard of plots for time steps, potential, kintetic, and total energy
def create_dashboard(h, t, k, p): plt.style.use('seaborn') # Initialize the dashboard fig = plt.figure(figsize=(20, 8)) ax1 = fig.add_subplot(2, 2, 1) ax2 = fig.add_subplot(2, 2, 2) ax3 = fig.add_subplot(2, 2, 3) ax4 = fig.add_subplot(2, 2, 4) # Create individual graphs dt_line, = a...
[ "def plot_vanHove_dt(comp,conn,start,step_size,steps):\n \n (fin,) = conn.execute(\"select fout from comps where comp_key = ?\",comp).fetchone()\n (max_step,) = conn.execute(\"select max_step from vanHove_prams where comp_key = ?\",comp).fetchone()\n Fin = h5py.File(fin,'r')\n g = Fin[fd('vanHove...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Download and unpack the Zenodo minted data for the current stitches distribution.
def fetch_zenodo(self): # full path to the stitches root directory where the example dir will be stored if self.data_dir is None: data_directory = pkg_resources.resource_filename('stitches', 'data') else: data_directory = self.data_dir # build needed subdirector...
[ "def fetch_zenodo(self):\n\n # retrieve content from URL\n try:\n logging.info(f\"Downloading example data from {self.url}\")\n r = requests.get(self.url, stream=True)\n with io.BytesIO() as stream:\n with tqdm.wrapattr(\n stream,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all morbidities by war name.
def get_morbidities_for_war_era(): war_era_name = request.args.get('warEra') if not war_era_name: raise BadRequestError("warEra parameter is missing") return datasources_service.get_morbidities_for_war_era(war_era_name)
[ "def get_clanwar_leagues(self, tag):\n return self.request(\"clanwarleagues/wars/{warTag}\".format(warTag=tag))", "def get_war_eras():\n return datasources_service.get_war_eras()", "def query_tiles(name):\n return db.MapTile.query.filter(\n db.MapTile.name == TileSet[name].name).first()", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get list of all war eras.
def get_war_eras(): return datasources_service.get_war_eras()
[ "def ewriters():\n return dict(_ewriters)", "def get_morbidities_for_war_era():\n war_era_name = request.args.get('warEra')\n if not war_era_name:\n raise BadRequestError(\"warEra parameter is missing\")\n return datasources_service.get_morbidities_for_war_era(war_era_name)", "def list_shelve...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cancel an withdraw request.
def post_cancel_withdraw(self, withdraw_id: 'int') -> int: params = { "withdraw-id": withdraw_id } from huobi.service.wallet.post_cancel_withdraw import PostCancelWithdrawService return PostCancelWithdrawService(params).request(**self.__kwargs)
[ "def cancel_draw(self):\n self.accept_draw(clear=True)", "def cancel(self, order_id: int):", "def cancel_drawing(self):\n self.accept_drawing(clear=True)", "def cancel():\n context = {'user': toolkit.g.get('user') or toolkit.g.get('author')}\n organization_id = toolkit.request.args.get('or...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the withdraw quota for currencies
def get_account_withdraw_quota(self, currency: 'str') -> list: check_should_not_none(currency, "currency") params = { "currency": currency, } from huobi.service.wallet.get_account_withdraw_quota import GetAccountWithdrawQuotaService return GetAccountWithdrawQuotaSer...
[ "def options_to_withdraw(self, amount):\n counter = PaperMoneyCounter() # aux class\n options = [] # options to withdraw\n remaining_cash = 0 # aux var\n\n if (amount % 20 == 0 or amount % 50 == 0) and (amount <= 1000): # is it allowed to withdraw?\n # prioritizing 100-dollar ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parent get sub user depoist history.
def get_sub_user_deposit_history(self, sub_uid: 'int', currency: 'str' = None, start_time: 'int' = None, end_time: 'int' = None, sort: 'str' = None, limit: 'int' = None, from_id: 'int' = None) -> DepositHistory: check_should_not_none(sub_...
[ "def get_subaccount_transfer_history(self, **params):\n return self._request_margin_api('get', 'sub-account/transfer/subUserHistory', True, data=params)", "def get_sub_account_transfer_history(self, **params):\n return self._request_withdraw_api('get', 'sub-account/transfer/history.html', True, data...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add an obstacle to the map
def add_obstacle(self, obstacle_to_add): if self.obstacles.size != 0: self.obstacles = np.hstack((self.obstacles, obstacle_to_add)) else: self.obstacles = np.array([obstacle_to_add])
[ "def add_obstacle(self, obstacle):\n color = [1.0, 1.0, 1.0]\n frame_name = \"obstacle{}\".format(len(self._obstacles))\n frame = self._add_polydata(obstacle.to_polydata(), frame_name, color)\n self._obstacles.append((obstacle, frame))\n self._update_moving_object(obstacle, frame)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a waypoint to the drone
def add_waypoint(self, waypoint): self.drone.add_waypoint(waypoint)
[ "def waypoint_add_rel(self):\n pass", "def update(self, waypoint):\n self.waypoints.append(waypoint)", "def create_waypoint(self, waypoint):\n connection = self.__create_connection()\n try:\n waypoint_list = list(waypoint)\n key = self.__compound_key(waypoint)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the drone's location in the map
def set_drone_position(self, new_point): self.drone.set_drone_position(new_point)
[ "def set_location(self, x, y):\r\n self.__location = (x, y)", "def set_coordinate(self):\n airqual_dictionary = self.realtime_data['stations'][0] #get the very first(recent) data/result\n self.latitude = airqual_dictionary['lat']\n self.longitude = airqual_dictionary['lng']", "def se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reset the obstacles' positions within the map (should be called when map is refreshed to clean the array)
def reset_obstacles(self): self.obstacles = np.array([])
[ "def clearObstacles(self):\r\n \r\n self.lock.acquire()\r\n self._obstacles = []\r\n self.updated.set()\r\n self.changes.append('obstacles')\r\n self.lock.release()", "def reset_map(self):\n self.grid = np.zeros((self.width, self.height), np.uint8)", "def recreat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate possible paths around the passed obstacle
def generate_possible_paths(self, obstacle): if self.does_uav_intersect_obstacle_vertically(obstacle, self.drone.get_point(), self.drone.get_waypoint_holder().get_current_waypoint()): if self.does_path_intersect_obstacle_2d(obstacle, self.drone.get_point(), self.drone.get_waypoint_holder().get_curre...
[ "def find_path(self, start_point: Pos, end_point: Pos, obstacles: list) -> list:\n pass", "def get_all_paths(grid):\n\n print(\"Calculating all possible paths ... \")\n all_paths = {}\n\n origins = init_origins(grid) # all not wall and obstacle cells\n destinations = init_destinations(grid) #...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine if the UAV intersects an obstacle on the verticle axis
def does_uav_intersect_obstacle_vertically(self, obstacle, drone_point, waypoint): if isinstance(obstacle, StationaryObstacle): if drone_point[2] < obstacle.height + Constants.STATIONARY_OBSTACLE_SAFETY_RADIUS: return True return False
[ "def check_collision(self, auv_pos):\n for obs in self.obstacle_array:\n distance = self.calculate_range(auv_pos, obs)\n # obs[3] indicates the size of the obstacle\n if distance <= obs[3]:\n print(\"Hit an obstacle\")\n return True\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine if the vector between a UAV's position and the current waypoint intersect an obstacle.
def does_path_intersect_obstacle_2d(self, obstacle, uav_point, waypoint): drone_point = uav_point[:-1] waypoint = waypoint[:-1] obstacle_point = obstacle.get_point()[:-1] waypoint_vector = np.subtract(waypoint, drone_point) obstacle_vector = np.subtract(obstacle_point, drone_poi...
[ "def does_uav_intersect_obstacle_vertically(self, obstacle, drone_point, waypoint):\n if isinstance(obstacle, StationaryObstacle):\n if drone_point[2] < obstacle.height + Constants.STATIONARY_OBSTACLE_SAFETY_RADIUS:\n return True\n\n return False", "def inside_obstacle(poin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Looks at the signs of the components of the vectors to determine if the direction of the obstacle is in the same direction as the waypoint (quadrants)
def is_obstacle_in_path_of_drone(self, obstacle_vector, waypoint_vector): obstacle_list = obstacle_vector.tolist() waypoint_list = waypoint_vector.tolist() for index in range(len(obstacle_list)): if all(item > 0 for item in [-1.0 * obstacle_list[index], waypoint_vector[index]]) or a...
[ "def test_determine_direction(self):\n directions = range(1, 10)\n expected = [(-1, -1), (-1, 0), (-1, 1),\n (0, -1), (0, 0), (0, 1),\n (1, -1), (1, 0), (1, 1)]\n for index, direction in enumerate(directions):\n self.assertEqual(quiver_vectors[di...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the shortest path from the paths provided. This function assumes that the paths are possible waypoints calculated from the is_obstacle_in_path() function
def get_min_path(self, paths): shortest_path = paths[0] shortest_distance = self.get_path_distance(paths[0]) for path in paths[1:]: distance = self.get_path_distance(path) if distance < shortest_distance: shortest_path = path shortest_dis...
[ "def get_lowest_cost_path(paths): \n \n return min(paths, key = lambda t: t[1])", "def shortest_path(self):\r\n return min([Graph.get_total_path_distance(path) for path in self.path_list])", "def shortest_path(graph, source, destination):\n pass", "def path(self, source, target, path=[]):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the obstacles in the map
def get_obstacles(self): return self.obstacles
[ "def getObstacles(self):\r\n ausgabeObstacle = self.globalObstaclesList + self.globalHardObstaclesList\r\n self.globalObstaclesList = []\r\n return(ausgabeObstacle)", "def obstacles(self):\r\n\r\n #Radious arround the head\r\n limit_sight = self.snake_sight\r\n head = sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return True if the UAV has reached the current waypoint and false if not
def has_uav_reached_current_waypoint(self): return self.drone.has_reached_waypoint()
[ "def check_reached_waypoint_goal(self):\n return self.control_instance.check_reached_waypoint_goal()", "def at_goal(self):\n return self.distance_from_goal < self.robot.wheels.base_length/2", "def passed_waypoint(self, waypoint_num):\n bools = self.ros_node.get_data('/diff_drive/waypoints_a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hook to be invoked before the test method has been executed. May perform expensive setup here.
def before_test(self, func, *args, **kwargs): pass
[ "def before_tester_run(self) -> None:", "def before_test_run(self) -> None:", "def _on_test_begin(self):\n pass", "def prepare_test(self):\n pass", "def after_tester_run(self) -> None:", "def setUp(self):\n\n self._set_up()", "def _pre_init(self):\n pass", "def setUp(self) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates fixture objects from the given response and stores them in the applicationspecific cache.
def execute(self, response): if not has_request_context: return self._fallback_fixture_names() try: app = self.auto_fixture.app # Create response fixture fixture = Fixture.from_response(response, app, self.response_name) self.auto_fi...
[ "def test_template_source_data_response_serialization(self):\n\n # Construct dict forms of any model objects needed in order to build this model.\n\n env_variable_response_model = {} # EnvVariableResponse\n env_variable_response_model['hidden'] = True\n env_variable_response_model['name'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Falls back to the default fixture names if no names could be determined up to this point.
def _fallback_fixture_names(self): if not self.request_name or not self.response_name: warnings.warn( "No name was specified for the recorded fixture. Falling " "back to default names.") if not self.request_name: self.request_name = __default_name...
[ "def test_get_all_pytest_fixture_names(request):\n fixture_names = get_all_pytest_fixture_names(request.session, filter=test_get_all_pytest_fixture_names.__module__)\n clear_environment_fixture(fixture_names)\n assert fixture_names == ['make_synthesis', 'a_number_str', 'dummy']\n\n fixture_names = get_a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate ics from days.
def generate_ics(days: Sequence[dict], filename: Text) -> None: cal = Calendar() cal.add("X-WR-CALNAME", "中国法定节假日") cal.add("X-WR-CALDESC", "中国法定节假日数据,自动每日抓取国务院公告。") cal.add("VERSION", "2.0") cal.add("METHOD", "PUBLISH") cal.add("CLASS", "PUBLIC") cal.add_component(_create_timezone()) ...
[ "def make_ics(occurrences=None,title=None):\n tz = pytz.timezone(settings.TIME_ZONE)\n\n name = \"%s @ %s\"%(title,settings.SITE_NAME)\n calObj = icalendar.Calendar()\n calObj.add('method', 'PUBLISH') # IE/Outlook needs this\n calObj.add('version','2.0')\n calObj.add('prodid', '-//%s calendar product//mxm.dk...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get user profile Fetches from the user collection by using the user's email as key.
def get_user_profile(email): # GET # NOTE: This method previously called LCS with director credentials in order to retrieve the user's name # We will update TeamRU to store names along with our user objects, saving the need to call LCS again user_profile = coll("users").find_one({"_id": email}) if not ...
[ "def _getProfileFromUser(self):\n # Make sure user is authenticated\n user = endpoints.get_current_user()\n if not user:\n raise endpoints.UnauthorizedException('Authorization required')\n # Get Profile from datastore\n user_id = user.email()\n p_key = ndb.Key(Pr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create user profile Creates a new user profile from the user email, skills, prizes, and other fields.
def create_user_profile(email, **kwargs): # POST user_exists = coll("users").find_one({"_id": email}) if user_exists: return {"message": "User already exists"}, 400 # NOTE Doesn't make sense for a person to have prizes only a team should have this coll("users").insert_one( { ...
[ "def create_profile():\n if g.user is not None or 'openid' not in session:\n return redirect(url_for('index'))\n if request.method == 'POST':\n name = request.form['name']\n email = request.form['email']\n if not name:\n flash(u'Error: you have to provide a name')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resolver should be able to produce a value for a given key. If key doesn't exist, should return None.
def resolve(self, key: str) -> Optional[Any]: pass
[ "def resolve(self, key: str) -> Optional[Any]:\n return self.dict.get(key)", "def _get(self, key):\n key_in_st = []\n self._check_key(key_in_st, key, self._keys, 0, self._size - 1)\n if key_in_st[0]:\n return self._vals[key_in_st[1]]\n else:\n return None",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resolver should be able to produce a value for a given key. If key doesn't exist, should return None.
def resolve(self, key: str) -> Optional[Any]: return self.dict.get(key)
[ "def resolve(self, key: str) -> Optional[Any]:\n pass", "def _get(self, key):\n key_in_st = []\n self._check_key(key_in_st, key, self._keys, 0, self._size - 1)\n if key_in_st[0]:\n return self._vals[key_in_st[1]]\n else:\n return None", "def get_value(dat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines the number of files each node will process in scatter gather environment
def number_of_files_per_node(files, number_of_nodes): files_per_node = float(len(files))/float(number_of_nodes) if files_per_node > 0.: return int(math.floor(files_per_node)) else: return int(math.ceil(files_per_node))
[ "def get_number_of_processors_used(global_to_local_fpath):\n data = np.loadtxt(global_to_local_fpath, dtype='i4')\n n_proc = np.amax(data[:,1]) + 1\n return n_proc", "def fileCount(self):\n pass", "def num_partitions(self): # -> int:\n ...", "def file_engine_node_count(self) -> int:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send a request to Slack and validate the response
def slack_request(url: str, headers: dict, data: dict) -> dict: logger.debug(f'\nSending request to Slack API using {url}') response = requests.post(url=url, headers=headers, data=data) if response.status_code != 200: logger.error(f'Got stat...
[ "def slack_slash_request():\n try: \n if not is_slack_request_valid(\n ts=request.headers[\"X-Slack-Request-Timestamp\"],\n body=request.get_data().decode(\"utf-8\"), \n signature=request.headers[\"X-Slack-Signature\"],\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a report about stale branches for a list of repositories.
def check_stale_branches(event: dict, context) -> dict: ssm_parameters = load_params('dev_tools', 'dev') if 'jira_statuses_for_task_completion' in ssm_parameters and ssm_parameters['jira_statuses_for_task_completion']: jira_statuses_for_task_completion = ssm_parameters['jira_statuses_for_task_completi...
[ "def stale_pr_branches(config, args):\n repo = config.repo\n for pr in repo.pull_requests(state=\"closed\"):\n if pr.head.repo == pr.base.repo and repo.branch(pr.head.ref):\n yield {\n \"html_url\": pr.html_url,\n \"base_branch\": pr.base.ref,\n \"head_branch\": pr.head.ref,\n }"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reset this node's (and its children's) state to ready
def reset(self): self.state = EvaluationState.ready for child in self.children: if hasattr(child, "reset"): child.reset()
[ "def reset(self):\n # print \"Node \" + self.name_ + \" resetting.\"\n self.reset_self()\n for C in self.children_:\n C.reset()", "def reset_tree(self):\n self.root = None\n self.action = None\n self.dist_probability = None", "def reinitialize(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Evaluates the node's (and its children's) state.
def evaluate(self, blackboard): success = EvaluationState.success state = success for child in self.children: state = child.__call__(blackboard) if state != success: break return state
[ "def evaluate(self):\n\n def backtrack():\n # Move Tree backward\n self.remove_from_trackers(self.tree.current_node)\n # remove the current node from its parent's valid options\n self.tree.current_node.parent_Node.remove_current_child()\n self.tree.backt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Evaluates the node's (and its children's) state. Returns success if any node succeeds, else failure.
def evaluate(self, blackboard): success = EvaluationState.success for child in self.children: state = child.__call__(blackboard) if state == success: return success return EvaluationState.failure
[ "def evaluate(self, blackboard):\n success = EvaluationState.success\n\n state = success\n for child in self.children:\n state = child.__call__(blackboard)\n\n if state != success:\n break\n\n return state", "def evaluate(self):\n\n def backt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
imports 'catalog', and creates a pandas.DataFrame containing the columns specified in 'params'. 'catalog' is expected to be in the .csv format.
def import_data(catalog='xmatch_TGAS_Simbad.csv', params=None, nrows=None, delimiter=','): print "Loading %s and creating DataFrame.." % catalog df_imported = pd.read_csv(catalog, delimiter=delimiter, header=0, usecols=params, nrows=nrows) print "..Done\n----------" return df_imported
[ "def load_catalog(self):\n self.catalog = pd.read_csv(self.catalog_path, \n index_col=0, parse_dates=True)\n self.unique_years = self.catalog.index.year.unique()\n return", "def get_data() -> pd.DataFrame:\n try:\n return pd.read_csv('library.csv')\n except FileNotFoun...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Open a table fits file and convert it to a pandas dataframe.
def import_fits(fitsfile='tgasptyc.fits'): if isfile(fitsfile): print "Opening %s.." % fitsfile table = Table.read(fitsfile) pandas_df = table.to_pandas() else: print "%s not found. Exiting." % fitsfile sys.exit() print "Converting table to pandas_df.." print "..D...
[ "def df_from_fits(filename, i=1):\n return pd.DataFrame.from_records(fitsio.FITS(filename)[i].read().byteswap().newbyteorder())", "def _parse_fits(filepath):\n header, d = rhessi.parse_obssumm_file(filepath)\n data = DataFrame(d['data'], columns=d['labels'], index=d['time'])\n\n return hea...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
creates a new column 'tycho2_id' in the tycho2 catalog. This is for comparison with the TGAS catalog.
def create_tycho_id(tycho2df): tycho2df['tycho2_id'] = tycho2df.TYC1.astype(str).str.cat(tycho2df.TYC2.astype(str), sep='-')\ .str.cat(tycho2df.TYC3.astype(str), sep='-') tycho2df = tycho2df.rename(columns={'HIP': 'hip'}) return tycho2df
[ "def l2_id(self, l2_id):\n self._l2_id = l2_id", "def l2_id(self):\n return self._l2_id", "def fill_column_2(self):\n self.report.loc[:,self.fields[\"2\"]] = \\\n int(self.data_bucket.get_shareclass_infos(\"type_tpt\"))", "def get_idx2id(self, id2idx = None):\n if id2idx...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
select data with relative parallax error less than 'cutoff', add absolute magnitude columns for plotting. If catalog is not None, the cutoff on BV will not be applied (ensures initial variable stars DataFrame is not constrained in magnitudes)
def data_process(df_toprocess=None, cutoff=0.2, bv_cutoff=0.15, catalog=None): print "Selecting objects.." df_toprocess['sigma_pi/pi'] = df_toprocess.loc[:, 'parallax_error'].astype(float) / df_toprocess.loc[:, 'parallax']\ .astype(float) print "..Done\nCutoff at relative parallax error of %s\n----...
[ "def subcatsMWfootprint_diagnostics(catname='Skelton',plotdir='/Users/kschmidt/work/MUSE/MWv2_analysis/continuum_source_selection/',\n skeltonwhitakermag='814',xrange=None,bins=None,verbose=True):\n\n ids = np.array([])\n mags = np.array([])\n magnames = np.array(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
plot the background stars (HR diagram). The plot is a 2d histogram, for better readability. Only bins with at least 10 stars a shown.
def plot_hr_diag(hr_df, x='B_V', y='M_V', cutoff=0.2, bvcutoff=0.05): plt.figure(figsize=(11., 10.)) print "Plotting background stars.." plt.set_cmap('gray_r') plt.hist2d(hr_df[x].tolist(), hr_df[y].tolist(), (200, 200), norm=LogNorm(), cmin=10) plt.axis([-0.2, 2.35, -3., 7.]) plt.gca().invert_y...
[ "def histogram():\r\n y = np.random.rand(50)\r\n x = np.linspace(1,50,50)\r\n plt.subplot(1,2,1)\r\n plt.hist(y, bins=5)\r\n plt.subplot(1,2,2)\r\n plt.scatter(x,y)\r\n avg = np.mean(y)\r\n avg = np.ones(50)*avg\r\n plt.plot(x, avg,'r')\r\n plt.axis([0,50,0,1])\r\n plt.show()", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parent function of get_variable_stars. Sequencially select 'variableTypes' variable stars and plot them on the HR diagram.
def plot_variable_stars(variablesdf, variabletype=None, x='B_V', y='M_V'): if variabletype is None: variabletype = ['CEP', 'BCEP', 'BCEPS', 'DSCT', 'SR', 'SRA', 'SRB', 'SRC', 'SRD', 'RR', 'RRAB', 'RRC', 'GDOR', 'SPB', 'M', 'LPV', 'roAp'] markers = ['^', 'D', 'D', 'v', 's', 'D', '...
[ "def get_variable_stars(df_data, df_variables_names, variabletype=None):\n if variabletype is None:\n variabletype = ['CEP', 'BCEP', 'BCEPS', 'DSCT', 'SR', 'SRA', 'SRB', 'SRC', 'SRD', 'RR', 'RRAB', 'RRC',\n 'GDOR', 'SPB', 'M', 'LPV']\n\n print \"Selecting variable stars..\"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Child function fo plot_variable_stars. Process the DataFrame to select only stars marked as 'var_type' variable stars.
def get_variable_stars(df_data, df_variables_names, variabletype=None): if variabletype is None: variabletype = ['CEP', 'BCEP', 'BCEPS', 'DSCT', 'SR', 'SRA', 'SRB', 'SRC', 'SRD', 'RR', 'RRAB', 'RRC', 'GDOR', 'SPB', 'M', 'LPV'] print "Selecting variable stars.." # create a st...
[ "def plot_variable_stars(variablesdf, variabletype=None, x='B_V', y='M_V'):\n if variabletype is None:\n variabletype = ['CEP', 'BCEP', 'BCEPS', 'DSCT', 'SR', 'SRA', 'SRB', 'SRC', 'SRD', 'RR', 'RRAB', 'RRC', 'GDOR',\n 'SPB', 'M', 'LPV', 'roAp']\n markers = ['^', 'D', 'D', 'v', 's...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
plot a Cepheid at its reddened position on the HR diag. (assume that deredden_cepheids() have been used)
def plot_dereddening(): extinction_coefficients = {'2365-2764-1': np.array([0.2622, 0.844]), '4109-638-1': np.array([0.0524, 0.1576]), '2058-56-1': np.array([0.0751, 0.248]), '3642-2459-1': np.array([0.1907, 0.608]), '3999-1391-1': np.array([0.3911, 1.24...
[ "def anharm_plot():\n set_tag(qdt, \"EjdivEc\", log=False)\n set_tag(qdt, \"Ej\", log=False)\n\n #qdt.epsinf=qdt.epsinf/3.72\n #qdt.Np=10\n #qdt.Ec=qdt.fq*0.1*h\n print qdt.max_coupling, qdt.coupling_approx\n anharm=qdt.call_func(\"anharm\", EjdivEc=EjdivEc)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes the connection with IMDb.
def initialize_connection(): session = imdb.IMDb() return session
[ "def _setup_connection(cls):\n try:\n cls.imdb_access = imdb.IMDb()\n except imdb.IMDbError, err:\n print \"Problem with connectivity to imdb.com due to %s \" \\\n % (err)", "def __init__(self):\n\t\tself.obtainDatabaseConnection()", "def init(self):\n se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Displays a generic error message when there is a connection error.
def display_error(): clear_screen() line = '#' * 20 print(f'{line}\n# CONNECTION ERROR #\n{line}') exit(1)
[ "def show_connection_failed(self):\n self.set_status_text1(\n '<b>RPC network status:</b> failed connection to %s' % self.dashd_intf.get_active_conn_description(),\n 'error')", "def __display_error(self, socket_error):\r\n\t\tif socket_error == QAbstractSocket.RemoteHostClosedError:\r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Displays the ratings that were scraped.
def display_ratings(ratings): # only attempt to display the ratings if any were found if ratings: print('\n[RATINGS]\n') for rating in ratings: print(f' {rating}', end=' ') # needed to get printing back to normal print()
[ "def view_ratings(request):\n profs = Professor.objects.all()\n if profs:\n prof_table = \"\"\n for prof in profs:\n prof_ratings = Rating.objects.all().filter(prof=prof.id)\n if prof_ratings:\n average_rating = prof_ratings.aggregate(ave=Avg('rating'))['ave'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Scrapes the plot from the provided URL.
def get_plot(url): soup = get_soup(url.rsplit('/', 1)[0]) if soup: # scrape the plot section plot_div = soup.find('div', {'id': 'titleStoryLine'}) # fixes bug were no plot is found try: plot_class = plot_div.find('span', {'itemprop': 'description'}) plot...
[ "def fn_GetMoviePlot(self, details):\n\n # If the custom url was not actually defined and we had no cached\n # data, then there is nothing to do.\n #\n if details is None:\n return\n\n dom = parseString(details)\n d = dom.firstChild\n self.plot = get_child...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cleans up the given comments.
def cleanup_comments(comments): clean_comments = [] if comments: for comment in comments: cleaned_up = sub(r'\n\n {8}\n {8}\n {12}\n {16}\n {16}\n {12}\nEdit', '', comment) clean_comments.append(cleaned_up) return clean_comments
[ "def clear_comments(self):\n content_string_list = self.doc_object.tex_file_contents\n comment_removed_content_list = []\n for cont_str in content_string_list:\n comment_removed_content = strip_comments(cont_str)\n comment_removed_content_list.append(comment_removed_conten...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses the certificates specific to the United States.
def parse_certificates(soup): # removes the first item because it does not needed rating_tags = soup.find_all('a')[1:] rating_codes = [code.string for code in rating_tags] mpaa = [] if rating_codes: for rating in rating_codes: # sorry international folks, only interested in the ...
[ "def populate_sagepay_country_code(self):\n try:\n r = requests.get('http://www.iso.org/iso/home/standards/country_codes/country_names_and_code_elements_txt.htm')\n except requests.RequestException:\n return False\n countries = r.text.split('\\r\\n')\n for country i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses the given section.
def parse_section(soup): section_tag = soup.find_all('a', {'class': 'advisory-severity-vote__message'}) section_scale = [code.string for code in section_tag] section = section_scale[0] if section_scale else None section_comment_tags = soup.find_all('li', {'class': 'ipl-zebra-list__item'}) section_c...
[ "def _parse_section(self, template, start_index, section_key):\n parsed_section, content_end_index, end_index = (\n self.parse(template=template,\n start_index=start_index,\n section_key=section_key)\n )\n\n return (parsed_section, temp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return True if ``value`` is an health check.
def is_healthcheck(self, value): return is_healthcheck(value)
[ "def is_true(value):\n \n return (value is True)", "def isTrue(value):\n if type(value) == str:\n return value.lower() == \"on\"\n elif value:\n return True\n return False", "def _check_value_type(self, value):\n if value is not None and self.value_type is not None:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return copy of TestSuite where only health checks remain.
def filter_suite(self, suite): if isinstance(suite, unittest.TestSuite): suite_copy = self.suiteClass() for sub in suite: if isinstance(sub, unittest.TestSuite): suite_copy.addTest(self.filter_suite(sub)) else: if se...
[ "def filter_tests(suite):\r\n result = unittest.TestSuite()\r\n for test in suite:\r\n if isinstance(test, unittest.TestSuite):\r\n result.addTest(filter_tests(test))\r\n elif not test.__class__.__name__.startswith(\"_\"):\r\n result.addTest(test)\r\n return result", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load healthchecks from TestCase.
def loadTestsFromTestCase(self, testCaseClass): suite = super(HealthCheckLoader, self).loadTestsFromTestCase( testCaseClass) return self.filter_suite(suite)
[ "def test_health_check_get(self):\n pass", "def test_health_get(self):\n pass", "def test_v1_check_health(self):\n pass", "def loadTestsFromModule(self, module, *args, **kwargs):\n suite = super(HealthCheckLoader, self).loadTestsFromModule(\n module, *args, **kwargs)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load healthchecks from module.
def loadTestsFromModule(self, module, *args, **kwargs): suite = super(HealthCheckLoader, self).loadTestsFromModule( module, *args, **kwargs) return self.filter_suite(suite)
[ "def _load(self):\n p = os.path.join(paths.setup_dir, 'system_health.yaml')\n if os.path.isfile(p):\n with open(p, 'r') as rfile:\n config = yaml.load(rfile)\n if config:\n self._values = config['values']\n self._conditiona...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load healthchecks from name.
def loadTestsFromName(self, name, module=None): suite = super(HealthCheckLoader, self).loadTestsFromName(name, module) return self.filter_suite(suite)
[ "def loadTestsFromNames(self, names, module=None):\n suite = super(HealthCheckLoader, self).loadTestsFromNames(names,\n module)\n return self.filter_suite(suite)", "def load_checks(self):\n self.checks = []\n limiters.get...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load healthchecks from names.
def loadTestsFromNames(self, names, module=None): suite = super(HealthCheckLoader, self).loadTestsFromNames(names, module) return self.filter_suite(suite)
[ "def loadTestsFromName(self, name, module=None):\n suite = super(HealthCheckLoader, self).loadTestsFromName(name, module)\n return self.filter_suite(suite)", "def _load_checks(configs):\n checks = []\n\n # active checks\n if configs['actives']:\n logger.debug(\"Loading active checks....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate the public key if it is related to the given EC curve and formats the public key to a uncompressed byte string. Afterwards the function create a hash value of the uncompressed public key value
def get_public_key_fingerprint(curve: object, temp_public_key: object) \ -> object: vk = VerifyingKey.from_string(bytes.fromhex(temp_public_key), curve=curve) uncompressed_pub_key = vk.to_string('uncompressed') pub_key_hash_fingerprint = hashlib.sha256(uncompressed_pub_key) return pub_key_ha...
[ "def verify(self, pkey, e, sig):\n # First we define modular exponent, which is\n # used to calculate the y from a compressed\n # public key.\n # This only works for curves with an integer\n # order n that is congruent to 3 mod 4.\n def pow_mod(x, y, z):\n n = 1\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save model hyperparameters/metadata to output directory. model_options is an argparse Namespace, and is converted to a dictionary and pickled.
def save_model_options(output_dir, model_options, predictor='classify'): if not isinstance(model_options.training_data, str): training_data = '.'.join(model_options.training_data) else: training_data = model_options.training_data output_file = construct_filename(output_dir, ...
[ "def export_model(self, model):\n os.mkdir(model)\n classifier_path = os.path.join(model, 'classifier')\n parameters_path = os.path.join(model, 'parameters.pkl')\n parameters = {'label_mapping': self.label_mapping, 'word_regex': self.word_regex, 'tokenize': self.tokenize,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Charge given price to the card, assuming sufficient card limit Return True if charge was processed;False if charge was denied
def charge(self,price): if price + self._balance> self._limit: return False else: self._balance+=price return True
[ "def charge(self, price):\n if price + self._balance > self._limit: #if charge would exceed limit\n return False #can not accept charge\n else:\n self._balance += price\n return True", "def charge(self, price):\n\n if price + self._balance > self._limit:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Process customer payment that reduces balance
def make_payment(self,amount): self._balance-=amount
[ "def make_payment(self, amount):\n self._balance -= amount #UGH NO RETURN STATEMENT WAS NEEDED", "def make_payment(self, payment):\n self._balance -= payment", "def monthlyProcess(self):\n n=0\n if self.numWithdrawals>4:\n n=self.numWithdrawals-4\n self.balance-=sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate random bytes to use as csrf secret
def gen_csrf_secret(): return Random.new().read(csrf_secret_len)
[ "def generate_csrf_token():\n return binascii.b2a_hex(os.urandom(32))", "def gen_secret():\n return urlsafe_b64encode(bytes([random.getrandbits(8) for _ in range(18)])).decode('ascii')", "def gen_csrf_token():\n\n return \"\".join(random.choice(\n string.ascii_uppercase + string.digits) for x in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read csrf secret from session if it exists; otherwise generate it and store in session
def get_csrf_secret(): sess = managers.request_manager.get_request().session() secret = sess.get(csrf_secret_sess_var_name, None) if not secret: secret = gen_csrf_secret() sess[csrf_secret_sess_var_name] = secret return secret
[ "def gen_csrf_secret():\n\treturn Random.new().read(csrf_secret_len)", "def generate_csrf_token():\n if '_csrf_token' not in session:\n session['_csrf_token'] = binascii.hexlify(os.urandom(32)).decode()\n return session['_csrf_token']", "def generate_csrf_token():\n if '_csrf_token' not in login...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate csrf token based on existing/new csrf secret and provided/new salt
def create_csrf_token(salt=''): if not salt: salt = Random.new().read(csrf_salt_len).encode('hex') h = SHA256.new() h.update(get_csrf_secret() + salt) return h.hexdigest() + salt
[ "def gen_csrf_secret():\n\treturn Random.new().read(csrf_secret_len)", "def generate_csrf_token():\n return binascii.b2a_hex(os.urandom(32))", "def generate_csrf_token():\n if '_csrf_token' not in session:\n session['_csrf_token'] = binascii.hexlify(os.urandom(32)).decode()\n return session['_cs...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verify csrf token against csrf secret from the session; if token is not provided it's read from request arguments
def verify_csrf_token(token=''): if not token: token = managers.request_manager.get_request().arguments().arguments().get(csrf_token_arg_name, "") if token: token = token[0] if len(token) != 2 * digest_size + 2 * csrf_salt_len: debug('Incorrect csrf token length') raise VDOM_csrf_exception() salt = token[...
[ "def csrf_protect():\n if request.method == \"POST\" and request.path[0:5] != \"/api/\":\n token = login_session.pop('_csrf_token', None)\n request_token = request.form.get('_csrf_token')\n print(\"Comparing server token [\" + token + \"]\")\n print(\"with client token [\" + request_t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
list starter arguments that must be applied conditionally based on version
def get_version_specific_arguments(self, version: str): result = [] semversion = semver.VersionInfo.parse(version) # Extended database names were introduced in 3.9.0 if self.supports_extended_names: result += ["--args.all.database.extended-names-databases=true"] # T...
[ "def test_prelim_opts_args(application):\n opts, args = application.parse_preliminary_options(\n ['--foo', '--verbose', 'src', 'setup.py', '--statistics', '--version'])\n\n assert opts.verbose\n assert args == ['--foo', 'src', 'setup.py', '--statistics', '--version']", "def get_requirement_strings...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the list of dbservers managed by this starter
def get_dbservers(self): ret = [] for i in self.all_instances: if i.is_dbserver(): ret.append(i) return ret
[ "def get_servers_list(self):\n return self.nova_client.servers.list()", "def get_servers(self):\n\t\treturn self.__servers", "def get_all_servers(self) -> List[Server]:", "def get_all_servers(self) -> List[Server]:\n pass", "def servers(self):\n return self._servers", "def bootstrap_s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the list of agents managed by this starter
def get_agents(self): ret = [] for i in self.all_instances: if i.instance_type == InstanceType.AGENT: ret.append(i) return ret
[ "def get_agents(self):\n if self.retrieved:\n raise errors.IllegalState('List has already been retrieved.')\n self.retrieved = True\n return objects.AgentList(self._results, runtime=self._runtime)", "def items(self):\n return self.agents.items()", "def list(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the first frontendhost of this starter
def get_frontend(self): servers = self.get_frontends() assert servers, "starter: don't have instances!" return servers[0]
[ "def getFrontend(self):\n return self.header['FRONTEND']", "def GetHost():\r\n assert _server_environment is not None\r\n return _server_environment._staging_host if _server_environment._is_staging else _server_environment._prod_host", "def syshost():\n hostA = platform.node().split('.')\n idx = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the first dbserver of this starter
def get_dbserver(self): servers = self.get_dbservers() assert servers, "starter: don't have instances!" return servers[0]
[ "def get_stored_primary_server_name(db):\n if \"last_primary_server\" in db.collection_names():\n stored_primary_server = db.last_primary_server.find_one()[\"server\"]\n else:\n stored_primary_server = None\n\n return stored_primary_server", "def find_dbserver(self):\n if self.dbserv...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the first agent of this starter
def get_agent(self): servers = self.get_agents() assert servers, "starter: have no instances!" return servers[0]
[ "def agent(self):\n value = self._data.get('agent', None)\n if value is not None:\n data = {\n 'response': value,\n }\n return self.__class_agent__(self._api, data)", "def getAgent(self):\n return Agent(name = self.__str__(), strategy = (lambda ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }