content
stringlengths
0
894k
type
stringclasses
2 values
""" 3->7->5->12->None """ class SinglyListNode(object): def __init__(self, value): self.value = value self.next = None a = SinglyListNode(3) b = SinglyListNode(7) c = SinglyListNode(5) d = SinglyListNode(12) a.next = b b.next = c c.next = d print(a.next) print(b) print(b.next) print(c) d...
python
from __future__ import absolute_import, unicode_literals import logging from django.core.management.base import BaseCommand from housing_counselor.geocoder import BulkZipCodeGeocoder, GeocodedZipCodeCsv logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Geocode all possible zipcodes' ...
python
""" Ejercicio 6 Escriba un programa que pida la fecha segun el formato 04/12/1973 y lo retome segun el formato 1973/12/04 """ from datetime import date from datetime import datetime fecha = str(input("Ingrese una fecha(formato dd/mm/aaaa): ")) fecha1 = datetime.strptime(fecha, "%d/%m/%Y") fecha3 = datetime.strftime(f...
python
from .registries import Registry, meta_registry, QuerySet, Manager, MultipleObjectsReturned, DoesNotExist __version__ = "0.2.1"
python
# Copyright 2019 The MACE Authors. 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 la...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the tag_linux.txt tagging file.""" import unittest from plaso.containers import events from plaso.lib import definitions from plaso.parsers import bash_history from plaso.parsers import docker from plaso.parsers import dpkg from plaso.parsers import selinux ...
python
__author__ = 'surya' # plot each IntegralInteraction S values and save a plot in the end for the respective plate def plot(file,nslen,slen): import matplotlib.pyplot as plt start=5 list=[] with open(file+"_IntegralIntensity.txt") as files: next(files) for lines in files: s...
python
from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.postgres import fields as pgfields from django.contrib.auth.models import User # about user # h...
python
import requests from bs4 import BeautifulSoup #define a founction that get text from a html page def gettext(url, kv=None): try: r = requests.get(url,headers = kv) r.raise_for_status() r.encoding = r.apparent_encoding return r.text except: print("Failure") #defi...
python
"""\ wxDatePickerCtrl objects @copyright: 2002-2007 Alberto Griggio @copyright: 2014-2016 Carsten Grohmann @copyright: 2016 Dietmar Schwertberger @license: MIT (see LICENSE.txt) - THIS PROGRAM COMES WITH NO WARRANTY """ import wx from edit_windows import ManagedBase, EditStylesMixin from tree import Node import commo...
python
from util.html import HTML import numpy as np import os import ntpath import time from . import util import matplotlib.pyplot as plt from util.util import load_validation_from_file, smooth_kernel, load_loss_from_file class Visualizer(): """This class includes several functions that can display/save images and prin...
python
# Copyright 2009-2010 by Ka-Ping Yee # # 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 w...
python
import pytest import NAME
python
import os import numpy as np import joblib class proba_model_manager(): def __init__(self, static_data, params={}): if len(params)>0: self.params = params self.test = params['test'] self.test_dir = os.path.join(self.model_dir, 'test_' + str(self.test)) self.istra...
python
"""Test the cli_data_download tool outputs.""" # TODO review and edit this import argparse from pathlib import Path from cmatools.cli_data_download import cli_data_download from cmatools.definitions import SRC_DIR DEBUG = True """bool: Debugging module-level constant (Default: True).""" # Define cli filepath CLI =...
python
import sys, json from PIL import Image from parser.png_diff import PNG_DIFF from format.util import * def diff(file_before, file_after): """diff png file args: file_before (str) file_after (str) returns: png_diff (PNG_DIFF) """ png_before = Image.open(file_before) png_...
python
# -*- coding: utf-8 -*- # Check if the move of v can satisfied, makebetter, or notsatisfied from .FMConstrMgr import FMConstrMgr class FMBiConstrMgr(FMConstrMgr): def select_togo(self): """[summary] Returns: dtype: description """ return 0 if self.diff[0] < self.diff...
python
from django.shortcuts import get_object_or_404, render from .models import Card, Group, Product def searching(request, keyword): products = Product.objects.filter(title__contains=keyword) return render(request, 'main/catalog.html', {'products': products, 'keyword': keyword}) def index(request): offers =...
python
# # project-k Forth kernel in python # Use the same kernel code for all applications. # FigTaiwan H.C. Chen hcchen5600@gmail.com 21:14 2017-07-31 # import re, sys name = "peforth" vm = __import__(__name__) major_version = 1; # major version, peforth.py kernel version, integer. ip = 0; stack = [] ; rstack = []; voc...
python
from wallet import Wallet wallet = Wallet() address = wallet.getnewaddress() print address
python
from config.settings_base import * ##### EDIT BELOW API_KEY = "Paste your key in between these quotation marks"
python
from rest_framework import serializers from .models import Homework class HomeworkStudentSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') course = serializers.ReadOnlyField(source='course.id') lecture = serializers.ReadOnlyField(source='lecture.id') g...
python
#!/usr/bin/env python ''' Copyright (C) 2019, WAFW00F Developers. See the LICENSE file for copying permission. ''' NAME = 'Open-Resty Lua Nginx (FLOSS)' def is_waf(self): schema1 = [ self.matchHeader(('Server', r'^openresty/[0-9\.]+?')), self.matchStatus(403) ] schema2 = [ self.ma...
python
from pypy.rlib import _rffi_stacklet as _c from pypy.rlib import objectmodel, debug from pypy.rpython.annlowlevel import llhelper from pypy.tool.staticmethods import StaticMethods class StackletGcRootFinder: __metaclass__ = StaticMethods def new(thrd, callback, arg): h = _c.new(thrd._thrd, llhelper(_...
python
# coding: utf-8 from __future__ import unicode_literals import re from django import forms from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from django.utils.encoding import iri_to_uri, smart_text try: from urllib.parse import urljoin except ImportError: from urlparse import urljoin _...
python
from typing import List import torch import numpy as np # details about math operation in torch can be found in: http://pytorch.org/docs/torch.html#math-operations # convert numpy to tensor or vise versa np_data = np.arange(6).reshape((2, 3)) # reshape 重塑 把1X6矩阵变为2X3矩阵 # numpy.arange([start=0, ]stop, [step=1, ]dtype...
python
# --- # jupyter: # jupytext: # formats: ipynb,py # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.9.1+dev # kernelspec: # display_name: Python [conda env:core_acc_env] * # language: python # name: conda-env-core_ac...
python
from rest_framework import viewsets, filters, status from rest_framework.authentication import TokenAuthentication from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.settings import api_settin...
python
import json, yaml import logging DEBUG =0 logger = logging.getLogger() if DEBUG: #coloredlogs.install(level='DEBUG') logger.setLevel(logging.DEBUG) else: #coloredlogs.install(level='INFO') logger.setLevel(logging.INFO) strhdlr = logging.StreamHandler() logger.addHandler(strhdlr) formatter = logging.F...
python
#!/usr/bin/env python3 """ Makes Maven multi module project. """ from argparse import ArgumentParser from os import makedirs from os.path import realpath, relpath, dirname, normpath from sys import argv import vang.maven.pom as pom POM_TEMPLATE = """<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xs...
python
from sparkpost import SparkPost sp = SparkPost() response = sp.templates.update( 'TEST_ID', name='Test Template', from_email='test@test.com', subject='Updated Test email template!', html='<b>This is a test email template! Updated!</b>' ) print(response)
python
# Copyright 2013 - Noorul Islam K M # # 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 w...
python
import json import logging import os import boto3 from get_and_parse_hiscores.lib.hiscores import rs_api logger = logging.getLogger() logger.setLevel(logging.DEBUG) ddb = boto3.resource("dynamodb") table = ddb.Table(os.environ["HISCORES_TABLE_NAME"]) def handler(event, context): """Call HiScores API, parse res...
python
import sys import copy import math def extra(): fp = open("23.input") nums = list(map(int, fp.readline())) next_nums = {} for i in range(len(nums) - 1): next_nums[nums[i]] = nums[i + 1] MAX_VAL = 1_000_000 next_nums[nums[-1]] = 10 for i in range(10, MAX_VAL): next_nums[i] ...
python
# coding=utf-8 """ Common methods for UI code. """ from __future__ import absolute_import from datacube.utils import is_supported_document_type def get_metadata_path(dataset_path): """ Find a metadata path for a given input/dataset path. :type dataset_path: pathlib.Path :rtype: Path """ # T...
python
import sys import json import collections MEM_TOKEN_SIZE = 4 def build_vocab(tokens, vocab_count): token_list = tokens.split() for tok in token_list: if tok in vocab_count.keys(): vocab_count[tok] += 1 else: vocab_count[tok] = 1 def process_one_conversation(text, voc...
python
import os, wifisec, platform from speedtest import SpeedTest from hku import fetch_heroku from rich import print from rich.table import Table def display(): plat = platform.system() global clear if plat == "Linux": clear = lambda: os.system('clear') elif plat == "Windows": clear = lambd...
python
from scripttease.library.commands.base import Command, ItemizedCommand, Sudo from scripttease.library.overlays.common import python_pip class TestCommand(object): def test_getattr(self): c = Command("ls -ls", extra=True) assert c.extra is True def test_get_statement(self): c = Comman...
python
from AtomicContributions.ContributionsOfAtomsToModes import AtomicContributionsCalculator import unittest import numpy as np import os path_here = os.path.dirname(__file__) class AtomicContributionToModesTest(unittest.TestCase): def setUp(self): self.Contributions = AtomicContributionsCalcula...
python
from typing import Type from serflag import SerFlag from handlers.graphql.utils.query import resolve_from_root def resolve_myactions(actions_type: Type[SerFlag]): def resolver(root, info, **args): actions = resolve_from_root(root, info) if not actions: return [] return actio...
python
#!/usr/bin/python3 import math import pygame import random import sys from pygame import K_d, K_a, K_w, K_s, K_SPACE SIZE = WIDTH, HEIGHT = 500, 500 BLACK = 0, 0, 0 WHITE = 255, 255, 255 SHIP_W = 12 SHIP_H = 25 MAX_SPEED = 3 ASTEROID_LIMIT = 2 class Game_Space: """Initiates and holds all variables needed for t...
python
import logging import os.path from os import getenv import telegram.ext from dotenv import load_dotenv from telegram.ext import Updater, CommandHandler, MessageHandler from telegram.ext.filters import Filters from bot.commands import hello_cmd, echo_cmd, pin_message_cmd, slap_cmd, me_cmd, \ unknown_command_cmd, s...
python
from pyHS100 import Discover for dev in Discover.discover().values(): print(dev) print("host:" + dev.host)
python
from collections import namedtuple Meta= namedtuple('Meta', ('long_name', 'units', 'comment')) Meta.__new__.__defaults__ = (None,) * len(Meta._fields) METADATA = { 'FileCode': Meta( long_name='file_code'), 'HeaderLen': Meta( long_name='header_length', units='bytes'), 'StartTime': M...
python
# Generated by Django 2.2.6 on 2019-10-12 18:48 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('fashion_catalogue', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='category', name='color', )...
python
# eqcmd.py: Basic routines for interfacing with EQ. import asyncio from asyncio.subprocess import create_subprocess_shell, PIPE import eqlog import os import re import shlex import random class CommandError(Exception): """A problem running a command""" pass class NotReadyError(Exception): """EverQuest ...
python
# Generated by Django 2.0.5 on 2018-08-03 11:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('surveys', '0005_answer_training_set'), ] operations = [ migrations.CreateModel( name='Translate_Hired_Power', fields...
python
# Copyright 2021 Google 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 to in writing, ...
python
import numpy as np import tensorflow as tf import time import keras def KL_generated_images(dec, cla, N, dimZ, task, sample_W = True): z = tf.random_normal(shape=(N, dimZ)) x_gen = dec(z, sampling = sample_W) y_gen = tf.clip_by_value(cla(x_gen), 1e-9, 1.0) y_true = np.zeros([N, 10]); y_true[:, task] = ...
python
#!/usr/bin/python # Written By: Sahar Hathiramani # Date: 01/07/2021 import os import socket from termcolor import colored os.system("clear") print("🄱🄰🄳 🄱🄾🅈 🄱🅄🅃 🄰 🅂🄰🄳 🄱🄾🅈") sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.setdefaulttimeout(2) host = input("[*] Please Specify a Host to ...
python
import gzip import warnings from pkg_resources import resource_stream, resource_filename import numpy as np import matplotlib.image as mpimg from os.path import dirname, join def load_hill_topography(): """ Load hillshading and return elevation :return: np.array """ stream = resource_stream(__name...
python
import textwrap import uuid from multiprocessing import Pool from pprint import pprint import oyaml as yaml from cloudmesh.common.DateTime import DateTime from cloudmesh.common.console import Console from cloudmesh.configuration.Config import Config from cloudmesh.mongo.CmDatabase import CmDatabase from cloudmesh.mong...
python
import collections.abc import re import numpy as np import pandas as pd import torch import joblib import os from pathlib import Path from loguru import logger from sklearn.model_selection import train_test_split from torch._six import string_classes, int_classes from ivadomed import utils as imed_utils from ivadomed.k...
python
""" tunning, featuralization, output formatting """ import numpy as np import time def functionongraph(graphs_, i, key='deg', edge_flag=False): # for graphs_[i], get the key-val distribution components = len(graphs_[i]); lis = [] for j in range(components): g = graphs_[i][j] try: ...
python
import discord from discord.ext import commands from discord.ext.commands.cooldowns import BucketType from .utils.video import run_command, video_size, has_audio from .utils.message import get_nearest, get_msg_video, get_msg_image, get_msg_video_or_img import tempfile import os import io from PIL import Image import ra...
python
# This file contain all routes of secretary #################################################################### # import #################################################################### from flask_restx import Resource, reqparse # to use Resource, that expose http request method from ...
python
from view import View from serialConnection import SerialConnection from PyQt5.QtWidgets import QApplication import time class Controller: def __init__(self, serialConnection, Instructions): self.serialConnection = serialConnection self.Instructions = Instructions self.samples = [] ...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from configurable import Configurable #*************************************************************** class BaseOptimizer(Configurable...
python
# %% from sre_constants import error import pandas as pd import openpyxl as pxl from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions a...
python
import unittest from libpysal.examples import load_example import geopandas as gpd import numpy as np from segregation.aspatial import MultiRelativeDiversity class Multi_Relative_Diversity_Tester(unittest.TestCase): def test_Multi_Relative_Diversity(self): s_map = gpd.read_file(load_example("Sacramento1")...
python
#!/usr/bin/python # -*- coding: utf-8 -*- ### BEGIN LICENSE #Copyright (c) 2009 Eugene Kaznacheev <qetzal@gmail.com> #Copyright (c) 2013 Joshua Tasker <jtasker@gmail.com> #Permission is hereby granted, free of charge, to any person #obtaining a copy of this software and associated documentation #files (the "So...
python
#! /usr/bin/python3 from __future__ import unicode_literals # from _typeshed import NoneType import math import os import sys import datetime from typing import TextIO import python_magnetrun import numpy as np import matplotlib # print("matplotlib=", matplotlib.rcParams.keys()) matplotlib.rcParams['text.usetex'] = ...
python
import itertools import numpy as np import pytest from pyquil import Program from pyquil.gate_matrices import QUANTUM_GATES as GATES from pyquil.gates import * from pyquil.numpy_simulator import targeted_einsum, NumpyWavefunctionSimulator, \ all_bitstrings, targeted_tensordot, _term_expectation from pyquil.paulis...
python
from future.utils import iteritems from pandaharvester.harvestercore.plugin_base import PluginBase from pandaharvester.harvestermover import mover_utils # preparator plugin with RSE + no data motion class RseDirectPreparator(PluginBase): """The workflow for RseDirectPreparator is as follows. First panda makes a ...
python
''' Created on Jun 6, 2012 @author: kristof ''' import time import datetime import general_settings from twython import Twython from klout import KloutInfluence import tweeql.extras.sentiment import tweeql.extras.sentiment.analysis from pkg_resources import resource_filename from dateutil import parser import itertool...
python
import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../'))) from src.Utils.Point import Point from src.Utils.Vector import Vector from src.Utils.LinearEquation import LinearEquation import math """ This module regroups a lot of class definition that are basic encapsulat...
python
#!/usr/bin/env python import glob import yaml import sys import argparse import cparser import generator import json from clang.cindex import Index, CursorKind, Config import codecs import re import os from typing import List, Dict file_cache = {} rules = [ [r'@c\s+(\w+)', 'inlinecode'], [r'\s*[@\\]code(.*?...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by yetongxue<me@xander-ye.com> import socket client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(('127.0.0.1', 8001)) while True: re_data = input() client.send(re_data.encode('utf8')) data = client.recv(1024) print(data...
python
from gym_nav.envs.nav_env import NavEnv from gym_nav.envs.multi_nav_env import MultiNavEnv
python
from .get_data import get_all_data, get_data_from_api from ..dict_as_attribute import DictAsObj as DictToObj class Items: states = {} countries = {} total = {} data = get_data_from_api() for entity in data: if 'Countries' == entity: countries.update(data[entity]) elif ...
python
# Copyright 2017, Google 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 copyright # notice, this list of conditions and the f...
python
#!/usr/bin/python3 """ Copyright 2018-2019 Firmin.Sun (fmsunyh@gmail.com) 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 applic...
python
import json from typing import Any import pytest from pydantic import BaseModel, ConfigError, NoneBytes, NoneStr, ValidationError, pretty_errors class UltraSimpleModel(BaseModel): a: float = ... b: int = 10 def test_ultra_simple_success(): m = UltraSimpleModel(a=10.2) assert m.a == 10.2 assert...
python
from accountancy.helpers import sort_multiple from nominals.models import NominalTransaction from vat.models import VatTransaction from cashbook.models import CashBookLine def create_lines(line_cls, header, lines): # DO WE NEED THIS? tmp = [] for i, line in enumerate(lines): line["line_no"] = i +...
python
import random from django.http import Http404, JsonResponse from django.shortcuts import render from .models import Tweet def home_view(request, *args, **kwargs): return render(request, "pages/home.html", context={}, status=200) def tweet_list_view(request, *args, **kwargs): qs = Tweet.objects.all() tw...
python
from models.db import db from models.post import Post from flask_restful import Resource from flask import request from sqlalchemy.orm import joinedload from resources.s3 import * class Posts(Resource): def get(self): posts = Post.find_all() return posts def post(self): data = request...
python
from .base import BaseAttack from .fgsm import FGSMAttack
python
""" rg_utils load helpers methods from python """ import pandas as pd import re import robustnessgym as rg from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score def update_pred(dp, model, dp_only=False): """ Updating data panel with model prediction""" model.predict_batch(dp, [...
python
# Generated by Django 3.0.7 on 2020-07-29 17:16 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('permafrost', '0012_auto_20200729_1710'), ('permafrost', '0015_auto_20200606_0042'), ] operations = [ ]
python
from flask import Flask app = Flask(__name__) def wrap_html(message): html = """ <html> <body> <div style='font-size:80px;'> <center> <image height="600" width="531" src="https://secure.meetupstatic.com/photos/event/2/a/a/3/600_452110915.jpeg"> ...
python
""" Every issue is reported as ``robocop.rules.Message`` object. It can be later printed or used by post-run reports. Output message format --------------------- Output message of rules can be defined with ``-f`` / ``--format`` argument. Default value:: "{source}:{line}:{col} [{severity}] {rule_id} {desc} ({name...
python
#! /usr/bin/env python # -*- coding: utf-8 -*- # # vim: fenc=utf-8 # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # # """ File name: favorites.py Version: 0.1 Author: dhilipsiva <dhilipsiva@gmail.com> Date created: 2015-07-26 """ __author__ = "dhilipsiva" __status__ = "development" """ """ fmt = """ "%i" ...
python
__author__ = 'Pauli Salmenrinne' from setuptools import setup requires = [ ] setup( name='sarch2', version="1.1.0", description='Simple archiving solution', scripts=['bin/sarch2'], packages=['sarch2'], long_description=open('README.rst').read(), url='https://githu...
python
#!/usr/bin/python # # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Recover duts. This module runs at system startup on Chromium OS test images. It runs through a set of hooks to keep a DUT from...
python
#-*-coding: utf8-*- import redis def connection(ip, port): r = redis.StrictRedis(host=ip, port=port, db=0) return r def add(r, query, suggestions): ''' :param query: string :param suggestions: {sug1:score1,sugg2:score2...} use SortedSet to store suggestions ''' r.zadd('suggestions',...
python
import sys import click from tabulate import tabulate from . import admin from ...session import Session from ..pretty import print_error @admin.command() @click.option('--status', default='RUNNING', type=click.Choice(['PREPARING', 'BUILDING', 'RUNNING', 'RESTARTING', ...
python
import io import time from typing import Optional, Tuple from rich.console import Console from rich.live import Live from rich.panel import Panel from rich.progress import ( BarColumn, DownloadColumn, FileSizeColumn, MofNCompleteColumn, Progress, ProgressColumn, SpinnerColumn, Task, ...
python
from django.apps import AppConfig class CapstoneConfig(AppConfig): name = 'capstone'
python
""" Iterative deepening Depth-first Search specialization of a generic search algorithm. """ from typing import Optional from search.algorithms.search import Node, SearchAlgorithm from search.space import Space from search.algorithms.dfs import DFS import time from math import sqrt, pi class IDDFS(DFS): """Iter...
python
from __clrclasses__.System import Comparison as _n_0_t_0 from __clrclasses__.System import ValueType as _n_0_t_1 from __clrclasses__.System import Predicate as _n_0_t_2 from __clrclasses__.System import Array as _n_0_t_3 from __clrclasses__.System import IDisposable as _n_0_t_4 from __clrclasses__.System import SystemE...
python
from pytorch.schedulers.imports import * from system.imports import * @accepts(dict, post_trace=True) @TraceFunction(trace_args=False, trace_rv=False) def load_scheduler(system_dict): learning_rate_scheduler = system_dict["local"]["learning_rate_scheduler"]; optimizer = system_dict["local"]["optimizer"]; ...
python
#!/usr/local/bin/python3 # A wrapper to test query v2 API # Advantage: directly replace the `query` variable with any SQL string # to run the test. In command line, the SQL has to be in one-line # to ensure nothing wrong, which is cumbersome. import subprocess import sys import os MY_ENV = os....
python
from sys import stdin def main(): for s in sorted(list(map(int, stdin.readline().strip())), reverse=True): print("", end="".join(str(s))) if __name__ == "__main__": main()
python
""" Description: Defines the QAOACustom and CircuitSamplerCustom classes that replace the qiskit QAOA and CircuitSampler classes respectively. It is more easily customised than qiskit's built in ones and includes a variety of helper methods. Author: Gary Mooney Adapted from Qiskit 0.26.2 documentation...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2017~2999 - cologler <skyoflw@gmail.com> # ---------- # # ---------- import os import importlib from .common import TypeMatcher for name in os.listdir(os.path.dirname(__file__)): if name.startswith('_') or not name.endswith('.py'): continue ...
python
# Copyright (c) 2021 - present / Neuralmagic, 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 b...
python
# -*- coding: utf-8 -*- # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTI...
python
import json import pathlib import os print("Please enter the input path to the filepath you want to use for Mistos") print("We will create a folder called 'Mistos' there. It contains your input and output directory") path = input() is_dir = False while is_dir == False: path = pathlib.Path(path) if path.is_di...
python
"Tests for presto.map" import unittest as ut from presto.map import System, Constellation, Region class TestMap(ut.TestCase): def test_map(self): "Basic map data functionality test" stacmon = System.by_name("Stacmon") self.assertTrue(stacmon) self.assertEqual(len(list(stacmon.nei...
python
import logging import smores.medkit as medkit failures = [] def rxnorm_ingredient(rxcui, expect): _return_check=False _med_key_check=None _ing_key_check=None _overall=False _failures=[] ingredients = medkit.get_ingredients(rxcui, 'RXNORM') if ingredients is not None: if len(ingredie...
python