text string | size int64 | token_count int64 |
|---|---|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, codecs
#usage: from frogatto's base folder, run:
#utils/text_width_check.py po/(desired file, with a "po" or "pot" extension) [optional:max width]
#e.g.:
#utils/text_width_check.py po/frogatto.pot 360
global MAXWIDTH
MAXWIDTH = 360
def main(catalog):
if ca... | 2,902 | 1,232 |
import numpy as np
from .sparse import normalize as _normalize
from .sparse import binarize as _binarize
def compute_dense_features(features, word_embeddings, method='wt_sum',
normalize=True, binarize=False):
"""
Compute dense features as per given sparse features and word embedding... | 1,228 | 361 |
# The MIT License
# Copyright (c) 2017 OpenAI (http://openai.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 us... | 2,381 | 830 |
num=0
for i in range(len(s)-2):
if(s[i:i+3]=='bob'):
num+=1
print "Number of times bob occurs is:",num
| 115 | 52 |
from pygments.lexer import RegexLexer
from pygments.token import *
import re
__all__ = ['FloorplanLexer']
class FloorplanLexer(RegexLexer):
name = 'Floorplan'
aliases = ['floorplan']
filenames = ['*.flp']
flags = re.MULTILINE | re.UNICODE
reserved = ( 'ptr', 'flags', '_', 'Counter', 'bit'
, '... | 1,451 | 578 |
from django.db import models
global_max_length = 200
class FilesystemStats(models.Model):
device = models.CharField(max_length = global_max_length)
used_perc = models.DecimalField(max_digits = 5, decimal_places = 2)
size = models.IntegerField()
used = models.IntegerField()
avail = models.IntegerFi... | 1,266 | 412 |
import asyncio
import concurrent.futures
from datetime import datetime, timedelta, timezone
from logging import getLogger
from typing import Awaitable, Callable, Iterator, Optional, Tuple, TypeVar
import grpc
from google.cloud import bigquery
import ib_insync
from blotter import blotter_pb2, blotter_pb2_grpc, request... | 8,816 | 2,617 |
import calendar
import json
import logging
from urllib.parse import urlencode
from django.core.urlresolvers import NoReverseMatch, reverse
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
from ralph.dashboards.helpers import encode_params, normalize_value
logger = lo... | 5,859 | 1,698 |
#coding=utf-8
'''
Created on 2013-3-8
@author: pyroshow
'''
from PySide.QtGui import *
from Models.LocalDB import *
from datetime import datetime
class ModifyAliasNotes(QDialog):
def __init__(self, sess, UUID, Alias, Notes, parent =None):
QDialog.__init__(self, parent)
self.... | 2,094 | 651 |
from timeit import default_timer
import requests
def load_data(delay):
print(f'Starting {delay} second timer')
text = requests.get(f'https:// httpbin.org/delay/{delay}').text
print(f'Completed{delay}second timer ')
return text
def run_demo():
start_time = default_timer()
two_data = load_data(... | 496 | 168 |
class SpaceAge:
EARTH_PERIOD = 31557600
MERCURY_PERIOD = 0.2408467 * EARTH_PERIOD
VENUS_PERIOD = 0.61519726 * EARTH_PERIOD
MARS_PERIOD = 1.8808158 * EARTH_PERIOD
JUPITER_PERIOD = 11.862615 * EARTH_PERIOD
SATURN_PERIOD = 29.447498 * EARTH_PERIOD
URANUS_PERIOD = 84.016846 * EARTH_PERIOD
NE... | 1,188 | 541 |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os
from setuptools import setup
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'requirements.txt')) as f:
requirements = f.readlines()
setup(
name="pyctf",
version="0.0",
packages=['pyctf'],
package_dir={'pyctf'... | 511 | 191 |
# 3rd Pipe Handle (2111019) | Home of the Missing Alchemist (261000001)
undergroundStudy = 3339
if sm.hasQuest(undergroundStudy) or sm.hasQuestCompleted(undergroundStudy):
# The dummy quest ID 7063 will be used to determine if the pipes are being activated in the right order
# This needs to be activated after... | 664 | 238 |
from pathlib import Path
from unittest.mock import call
from unittest.mock import MagicMock
from unittest.mock import patch
from ibutsu_server.test import BaseTestCase
XML_FILE = Path(__file__).parent / "res" / "empty-testsuite.xml"
XML_FILE_COMBINED = Path(__file__).parent / "res" / "combined.xml"
class TestImpor... | 3,501 | 1,105 |
# -*- coding: UTF-8 -*-
from git import Repo
import shutil
import os
import glob
import re
import yaml
def get_yaml(f):
pointer = f.tell()
if f.readline() != '---\n':
f.seek(pointer)
return ''
readline = iter(f.readline, '')
readline = iter(readline.next, '---\n')
return ''.join(readline)
def suppri... | 3,078 | 1,188 |
#!/usr/bin/env python
#
# SPDX-FileCopyrightText: 2019-2022 Espressif Systems (Shanghai) CO LTD
# SPDX-License-Identifier: Apache-2.0
import os
import subprocess
import sys
from unittest import TestCase, main, mock
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
try:
import... | 8,741 | 2,651 |
from django.urls import path
from django.urls import include
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
urlpatterns = [
path('', include(router.urls)),
path('user/', views.UserView.as_view()),
path('<str:token>/client/', views.ClientListView.as_view()),
p... | 481 | 154 |
# 21. rewrite the program from steps 18 to 20 so that it works for reverse complement (i.e. the user types the strings “ATTCGT” and “AAGGAT” and she gets the previous example as result)
#18. print 3 rows: the first and the third for the sequences,
#the second one should contain “|” if the bases are complementary, “X” ... | 938 | 351 |
from src import ma
from src.models import Client
from src.models import FlavorItems
from marshmallow import fields
class OrdersSchema(ma.Schema):
class Meta:
model = FlavorItems
fields = ('item_id', 'flavor_id')
class ClientSchema(ma.Schema):
orders = fields.Nested(OrdersSchema, many=True)
... | 494 | 153 |
"""
Django settings for nugis project.
Generated by 'django-admin startproject' using Django 2.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
impo... | 5,059 | 1,810 |
from rdflib import Namespace, BNode, Literal, URIRef
from rdflib.graph import Graph, ConjunctiveGraph
from rdflib.plugins.memory import IOMemory
ns = Namespace("http://love.com#")
mary = URIRef("http://love.com/lovers/mary#")
john = URIRef("http://love.com/lovers/john#")
cmary=URIRef("http://love.com/lovers/mary#")
... | 929 | 364 |
#!/usr/bin/env python3
from flask import Flask
app = Flask(__name__)
@app.route("/hello-world")
def hello():
return "Hello world!"
if __name__ == "__main__":
from gevent.pywsgi import WSGIServer
http_server = WSGIServer(('0.0.0.0', 5000), app)
http_server.serve_forever()
| 297 | 116 |
"""Tools for Symmetric ciphers common to all the backends."""
from __future__ import annotations
import hmac
import typing
from functools import partial
from .. import base, exc
class FileCipherWrapper(base.BaseAEADCipher):
"""
Wraps ciphers that support BaseAEADCipher interface and provides
file encry... | 8,158 | 2,385 |
"""
datos de entrada
variable 1--->a--->int
variable 2--->b--->int
variable 3--->c--->int
variable 4--->d--->int
"""
#entrada
a=int(input("ingrese variable 1: " ))
b=int(input("ingrese variable 2: "))
c=int(input("ingrese variable 3: "))
d=int(input("ingrese variable 4: "))
#caja negra
if (d==0):
re=(a-c)**2
elif(d... | 380 | 177 |
from flask import Flask ,jsonify ,abort ,make_response ,request
from flask_restful import Resource, Api
#from ./estimator import *
app = Flask(__name__)
api = Api(app)
class HelloWorld(Resource):
def get(self):
return {'hello': data}
api.add_resource(HelloWorld, '/api/v1/on-covid-19')
todos = {}
class ... | 1,852 | 683 |
import clr
def process_input(func, input):
if isinstance(input, list): return [func(x) for x in input]
else: return func(input)
def journalDirectiveValues(jdirective):
if jdirective.__repr__() == 'JournalDirective': return jdirective.Values
else: return []
OUT = process_input(journalDirectiveValues,IN[0]) | 314 | 106 |
import os
import pickle
import subprocess
import dgl
from dgl.data import DGLDataset
class PathwayDataset(DGLDataset):
"""
A class that inherits from DGLDataset and extends its functionality
by adding additional attributed and processing of the graph
accordingly.
Attributes
----------
ro... | 2,350 | 720 |
word = input()
reversed_word = ""
for i in range(len(word) - 1, - 1, -1):
reversed_word += word[i]
print(reversed_word)
| 124 | 55 |
class Binomial:
def __init__(self, xmax, ymax):
self.A = [ [None] * ymax for i in range(xmax) ]
self.trace = False
def setTrace(self, trace):
self.trace = trace
def b(self, x , y ):
# runs O(x*y) time
A = self.A
trace = self.trace
for i in range ( x ):
for j in range ( y ):
if ( A[i][j]... | 1,024 | 568 |
import ctypes
import os
import re
import subprocess
QalcExchangeRatesUpdater = ctypes.cdll.LoadLibrary(
os.path.join("/".join(__name__.split("."))
if __name__ != "__main__" else ".",
"qalc-update-exchange-rates.so")
)
qalc_update_exchange_rates = QalcExchangeRatesUpdater._Z20upda... | 957 | 423 |
# -*- coding: utf-8 -*-
import pytest
from django.core.urlresolvers import reverse
from autobreadcrumbs.resolver import PathBreadcrumbResolver
# Autodiscovering is disabled since it allready have be executed
# previously, see warning from "test_004_autodiscover.py"
# from autobreadcrumbs.discover import autodiscover... | 2,538 | 936 |
import aiohttp
import dateutil.parser
import json
from datetime import datetime, timezone, timedelta
from enum import Enum
from . import exceptions as MixerExceptions
from .objects import MixerUser, MixerChannel
class RequestMethod(Enum):
GET = 0
POST = 1
class MixerAPI:
API_URL = "https://mixer.com/api... | 7,480 | 2,152 |
#!/usr/bin/env python
###########################################################################
# This software is graciously provided by HumaRobotics
# under the Simplified BSD License on
# github:
# HumaRobotics is a trademark of Generation Robots.
# www.humarobotics.com
# Copyright (c) 2015, Generation Robo... | 3,983 | 1,291 |
from typing import List
# Define directions
DIAGONOAL = (-1, -1)
UP = (0, -1)
LEFT = (-1, 0)
def trace_table(backtrack_table, seq1, seq2) -> List[str]:
"""Trace back the backtrack table to find the longest common subsequence"""
i, j = len(seq1)-1, len(seq2)-1
lcs = []
while i >= 0 and j >= 0:
... | 1,647 | 651 |
from __future__ import unicode_literals
from .. import Provider as PersonProvider
class Provider(PersonProvider):
formats_female = (
'{{first_name_female}} {{last_name}}',
'{{first_name_female}} {{last_name}}',
'{{first_name_female}} {{last_name}}',
'{{first_name_female}} {{last_na... | 1,488 | 569 |
"""File that summarizes all key results.
To train networks in a specific experiment, run in command line
python main.py --train experiment_name
To analyze results from this experiment
python main.py --analyze experiment_name
To train and analyze all models quickly, run in command line
python main.py --train --analyze... | 1,787 | 527 |
from os.path import exists as path_exists
from shutil import rmtree
from tempfile import mkdtemp
from typing import Optional
class TemporaryDirectory:
"""Create a temporary directory using :func:`tempfile.mkdtemp`.
The resulting object can be used as a context manager. For example:
>>> with Tempora... | 1,564 | 432 |
import shutil
from dataclasses import dataclass
from enum import Enum, auto
from pathlib import Path
import pytest
from pytest_cases import fixture_union
class GsfVersion(Enum):
V03_08 = auto()
@dataclass(frozen=True)
class GsfDatafile:
gsf_version: GsfVersion
path: Path
num_beams: int
GSF_03_08_... | 1,216 | 498 |
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Provides the web interface for adding and removing test owners."""
import json
from google.appengine.api import users
from dashboard import request_han... | 3,041 | 943 |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | 1,604 | 472 |
# coding=utf-8
"""
Copyright 2012 Ali Ok (aliokATapacheDOTorg)
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 ... | 5,775 | 1,803 |
class Item:
def __init__(self, x, y):
self.x = x
self.y = y
self.char = 'X'
self.color = 1
self.mine = None
self.type = 'thing'
def add_to_mine(self, mine):
self.mine = mine
def is_attractive_to(self, creature: 'Creature'):
return False
... | 423 | 143 |
# create dictionary
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
# assign variable to value in dictionary
new_points = alien_0['points']
print(f'You just earned {new_points} points!')
print(alien_0)
# adding new key-value pair
alien_0['x_position'] = 0
alien_0['y_position... | 4,173 | 1,494 |
import cooper_item
import logging # https://docs.python.org/3/library/logging.html
import pprint
import table_mod as tables
from money import Money
# create_item = cooperidge_item.CooperageItem
# https://docs.python.org/3/library/logging.html#logrecord-attributes
#fmt = '%(asctime)s | %(levelname)s ... | 6,936 | 2,360 |
"""
Python Is Easy course @Pirple.com
Homework Assignment #3: "If" Statements
Patrick Kalkman / patrick@simpletechture.nl
Details:
Create a function that accepts 3 parameters and checks for equality between
any two of them.
Your function should return True if 2 or more of the parameters are equal,
and false is no... | 1,667 | 553 |
from __future__ import absolute_import, unicode_literals
from django.apps import AppConfig
class TuiuiuTestsAppConfig(AppConfig):
name = 'tuiuiu.tests.modeladmintest'
label = 'test_modeladmintest'
verbose_name = "Test Tuiuiu Model Admin"
| 253 | 86 |
from distutils.core import setup
setup(name='fc-view',
version=0.1,
packages=[''],
package_dir={'': '.'},
install_requires=['numpy', 'scipy'],
py_modules=['opt_sign_flip', 'mat_reorder'])
| 219 | 79 |
import os
import sys
import time
import argparse
import subprocess as sp
script_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(script_dir, "modules"))
from cparser import Parser
from scanner import Scanner, SymbolTableManager
from semantic_analyser import SemanticAnalyser
from code_... | 4,201 | 1,264 |
from flask import render_template, request, redirect, url_for, abort
from . import main
from flask_login import login_required, current_user
from ..models import User, PitchCategory, Pitches, Comments
from .forms import UpdateProfile, PitchForm, CommentForm, CategoriesForm
from .. import db, photos
@main.route('/')
d... | 4,902 | 1,623 |
from typing import List
from etk.extraction import Extraction
from etk.extractor import Extractor, InputType
from enum import Enum, auto
from langid import classify
from langdetect import detect
class LanguageIdentificationExtractor(Extractor):
"""
Identify the language used in text, returning the identifier... | 1,944 | 516 |
from django.conf.urls import include, url
from django.contrib import admin
from django.template.response import TemplateResponse
from django.views.generic import TemplateView, RedirectView
from django.contrib.staticfiles.views import serve
from shifts import settings
urlpatterns = [
url(r'^$', TemplateView.as_view... | 859 | 274 |
class CoronaConstants:
# Disease constants
latent_period = 4 # nu
infectious_period = 5 # omega
fraction_tested = 1/15 # alpha
contacts_average = 13.85 # c
fraction_local_contacts = 0.5 # rho
basic_reproduction_number = 1.25
transmission_pr... | 1,747 | 580 |
from math import sqrt
from typing import List
from cachetools import cached, LFUCache
from classes.product import Product
from util.enums import BridgeOption
@cached(cache=LFUCache(2048))
def theoretical_bridge(mode: str, value: int):
bridge_list = []
d_value = 50
bridge_input = value
if mode in (B... | 2,273 | 1,164 |
"""
Support cell types defined in 9ML with NEURON.
Requires the 9ml2nmodl script to be on the path.
Classes:
NineMLCell - a single neuron instance
NineMLCellType - base class for cell types, not used directly
Functions:
nineml_cell_type - return a new NineMLCellType subclass
Constants:
NMODL... | 3,388 | 1,091 |
from time import *
def ifOrTuple():
boolVal = False
t = time()
for i in range(10000000):
"test" if boolVal else "testFalse"
print("Average: {}".format(time() - t))
combined = 0.0
t = time()
for i in range(10000000):
("testFalse", "test")[boolVal]
print("Average: {}".for... | 693 | 277 |
"""fly specific views
"""
import os
from flask import render_template, request, flash, url_for, redirect, \
send_from_directory, session
from functools import wraps
from flask_login import current_user, login_user, login_required, logout_user
import datajoint as dj
import pandas as pd
from loris import config
fro... | 5,404 | 1,744 |
try:
import multiprocessing
except ImportError:
pass
from setuptools import setup
import postmon
setup(
name='postmon',
version=postmon.__version__,
description='Postmon service wrapper',
url='http://github.com/PostmonAPI/postmon-python',
author='Iuri de Silvio',
author_email='iurisi... | 990 | 309 |
class DemoException(Exception):
'''A kind of exception to demonstrate'''
def demonstrate_exc_finally():
print('-> coroutine started')
try:
while True:
try:
x = yield
except DemoException:
print('*** DemoExcepetion handled. Continuining...')
... | 555 | 169 |
"""
Testcases for the CoreFoundation wrappers introduced in 1.5
"""
import objc
from PyObjCTools.TestSupport import *
import re
import sys
from PyObjCTest.corefoundation import *
# registerCFSignature(name, encoding, typeId [, tollfreeName]) -> type
CFUUIDRef = objc.registerCFSignature(
"CFUUIDRef",
... | 3,031 | 1,022 |
import discord
import logging
# Set up the logging module to output diagnostic to the console.
logging.basicConfig()
client = discord.Client()
client.login('email', 'password')
if not client.is_logged_in:
print('Logging in to Discord failed')
exit(1)
@client.event
def on_ready():
print('Connected!')
... | 555 | 179 |
#!/usr/bin/env python
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License");... | 8,673 | 2,444 |
def get_multiples_of(num_list, n):
'''
This function returns the number of numbers in num_list that are multiples of n.
If there is no number in num_list that is a multiple of n, the function returns 0.
Parameters:
- num_list, a list of positive integers; list may be empty
- n, ... | 640 | 208 |
from django import forms
from .models import Topic, Post
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['topic_name']
labels = {'topic_name': ''}
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['text']
labels = {'text':... | 392 | 120 |
# coding: utf-8
"""
NiFi Rest API
The Rest API provides programmatic access to command and control a NiFi instance in real time. Start and stop processors, monitor queues, query provenance data, and more. Each endpoint below includes a description, ... | 8,230 | 2,169 |
from setuptools import setup, find_packages
setup(
name="df2numpy",
version="1.1.0",
description="A simple tool for quick transformation from pandas.DataFrame to numpy.array dataset containing some utilities",
long_description='./README.md',
author="Masaki Kitayama",
author_email="kitayama-mas... | 528 | 174 |
#!/usr/bin/env python
# IMPORT
from __future__ import print_function
import sys
import os
import time
from abc import abstractmethod
from blue_st_sdk.manager import Manager
from blue_st_sdk.manager import ManagerListener
from blue_st_sdk.node import NodeListener
from blue_st_sdk.feature import FeatureLi... | 11,726 | 3,305 |
import attr
from vec import Vector2
from adr.Components.Aerodynamic import AerodynamicSurface
@attr.s(auto_attribs=True)
class RectangularAerodynamicSurface(AerodynamicSurface):
type: str = 'rectangular_aerodynamic_surface'
span: float = None
chord: float = None
@property
def area(self):
... | 540 | 187 |
import math
import numpy as np
from multiprocessing import Pool
from scipy.spatial import cKDTree
from scipy.linalg import orth
from scipy.linalg.interpolative import svd as rsvd
from scipy.sparse import issparse
from numba import jit, float32, int32, int8
from . import settings
from .irlb import lanczos
@jit(float3... | 9,934 | 3,765 |
#coding: utf-8
import re
import requests
from bs4 import BeautifulSoup
from .generic_utils import str_strip, handleKeyError
def str2soup(string):
"""Convert strings to soup, and removed extra tags such as ``<html>``, ``<body>``, and ``<head>``.
Args:
string (str) : strings
Returns:
bs4.Be... | 15,408 | 4,652 |
# -*- coding: utf-8 -*-
# Copyright 2017 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# This module is not automatically loaded by the `cros` helper. The filename
# would need a "cros_" prefix to make that happen. ... | 8,444 | 2,743 |
#!/usr/bin/env python
"""The setup script."""
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
requirements = [
{%- if cookiecutter.command_line_interface|lower == 'click' %}
'Click>=7.0',
{%- endif %}
]
test_requirements = [
{%- if c... | 2,176 | 720 |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 18 11:42:40 2018 by Yongrui Huang
Modified on Tue Oct 29th 16:16:50 2019 by Ruixin Lee
@author: Yongrui Huang
"""
import sys
sys.path.append('../')
from data_collection_framework.util import record
import configuration
import os
import platform
import time
import ctypes
... | 8,298 | 2,778 |
import os
from glob import glob
from shutil import copyfile
from math import floor
import sys
import threading
# from download_parameter_files import download_parameter_files
def split_file(num_lines, num_files, raw, tmp):
smallfile = None
file_num = 0
with open(raw) as bigfile:
for lineno, line in enumerate(bigf... | 3,198 | 1,249 |
import requests, re
import numpy as np
u='https://api.stackexchange.com/2.2/similar'
tag_arr=[]
def clean_text(text):
text = str(text)
text = re.sub(r"[^\w]", " ", text.lower())
return text
# for i in range(1,28):
for i in range(1,2):
print(i)
p={'page':str(i), 'pagesize':'100','fromdate':'138853440... | 926 | 370 |
import yfinance as yf
def extraer_datos_yahoo(stocks, start='2015-01-01', end='2020-04-30'):
'''
Funcion para extraer precios al cierre de las acciones mediante yahoo finance de 2015-01-01 a 2020-04-30
params: stocks lista de acciones de las cuales se desea obtener el precio
start fecha inicial... | 832 | 329 |
import collections
class Node:
def __init__(self, data, parent):
self.parent = parent
self.data = data
self.children = {}
def __contains__(self, item):
return item in self.children
def __getitem__(self, item):
return self.children[item]
def __setitem__(self, ... | 1,244 | 337 |
import csv
import matplotlib.pyplot as plt
import json
combine = []
def norm_name(name):
i = len(name) - 1
while i > -1 and not('a' <= name[i] <= 'z' or 'A' <= name[i] <= 'Z'):
i -= 1
return name[0:i+1]
def percentile(d, min, max):
if ((min <= d <= max) == False and (max <= d <= min) == False):
return 0
ret... | 4,530 | 2,116 |
"""
Tests the biodata module
"""
import unittest
import candig.server.datamodel.datasets as datasets
import candig.server.exceptions as exceptions
import candig.server.datamodel.bio_metadata as bioMetadata
import candig.schemas.protocol as protocol
class TestIndividuals(unittest.TestCase):
"""
Tests the In... | 2,786 | 811 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.colors import ListedColormap
from . import common
def v_loc(x):
return 40*np.log10(x + 1)
def x_loc(x):
return 40*(np.log10(x) + 1)
def main(debug=False):
thr_v = 25.0
thr_x = lambda v: 1... | 4,580 | 2,096 |
import math
import numpy as np
import traitlets
from OpenGL import GL
from yt_idv.scene_components.base_component import SceneComponent
from yt_idv.scene_data.particle_positions import ParticlePositions
class ParticleRendering(SceneComponent):
name = "particle_rendering"
data = traitlets.Instance(ParticlePo... | 1,660 | 564 |
from scripts import custom
def test_map_priority():
raw_input_1 = "0"
output_1 = custom.map_priority(raw_input_1)
assert output_1 == "stat"
raw_input_2 = 0
output_2 = custom.map_priority(raw_input_2)
assert output_2 == "stat"
raw_input_3 = "1"
output_3 = custom.map_priority(raw_inpu... | 1,078 | 436 |
import argparse
from os import path
from uniplot import plot
from . import parse
from . import analysis
file = open("location.txt", "r")
LOC = file.read()
file.close()
def file_location_configuration(args):
"""Allows to set the location from where to get the data file"""
open("location.txt", "w").close()
... | 3,332 | 1,010 |
import pytest
from novelsave_sources import models as sm
from novelsave.core import dtos
from novelsave.utils.adapters import SourceAdapter
@pytest.fixture
def source_adapter() -> SourceAdapter:
return SourceAdapter()
def test_novel_to_internal(source_adapter):
test_novel = sm.Novel(
title="title",... | 2,709 | 808 |
# importing info from views and the path function
from django.urls import path
from . import views
# defining endpoints
urlpatterns = [
path('', views.index, name='index'),
path('appInfo/', views.index, name='appInfo')
] | 233 | 71 |
# Generated by Django 2.1.5 on 2019-01-25 16:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("data_refinery_common", "0009_es_cache"),
]
operations = [
migrations.AddField(
model_name="dataset",
name="sha1",
... | 593 | 193 |
#!/usr/bin/env python3
from sys import stderr
from os import environ
import yaml, cgi
from citematic_coins import coins
bib_path = environ['DAYLIGHT_BIB_PATH']
with open(bib_path) as o:
database = yaml.load(o)
print('''<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Bibliography ... | 570 | 225 |
import logging
from Queue import Empty
from multiprocessing import Process, Event
from multiprocessing import Queue as mQ
from threading import Thread
from Queue import Queue as Q
from time import sleep
import praw
from wsgi.engine import get_reposts_count
from wsgi.scripts import GET_USER_AGENT_R
from wsgi.scripts.... | 4,694 | 1,649 |
from typing import List, Any
import inspect
import importlib
import sys
try:
# First attempt using convention of build directory
from pathlib import Path
wrap_itk_pth: Path = Path(__file__).parent / "WrapITK.pth"
if not wrap_itk_pth.is_file():
print(
"ERROR: itk_generate_pyi.py mu... | 2,955 | 908 |
from flask import jsonify
def make_response(status, message):
raw_response = {
"status": status
}
if status == 200:
raw_response["results"] = message
else:
raw_response["message"] = message
resp = jsonify(raw_response)
resp.status_code = status
return resp
| 314 | 96 |
import math
import os
import random
import logging
import copy
import queue
from pygame.math import Vector2
from gobigger.agents.base_agent import BaseAgent
# from .base_agent import BaseAgent
tabu_size=1
position_size=11
class BotAgent(BaseAgent):
'''
Overview:
A simple script bot
... | 33,445 | 11,402 |
from setuptools import find_packages
from setuptools import setup
setup(
name="dummyslurm",
license="MIT",
author="Tom de Geus",
author_email="tom@geus.me",
description="Dummy slurm installation",
long_description="Dummy slurm installation",
keywords="SLURM",
url="https://github.com/tde... | 682 | 230 |
# Original by /u/Oran9eUtan
# https://redd.it/bq45gc
# Converted to Python by Peppermint#2241
each_player = ongoing_each_player(all, all)
n_allowed_heroes = count_of(allowed_heroes(event_player))
interact_pressed = is_button_held(event_player, interact)
eye_pos = eye_position(event_player)
rule "Reset menu positions ... | 3,576 | 1,497 |
""" Orbital Mechanics for Engineering Students Problem 1.20
Question:
Numerically solve the second order-differential equation
t*yDDot + t^2*yDot - 2*y = 0
for y at t = 4, if the initial conditions at t=1 are:
- y = 0
- yDot = 1
Written by: J.X.J. Bannwarth
"""
import numpy as np
import matplotlib... | 948 | 437 |
from initialize import initialize
import timeit
import numpy as np
import computations
### STOCHASTIC GRADIENT DESCENT
def sgd_entropic_regularization(a, b, M, reg1, reg2, numItermax, lr, maxTime):
r'''
Compute the sgd algorithm with one-sized batches to solve the regularized discrete measures
ot dual estim... | 6,401 | 2,218 |
# from model_mommy import mommy
# from django.test import TestCase
# from rest_framework_jwt.serializers import JSONWebTokenSerializer
# from boilerplate_app.models import User
# from boilerplate_app.serializers import UserListSerializer, UserCreateSerializer
# class APITests(TestCase):
# def test_list_user(... | 8,798 | 2,817 |
import torch
def postprocess(img_out):
return (img_out.permute(0,2,3,1)* 127.5 + 128).clamp(0, 255).to(torch.uint8).cpu().numpy()
def flicker(frames, f = 30):
frames[::f]*=0
frames[2::f]*=0
frames[1::f]=255-frames[1::f]
return frames
def latent_walk(w,num=20, width=1):
lin = torch.linspace(0,width,num)[:... | 984 | 468 |
"""igvm - Exceptions
Copyright (c) 2018 InnoGames GmbH
"""
class IGVMError(Exception):
pass
class ConfigError(IGVMError):
"""Indicates an error with the Serveradmin configuration."""
pass
class HypervisorError(IGVMError):
"""Something went wrong on the hypervisor."""
pass
class NetworkError... | 1,853 | 545 |
import unittest
import numpy as np
import cPickle as pickle
import os
from wakeexchange.OptimizationGroups import AEPGroup
from fusedwake.WindTurbine import WindTurbine
from fusedwake.WindFarm import WindFarm
from windIO.Plant import WTLayout, yaml
from openmdao.api import Problem
class TestFlorisWrapper(unittest.... | 16,275 | 6,031 |
import argparse
def parse_args():
# parse args and config and redirect to train_sp
parser = argparse.ArgumentParser(
description="Synthesize with acoustic model & vocoder")
# acoustic model
parser.add_argument(
'--am',
type=str,
default='fastspeech2_csmsc',
choi... | 3,045 | 1,006 |
import numpy as np
def test_vector():
from alg3dpy.line import asline
from alg3dpy.vector import asvector
from alg3dpy.plane import plane2lines
xaxis = asvector([1, 0, 0])
yaxis = asvector([0, 1, 0])
zaxis = asvector([0, 0, 1])
yaxisneg = asvector([0, -1, 0])
assert xaxis.anglewith(yaxi... | 1,054 | 455 |