content
stringlengths
0
894k
type
stringclasses
2 values
from mock import patch from twisted.trial.unittest import TestCase from apns.errorresponse import ( ErrorResponse, ErrorResponseInvalidCodeError, ErrorResponseInvalidCommandError ) MODULE = 'apns.errorresponse.' class ErrorResponseTestCase(TestCase): CLASS = MODULE + 'ErrorResponse.' def test_...
python
from typing import List def warmUp(nums: List[int], target: int) -> List[int]: numsDict = {} for index, item in enumerate(nums): diff = target - item if diff in numsDict: return numsDict[diff], index numsDict[item] = index
python
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup with open('README.rst') as readme_file: readme = readme_file.read() requirements = [ 'pika', 'twisted', 'checkoutmanager', # The 'collectors' branch of chint...
python
# 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, software # distributed under the Li...
python
from fastapi import APIRouter from kairon.api.auth import Authentication from kairon.api.processor import AccountProcessor from kairon.api.models import Response, User from fastapi import Depends router = APIRouter() auth = Authentication() @router.get("/details", response_model=Response) async def get_users_detail...
python
import time from slacker import Slacker from script.util.BaseFSM import BaseFSM from script.util.misc_util import error_trace class SlackBotFsm(BaseFSM): def __init__(self): super().__init__() self.add_state('pending', initial_state=True) self.add_state('on going') sel...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # rom.py # # Part of MARK II project. For informations about license, please # see file /LICENSE . # # author: Vladislav Mlejnecký # email: v.mlejnecky@seznam.cz from memitem import memitem import sys import mif class rom(memitem): def __init__(self, baseAddress, s...
python
#! /usr/bin/env python # -*- coding:utf-8; mode:python -*- from ilcli import Command class FirstDemoCommand(Command): ignore_arguments = ['-b'] def _init_arguments(self): super()._init_arguments() self.add_argument('--foo') class SecondDemoCommand(FirstDemoCommand): ignore_arguments = ...
python
r"""UTF-8 sanitizer. Python's UTF-8 parser is quite relaxed, this creates problems when talking with other software that uses stricter parsers. >>> _norm(safe_utf8_decode(b"foobar")) (True, ['f', 'o', 'o', 'b', 'a', 'r']) >>> _norm(safe_utf8_decode(b'X\0Z')) (False, ['X', 65533, 'Z']) >>> _norm(safe_utf8_decode(b'OK'...
python
#! /usr/local/bin/python3 import operator import sys from collections import deque from math import prod pubKeys = [int(x) for x in sys.stdin.read().split("\n")[:2]] subject = [1 for i in pubKeys] print(pubKeys) handDivisor = 20201227 acc = [0 for i in pubKeys] for i, k in enumerate(pubKeys): while k != subje...
python
import sys import os sys.path.append(os.path.join('..','utils')) import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from utilsRobust import * ###################### ### VARIOUS TESTS FOR UTILS ROBUST ###################### def test_mestimate(): mean = 0 std = 5 ...
python
import numpy as np from scratch.abstract import AbstractModel class PCA(AbstractModel): def __init__(self): pass @staticmethod def normalizing(v): return (v - np.mean(v)) / np.std(v) def fit(self, X): # step 1: normalizing Xarray = X.to_numpy() self.Xscale = ...
python
from django.db import models class Like(model.Models): uid = models.IntegerField() name = models.CharField() # Create your models here.
python
import numpy as np import pytest import tensorflow as tf from tensorflow.keras.layers import Dense, Input, InputLayer from alibi_detect.cd.preprocess import UAE, HiddenOutput, pca n, n_features, n_classes, latent_dim, n_hidden = 100, 10, 5, 2, 7 shape = (n_features,) X = np.random.rand(n * n_features).reshape(n, n_fea...
python
# Generated by Django 2.1.3 on 2019-02-27 15:31 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('queueapp', '0007_auto_20190220_1642'), ] operations = [ migrations.AddField( model_name='queue', name='pause_and_cle...
python
import re import sys import unittest from line import * from canonicalLine import * from degenerateLine import * from lineClassifier import * import importlib pd.set_option('display.width', 1000) filename = "../testData/daylight_1_4.eaf" xmlDoc = etree.parse(filename) lineCount = len(xmlDoc.findall("TIER/ANNOTATION/A...
python
# pylint:disable=missing-module-docstring,missing-class-docstring,missing-function-docstring from .base import compare_template, SimpleTestCase class CopyButtonTest(SimpleTestCase): maxDiff = None def test_rendered(self): template = """ {% load carbondesign %} {% CopyButton %} """ expected = "...
python
# These should probably all live in separate files from ..tensorboard_writer import TensorboardWriter from allennlp.training.callbacks.events import Events from allennlp.training.callbacks.callback import Callback, handle_event from allennlp.common.params import Params import logging from typing import Set, Dict, TYPE_...
python
from datetime import datetime from decimal import Decimal import calendar from enum import IntEnum import timex from sqlalchemy import event from sqlalchemy import and_, or_ from sqlalchemy import literal_column from sqlalchemy import Column, Table, ForeignKey, Index, UniqueConstraint from sqlalchemy import Float, Bo...
python
from Step_5.A3C import A3Cagent from Step_5.Parameter import PARA from Step_5.A3C_NETWORK import A3C_shared_network class MainModel: def __init__(self): self.worker = [] shared_model = A3C_shared_network().model for i in range(0, 2): self.worker.append(A3Cagent(Remote_ip=PARA.Re...
python
import profig from gogetmarvel.comic import Comic from gogetmarvel.engine import Engine cfg = profig.Config('gogetmarvel/config.cfg') cfg.sync() class Marvel(object): """ Main marvel object connects the engine to its children. """ def __init__(self, private_key=None, public_key=None): """ ...
python
#!/usr/bin/env python #coding:utf-8 import requests import re #下面三行是编码转换的功能,大家现在不用关心。 import sys reload(sys) sys.setdefaultencoding("utf-8") #header是我们自己构造的一个字典,里面保存了user-agent header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36'} #部分网...
python
import repetition menu_selex = 'y' while menu_selex == 'y': #This is so that HW Menu is generated print('\nHomework 3 Menu\n1-Factorial\n2-Sum odd numbers\n3-Exit') selex = int(input('Please select menu item 1, 2 or 3: ')) if selex == 1: #This is the factorial part of the assignment keep_...
python
import os import re import sys import time import traceback import logging import hashlib from urllib.parse import urlsplit, urlunsplit from datetime import datetime from dateutil import tz from flask import ( Flask, render_template, request, redirect, url_for, send_from_directory, jsonify, ...
python
# Assessing placement bias of the global river gauge network # Nature Sustainability # Authors: Corey A. Krabbenhoft, George H. Allen, Peirong Lin, Sarah E. Godsey, Daniel C. Allen, Ryan M. Burrows, Amanda G. DelVecchia, Ken M. Fritz, Margaret Shanafield # Amy J. Burgin, Margaret Zimmer, Thibault Datry, Walter K. Dodds...
python
from __future__ import annotations import logging import random from collections import defaultdict from dataclasses import dataclass from typing import Callable, Dict, List, Optional, Tuple, Union from nuplan.common.actor_state.vehicle_parameters import VehicleParameters from nuplan.database.nuplan_db.lidar_pc impor...
python
from antlr4 import InputStream, CommonTokenStream, ParseTreeWalker from parse.MATLABLexer import MATLABLexer from parse.MATLABParser import MATLABParser from TranslateListener import TranslateListener from error.ErrorListener import ParseErrorExceptionListener from error.Errors import ParseError def parse(in_str): ...
python
import cv2 import numpy as np from matplotlib import cm from matplotlib import pyplot as plt from CS_data_generate import cs_data_generate from deciVAT import deciVAT from decVAT import decVAT from dunns_index import dunns_index from inciVat import inciVAT from incVat import incVAT def length(mat): return np.max...
python
from django.urls import path from . import views urlpatterns = [ path('iniciar-jogo/', views.JogoAPIView.as_view()), path('finalizar-jogo/<int:id>', views.JogoAPIView.as_view()), path('buscar-jogo/<int:id>', views.JogoAPIView.as_view()), ]
python
import numpy import os import sys def testing(l1, l2): outputData = str(19) + ' ' + str(0) + '\n' taken = [0, 0, 1, 1] outputData += ' '.join(map(str, taken)) return outputData def solveIt(inputData): lines = inputData.split('\n') l1, l2 = map(list, zip(*(s.split(" ") for s in lines))) r...
python
""" CAR CONFIG This file is read by your car application's manage.py script to change the car performance. EXMAPLE ----------- import dk cfg = dk.load_config(config_path='~/d2/config.py') print(cfg.CAMERA_RESOLUTION) """ import os #PATHS CAR_PATH = PACKAGE_PATH = os.path.dirname(os.path.realpath(__file__)) DAT...
python
import wpilib.command from wpilib import Timer from data_logger import DataLogger from profiler import TrapezoidalProfile from pidcontroller import PIDController from drivecontroller import DriveController class ProfiledForward(wpilib.command.Command): def __init__(self, distance_ft): super().__init__("P...
python
from typing import Any, Dict __all__ = ( "UserPublicMetrics", "TweetPublicMetrics", ) class UserPublicMetrics: """Represent a PublicMetrics for a User. This PublicMetrics contain public info about the user. .. versionadded:: 1.1.0 """ def __init__(self, data: Dict[str, Any] = {}): ...
python
"""The Labeled Faces in the Wild (LFW) dataset. from dltb.thirdparty.datasource.lfw import LabeledFacesInTheWild lfw = LabeledFacesInTheWild() lfw.prepare() lfw.sklearn is None """ # standard imports import logging import importlib # toolbox imports from dltb.datasource import DataDirectory # logging LOG = logging...
python
import FWCore.ParameterSet.Config as cms muonTrackProducer = cms.EDProducer("MuonTrackProducer", muonsTag = cms.InputTag("muons"), inputDTRecSegment4DCollection = cms.InputTag("dt4DSegments"), inputCSCSegmentCollection = cms.InputTag("cscSegments"), selectionTags = cms.vstring('TrackerMuonArbitrated'), ...
python
''' This file ''' import logging import urllib.parse import requests import datetime import argparse import json import jwt import pytz import time import math class API(object): def __init__(self, clientid=None, clientsecret=None,username=None, password=None,timezone=None): assert clientid is not No...
python
"""URLS for accounts""" from django.urls import path import django.contrib.auth.views from . import views # pylint: disable=invalid-name app_name = 'accounts' urlpatterns = [ path('login/', views.SocialLoginView.as_view(), name='login'), path('login/native/', views.NativeLoginView.as_view(), name='login-na...
python
# Copyright (c) Techland. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. """Contains the Analyser class, used to run analysis on the dependency graph.""" import logging import os from collections import defaultdict import networkx as nx from cppbuil...
python
#!/usr/bin/env python # # Copyright (c) 2010 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # # runclient.py gets the chromoting host info from an input arg and then # tries to find the authentication info in the .chromoti...
python
import numpy as np import scipy.integrate as spi import matplotlib.pyplot as plt #t is the independent variable P = 3. #period value BT=-6. #initian value of t (time begin) ET=6. #final value of t (time end) FS=1000 #number of discrete values of t between BT and ET #the periodic real-valued function f(t) with period ...
python
#first, we import the required libraries import threading, os, time, requests, yaml from tkinter.filedialog import askopenfilename from tkinter import Tk from concurrent.futures import ThreadPoolExecutor from console.utils import set_title from timeit import default_timer as timer from datetime import timedelta,...
python
# This is a dummy test file; delete it once the package actually has tests. def test_import(): import qutip_tensornetwork assert qutip_tensornetwork.__version__
python
import abc from smqtk.utils.plugin import Pluggable class DummyInterface (Pluggable): @abc.abstractmethod def inst_method(self, val): """ test abstract method. """
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals import datetime from django.db import migrations def backfill_91_other_meetings(apps, schema_editor): Meeting = apps.get_model('meeting', 'Meeting') Schedule = apps.get_model('meeting', 'Schedule') ScheduledSess...
python
import csv import os import time import pytest from conftest import params from pygraphblas import * from src.RegularPathQuering import rpq @pytest.mark.parametrize('impl,graph,regex', params) def test_benchmark_rpq(impl, graph, regex): impl_name = impl['name'] g = impl['impl'].from_txt(graph['graph']) ...
python
""" Allen-Zhu Z, Ebrahimian F, Li J, et al. Byzantine-Resilient Non-Convex Stochastic Gradient Descent[J]. arXiv preprint arXiv:2012.14368, 2020. """ import torch import random from .base import _BaseAggregator from ..utils import log class Safeguard(_BaseAggregator): """[summary] Args: _BaseAggr...
python
import os import re import logging import importlib import itertools import contextlib import subprocess import inspect from .vendor import pather from .vendor.pather.error import ParseError import avalon.io as io import avalon.api import avalon log = logging.getLogger(__name__) # Special naming case for subproces...
python
import numpy as np import pytest from numpy.testing import assert_raises from numpy.testing import assert_allclose from sklearn import datasets from inverse_covariance import ( QuicGraphicalLasso, QuicGraphicalLassoCV, QuicGraphicalLassoEBIC, quic, ) def custom_init(X): init_cov = np.cov(X, rowv...
python
# -*- coding: utf-8 -*- from tests import AbstractTestCase class FeaturesTestCase(AbstractTestCase): """ Test case for the methods related to the font features. """ def test_get_features(self): font = self._get_font("/Roboto_Mono/static/RobotoMono-Regular.ttf") features = font.get_fe...
python
from flask import Flask, render_template, request from transformers import pipeline from transformers import RobertaTokenizer, RobertaForSequenceClassification tokenizer = RobertaTokenizer.from_pretrained("pdelobelle/robBERT-base") model = RobertaForSequenceClassification.from_pretrained("dbrd_model2_copy") app = Flas...
python
__author__ = 'Michael Foord'
python
from __future__ import annotations import ast import json from django.contrib import admin from django.utils.safestring import mark_safe from command_log.models import ManagementCommandLog def pretty_print(data: dict | None) -> str: """Convert dict into formatted HTML.""" if data is None: return ""...
python
bicycle = {'Price': '------', 'Brand': '------', 'Model': '------', 'Frame': '------', 'Color': '------', 'Size': '------', 'Fork': '------', 'Headset': '------', 'Stem': '------', 'Handlebar': '------', 'Grips': '------', 'Rear Derailleur': '------', 'Front Derailleur': '------', 'Shifter': '------', 'Brake': '------'...
python
from PyMdlxConverter.common.binarystream import BinaryStream from PyMdlxConverter.parsers.mdlx.tokenstream import TokenStream from PyMdlxConverter.parsers.mdlx.extent import Extent from PyMdlxConverter.parsers.errors import TokenStreamError class Sequence(object): def __init__(self): self.name = '' ...
python
import threading from app.crawler.indeed_job_posting import IndeedJobPostingCrawler from app.crawler.indeed_job_search_result import IndeedJobSearchResultCrawler class CrawlerManager: """ Crawler manager """ @classmethod def start(cls): crawlers = [ IndeedJobPostingCrawler(), ...
python
#Code for acessment of the external coils at equatorial plane #Andre Torres #21-12-18 from getMirnov import * %matplotlib qt4 #SDAS INFO shotN=44835 #44409 ch_rad_u = 'MARTE_NODE_IVO3.DataCollection.Channel_141' ch_vertical= 'MARTE_NODE_IVO3.DataCollection.Channel_142' ch_rad_b = 'MARTE_NODE_IVO3.DataCollection.Channe...
python
import math, csv, re def check_negative(freq): if freq < 0: raise ValueError("negative frequency") def cent_diff(freq1, freq2): """Returns the difference between 2 frequencies in cents Parameters ---------- freq1 : float The first frequency freq2 : float The second fre...
python
import itertools N = int(input()) pairs = [] for x in range(N): input_ = input().split() pairs.append([input_[0], input_[len(input_)-1]]) random = ['Beatrice', 'Sue', 'Belinda', 'Bessie', 'Betsy', 'Blue', 'Bella', 'Buttercup'] perm = list(itertools.permutations(random)) possible_list = [] for x in ...
python
""" written by Joel file from previous assignment with some changes to fit the new one contains all the magic numbers for the boid class created in the Pacman game """ import numpy as np # if True the objects that passes through the screen will # appear on a random spot on the other side. RANDOM_MODE ...
python
# Generated by Django 2.1.7 on 2019-04-01 15:18 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('webapp', '0039_auto_20190317_1533'), ('webapp', '0040_merge_20190312_1600'), ] operations = [ ]
python
import logging import random import numpy as np from transformers import BertConfig logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s') logger = logging.getLogger(__name__) class InputFeatures(object): """A single set of original_features of data.""" def __init__(self, input_ids, i...
python
import pytest from stix2 import TLP_AMBER, Malware, exceptions, markings from .constants import FAKE_TIME, MALWARE_ID from .constants import MALWARE_KWARGS as MALWARE_KWARGS_CONST from .constants import MARKING_IDS """Tests for the Data Markings API.""" MALWARE_KWARGS = MALWARE_KWARGS_CONST.copy() MALWARE_KWARGS.u...
python
# Copyright 2018 ICON Foundation # # 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 writi...
python
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
python
class Grill: """ This is grill. """
python
import torch from torch import nn from copy import deepcopy from utils import visualize_batch class LLL_Net(nn.Module): """ Basic class for implementing networks """ def __init__(self, model, remove_existing_head=False): head_var = model.head_var assert type(head_var) == str assert no...
python
import json from django.conf import settings import requests class SalsaException(Exception): pass class SalsaAPI(object): ''' Wrapper for supporter methods: https://help.salsalabs.com/hc/en-us/articles/224470107-Engage-API-Supporter-Data ''' HOSTNAME = 'https://api.salsalabs.org' SAMP...
python
from typing import Literal from beartype._decor.main import beartype from pglet.control import Control POSITION = Literal[None, "left", "top", "right", "bottom"] class Spinner(Control): def __init__( self, label=None, id=None, label_position: POSITION = None, size=None, ...
python
from django.conf.global_settings import AUTH_USER_MODEL from django.contrib.auth.models import User from django.db import models from django.utils import timezone class Environment(models.Model): name = models.CharField(max_length=150) active = models.BooleanField(default=True) def set_environment_into_s...
python
from django.urls import path from .views import UserApi, CrimeMap, EntertainmentMap, EventMap, ArtMap, DirtinessMap from rest_framework.authtoken import views urlpatterns = [ path('user/', UserApi.as_view(), name="user-detail"), path('login/', views.obtain_auth_token), path('crime/', CrimeMap.as_view(), na...
python
from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class PimdmStateRefresh(Base): __slots__ = () _SDM_NAME = 'pimdmStateRefresh' _SDM_ATT_MAP = { 'HeaderVersion': 'pimdmStateRefreshMessage.header.version-1', 'HeaderType': 'pimdmStateRefreshMessage.header.type-2...
python
from binary_search_tree.e_search_bst import BinarySearchTree from binarytree import build class TestBinarySearchTree: def test_null_node(self): bst = BinarySearchTree() ans = bst.searchBST(None, 10) assert ans is None def test_root_node(self): bst = BinarySearchTree() ...
python
# Generated by Django 4.0.3 on 2022-03-21 06:04 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('inadimplentes', '0010_alter_inquilino_status_de_pagamentos'), ] operations = [ migrations.RemoveField( model_name='inquilino', ...
python
''' 线性回归: 输入 输出 0.5 5.0 0.6 5.5 0.8 6.0 1.1 6.8 1.4 7.0 ... y = f(x) 预测函数:y = w0+w1x x: 输入 y: 输出 w0和w1: 模型参数 所谓模型训练,就是根据已知...
python
"""Implementation of Rule L020.""" import itertools from sqlfluff.core.rules.base import BaseCrawler, LintResult class Rule_L020(BaseCrawler): """Table aliases should be unique within each clause.""" def _lint_references_and_aliases( self, table_aliases, value_table_function_aliases...
python
from django.db import models class ExchangeRateManager(models.Manager): def get_query_set(self): return super(ExchangeRateManager, self).get_query_set()\ .select_related('source', 'target') def get_rate(self, source_currency, target_currency): return self.get(source__code=source_c...
python
import base64 class Module: def __init__(self, mainMenu, params=[]): # metadata info about the module, not modified during runtime self.info = { # name for the module that will appear in module menus 'Name': 'CreateDylibHijacker', # list of one or more authors ...
python
import dash_html_components as html import dash_core_components as dcc import dash_bootstrap_components as dbc from dash.dependencies import Output,Input,State from dash import no_update import random from flask_login import current_user import time from functools import wraps from server import app login_alert = dbc...
python
# -*- coding: utf-8 -*- """Namespace Service The namespace service is responsible for * Providing the default namespace from config * Providing list of all known namespaces """ from typing import List from brewtils.models import Garden, Request, System import beer_garden.db.api as db import beer_garden.config as co...
python
from dancingshoes.helpers import GlyphNamesFromFontLabFont, AssignFeatureCodeToFontLabFont from myFP.features import MakeDancingShoes f = fl.font fl.output = '' glyphnames = GlyphNamesFromFontLabFont(f) shoes = MakeDancingShoes(glyphnames) AssignFeatureCodeToFontLabFont(f, shoes) # Verbose output if sh...
python
# Copyright 2018 Xanadu Quantum Technologies 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 or agre...
python
#!/usr/bin/env python # encoding: utf-8 # File : test_processor.py # Author : Ben Wu # Contact : benwu@fnal.gov # Date : 2019 Mar 06 # # Description : import sys import os sys.path.insert(1, "%s/../.." % os.path.dirname(os.path.abspath(__file__))) from NanoUpTools.framework import processor f...
python
#!/bin/python3 import os # Complete the maximumPeople function below. def maximumPeople(p, x, y, r): # Return the maximum number of people that will be in a sunny town after removing exactly one cloud. import operator # make list of cloud tuples with start and end clouds = [] for location_cloud,...
python
from .subsample import ExtractPatches from .augment import Flip_Rotate_2D, Shift_Squeeze_Intensities, Flip_Rotate_3D, MaskData
python
import requests class Config: ak = "PmkYQbXLGxqHnQvRktDZCGMSHGOil2Yx" ride_url_temp = "http://api.map.baidu.com/direction/v2/riding?origin={},{}&destination={},{}&ak={}" baidu_map_url_temp = "http://api.map.baidu.com/geocoding/v3/?address={}&output=json&ak={}" wm_get_url = "https://apimobile.meituan.c...
python
import datetime import time import iso8601 import psycopg2 from temba_client.v2 import TembaClient RAPIDPRO_URL = "https://rapidpro.prd.momconnect.co.za/" RAPIDPRO_TOKEN = "" DB = { "dbname": "ndoh_rapidpro", "user": "ndoh_rapidpro", "port": 7000, "host": "localhost", "password": "", } if __nam...
python
# -*- coding: utf-8 -*- # # Copyright (C) 2006-2009 Edgewall Software # Copyright (C) 2006 Matthew Good <matt@matt-good.net> # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac...
python
#!/usr/bin/env python # -- coding: utf-8 -- """ @AUTHOR : zlikun <zlikun-dev@hotmail.com> @DATE : 2019/03/01 17:03:55 @DESC : 两数相加 """ class ListNode: def __init__(self, x): self.val = x self.next = None # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # ...
python
#-*- coding: utf-8 -*- from api.management.commands.importbasics import * def import_idols(opt): local, redownload = opt['local'], opt['redownload'] idols = models.Idol.objects.all().order_by('-main', '-main_unit') for idol in raw_information.keys(): card = models.Card.objects.filter(name=idol).ord...
python
#-*- coding:utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (C) 2013-2015 Akretion (http://www.akretion.com) from . import wizard
python
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: rastervision/protos/task.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import ref...
python
from rest_framework.serializers import ModelSerializer from .models import UploadedFile class UploadedFileSerializer(ModelSerializer): class Meta: model = UploadedFile fields = ("id" , "user_id" , "file" , "size" , "type" ) def __init__(self, *args, **kwargs): super(UploadedFi...
python
# Data sources tissues = { 'TCGA': ['All'], 'GDSC': ['All'] } projects = { 'TCGA':[None], 'GDSC': None } data_sources = ['GDSC', 'TCGA'] data_types = ['rnaseq'] genes_filtering = 'mini' source = 'GDSC' target = 'TCGA' # TRANSACT analysis kernel_surname = 'rbf_gamma_0_0005' kernel_name = 'rbf' kernel...
python
import unittest from mocks import MockUser class TestUser(unittest.TestCase): def testEmailNickname(self): user = MockUser(email="foo@example.com") self.assertEquals(str(user), "foo") def testNicknameOverride(self): user = MockUser(email="foo@example.com", nickname="bar") self.assertEquals(str...
python
#!/usr/bin/env python3 import sys def main(phone_map, abbreviations): phone_map = {v[0]: v[1].strip() for v in (l.split(None, 1) for l in open(phone_map, encoding='utf-8'))} abbr_map = {v[0]: v[1].strip().split(',') for v in (l.split(None, 1) ...
python
"""Tests for the HTMLSanitize preprocessor""" from .base import PreprocessorTestsBase from ..sanitize import SanitizeHTML from nbformat import v4 as nbformat class TestSanitizer(PreprocessorTestsBase): """Contains test functions for sanitize.py""" maxDiff = None def build_preprocessor(self): ...
python
'''Dois times, Cormengo e Flaminthians, participam de um campeonato de futebol, juntamente com outros times. Cada vitória conta três pontos, cada empate um ponto. Fica melhor classificado no campeonato um time que tenha mais pontos. Em caso de empate no número de pontos, fica melhor classificado o time que tiver maior ...
python
""" Класс данных БД """ import sqlite3 import os class DbLib: def __init__(self,namefile): if not os.path.exists(namefile): self.conn = sqlite3.connect(namefile, check_same_thread=False) self.c = self.conn.cursor() # Create table ...
python
from discord.ext import commands as cmd import os import util.Modular as mod class Setup(cmd.Cog): def __init__(self, panda): self.panda = panda @cmd.Cog.listener() async def on_ready(self): print('Successfuly initalized Panda™'+'\n'*5) @cmd.command(help='Basic inform...
python
import time # You can edit this code and run it right here in the browser! # First we'll import some turtles and shapes: from turtle import * from shapes import * # Creating a window window = turtle.Screen() window.setup(400, 400) # Create a turtle named Tommy: tommy = Turtle() tommy.shape("turtle") tommy.speed(0) # s...
python