text
string
size
int64
token_count
int64
# Generated by Django 2.2.4 on 2020-02-08 02:22 from django.db import migrations def move_batch_fks(apps, schema_editor): Batch = apps.get_model("petition", "Batch") CIPRSRecord = apps.get_model("petition", "CIPRSRecord") for batch in Batch.objects.all(): print(f"Adding batch {batch.pk} to {batch...
759
271
__version__ = "2.9.10"
23
14
import maya.cmds as mc import os import logging logging.basicConfig() log = logging.getLogger(__name__) log.setLevel(logging.INFO) def isNewScene(): """ Method used to check if this is an untitled scene file. :rtype: bool """ return len(mc.file(query=True, sceneName=True)) == 0 def isSaveRequ...
3,442
1,121
__version__ = "0.2.0" from diffir.weight import Weight from diffir.weight.custom import CustomWeight from diffir.weight.unsupervised import ExactMatchWeight from diffir.measure import Measure from diffir.measure.qrels import QrelMeasure from diffir.measure.unsupervised import TopkMeasure from diffir.weight.weights_bui...
346
103
#!/usr/bin/env python # -*- coding: utf-8 -*- ################################################################################ # # qooxdoo - the new era of web development # # http://qooxdoo.org # # Copyright: # 2006-2010 1&1 Internet AG, Germany, http://www.1und1.de # # License: # MIT: https://opensource.org...
34,160
8,747
import sys import numpy as np import torch from monai import transforms, data from ..data import DataModule, ReadImaged, Renamed, Inferer ################################### # Transform ################################### def wmh_train_transform( spacing=(1.0, 1.0, 1.0), spatial_size=(128, 128, 128), num_patc...
6,486
2,102
import imghdr import smtplib import os from email.message import EmailMessage EMAIL_ADDRESS = os.environ.get("GMAIL_ADDRESS") EMAIL_PASSWORD = os.environ.get("GMAIL_APP_PASS") pdfs = ["/home/shihab4t/Downloads/Profile.pdf"] with smtplib.SMTP_SSL("smtp.gmail.com", 465) as smtp: smtp.login(EMAIL_ADDRESS, EMAIL_P...
890
323
from .project import Project # noqa: F401
43
16
import selenium from selenium import webdriver try: browser = webdriver.Firefox() browser.get('mikekus.com') except KeyboardInterrupt: browser.quit()
163
50
"""Base class for rotor tests.""" import unittest from enigma.rotor.reflector import Reflector from enigma.rotor.rotor import Rotor class RotorTest(unittest.TestCase): """Provides tools testing rotors.""" def get_rotor( self, wiring="EKMFLGDQVZNTOWYHXUSPAIBRCJ", ring_setting=1, ...
740
251
# Created by Egor Kostan. # GitHub: https://github.com/ikostan # LinkedIn: https://www.linkedin.com/in/egor-kostan/ # FUNDAMENTALS ARRAYS NUMBERS BASIC LANGUAGE FEATURES import unittest import allure from utils.log_func import print_log from kyu_8.check_the_exam.check_exam import check_exam @allure.epic('8 kyu')...
2,186
745
import os.path from twisted.internet import defer import pysoup.utils class Virtualenv(object): def __init__(self, display_pip, path): self._display_pipe = display_pip self._path = path @property def path(self): return self._path @property def venv_path(self): ...
1,193
379
from yggdrasil.metaschema.datatypes import MetaschemaTypeError from yggdrasil.metaschema.datatypes.MetaschemaType import MetaschemaType from yggdrasil.metaschema.datatypes.JSONObjectMetaschemaType import ( JSONObjectMetaschemaType) from yggdrasil.metaschema.properties.ArgsMetaschemaProperty import ( ArgsMetasch...
2,791
758
# Generated by Django 2.1.3 on 2018-12-02 17:52 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('battleships', '0003_auto_20181202_1832'), ] operations = [ migrations.RenameField( model_name='coordinate', old_name='ship',...
368
138
""" Functions for storing and retrieving cache metadata from text files. Each Cache asset is a path: /path/filename There are four metadata files in the cache for each: /path/.stagecache.filename/size The size of the asset in bytes /path/.stagecache.filename/cache_lock The requested end time of the cache...
11,168
3,201
import numpy as np import numpy.random as npr import cv2 from core.config import cfg import utils.blob as blob_utils def get_minibatch_blob_names(is_training=True): """Return blob names in the order in which they are read by the data loader. """ # data blob: holds a batch of N images, each with 3 channel...
3,858
1,405
import abc import os import pandas as pd import numpy as np from EoraReader import EoraReader class PrimaryInputs(EoraReader): def __init__(self, file_path): super().__init__(file_path) self.df = None def get_dataset(self, extended = False): """ Returns a pandas dataframe conta...
1,288
374
import logging from toto.invocation import * @requires('client_error', 'client_type') def invoke(handler, parameters): '''A convenince method for writing browser errors to Toto's server log. It works with the ``registerErrorHandler()`` method in ``toto.js``. The "client_error" parameter should be set to the str...
695
208
# Copyright 2021 TUNiB 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, softw...
1,945
587
import pygame class Checkerbox(pygame.sprite.Sprite): def __init__(self, size, color, coords): super().__init__() self.rect = pygame.Rect(coords[0], coords[1], size, size) self.color = color self.hovered = False def draw(self, screen): pygame.draw.rect(screen, self.co...
503
166
# Copyright (c) 2020, CNRS # Authors: Pierre Fernbach <pfernbac@laas.fr> import unittest import subprocess import time from mlp import LocoPlanner, Config from utils import check_motion from hpp.corbaserver.rbprm.utils import ServerManager class TestTalosWalkSl1mTopt(unittest.TestCase): def test_talos_walk_sl1m_to...
1,319
484
import os import logging ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) DEBUG = True LOG = logging.getLogger() NAME = 'Sample Server' VERSION = 'v1.0' SERVER = 'example.SampleServer' ENABLE_CORS = True
212
77
# coding=utf-8 # Copyright 2021 The Uncertainty Baselines 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 ap...
9,567
3,153
''' ============================================================================== Author: Mahnoor Anjum Description: Digital Multiplexing Techniques: 1- Frequency Division Multiplexing Contact: manomaq@gmail.com ===========================================================...
1,098
431
'''OpenGL extension ATI.text_fragment_shader This module customises the behaviour of the OpenGL.raw.GL.ATI.text_fragment_shader to provide a more Python-friendly API Overview (from the spec) The ATI_fragment_shader extension exposes a powerful fragment processing model that provides a very general means of expr...
3,880
1,016
import numpy as np import math from scipy.ndimage import convolve from tqdm import tqdm def hog3d(vox_volume, cell_size, block_size, theta_histogram_bins, phi_histogram_bins, step_size=None): """ Inputs vox_volume : a [x x y x z] numpy array defining voxels with values in the range 0-1 cell_size : s...
7,311
2,888
from django.urls import include, path from datatrans.views import example urlpatterns = [ path(r'^datatrans/', include('datatrans.urls')), path(r'^example/register-credit-card$', example.register_credit_card, name='example_register_credit_card'), path(r'^example/pay$', example.pay, name='example_pay'), ]
320
109
import attr import types from typing import Union from enum import Enum import numpy as np from scipy.optimize import differential_evolution import pygmo as pg class OptimizationMethod(Enum): """ Available optimization solvers. """ SCIPY_DE = 1 PYGMO_DE1220 = 2 @attr.s(auto_attribs=True) class S...
11,160
3,425
# MIT License # # Copyright (c) 2021 TrigonDev # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, pu...
1,461
494
__title__ = 'cisco_support' __description__ = 'Cisco Support APIs' __version__ = '0.1.0' __author__ = 'Dennis Roth' __license__ = 'MIT'
137
56
#!/usr/bin/env python3 # trunc8 did this import numpy as np class Searchers: def __init__(self, g, N=100, M=2, initial_positions=np.array([90,58]), target_initial_position=45): ''' g: Graph of environment N: Number of vertices M: Number of ...
747
237
from fastapi import FastAPI from vogue.api.api_v1.endpoints import ( insert_documents, home, common_trends, sequencing, genootype, reagent_labels, prepps, bioinfo_covid, bioinfo_micro, bioinfo_mip, update, ) from vogue.settings import static_files app = FastAPI() app.mount...
1,015
363
import torch.nn as nn import torch.nn.functional as F from dgcnn.pytorch.model import DGCNN as DGCNN_original from all_utils import DATASET_NUM_CLASS class DGCNN(nn.Module): def __init__(self, task, dataset): super().__init__() self.task = task self.dataset = dataset if task == "...
1,090
343
from collections import deque N, K = map(int, input().split()) T = [int(input()) for _ in range(N)] ans_dq = deque([0, 0, 0]) for i, t in enumerate(T): ans_dq.append(t) ans_dq.popleft() if sum(ans_dq) < K and i > 1: print(i + 1) break else: print(-1)
283
122
velocidade = float(input("Digite a sua velocidade em Km/h: ")) if velocidade > 80: amais = velocidade - 80 amais = amais*7 print("Você foi multado, devera pagar uma multa de: R${:.2f}".format(amais)) print("FIM, não se mate")
238
95
import numpy as np import gym import argparse from keras.models import Sequential from keras.layers import Dense, Activation, Flatten, Convolution2D from keras.optimizers import Adam from rl.agents.dqn import DQNAgent from rl.policy import LinearAnnealedPolicy, EpsGreedyQPolicy from rl.memory import SequentialMemory ...
3,746
1,256
#!/usr/bin/env python3 import spacy from spacy import displacy from pathlib import Path nlp = spacy.load("en_core_web_md") doc = nlp("I'm a butterfly.") svg = displacy.render(doc, style="dep", jupyter=False) filename = "butterfly.svg" output_path = Path(filename) output_path.open("w", encoding="utf-8").write(svg)
318
121
import cv2 import tensorflow as tf from tensorflow import keras import matplotlib.pyplot as plt import numpy as np model = "./AI_Mask_Detector/res10_300x300_ssd_iter_140000_fp16.caffemodel" config = "./AI_Mask_Detector/deploy.prototxt" # model = './AI_Mask_Detector/opencv_face_detector_uint8.pb' # config = './AI_Mask_...
3,485
1,282
import sys import logging import numpy as np import tensorflow as tf from tensorflow.keras import backend as K from capsulelayers import CapsuleLayer from capsulelayers import MatMulLayer from loupe_keras import NetVLAD sys.setrecursionlimit(2**20) np.random.seed(2**10) # Custom layers # Note - Usage of Lambda layer...
55,499
20,951
import remi.gui as gui import os import logging log = logging.getLogger('remi.gui.remijquerytools.overlay') def get_res_path(): """ return addtion to 'res' path for items needed by this lib """ res_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'res') return res_path class Overlay(gui....
2,537
716
elements = [int(x) for x in input().split(', ')] even_numbers = [x for x in elements if x % 2 == 0] odd_numbers = [x for x in elements if x % 2 != 0] positive = [x for x in elements if x >= 0] negative = [x for x in elements if x < 0] print(f"Positive: {', '.join(str(x) for x in positive)}") print(f"Negative: {', '.j...
468
189
import numbers from typing import Iterable, Tuple, Union import numpy as np ######################################################################################## # API Types ######################################################################################## ShapeType = Tuple[int, ...] RandomStateType = Unio...
2,048
529
"""Django Views for the socialprofile module""" import json import logging import sweetify from django.conf import settings from django.contrib import messages from django.contrib.auth import REDIRECT_FIELD_NAME, login from django.contrib.auth import logout as auth_logout from django.contrib.auth.decorators import log...
12,279
3,394
from fruits import validate_fruit fruits = ["banana", "lemon", "apple", "orange", "batman"] print fruits def list_fruits(fruits, byName=True): if byName: # WARNING: this won't make a copy of the list and return it. It will change the list FOREVER fruits.sort() for index, fruit in enumerate...
519
176
from unittest.mock import Mock from django.apps import apps from django.contrib import admin from django.test import RequestFactory, TestCase from djangocms_moderation.cms_config import ModerationExtension from djangocms_moderation.models import ModerationRequestTreeNode from djangocms_content_expiry.cms_config impo...
3,439
1,017
vals = { "yes" : 0, "residential" : 1, "service" : 2, "unclassified" : 3, "stream" : 4, "track" : 5, "water" : 6, "footway" : 7, "tertiary" : 8, "private" : 9, "tree" : 10, "path" : 11, "forest" : 12, "secondary" : 13, "house" : 14, "no" : 15, "asphalt" : 16, "wood" : 17, "grass" : 18, "paved" : 19, "primary" : 20, "un...
4,466
2,845
import pika import uuid import time import json class FernetRpc(object): def __init__(self): self.connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost')) self.channel = self.connection.channel() result = self.channel.queue_declare(queue='', exclusiv...
1,406
420
# services/ovpn_server/project/tests/test_ovpn_server.py import os import json import io from flask import current_app from project.tests.base import BaseTestCase class TestOvpnServer(BaseTestCase): def test_certificates(self): with self.client: pki_path = current_app.config['PKI_PATH'] ...
3,225
929
# vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) import os from threading import RLock from powerline.lib.path import realpath class StatFileWatcher(object): def __init__(self): self.watches = {} self.lock = RLock() def watch(self, path): p...
956
390
## This code is written by Davide Albanese, <albanese@fbk.eu>. ## (C) 2010 mlpy Developers. ## This program is free software: you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your op...
2,531
860
''' All cartgripper env modules built on cartrgipper implementation in https://github.com/SudeepDasari/visual_foresight ''' from abc import ABC from mujoco_py import load_model_from_path, MjSim import numpy as np from base_env import BaseEnv class BaseMujocoEnv(BaseEnv, ABC): def __init__(self, model_path, _hp):...
2,641
824
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: """Naive Logic""" ''' for i in range(len(nums)): left = nums[i+1:] for j in range(len(left)): if (nums[i]+left[j]) ==target : return i,j+i+1 ''' '''Better...
853
287
n1 = int(input('Digite um número e veja qual a sua tabuada: ')) n = 0 print('{} X {:2} = {:2}'.format(n1, 0, n1*n)) while n < 10: n += 1 print('{} X {:2} = {:2}'.format(n1, n, n1*n))
191
96
# encoding: utf-8 from web.ext.acl import when from ..templates.admin.admintemplate import page as _page from ..templates.admin.requests import requeststemplate, requestrow from ..templates.requests import requestrow as rr from ..send_update import send_update import cinje @when(when.matches(True, 'session.authentica...
2,587
705
class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ return binarySearch(nums,target,0,len(nums)-1) def binarySearch(nums, target, low, high): if (low > high): return -1 ...
895
264
def write_file(filess, T): f = open(filess, "w") for o in T: f.write("[\n") for l in o: f.write(str(l)+"\n") f.write("]\n") f.close() def save_hidden_weight(nb_hidden, hiddenw): for i in range(nb_hidden): write_file("save/base_nn_hid_" + str(i+1) + "w.nn", hiddenw[i]) def load_hiddenw(filess, hi...
2,560
1,213
from unittest import TestCase from day10 import KnotHasher class TestKnotHasher(TestCase): def test_calc(self): sut = KnotHasher(5, [3, 4, 1, 5]) self.assertEqual(12, sut.calc()) def test_hash1(self): sut = KnotHasher(256, '') self.assertEqual('a2582a3a0e66e6e86e3812dcb672a272...
755
372
import constants, helpers, os temp_msg = None whole_msg = b'' file_path = None helpers.sock.bind(constants.IP_PORT) print "Server Ready" # recieve while temp_msg != constants.EOF: datagram = helpers.sock.recvfrom(constants.BUFFER_SIZE) temp_msg = datagram[0] if file_path is None: print("Receiv...
602
225
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
3,697
1,006
#!/usr/bin/env python3 import fire import json import os import numpy as np import tensorflow as tf import model, sample, encoder def interact_model( model_name='117M', seed=None, nsamples=1000, batch_size=1, length=None, temperature=1, top_k=0, top_p=0.0 ): """ Interactively ...
4,717
1,450
import pytest @pytest.fixture(scope='module') def driver(): from selenium import webdriver options = webdriver.ChromeOptions() options.headless = True chrome = webdriver.Chrome(options=options) chrome.set_window_size(1440, 900) yield chrome chrome.close()
291
98
import saludos saludos.saludar()
33
15
# -*- coding: utf-8 -*- # @Author : LG """ 执行用时:148 ms, 在所有 Python3 提交中击败了35.57% 的用户 内存消耗:13.7 MB, 在所有 Python3 提交中击败了36.81% 的用户 解题思路: 回溯 具体实现见代码注释 """ class Solution: def splitIntoFibonacci(self, S: str) -> List[int]: def backtrack(S, current): if S == '' and len(current) > 2: # 字...
1,033
484
import re import os values = { 'uc': 'Vurple', 'lc': 'vurple', 'cl': '#116BB7', } def main(): infile = "yeti/variables.less" f = open(infile, 'r') lines = f.readlines() f.close() outfile = values['lc'] + "/variables.less" f = open(outfile, 'w') for line in lines: l...
2,771
1,061
#!/usr/bin/python3 from validData import * from command import * from readback import * import sys import time # Expected Input # 1: Row -> 0 to 9 # 2: Column -> 0 to 19 if ( isInt(sys.argv[1]) and strLengthIs(sys.argv[1],1) and isInt(sys.argv[2]) and (strLengthIs(sys.argv[2],1) or strLengthIs(sys.ar...
721
292
from getpass import getpass from colorama import init, Fore, Back, Style yes = ['Y', 'y', 'YES', 'yes', 'Yes'] class interface(object): """ Terminal CLI """ def log(self, arg, get=False): if not get: print("[*]: {} ".format(arg)) else: return "[*]: {} ".format(a...
1,834
555
from django.apps import AppConfig class EnvcontactsConfig(AppConfig): name = 'envcontacts' # def ready(self) -> None: # from envnet.registry.registry import ServiceRegistry # try: # from setup.ui_server_conf import run_config # host = run_config["HOST"]["name"] # ...
885
272
from sly import Lexer from sly import Parser import sys #-------------------------- # While Loop # Del Var # Print stmt # EQEQ, LEQ #-------------------------- #=> This version has parenthesis precedence! class BasicLexer(Lexer): tokens = { NAME, NUMBER, STRING, IF, FOR, PRINT, CREATEFILE, WRITE, EQEQ,...
8,053
2,832
import braintree from braintree.resource import Resource class ApplePayCard(Resource): """ A class representing Braintree Apple Pay card objects. """ class CardType(object): """ Contants representing the type of the credit card. Available types are: * Braintree.ApplePayCard.Am...
1,012
288
from __future__ import print_function from time import time import csv import sys import os from sklearn.feature_extraction.text import CountVectorizer import numpy as np import lda import logging logging.basicConfig(filename='lda_analyser.log', level=logging.DEBUG) entities = ['jose_mourinho', 'cristia...
4,054
1,335
from __future__ import print_function import re import datetime as dt from behav.loading import load_data_pandas import warnings import subprocess import os import sys process_fname = "/home/bird/opdat/panel_subject_behavior" box_nums = [] bird_nums = [] processes = [] with open(process_fname, "rt") as psb_file: ...
4,476
1,413
from app.models import Circuit, CircuitSchema, Provider from flask import make_response, jsonify from app import db def read_all(): """ This function responds to a request for /circuits with the complete lists of circuits :return: sorted list of circuits """ circuits = Circuit.query.al...
2,239
723
import asyncio import json import re from collections import deque from typing import Deque, Dict, List, Match, Pattern import aiohttp from .error import RateLimited headers: dict = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko" } DATA_JSON: Pattern = re.compile( r'(...
2,311
747
# Generated by Django 2.2.5 on 2019-09-24 09:11 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Category', fields=[ ...
2,522
800
from PySide2.QtGui import QVector3D, QColor from field.ColorField import ColorField from field.FloatField import FloatField from field.StringField import StringField from field.Vector3Field import Vector3Field class FieldFactory(object): def create(self, property): result = None type...
690
196
"""Some debugging functions for working with the Scrapy engine""" # used in global tests code from time import time # noqa: F401 def get_engine_status(engine): """Return a report of the current engine status""" tests = [ "time()-engine.start_time", "engine.has_capacity()", "len(engin...
1,348
458
#!/usr/bin/python3 from typing import Dict import optparse import numpy as np import rasterio from rasterio import features def main(county_pop_file, spatial_dist_file, fname_out, no_data_val=-9999): ''' county_pop_file: County level population estimates spatial_dist_file: Spatial projection of populati...
2,588
837
import os import requests import subprocess import time import yaml class PullRequestOperation(object): def __init__(self, owner, repo, local_owner): """initialize owner, repo and access_token""" self.owner = owner self.repo = repo self.local_owner = local_owner self.access...
9,557
2,918
import testtools from oslo_log import log from tempest.api.compute import base import tempest.api.compute.flavors.test_flavors as FlavorsV2Test import tempest.api.compute.flavors.test_flavors_negative as FlavorsListWithDetailsNegativeTest import tempest.api.compute.flavors.test_flavors_negative as FlavorDetailsNegativ...
1,103
360
#!/usr/bin/env python3 """ dycall.exports ~~~~~~~~~~~~~~ Contains `ExportsFrame` and `ExportsTreeView`. """ from __future__ import annotations import logging import pathlib from typing import TYPE_CHECKING import ttkbootstrap as tk from ttkbootstrap import ttk from ttkbootstrap.dialogs import Messagebox from ttkbo...
8,910
2,538
#!/usr/bin/env python """ Filter a fasta alignment according to its occupancy: filter_by_occupancy.py fasta_raw.fa fasta_trimmed.fa 0.5 """ import os import sys from helpers import fasta_to_dict def filter_by_occupancy(filename_in, filename_out, min_occupancy=0.5): """ Filter an alignment in fasta format ...
1,899
672
#!/usr/bin/env python """ xontrib-dotenv ----- Automatically reads .env file from current working directory or parentdirectories and push variables to environment. """ from setuptools import setup setup( name='xontrib-dotenv', version='0.1', description='Reads .env files into environment', long_descr...
954
304
# -*- coding: utf-8 -*- from django.conf.urls import url from tests.sample_app.views import NewsArticleDetailView urlpatterns = [ url(r'^(?P<pk>\d+)/$', NewsArticleDetailView.as_view(), name='news-article-detail'), ]
222
82
class Config(object): embedding_size = 300 n_layers = 1 hidden_size = 128 drop_prob = 0.2
105
44
import numpy as np def center_to_corner(boxes): """ Convert bounding boxes from center format (cx, cy, width, height) to corner format (xmin, ymin, xmax, ymax) Args: - boxes: numpy array of tensor containing all the boxes to be converted Returns: - A numpy array or tensor of converted bo...
624
236
import numpy as np list = [np.linspace([1,2,3], 3),\ np.array([1,2,3]),\ np.arange(3),\ np.arange(8).reshape(2,4),\ np.zeros((2,3)),\ np.zeros((2,3)).T,\ np.ones((3,1)),\ np.eye(3),\ np.full((3,3), 1),\ np.random.rand(3),\ np.random.rand(3,3),\ np.random.uniform(5,15,3),\ np.random.randn(3),\ np.random.normal(3, 2.5, ...
337
180
# coding: utf-8 # flake8: noqa from __future__ import absolute_import # import models into model package from data_explorer.models.dataset_response import DatasetResponse from data_explorer.models.facet import Facet from data_explorer.models.facet_value import FacetValue from data_explorer.models.facets_response impor...
337
98
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Command line utilities for package Seabird """ import click from seabird.exceptions import CNVError from .cnv import fCNV from .netcdf import cnv2nc @click.group() def cli(): """ Utilities for seabird files """ pass @cli.command(name='cnvdump') @click.a...
2,288
791
#!/usr/bin/env python3 #import face_recognition import cv2 import numpy as np from datetime import datetime, timedelta from buffer import Buffer from collections import deque import os from copy import copy import archive WEIGHT_EPS = 5 TIMEOUT = 5 # in seconds def poll_weight(): return 500 # with an fps we the...
1,752
556
r""" =============================================================================== pore_topology -- functions for monitoring and adjusting topology =============================================================================== """ import scipy as _sp def get_subscripts(network, shape, **kwargs): r""" Retu...
2,895
879
# Copyright (C) 2007 Samuel Abels # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distri...
9,559
2,519
#!/usr/bin/env python # -*- coding: utf-8 -*- from matplotlib import pyplot as plt from matplotlib.ticker import ScalarFormatter import pandas as pd from covsirphy.util.argument import find_args from covsirphy.visualization.vbase import VisualizeBase class BarPlot(VisualizeBase): """ Create a bar plot. ...
5,763
1,693
import os import math from pathlib import Path import clip import torch from PIL import Image import numpy as np import pandas as pd from common import common_path # Set the path to the photos # dataset_version = "lite" # Use "lite" or "full" # photos_path = Path("unsplash-dataset") / dataset_version / "photos" ph...
3,342
1,047
import numpy as np import datajoint as dj from treadmill_pipeline import project_database_prefix from ephys.utilities import ingestion, time_sync from ephys import get_schema_name schema = dj.schema(project_database_prefix + 'treadmill_pipeline') reference = dj.create_virtual_module('reference', get_schema_name('re...
4,612
1,315
from rest_framework import serializers from management.models.main import MailSetting, LdapSetting, ShopSetting, LegalSetting, Header, CacheSetting, Footer class MailSettingSerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField() class Meta: model = MailSetting fields = '__a...
1,324
369
"""Unit test optimal lineup functions.""" import unittest import copy import ff_espn_api # pylint: disable=import-error from collections import defaultdict from fantasy_coty.main import add_to_optimal class TestAddToOptimal(unittest.TestCase): """Test add_to_optimal() function.""" def setUp(self): "...
9,854
3,455
from pyspark import SparkConf, SparkContext from pyspark.sql import SparkSession, functions, types from pyspark.sql.functions import date_format from pyspark.sql.functions import year, month, dayofmonth import sys import json import argparse assert sys.version_info >= (3, 5) # make sure we have Python 3.5+ # add more ...
5,391
2,189
"""Contrastive loss functions.""" from functools import partial import tensorflow as tf LARGE_NUM = 1e9 def cont_loss2(temperature: float): func = partial(add_contrastive_loss, temperature=temperature) func.__name__ = 'cont_loss2' return func def add_supervised_loss(labels: tf.Tensor, logits: tf.Tenso...
2,177
738
import pandas as pd from suzieq.engines.pandas.engineobj import SqPandasEngine from suzieq.sqobjects import get_sqobject class TableObj(SqPandasEngine): @staticmethod def table_name(): return 'tables' def get(self, **kwargs): """Show the known tables for which we have information""" ...
3,391
964
"""Handle Data attributes.""" from datetime import datetime from ipaddress import IPv4Address, IPv6Address, ip_address as convert_ip from typing import Iterable, Union import attr @attr.s class Device: """A single device.""" mac: str = attr.ib() hostname: str = attr.ib(cmp=False) ip: Union[IPv4Addre...
3,306
1,202