text
string
size
int64
token_count
int64
"""RSS feeds for the `multilingual_news` app.""" from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.contrib.sites.shortcuts import get_current_site from django.contrib.syndication.views import Feed from django.core.urlresolvers import reverse from django.utils.transl...
5,612
1,696
""" Base settings to build other settings files upon. """ import os from pathlib import Path import environ ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent.parent # field/ APPS_DIR = ROOT_DIR / "field" env = environ.Env() READ_DOT_ENV_FILE = env.bool("DJANGO_READ_DOT_ENV_FILE", default=False) if READ_DO...
15,814
5,240
# -*- coding: utf-8 -*- import pandas as pd import pytest from bio_hansel.qc import QC from bio_hansel.subtype import Subtype from bio_hansel.subtype_stats import SubtypeCounts from bio_hansel.subtyper import absent_downstream_subtypes, sorted_subtype_ints, empty_results, \ get_missing_internal_subtypes from bio_...
5,464
1,988
import gzip import json import pickle from collections import defaultdict from pathlib import Path from zipfile import ZipFile from tqdm import tqdm from capreolus import ConfigOption, Dependency, constants from capreolus.utils.common import download_file, remove_newline from capreolus.utils.loginit import get_logger...
8,869
2,959
from click.testing import CliRunner from honeybee_radiance_folder.cli import filter_json_file import json import os def test_filter_file(): runner = CliRunner() input_file = './tests/assets/project_folder/grid_info.json' output_file = './tests/assets/temp/grid_filtered_0.json' result = runner.invoke( ...
1,161
384
import logging from django import forms from django.forms import ModelForm from django.forms.widgets import flatatt from django.utils.html import mark_safe from perma.models import Registrar, Organization, LinkUser logger = logging.getLogger(__name__) class RegistrarForm(ModelForm): class Meta: model = ...
13,648
3,923
import io import os import re import zipfile import flask import markdown import blueprints.example import blueprints.home import blueprints.presentation import blueprints.transformations class Zipper(object): def __init__(self): self._content = None self._content_handler = io.BytesIO() def append(self, file...
5,403
1,937
import os, time import numpy as np import logging import fire import torch import torch.optim as optim import torch.nn as nn from torch.utils.data import DataLoader from model import * from dataset import * def train(dataloader, model, optimizer, criterion, device): epoch_loss = 0.0 total_nu...
4,420
1,621
# -*- coding: utf-8 -*- """ download file using requests Created on Fri Jul 3 09:13:04 2015 @author: poldrack """ import requests import os from requests.packages.urllib3.util import Retry from requests.adapters import HTTPAdapter from requests import Session, exceptions # from http://stackoverflow.com/questions/16...
1,018
353
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2011 Fourth Paradigm Development, Inc. # # Licensed under the Apache License, Version 2.0 (the "Licen...
9,388
2,812
from datetime import datetime as dt from bitmap import Bitmap, PilBitmap h = 500 w = 500 image = Bitmap(w, h, alpha=True) pil_image = PilBitmap(w, h, alpha=True) color_red = 0 for i in range(h): for j in range(w): image.set_rgba_pixel(j, i, color_red, 0, 0, 150) pil_image.set_rgba_pixel(j, i, colo...
612
274
# Copyright AllSeen Alliance. All rights reserved. # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR...
9,157
2,979
# Generated by Django 2.0.2 on 2018-06-13 22:10 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ("ddcz", "0009_auto_201806...
2,187
550
# coding=utf-8 # Copyright 2020 The Learning-to-Prompt Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
8,145
3,010
from __future__ import absolute_import, division, print_function from matplotlib.backends.backend_qt5 import NavigationToolbar2QT from glue.config import viewer_tool from glue.viewers.common.tool import CheckableTool, Tool __all__ = ['MatplotlibTool', 'MatplotlibCheckableTool', 'HomeTool', 'SaveTool', 'P...
2,693
958
import matplotlib.pyplot as plt import numpy as np from ipywidgets import interactive, interactive_output, fixed, HBox, VBox import ipywidgets as widgets def true_function_old(x): x_copy = -1 * x f = 2 * x_copy * np.sin(0.8*x_copy) + 0.5 * x_copy**2 - 5 return f def sigmoid(x, L=10, k=2, x_0=20): re...
1,003
452
#!/usr/bin/env python import os import sys import jieba import numpy as np jieba.setLogLevel(60) # quiet fname = sys.argv[1] with open(fname) as f: text = f.read() tokenizer = jieba.Tokenizer() tokens = list(tokenizer.cut(text)) occurences = np.array([tokenizer.FREQ[w] for w in tokens if w in tokenizer.FREQ])...
1,036
441
from itertools import tee from typing import Dict, Iterator, List, Sequence, Tuple from brown_clustering.defaultvaluedict import DefaultValueDict Corpus = Sequence[Sequence[str]] class BigramCorpus: def __init__( self, corpus: Corpus, alpha: float = 1, start_symbo...
2,836
944
from .base import * class Input(Layer): def __init__(self, input_shape: Union[List, Tuple], **kwargs): super(Input, self).__init__(input_shape=input_shape, **kwargs) self._shape = input_shape def call(self, x: F.Tensor, *args, **kwargs) -> F.Tensor: self._data = x return self....
3,299
1,103
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2018 JiNong, Inc. # All right reserved. # """ Utility Functions를 정의함. """ import time import math import logging import logging.handlers def getdefaultlogger(): _logger = logging.getLogger('mate') _logger.setLevel(logging.DEBUG) streamHa...
2,888
1,136
# -*- encoding:utf-8 -*- # @Time : 2019/10/23 15:45 # @Author : gfjiang # @Site : # @File : __init__.py # @Software: PyCharm
144
80
import sys # for development sys.path.append('../../src') from screencastscript import ScreencastScript # noqa: E402 screencast = ScreencastScript() screencast.sleep(1) screencast.i3wm_focus_left() screencast.sleep(1) screencast.i3wm_zoom_in() screencast.sleep(1) screencast.i3wm_zoom_out() screencast.sleep(1) sc...
611
299
""" computes the mean hippocampal-cortical functional connectivity (fc) matrix, for the left hemisphere subfields """ import os import h5py import numpy as np # data dirs ddir = '../data/' conndir = '../data/tout_hippoc/' odir = '../data/tout_group/' # get HCP - S900 subject list subjlist = '../d...
1,003
474
"""A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ #To install: # py -3 setup.py sdist # pip3 install . # Always prefer setuptools over distutils from setuptools import setup, find_packages from os import path from io import...
3,907
1,235
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-10-18 14:23 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('peeldb', '0032_skill_skill_type'), ] operations = [ migrations.AlterField( ...
1,563
429
from wpc.report.issue import issue import xml.etree.cElementTree as etree from lxml import etree as letree from operator import itemgetter, attrgetter, methodcaller # TODO should this class contain info about the scan? or define a new class called report? # Version of script # Date, time of audit # Who the audit ran...
1,905
642
#!/usr/bin/python """ From Mininet 2.2.1: convert simple documentation to epydoc/pydoctor-compatible markup """ from sys import stdin, stdout, argv import os from tempfile import mkstemp from subprocess import call import re spaces = re.compile(r'\s+') singleLineExp = re.compile(r'\s+"([^"]+)"') commentStartExp = r...
1,456
511
from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy, reverse from django.shortcuts import redirect from .models import StockEntry, StockEntryLine from .forms import StockEntryForm, StockEntryLineForm, StockEn...
3,924
1,203
""" sentry.web.frontend.generic ~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from...
2,589
742
import setuptools setuptools.setup( name="synmetric", version="0.2.dev1", license='MIT', author="Harsh Soni", author_email="author@example.com", description="Metric to evaluate data quality for synthetic data.", url="https://github.com/harsh020/synthetic_metric", download_url = 'https:...
878
295
"""Submodule for NeuroKit.""" from .microstates_clean import microstates_clean from .microstates_peaks import microstates_peaks from .microstates_static import microstates_static from .microstates_dynamic import microstates_dynamic from .microstates_complexity import microstates_complexity from .microstates_segment im...
813
227
from pytest import raises from notario.validators import Hybrid from notario.exceptions import Invalid from notario.decorators import optional from notario import validate def validator(x): assert x, 'fail' class TestHybrid(object): def test_use_validator_passes(self): schema = () hybrid = ...
2,184
702
from django.urls import path, include from . import views from rest_framework import routers router = routers.SimpleRouter() router.register(r'players', views.PlayerView, basename='players') router.register(r'teams', views.TeamView, basename='teams') urlpatterns = [ path('', views.APIWelcomeView), path('', ...
346
109
# Generated by Django 2.0.2 on 2020-11-01 20:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('watch', '0013_alert'), ] operations = [ migrations.AlterField( model_name='alert', name='news', field=mo...
380
132
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import torchx.examples.apps.lightning_classy_vision.component as lightning_classy_vision from torchx.components...
612
181
import requests from sanic import Sanic from sanic.response import json from sanic_limiter import Limiter, get_remote_address from bs4 import BeautifulSoup async def ratelimit_handler(request, exception): return json({"error": f"Ratelimit exceeded {exception}."}, status=429) app = Sanic() app.error_handler.add(...
1,270
431
from os.path import join, dirname import numpy as np from .text import put_text from .. import const from ..os import makedirs from ..imprt import preset_import from ..log import get_logger logger = get_logger() def make_video( imgs, fps=24, outpath=None, method='matplotlib', dpi=96, bitrate=-1): """Wri...
8,373
2,852
# -*- coding: utf-8 -*- """Top-level package for Shipfunk.""" __author__ = """Jaana Sarajärvi""" __email__ = 'jaana.sarajarvi@vilkas.fi' __version__ = '0.1.1'
161
78
#! python3 # coding: utf-8 from vpc.nos import NetworkElement,NetworkElementEvent,event_t,EventChain class OVSEvent(NetworkElementEvent): def __init__(self,ne_id,type): super().__init__(ne_id,type) class OVS(NetworkElement): def __init__(self,channel,datapath): super().__init__() self...
638
224
import logging class BaseConfig(object): """BaseConfig provides a common interface for nested access for all Config objects in CCI.""" defaults = {} def __init__(self, config=None, keychain=None): if config is None: self.config = {} else: self.config = config ...
1,307
347
""" Created on Tue Feb 24 16:08:39 2015 @author: mukherjee """ import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn import preprocessing, metrics from sklearn.learning_curve import learning_curve # read Form data DATA_FORM_FILE = 'all-merged-cat.csv' #rawdata = pd.read_cs...
8,995
3,187
from httpcore import TimeoutException from httpcore._exceptions import ConnectError from httpx import Timeout, Client, ConnectTimeout from unittest.mock import patch from pytest import raises from googletrans import Translator def test_bind_multiple_service_urls(): service_urls = [ 'translate.google.com'...
4,140
1,424
# -*- coding: utf-8 -*- import torch import torch.nn as nn import torch.nn.functional as F import numpy as np # Func1: change density map into count map # density map: batch size * 1 * w * h def get_local_count(density_map,psize,pstride): IF_gpu = torch.cuda.is_available() # if gpu, return gpu IF_r...
3,324
1,352
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from pants.option.option_types import BoolOption from pants.option.subsystem import Subsystem class AvroSubsystem(Subsystem): options_scope = "avr...
540
171
# 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 t...
11,864
3,662
import matplotlib import pandas as pd matplotlib.rcParams['pdf.fonttype'] = 42 matplotlib.rcParams['ps.fonttype'] = 42 import matplotlib.pyplot as plt import seaborn as sns from utils.utils import mkdir_p sns.set() sns.despine() sns.set_context("paper", rc={"font.size": 18, "axes.labelsize": 18, "xtick.labelsize": 15...
3,780
1,534
import os, sys import shutil from unittest import TestCase, main from ocrd.resolver import Resolver from ocrd_models.ocrd_page import to_xml from ocrd_modelfactory import page_from_file from ocrd_utils import MIMETYPE_PAGE from ocrd_tesserocr.recognize import TesserocrRecognize from ocrd_keraslm.wrapper import KerasRa...
3,979
1,264
# Copyright 2020 DeepMind Technologies Limited. # # 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 ag...
16,415
5,158
#-*- coding: utf-8 -*- import frappe import boto3 import boto3.session import rows import json import zipfile import tempfile import sqlite3 from io import BytesIO from frappe import _ from frappe.utils import cint, flt, today, getdate, get_first_day, add_to_date try: from frappe.utils import file_manager with_file_...
5,269
2,000
# Copyright 2019 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, s...
1,983
577
# -*- coding: utf-8 -*- # pylint: disable-msg=E1101,W0612 from warnings import catch_warnings, simplefilter from pandas import Panel from pandas.util.testing import assert_panel_equal from .test_generic import Generic class TestPanel(Generic): _typ = Panel _comparator = lambda self, x, y: assert_panel_equa...
1,195
387
# calculate shortest paths between OD pairs # in the map_speed_od postgis table # update the shortest path geometry into the table import requests, json, psycopg2 # get OD pairs from DB conn_string = ( "host='localhost' dbname='' user='' password=''" ) connection = psycopg2.connect(conn_string) connection.autocommit ...
1,233
507
#-*- coding:utf-8 -*- # @Time : 2020-02-15 15:49 # @Author : Zhirui(Alex) Yang # @Function : import os def create_folder(folder_name): if not os.path.exists(folder_name): os.makedirs(folder_name) print(folder_name, 'has created!') else: print(folder_name, 'already existed!')
320
131
import ssl import socket from typing import Tuple from hyper.common.util import to_native_string from urllib.parse import urlparse from hyper import HTTP11Connection, HTTPConnection from hyper.common.bufsocket import BufferedSocket from hyper.common.exceptions import TLSUpgrade from hyper.contrib import HTTP20Adapter ...
7,842
2,075
from itertools import * import time import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) #my own variance function runs much faster than numpy or the Python 3 ported statistics module def variance(data,u): return sum([(i-u)**2 for i in data])/len(data) ##rounding the means and variances helps to col...
1,387
494
# coding: utf-8 """ paginate.py ``````````` : 分页api """ from flask import url_for def pagination(lit, page, perpage,endpoint): """ 返回当前分页的列表对象, next、last链接 {current: next_lit} """ _yu = len(lit) % perpage _chu = len(lit) // perpage if _yu == 0: last = _chu else:...
621
247
import pandas as pd from . import default import wikipedia import json from flask import jsonify import re import os import multiprocessing import requests import urllib import hashlib df = 0 wikipedia.set_lang("de") def init(): path = os.path.dirname(os.path.abspath(__file__)) + "/surveyor_hackathon_data_20171...
5,272
1,890
import json,requests def test(): url='http://localhost:5000/login' headers = {'Content-Type':'application/json'} data={ "user": "xutongxin" } req = requests.post(url, json.dumps(data), headers) result = json.loads(req.text) print(test)
246
96
from camera import board_image_processor as bip from chess.models import * import cv2 import numpy as np from media.sound import * def show_webcam(mirror=False): cam = cv2.VideoCapture(0) while True: ret_val, img = cam.read() #chess_state = process_image(img) cv2.imshow('webcam', img) ...
3,481
1,194
import numpy as np from numpy import random import glob import scipy.io.wavfile np.random.seed(4) def preprocess(periods, testCategoryNum): periodList = periods catNum = len(periodList) def createpathlist(): print("Loading file paths.") x = [] y = [] for recDirIndex in ...
2,854
878
import a as b import b.c as e b.foo(1) e.baz(1)
49
28
#!/usr/bin/python """Summary - Flask Views Used to Control/Wrap a web UI around the Add User Python Script Author: Graham Land Date: 08/12/16 Twitter: @allthingsclowd Github: https://github.com/allthingscloud Blog: https://allthingscloud.eu """ from flask import flash, render_template, session,...
10,054
2,505
from django.contrib.auth.models import AbstractUser from django.core.validators import MinLengthValidator from django.utils.translation import gettext_lazy as _ from django.db import models from . import validators class User(AbstractUser): min_length_validator = MinLengthValidator( limit_value=3, ...
867
247
''' :class:`eulxml.xmlmap.XmlObject` classes for working with ABBYY FineReadux OCR XML. Currently supports **FineReader6-schema-v1** and **FineReader8-schema-v2**. ---- ''' from eulxml import xmlmap class Base(xmlmap.XmlObject): '''Base :class:`eulxml.xmlmap.XmlObject` for ABBYY OCR XML with common namespace...
5,135
1,590
'''for c in range(1, 10): print(c) print('FIM')''' '''c = 1 while c < 10: print(c) c += 1 print('FIM')''' '''n = 1 while n != 0: #flag ou condição de parada n = int(input('Digite um valor: ')) print('FIM')''' '''r = 'S' while r == 'S': n = int(input('Digite um valor: ')) r = str(input('Quer c...
742
309
"""Issue #712""" from nbformat.v4.nbbase import new_code_cell, new_notebook from jupytext import reads, writes from jupytext.cell_to_text import three_backticks_or_more from jupytext.compare import compare, compare_notebooks from .utils import requires_myst def test_three_backticks_or_more(): assert three_backt...
2,330
898
# Generated by Django 2.1 on 2018-09-02 14:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('workshops', '0151_auto_20180902_0409'), ] operations = [ migrations.AddField( model_name='event', name='open_TTT_appli...
629
198
''' This file provides a wrapper class for Fast_AT (https://github.com/locuslab/fast_adversarial) model for CIFAR-10 dataset. ''' import sys import os import torch import torch.nn as nn import torch.nn.functional as F import tensorflow as tf from ares.model.pytorch_wrapper import pytorch_classifier_with_logits from ...
5,220
2,028
from typing import Callable, TypeVar, List T = TypeVar('T') class Registrable(object): reg_list = dict() @classmethod def register(cls, class_name: str) -> Callable: def register_inner(class_type: T) -> None: cls.reg_list[class_name] = class_type return register_inner @c...
526
176
from discord.ext.commands import command, Cog from noheavenbot.utils.constants import TEXTCHANNELS from discord import Member from noheavenbot.utils.database_tables.table_users import Users from noheavenbot.utils.validator import has_role as check_role class Test(Cog): def __init__(self, bot): self.bot =...
688
227
from mayan.apps.testing.tests.base import GenericViewTestCase from ..events import event_smart_link_edited from ..permissions import permission_smart_link_edit from .mixins import ( SmartLinkConditionViewTestMixin, SmartLinkTestMixin, SmartLinkViewTestMixin ) class SmartLinkConditionViewTestCase( SmartL...
6,174
1,925
#!/usr/bin/env python # coding: utf-8 # # Self-Driving Car Engineer Nanodegree # # # ## Project: **Finding Lane Lines on the Road** # *** # In this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of individual images, and...
19,105
6,322
from container.base import TimeBase from container.array import TimeArray, TimeDtype from container.timeseries import TimeSeries from container.timeframe import TimeFrame
170
38
"""Base utility functions, that manipulate basic data structures, etc.""" ################################################################################################### ################################################################################################### def flatten(lst): """Flatten a list of l...
558
122
from django import forms from zentral.core.probes.forms import BaseCreateProbeForm from zentral.utils.forms import validate_sha256 from .probes import (OsqueryProbe, OsqueryComplianceProbe, OsqueryDistributedQueryProbe, OsqueryFileCarveProbe, OsqueryFIMProbe) # OsqueryProbe ...
11,593
3,278
""" Class description goes here. """ """Package containing gRPC classes.""" __author__ = 'Enrico La Sala <enrico.lasala@bsc.es>' __copyright__ = '2017 Barcelona Supercomputing Center (BSC-CNS)'
197
71
""" This package contains :class:`~cms.models.offers.offer_template.OfferTemplate` """
87
31
import numpy from scipy.spatial import distance import matplotlib.pyplot as plt import math import matplotlib.ticker as mtick freqs = [20, 25, 31.5, 40, 50, 63, 80, 100, 125, 160, 200, 250, 315, 400, 500, 630, 800, 1000, 1250, 1600, 2000, 2500, 3150, 4000, 5000, 6300, 8000, 10000, 12500] def cosine_distance(a, b, we...
5,150
2,407
#!/usr/bin/python # # HC-SR04 Ultrasonic ranging sensor # import RPi.GPIO as GPIO import sys, time try: GPIO.setmode(GPIO.BCM) TRIG = 23 ECHO = 24 print "Distance measurement in progress..." GPIO.setup(TRIG, GPIO.OUT) GPIO.setup(ECHO, GPIO.IN) GPIO.output(TRIG, False) whi...
1,094
414
# # -*- coding: utf-8 -*- # Copyright 2020 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # from __future__ import absolute_import, division, print_function __metaclass__ = type """ The eos_ospfv3 config file. It is in this file where the current configuration ...
10,651
3,073
from platypush.plugins import Plugin, action class LoggerPlugin(Plugin): """ Plugin to log traces on the standard Platypush logger """ @action def trace(self, msg, *args, **kwargs): """ logger.trace wrapper """ self.logger.trace(msg, *args, **kwargs) @action ...
1,141
348
from django.test.utils import override_settings from hc.api.models import Channel from hc.test import BaseTestCase @override_settings(PD_VENDOR_KEY="foo") class AddPdConnectTestCase(BaseTestCase): def setUp(self): super().setUp() self.url = "/projects/%s/add_pdc/" % self.project.code def test...
1,632
572
import sys sys.setrecursionlimit(3000) def check(rs, cs): table[rs][cs] = 2 if (rs, cs) == (rg, cg): return True if rs > 0 and table[rs - 1][cs] == 1 and check(rs - 1, cs): return True if cs > 0 and table[rs][cs - 1] == 1 and check(rs, cs - 1): return True if rs < r - 1 and table[rs...
994
415
import json import logging from unittest import mock, TestCase from bullet_train import BulletTrain import os logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) TEST_API_URL = 'https://test.bullet-train.io/api' TEST_IDENTIFIER = 'test-identity' TEST_FEATURE = 'test-feature' class MockResponse: ...
4,329
1,445
""" This module contains entry points for command-line utilities provided by Plim package. """ import sys import os import argparse import codecs from pkg_resources import get_distribution from pkg_resources import EntryPoint from mako.template import Template from mako.lookup import TemplateLookup from .util import ...
3,105
857
#!/usr/bin/python import time import sys import os from copy import deepcopy sys.path.append(os.path.join(os.getcwd(), '..')) from alphafold.partition import DynamicProgrammingData as DP def getval( DP, idx ): return DP.X[ idx ][ idx ] x = [[]]*500 for i in range( 500 ): x[i] = [0.0]*500 dx = deepcopy( x ) xcontr...
2,568
1,373
#!/usr/bin/env python3 # -*-coding:Latin-1 -* import time from Definitions import * #from ev3dev2.motor import OUTPUT_B,LargeMotor from ev3dev2.sensor import * from AddSensors import AngleSensor from ev3dev2.sensor.lego import TouchSensor import Trace trace = Trace.Trace() i=0 toucher = TouchSensor(INPUT_3) EncoderS...
688
289
class CircularQueue: """ A circlular queue: a first-in-first-out data structure with a fixed buffer size. """ def __init__(self, size): if type(size) is not int: raise TypeError("Queue size must be a postive integer.") if size <= 0: raise ValueError("Queue size m...
1,912
544
def load_model(model_path, device_type='cuda'): import torch from viclassifier.utils import dev_opt device = dev_opt.usingDevice(device_type) model = torch.load(model_path, map_location=device) model.to(device) # 测试时不启用 BatchNormalization 和 Dropout model.eval() return model def predic...
2,697
1,166
# See LICENSE for licensing information. # # Copyright (c) 2016-2019 Regents of the University of California and The Board # of Regents for the Oklahoma Agricultural and Mechanical College # (acting for and on behalf of Oklahoma State University) # All rights reserved. # #!/usr/bin/env python3 "Run a regresion test the...
1,675
519
# -*- coding: utf-8 -*- """ Created on Sat May 21 17:05:48 2022 @author: Guido Meijer """ import numpy as np import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score, balanced_accuracy_score, confusion_matrix from ibllib.atlas import BrainRegions from joblib im...
3,021
1,218
# Vinicius Ribeiro # Nmec 82773 # Make sure to run pip3 install -r requirements.txt and load the .dump at Neo4j # https://neo4j.com/docs/operations-manual/current/tools/dump-load/ # Dataset: https://neo4j.com/graphgist/beer-amp-breweries-graphgist#_create_nodes_and_relationships import sys from neo4j import GraphData...
3,923
1,320
#!/usr/bin/env python import pytest from pyxenon_snippets import directory_listing_recursive def test_directory_listing_recursive(): directory_listing_recursive.run_example()
184
62
import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines sys.setrecursionlimit(10 ** 7) from itertools import product n, m = map(int, readline().split()) inf = float('inf') dp = [inf] * (2 ** n) dp[0] = 0 for _ in range(m): s, c = readline().rstrip().deco...
764
296
# -*- coding: utf-8 -*- # 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...
55,250
15,303
import datetime t=datetime.datetime.now() #date format weekday=t.strftime("%a") # %A for abbr day=t.strftime("%d") month=t.strftime("%b") #%B for abbr month_num=t.strftime("%m") year=t.strftime("%Y") date=t.strftime("%Y-%m-%d") print(date) #time format hour_12=t.strftime("%I") hour_24=t.strftime("%H") minutes=t....
781
363
password="pbkdf2(1000,20,sha512)$8a062c206755a51e$df13c5122a621a9de3a64d39f26460f175076ca0"
92
77
import os from TheKinozal import settings from storages.backends.s3boto3 import S3Boto3Storage from helpers.random_string import generate_random_string from helpers.chunked_upload import ChunkedS3VideoUploader class AsyncS3VideoStorage(S3Boto3Storage): def _save(self, name, content): filename, ext = os.pat...
562
182
import struct import numpy as np import pandas as pd df_train = pd.read_csv('../data/train_data.csv') df_valid = pd.read_csv('../data/valid_data.csv') df_test = pd.read_csv('../data/test_data.csv') with open('result.dat', 'rb') as f: N, = struct.unpack('i', f.read(4)) no_dims, = struct.unpack('i', f.read(4)) ...
1,098
462
from django.conf.urls.defaults import patterns, url, include # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns( '', (r'^log/', include('requestlog.urls')), (r'^admin/', include(admin.site.urls)), # Pass anything that does...
623
203