text string | size int64 | token_count int64 |
|---|---|---|
import csv
from math import ceil
import cv2
import numpy as np
from sklearn.model_selection import train_test_split
import sklearn
from keras.models import Sequential
from keras.layers import Flatten, Dense, Lambda, BatchNormalization, Dropout, Cropping2D
from keras.layers.convolutional import Convolution2D
from keras... | 4,232 | 1,281 |
"""init module for natcap.invest."""
import dataclasses
import logging
import os
import sys
import pkg_resources
LOGGER = logging.getLogger('natcap.invest')
LOGGER.addHandler(logging.NullHandler())
__all__ = ['local_dir', ]
try:
__version__ = pkg_resources.get_distribution(__name__).version
except pkg_resources... | 8,854 | 2,992 |
# -*- coding: utf-8 -*-
# pylint: disable=E1101
import logging
import os
import operator
from binascii import hexlify
from pyramid.security import DENY_ALL
from pyramid.security import Everyone
from pyramid.security import Allow
from pyramid.settings import asbool
from pyramid_mailer.message import Message
from s... | 18,507 | 5,092 |
import math
import sys
from fractions import Fraction
from random import uniform, randint
import decimal as dec
def log10_floor(f):
b, k = 1, -1
while b <= f:
b *= 10
k += 1
return k
def log10_ceil(f):
b, k = 1, 0
while b < f:
b *= 10
k += 1
return k
def log10_... | 5,013 | 2,174 |
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="example-pkg-vanderbeck", # Replace with your own username
version="0.0.1",
author="Lindsay Vanderbeck",
author_email="lindsay.vanderbeck@live.ca",
description="A small ex... | 876 | 286 |
import os
import random
import sys
import time
from typing import ClassVar, List
from urllib.parse import urlsplit
import attr
from bs4 import BeautifulSoup
import requests
# Epsilon value
EPS = sys.float_info.epsilon
def req(url, verbose=False):
"""Make a request, sleeping for a random period of time afterwar... | 1,820 | 580 |
"""
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
APP = ["quick-gray.py"]
APP_NAME = "QuickGrayscale"
DATA_FILES = ["status-bar-logo.png", "status-bar-logo--dark.png"]
OPTIONS = {
"iconfile":"./assets/gq.icns",
"plist": {
"CFBundl... | 761 | 277 |
# https://deeplearningcourses.com/c/deep-learning-gans-and-variational-autoencoders
# https://www.udemy.com/deep-learning-gans-and-variational-autoencoders
# a simple script to see what StochasticTensor outputs
from __future__ import print_function, division
from builtins import range
# Note: you may need to update yo... | 1,074 | 384 |
"""
Description: A Python module to use easily the osu!api V1.
Author: LostPy
License: MIT
Date: 2021-01-11
"""
import requests as req
import json
from . import from_json
base_url ='https://osu.ppy.sh/api'
urls = {
'beatmaps': base_url + '/get_beatmaps?',
'user': base_url + '/get_user?',
'scores': base_url + '/get... | 3,809 | 1,533 |
import glob
import matplotlib.pyplot as plt
import numpy as np
import sys
plt.ion()
data_files = list(glob.glob(sys.argv[1]+'/mnist_net_*_train.log'))
valid_data_files = list(glob.glob(sys.argv[1]+'/mnist_net_*_valid.log'))
for fname in data_files:
data = np.loadtxt(fname).reshape(-1, 3)
name = fname.split('/')[... | 572 | 247 |
from props.dependency_tree.definitions import subject_dependencies, ARG_LABEL,\
object_dependencies, SOURCE_LABEL, domain_label, POSSESSED_LABEL,\
POSSESSOR_LABEL
class Proposition:
def __init__(self,pred,args,outputType):
self.pred = pred
self.args = args
self.outputType = ou... | 2,395 | 786 |
from flask import Flask, request, render_template, session, redirect, url_for, flash
from flask_script import Manager, Shell
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import Required
from fla... | 4,263 | 1,461 |
# Copyright (c) 2015, Matt Layman
import os
import unittest
from tap.runner import TAPTestResult
class FakeTestCase(unittest.TestCase):
def runTest(self):
pass
def __call__(self, result):
pass
class TestTAPTestResult(unittest.TestCase):
@classmethod
def _make_one(cls):
#... | 2,799 | 846 |
# Weird Algorithm
# Consider an algorithm that takes as input a positive integer n. If n is even, the algorithm divides it by two, and if n is odd, the algorithm multiplies it by three and adds one. The algorithm repeats this, until n is one.
n = int(input())
print(n, end=" ")
while n != 1:
if n % 2 == 0:
... | 390 | 132 |
"""Simple Benchmark of Reading Small Files From Disk
Usage:
benchmark.py (-h | --help)
benchmark.py init COUNT
benchmark.py (create|test) (flat|two_level|four_level|memmap) [--size=<size>]
Arguments:
COUNT The number of files to be created. Supports scientific notation (e.g. 3e5).
Options:
-h --help ... | 5,868 | 2,167 |
from pyblish import api
import openpype.api as pype
class IntegrateVersionUpWorkfile(api.ContextPlugin):
"""Save as new workfile version"""
order = api.IntegratorOrder + 10.1
label = "Version-up Workfile"
hosts = ["hiero"]
optional = True
active = True
def process(self, context):
... | 568 | 174 |
import sys, os
filename = os.path.join(os.path.dirname(__file__), '..')
sys.path.insert(1, filename)
from zoomapi import OAuthZoomClient
import json
from configparser import ConfigParser
from pyngrok import ngrok
parser = ConfigParser()
parser.read("bots/bot.ini")
client_id = parser.get("OAuth", "client_id")
client_s... | 1,321 | 444 |
#!/usr/bin/python
# encoding: utf-8
from collections import Counter
from gist import create_workflow
from pprint import pprint as pp
import sys
import workflow
from workflow import Workflow, web
from workflow.background import run_in_background, is_running
def main(wf):
arg = wf.args[0]
wf.add_item(u"Set tok... | 476 | 165 |
from howtrader.app.cta_strategy import (
CtaTemplate,
StopOrder,
TickData,
BarData,
TradeData,
OrderData,
BarGenerator,
ArrayManager
)
from howtrader.trader.constant import Interval
from datetime import datetime
from howtrader.app.cta_strategy.engine import CtaEngine, EngineType
import ... | 2,699 | 1,159 |
T = int(input())
if T > 100:
print('Steam')
elif T < 0:
print('Ice')
else:
print('Water')
| 102 | 48 |
PSQL_CONNECTION_PARAMS = {
'dbname': 'ifcb',
'user': '******',
'password': '******',
'host': '/var/run/postgresql/'
}
DATA_DIR = '/mnt/ifcb'
| 159 | 70 |
import argparse
import glob
import os
import random
import re
from dataclasses import dataclass
from functools import partial
from math import ceil
from typing import List, Optional
import numpy as np
import torch
from torch.optim.lr_scheduler import ReduceLROnPlateau
from tqdm import tqdm
import util
tqdm.monitor_i... | 15,702 | 4,955 |
import cv2
import argparse
import numpy as np
def gray2bgr565(input_file, output_file):
img = np.fromfile(input_file, dtype=np.uint16)
img = img.reshape(480, 640)
# img = cv2.imread(input_file, cv2.IMREAD_ANYDEPTH)
ratio = np.amax(img) / 256
img8 = (img / ratio).astype('uint8')
img8 = cv2.cvtCo... | 780 | 300 |
from django.shortcuts import render,redirect
from .forms import UserForm,RoleForm,RightsForm
from .models import UserTable,UserRole,UserRights
def show_users(request):
if request.method == "GET":
users = list(UserTable.objects.values_list('user_name', flat=True).order_by('id'))
users_list = {'users_... | 2,354 | 716 |
from engine.entities.base import BaseEntity
class Ship(BaseEntity):
WIDTH = 8
HEIGHT = 8
| 99 | 37 |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
tunacell package
============
plotting/defs.py module
~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
DEFAULT_COLORS = ('red', 'blue', 'purple', 'green', 'yellowgreen', 'cyan',
'magenta',
'indigo', 'darkorange', 'pink', 'yellow')
colors = DEFAULT_... | 3,201 | 884 |
import math
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate
import pdb
import sys
from ilqr.vehicle_model import Model
from ilqr.local_planner import LocalPlanner
from ilqr.constraints import Constraints
class iLQR():
def __init__(self, args, obstacle_bb, verbose=False):
... | 7,109 | 2,807 |
from .train import train
| 25 | 7 |
class KeyBoardService():
def __init__(self):
pass
def is_key_pressed(self, *keys):
pass
def is_key_released(self, *key):
pass | 164 | 56 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 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... | 4,034 | 1,217 |
import os
from dotenv import load_dotenv
basedir = os.path.abspath(os.path.dirname(__file__))
load_dotenv(os.path.join(basedir, '.env'))
class Config(object):
SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
VKAPI = {
'v': '5.122',
'client_id': '7386546',
'redirect... | 494 | 204 |
import argparse
import itertools
import json
import logging
import os
import pickle
import time
import warnings
from collections import Counter, defaultdict
from typing import Dict, Any, List, Iterable, Tuple, Set
warnings.filterwarnings(action='ignore', category=UserWarning, module='gensim')
import langdetect
import... | 38,153 | 10,601 |
#!/usr/bin/env python3
"""Switcharoo.
Create a function that takes a string and returns a new string with its
first and last characters swapped, except under three conditions:
If the length of the string is less than two, return "Incompatible.".
If the argument is not a string, return "Incompatible.".
If the first a... | 1,247 | 446 |
#!/usr/bin/python
'''
async-lookup.py : This example shows how to use asynchronous lookups
Authors: Zdenek Vasicek (vasicek AT fit.vutbr.cz)
Marek Vavrusa (xvavru00 AT stud.fit.vutbr.cz)
Copyright (c) 2008. All rights reserved.
This software is open source.
Redistribution and use in source and bina... | 2,212 | 791 |
"""1/1 adventofcode"""
with open("input.txt", "r", encoding="UTF-8") as i_file:
data = list(map(int, i_file.read().splitlines()))
values = ["i" if data[i] > data[i - 1] else "d" for i in range(1, len(data))]
print(values.count("i"))
| 244 | 101 |
"""
Simple ResNet FPN that only outputs p2.
Modified from https://github.com/HRNet/Higher-HRNet-Human-Pose-Estimation/blob/master/lib/models/pose_higher_hrnet.py
"""
__author__ = "Hengyue Liu"
__copyright__ = "Copyright (c) 2021 Futurewei Inc."
__credits__ = []
__license__ = "MIT License"
__version__ = "0.1"
__maintai... | 3,345 | 1,104 |
import os
from flask import Flask
def create_app():
app = Flask(__name__, instance_relative_config=True)
from . import catalogue
app.register_blueprint(catalogue.bp)
return app
| 198 | 64 |
from google.cloud import storage
GCS_CLIENT = storage.Client()
GCS_BUCKET = GCS_CLIENT.get_bucket('senpai-io.appspot.com')
path = 'quandl-stage/backfill_data_jan2015_mar2018.csv'
blob = GCS_BUCKET.blob(path)
blob.upload_from_filename(filename='data_jan2015_mar2018.csv')
| 273 | 120 |
import json
from requests.models import Response
from http import HTTPStatus
from CMS.test.mocks.search_mocks_content import content
class SearchMocks:
@classmethod
def get_search_response_content(cls):
return content;
@classmethod
def get_successful_search_response(cls):
respon... | 740 | 206 |
import numpy as np
from spacy.pipeline.sentencizer import Sentencizer
from glob import glob
from spacy.lang.en import English
def metrics(a, b):
from sklearn.metrics import f1_score, recall_score, precision_score, accuracy_score
return (accuracy_score(a, b),
recall_score(a, b),
precisi... | 1,818 | 599 |
from os import path
from operator import itemgetter
from time import sleep
class Contact:
'''def __init__(self, name = ' ', phone = ' ', birthday = ' '):
self.name = name
self.phone = phone
self.birthday = birthday'''
def check_if_txt_exists(self):
'''Checks if txt exists and i... | 6,893 | 2,194 |
# -*- encoding: utf-8 -*-
from .applicaton import app, api
from . import resources
| 84 | 30 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
# (c) 2017 Gregor Mitscha-Baude
# TODO: obtain rD from actual simulation
from nanopores import fields, kT, eta, qq, savefigs
from numpy import exp, pi, sqrt, linspace, diff, array, dot
L = 46e-9 # length of pore
r = 2.0779e-9 # radius of protein trypsin... | 3,157 | 1,362 |
from modules.mpulib import computeheading, attitudefromCompassGravity, RP_calculate, MadgwickQuaternionUpdate, Euler2Quat, quaternion_to_euler_angle, MPU9250_computeEuler
import socket, traceback
import csv
import struct
import sys, time, string, pygame
import pygame
import pygame.draw
import pygame.time
import numpy ... | 15,605 | 8,534 |
from rest_framework import generics
from rest_framework import response
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.views import APIView
from rest_api.serializers.doc_serializers import (DoctorRegisterSerializer,
DoctorUsersSerializer, DoctorLoginSerializer, Doct... | 5,229 | 1,402 |
"""
======================
Quaternion Integration
======================
Integrate angular velocities to a sequence of quaternions.
"""
import numpy as np
import matplotlib.pyplot as plt
from pytransform3d.rotations import quaternion_integrate, matrix_from_quaternion, plot_basis
angular_velocities = np.empty((21, 3)... | 652 | 262 |
def past(h, m, s):
h_ms = h * 3600000
m_ms = m * 60000
s_ms = s * 1000
return h_ms + m_ms + s_ms
# Best Practices
def past(h, m, s):
return (3600*h + 60*m + s) * 1000 | 188 | 109 |
import gmsh
import sys
import numpy as np
import calfem.mesh as cfm
import calfem.vis_mpl as cfv
if __name__ == "__main__":
gmsh.initialize(sys.argv)
gmsh.model.add("t1")
gmsh.model.geo.add_point(0.0, 0.0, 0.0)
gmsh.model.geo.add_point(1.0, 0.0, 0.0)
gmsh.model.geo.add_point(1.0, 1.0, 0.0)
gm... | 1,071 | 552 |
# En este problema vamos a resolver el problema de la bandera de Dijkstra.
# Tenemos una fila de fichas que cada una puede ser de un único color: roja, verde o azul. Están colocadas en un orden cualquiera
# y tenemos que ordenarlas de manera que quede, de izquierda a derecha, los colores ordenados primero en rojo, lue... | 1,495 | 531 |
def test_placeholder():
...
| 32 | 10 |
import pytest
import responses
from src.data import download
def declare_action(fname, action, pooch):
"""Declare the download action taken.
This function helps us know if ``src.data.download.fetch`` downloaded a
missing file, fetched an available file, or updated on old file.
Args:
... | 1,860 | 637 |
from google.appengine.ext import webapp
from wsgiref.handlers import CGIHandler
from model import Membership
from model import Group
from model import Transaction
class WhatHandler(webapp.RequestHandler):
def get(self):
page = self.request.get('p');
if page is None or page == '':
page = 1
else:... | 1,434 | 633 |
from abc import ABCMeta, abstractmethod
class Department:
def __init__(self, name, code):
self.name = name
self.code = code
class Employee(metaclass=ABCMeta):
def __init__(self, code, name, salary, department):
self.code = code
self.name = name
self.salary = salary
... | 1,191 | 382 |
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
import os
from torch.autograd import Variable
import argparse
import numpy as np
from torch.optim.lr_scheduler import *
from model.resnet import resnet101
from data_pre.FashionAI import fashion
pa... | 3,130 | 1,323 |
import arcade
import math
import LevelGenerator
import Textures
import Sounds
from Constants import TILE_SIZE, ROOM_WIDTH, ROOM_HEIGHT
from Mob import Mob
from Projectile import Projectile
class Player(Mob):
def __init__(self, x, y, keyboard):
self.keyboard = keyboard
self.movespeed = 2.5
... | 7,363 | 2,441 |
from flask_wtf import FlaskForm
from wtforms.validators import DataRequired, Length, NumberRange, InputRequired, ValidationError
from dmutils.forms.fields import (
DMBooleanField,
DMDateField,
DMPoundsField,
DMStripWhitespaceStringField,
DMRadioField,
)
from dmutils.forms.validators import Greater... | 5,127 | 1,463 |
#!/usr/bin/env python3
"""Utilities for dealing with .strings files"""
import re
from typing import List, Match, Optional, TextIO, Tuple, Union
from dotstrings.dot_strings_entry import DotStringsEntry
_ENTRY_REGEX = r'^"(.+)"\s?=\s?"(.*)";$'
_ENTRY_PATTERN = re.compile(_ENTRY_REGEX)
_NS_ENTRY_REGEX = r'^(NS[^ ]+)... | 5,093 | 1,569 |
import tensorflow as tf
from data_types.training_result import TrainingResult
from data_types.training_set import TrainingSet
from timeseries.build import compile_and_fit
from timeseries.window_generator import WindowGenerator
def evaluate_linear(
training_set: TrainingSet
) -> TrainingResult:
## LINEAR
... | 1,249 | 383 |
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from django.core.mail import get_connection
from django.core.mail.message import EmailMessage, EmailMul... | 3,639 | 1,158 |
import matplotlib.pyplot as plt
import numpy as np
from gpar.regression import GPARRegressor
from wbml.experiment import WorkingDirectory
import wbml.plot
if __name__ == "__main__":
wd = WorkingDirectory("_experiments", "synthetic", seed=1)
# Create toy data set.
n = 200
x = np.linspace(0, 1, n)
n... | 2,292 | 915 |
#%%
import numpy as np
import pandas as pd
import bokeh.plotting
import bokeh.io
import bokeh.models
import growth.model
import growth.viz
const = growth.model.load_constants()
colors, palette = growth.viz.bokeh_style()
mapper = growth.viz.load_markercolors()
bokeh.io.output_file('../../figures/interactive/interac... | 8,462 | 2,787 |
"""Helper methods for monitoring of events."""
from edx_django_utils.monitoring import set_custom_attribute, set_custom_attributes_for_course_key
def monitor_import_failure(course_key, import_step, message=None, exception=None):
"""
Helper method to add custom parameters to for import failures.
Arguments:... | 1,156 | 319 |
############################################################################
# Copyright (c) 2015-2017 Saint Petersburg State University
# Copyright (c) 2011-2015 Saint Petersburg Academic University
# All Rights Reserved
# See file LICENSE for details.
##################################################################... | 24,725 | 8,189 |
from flask_wtf import FlaskForm
from flask_wtf.file import FileAllowed, FileField
from flask_babel import lazy_gettext as _l
from wtforms import StringField, TextAreaField, SubmitField, PasswordField, BooleanField
from wtforms.validators import DataRequired, Email, ValidationError, Length, EqualTo
from app.models impo... | 3,713 | 992 |
from helpers import poseRt
from frame import Frame
import time
import numpy as np
import g2o
import json
LOCAL_WINDOW = 20
#LOCAL_WINDOW = None
class Point(object):
# A Point is a 3-D point in the world
# Each Point is observed in multiple Frames
def __init__(self, mapp, loc, color, tid=None):
self.pt = np... | 5,308 | 2,081 |
#!/usr/bin/env python3
import sys
file = open(sys.argv[1], "r")
total = 0
for line in file:
letterMatch = 0
param = line.split()
passIndex = [int(x) for x in param[0].split('-')]
targetLetter = param[1][0]
password = param[2]
if password[passIndex[0]-1] == targetLetter:
letterMatch +... | 482 | 181 |
import torch
import os
import logging
import json
from abc import ABC
from ts.torch_handler.base_handler import BaseHandler
from transformers import T5Tokenizer, T5ForConditionalGeneration
logger = logging.getLogger(__name__)
class TransformersSeqGeneration(BaseHandler, ABC):
_LANG_MAP = {
"es": "Spanish... | 3,165 | 930 |
import flask
from flask import request
import flask_restful as restful
from marshmallow import Schema, fields, validate
from api.helpers import success, created
from api.exceptions import NotFound
#from api.restful import API
#@API.route('/sensors', methods=['GET'], resource_class_kwargs={'test': 'foo'})
class Sensor... | 1,114 | 351 |
from __future__ import division
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
from utils.parse_config import *
from utils.utils import build_targets, to_cpu, non_max_suppression
import matplotlib.pyplot as plt
import matplotlib.patches as pa... | 5,802 | 1,910 |
'''
ggtools gg subpackage
This subpackage defines the following functions:
# ====================== fitting function ==================== #
func - Define a linear function f(x) = a0 + a1/T*x to be fitted, where a0 and a1 are parameters for inter
# ====================== estinate lovebums =================== #
love... | 5,553 | 1,650 |
"""
.. module:: django_core_models.locations.urls
:synopsis: django_core_models locations application urls module
django_core_models *locations* application urls module.
"""
from __future__ import absolute_import
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^addresses/$',
... | 3,203 | 1,115 |
# -*- coding: utf-8 -*-
import os,urllib
class Dataset(object):
def __init__(self,opt=None):
if opt is not None:
self.setup(opt)
self.http_proxy= opt.__dict__.get("proxy","null")
else:
self.name="demo"
self.dirname="demo"
self.http_proxy="... | 3,984 | 1,176 |
# Please note that since the number of topics in computer science are exactly 40 and it's less than 100
# therefore we applied the limit on the second file (arxiv2.py) which has somewhere around 700-800 outputs
# To run this file please put it in the spiders folder and run the code below in terminal/cmd:
# scrapy ... | 1,232 | 410 |
from collections import OrderedDict
from pdm.pep517._vendor.toml import TomlEncoder
from pdm.pep517._vendor.toml import TomlDecoder
class TomlOrderedDecoder(TomlDecoder):
def __init__(self):
super(self.__class__, self).__init__(_dict=OrderedDict)
class TomlOrderedEncoder(TomlEncoder):
def __init__... | 392 | 140 |
# coding:utf-8
from urllib.parse import urlencode, urljoin
from .client import Client
class API(Client):
HOST = None
PATH = None
TIMEOUT = 30
@classmethod
def _build_url(cls, path_args=None, params=None):
url = urljoin(cls.HOST, cls.PATH)
if path_args:
url = url.form... | 673 | 225 |
__author__ = 'sheraz'
__all__ = ['parse','normalize']
from ingredient_parser.en import parse
| 96 | 36 |
#!/usr/bin/python
from __future__ import print_function
import numpy as np
import os
from human_player import human_player
import time
class Board(object):
"""board for game"""
def __init__(self,**kwargs):
self.width = int(kwargs.get('width',8))
self.height = int(kwargs.get('height',8))
... | 11,847 | 3,807 |
import unittest
import io
from unittest import mock
from tests.lib.utils import INSPECT
from custom_image_cli.validation_tool import validation_helper
from custom_image_cli.validation_tool.validation_models.validation_models import \
ImageDetail, ImageManifest, EmrRelease
class TestValidationHelper(unittest.TestC... | 3,393 | 1,015 |
# -*- coding: utf-8 -*-
import nltk
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
#from nltk import pos_tag
from nltk.tag import StanfordNERTagger
from nltk.tokenize import word_tokenize
style.use('fivethirtyeight')
# Process text
raw_text = open("news_article.txt").read... | 2,216 | 887 |
from . import general
from . import simple
from . import type
from . import compound
from . import nested | 105 | 26 |
# Iteration: Repeat the same procedure until it reaches a end point.
# Specify the data to iterate over,what to do to data at every step, and we need to specify when our loop should stop.
# Infinite Loop: Bug that may occur when ending condition speicified incorrectly or not specified.
spices = [
'salt',
'pepp... | 539 | 156 |
import os
import json
from functools import reduce
import numpy as np
import pandas as pd
import geopandas as gpd
from dsed.ow import DynamicSednetCatchment, FINE_SEDIMENT, COARSE_SEDIMENT
from dsed.const import *
import openwater.nodes as node_types
from openwater.examples import from_source
from openwater import d... | 42,211 | 14,285 |
#! /usr/bin/env python2.5
# Copyright 2009 the Melange 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 applic... | 3,738 | 1,171 |
# coding: utf-8
print(__import__('task_list_dev').tools.get_list())
| 70 | 28 |
#Warmup-1 > not_string
def not_string(str):
if str.startswith('not'):
return str
else:
return "not " + str | 119 | 46 |
""" scaling images
"""
from __future__ import print_function, unicode_literals, absolute_import, division
import logging
logger = logging.getLogger(__name__)
import os
import numpy as np
import warnings
from gputools import OCLArray, OCLImage, OCLProgram
from gputools.core.ocltypes import cl_buffer_datatype_dict
fr... | 11,242 | 3,655 |
import streamlit as st
from streamlit import caching
import os
import torch
from src.core.detect import Detector
from src.core.utils import utils
from PIL import Image
import cv2
st.title('1stDayKit Object Detection')
st.write('1stDayKit is a high-level Deep Learning toolkit for solving generic tasks.')
uploaded_file... | 776 | 261 |
from sqlalchemy.engine import Engine, Connection
from .__interface import IConnection
class Sql(IConnection):
pass
| 121 | 33 |
"""An Http API Client to interact with meross devices"""
from email import header
import logging
from types import MappingProxyType
from typing import List, MappingView, Optional, Dict, Any, Callable, Union
from enum import Enum
from uuid import uuid4
from hashlib import md5
from time import time
from json import (
... | 8,036 | 2,642 |
num = int(input('Digite um número: '))
print('''Qual será a base de conversão do número {}
[1] para "binário"
[2] para "octal"
[3] para "hexadecimal"'''.format(num))
num1 = int(input('Escolha uma opção: '))
if num1 == 1:
print('Você escolheu converter o número {} para binário. O valor é de {}.'.format(
num... | 632 | 229 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Plot contours from an 2D histogram showing the standard deviation
"""
import numpy as np
import matplotlib.pyplot as plt
# Build datas ###############
x, y = np.random.normal(size=(2, 1000000))
xbins = np.linspace(-2, 2, 30)
ybins = np.linspace(-2, 2, 30)
counts,... | 1,359 | 576 |
import os
import json
import pytest
import pandas as pd
# TODO: revise the following constants when using new or revised CPS/PUF data
CPS_START_YEAR = 2014
PUF_START_YEAR = 2011
PUF_COUNT = 248591
LAST_YEAR = 2027
@pytest.fixture(scope='session')
def test_path():
return os.path.abspath(os.path.dirname(__file__)... | 2,648 | 1,110 |
import time
import logging
from tests.common.helpers.assertions import pytest_assert
from tests.common.snappi.snappi_helpers import get_dut_port_id
from tests.common.snappi.common_helpers import start_pfcwd, stop_pfcwd
from tests.common.snappi.port import select_ports, select_tx_port
from tests.common.snappi.snappi_he... | 9,326 | 3,125 |
from math import sqrt
import re
from curious.commands import Context
from curious.commands.exc import ConversionFailedError
from typing import Tuple
colour_pattern = re.compile(r'(#|0x)?([A-Za-z0-9]{1,6})')
RGB = Tuple[int, int, int]
class Colour:
"""
A class that represents a colour.
"""
def __ini... | 3,353 | 1,178 |
'''
Docstring with single quotes instead of double quotes.
'''
my_str = "not an int"
| 85 | 26 |
from client import linodeClient
import os
linode = linodeClient(os.getcwd() + '/../.config')
userInput = raw_input("What do you want to do?\n")
if userInput == 'create':
print(linode.createLinode('3', '1'))
if userInput == 'destroy':
userInput = raw_input("What do you want to destroy?\n")
response = lin... | 1,789 | 634 |
# Generated by Django 3.2.2 on 2021-06-22 22:47
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('base', '0001_initial'),
]
operations = [
migrations.CreateModel(
... | 6,694 | 1,973 |
def selection_sort(input_list):
for i in range(len(input_list)):
min_index = i
for k in range(i, len(input_list)):
if input_list[k] < input_list[min_index]:
min_index = k
input_list[i], input_list[min_index] = input_list[min_index], input_list[i]
return inpu... | 327 | 110 |
username = 'user@example.com'
password = 'hunter2'
# larger = less change of delays if you skip a lot
# smaller = more responsive to ups/downs
queue_size = 2 | 163 | 57 |
"""
Created on 9 Aug 2016
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
"""
import _csv
import sys
# --------------------------------------------------------------------------------------------------------------------
class Histogram(object):
"""
classdocs
"""
__HEADER_BIN = ".bin"
... | 3,299 | 904 |