content
stringlengths
0
894k
type
stringclasses
2 values
# Copyright (c) 2011-2013 Kunal Mehta. All rights reserved. # Use of this source code is governed by a BSD License found in README.md. from django.conf import settings from django.contrib.auth import authenticate, login, logout from django.core.urlresolvers import reverse from django.http import HttpResponse, HttpResp...
python
import unittest import torchtext.vocab as v import han.encode.sentence as s class SentenceEncoderTestCase(unittest.TestCase): def test(self): vocab = v.build_vocab_from_iterator([["apple", "is", "tasty"]]) sut = s.SentenceEncoder(vocab) res = sut.forward(["apple is tasty", "tasty is appl...
python
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging from pathlib import Path from typing import Any, Dict, List, Optional import torch from torch import Tensor from fairseq impo...
python
from .abstract_choices_factory import AbstractChoicesFactory from .choice import Choice from src.round import Output from random import randrange class PlayerVsComChoicesFactory(AbstractChoicesFactory): def make_player1_choice(): player_choice = Choice('placeholder') while not player_choice.is_val...
python
from apple_health.util import parse_date, parse_float DATE_COMPONENTS = "@dateComponents" ACTIVE_ENERGY_BURNED = "@activeEnergyBurned" ACTIVE_ENERGY_BURNED_GOAL = "@activeEnergyBurnedGoal" ACTIVE_ENERGY_BURNED_UNIT = "@activeEnergyBurnedUnit" APPLE_EXERCISE_TIME = "@appleExerciseTime" APPLE_EXERCISE_TIME_GOAL = "@appl...
python
# Warning: Don't edit file (autogenerated from python -m dev codegen). ROBOCODE_GET_LANGUAGE_SERVER_PYTHON = "robocode.getLanguageServerPython" # Get a python executable suitable to start the language server. ROBOCODE_GET_PLUGINS_DIR = "robocode.getPluginsDir" # Get the directory for plugins. ROBOCODE_CREATE_ACTIVIT...
python
import urllib2 import threading from bs4 import BeautifulSoup import re import json import sys import os import django from stock_list import getlist, getLSEList from extract_stock_info import get_info, getLSEInfo from extract_stock_history import get_historical_info from extract_sector_history import get_sector_histo...
python
import Tkinter as tk class NatnetView: def __init__(self, parent, reader): self.parent = parent self.reader = reader self.setup() def __del__(self): self.destroy() def destroy(self): self.frame.grid_forget() def setup(self): # container self.fr...
python
import gmpy2 from gmpy2 import ( mpz, powmod, mul, invert, ) B = 2 ** 20 p = mpz('13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084171') g = mpz('117178298803662070095161175963353670885580849999989522...
python
#单一状态 class Borg: __shared_state = {"1":"2"} def __init__(self): self.x = 1 self.__dict__ = self.__shared_state b = Borg() b1 = Borg() b.x = 4 print("Borg Object b:",b) print("Borg Object b1:",b1) print("Object state b:",b.__dict__) print("Object state b1:",b1.__dict__)
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jul 25 06:10:44 2018 @author: Kazuki """ import numpy as np import pandas as pd from tqdm import tqdm import gc, os from collections import defaultdict import sys sys.path.append(f'/home/{os.environ.get("USER")}/PythonLibrary') #import lgbextension as...
python
# flake8: noqa ''' All step-related classes and factories ''' from .base_steps import ( BaseStep, BaseStepFactory, BaseValidation, ) from .steps import TestStep from .outputs import OutputValueStep from .steps_aggregator import StepsAggregator from .validations import ( Validation, XPathValidatio...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import csv import math # Respect seigot class Waypoint: way_point = 0 def __init__(self, path): self.points = [] # self.way_point = 0 with open(path) as f: lines = csv.reader(f) for l in lines: p...
python
import typing from ariadne import SchemaDirectiveVisitor from ariadne.types import GraphQLResolveInfo from graphql import default_field_resolver from pytimeparse import parse as parse_duration from .utils.rate_limit import RateLimit, TooManyRequests class DateDirective(SchemaDirectiveVisitor): def visit_field_d...
python
import random import math import operator from collections import Counter, defaultdict import twokenize import peewee from models import database, SMS, Contact class NaiveBayes(object): def __init__(self): self.doccounts = Counter() self.classcounts = Counter() self.wordcounts = defaultdic...
python
from LucidDynamodb import DynamoDb from LucidDynamodb.exceptions import ( TableNotFound ) import logging logging.basicConfig(level=logging.INFO) if __name__ == "__main__": try: db = DynamoDb() db.delete_table(table_name='dev_jobs') logging.info("Table deleted successfully") tabl...
python
from .queries import *
python
import Transformation import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl def calc_cov_ellipse(a, b, d): s = np.array([[a, b], [b, d]]) (w, v) = np.linalg.eig(s) angle = np.degrees(np.arctan2(v[1, 0], v[0, 0])) return 2*np.sqrt(w[0]), 2*np.sqrt(w[1]), angle class SubPlot: ...
python
from django.db import models from django.utils.text import gettext_lazy as _ from common.models import CommonData, ErrorMessages from jobs.models import JobOffer, Profile class Comment(CommonData): model_name = 'Comment' profile: Profile = models.ForeignKey( to=Profile, on_delete=models.PROT...
python
#!/usr/bin/env python # -*- coding: utf-8 -*-# # MIT License # # Copyright (c) 2019 Pim Witlox # # 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 limita...
python
from hello.hello import print_hello from world.world import print_world def main(): print_hello() print_world() return if __name__ == '__main__': main()
python
from django.contrib.sites.models import Site from .settings import CMS_TEMPLATES from django.contrib.auth.models import User # Default page settings Not used for installation # Content for adding a page # Still under development title = 'Django CMS setup' description = 'Open Source programming at its best' template =...
python
from .shared import replace_gender #TODO At some point, I want to be able to pass only part of the subject tree # to child snippets. class Snippet(object): ''' The base snippet class that all snippets will extend. Responsible for listing required and optional subject data, validating a passed subject, genera...
python
#!/usr/bin/python2.7 ############################################################### #### Assembled by: Ian M. Pendleton ###################### #### www.pendletonian.com ###################### ############################################################### # Updated December 17, 2019 ### T...
python
#!/usr/bin/env python from setuptools import setup from setuptools.command.install import install as _install class install(_install): def pre_install_script(self): pass def post_install_script(self): pass def run(self): self.pre_install_script() _install.run(self) ...
python
bg_black = "\u001b[48;5;0m" bg_gray = "\u001b[48;5;8m" bg_red = "\u001b[48;5;9m" bg_green = "\u001b[48;5;10m" bg_yellow = "\u001b[48;5;11m" bg_blue = "\u001b[48;5;12m" bg_purple = "\u001b[48;5;13m" bg_cyan = "\u001b[48;5;14m" bg_white = "\u001b[48;5;15m" def customColor(number): print(f"\u001b[48;5;{number}m")
python
# Copyright 2021 VMware, Inc. # SPDX-License: Apache-2.0 import logging import salt.exceptions import saltext.vmware.utils.common as utils_common import saltext.vmware.utils.esxi as utils_esxi from salt.defaults import DEFAULT_TARGET_DELIM from saltext.vmware.utils.connect import get_service_instance log = logging.ge...
python
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above...
python
a = int(input()) b = int(input()) cont = a if a <= b: for i in range(a, b+1): for n in range(1, 10+1): total = cont * n print(f'{cont} x {n} = {total}') print('-'*10) cont += 1 else: print('Nenhuma tabuada no intervalo!') ...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Aug 6 07:51:51 2018 @author: tuheenahmmed """ def getWordScore(word, n): """ Returns the score for a word. Assumes the word is a valid word. The score for a word is the sum of the points for letters in the word, multiplied by the leng...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' """ Снежинка / Snowflake """ # Оригинал: http://www.cyberforum.ru/pascalabc/thread994987.html # uses graphABC; # const k=8; # var x,y:integer; # procedure snow (x0,y0,r,n:integer); # const t=2*pi/k; # var i,x,y:integer; # begin # for i:=1 to ...
python
## # Copyright (c) 2007-2016 Apple Inc. All rights reserved. # # 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 l...
python
'''Author: Brandon Trabucco, Copyright 2019 Helper functions to display and run a simple game''' from game_engine.colors import * from game_engine.tiles import * from game_engine.stacks import * from game_engine.drawable import Drawable import random random.seed(12345) ##################################### # lets...
python
import rospy from geometry_msgs.msg import Twist from std_msgs.msg import String import time import sys, select, termios, tty import donkeycar as dk # import keyboard # using module keyboard from pynput import keyboard ############################################################################################# # ...
python
from os import getcwd from re import findall from re import match def parseStep(line): state = match(r"(on|off)", line).groups()[0] x1, x2, y1, y2, z1, z2 = map(int, findall(r"(-?\d+)", line)) return state, (x1, x2), (y1, y2), (z1, z2) def main(): with open(f"{getcwd()}/2021/day22/input.txt") as fi...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- " Help code for sl training " import traceback import numpy as np import torch import torch.nn as nn from pysc2.lib.actions import RAW_FUNCTIONS as F from alphastarmini.core.arch.agent import Agent from alphastarmini.core.sl.feature import Feature from alphastarmini....
python
from ..catalogs.in_memory import Catalog from .dataframe import DataFrameAdapter import dask.dataframe import pandas class ExcelReader(Catalog): """ Read the sheets in an Excel file. This maps the Excel file, which may contain one of more spreadsheets, onto a "Catalog" of tabular structures. Ex...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Tool to manage local 3D Beacon install .. currentmodule:: bio3dbeacon .. moduleauthor:: Ian Sillitoe <i.sillitoe@ucl.ac.uk> """ from .version import __version__, __release__ # noqa
python
import mido import cv2 #Color library using dictionary from RGB to velocity value of the Launchpad MK2 from ClearLaunchpad import RemoveNotes, ClearScreen from FirstMido import FillNotes cap = cv2.imread("Velocity2RGB.png") Complete = cap.copy() while(True): Mat = cv2.inRange(cap, (0, 0, 0), (254, 254, 254)) ...
python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Copyright (c) 2012, Rui Carmo Description: In-process job management License: MIT (see LICENSE.md for details) """ import os, sys, logging, time, traceback, multiprocessing, gc from cPickle import loads, dumps from Queue import PriorityQueue, Empty from threading import T...
python
# Copyright 2019 The Cirq Developers # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
python
#!/usr/bin/python # # Copyright 2019 Polyaxon, Inc. # # 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 o...
python
grk_tws = [['G946'], ['G5206'], ['G3428', 'G3429', 'G3430', 'G3431', 'G3432'], ['G3841'], ['G1041', 'G2379'], ['G281'], ['G32', 'G743', 'G2465'], ['G32', 'G743', 'G218', 'G1472', 'G2025', 'G3462', 'G5545', 'G5548'], ['G500'], ['G651', ' G652', ' G2491', ' G5376', ' G5570'], ['G322', 'G606', 'G1299', 'G1303', 'G1935', '...
python
import os # os is only used for finding a dynamic absolute path to the I/O files absolute_path = os.path.dirname(os.path.abspath(__file__)) inn = absolute_path + '/rom.in' outt = absolute_path + '/rom.out' # Open input files fin = open(inn) fout = open(outt, 'w') # Get first line for array size firstLine = fin.read...
python
import factory from karp.domain.model import Entry, Resource class ResourceFactory(factory.Factory): class Meta: model = Resource entity_id = factory.
python
#!/usr/bin/env python3 # Copyright 2020 Christian Henning # # 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 l...
python
import glob import os import pandas as pd import pytz from dateutil import parser, tz from matplotlib import pyplot as plt fp = "C:\\Users\\Robert\\Documents\\Uni\\SOLARNET\\HomogenizationCampaign\\rome\\" file = os.path.join(fp, "data.csv") data = pd.read_csv(file, delimiter=" ") print(data) converted_data = [] f...
python
from test.common_test_util import expected_result from test.hquery.hquery_test_util import query_html_doc def test_escapes_work_in_string_literals(): assert query_html_doc('', '"foo&#10;bar"') == expected_result(""" foo bar""") assert query_html_doc('', "'foo&#10;bar'") == expected_result(""" foo ...
python
import argparse import sys parser = argparse.ArgumentParser(description='Extract gold entities conll file.') parser.add_argument('--input_file') args = parser.parse_args() reading = 0 golds = [] sentences = [] with open(args.input_file, 'r') as i_file: for line in i_file: line = line.strip() if li...
python
from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.contrib.auth.models import User from django.http import Http404 # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) pic = models.ImageField(upload_to='...
python
import torch import torch.utils.data import os import numpy as np from PIL import Image from utils.util import * def loaderAndResize(path): return Image.open(path).resize((128, 128)) def loader(path): return Image.open(path) class GlassandAttrFaceImageLoader(torch.utils.data.Dataset): def __init__(...
python
#!/usr/bin/env python import pytest from pytest import approx import igrf13 time = "2010-07-12" def test_igrf13(): mag = igrf13.igrf(time, 65, 85, 0, model=12) assert mag.north.item() == approx(9295.100256) assert mag.east.item() == approx(2560.199706) assert mag.down.item() == approx(59670.251893...
python
import logging import sdk_cmd import sdk_tasks import shakedown from tests import config log = logging.getLogger(__name__) def broker_count_check(count, service_name=config.SERVICE_NAME): def fun(): try: if len(sdk_cmd.svc_cli(config.PACKAGE_NAME, service_name, 'broker list', json=True)) == ...
python
# -*- coding: utf-8 -*- """ testunit 基础类 @Time : 2020/4/10 上午1:03 @File : testbase.py @author : pchaos @license : Copyright(C), pchaos @Contact : p19992003#gmail.com """ import unittest import datetime import QUANTAXIS as qa from .testbase import TestingBase class qaTestingBase(TestingBase): """unittest...
python
# -*- coding: utf-8 -*- import pytest import os import csv import tempfile from datetime import datetime from nart.writer.builtins.csvwriter import CSVWriter from nart.model.nartdata import NartData from nart.model.nartitem import NartItem @pytest.fixture def csvwriter_fixture(): """ csvrepo의 filepath를 생성하고,...
python
import torchvision.transforms as transforms config = { 'params': { "backbone": { "kernel_size": 3, "output_dim": 128, "input_dim": 3, "stride": 2, "padding": 1, "out_img_size": 16 }, "primary_capsules": { "k...
python
""" This file is part of tendril See the COPYING, README, and INSTALL files for more information """ import os import imp dirname, fname = os.path.split(os.path.abspath(__file__)) def import_(filename): (path, name) = os.path.split(filename) (name, ext) = os.path.splitext(name) (f, filename, data) = im...
python
# Copyright (C) 2021, Raffaello Bonghi <raffaello@rnext.it> # All rights reserved # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notice, this list...
python
import logging from typing import TYPE_CHECKING, Optional from web3.types import BlockIdentifier from rotkehlchen.assets.asset import Asset from rotkehlchen.constants.assets import A_ALETH, A_ETH, A_WETH from rotkehlchen.constants.ethereum import SADDLE_ALETH_POOL from rotkehlchen.constants.misc import EXP18 from rot...
python
from .version import __version__ # scTenifoldXct.__version__ from scTenifoldXct.core import scTenifoldXct from scTenifoldXct.visualization import get_Xct_pairs, plot_XNet from scTenifoldXct.merge import merge_scTenifoldXct
python
# Copyright 2014-2017 Lionheart Software LLC # # 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...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # check_apcaccess.py - a script for checking a APC UPS # using the apcaccess utility # # 2016 By Christian Stankowic # <info at stankowic hyphen development dot net> # https://github.com/stdevel # # Enhanced and error corrections by Chris Johnston 2017 # Tested on BX1300G ...
python
from tiltfile_runner import run_tiltfile_func from unittest.mock import Mock import unittest import pytest import yaml class DockerLocalTest(unittest.TestCase): def test_delegates_to_local_resource_for_build(self): local_resource = Mock() run_tiltfile_func("docker_task/Tiltfile", ...
python
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # File : embedding.py # Author : Jiayuan Mao # Email : maojiayuan@gmail.com # Date : 10/03/2018 # # This file is part of NSCL-PyTorch. # Distributed under terms of the MIT license. import torch import torch.nn as nn __all__ = ['LearnedPositionalEmbedding'] class ...
python
import os import tempfile import unittest import logging from pyidf import ValidationLevel import pyidf from pyidf.idf import IDF from pyidf.plant_heating_and_cooling_equipment import HeatPumpWaterToWaterEquationFitHeating log = logging.getLogger(__name__) class TestHeatPumpWaterToWaterEquationFitHeating(unittest.Tes...
python
#!/usr/bin/python """ Runs every day as crontab task to pull down previous day's log from Google app engine, and uploads it to S3. """ import os import sys import shutil import subprocess import string from pytz import timezone from datetime import datetime, timedelta settings = { 'appcfg' : '<path to ga...
python
#!/usr/bin/python # Copyright (c) 2017, 2018 Michael De La Rue # Copyright (c) 2017, 2018 Will Thames # Copyright (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'communi...
python
# window.py # # Copyright 2020 Herpiko Dwi Aguno # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is d...
python
''' Module for performing Stable Matching it solves an instance of the stable marriage problem. This is used as a utility for Text-Media Matching ''' class StableMatcher: ''' Class to implement Stable matching This Class implements the stable matching using the gale shapley algorithm. ''' def __...
python
import pandas as pd import numpy as np import matplotlib.pyplot as plt import os csv_files = os.listdir(os.getcwd()) csv_files = [f for f in csv_files if "Line" in f and ".csv" in f] # Function to determine significance def isSignificant(xval,yval, xthr = 1, ythr = 2): if abs(xval) >= xthr and abs(yval) >= ythr: ...
python
x, y = map(int, input().split(" ")) if x == 0 and y == 0: print("origem") elif x > 0 and y > 0: print("1 quadrante") elif x < 0 and y > 0: print("2 quadrante") elif x < 0 and y < 0: print("3 quadrante") elif x > 0 and y < 0: print("4 quadrante") elif x == 0 and y != 0: print("Eixo y") eli...
python
from django.conf.urls import url from web.views import get_index, fetch urlpatterns = [ url(r'^$', get_index), url(r'^fetch/$', fetch), ]
python
#!/usr/bin/env python def part1(numbers, cards): for number in numbers: for card in cards: mark(card, number) if has_won(card): return score(number, card) def part2(numbers, cards): for number in numbers: iter_cards = cards.copy() for card in i...
python
import json import webapp2 from controllers.api.api_base_controller import ApiBaseController from consts.district_type import DistrictType from consts.event_type import EventType from datetime import datetime from database.district_query import DistrictsInYearQuery from database.event_query import DistrictEventsQuer...
python
# coding=utf-8 from sys import exit from pytun import * from scapy.all import * from MANGLE import * from FenrirFangs import * from Autoconf import * import socket import select import time from struct import * from binascii import hexlify,unhexlify class FENRIR: def __init__(self): if os.geteuid() != 0: exit(...
python
from click.testing import CliRunner import unittest from mock import patch, Mock, PropertyMock from floyd.cli.version import upgrade class TestFloydVersion(unittest.TestCase): """ Tests cli utils helper functions """ def setUp(self): self.runner = CliRunner() @patch('floyd.cli.version.pi...
python
# -*- coding: utf-8 -*- """ EnigmaLight Plugin by Speedy1985, 2014 https://github.com/speedy1985 Parts of the code is from DonDavici (c) 2012 and other plugins: all credits to the coders :-) EnigmaLight is free software: you can redistribute it and/or modify it under the terms of the GNU General Public Li...
python
#! /usr/bin/env python3 import os, sys, time, re pid = os.getpid() os.write(1, ("About to fork (pid:%d)\n" % pid).encode()) rc = os.fork() if rc < 0: os.write(2, ("fork failed, returning %d\n" % rc).encode()) sys.exit(1) elif rc == 0: # child os.write(1, ("Child: My pid==%d. Parent'...
python
import sys import math import random class leds: def __init__(self, call): self.call = call def show_next(self, color, index): data = [0x18, 0x05, 0x05, 0x02] if(color == "white"): data[2] = 0x01 elif(color == "red"): data[2] = 0x02 elif(color =...
python
#!/usr/bin/python from UcsSdk import * import time # This script shows how to monitor UCS Manager events and define your own call back to take specific action on the respective events. ucsm_ip = '0.0.0.0' user = 'username' password = 'password' def callback_all(mce): print 'Received a New Event with ...
python
import yaml import sys import os import time import re import copy import pprint """ For each possible rule path """ class ParserError(ValueError): pass class ParserError(ValueError): pass class Context(object): def __init__(self,level,name,parent=None): self.level = level self.name = ...
python
from typing import ClassVar, List, Tuple from urllib.parse import quote as http_quote from .base import BaseProtocol from ..types import IPAddressType # HTTP 1.1 only class HTTPProtocol(BaseProtocol[IPAddressType]): ports: ClassVar[Tuple[int, ...]] = (80,) _TYPES: ClassVar[List[bytes]] = [ b"*/*; q=0...
python
''' Leia a hora inicial e a hora final de um jogo. A seguir calcule a duração do jogo, sabendo que o mesmo pode começar em um dia e terminar em outro, tendo uma duração mínima de 1 hora e máxima de 24 horas. | Input Sample | Output Samples | | ------------ | ----------------------- | | 16 2 | O JOGO D...
python
# stdlib imports import logging from datetime import datetime, timedelta # third party imports from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import (Column, Integer, Float, String, DateTime, ForeignKey, Boolean) from sqlalchemy import create_engine from sqlalchemy.orm ...
python
# Copyright (c) Xidian University and Xi'an University of Posts & Telecommunications. All Rights Reserved import random from .nasbench_101_cell import Cell as Cell_101 from .nasbench_201_cell import Cell as Cell_201 from gnn_lib.data import Data from nas_lib.utils.utils_data import nas2graph from nas_lib.utils.predict...
python
''' Utility module. ''' import yaml import numpy as np swap = lambda x1, x2: (x2, x1) if x1 > x2 else (x1, x2) square = lambda x: x**2 def read_params(file) -> dict: ''' Read yaml file. Args: file (str): Path to the yaml file. Returns: dict: Contents of the yaml file. ''' ...
python
# -*- coding: utf-8 -*- """ Example code showing how to control Thorlabs TDC Motors using PyAPT V1.2 20141125 V1.0 First working version 20141201 V1.0a Updated to short notation 20150324 V1.1 Added more descriptions 20150417 V1.2 Implemented motor without serial Michael Leung mcleung@stanford.edu """ # Imp...
python
''' Дополните приведенный код, так чтобы он вывел сумму квадратов элементов списка numbers. numbers = [1, 78, 23, -65, 99, 9089, 34, -32, 0, -67, 1, 11, 111] ''' numbers = [1, 78, 23, -65, 99, 9089, 34, -32, 0, -67, 1, 11, 111] numbers2 = [] for i in range(len(numbers)): numbers2.append(numbers[i] ** 2) print(sum(n...
python
''' Copyright (C) 2015 Ryan Gonzalez 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, merge, publish, distribute,...
python
# Generated by Django 2.2.24 on 2021-08-16 09:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('landing', '0103_policyarticle'), ] operations = [ migrations.AddField( model_name='section', name='prefix', ...
python
class Config: """Discriminator configurations. """ def __init__(self, steps: int): """Initializer. Args: steps: diffusion steps. """ self.steps = steps # embedding self.pe = 128 self.embeddings = 512 self.mappers = 2 # blo...
python
''' Simple program to gather all the internal and external links. NOT to be confused with inlinks and outlinks. Internal links are those links that point to another website within the same domain External links are those links that point to another website that does NOT share the same domain Reference link: https://www...
python
from setuptools import setup setup( name='simplejira', version='1.0', description='simplejira', author='Brandon Squizzato', author_email='bsquizza@redhat.com', url='https://www.github.com/bsquizz/simplejira', packages=['simplejira'], install_requires=[ 'jira', 'pyyaml', ...
python
import requests import jwt import binascii from base58 import b58decode_check from ecdsa import SECP256k1, VerifyingKey, SigningKey def submitTransaction(signedTransactionHex, nodeURL): endpointURL = nodeURL + "submit-transaction" payload = {'TransactionHex': signedTransactionHex} response = requests.post...
python
"""A module that provides methods for accessing the Auth API and providing the logged in user details.""" import http import json import logging import fastapi import fastapi.security import fastapi.security.http import requests from pydantic import BaseModel # pylint:disable=no-name-in-module import config logge...
python
""" Exercise 7 - Sequence Slicing Question: List slicing is important in various data manipulation activities. Let's do a few more exercises on that. Please complete the script so that it prints out the first three items of list letters. letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] Expected out...
python
#!/usr/bin/env python3 # (C) 2021 gomachssm import datetime __copyright__ = f'(C) {datetime.date.today().year} gomachssm' __version__ = 'dummy' # get from tag, matches v([0-9]+\.[0-9]+\.[0-9]+). __license__ = 'Apache License, Version 2.0' __author__ = 'gomachssm' __url__ = 'https://github.com/gomachssm/twsqlparser'...
python
import os import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import standard.analysis as sa from tools import nicename import tools import task import settings mpl.rcParams['font.size'] = 7 mpl.rcParams['pdf.fonttype'] = 42 mpl.rcParams['ps.fonttype'] = 42 mpl.rcParams['font.family'] = 'aria...
python
from django.shortcuts import render , reverse from django.http import HttpResponseRedirect # Create your views here. def home(request): return render(request , 'home.html')
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Root __init__ """ __author__ = "Samuel Marks" __version__ = "0.0.7" __description__ = "CLI to replace HTTP GET on GitHub API with clones"
python