text
string
size
int64
token_count
int64
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # -------------------------------------------------------------------------- from enum import IntEnum from .. import utils __all__ = ["EventTypes", "create_event"] logger = utils.ge...
3,351
1,022
# Copyright (c) 2012 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. { 'variables': { 'chromium_code': 1, }, 'includes': [ '../build/win_precompile.gypi', 'base.gypi', ], 'targets': [ { 'tar...
59,130
19,457
""" PROBLEM A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. ANSWER: 906609 Solve time ~ 0.760 seconds """ from itertools import product import unittest fro...
1,029
374
import sys import json import logging import argparse import warnings import requests from indexclient import errors # DEPRECATED 11/2019 -- interacts with old `/alias/` endpoint. # For creating aliases for indexd records, prefer using # the `add_alias` function, which interacts with the new # `/index/{GUID}/aliase...
1,399
420
import psycopg2 import redis import json from bottle import Bottle, request class Sender(Bottle): def __init__(self): super().__init__() self.route('/', method='POST', callback=self.send) self.fila = redis.StrictRedis(host='queue', port=6379, db=0) DSN = 'dbname=email_sender user=p...
1,151
386
import click import poyo import ruamel.yaml import runez import strictyaml import yaml as pyyaml from zyaml import load_path, load_string, tokens_from_path, tokens_from_string from zyaml.marshal import decode, default_marshal, represented_scalar from . import TestSettings class ImplementationCollection(object): ...
8,949
2,714
import pandas as pd import numpy as np import re import pickle # plotting import seaborn as sns import matplotlib.pyplot as plt # Tune learning_rate from numpy import loadtxt from xgboost import XGBClassifier from sklearn.model_selection import GridSearchCV from sklearn.model_selection import Stratifie...
11,447
4,054
############################################################################### # @todo add Pilot2-splash-app disclaimer ############################################################################### """ Get's KRAS states """ import MDAnalysis as mda from MDAnalysis.analysis import align from MDAnalysis.lib.mdamath ...
17,464
6,645
""" homeassistant.components.switch.hikvision ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Support turning on/off motion detection on Hikvision cameras. Note: Currently works using default https port only. CGI API Guide: http://bit.ly/1RuyUuF Configuration: To use the Hikvision motion detection switch you will need to...
3,676
1,145
"""Define mixins to easily compose custom FilterDefinition classes.""" class TermsQueryMixin: """A mixin for filter definitions that need to apply term queries.""" def get_query_fragment(self, data): """Build the query fragments as term queries for each selected value.""" value_list = data.ge...
5,689
1,340
from typing import List, Optional, TYPE_CHECKING import weakref from PyQt5.QtCore import QEvent, Qt from PyQt5.QtWidgets import (QComboBox, QGridLayout, QGroupBox, QHBoxLayout, QLabel, QLineEdit, QVBoxLayout, QWidget) from electrumsv.app_state import app_state from electrumsv.bitcoin import script_template_to_str...
12,830
3,996
import os import sys if sys.version_info[0] == 2: _ENCODE = sys.getfilesystemencoding() def path_join(*args): bin_args = map(lambda a: a.decode(_ENCODE), args) return os.path.join(*bin_args).encode(_ENCODE) def str_join(s, l): bin_args = map(lambda a: a.decode(_ENCODE), l) b = s.decode(_ENCODE)...
514
198
#!/usr/bin/env python """ VAPI test """ import unittest import os import signal from framework import VppTestCase, running_extended_tests, \ VppTestRunner, Worker @unittest.skipUnless(running_extended_tests(), "part of extended tests") class VOMTestCase(VppTestCase): """ VPP Object Model Test """ def te...
1,518
445
import json import re import scrapy from locations.hourstudy import inputoutput DAYS = { 'mo': 'Mo', 'tu': 'Tu', 'we': 'We', 'fr': 'Fr', 'th': 'Th', 'sa': 'Sa', 'su': 'Su', } class TescoSpider(scrapy.Spider): name = "tesco" allowed_domains = ["tescolocation.api.tesco.com"] def st...
3,096
972
from importlib import import_module import re from copy import deepcopy from collections import OrderedDict from astropy.utils.data_info import MixinInfo from .column import Column from .table import Table, QTable, has_info_class from astropy.units.quantity import QuantityInfo __construct_mixin_classes = ('astropy.t...
12,883
3,792
''' Created on Jun 18, 2013 @author: Yubin Bai All rights reserved. ''' import time from multiprocessing.pool import Pool parallelSolve = False infinity = 1 << 30 def solve(par): H, U, D, F = par day = 0 amountRise = U currH = 0 while True: amountRise = U * (1 - 0.01 * F * day) ...
1,914
686
from typing import Dict, Optional, List, Any import torch import torch.nn.functional as F from allennlp.data import Vocabulary from allennlp.models.model import Model from allennlp.modules import FeedForward, TextFieldEmbedder, Seq2SeqEncoder from allennlp.nn import InitializerApplicator, RegularizerApplicator from al...
5,074
1,553
# # -*- coding: utf-8 -*- """Development related tasks to be run with 'invoke'""" import os import pathlib import shutil import invoke TASK_ROOT = pathlib.Path(__file__).resolve().parent TASK_ROOT_STR = str(TASK_ROOT) # shared function def rmrf(items, verbose=True): """Silently remove a list of directories or ...
4,716
1,607
import stl_path class MyNDRPlugin(): def __init__(self): pass def pre_iteration(self, finding_max_rate, run_results=None, **kwargs): """ Function ran before each iteration. :parameters: finding_max_rate: boolean Indicates whether we are running ...
4,116
1,034
"""Support for Epson Workforce Printer.""" from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_HOST, CONF_MONITORED_CONDITIONS from homeassistant.exceptions import PlatformNotReady import homeassistant....
2,590
851
import asyncio import logging import random import typing as t from datetime import datetime, timezone from operator import attrgetter import discord import discord.abc from discord.ext import commands from bot import constants from bot.bot import Bot from bot.exts.help_channels import _caches, _channel, _cooldown, _...
19,661
5,551
import os import math import random import time from code.menu.menu import Menu from code.tools.eventqueue import EventQueue from code.tools.xml import XMLParser from code.utils.common import coalesce, intersect, offset_rect, log, log2, xml_encode, xml_decode, translate_rgb_to_string from code.constants.common i...
16,516
4,776
# -*- coding: utf-8 ; test-case-name: bridgedb.test.test_runner -*- # # This file is part of BridgeDB, a Tor bridge distribution system. # # :authors: Isis Lovecruft 0xA3ADB67A2CDB8B35 <isis@torproject.org> # please also see AUTHORS file # :copyright: (c) 2007-2015, The Tor Project, Inc. # (c) 200...
3,665
1,051
#!/usr/bin/env python3 # # Create disk image # import re, sys, traceback from .tasks import task_fetch_partitions, task_refresh_partitions, task_mount, task_remove_persistent_rules, task_remove_logs, task_fsck, task_shrink_partition, task_expand_partition, task_unmount from .partclone_tasks import task_create_disk_im...
4,258
1,396
import argparse import logging import apache_beam as beam from apache_beam.io import WriteToBigQuery from apache_beam.io import ReadFromText, WriteToText from apache_beam.options.pipeline_options import PipelineOptions class ProcessCSV(beam.DoFn): def process(self, element, *args, **kwargs): import csv ...
4,053
1,141
from flask import request from flask_jwt import jwt_required from flask_restful import Resource from main.server import app, cache, db from main.server.models import Message, MessageSchema messages_schema = MessageSchema(many=True) message_schema = MessageSchema() @app.after_request def add_header(response): r...
4,259
1,238
#!/usr/bin/env python3 import rospy from wecook.msg import ActionMsg, TaskMsg, SceneMsg, ObjectMsg, ContainingMsg, AgentMsg def talker(): pub = rospy.Publisher('WeCookDispatch', TaskMsg, queue_size=10) rospy.init_node('wecook_chicken_pasta', anonymous=True) scene_msg = SceneMsg([ObjectMsg('wall0', ...
5,171
1,717
# -*- coding: utf-8 -*- {{{ # vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et: # # Copyright 2017, Battelle Memorial Institute. # # 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...
5,380
1,522
"""Ni-Superalloy dataset. Scientific Machine Learning Benchmark A benchmark of regression models in chem- and materials informatics. 2019, Brendan Folie, Citrine Informatics. See class NiSuperalloyDataset for details. """ import os import json import zipfile from typing import List, Optional, Tuple, Union import nu...
18,984
5,128
import metricbeat import os import pytest import sys import unittest class Test(metricbeat.BaseTest): COMPOSE_SERVICES = ['postgresql'] def common_checks(self, output): # Ensure no errors or warnings exist in the log. self.assert_no_logged_warnings() for evt in output: t...
3,777
1,099
# Copyright The PyTorch Lightning team. # # 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 i...
2,520
735
from django.contrib import admin from books.models import Genre, Author, Book, TBR # Register your models here. admin.site.register(Genre) admin.site.register(Author) admin.site.register(Book) admin.site.register(TBR)
219
69
# (C) Datadog, Inc. 2018-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import os from packaging import version from datadog_checks.base.utils.common import get_docker_hostname HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(os.path.dirname(HERE)) ...
2,337
1,032
# Copyright 2020 The StackStorm Authors. # Copyright 2019 Extreme Networks, 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 ...
7,668
2,237
# Look at the charactercreator_character table # GET_CHARACTERS = """ # SELECT * # FROM charactercreator_character; # """ # How many total Characters are there? (302) TOTAL_CHARACTERS = """ SELECT COUNT(*) as number_of_characters FROM charactercreator_character; """ # How many of each specific subclass? # TOTAL_SUBC...
2,952
1,004
#! /usr/bin/env python # import warnings import numpy as np UNIT_SQUARE = np.asarray([[0,0],[0,1],[1,1],[1,0]])-0.5 from propobject import BaseObject from shapely import geometry import pandas import geopandas # ======================= # # # # Functions # # ...
21,364
6,257
""" Binary serialization NPY format ========== A simple format for saving numpy arrays to disk with the full information about them. The ``.npy`` format is the standard binary file format in NumPy for persisting a *single* arbitrary NumPy array on disk. The format stores all of the shape and dtype information necess...
31,445
9,106
""" Enumerator Test """ from typing import Any class is_valid_enum(): """ Test if a variable is on a list of valid values """ __slots__ = ('symbols') def __init__(self, **kwargs): """ -> "type": "enum", "symbols": ["up", "down"] symbols: list of allowed values (case sensit...
539
169
#!/usr/bin/env python from zoneinfo import ZoneInfo import flask from dateutil.parser import parse from flask_assets import Bundle, Environment from logzero import logger, setup_logger from webassets.filter import get_filter from config import cfg from apis import calendar as gcal setup_logger(name=__name__) app =...
2,420
836
#!/usr/bin/env python import astropy.io.fits as fits import numpy as np import os import matplotlib.pyplot as plt import argparse def _fname(expid, night, basedir='/n/home/datasystems/users/ameisner/reduced/focus', ccds=False): fname = basedir + '/' + night + '/' + str(expid).zfill(...
6,090
2,434
from typing import List from ddq.taxonomy.reference import Reference from ddq.topics.topic import Topic class Logic(Topic): def references(self) -> List[Reference]: return [ Reference("Classical and Nonclassical Logics", [("Eric", "Schechter")]) ]
313
87
# Copyright (c) Facebook, Inc. and its affiliates. import base64 import logging import os import sys from tensorboardX import SummaryWriter from pythia.utils.distributed_utils import is_main_process from pythia.utils.general import (ckpt_name_from_core_args, foldername_from_config_ov...
4,344
1,307
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities fro...
13,522
3,849
import sys import os import sphinx_rtd_theme source_path = os.path.normpath( os.path.join( os.path.abspath( os.path.split(__file__)[0]))) try: from conf_base import * except ImportError: sys.path.append(source_path) from conf_base import * html_theme = 'sphinx_rtd_theme' html_the...
661
254
""" This module contains routines for reading and working with adv data. It contains: +-----------------------------------+-----------------------------------------+ | Name | Description | +===================================+====================================...
2,247
474
# Generated by Django 3.1.2 on 2020-10-11 10:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0001_initial'), ] operations = [ migrations.AlterField( model_name='task', name='author', field=m...
561
189
# # 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...
4,123
1,121
__author__ = "Dave Wapstra <dwapstra@cisco.com>" from unicon.plugins.confd import ConfdServiceList, ConfdConnection, ConfdConnectionProvider from .statemachine import CspStateMachine from .settings import CspSettings from . import service_implementation as csp_svc class CspServiceList(ConfdServiceList): def __i...
711
223
# -*- coding: utf-8 -*- from setuptools import setup import search_google as package def readme(): with open('README.rst') as f: return ''.join(f.readlines()[11:]) setup( name=package.__name__, version=package.__version__, description=package.__description__, long_description=readme(), author=pack...
665
224
import setuptools import os try: import pypandoc description = pypandoc.convert('README.md', 'rst') if os.path.exists('README.md') else '' except ImportError: description = '' setuptools.setup( name = 'macpack', packages = setuptools.find_packages(), version = '1.0.3', description = 'Makes a macOS binar...
851
296
import vtk # Read the file (to test that it was written correctly) reader = vtk.vtkXMLImageDataReader() reader.SetFileName("../data/wind_image.vti") reader.Update() print(reader.GetOutput()) # Convert the image to a polydata imageDataGeometryFilter = vtk.vtkImageDataGeometryFilter() imageDataGeometryFilter.SetInputCon...
1,371
435
""" # ----------------------------------------------------------------------------- # @brief: # Tingwu: reset the reward function so that it's more similar to the one # defined in GYM # ----------------------------------------------------------------------------- """ import numpy as np from mbbl.config i...
11,303
3,654
from .bar import * from .create_session import * from .image import * from .line import * from .mesh import * from .pie import * from .text import * from .VisdomFigure import * from .VisdomScene import *
270
71
# Ping Pong Pi web UI running on flask. # Uses zmq to speak to daemon controlling screen. from flask import Flask, render_template, appcontext_tearing_down, request from multiprocessing import Process, Queue from multiprocessing.connection import Client import atexit import time import zmq app = Flask(__name__) @ap...
1,426
476
# -*- encoding: utf-8 -*- # Copyright (c) 2019 European Organization for Nuclear Research (CERN) # # 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...
5,171
1,554
from sudoku import Sudoku def main(): s = Sudoku.parse( ''' ------------- | |2 | | | | 6 |4 3| | | 5| 7 | ------------- | 7 | 2|8 | |51 | 4|9 | | 9| 3| | ------------- | | 9| | | 2| | 98| | 83|1 |2 | ------------- ''' ) print(s) print(s.solve()) if __name...
346
197
import numpy as np import pandas as pd from autogbt.sampler import MajorityUnderSampler def _test_sample(y): sampler = MajorityUnderSampler() idx = sampler.sample(y, 40000, 3.0) assert len(idx) == 40000 assert y[idx].sum() == 10000 def test_sample_with_series(): y = pd.Series(np.concatenate([np....
776
343
import numpy as np import sys from timeit import default_timer as timer sys.path.append("../../") from core import wnn from encoding import thermometer from encoding import util #Load Diabetes data base_path = "../../dataset/diabetes/" #2/3 Test bits_encoding = 20 train_data, train_label, test_data, test_label, data...
2,157
909
from pygamehelper import * from pygame import * from pygame.locals import * from vec2d import * from random import uniform import numpy as np class Starter(PygameHelper): def __init__(self): self.w, self.h = 800, 600 PygameHelper.__init__(self, size=(self.w, self.h), fill=((0,0,0))) d...
690
237
import glob import os import sys import utils from recorder import StreamRec OUTDIR = "" def parse_args(a): global OUTDIR i = 1 while i < len(a): if a[i] in ["-h", "--help", "/?"]: usage() if a[i] in ["-d", "--dir"]: OUTDIR = a[i + 1] i += 1 i ...
1,155
402
# Copyright (c) 2017 Huawei Technologies Co., Ltd. # 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 # # ...
2,268
695
#!/usr/bin/python # -*- coding: utf-8 -*- # routers are dictionaries of URL routing parameters. # # For each request, the effective router is: # the built-in default base router (shown below), # updated by the BASE router in routes.py routers, # updated by the app-specific router in routes.py routers (if an...
9,507
2,880
#%% from uarray.core import * #%% s = Scalar(Int(10)) #%% @operation def Always(a: T) -> CCallableUnary[T, CContent]: ... #%% register(Call(Always(w("a")), w("idx")), lambda a, idx: a) #%% a_ten = Always(s) #%% s = Sequence(Int(10), a_ten)
252
122
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyBlack(PythonPackage): """Black is the uncompromising Python code formatter. By using it,...
2,540
1,117
# -*- coding: utf-8 -*- # @Author: Manuel Rodriguez <valle> # @Date: 27-Aug-2017 # @Email: valle.mrv@gmail.com # @Filename: admin_extras.py # @Last modified by: valle # @Last modified time: 02-Feb-2018 # @License: Apache license vesion 2.0 from django import template from django.db.models import Q try: from ...
3,772
1,408
#!/usr/bin/env python # Aesara tutorial # Solution to Exercise in section 'Using the GPU' # 1. Raw results import numpy as np import aesara import aesara.tensor as tt aesara.config.floatX = "float32" rng = np.random N = 400 feats = 784 D = ( rng.randn(N, feats).astype(aesara.config.floatX), rng.randint...
17,165
8,510
def translate_bbox(bbox, y_offset=0, x_offset=0): """Translate bounding boxes. This method is mainly used together with image transforms, such as padding and cropping, which translates the left top point of the image from coordinate :math:`(0, 0)` to coordinate :math:`(y, x) = (y_{offset}, x_{offse...
1,242
383
import os from configparser import ConfigParser from helper.helper_web import get_browser def before_all(context): config = ConfigParser() print((os.path.join(os.getcwd(), 'setup.cfg'))) my_file = (os.path.join(os.getcwd(), 'setup.cfg')) config.read(my_file) # Reading the browser type from the c...
504
157
from pathlib import Path from tkinter import Frame, Label from recipe_organizer.events.event import Event, EventType from recipe_organizer.events.event_observer import EventObserver from recipe_organizer.events.event_publisher import EventPublisher from recipe_organizer.gui.interfaces.widget_container import WidgetCon...
2,422
737
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Spot(AutotoolsPackage): """Spot is a C++11 library for omega-automata manipulation and mod...
917
422
k=0 while k!=1: print(k) k+=1
42
25
# ________ # / # \ / # \ / # \/ import random import textwrap import emd_mean import AdvEMDpy import emd_basis import emd_utils import numpy as np import pandas as pd import cvxpy as cvx import seaborn as sns import matplotlib.pyplot as plt from scipy.integrate import odeint from ...
74,159
34,269
import argparse import logging import torch import torch.nn.functional as F import numpy as np from torch import nn from torch.autograd import Variable from transformers import GPT2Config from transformers import GPT2LMHeadModel, GPT2Tokenizer, BertTokenizer from DataLoader import * from Model import BERTGen from utils...
8,165
2,546
# Copyright 2019 Atalaya Tech, 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 agreed to in writing, ...
9,901
2,969
""" Revision ID: 0158_remove_rate_limit_default Revises: 0157_add_rate_limit_to_service Create Date: 2018-01-09 14:33:08.313893 """ import sqlalchemy as sa from alembic import op revision = "0158_remove_rate_limit_default" down_revision = "0157_add_rate_limit_to_service" def upgrade(): op.execute("ALTER TABLE ...
615
236
import os import errno from datetime import datetime print("Generating A New Post\n") post_name = input('Input Post Name: ') date_time = datetime.now() date_time_dir = date_time.strftime("%Y-%m-%d") date_time_post = date_time.strftime("%Y-%m-%d %H:%M:%S") p_name = post_name.replace(" ","-") p_name = p_name.replace(...
1,267
509
#!/usr/bin/env python # encoding: utf-8 -*- """ This module contains unit tests of the rmgpy.reaction module. """ import numpy import unittest from external.wip import work_in_progress from rmgpy.species import Species, TransitionState from rmgpy.reaction import Reaction from rmgpy.statmech.translation import Transl...
39,758
13,923
from django.conf.urls import url, include from core.routers import OptionalTrailingSlashRouter from blog import views as blogViews from snippets import views as snippetsViews from projects import views as projectsViews from tags import views as tagsViews from contents import views as contentsViews from contact import ...
888
245
""" closed-loop MILP solved to determine optimal ordering defined by ADG """ import sys import yaml import time import matplotlib.colors as mcolors import matplotlib import matplotlib.pyplot as plt import random import logging import time import networkx as nx import csv import statistics as stat import os import ...
9,402
3,042
import pytest from unittest.mock import patch import rfidsecuritysvc.model.guest as model from rfidsecuritysvc.model.color import Color from rfidsecuritysvc.model.guest import Guest from rfidsecuritysvc.model.sound import Sound from rfidsecuritysvc.exception import SoundNotFoundError def test_Guest(assert_model, def...
4,558
1,612
# encoding: utf-8 import os import roms def console_roms_directory(configuration, console): """ If the user has specified a custom ROMs directory in consoles.txt then return that. Otherwise, append the shortname of the console to the default ROMs directory given by config.txt. """ if console.custom_ro...
1,119
322
#! -*- coding:utf-8 -*- # CLUE评测 # c3多项选择阅读理解 # 思路:每个选项分别与问题、篇章拼接后打分排序 import json import numpy as np from snippets import * from bert4keras.backend import keras from bert4keras.snippets import sequence_padding, DataGenerator from bert4keras.snippets import open from bert4keras.snippets import truncate_sequences from ...
5,527
2,112
# Copyright 2018 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. from benchmarks import smoothness,thread_times import page_sets from telemetry import benchmark # pylint: disable=protected-access def CustomizeBrowserOptio...
1,590
501
import itertools as it from toolz.compatibility import range, map, iteritems def hashable(x): try: hash(x) return True except TypeError: return False def transitive_get(key, d): """ Transitive dict.get >>> from logpy.util import transitive_get >>> d = {1: 2, 2: 3, 3: 4} ...
3,481
1,217
import rinobot_plugin as bot import numpy as np def main(): # lets get our parameters and data filepath = bot.filepath() data = bot.loadfile(filepath) # now comes the custom plugin logic shift = bot.get_arg('shift', type=float, required=True) index = bot.index_from_args(data) data[index] =...
545
184
from gluon.contrib.memcache.memcache import Client import time """ examle of usage: cache.memcache=MemcacheClient(request,[127.0.0.1:11211],debug=true) """ import cPickle as pickle import thread locker = thread.allocate_lock() def MemcacheClient(*a, **b): locker.acquire() if not hasattr(MemcacheClient, '__...
1,912
631
class Some_enum(Enum): some_literal = "some_literal" class Something(Some_enum): pass class Reference: pass __book_url__ = "dummy" __book_version__ = "dummy" associate_ref_with(Reference)
206
78
#!/usr/bin/env python # encoding: utf-8 import numbers import os import re import sys from itertools import chain import numpy as np import scipy.sparse as sp import six import pickle from .model import get_convo_nn2 from .stop_words import THAI_STOP_WORDS from .utils import CHAR_TYPES_MAP, CHARS_MAP, create_feature_...
11,135
3,573
# Copyright 2021 Yan Yan # # 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, soft...
4,824
1,602
#!/usr/bin/env python # # Copyright (c) 2013 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. """Runs Android's lint tool.""" import optparse import os import sys from xml.dom import minidom from util import build_utils ...
5,346
1,709
# Copyright 2020 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, ...
9,424
3,168
from torch import nn def get_fc_discriminator(num_classes, ndf=64): return nn.Sequential( nn.Conv2d(num_classes, ndf, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf, ndf * 2, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negat...
2,865
1,410
# -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) """Module checking Spyder runtime dependencies""" import os # Local imports from spyder.utils import programs class Dependency(object): """Sp...
3,652
1,086
import os from setuptools import find_packages, setup # Load version number __version__ = None src_dir = os.path.abspath(os.path.dirname(__file__)) version_file = os.path.join(src_dir, 'chemprop', '_version.py') with open(version_file, encoding='utf-8') as fd: exec(fd.read()) # Load README with ope...
2,947
999
# Copyright 1999-2020 Alibaba Group Holding Ltd. # # 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 a...
2,335
749
""" Main module. Implement the central Checker class. Also, it models the Bindings and Scopes. """ import __future__ import doctest import os import sys PY2 = sys.version_info < (3, 0) PY32 = sys.version_info < (3, 3) # Python 2.5 to 3.2 PY33 = sys.version_info < (3, 4) # Python 2.5 to 3.3 PY34 = ...
50,221
14,545
# Project Name: Auto Screenshot # Description: Take screenshot of screen when any change take place. # Author: Mani (Infinyte7) # Date: 26-10-2020 # License: MIT from pyscreenshot import grab from PIL import ImageChops import os import time import subprocess, sys from datetime import datetime import tkinter as tk fr...
3,349
1,093
# -*- coding: utf-8 -*- # 版权所有 2019 深圳米筐科技有限公司(下称“米筐科技”) # # 除非遵守当前许可,否则不得使用本软件。 # # * 非商业用途(非商业用途指个人出于非商业目的使用本软件,或者高校、研究所等非营利机构出于教育、科研等目的使用本软件): # 遵守 Apache License 2.0(下称“Apache 2.0 许可”),您可以在以下位置获得 Apache 2.0 许可的副本:http://www.apache.org/licenses/LICENSE-2.0。 # 除非法律有要求或以书面形式达成协议,否则本软件分发时需保持当前许可“原样”...
2,749
1,442
# -*- coding: utf-8 -*- ''' Oracle DataBase connection module :mainteiner: Vladimir Bormotov <bormotov@gmail.com> :maturity: new :depends: cx_Oracle :platform: all :configuration: module provide connections for multiple Oracle DB instances. **OS Environment** .. code-block:: text ORACLE_HOME: pa...
5,517
1,903
import base64 import operator import struct import time import pytest import six import consul import consul.std Check = consul.Check class TestHTTPClient(object): def test_uri(self): http = consul.std.HTTPClient() assert http.uri('/v1/kv') == 'http://127.0.0.1:8500/v1/kv' assert http....
32,785
11,092