text
string
size
int64
token_count
int64
import click from arbol.arbol import aprint, asection from dexp.cli.defaults import DEFAULT_CLEVEL, DEFAULT_CODEC, DEFAULT_STORE from dexp.cli.parsing import _get_output_path, _parse_channels, _parse_chunks from dexp.datasets.open_dataset import glob_datasets from dexp.datasets.operations.crop import dataset_crop @c...
2,962
980
import sys from matplotlib import image as mpimg import numpy as np import os DIPHA_CONST = 8067171840 DIPHA_IMAGE_TYPE_CONST = 1 DIM = 3 input_dir = os.path.join(os.getcwd(), sys.argv[1]) dipha_output_filename = sys.argv[2] vert_filename = sys.argv[3] input_filenames = [name for nam...
2,287
883
""" Tools para validar o arquivo template recebido do SQS """ class Validate: def __init__(self): pass def check_validate_yml(self, template): """ valida se o arquivo yml é valido """ if template: return True else: return False def che...
1,507
407
import numpy as np import matplotlib.pyplot as plt import math def normal(mu,sigma,x): #normal distribution return 1/(math.pi*2)**0.5/sigma*np.exp(-(x-mu)**2/2/sigma**2) def eval(x): return normal(-4,1,x) + normal(4,1,x) #return 0.3*np.exp(-0.2*x**2)+0.7*np.exp(-0.2*(x-10)**2) def ref(x_star,x): #normal...
1,223
577
#!/usr/bin/python # -*- encoding: utf8 -*- import itertools import math import sys import IPy def main(): china_list_set = IPy.IPSet() for line in sys.stdin: china_list_set.add(IPy.IP(line)) # 输出结果 for ip in china_list_set: print '<item>' + str(ip) + '</item>' if __name__ == "__ma...
338
139
name = "mail.txt" counts = dict() handle = open(name) for line in handle: line = line.rstrip() if line == '': continue words = line.split() if words[0] == 'From': counts[words[5][:2]] = counts.get(words[5][:2], 0) + 1 tlist = list() for key, value in counts.items(): ...
436
160
import os from typing import Any, Dict, List, Optional import carla from core.simulators.carla_simulator import CarlaSimulator from core.simulators.carla_data_provider import CarlaDataProvider from .srunner.scenarios.route_scenario import RouteScenario, SCENARIO_CLASS_DICT from .srunner.scenariomanager.scenario_mana...
9,338
2,508
import myproject myproject.logs(show_level='debug') myproject.mymod.do_something()
86
32
#!/usr/bin/env python # coding: utf-8 # BEGIN --- required only for testing, remove in real world code --- BEGIN import os import sys THISDIR = os.path.dirname(os.path.abspath(__file__)) APPDIR = os.path.abspath(os.path.join(THISDIR, os.path.pardir, os.path.pardir)) sys.path.insert(0, APPDIR) # END --- required only f...
709
263
''' HDF-saving features ''' import time import tempfile import random import traceback import numpy as np import fnmatch import os, sys import subprocess from riglib import calibrations, bmi from riglib.bmi import extractor from riglib.experiment import traits import hdfwriter class SaveHDF(object): ''' Saves...
3,325
961
# # Copyright (c) 2013-2018 Quarkslab. # This file is part of IRMA project. # # 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 in the top-level directory # of this distribution and at: # # http:...
2,040
625
import time import os import math import numpy as np from libs import utils from libs.img_dataset import ImgDataset from nets.crnn import CRNN from nets.cnn.paper_cnn import PaperCNN import shutil def calculate_accuracy(predicts, labels): """ :param predicts: encoded predict result :param labels: ground...
7,979
2,747
#!/bin/python3 import math import os import random import re import sys # Complete the solve function below. def solve(meal_cost, tip_percent, tax_percent): tip = (meal_cost * tip_percent)/100 tax = (meal_cost * tax_percent)/100 print(int(meal_cost + tip + tax + 0.5)) # We add 0.5 because...
606
226
# -*- coding: utf-8 -*- # # Helper Script for Mass-Invitation of Participant Organisations # # RLPPTM Template Version 1.0 # # Execute in web2py folder after code upgrade like: # python web2py.py -S eden -M -R applications/eden/modules/templates/RLPPTM/tools/mis.py # import os import sys from core import s3_format_dat...
5,706
1,517
def save_form(form, actor=None): """Allows storing a form with a passed actor. Normally, Form.save() does not accept an actor, but if you require this to be passed (is not handled by middleware), you can use this to replace form.save(). Requires you to use the audit.Model model as the actor is passed to th...
1,133
341
# coding = utf-8 # Create date: 2018-11-05 # Author :Hailong def test_sysctl(ros_kvm_with_paramiko, cloud_config_url): command = 'sudo cat /proc/sys/kernel/domainname' feed_back = 'test' client = ros_kvm_with_paramiko(cloud_config='{url}/test_sysctl.yml'.format(url=cloud_config_url)) stdin, stdout, st...
728
271
import json import logging from django.core.management.base import BaseCommand from django.db import transaction from paprika_sync.core.models import PaprikaAccount from paprika_sync.core.serializers import RecipeSerializer, CategorySerializer from paprika_sync.core.utils import log_start_end logger = logging.getLo...
3,310
902
#!/usr/bin/env python # Licensed under a 3-clause BSD style license - see LICENSE.rst import mica.archive.asp_l1 mica.archive.asp_l1.main()
142
59
from time import sleep from proto9x.usb import usb from proto9x.tls import tls from proto9x.flash import read_flash from proto9x.init_flash import init_flash from proto9x.upload_fwext import upload_fwext from proto9x.calibrate import calibrate from proto9x.init_db import init_db #usb.trace_enabled=True #tls.trace_en...
738
281
from dataclasses import dataclass, field @dataclass class FooTest: class Meta: name = "fooTest" value: str = field( init=False, default="Hello" ) @dataclass class Root: class Meta: name = "root" foo_test: str = field( init=False, default="Hello",...
448
137
import json import os from collections import OrderedDict from copy import deepcopy import SimpleITK as sitk from batchgenerators.augmentations.utils import resize_segmentation # resize_softmax_output from skimage.transform import resize from torch.optim import lr_scheduler from torch import nn import numpy as np impor...
43,545
14,728
import os basepath = '/home/archit/scratch/cartpoles/data/hyperparam/cartpole/offline_learning/esarsa-adam/' dirs = os.listdir(basepath) string = '''''' for dir in dirs: print(dir) subbasepath = basepath + dir + '/' subdirs = os.listdir(subbasepath) for subdir in subdirs: print(subdir) subsubbasepath = subbasep...
982
409
import os import shutil import tempfile import zipfile def archive_write(archivepath, data, filename, compression, compressionlevel): """ Create a file named filename in the archive and write data to it :param archivepath: The path to the zip-archive :type archivepath: str :param data: The data t...
4,848
1,294
"""Abstract class for all the scan planners https://www.postgresql.org/docs/9.1/using-explain.html https://www.postgresql.org/docs/9.5/runtime-config-query.html """ from src.query_planner.abstract_plan import AbstractPlan from typing import List class AbstractScan(AbstractPlan): """Abstract class for all the scan...
968
272
# !usr/bin/python # coding:utf-8 import time import socket def main(): print "Socket client creat successful" host = "192.0.2.1" port = 9876 bufSize = 1024 addr = (host, port) Timeout = 300 mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) mySocket.settimeout(Timeout) ...
926
286
import argparse import sys from cliquet.scripts import cliquet from pyramid.scripts import pserve from pyramid.paster import bootstrap def main(args=None): """The main routine.""" if args is None: args = sys.argv[1:] parser = argparse.ArgumentParser(description="Kinto commands...
1,642
444
from django.contrib import admin from django.contrib.auth.models import User from .models import Vegetable, Harvest, Transaction, Merchandise, MerchandisePrice from .models import PurchasedItem, UserProfile, VegetablePrice, StockedVegetable from .models import MerchandisePhotos admin.site.register(Vegetable) admin.sit...
625
200
from ctypes import sizeof from io import BytesIO import unittest from pyglet.media.synthesis import * local_dir = os.path.dirname(__file__) test_data_path = os.path.abspath(os.path.join(local_dir, '..', '..', 'data')) del local_dir def get_test_data_file(*file_parts): """Get a file from the test data directory...
3,423
1,091
#Datos de entrada num=int(input("Ingrese un numero: ")) # Proceso if num==10: print("Calificacion: A") elif num==9: print("Calificacion: B") elif num==8: print("Calificacion: C") elif num==7 and num==6: print("Calificacion: D") elif num<=5 and num>=0: print("Calificacion: F")
282
111
ribbon_needed = 0 with open("input.txt", "r") as puzzle_input: for line in puzzle_input: length, width, height = [int(item) for item in line.split("x")] dimensions = [length, width, height] smallest_side = min(dimensions) dimensions.remove(smallest_side) second_smallest_side = min(dimensions) ribbon_n...
417
164
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. # Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. # # 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 Licen...
11,424
3,173
import numpy as np import torch import torch.nn.functional as F def content_loss(content_weight, content_current, content_target): """ Compute the content loss for style transfer. Inputs: - content_weight: Scalar giving the weighting for the content loss. - content_current: features of the curre...
5,277
1,301
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import xml.sax.saxutils from Peach.transformer import Transformer class HtmlDecode(Transformer): """Decode HTML en...
495
161
# From: http://williams.best.vwh.net/avform.htm#GCF import math EPS = 0.0001 d2r = math.pi / 180.0 r2d = 180.0 / math.pi rad2nm = (180.0 * 60.0) / math.pi nm2rad = 1.0 / rad2nm nm2meter = 1852 meter2nm = 1.0 / nm2meter # p1 = (lat1(deg), lon1(deg)) # p2 = (lat2(deg), lon2(deg)) def course_and_dist(p1, p2): # thi...
2,132
953
import connexion, os from connexion.resolver import RestyResolver from flask import json from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow # Globally accessible libraries db = SQLAlchemy() mm = Marshmallow() def init_app(): """Initialize the Connexion application.""" BASE_DIR...
1,195
380
''' Summary: Program that implements a routing deamon based on the RIP version 2 protocol from RFC2453. Usage: python3 Router.py <router_config_file> Configuration File: The user supplies a router configuration file of the format: [Setting...
29,893
8,672
from ibllib.io import spikeglx import numpy as np import ibllib.dsp as dsp from scipy import signal from ibllib.misc import print_progress from pathlib import Path import alf.io as aio import logging import ibllib.ephys.ephysqc as ephysqc from phylib.io import alf _logger = logging.getLogger('ibllib') ...
5,669
2,128
from django.db import models class SiteSettings(models.Model): site_name = models.CharField(max_length=200 , verbose_name='Site Name') site_url = models.CharField(max_length=200 , verbose_name='Site URL') site_address = models.CharField(max_length=300 , verbose_name='Site Address') site_phone = mode...
2,740
854
# -*- coding: utf-8 -*- # vispy: gallery 10 # Copyright (c) Vispy Development Team. All Rights Reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. import sys import numpy as np from vispy import app, gloo, visuals from vispy.visuals.filters import Clipper, ColorFilter from vispy.visual...
9,955
3,313
from unittest import TestCase from datetime import datetime import pyarrow as pa import numpy as np import pandas as pd from h1st.schema import SchemaInferrer class SchemaInferrerTestCase(TestCase): def test_infer_python(self): inferrer = SchemaInferrer() self.assertEqual(inferrer.infer_schema(1)...
4,243
1,395
""" # refactoring Refactoring is the key to successfull projects. Refactor: 1) annuity_factor such that: conversion to integer is handled, no extra printing 2) policy_book into a class such that: a function generates the book and the premium stats and visualizations functions are avalaible 3) book_report su...
373
112
"""Auxiliary methods.""" import os import json from errno import EEXIST import numpy as np import seaborn as sns import cPickle as pickle import matplotlib.pyplot as plt sns.set() DEFAULT_LOG_DIR = 'log' ATOB_WEIGHTS_FILE = 'atob_weights.h5' D_WEIGHTS_FILE = 'd_weights.h5' class MyDict(dict): """ Dictionar...
6,272
2,231
from github import Github def parseGithubURL(url): splitURL = url.split('/') owner = splitURL[3] repo = splitURL[4] return { "owner": owner, "repo": repo } def fetchRepoFiles(owner, repo): files = [] g = Github('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') repo = g.get_rep...
834
297
#-*- coding: utf-8 -*- import codecs import random from utils.global_names import GlobalNames, get_file_path def modify_tokens(tokens): new_tokens = [] pos = 0 len_ = len(tokens) while pos < len_: if tokens[pos] == "[": if pos+2 < len_ and tokens[pos+2] == "]": to...
995
322
from graphgallery.functional import device import tensorflow as tf import torch def test_device(): # how about other backend? # tf assert isinstance(device("cpu", "tf"), str) assert device() == 'cpu' assert device("cpu", "tf") == 'CPU' assert device("cpu", "tf") == 'cpu' assert device("de...
1,087
354
# -*- coding: utf-8 -*- """ A card (duh). """ import random import uuid from enum import Enum from typing import List from py_hanabi.settings import CARD_DECK_DISTRIBUTION __author__ = "Jakrin Juangbhanich" __email__ = "juangbhanich.k@gmail.com" class Color(Enum): RED = 1 BLUE = 2 GREEN = 3 YELLOW ...
3,482
1,145
import types import django.test.testcases from django.conf import settings from facetools.models import TestUser from facetools.common import _create_signed_request from facetools.test import TestUserNotLoaded from facetools.signals import sync_facebook_test_user, setup_facebook_test_client from facetools.common impor...
4,344
1,232
import setuptools import distpickymodel def get_long_desc(): with open("README.rst", "r") as fh: return fh.read() setuptools.setup( name="distpickymodel", version=distpickymodel.__version__, author="Dan G", author_email="daniel.garcia@d2garcia.com", description="A shared Mongoengine-...
1,186
380
import unittest from password import Credentials class TestCredentials(unittest.TestCase): """ Class to test behaviour of the credentials class """ def setUp(self): """ Setup method that defines instructions """ self.new_credentials = Credentials("Github","Tina","blackfa...
1,948
539
def calc_fitness(pop): from to_decimal import to_decimal from math import sin, sqrt for index, elem in enumerate(pop): # só atribui a fitness a cromossomos que ainda não possuem fitness # print(elem[0], elem[1]) x = to_decimal(elem[0]) y = to_decimal(elem[1]) # x = ...
564
238
# -*- coding: utf-8 -*- from oopschool.school import Student,Tesla,SpecialStudent,Teacher from oopschool.newschool import Test
128
45
class Solution: def hammingDistance(self, x: int, y: int) -> int: xor = x ^ y distance = 0 while xor: if xor & 1: distance += 1 xor = xor >> 1 return distance class Solution: def hammingDistance(self, x: int, y: int) -> int: xor =...
450
145
import logging from rdl.data_sources.MsSqlDataSource import MsSqlDataSource from rdl.data_sources.AWSLambdaDataSource import AWSLambdaDataSource class DataSourceFactory(object): def __init__(self, logger=None): self.logger = logger or logging.getLogger(__name__) self.sources = [MsSqlDataSource, AW...
1,163
293
# --------------------------------- # Prepare the data etc. # ---------------------------------- import numpy as np import pandas as pd # train_x is the training data, train_y is the target values, and test_x is the test data # stored in pandas DataFrames and Series (numpy arrays also used) train = pd.read_csv('../in...
2,753
926
#!/usr/bin/env python # -*- coding: utf-8 -*- import wit import json class WitClient(object): """docstring for WitClient""" _access_token = 'NBPOVLY7T6W3KOUEML2GXOWODH3LPWPD' def __init__(self): wit.init() def text_query(self, text): res = json.loads(wit.text_query(text, WitClient._access_token)) return ...
476
194
# Problem Statement: https://www.hackerrank.com/challenges/itertools-combinations-with-replacement/problem from itertools import combinations_with_replacement S, k = input().split() for comb in combinations_with_replacement(sorted(S), int(k)): print(''.join(comb))
268
84
""" Visual Genome Python API wrapper, models """ class Image: """ Image. ID int url hyperlink string width int height int """ def __init__(self, id, url, width, height, coco_id, flickr_id): self.id = id self.url = url self.width ...
5,341
1,597
import csv import matplotlib.pyplot as plt import time PLOT_PER_WINDOW = False WINDOW_LENGTH = 60000 BINS = 1000 delay_store = {} perwindow_delay_store = {} plotting_delay_store = {} filename = "output-large.csv" # filename = "output.csv" # filename = "output-medium.csv" # filename = "output-small.csv" # filename = "...
2,152
801
#!/usr/bin/env python # author: Peter Thorpe September 2015. The James Hutton Insitute, Dundee, UK. # title rename single copy busco genes from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord from Bio import SeqIO import os from sys import stdin,argv import sys from optparse import OptionParser ###############...
3,472
1,021
# Download the Python helper library from twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console api_key_sid = 'SKXXXX' api_key_secret = 'your_api_key_secret' client = Client(api_key_sid, api_key_secret) did_delete = client.video\ .c...
427
136
from time import sleep debug_mode = False time_to_exit = False exiting = False exit_code = 0 def get_debug_mode(): return debug_mode def trigger_exit(_exit_code): global time_to_exit, exit_code exit_code = _exit_code time_to_exit = True sleep(0.1)
274
101
from __future__ import absoulte_import from __future__ import division from __future__ import print_function import tensorflow as tf from data import data_utils data = data_utils class SequenceWrapperTest(tf.test.TestCase): def testDefaultTimesteps(self): seq = data.SequenceWrapper() t1 = seq....
6,924
2,423
from django.apps import AppConfig class HeadlesspreviewConfig(AppConfig): name = 'headlesspreview'
105
30
import argparse import numpy as np import matlab.engine from scipy.io import savemat import os from time import time def main(args): start_time = time() eng = matlab.engine.start_matlab() eng.addpath(os.path.join(file_dir, 'matlab_engine')) eng.addpath(os.path.join(file_dir, r'matlab_engine/weight_uti...
3,546
1,124
from stockprophet.cli import entry_point from stockprophet.crawler import ( init_stock_type, init_stock_category ) from stockprophet.db import init_db from .utils import read_db_settings def preprocessing() -> bool: result = False # noinspection PyBroadException try: db_config = read_db_setti...
805
266
import aoc_helper RAW = aoc_helper.day(25) print(RAW) def parse_raw(): ... DATA = parse_raw() def part_one(): ... def part_two(): ... aoc_helper.submit(25, part_one) aoc_helper.submit(25, part_two)
216
97
def setIntersectionCount(group): return len(set.intersection(*group)) groupList = [] tempGroup = [] with open("./6/input.txt") as inputFile: for line in inputFile: line = line.replace("\n","") if len(line) > 0: tempGroup.append(set(line)) else: groupList.append(tempGroup) tempGroup = [] if len(tempGr...
475
174
# Copyright (c) 2021 PaddlePaddle Authors. 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 # # Unless required by applic...
2,964
1,202
# Generated by Django 2.0.6 on 2018-11-02 09:44 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pages', '0003_coachingcourse'), ] operations = [ migrations.AlterField( model_name='coachingcourse', name='username'...
403
135
from collections import OrderedDict from random import Random from typing import Set from .._types import Dataset, Split, LabelIndices from .._util import per_label from ._RandomSplitter import RandomSplitter from ._Splitter import Splitter class StratifiedSplitter(Splitter): """ TODO """ def __init_...
1,119
317
from enum import Enum class SubscriptionPlatform(Enum): ios = 'ios' android = 'android' macos = 'macos' uikitformac = 'uikitformac' stripe = 'stripe' class AttributionNetworkCode(Enum): apple_search_ads = 0 adjust = 1 apps_flyer = 2 branch = 3 tenjin = 4 facebook = 5
315
119
from __future__ import absolute_import, division, print_function, unicode_literals import torch.nn.qat as nnqat import torch.nn.intrinsic import torch.nn.functional as F class LinearReLU(nnqat.Linear): r""" A LinearReLU module fused from Linear and ReLU modules, attached with FakeQuantize modules f...
1,441
491
'''OpenGL extension EXT.draw_buffers2 This module customises the behaviour of the OpenGL.raw.GL.EXT.draw_buffers2 to provide a more Python-friendly API Overview (from the spec) This extension builds upon the ARB_draw_buffers extension and provides separate blend enables and color write masks for each color outp...
992
281
""" Module containing the RetryingClient wrapper class. """ from time import sleep def _ensure_tuple_argument(argument_name, argument_value): """ Helper function to ensure the given arguments are tuples of Exceptions (or subclasses), or can at least be converted to such. Args: argument_name: s...
6,443
1,726
import numpy as np import numpy.linalg as lg A_mat = np.matrix([ [0, 1, 1, 1, 0], [1, 0, 0, 0, 1], [1, 0, 0, 1, 1], [1, 0, 1, 0, 1], [0, 1, 1, 1, 0] ]) eigen = lg.eig(A_mat) # return Arr[5] with 5 different linear independent eigen values vec = eigen[1][:, 0] # the column (eigen vect...
461
226
# Generated by Django 2.2.2 on 2019-08-25 09:29 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('classroom', '0024_auto_20190825_1723'), ] operations = [ migrations.AddField( model_name='myfile', name='file', ...
397
147
from jumbo_api.objects.store import Store class Profile(object): def __init__(self, data): self.id = data.get("identifier") self.store = Store(data.get("store")) def __str__(self): return f"{self.id} {self.store}"
249
82
#!/usr/bin/env python import os import sys import time import errno import stat import datetime import socket import struct import atexit import logging #from lru import LRUCacheDict from logging import handlers from task_manager import Job, taskManage from ctypes import * from urlparse import * from multiprocessing ...
11,928
4,277
# -*- encoding: utf-8 -*- from flask import request from lazyblacksmith.utils.request import is_xhr import logging logger = logging.getLogger('lb.ajax') def is_not_ajax(): """ Return True if request is not ajax This function is used in @cache annotation to not cache direct call (http 40...
365
125
import os class Traces: def __init__(self, positive = set(), negative = set()): self.positive = positive self.negative = negative """ IG: at the moment we are adding a trace only if it ends up in an event. should we be more restrictive, e.g. consider xxx, the same as xxxxxxxxxx (wher...
6,145
1,697
import django from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns if django.VERSION[:2] > (1, 9): from django.views.i18n import JavaScriptCatalog else: from django.views.i18n import javas...
1,758
593
import math import time def check_prime(n): if n % 2 == 0: return False, 2 for i in range(3, int(math.sqrt(n)) + 1): if n % i == 0: return False, i return True, None if __name__ == "__main__": primes = [] t1 = time.time() # 100109100129100151 big prime # htt...
1,770
1,005
import pytest from katana.dynamic_bitset import DynamicBitset __all__ = [] SIZE = 50 @pytest.fixture def dbs(): return DynamicBitset(SIZE) def test_set(dbs): dbs[10] = 1 assert dbs[10] def test_set_invalid_type(dbs): try: dbs[2.3] = 0 assert False except TypeError: p...
1,609
724
import unittest import astar class BasicTests(unittest.TestCase): def test_bestpath(self): """ensure that we take the shortest path, and not the path with less elements. the path with less elements is A -> B with a distance of 100 the shortest path is A -> C -> D -> B with a distanc...
1,026
336
#!/bin/env python3 import csv def intersect(list1,list2): list3 = [ value for value in list1 if value in list2] return list3 def category(list1,effects): cat = 'Good' good = 0 bad = 0 for ing in list1: if effects[ing]=='Good': good += 1 else: bad += 1 ...
2,623
885
# coding: utf-8 """ Control-M Services Provides access to BMC Control-M Services # noqa: E501 OpenAPI spec version: 9.20.215 Contact: customer_support@bmc.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six from clients.ct...
5,679
1,613
# -*- coding: utf-8 -*- import pytest import numpy as np from unittest import TestCase from pyleecan.Classes.CellMat import CellMat from pyleecan.Classes.MeshSolution import MeshSolution from pyleecan.Classes.PointMat import PointMat from pyleecan.Classes.MeshMat import MeshMat from pyleecan.Classes.ScalarProductL2 i...
3,469
1,316
# -*- coding: utf-8 -*- """ Pytorch models __author__ = 'Jamie (krikit@naver.com)' __copyright__ = 'No copyright. Just copyleft!' """ # pylint: disable=no-member # pylint: disable=invalid-name ########### # imports # ########### import torch import torch.nn as nn from embedder import Embedder from pos_models impo...
13,863
5,264
# -*- coding: utf-8 -*- """Top-level package for pyseqlogo.""" __author__ = """Saket Choudhary""" __email__ = 'saketkc@gmail.com' __version__ = '0.1.0' from .pyseqlogo import draw_logo from .pyseqlogo import setup_axis
221
90
# coding: utf-8 import os.path try: from setuptools import setup extras = dict(zip_safe=False, test_suite='nose.collector', tests_require=['nose']) except ImportError: from distutils.core import setup extras = {} import apscheduler here = os.path.dirname(__file__) readme_path = os.path.join(here, 'R...
1,274
410
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Travis Yates """Tests for object_detection.export_inference_graph.""" import os import mock import numpy as np import tensorflow as tf from object_detection import exporter from object_detection.builders import model_builder from object_detection.core i...
9,576
3,124
import os import sys import random def get_next_wallpaper(curr_path): lst_dir = os.listdir() rand_index = random.randint(0, len(lst_dir) - 1) return lst_dir[rand_index] def get_wall_dir(): return "/Users/MYOUNG/Pictures/mmt" def main(): script = "osascript -e 'tell application \"Finder\" to s...
543
204
"""Automated CI tools to run with Nox""" import nox from nox import Session locations = "src", "noxfile.py", "docs/conf.py" nox.options.sessions = "lint", "tests" @nox.session(python="3.9") def tests(session: Session) -> None: """Run tests with nox""" session.run("poetry", "install", external=True) sessi...
2,099
753
import cocotb_test.simulator # For partial back compatibility def run(simulator=None, **kwargs): if simulator: sim = simulator(**kwargs) sim.run() else: cocotb_test.simulator.run(**kwargs)
225
78
from django.apps import AppConfig class ProjectManagementConfig(AppConfig): name = 'kanban_backend.project_management' def ready(self): try: import kanban_backend.users.signals # noqa F401 except ImportError: pass
267
76
""" ~ Tracing ~ This modules containes functions and classes related to the console debug long or trace. """ from enum import Enum, auto import time __all__ = ( "TraceLEVELS", "trace" ) m_use_debug = None class TraceLEVELS(Enum): """ Info: Level of trace for debug """ NORMAL...
1,098
356
""" sunkit-image ============ A image processing toolbox for Solar Physics. * Homepage: https://sunpy.org * Documentation: https://sunkit-image.readthedocs.io/en/latest/ """ import sys from .version import version as __version__ # NOQA # Enforce Python version check during package import. __minimum_python_version_...
728
226
import plotly.graph_objects as go import plotly.express as px import pandas as pd class View: def __init__(self, st): self.st = st self.st.set_page_config(layout='wide') self.side_bar = st.sidebar def show_message(self, location, _type, message): if location == "sb": ...
26,004
8,066
# Exercise 4.11 # Author: Noah Waterfield Price import sys g = 9.81 # acceleration due to gravity try: # initial velocity (convert to m/s) v0 = (1000. / 3600) * float(sys.argv[1]) mu = float(sys.argv[2]) # coefficient of friction except IndexError: print 'Both v0 (in km/s) and mu must be supplied on...
662
291
# Testing code to check update status on demand from socketIO_client import SocketIO, LoggingNamespace from threading import Thread socketIO = SocketIO('localhost', 3000) status = 'pause' def on_push_state(*args): print('state', args) global status, position, duration, seek status = args[0]['s...
866
260