text
string
size
int64
token_count
int64
"""Wrappers for the ophyd devices.""" from ophyd import Device, Signal from ophyd import Kind from ophyd.device import Component as Cpt class CalibrationData(Device): """A device to hold pyFAI calibration data.""" dist = Cpt(Signal, value=1., kind=Kind.config) poni1 = Cpt(Signal, value=0., kind=Kind.confi...
746
279
import numpy as np import pytest from sklearn.dummy import DummyRegressor from sklearn.model_selection import GridSearchCV from sklearn.pipeline import Pipeline from hcrystalball.metrics import get_scorer from hcrystalball.model_selection import FinerTimeSplit from hcrystalball.model_selection import get_best_not_fail...
3,195
1,037
""" Parser generator utility. This script can generate a python script from a grammar description. Invoke the script on a grammar specification file: .. code:: $ ppci-yacc test.x -o test_parser.py And use the generated parser by deriving a user class: .. code:: import test_parser class MyParser(test...
1,227
387
# Movie Related Information from imdb.parser.character.search_character_id import search_character_id from imdb.parser.company.search_company_id import search_company_id from imdb.parser.event.search_event_id import search_event_id from imdb.parser.movie.company import company from imdb.parser.movie.critic_reviews impo...
3,434
1,091
# Generated by Django 2.1.4 on 2019-01-23 12:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('profiles', '0021_auto_20190122_1723'), ] operations = [ migrations.AlterField( model_name='userprofile', name='bio',...
402
148
from squidpy.instrument import Instrument import visa class SR830(Instrument): ''' Instrument driver for SR830 ''' def __init__(self, gpib_address='', name='SR830'): self._units = {'amplitude': 'V', 'frequency': 'Hz'} self._visa_handle = visa.ResourceManager().open_resource(gpib_address...
2,837
1,088
import os from logging.config import dictConfig from typing import Optional from flask import render_template, request, send_from_directory from flask_babel import get_locale, lazy_gettext as _ from werkzeug.utils import ImportStringError from .auth import auth_bp from .comp import comp_bp from .ext import babel, csr...
3,602
1,129
# -*- coding: utf-8 -*- ############################################################################## ## ## This file is part of Taurus ## ## http://taurus-scada.org ## ## Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain ## ## Taurus is free software: you can redistribute it and/or modify ## it under the te...
3,695
1,171
import os, pickle import os.path as osp import numpy as np import cv2 import scipy.ndimage as nd import init_path from lib.dataset.get_dataset import get_dataset from lib.network.sgan import SGAN import torch from torch.utils.data import DataLoader import argparse from ipdb import set_trace import matplotlib.pyplot as...
7,762
2,857
from random import seed, random from math import sqrt, log, cos, pi, ceil import time import json from . import behavior from ..app_logging import AppLogging MAX_KEY = "max" MIN_KEY = "min" class Compute(behavior.Behavior): def __init__(self, value): super().__init__("COMPUTE", value) def execute(self): ...
2,902
954
# Copyright 2021 Huawei Technologies Co., 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 agreed to...
2,128
761
import os import shutil from shapely.geometry import Polygon from .. import osm_create_maps from .. import util TEST_FP = os.path.dirname(os.path.abspath(__file__)) def test_get_width(): assert osm_create_maps.get_width('15.2') == 15 assert osm_create_maps.get_width('') == 0 assert osm_create_maps.get_wi...
2,577
929
import unittest import numpy as np import tensorflow as tf from megnet.losses import mean_squared_error_with_scale class TestLosses(unittest.TestCase): def test_mse(self): x = np.array([0.1, 0.2, 0.3]) y = np.array([0.05, 0.15, 0.25]) loss = mean_squared_error_with_scale(x, y, scale=100)...
444
183
'''#The Forbidden module --- The idea is simple; 1. Take a python data structure ( only dicts and lists for now ) and then return a serialized text format called *forbidden*. 2. Take an already serialized *forbidden* format and return the appropriate python data structure. --- Examples: --- #### 1.List & Tuples | Pyt...
4,264
1,501
# 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
8,276
2,615
import datetime import requests import socket import random import sys import time def now(): a=datetime.fromtimestamp(time.time()) return a.strftime("%H:%M:%S %Y-%m-%d") def getmyip(): a=requests.get('http://checkip.dyndns.org') a=a.content b=a[76:89] return b class node: def __init__...
1,147
398
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 1999-2017 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/LICENS...
23,040
6,760
# SPDX-License-Identifier: MIT # Copyright (C) 2018-present iced project and contributors # ⚠️This file was generated by GENERATOR!🦹‍♂️ # pylint: disable=invalid-name # pylint: disable=line-too-long # pylint: disable=too-many-lines """ Mnemonic condition code selector (eg. ``JG`` / ``JNLE``) """ import typing if t...
525
246
# -*- coding: utf-8 -*- # FOGLAMP_BEGIN # See: http://foglamp.readthedocs.io/ # FOGLAMP_END """HTTP Listener handler for sensor readings""" import asyncio import copy import sys from aiohttp import web from foglamp.common import logger from foglamp.common.web import middleware from foglamp.plugins.common import uti...
7,936
2,436
""" This script provides an exmaple to wrap UER-py for classification inference (cross validation). """ import sys import os import argparse import torch import torch.nn as nn import numpy as np uer_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) sys.path.append(uer_dir) from uer.utils.vocab im...
4,924
1,462
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'D:\RAZNOE\prgrming\horsy\Source\client\uis\horsy_package.ui' # # Created by: PyQt5 UI code generator 5.15.6 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know wha...
6,491
2,500
from __future__ import absolute_import try: import pandas as pd import pandas._testing as tm import_failed = False except ImportError: import_failed = True import unittest, os import warnings import string, random, copy import numpy as np from numpy.testing import assert_array_equal, assert_array_alm...
31,084
10,593
import pytest from lib import flashing_neighbours, part1, part2 def test_part1(): assert part1(data) == 1656 def test_part2(): assert part2(data) == 195 @pytest.mark.parametrize("steps", range(1, 3)) def test_part1_small(steps): assert part1(small, steps=1) == 9 @pytest.mark.parametrize(("grid", "ex...
871
459
import pandas as pd import numpy as np from sklearn import ensemble, calibration, metrics, cross_validation from sklearn import feature_extraction, preprocessing import xgboost as xgb import keras.models as kermod import keras.layers.core as kerlay import keras.layers.advanced_activations as keradv import keras.layers....
7,728
2,747
from .aqualog import Aqualog from .fluorolog import Fluorolog name = "Horiba" instruments = [Aqualog, Fluorolog]
114
45
import youtube_dl class Download2Mp3: def __init__(self, CallableHook=None): self.hook = CallableHook self.notDownloaded = [] self.setupDownloadParam() # Public functions def downloadMusicFile(self, url): if type(url) is not str: raise TypeError("url argument i...
1,432
437
if __name__ == "__main__": """ Pobierz podstawe i wysokosc trojkata i wypisz pole. """ print("podaj podstawe i wysokosc trojkata:") a = int(input()) h = int(input()) print( "pole trojkata o podstawie ", a, " i wysokosci ", h, " jest rowne ", a * h / 2 ) """ Pobierz dlu...
529
212
#!/usr/bin/env python # encoding: utf-8 """ models.py Created by Darcy Liu on 2012-03-03. Copyright (c) 2012 Close To U. All rights reserved. """ from django.db import models from django.contrib.auth.models import User # class Message(models.Model): # key = models.AutoField(primary_key=True) # title = models...
803
267
""" Helper functions for model training, loading, testing etc """ import pickle import tqdm import torch import numpy as np def train(t_model, optimizer, loss_function, train_dataset, validation_dataset): epoch = 0 while 1: epoch += 1 train_loss = 0.0 train_accu = 0.0 ...
2,772
973
#!/usr/bin/python import RPi.GPIO as GPIO from picamera import PiCamera import time import datetime PIN = 12 GPIO.setmode(GPIO.BCM) GPIO.setup(PIN, GPIO.IN) camera = PiCamera() camera.rotation = 180 camera.resolution = (1024, 576) #camera.start_preview() #sleep(20) #camera.stop_preview() while True: time.s...
790
317
#!/usr/bin/env python import rospy import threading from ca_msgs.msg import Bumper from geometry_msgs.msg import Twist, Vector3 class StateMachine(object): def __init__(self): self.pub = rospy.Publisher("/cmd_vel", Twist, queue_size=10) self.goal_queue = [] def rotate(self, ang_vel): self.move(0., an...
2,689
1,026
class Solution: def divisorGame(self, N: int) -> bool: return True if N % 2 == 0 else False
103
34
# # 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...
915
257
import os path = './converted/' for filename in os.listdir(path): newFilename = filename.lower().replace(' ', '-').replace('’', '') os.rename(path + filename, path + newFilename.lower()) then = os.listdir(path) print(then)
235
80
from django.conf import settings from django.contrib.auth.models import User from django.urls import reverse from rest_framework.test import APITestCase class BaseAPITest(APITestCase): def setUp(self, password=None) -> None: self.user = User(username="John Smith", email="john@example.com") self.us...
2,792
811
#!/usr/bin/env python """Exercises using Netmiko""" from __future__ import print_function from getpass import getpass from netmiko import ConnectHandler #def save_file(filename, show_run): # """Save the show run to a file""" # with open(filename, "w") as f: # f.write(show_run) def main(): """Exerci...
948
333
"""Core pytorch operations regarding optimization (optimize, schedule) are placed in general tests.""" import pytest import torch import torchtraining.pytorch as P def test_backward(): backward = P.Backward() x = torch.randn(10, requires_grad=True) y = x ** 2 backward(y.sum()) assert x.grad is not...
326
107
import sys from pathlib import Path # -------- START of inconvenient addon block -------- # This block is not necessary if you have installed your package # using e.g. pip install -e (requires setup.py) # or have a symbolic link in your sitepackages (my preferend way) sys.path.append( str(Path(__file__).parent.pare...
1,464
536
import mock from twisted.trial.unittest import TestCase from treq._utils import default_reactor, default_pool, set_global_pool class DefaultReactorTests(TestCase): def test_passes_reactor(self): mock_reactor = mock.Mock() self.assertEqual(default_reactor(mock_reactor), mock_reactor) def te...
2,092
629
# -*- coding: utf-8 -*- """ pygments.lexers.solidity ~~~~~~~~~~~~~~~~~~~~~~~~ Lexer for the Solidity language. :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.lexer import ( RegexLexer, bygroups, c...
12,792
4,070
logo = """ _____________________ | _________________ | | | Pythonista 0. | | .----------------. .----------------. .----------------. .----------------. | |_________________| | | .--------------. || .--------------. || .--------------. || .--------------. | | ___ ___ ___ ___ | | | ______ | || | ...
2,305
828
""" Emoji extras for Material. Override the indexes with an extended version that includes short names for Material icons, FontAwesome, etc. """ import os import glob import copy import codecs import inspect import material import pymdownx from pymdownx.emoji import TWEMOJI_SVG_CDN, add_attriubtes import xml.etree.Ele...
2,863
932
fd = open('f',"r") buffer = fd.read(2) print("first 2 chars in f:",buffer) fd.close()
86
40
# -*- coding: UTF-8 -*- import config import gevent import availability.check from persistence import persister import time def crawl_worker(queue_verification, queue_persistence): """ 爬取下来的代理检测可用性的进程 :param queue_verification: 待验证代理队列 :param queue_persistence: 已验证待保存代理队列 :return: """ whil...
1,388
502
import unittest import tests.fixtures.heuristics_fixtures as fixtures from timeeval.heuristics import DatasetIdHeuristic class TestDatasetIdHeuristic(unittest.TestCase): def test_heuristic(self): heuristic = DatasetIdHeuristic() value = heuristic(fixtures.algorithm, fixtures.dataset, fixtures.rea...
401
132
""" Imported model and adapter won't be grokked: >>> import grokcore.component as grok >>> grok.testing.grok(__name__) >>> from grokcore.component.tests.adapter.adapter import IHome >>> cave = Cave() >>> home = IHome(cave) Traceback (most recent call last): ... TypeError: ('Could not adapt', <grokcor...
551
182
# from http://www.voidspace.org.uk/python/weblog/arch_d7_2007_03_17.shtml#e664 def ReadOnlyProxy(obj): class _ReadOnlyProxy(object): def __getattr__(self, name): return getattr(obj, name) def __setattr__(self, name, value): raise AttributeError("Attributes can't be set on t...
862
272
import pigpio import time class OdomDist(object): """ Take a tick input from odometry and compute the distance travelled """ def __init__(self, mm_per_tick, debug=False): self.mm_per_tick = mm_per_tick self.m_per_tick = mm_per_tick / 1000.0 self.meters = 0 self.last_time...
2,834
917
# coding: utf-8 import pprint import re import six class ActionSmnForwarding: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the valu...
6,370
1,971
from typing import Optional, Any, List, Dict, Union from .default_arg import DefaultArg, NotGiven from .internal_utils import _to_dict_without_not_given, _is_iterable from .types import TypeAndValue class UserAddress: country: Union[Optional[str], DefaultArg] locality: Union[Optional[str], DefaultArg] po...
8,190
2,478
"""Contains code that stitches together different parts of the library. By containing most side effects here the rest of the code can be more deterministic and testable. This code should not be unit tested. """ import os from pathlib import Path from typing import Union, List, Tuple, Dict, Optional import yaml from py...
4,875
1,519
# <<BEGIN-copyright>> # Copyright 2021, Lawrence Livermore National Security, LLC. # See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: BSD-3-Clause # <<END-copyright>> import sys import glob, os, shutil, filecmp PYTHON = sys.executable files = sorted( glob.glob( 't*.py' ) ) if( os.path.exi...
755
299
settings = {"velocity_min": 1, "velocity_max": 3, "x_boundary": 800, "y_boundary": 800, "small_particle_radius": 5, "big_particle_radius": 10, "number_of_particles": 500, "density_min": 2, "density_max": 20 }
315
116
import logging import smtplib from crawlino import hook_plugin, PluginReturnedData, CrawlinoValueError log = logging.getLogger("crawlino-plugin") @hook_plugin def hook_mail(prev_step: PluginReturnedData, **kwargs): log.debug("Hooks Module :: mail plugin") data = prev_step.to_dict # --------------------...
2,791
760
from pydantic import BaseModel class PrivyMessage(BaseModel): recipient_alias: str # alias of recipient message: str # the message
142
43
import os import csv import glob import numpy as np import pandas as pd import nltk import string import re from numpy import genfromtxt from nltk import * from nltk.corpus.reader.plaintext import PlaintextCorpusReader from nltk import word_tokenize from nltk.util import ngrams from collections import Counter def sta...
2,825
1,035
from .imutils import * from .boxutils import *
47
15
import os from PyPDF2 import PdfFileReader, PdfFileWriter def merge_pdfs(): ''' Merge multiple PDF's into one combined PDF ''' input_paths = input(r"Enter comma separated list of paths to the PDFs ") paths = input_paths.split(',') pdf_file_writer = PdfFileWriter() # Pick each pdf one by one and ...
4,256
1,414
import xml.etree.ElementTree as ET import re import os import loc datadir = 'D:/Steam/steamapps/common/Galactic Civilizations III/data' gamedatadir = os.path.join(datadir, 'Game') def processTechTree(techList, filename): filebase, _ = os.path.splitext(filename) techSpecializationList = ET.parse(os.path.join(g...
6,060
1,884
import sys import json import os import numpy as np from scipy.optimize import linear_sum_assignment import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d, Axes3D import cv2 import pylab as pl from numpy import linalg as LA import random import math from mpl_toolkits.mplot3d import axes3d, Axes3D from...
13,052
5,008
import re from functools import partial from traceback import print_tb import pytest from more_itertools import ilen from rossum.workspace import create_command, list_command, delete_command, change_command from tests.conftest import ( TOKEN, match_uploaded_json, ORGANIZATIONS_URL, WORKSPACES_URL, ...
4,887
1,594
#!/usr/bin/env python3 # Copyright 2014 The Meson development 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 appl...
9,457
2,743
import matplotlib.pyplot as plt import numpy as np def count_harmonic_numbers(n: int): count = 0 for i in range(1, n+1): # 1 ~ N まで for _ in range(i, n+1, i): # N以下の i の倍数 count += 1 return count x = np.linspace(1, 10**5, 100, dtype='int') y = list(map(lambda x: count_harmonic_numb...
481
223
import logging import csv from urllib2 import urlopen, quote from datetime import datetime from stockviewer.utils import make_timedelta, make_fields class websource(): def __init__(self, config): logging.debug('Web source init: config {}'.format(config)) self.__config = config self.__url = self.__config.find(...
1,549
568
from .account import Account from .bucket import Bucket __all__ = ["Account", "Bucket"]
90
30
import pathlib import numpy as np def create_submission(path: pathlib.Path, predictions): pred_with_id = np.stack([np.arange(len(predictions)), predictions], axis=1) np.savetxt( fname=path, X=pred_with_id, fmt="%d", delimiter=",", header="id,label", comments=""...
328
112
import json import urllib import utils as ut from distutils.util import strtobool class Call(object): """docstring for Call""" def __init__(self, currentStrike, currentPrice, currentProbOTM, currentIV, currentITM): self.currentStrike = currentStrike self.currentPrice = currentPrice self.currentProbOTM = curr...
2,566
918
""" Module used for building hopla. [quote](https://setuptools.readthedocs.io/en/latest/setuptools.html): As PEP 517 is new, support is not universal, and frontends that do support it may still have bugs. For compatibility, you may want to put a setup.py file containing only a setuptools.setup() invocation. """ import...
352
110
# -*- coding: utf-8 -*- """ Created on Sun Apr 20 17:12:53 2014 author: Josef Perktold """ import numpy as np from statsmodels.regression.linear_model import OLS, WLS from statsmodels.sandbox.regression.predstd import wls_prediction_std def test_predict_se(): # this test doesn't use reference values # chec...
3,545
1,582
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import json from Tools.Logger import logger from Lib.Similarity.Similarity import Similarity class Jaccard(Similarity): def predict(self, doc): results = [] for index in range(self.total): x = self.X[index] ...
738
241
""" Copyright (c) Microsoft Corporation """ import sys import time import logging from argparse import ArgumentParser from .constants import * from .discovery import * from .nvme import storeNVMeDevice from .ata import storeATADevice from .datahandle import outputData REV_MAJO...
4,209
1,257
'''8. Write a Python program to count occurrences of a substring in a string.''' def count_word_in_string(string1, substring2): return string1.count(substring2) print(count_word_in_string('The quick brown fox jumps over the lazy dog that is chasing the fox.', "fox"))
272
82
test = { "name": "q2", "points": 1, "hidden": True, "suites": [ { "cases": [ { "code": r""" >>> sample_population(test_results).num_rows 3000 """, "hidden": False, "locked": False, }, { "code": r""" >>> "Test Result" in sample_population(test_results).labe...
664
374
import logging import jsonpointer import yadage.handlers.utils as utils from yadage.handlers.expression_handlers import handlers as exprhandlers log = logging.getLogger(__name__) handlers, predicate = utils.handler_decorator() def checkmeta(flowview, metainfo): log.debug('checking meta %s on view with offset ...
3,144
881
from pyspark.sql import SparkSession spark = SparkSession.builder.master("local").appName('ReadParquet').config("spark.driver.host", "localhost").config( "spark.ui.port", "4040").getOrCreate() peopleDF = spark.read.json("people.json") # DataFrames can be saved as Parquet files, maintaining the schema information...
877
261
# -*- coding: utf-8 -*- """ The MIT License (MIT) Copyright (c) 2019 Lorenzo 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, ...
5,832
1,808
import os from enum import Enum import requests from docker import ContextAPI from docker.transport import UnixHTTPAdapter from compose.const import IS_WINDOWS_PLATFORM if IS_WINDOWS_PLATFORM: from docker.transport import NpipeHTTPAdapter class Status(Enum): SUCCESS = "success" FAILURE = "failure" ...
1,852
562
import vpython as vp import logging import time from robot_imu import RobotImu logging.basicConfig(level=logging.INFO) imu = RobotImu() pr = vp.graph(xmin=0, xmax=60, scroll=True) graph_pitch = vp.gcurve(color=vp.color.red, graph=pr) graph_roll = vp.gcurve(color=vp.color.green, graph=pr) xyz = vp.graph(xmin=0, xmax...
921
406
# -*- coding: UTF-8 -*- import time import simplejson as json from MySQLdb.connections import numeric_part from django.contrib.auth.decorators import permission_required from django.http import HttpResponse from common.utils.extend_json_encoder import ExtendJSONEncoder from common.utils.const import SQLTuning from s...
10,440
3,311
class Solution: def isValid(self, s): """ :type s: str :rtype: bool """ if not s: return True stack = [] for char in s: if char == '{' or char == '[' or char == '(': stack.append(char) else: ...
902
218
""" Well-known crypto-arithmetic puzzle of unknown origin (e.g., a model is present in Gecode) Examples of Execution: python3 Alpha.py python3 Alpha.py -variant=var """ from pycsp3 import * if not variant(): def of(word): return [x[i] for i in alphabet_positions(word)] # x[i] is the value for t...
2,230
987
def read_data(): rules = dict() your_ticket = None nearby_tickets = [] state = 0 with open('in') as f: for line in map(lambda x: x.strip(), f.readlines()): if line == '': state += 1 continue if line == 'your ticket:': co...
3,030
878
import socket import threading from time import sleep import pytest import gnmi_pb2 from client_server_test_base import GrpcBase from confd_gnmi_api_adapter import GnmiConfDApiServerAdapter from confd_gnmi_common import make_gnmi_path, make_xpath_path from confd_gnmi_server import AdapterType from route_status import...
3,717
1,155
import numpy as np import cv2 import math class FingerFinder(object): """docstring for FingerFinder""" def __init__(self, background_reduction=False): super(FingerFinder, self).__init__() self.bg_reduction = background_reduction self.kernel = cv2.getStructuringElement(cv2.MORPH_RECT, ...
3,486
1,393
from django.contrib import admin from .models import Item @admin.register(Item) class ItemAdmin(admin.ModelAdmin): fieldsets = [ ('Item', { 'fields': [ 'name', 'stock', 'description', 'thumbnail' ] }), (...
455
121
import numpy as np import json import colour_demosaicing def LoadRaw(FN): """ DEPRECATED! load and unpack RAW image :params FN: file name """ data = np.load(FN) shape = data.shape if shape == (1944, 3240): CameraType = 1 elif shape == (2464, 4100): CameraType = 2 ...
8,950
3,509
from numpy.core.defchararray import array from tensorflow.keras.models import Model from tensorflow.keras.models import load_model from tensorflow.keras.datasets import mnist from PIL import Image from tqdm import tqdm import matplotlib.pyplot as plt import statistics import numpy as np import pickle import cv2 import ...
4,487
1,548
from ROOT import gROOT, gStyle, Double from ROOT import TLegend, TLatex, TCanvas, THStack, TLine, TBox from ROOT import kYellow, kBlack, kWhite, kRed, kWhite, kOrange import os import random from colors import set_color_1D, set_color_2D, set_data_style, set_MCTotal_style, set_signal_style_1D tsize = 0.06 tyoffset = ...
14,806
5,884
#!/usr/bin/python3 import sys import os, os.path import platform import shutil import time import re import difflib import pickle from subprocess import run, PIPE from colorama import init, Fore, Back, Style from statistics import median # Globals if platform.system() in ['Linux', 'Darwin']: SYNQUID_CMD = ['stack'...
32,421
11,028
# Histogram equalization import cv2 import numpy as np import os from plantcv.plantcv import print_image from plantcv.plantcv import plot_image from plantcv.plantcv import fatal_error from plantcv.plantcv import params def hist_equalization(gray_img): """Histogram equalization is a method to normalize the distri...
977
309
import pytest from ehub.users.models import User from ehub.users.tests.factories import UserFactory @pytest.fixture(autouse=True) def media_storage(settings, tmpdir): settings.MEDIA_ROOT = tmpdir.strpath @pytest.fixture def user() -> User: return UserFactory()
274
95
from Sort.Example import Example class Merge(Example): def __init__(self) -> None: super().__init__() def sort(self, a): # create aux just once self.aux = [None for i in range(len(a))] self._sort(a, 0, len(a) - 1) def _sort(self, a, lo, hi): if lo >= hi: ...
1,448
523
from rest_framework import permissions from csp import settings from rest_framework.exceptions import PermissionDenied class IsWorker(permissions.BasePermission): def has_permission(self, request, view): return request.user.profile.is_worker class IsRequester(permissions.BasePermission): def has_obj...
916
234
from setuptools import setup requires = [ 'pyramid', 'waitress', 'python-dateutil' ] setup(name='hello', install_requires=requires, package_dir={'': "hello"}, entry_points="""\ [paste.app_factory] main = hello:main """, )
278
99
import sys import signal from clint.textui import colored, puts from downloader import Downloader from extractor import Extractor signal.signal(signal.SIGINT, lambda x, y: sys.exit(0)) def main(): downloader = Downloader() extractor = Extractor() url = "https://pornhub.com" puts(colored.green("getti...
1,025
327
from cryptography.fernet import Fernet import os import discord import aiohttp import secrets from urllib.parse import quote from dotenv import load_dotenv load_dotenv() class OAuth: def __init__(self): # User Provided Data self.client_id = os.getenv("CID") self.client_secret = os.getenv("C...
6,259
1,853
mapping = { "settings": { "index": { "max_result_window": 15000, "analysis": { "analyzer": { "default": { "type": "custom", "tokenizer": "whitespace", "filter": ["english_s...
17,428
3,677
######################################################################### # Ryuretic: A Modular Framework for RYU # # !/ryu/ryu/app/Ryuretic/Ryuretic_Intf.py # # Authors: # # Jacob Cox (jcox70@gatech.edu) ...
24,311
10,048
from __future__ import division import numpy as np def SoftmaxLoss2(w, X, y, k): # w(feature*class,1) - weights for last class assumed to be 0 # X(instance,feature) # y(instance,1) # # version of SoftmaxLoss where weights for last class are fixed at 0 # to avoid overparameterization n, ...
715
302
from .utils import hash_string from typing import Union class StringStore: """StringStore object acts as a lookup table. It looks up strings by 64-bit hashes and vice-versa, looks up hashes by their corresponding strings. """ def __init__(self, strings=None): """Create the StringStore object ...
3,260
896