content
stringlengths
5
1.05M
import pytest import pandas as pd import numpy as np from pyseas.maps import rasters def test_uniform(): scale = 4 lon_bin_template = np.arange(-180 * scale, 180 * scale) lat_bin_template = np.arange(-90 * scale, 90 * scale) lon_bin, lat_bin = [x.flatten() for x in np.meshgrid(lon_bin_template, lat_b...
""" This package contains all views related to organizations """ from .organization_view import OrganizationView from .organization_list_view import OrganizationListView
from datetime import date # Python code for task 3 s = date(2010, 8, 9) # CP1 launch date t = date.today() print(s.strftime("%a")) # 'Mon', %A for 'Monday' print("{} day(s) ago".format((t-s).days)) # ans grows over time
"""Inter-region correlation processing module""" from scipy.stats import linregress from lib.storage import Storage from lib.correlation import is_correlation def process(storage: Storage): """Process time series in the storage""" all_tfr = storage.tfr_dataset.all_series(storage.regions) min_values_per_...
import numpy as np from vispy import app, gloo, visuals from vispy.geometry import create_sphere from vispy.visuals.transforms import (STTransform, AffineTransform, ChainTransform) class Canvas(app.Canvas): def __init__(self): app.Canvas.__init__(self, keys='interacti...
import glob import os import json # jq '. | map(select( .user.screen_name == "paseri_Hades")) | .[] | { text: .text, id: .id_str }' log/convert.json if __name__ == '__main__': convert = {} for file_path in sorted(glob.glob('./log/2019*.json'), reverse=True): with open(file_path) as f: da...
from random import choice from microbit import display, Image, button_a, button_b, pin_logo from speech import say from time import sleep SPEED = 95 chocolates = ['milk', 'white', 'dark', 'caramel', 'mint'] rooms = {} room_number = 1 guesses = 2 for room in range(1, len(chocolates) + 1): random_chocolate = choic...
# -*- encoding: utf8 -*- from kraken2headder import add_taxonomy, convert_accession from ftplib import FTP import gzip import shutil from retry import retry """ This process requires Biopython, retry. Install them beforehand. dogtun Inc. oec """ # fasta url to download ftp_host = "ftp.ddbj.nig.ac.jp" ftp_path = "/ddb...
import random a= random.randint(1,20) print(a)
class TypeClass(object): def __init__(self, **kwargs): for k in kwargs: setattr(self, k, kwargs[k]) def __repr__(self): dict_keys = self.__dict__.keys() class_attr = [] for k in dict_keys: v = getattr(self, k, None) if type(v) == int: ...
class GameEvent: """ Represents an event that occurred in a League of Legends game, as defined by the League of Legends client API. """ def __init__(self, data): self.id = data['EventID'] self.name = data['EventName'] self.time = data['EventTime']
# -*- coding: utf-8 -*- """ Created on Wed Sep 11 11:41:46 2019 @author: autol """ import configparser #%% config and default values def write_config(cfgfile): cfg = configparser.ConfigParser(allow_no_value=1, inline_comment_prefixes=('#', ';')) cfg['config'] = dict( ...
import ROOT import math from functools import partial import PlotUtils from config import PlotConfig from config.AnalysisConfig import AnalysisConfig from config.DrawingConfig import Default_Plot_Type,Default_Scale,DefaultSlicer from tools import Utilities,PlotTools from tools.PlotLibrary import HistHolder ROOT.TH1.Add...
import numpy as np import pandas as pd from rnanorm.normalization import cpm def test_cpm_normalization(): """Test CPM formula implementation. CPM expressions of a minimal example have been manually computed and compared against implementation. Expression data: S1 S2 ...
import subprocess def test_basic(): test_list = [ "examples/test_basic.S", "examples/test_basic_0.S", "examples/test_basic_2.S", "examples/test_dual_split_regs.S", "examples/test_immediate.S", "examples/test_extended.S", ] # testing all available examples ...
#!/usr/bin/env python # # This software is distributed under BSD 3-clause license (see LICENSE file). # # Authors: Heiko Strathmann # from numpy import random import math from shogun import machine_evaluation from shogun import splitting_strategy from shogun import BinaryLabels from shogun import GridSearchModelSelec...
from .usersim_rule import * from .usersim_model import * from .RealUser import *
# -*- coding: utf-8 -*- # File generated according to Generator/ClassesRef/Simulation/LossModelSteinmetz.csv # WARNING! All changes made in this file will be lost! """Method code available at https://github.com/Eomys/pyleecan/tree/master/pyleecan/Methods/Simulation/LossModelSteinmetz """ from os import linesep from sy...
from SimpleCV import Kinect, Display import time # Initialize the Kinect kin = Kinect() # Initialize the display disp = Display((640,480)) # This should be adjusted to set how many pixels # represent an inch in the system's environment pixelsToInches = 6 while not disp.isDone(): img = kin.getDepth() blobs =...
# coding: utf-8 # author: Ankur Roy Chowdhury from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.ui import Select from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver...
import pandas as pd # ====================================================================================================================== # Model of district cooling plant CLASS # ====================================================================================================================== class CoolingPl...
import io from ir_model import IRModel from embeddings_model import EmbeddingsModel import pickle import traceback class Doc(object): def __init__(self, text, doc_id=None, mentions_targets=None): self.text = text self.doc_id = doc_id self.mentions_targets = mentions_targets #list of tuples ...
import os import platform import argparse PUMA = 'puma' OBAMA = 'obama' PATH_DATASET = '/home/peter/dataset' if platform.node() == PUMA: # PATH_DATASET = '/home/peter/dataset' PATH_CONDA = '/home/peter/.conda/envs' else: PATH_DATASET = '/home/peter/extra/dataset' PATH_CONDA = '/home/peter/anaconda3/...
#!/usr/bin/env python3 # -*- coding: utf8 -*- import unittest import dsklayout.graph as graph class Test__graph__PackageSymbols(unittest.TestCase): def test__bfs__symbols(self): self.assertIs(graph.Bfs, graph.bfs_.Bfs) def test__dfs__symbols(self): self.assertIs(graph.Dfs, graph.dfs_.Dfs) ...
# ====================================================================== # Science for Hungry People # Advent of Code 2015 Day 15 -- Eric Wastl -- https://adventofcode.com # # Python implementation by Dr. Dean Earl Wright III # ====================================================================== # ================...
#!/usr/bin/env python # coding=utf-8 # Copyright Matus Chochlik. # Distributed under the Boost Software License, Version 1.0. # See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt import os, sys, glob, subprocess def root_dir(): return os.path.abspath(os.path.join( os.path.dirn...
import os from django.core.files.uploadhandler import TemporaryFileUploadHandler, StopUpload, StopFutureHandlers from rdkit.Chem import MolFromMolBlock, ForwardSDMolSupplier from .customized_errors import MultipleMoleculesinSDF,InvalidMoleculeFileExtension, RequestBodyTooLarge, FileTooLarge, TooManyFiles from django.co...
# -*- coding:utf-8 -*- from selenium import webdriver from selenium.webdriver.chrome.options import Options import answer unit_url_tmp = [ "http://202.119.161.130/StudentSTS/unitnav.aspx?UnitTreeid=4612", "http://202.119.161.130/StudentSTS/unitnav.aspx?UnitTreeid=4613", "http://202.119.161.130/Stud...
from tap_liveperson.streams.base import BaseStream import singer LOGGER = singer.get_logger() # noqa class EngagementHistoryStream(BaseStream): API_METHOD = 'POST' SERVICE_NAME = 'engHistDomain' TABLE = 'engagement_history' @property def api_path(self): return ( '/interacti...
import json with open("config.json", "rt") as fp: config = json.load(fp) # configuration global variables REGION_NAME = config["QueueRegion"] QUEUE_URL = config["QueueURL"] OUTPUT_FILEPATH = config["OutputFilePath"] SNS_TOPIC_ARN = config["SNSTopicARN"] SNS_TOPIC_REGION = config["SNSTopicRegion"]
import menu menu.menu() menu.order() option=int(input("enter the option")) while option != 0: if option == 1: print("ordered Burger") q=int(input("enter the quantity :")) print(f"cost for {q} burger is {menu.burger(q)}") elif option ==2: print("Ordered Pizza") q=int(input("enter the...
import abc from multiprocessing import Process, Queue import numpy as np class PlotBase: def __init__(self): self._q = Queue(maxsize=10) self._plotting_process = Process(target=self._daemon, args=(self._q,), daemon=True) self._plotting_process.start() @abc.abstractmethod ...
#importing necessary packages from PIL import Image import numpy as np # opens the image image=Image.open('flower.jpeg') #converting the image into array image_array=np.array(image) #Now convert the colouerd into grayscale by following method (B*0.2989+G*0.5870+R*0.1140) #repalce the average value in r,g,b in p...
from pathlib import Path import pickle import numpy as np import keras import os import multiprocessing.pool from functools import partial import keras_preprocessing.image.utils as utils from random import sample as randsomsample import pandas as pd import math from sklearn.preprocessing import LabelEncoder, MinMaxScal...
''' permissions functions Copyright (c) 2017 Vanessa Sochat Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, mer...
import numpy as np from kb_learning.planning import WayPointConf def generate_circular_path(center: np.ndarray, radius=.8, angular_range=(-np.pi/2, .0), num_way_points=10): angles = np.linspace(*angular_range, num_way_points) arc_points = np.c_[np.cos(angles), np.sin(angles)] * radius + np.asarray(center) ...
# Copyright © 2017 Valentin Rosca <rosca.valentin2012@gmail.com> # Copyright © 2017 Cosmin Pascaru <cosmin.pascaru2@gmail.com> # Copyright © 2017 Andrei Netedu <andrei.netedu2009@gmail.com> # Copyright © 2017 Alexandru Miron <mironalex96@gmail.com> from sqlalchemy import Column, Integer, String, LargeBinary from sqlal...
#!/usr/bin/env python import time import logging import traceback import schedule from random import shuffle, randint from time import sleep from datetime import datetime from typing import List, Dict from sqlalchemy.exc import IntegrityError from sqlalchemy import func from scraper.scholarly import search_author, se...
#!/usr/bin/env python3 """ This script is adapted from the Bertology pruning code (https://github.com/huggingface/transformers/blob/783d7d2629e97c5f0c5f9ef01b8c66410275c204/examples/research_projects/bertology/run_bertology.py) to prune GPT-like models. The author is @altsoph. """ import argparse import logging import...
class UID(object): def __init__(self, body, head): self.body = body self.head = head def get_body(self): return self.body def get_head(self): return self.head def __hash__(self): return hash(self.body) + hash(self.head) def __eq__(self, other): re...
"""populate_reconcile_queue""" import logging import os from cbers2stac.layers.common.utils import get_client # Get rid of "Found credentials in environment variables" messages logging.getLogger("botocore.credentials").disabled = True LOGGER = logging.getLogger() LOGGER.setLevel(logging.INFO) def populate_queue_wi...
def main(argv=None): print('main called with', argv) if argv is None: from sys import argv argv= argv[1:] print('main argv revision with', argv) from .main import main as m exit(m(argv)) main()
# #! /usr/bin/env python3 # # import pytest # import os # import shutil # # import indy_client.test.cli.test_tutorial as testTutorialMod # import indy_client.test.cli.conftest as cliConftestMod # # curDirPath = os.path.dirname(os.path.abspath(__file__)) # pathForPoolTxnFile = '/home/rkalaria/.indy/pool_transactions_san...
import json import httplib2 import sys from testscripts.const import MSB_BASE_URL data = { "gracefulTerminationTimeout": 600, "terminationType": "FORCEFUL" } headers = {'content-type': 'application/json', 'accept': 'application/json'} ca_certs = None auth_type = "rest_no_auth" http = httplib2.Http(ca_certs=ca...
#!/bin/python3.6 # -*- coding: utf-8 -*- # # MIT License # # Copyright (c) 2018 Robert Gustafsson # Copyright (c) 2018 Andreas Lindhé # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without...
#!/usr/bin/env python #encoding=utf-8 import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D class FC: def __init__(self, in_num, out_num, lr=0.01): self._in_num = in_num self._out_num = out_num self.w = np.random.randn(out_num, in_num)*10 self.b = np.zeros(out_num) self...
# Copyright 2018 The Magenta Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
# -*- coding: utf-8 -*- """The NTFS directory implementation.""" from dfvfs.lib import errors from dfvfs.path import ntfs_path_spec from dfvfs.vfs import directory class NTFSDirectory(directory.Directory): """File system directory that uses pyfsntfs.""" _FILE_REFERENCE_MFT_ENTRY_BITMASK = 0xffffffffffff def ...
class dotUIModelObjectSelector_t(object): # no doc aObjects=None Functionality=None nObjects=None ShowDimensions=None
"""Transform a mypy AST to the IR form (Intermediate Representation). For example, consider a function like this: def f(x: int) -> int: return x * 2 + 1 It would be translated to something that conceptually looks like this: r0 = 2 r1 = 1 r2 = x * r0 :: int r3 = r2 + r1 :: int return r3 The...
def create_expr_string(clip_level_value): """Create the expression arg string to run AFNI 3dcalc via Nipype. :type clip_level_value: int :param clip_level_value: The integer of the clipping threshold. :rtype: str :return The string intended for the Nipype AFNI 3dcalc "expr" arg inputs. """ ...
__author__ = 'rene_esteves' def populate_ordered(input): serie = add_serie('ordered-10000') for p in range(input): add_datum(p, serie) def add_serie(name): serie = Serie(serie_text=name) serie.save() print ("serie = " + str(serie)); return serie def add_datum(value, serie): datum ...
__version__ = '1.0' from .sherpa import main main()
import logging logger = logging.getLogger('BSUIDEBUG') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages fh = logging.FileHandler('/home/xf16id/logs/bsui-debug-2018-08-08.txt') fh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch....
import numpy as np import sys sys.path.append('.') from AND_NAND_OR import AND, NAND, OR def XOR(x1, x2): return AND(OR(x1, x2), NAND(x1, x2)) if __name__ == "__main__": print('XOR') y = XOR(0, 0) print(y) y = XOR(1, 0) print(y) y = XOR(0, 1) print(y) y = OR(1, 1) print(y) ...
import socket import threading import time # 服务端 def deal_client(sock,addr): print('Accept new connection from {}'.format(addr)) # send() 的参数为二进制数据,字节数据 sock.send(b'Hello, I am a server.') while True: # recv()接收到的是字节数据 data=sock.recv(1024) time.sleep(1) if not data or d...
"""Database comparison feature tests.""" import pandas as pd from pytest_bdd import ( given, scenarios, then, when, parsers ) from tests.pageobjects.db_comparison import DBComparison as db scenarios('../features/db.feature') @given(parsers.parse('connection is established between source and targ...
from operator import itemgetter NODE_USER_TAGS = ('datacenter', 'pod', 'rack') NODE_TAGS = ('pod', 'rack') def is_tagged(data): return (any(data.get(tag) for tag in NODE_TAGS) or all(data['userTags'].get(tag) for tag in NODE_TAGS)) def get_topology_edges(cvp): res = cvp.get('$n/topology/edges'...
#!/usr/bin/env python # -*- encoding: utf-8 -*- import math import torch from torch import nn as nn, Tensor, distributed as dist from colossalai.context import seed, ParallelMode from colossalai.core import global_context as gpc from colossalai.nn.layer._common_utils import divide, ACT2FN from colossalai.nn.layer.pa...
import os from hydroDL import kPath from hydroDL.master import slurm import numpy as np # create mask for gageII basins codePath = os.path.join(kPath.dirCode, 'app', 'data', 'GLASS', 'extractData.py') cmdPtn = 'python {} -S {} -E {}' ns = 7111 k1Lst = np.arange(0, ns, 100) k2Lst = np.append(k1L...
from constants import * from scipy import integrate import matplotlib.pyplot as plt def s_infinite_spherical_well(temp_K, mass_au, c_au): z = ((2.0 * np.pi * mass_au * Constants.kb_au * temp_K) / (Constants.h_au ** 2))**1.5 * ((4.0 * np.pi * c_au**3) / 3.0) return 1.5 * Constants.kb_JKmol + Constants.kb_JKm...
import os import tensorflow as tf import numpy as np from imageio import imread import matplotlib from src.flowlib import read_flow, flow_to_image matplotlib.use('TKAgg') import matplotlib.pyplot as plt _preprocessing_ops = tf.load_op_library( tf.resource_loader.get_path_to_datafile("./src/ops/build/preprocessing....
import pytest from bson import ObjectId from mongoengine import Document, EmbeddedDocument, StringField, connect from cleancat import Schema, StopValidation, String, ValidationError from cleancat.mongo import ( MongoEmbedded, MongoEmbeddedReference, MongoReference, ) @pytest.fixture def mongodb(): co...
#!/usr/bin/python # -*- coding: UTF-8 -*- ############################## Regex Strings ################################### # Note: the characters in standard_punct and standard_delimiters CANNOT overlap. from conf.settings import CUSTOM_START_WORDS from constants.database import ANSWER_VALUE, SKIP_VALUE, BAD_RESPONSE_...
# -*- coding: utf-8 -*- """Wrapper around the SEMrush API.""" # :copyright: (c) 2015 Jeremy Storer and individual contributors, # All rights reserved. # :license: MIT License, see LICENSE for more details. from collections import namedtuple version_info_t = namedtuple( 'version_info_t', ('major...
""" WSGI config for the alternate origin server used for serving sandboxed content """ import os import kolibri.core.content from kolibri.core.content.utils import paths from kolibri.core.content.zip_wsgi import get_application from kolibri.utils.kolibri_whitenoise import DynamicWhiteNoise os.environ.setdefault( ...
#!/usr/bin/python """ (C) Copyright 2020-2021 Intel Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent """ from logging import DEBUG, INFO, WARNING, ERROR import sys class TestLogger(): """Defines a Logger that also logs messages to DaosLog.""" _LEVELS = { "debug": DEBUG, "info": ...
import praw import config import time import os # Made by reddit user /u/Stronger1088 # Following this tutorial https://youtu.be/krTUf7BpTc0 # This is my first bot so I hope its good enough! I tried to rule out all of the bugs possible but there might still be some. Feel free to message me! Ty! def authentication():...
# -*- coding: utf-8 -*- # Copyright (c) 2015, New Indictrans Technologies PVT LTD and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document from frappe.utils import today from frappe import _ class SchemeManageme...
import pytest from gvalidate import validate_in_interval, validate_positive @validate_positive("length") def f_positive(length, width): pass @validate_positive() def f_positive_check_all(length, width): pass @validate_positive("length") @validate_positive("width") def f_positive_nested(length, width): ...
from django.contrib import messages from django.shortcuts import (HttpResponse, HttpResponseRedirect, get_object_or_404, redirect, render) from django.utils import timezone from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse, reverse_lazy from django.contrib.auth import login, log...
from ._components import BiExperimentComponent, BiExperimentViewerComponent, BiExperimentCreateComponent from ._containers import BiExperimentContainer, BiExperimentCreateContainer from ._models import BiExperimentModel, BiExperimentCreateModel from ._states import BiExperimentStates, BiExperimentCreateStates __all__...
''' Implements utils for running the compiler and parsing clang's compile_commands.json. ''' import json import os import re import shlex import subprocess import sys from contextlib import contextmanager from functools import lru_cache from itertools import chain from typing import AnyStr, Callable, Dict, Iterable, L...
import paddle import torch import numpy as np # torch_model_path = "cnndm/finetune_cnndm_checkpoints/checkpoint9.pt" torch_model_path = "pretrained_checkpoints/prophetnet_en.pt" # torch_model_path = "gigaword/finetune_gigaword_checkpoints/checkpoint7.pt" torch_state_dict = torch.load(torch_model_path)["model"] # padd...
import gym import gym_panda #need to be imported !! import random import numpy as np import matplotlib.pyplot as plt import time import execnet from pilco.models import PILCO from pilco.controllers import RbfController, LinearController from pilco.rewards import ExponentialReward import tensorflow as tf from gpflow ...
"""fileformatjson.py unit tests.""" import os import json import shutil from pypyr.context import Context from pypyr.errors import KeyInContextHasNoValueError, KeyNotInContextError import pypyr.steps.fileformatjson as fileformat import pytest def test_fileformatjson_no_in_obj_raises(): """None in path raises.""" ...
print(""" 011) Faça um programa que leia a largura e a altura de uma parede em metros, calcule a sua área e a quantidade de tinta necessária para pintá-la, sabendo que cada litro de tinta, pinta uma área de 2m² """) altura = float(input('Informe a altura da parede (Em metros): ')) largura = float(input('Informe a lar...
import os import numpy as np import pandas as pd import xarray as xr import datetime import time import cftime import warnings import requests import shutil def set_bnds_as_coords(ds): new_coords_vars = [var for var in ds.data_vars if 'bnds' in var or 'bounds' in var] ds = ds.set_coords(new_coords_vars) re...
from .builder import CUDAOpBuilder class QuantizerBuilder(CUDAOpBuilder): BUILD_VAR = "DS_BUILD_QUANTIZER" NAME = "quantizer" def __init__(self, name=None): name = self.NAME if name is None else name super().__init__(name=name) def absolute_name(self): return f'deepspeed.ops....
################################################# ### THIS FILE WAS AUTOGENERATED! DO NOT EDIT! ### ################################################# import pickle, gzip, torch, math, numpy as np, torch.nn.functional as F from pathlib import Path from IPython.core.debugger import set_trace fro...
import json from typing import Any, Dict, Iterable, List from kfp_server_api.models.api_run_detail import ApiRunDetail as kfp_ApiRunDetail import skit_pipelines.constants as const def filter_artifact_nodes(nodes: Dict[str, Any]) -> List[Dict[str, Any]]: return [ node for node in nodes.values() if node[c...
import subprocess from typing import List import click import requests from pygments import console from umm.cli.client import add_request, confirm_request, umm_request from umm.server.__main__ import main @click.command() @click.option("--start", "-s", is_flag=True) @click.option("--add", is_flag=True) @click.argu...
import os import stat def is_executable_file(path): """Checks that path is an executable regular file (or a symlink to a file). This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``, but on some platforms :func:`os.access` gives us the wrong answer, so this checks permission bits dire...
#!/usr/bin/env python # -*- coding: utf-8 -*- import pathlib from pkg_resources import parse_requirements from setuptools import find_packages, setup # Repository root directory for use with reading files directory = pathlib.Path(__file__).parent # Load install_requires from requirements.txt. # https://stackoverflow...
import h5py import numpy as np from torch.utils.data import Dataset class Train_Dataset(Dataset): def __init__(self, h5_file): super(Train_Dataset, self).__init__() self.h5_file = h5_file def __getitem__(self, idx): with h5py.File(self.h5_file, 'r') as fun: return np.expan...
"""Tests for pt_BR time humanizing.""" from __future__ import annotations import datetime as dt import freezegun import pytest from pytest_mock import MockerFixture import human_readable.times as times ONE_DAY_DELTA = dt.timedelta(days=1) # In seconds ONE_MICROSECOND = 1 / 1000000 FOUR_MICROSECONDS = 4 / 1000000 ...
import openpyxl import time import datetime from datetime import timedelta import time import smtplib import re from openpyxl.drawing.image import Image from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email import encoders from constants impo...
from django.shortcuts import render, redirect from django.conf import settings from django.utils import timezone from django.contrib.auth import authenticate, login, update_session_auth_hash from django.contrib.auth.forms import PasswordChangeForm from django.contrib.auth.decorators import login_required from .forms i...
from typing import List from csd.batch import Batch # from csd.codeword import CodeWord from csd.codebooks import CodeBooks from csd.codeword import CodeWord import numpy as np def _get_alphas() -> List[float]: alpha_init = 0.1 alpha_end = 1.4 number_points_to_plot = 16 alpha_step = (alpha_end - alph...
"""A script that does the manual conversion process of our docs automatically. Takes ~15 minutes. TODO(brycew): Robin's doesn't quite work, it's too big as an RTF for some reason. To Install: 1. Install python on Windows: https://www.python.org/downloads/windows/ (remember to put python on the PATH so you can call ...
import requests from urllib.parse import quote_plus class YahooProxyException(Exception): pass class YahooProxy(): ENDPOINT = 'https://query.yahooapis.com/v1/public/yql?format=json&q={query}' def __init__(self): pass def send_query(self, query): target = self.ENDPOINT.format(query=quo...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
from __future__ import absolute_import, unicode_literals from django.conf.urls import include, url from django.core import urlresolvers from django.template.loader import render_to_string from wagtail.wagtailadmin.menu import MenuItem from wagtail.wagtailcore import hooks from . import urls from .models import Remind...
class CannotAddPlaylist(Exception): '''Exception stating that the requested playlist could not be added to the queue.'''
# Copyright 2017 Red Hat # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, sof...
import django.db.models.deletion from django.conf import settings from django.db import migrations, models from opaque_keys.edx.django.models import CourseKeyField class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ ...
# Understand # Plan # Graphs Problem Solving # Translate the problem # Nodes: People # Edges: When a child has a parent # Build our graph, or just define get_neighbors # Choose an Algorithm # Either BFS or DFS # If we use DFS, how would we know if DFS happened to be faster? # import deque from collections # clas...
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import runpy import sys # Sometimes executing scripts can print out stuff before the actual output is # printed. For eg. when activating conda. Hence, printing out markers to make # it more resilient to pull the output. prin...
import json import bson import click from os import path import requests from requests.auth import HTTPBasicAuth from app import app, db def _get_aggreagation(name): with open('distributions.json') as json_data: return json.load(json_data) @click.argument('password') @click.argument('username') @app.c...
__version__ = 0.0