text string | size int64 | token_count int64 |
|---|---|---|
import datetime
import json
import os
from unittest import mock
from django.conf import settings
from django.core.files.storage import default_storage as storage
from freezegun import freeze_time
from waffle.testutils import override_switch
from olympia.amo.tests import addon_factory, TestCase, user_factory
from oly... | 4,812 | 1,664 |
from pulp import *
prob = LpProblem("PULPTEST", LpMinimize)
# model variables
XCOORD = [0, 1, 2]
YCOORD = [0, 1, 2]
NUMBERS = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# variable is a 3 x 3 x 9 matrix of binary values
allocation = LpVariable.dicts("square", (XCOORD, YCOORD, NUMBERS), 0, 1, LpInteger)
# target function
prob += 0... | 1,442 | 569 |
from rest_framework import status
from rest_framework.exceptions import APIException
class FeatureStateVersionError(APIException):
status_code = status.HTTP_400_BAD_REQUEST
class FeatureStateVersionAlreadyExistsError(FeatureStateVersionError):
status_code = status.HTTP_400_BAD_REQUEST
def __init__(self... | 482 | 134 |
# Copyright (c) 2021, salesforce.com, inc.
# All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
# For full license text, see the LICENSE file in the repo root
# or https://opensource.org/licenses/BSD-3-Clause
import itertools
import os
import random
from pathlib import Path
import numpy as np
import pycuda
... | 74,777 | 22,821 |
import numpy as np
import pandas as pd
import pytest
from etna.datasets import TSDataset
from etna.datasets import generate_ar_df
from etna.datasets import generate_const_df
from etna.datasets import generate_periodic_df
from etna.metrics import R2
from etna.models import LinearPerSegmentModel
from etna.transforms imp... | 11,030 | 4,653 |
# Generated by Django 2.1.3 on 2019-01-04 20:32
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import libs.spec_validation
class Migration(migrations.Migration):
dependencies = [
('db', '0016_experimentjob_sequence_and_deleted_flag_tpu_resources'),
]
operat... | 1,467 | 432 |
MAP_HEIGHT_MIN = 20
MAP_HEIGHT_MAX = 50
MAP_WIDTH_MIN = 20
MAP_WIDTH_MAX = 50
MAP_KARBONITE_MIN = 0
MAP_KARBONITE_MAX = 50
ASTEROID_ROUND_MIN = 10
ASTEROID_ROUND_MAX = 20
ASTEROID_KARB_MIN = 20
ASTEROID_KARB_MAX = 100
ORBIT_FLIGHT_MIN = 50
ORBIT_FLIGHT_MAX = 200
ROUND_LIMIT = 1000
def validate_map_dims(h, w):
ret... | 1,591 | 643 |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('home', views.home, name='home'),
path('login', views.ulogin, name='login'),
path('logout', views.ulogout, name='logout'),
path('password_change', views.password_change, name='password_change... | 544 | 174 |
#!/usr/bin/env python2
# coding: utf-8
# based on the vk4xmpp gateway, v2.25
# © simpleApps, 2013 — 2014.
# Program published under MIT license.
import gc
import json
import logging
import os
import re
import signal
import sys
import threading
import time
import urllib
core = getattr(sys.modules["__main__"], "__file... | 8,603 | 3,330 |
import math
def fibonacci(nth):
return int(1 / math.sqrt(5) * (math.pow((1 + math.sqrt(5)) / 2, nth + 1) - math.pow((1 - math.sqrt(5)) / 2, nth + 1)))
| 160 | 74 |
#!/usr/bin/python3
import telebot
from telebot import types
import datetime
from telegramcalendar import create_calendar
bot = telebot.TeleBot("")
current_shown_dates={}
@bot.message_handler(commands=['calendar'])
def get_calendar(message):
now = datetime.datetime.now() #Current date
chat_id = message.chat.id... | 2,577 | 852 |
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Activation, Flatten
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import f1_score
from sklearn.metrics import accuracy_score, confusi... | 5,094 | 2,010 |
'''
Micro Object Detector Net
the author:Luis
date : 11.25
'''
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from layers import *
from models.base_models import vgg, vgg_base
from ptflops import get_model_complexity_info
class BasicConv(nn.Module):
def __init__(self, in_planes, ou... | 14,275 | 5,689 |
from . import extensions | 24 | 5 |
import os
import ctypes
import time
PATH = 'C:/Users/acer/Downloads/wall/'
SPI=20
def changeBG(path):
"""Change background depending on bit size"""
count=0
for x in os.listdir(PATH):
while True:
ctypes.windll.user32.SystemParametersInfoW(SPI, 0, PATH+x, 3)
ti... | 412 | 153 |
import collections
import logging
import StringIO
from . import exc, Request, Expression
logger = logging.getLogger(__name__)
class CompiledRule(object):
"""
Compiled version of a routing rule.
`symbols`
A `rump.fields.Symbols` table used to store symbolic information used
in the compi... | 11,085 | 3,008 |
import binascii
def print_stream(stream, description):
stream.seek(0)
data = stream.read()
print('***' + description + '***')
print(data)
stream.seek(0)
def test_message(encoding='ascii', hex_bitmap=False):
binary_bitmap = b'\xF0\x10\x05\x42\x84\x61\x80\x02\x02\x00\x00\x04\x00\x00\x00\x00'
... | 951 | 506 |
from .betterbot import BetterBot
from . import commands
from datetime import datetime, timedelta
import importlib
import discord
import asyncio
import modbot
import forums
import base64
import json
import time
import os
import db
intents = discord.Intents.default()
intents.members = True
intents.presences = True
pre... | 16,265 | 7,093 |
import sys
from optparse import make_option
from django.core.management.base import BaseCommand
from django.conf import settings
import taskforce
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--verbose', action='store_true', dest='verbose',
help = 'Verbose... | 2,089 | 582 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2019-09-13 18:42
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("profiles", "0003_profile_smapply_id")]
operations = [
... | 521 | 183 |
string = input().split(", ")
beggars = int(input())
beggars_list = []
for x in range(0, beggars):
temp = string[x::beggars]
for j in range(0, len(temp)):
temp[j] = int(temp[j])
beggars_list.append(sum(temp))
print(beggars_list) | 250 | 99 |
# python to locate 1 in a 2D array
#below save it into a dictionary
# python to locate 1 in a 2D array
def check_zero(array1):
d = {}
print("array index zeros at:")
for i in range(len(array1)):
index = [k for k, v in enumerate(array1[i]) if v == 0]
d[i] = index
#print(i, index)
... | 1,978 | 1,027 |
# Allow tests/ directory to see faster_than_requests/ package on PYTHONPATH
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
| 163 | 49 |
#!/usr/bin/env python
from pySIR.pySIR import pySIR
import argparse
import datetime
import json
import os
import shlex
import subprocess
import sys
import time
import logging
logger = logging.getLogger('fib_optimizer')
log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
logging.basicConfig(level=log... | 7,711 | 2,652 |
import re
n = int(input())
def loopai(n):
x = [i+1 for i in range(n)]
z = x
print(re.sub(' ','',re.sub('\,','',re.sub('\]','',re.sub('\[','',str(z))))))
def main():
loopai(n)
if __name__ == '__main__':
main()
| 247 | 117 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from django.conf import settings
from django.http.response import HttpResponse
from django.views.generic import View
class HealthCheckView(View):
def get(self, request, *args, **kwargs):
return HttpResponse(settings.HEALTH_C... | 343 | 106 |
from assertpy import assert_that
import year2020.day21.reader as reader
def test_example():
lines = ['mxmxvkd kfcds sqjhc nhms (contains dairy, fish)\n',
'trh fvjkl sbzzf mxmxvkd (contains dairy)\n',
'sqjhc fvjkl (contains soy)\n',
'sqjhc mxmxvkd sbzzf (contains fish)\n']
... | 691 | 267 |
import cv2 as cv
import numpy as np
import os
import shutil
import torch
from torchvision import io
def resize_image(
image, expected_size, pad_value, ret_params=True, mode=cv.INTER_LINEAR
):
"""
image (ndarray) with either shape of [H,W,3] for RGB or [H,W] for grayscale.
Padding is added so that the... | 4,109 | 1,508 |
name = "Sharalanda"
age = 10
hobbies = ["draw", "swim", "dance"]
address = {"city": "Sebastopol", "Post Code": 1234, "country": "Enchantia"}
print("My name is", name)
print("I am", age, "years old")
print("My favourite hobbie is", hobbies[0])
print("I live in", address["city"])
| 281 | 115 |
class Solution(object):
def threeConsecutiveOdds(self, arr):
"""
:type arr: List[int]
:rtype: bool
"""
odds = 0
for a in arr:
if a % 2 == 1:
odds += 1
if odds >= 3:
return True
else:
... | 537 | 196 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Python-nvd3 is a Python wrapper for NVD3 graph library.
NVD3 is an attempt to build re-usable charts and chart components
for d3.js without taking away the power that d3.js gives you.
Project location : https://github.com/areski/python-nvd3
"""
from optparse import Optio... | 20,279 | 6,298 |
# Copyright (c) 2018 Javier M. Mellid <jmunhoz@igalia.com>
#
# 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, modif... | 5,733 | 1,595 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..builder import LOSSES
@LOSSES.register_module()
class DiceLoss(nn.Module):
def __init__(self, use_sigmoid=True, loss_weight=1.0):
"""`Dice Loss <https://arxiv.org/abs/1912.04488>`
Args:
use_sigmoid (bool, optio... | 1,822 | 609 |
from sys import maxsize
class Contact:
def __init__(self, first_name=None, middlename=None, lastname=None, nicknam=None, title=None, company=None,
address=None, home=None, mobile=None, work=None, fax=None,
email=None, email2=None, email3=None, secondaryphone=None, id=None, all_p... | 2,676 | 826 |
from .test_utils import (
BaseManagerTestCase,
skip_unless_module
)
from pulsar.managers.queued_drmaa import DrmaaQueueManager
class DrmaaManagerTest(BaseManagerTestCase):
def setUp(self):
super(DrmaaManagerTest, self).setUp()
self._set_manager()
def tearDown(self):
super(Dr... | 717 | 244 |
""" User model """
from __future__ import annotations
from datetime import tzinfo
import pytz
from pydantic import BaseModel, PrivateAttr, validator
from pydantic.fields import Field
from ..poll.poll import Poll
from ..primitive.timezone import TimeZone
from ..report.report import Report
from typing import Dict, L... | 2,235 | 703 |
import tkinter as tk
from tkinter import ttk
from tkinter import simpledialog, messagebox
import os.path
import pickle
class Album():
def __init__(self, nome, artista, ano, faixas):
self.__nome = nome
self.__artista = artista
self.__ano = ano
self.__faixas = faixas
def... | 5,264 | 1,730 |
import logging
import os
from oic.utils.http_util import BadRequest
from oic.utils.http_util import SeeOther
from otest.events import EV_HTTP_ARGS
from otest.result import safe_url
__author__ = 'roland'
logger = logging.getLogger(__name__)
class WebApplication(object):
def __init__(self, sessionhandler, webio... | 7,191 | 1,891 |
from .serializers import WeatherForecastDaySerializer
from .models import WeatherForecastDay
from datetime import datetime, timedelta
import requests
from decouple import config
import json
DATE_FORMAT = '%Y-%m-%d'
COUNTRY_CODES_TO_CAPITAL = {
'CZ': 'Prague',
'UK': 'London',
'SK': 'Bratislava',
}
WEATHER_... | 4,821 | 1,551 |
from flask import Blueprint, url_for
bp = Blueprint('printing', __name__,template_folder='templates')
from . import routes, forms
| 134 | 41 |
#!/usr/bin/python3
from csbiginteger.BigInteger import BigInteger
from functools import total_ordering
# requires: pip install msl-loadlib pycparser pythonnet
from msl.loadlib import LoadLibrary
# remember to execute first: cd csbiginteger/dotnet && dotnet build -c Release
net = LoadLibrary('csbiginteger/dotnet/bi... | 5,239 | 1,733 |
"""
Overview
--------
general info about this module
Classes and Inheritance Structure
----------------------------------------------
.. inheritance-diagram::
Summary
---------
.. autosummary::
list of the module you want
Module API
----------
"""
from __future__ import absolute_import, division, print_functio... | 8,841 | 2,713 |
import dico_command
class Basic(dico_command.Addon):
@dico_command.command("ping")
async def ping(self, ctx: dico_command.Context):
await ctx.reply(f"Pong! {round(self.bot.ping*1000)}ms")
def load(bot: dico_command.Bot):
bot.load_addons(Basic)
def unload(bot: dico_command.Bot):
bot.unload_... | 334 | 135 |
#!/usr/bin/env python3
from datetime import datetime, timezone, date
import os
import sys
import boto3
import logging
import json
#setup global logger
logger = logging.getLogger("SnapTool")
#set log level
LOGLEVEL = os.environ['LogLevel'].strip()
logger.setLevel(LOGLEVEL.upper())
logging.getLogger("botocore").setLeve... | 11,643 | 3,327 |
import torch
from fielder import FieldClass
import yaml
class ModelBase(FieldClass, torch.nn.Module):
"""Base Model Class"""
class FCNet(ModelBase):
d_in: int = 10
H: int = 100
n_hidden: int = 1
D_out: int = 1
def __post_init__(self):
super().__post_init__()
self.input_linea... | 4,176 | 1,594 |
import numpy as np
from pytope import Polytope
import matplotlib.pyplot as plt
np.random.seed(1)
# Create a polytope in R^2 with -1 <= x1 <= 4, -2 <= x2 <= 3
lower_bound1 = (-1, -2) # [-1, -2]' <= x
upper_bound1 = (4, 3) # x <= [4, 3]'
P1 = Polytope(lb=lower_bound1, ub=upper_bound1)
# Print the halfspace represen... | 5,138 | 2,444 |
#python libraries
import re
import os
# this package
from apetools.baseclass import BaseClass
from apetools.commons import enumerations
from apetools.commons import expressions
from apetools.commons.errors import ConfigurationError
MAC_UNAVAILABLE = "MAC Unavailable (use `netcfg`)"
class IfconfigError(Configuration... | 3,458 | 876 |
import retro # pip install gym-retro
import numpy as np # pip install numpy
import cv2 # pip install opencv-python
import neat # pip install neat-python
import pickle # pip install cloudpickle
class Worker(object):
def __init__(self, genome, config):
self.genome = genome
... | 2,471 | 799 |
# Yizhak Ben-Shabat (Itzik) <sitzikbs@gmail.com>
# Chamin Hewa Koneputugodage <chamin.hewa@anu.edu.au>
import os, sys, time
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from shapespace.dfaust_dataset import DFaustDataSet
import torch
import utils.visualizations as vis
import numpy as np
... | 9,420 | 3,554 |
import time
def main(request, response):
delay = float(request.GET.first(b"ms", 500))
time.sleep(delay / 1E3)
return [(b"Content-type", b"text/javascript")], u"export let delayedLoaded = true;"
| 208 | 74 |
# Copyright 2021 Collate
# 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... | 12,533 | 3,500 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import time
import torch
import numpy as np
import torchvision
import torch.nn as nn
import torch.optim as optim
import matplotlib.pyplot as plt
from torch.utils.data import DataLoader
from utils import *
from IPython import embed
class DCGAN(o... | 8,695 | 2,742 |
##########################################################################
# If not stated otherwise in this file or this component's Licenses.txt
# file the following copyright and licenses apply:
#
# Copyright 2018 RDK Management
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use th... | 8,940 | 2,802 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# FSRobo-R Package BSDL
# ---------
# Copyright (C) 2019 FUJISOFT. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
# 1. Redistributions of source code... | 37,563 | 21,878 |
"""
Author: Kourosh T. Baghaei
April 2021
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from .convnet import ConvNet
from .spikingconv2D import SpikingConv2D
from .spikingpool2D import SpikingAveragePool2D
from .spikinglinear import SpikingLinear
class SpikeConv(nn.Module):
def __init__(se... | 2,734 | 949 |
import unittest
from random import randint
from model.node import Node
from model.linked_list import LinkedList
SIZE = 5
class TestLinkedList(unittest.TestCase):
def test_copy(self):
nodes = []
for i in range(SIZE):
nodes.append(Node(i))
if i:
nodes[i - 1... | 1,483 | 391 |
from pygments.lexer import RegexLexer, include, words
from pygments.token import *
# https://docs.nvidia.com/cuda/parallel-thread-execution/index.html
class CustomLexer(RegexLexer):
string = r'"[^"]*?"'
followsym = r'[a-zA-Z0-9_$]*'
identifier = r'(?:[a-zA-Z]' + followsym + r'| [_$%]' + followsym + r')'
... | 3,141 | 1,194 |
# -*- coding: utf-8 -*-
"""Basic tests for state and entity relationships in dork
"""
import dork.types
from tests.utils import has_many, is_a
def test_items_exist():
"""the dork module should define an Item
"""
assert "Item" in vars(dork.types)
is_a(dork.types.Item, type)
def test_holders_exist():
... | 1,962 | 715 |
"""
text cleaning
"""
#-- Imports ---------------------------------------------------------------------
# base
import functools
import re
# third party
import toml
# project
from woffle.functions.compose import compose
#-- Definitions -----------------------------------------------------------------
#-- cleaning
#... | 1,115 | 306 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that contains utils functions related with Ziva plugin
"""
from __future__ import print_function, division, absolute_import
from tpDcc import dcc
PLUGIN_NAME = 'ziva'
def load_ziva_plugin():
if not is_ziva_plugin_loaded():
dcc.load_plugin(PLUGI... | 452 | 169 |
import json
import sys
import io
import time
from wrapt_timeout_decorator import *
from contextlib import redirect_stdout
class Checker:
def __init__(self, questions, answers, user_answers):
self.questions = questions['questions']
self.answers = answers["answers"]
self.user_answers = user... | 2,737 | 853 |
from datetime import datetime
from .cf_template import IAMTemplate
from scaffold.cf.stack.builder import StackBuilder
class IAMBuilder(StackBuilder):
def __init__(self, args, session, is_update):
super(IAMBuilder, self).__init__(args.stack_name, session, is_update)
self.args = args
def get_s... | 1,225 | 371 |
"""
Created by Sayem on 14 March, 2021
All rights reserved. Copyright © 2020.
"""
from .celery import app as celery_app
__author__ = "Sayem"
__all__ = ["celery_app"]
| 175 | 74 |
#
# Autogenerated by Thrift Compiler (1.0.0-dev)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py:new_style1
#
#from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException
from thrift.Thrift import TType, TMessageType, TException, TApplicati... | 194,383 | 74,212 |
#Create a list using []
a = [1,2,3,7,66]
#print the list using print() function
print(a)
#Access using index using a[0], a[1], ....
print(a[2])
#Changing the value of the list
a[0] = 777
print(a)
#We can create a list with items of different type
b = [77,"Root",False,6.9]
print(b)
#List Slicing
friends = ["Root","... | 385 | 163 |
import math
fco = open('train_co.txt', 'r')
fwr =open('train_wr.txt', 'r')
fcoal = open('train_co_al.txt', 'w')
fwral =open('train_wr_al.txt', 'w')
#first we align the two files
colines = fco.readlines()
wrlines = fwr.readlines()
for i in colines:
cols = i.split()
for j in cols:
fcoal.write(j+'\n')
for i in wrli... | 3,596 | 1,696 |
__all__ = ['PingEvents']
| 25 | 11 |
#!/usr/bin/env python2
# coding: utf-8
import sys
def main():
s = ' '.join((u'❄ ☃ ❄', sys.version.split()[0], u'❄ ☃ ❄'))
print(type(s))
return {'snowy_version': s}
if __name__ == '__main__':
main()
| 217 | 107 |
#AI is imported by default
#this is only a test for now
print "hello from aipy"
| 80 | 26 |
# Fizzbuzz.py
import sys
with open(sys.argv[1], 'r') as file:
for line in file:
nums = line.split()
i = int(nums[2])
n = 1
output = ""
while n <= i:
if n % int(nums[0]) == 0 and n % int(nums[1]) == 0:
output += "FB "
elif n % int(nums... | 542 | 188 |
singular = [
'this','as','is','thesis','hypothesis','less','obvious','us','yes','cos',
'always','perhaps','alias','plus','apropos',
'was','its','bus','his','is','us',
'this','thus','axis','bias','minus','basis',
'praxis','status','modulus','analysis',
'aparatus'
]
invariable = [ #frozen_li... | 5,421 | 1,738 |
import pytest
import cue
def test_basic():
cue.compile('')
assert '1' == str(cue.compile('1'))
assert ['1', '2', '3', '{\n\ta: 1\n}'] == [str(v) for v in cue.compile('[1,2,3,{a:1}]')]
assert [('a', '1'), ('b', '2')] == [(str(k), str(v)) for k, v in cue.compile('{a: 1, b: 2}')]
with pytest.raises(cue.CueErr... | 3,707 | 1,717 |
#!/usr/bin/env python
#
# xferfcn_input_test.py - test inputs to TransferFunction class
# jed-frey, 18 Feb 2017 (based on xferfcn_test.py)
import unittest
import numpy as np
from numpy import int, int8, int16, int32, int64
from numpy import float, float16, float32, float64, longdouble
from numpy import all, ndarray, ... | 11,924 | 4,135 |
"""Python Annotations that are shockingly useful."""
__all__ = ["__version__", "Field", "FunctionFields", "NamespaceFields"]
from .field import Field, FunctionFields, NamespaceFields
from .version import __version__
| 218 | 58 |
class Solution(object):
def summaryRanges(self, nums):
"""
:type nums: List[int]
:rtype: List[str]
"""
range_list = []
for i in range(len(nums)):
if i > 0 and nums[i - 1] + 1 == nums[i]:
range_list[-1][1] = nums[i]
else:
... | 548 | 198 |
from mqfactory.tools import Policy, Rule, CATCH_ALL
def test_empty_policy():
p = Policy()
assert p.match({"something": "something"}) == CATCH_ALL
assert p.match({}) == CATCH_ALL
def test_policy():
p = Policy([
Rule({ "a": 1, "b": 1, "c": 1 }, "a=1,b=1,c=1" ),
Rule({ "a": 1, "b": 1, ... | 751 | 341 |
import unittest
import pytest
import requests
import webmentiontools
from webmentiontools.request import (
is_successful_response,
request_get_url,
request_head_url,
request_post_url,
USER_AGENT
)
from .endpoints import WEBMENTION_ROCKS_TESTS
class RequestTestCase(unittest.TestCase):
def te... | 1,837 | 560 |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 21 20:19:26 2019
@author: skjerns
"""
from pyedflib.highlevel import *
import os
import gc
import warnings
import ospath #pip install https://github.com/skjerns/skjerns-utils
import numpy as np
import pyedflib #pip install https://github.com/skjerns/pyedflib/archive/custo... | 26,257 | 8,417 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, absolute_import, division
from builtins import map, range, object, zip, sorted
from .context import amplpy
import unittest
import tempfile
import shutil
import os
class TestBase(unittest.TestCase):
def setUp(self):
self.... | 789 | 257 |
#BEGIN_HEADER
#END_HEADER
'''
Module Name:
MetaboliteAtlas
Module Description:
A web-based atlas to liquid chromatography–mass spectrometry (LCMS) data
'''
class MetaboliteAtlas:
#BEGIN_CLASS_HEADER
#END_CLASS_HEADER
def __init__(self, config): #config contains contents of config file in hash or
... | 919 | 253 |
class Config:
"""
General configuration parent class
"""
pass
api_key = 'a493e30f11b147d0ba67b15ca60c5e4c'
SECRET_KEY = '1234567890'
class ProdConfig(Config):
"""
Production
"""
pass
class DevConfig(Config):
"""
development
"""
DEBUG = True
| 302 | 124 |
# vtnil write for Cryptography1 week2 homework
# ppt https://crypto.stanford.edu/~dabo/cs255/lectures/PRP-PRF.pdf
from Crypto.Cipher import AES
from binascii import a2b_hex
from math import ceil
questions = [
{"key": "140b41b22a29beb4061bda66b6747e14",
"ct": "4ca00ff4c898d61e1edbf1800618fb2828a226d160dad0... | 2,179 | 1,200 |
import torch
from torch import nn
class MS_CAM(nn.Module):
def __init__(self, C, H, W, r):
"""
MS_CAM is a module of AFF.
Args:
C: Channel
H: Height
W: Width
r: channel reduction ratio. The channel will be reduced to C/r and back to C.
... | 2,716 | 1,136 |
from threading import Thread
num = 0
def do_sth():
global num
for i in range(1000000):
num += 1
adda()
addb()
def adda():
global num
num += 1
def addb():
global num
num += 1
t1 = Thread(target=do_sth)
t2 = Thread(target=do_sth)
t1.start()
t2.start()
t1.join()
t2.join()... | 343 | 163 |
# -*- coding: utf-8 -*-
# (c) Copyright IBM Corp. 2010, 2020. All Rights Reserved.
# pragma pylint: disable=unused-argument, no-self-use
"""Function implementation"""
import logging
import re
from fn_aws_iam.lib.aws_iam_client import AwsIamClient
from fn_aws_iam.lib.helpers import CONFIG_DATA_SECTION, transform_kwarg... | 3,318 | 999 |
# coding=utf-8
from builtins import input
from optparse import make_option
from django.core import exceptions
from django.utils.encoding import force_str
from django.conf import settings
from django.db.utils import IntegrityError
from django.core.management import call_command
from tenant_schemas.utils import get_ten... | 7,258 | 1,955 |
# 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, ... | 3,565 | 1,596 |
from alpyro_msgs import RosMessage, boolean, int32
class TestRequestResult(RosMessage):
__msg_typ__ = "actionlib/TestRequestResult"
__msg_def__ = "aW50MzIgdGhlX3Jlc3VsdApib29sIGlzX3NpbXBsZV9zZXJ2ZXIKCg=="
__md5_sum__ = "61c2364524499c7c5017e2f3fce7ba06"
the_result: int32
is_simple_server: boolean
| 311 | 162 |
from __future__ import print_function
import sys
sys.path.append('./')
from colorprinter.pycolor import PyColor
from colorprinter.pycolor import cprint
@PyColor('ured')
def printer(string):
a = 1
b = 2
print(str((a + b)**4) + string)
class TestClass(object):
def test_pycolor(self):
printer('ed... | 1,313 | 478 |
# coding: utf-8
from . import main
from flask import render_template, jsonify, flash, request, current_app, url_for, Response, g, abort
@main.route('/')
def index():
return render_template('index.html')
@main.route('/about')
def about_page():
return render_template('about.html')
| 292 | 92 |
import itertools
from pm4py.objects.petri.petrinet import PetriNet
from da4py.main.objects.pnToFormulas import petri_net_to_SAT
from da4py.main.utils import variablesGenerator as vg, formulas
from da4py.main.utils.formulas import Or, And
from da4py.main.utils.unSat2qbfReader import writeQDimacs, cadetOutputQDimacs, r... | 9,918 | 3,527 |
#!/usr/bin/env python3
__doc__ = """Process a dump from the 'Charge Activity Report by Employee
- Project Detail Information' report from Webwise. We only need the
table view because we simply want to extract the fields. For this to
work, we _must_ have the table headers. Those are used as the keys in
the YAML forma... | 6,215 | 2,083 |
#!/usr/bin/env python
# Copyright 2016 The Kubernetes 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... | 4,240 | 1,370 |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import Time... | 25,459 | 7,640 |
from src import mining
from tkinter import filedialog
from PyQt4 import QtGui
dir=filedialog.askdirectory()
direcciones, nomArchivo = mining.path(dir)
cont=mining.coincidencias(direcciones,nomArchivo)
for i in range(len(nomArchivo)):
print(nomArchivo[i],cont[i]) | 269 | 92 |
from src.platform.jboss.interfaces import JINTERFACES
from cprint import FingerPrint
class FPrint(FingerPrint):
def __init__(self):
self.platform = "jboss"
self.version = "7.1"
self.title = JINTERFACES.MM
self.uri = "/console/app/gwt/chrome/chrome_rtl.css"
self.port = ... | 380 | 151 |
from django.db import models
from .utils import get_ip_from_request
class Ip(models.Model):
address = models.GenericIPAddressField(unique=True, db_index=True)
@classmethod
def get_or_create(cls, request):
raw_ip = get_ip_from_request(request)
if not raw_ip:
return None
... | 455 | 147 |
#! /usr/bin/env python3
# __author__ = "Praneesh Kataru"
# __credits__ = []
# __version__ = "0.2.1"
# __maintainer__ = "Praneesh Kataru"
# __email__ = "pranuvitmsse05@gmail.com"
# __status__ = "Prototype"
#
# Responsible for starting the required number of processes and threads
import threading
i... | 1,640 | 523 |
from binary_tree.m_create_from_pre_in import BinaryTree
class TestBinaryTree:
def test_lc_data_1(self):
bt = BinaryTree()
preorder = [3, 9, 20, 15, 7]
inorder = [9, 3, 15, 20, 7]
ans = bt.buildFromPreInOrder(preorder=preorder, inorder=inorder)
assert ans.val == 3
a... | 1,267 | 525 |
from collections import Counter
from utils import read_bits
def run_part_one():
print("--------------------------------")
print("Advent of Code 2021 - 3 - Part 1")
bits = read_bits('input.txt')
gamma_rate = ""
epsilon_rate = ""
for x in range(len(bits[0])):
relevant_bits = get_relevan... | 1,111 | 404 |