text string | size int64 | token_count int64 |
|---|---|---|
import inspect
import subprocess
import re
import sys
import logging
logger = logging.getLogger()
logger.addHandler(logging.StreamHandler(sys.stdout))
logger.setLevel(logging.DEBUG)
# numbers larger than 2000 silently fail
sys.setrecursionlimit(2000)
def first(s):
for x in s:
return x
assert False
... | 13,965 | 4,505 |
class NotInsideTransaction(Exception):
def __init__(self):
message = 'Trying to perform an operation that needs to be inside transaction'
super(NotInsideTransaction, self).__init__(message)
class MixedPositionalAndNamedArguments(Exception):
def __init__(self):
message = 'Cannot mix p... | 432 | 110 |
import socket
import threading as td
import time
class SockRecvTimeout(socket.socket):
def __init__(self,family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, fileno=None):
super().__init__(family, type, proto=0, fileno=None)
self.recv_flag = False
self.recv_data = None
... | 1,478 | 489 |
"""
Client for Yandex.Disk.
"""
__version__ = '0.5.1'
| 54 | 27 |
import logging
from amqpstorm import Connection
logging.basicConfig(level=logging.INFO)
with Connection('localhost', 'guest', 'guest') as connection:
with connection.channel() as channel:
channel.queue.declare('simple_queue')
channel.basic.consume(queue='simple_queue', no_ack=False)
for m... | 422 | 117 |
import pylab
import numpy
from math import sqrt, factorial, sin, cos, pi
## Retrieving physical parameters: ##
particleDensity = int(input('Please insert the particle density N/L: '))
cutoff = float(input('Please insert the desired energy cut-off [in units of Fermi energy]: '))
V0 = float(input('Please insert the des... | 1,950 | 714 |
import pathlib
import matplotlib as mpl
import matplotlib.image as image
import matplotlib.pyplot as plt
import pandas as pd
import simscale_eba.ResultProcessing as res
experimental_velocity_path = pathlib.Path.cwd() / "AIJ_Case_G_Normalised_Velocity.xlsx"
experimental_velocity = pd.read_excel(experimental_velocity_... | 7,274 | 2,914 |
from __future__ import absolute_import
from __future__ import unicode_literals
from pkg_resources import parse_version
try:
from pip import get_installed_distributions # pragma: no cover
except ImportError: # pragma: no cover
# pip >= 10.0.0
from pkg_resources import working_set # pragma: no cover
... | 10,034 | 2,535 |
from constants import projects_path
from mapper import MapperGenerator
from fileFilter import FileIndex, FileFilter
from util import FileIdx
import os
import json
class CleanUnfixedFiles():
def __init__(self):
self.generateFiles()
self.fileIdx = FileIdx()
self.buggyFiles = self.getAllBuggy... | 1,282 | 392 |
"""Custom errors."""
class ConfigurationError(Exception):
"""
This exception is raised if a user has misconfigured Flask-Stormpath.
"""
pass
| 159 | 45 |
import torch
from torch import nn
from torch.nn.init import xavier_uniform_, xavier_normal_
from torch.nn.parameter import Parameter
class MF(nn.Module):
'''
Time-aware matrix factorization
Cite: Collaborative filtering with temporal dynamics
We only consider q_i(t) here when modeling r_{u,i,t}
'''... | 5,658 | 1,996 |
#!/usr/bin/python3
import sys, io
import logging
import time
import zlib
import astm_file2mysql_general as astmg
import zlib
import base64
import struct
#apt search python3-matplotlib
#apt install python3-matplotlib
#import matplotlib.pyplot as plt
#import numpy as np
import datetime
#to ensure that password is no... | 7,746 | 2,994 |
import unittest
from karabo.Imaging import source_detection
from karabo.Imaging.source_detection import read_detection_from_sources_file_csv
from karabo.simulation.sky_model import read_sky_model_from_csv
from karabo.test import data_path
class TestSourceDetection(unittest.TestCase):
# TODO: move these on to CS... | 7,030 | 2,608 |
"""
holds testing code utilites
""" | 35 | 11 |
#!/usr/bin/python
# Software License Agreement (BSD License)
#
# Copyright (c) 2013, Juergen Sturm, TUM
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source... | 4,396 | 1,611 |
##############################################################################
#
# Copyright (c) 2008 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... | 56,065 | 15,205 |
# To be released soon. | 22 | 7 |
from metaflow import profile
NUM_HASH_BINS = 10000
PRECISION = 6
class FeatureEncoder():
NAME = 'grid'
FEATURE_LIBRARIES = {'python-geohash': '0.8.5',
'tensorflow-base': '2.6.0'}
CLEAN_FIELDS = ['pickup_latitude', 'pickup_longitude',
'dropoff_latitude', 'dropoff... | 1,557 | 518 |
import tkinter as tk
from tkinter import filedialog, Text
import os
app = tk.Tk()
def add_file():
file_name = filedialog.askopenfile(initialdir="/", title="Select Directory")
print(file_name)
canvas = tk.Canvas(app, height=700, width=700, bg="#263D42")
canvas.pack()
frame = tk.Frame(app, bg="white")
frame... | 620 | 252 |
from django.db import models
from django.urls import reverse
from django.utils.safestring import mark_safe
class GuestPost(models.Model):
'''
Do not remove or replace "help_text" variable content.
This blog uses hidden reCAPTCHA by Google, so you must tell
your users explicitly about using this featur... | 2,122 | 672 |
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By:
# Maintained By:
@given('a Category resource named "{name}" for scope "{scope}"')
def create_category(context, name, scope):
named_example_resou... | 372 | 128 |
#!/usr/bin/env python
import numpy as np
from io import StringIO
from itertools import permutations
def perms(arr):
for columns in permutations(range(3)):
for x in (1, -1):
for y in (1, -1):
for z in (1, -1):
a = arr[:, columns] * [x, y, z]
... | 2,751 | 849 |
import sys
from pathlib import Path
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
from Cython.Build import cythonize
import numpy as np
extra_compile_args = []
extra_link_args = []
# macOS Clang doesn't support OpenMP
if sys.platform != 'darwin':
extra_compile_args.ap... | 1,880 | 566 |
import logging
import logging.config
import pymongo
from web.contentment.taxonomy import Taxonomy
logging.config.dictConfig({
'version': 1,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'json',
# 'level': 'debug',
'stream': 'ext://sys.stdout',
}
},
... | 1,560 | 659 |
import time
from datetime import datetime as dt
hosts_path='C:\Windows\System32\drivers\etc\hosts'
redirect='127.0.0.1'
websites=['www.instagram.com','www.netflix.com','facebook.com','twitter.com']
while True:
if(dt(dt.now().year,dt.now().month,dt.now().day,9)<dt.now()<dt(dt.now().year,dt.now().month,dt.now... | 989 | 323 |
'''
Created on Aug 3, 2015
@author: Mikhail
@summary: Create several functions:
1. First function has two positional parameters and infinity numbers of positional parameters
2. Second function has a mandatory parameter with key and infinity number of parameters with keys
'''
def function_one(param_1, param_2, *list_... | 1,507 | 486 |
import torch
import Levenshtein as Lev
from ctcdecode import CTCBeamDecoder
class BeamCTCDecoder():
def __init__(self, PHONEME_MAP, blank_index=0, beam_width=100):
# Add the blank to the phoneme_map as the first element
if PHONEME_MAP[blank_index] != ' ':
PHONEME_MAP.insert(0, ' ')
... | 1,845 | 596 |
from collections import namedtuple
import pandas as pd
import numpy as np
from scipy.stats import norm
class FlexibleProbabilities(object):
"""
Flexible Probabilities
"""
def __init__(self, data):
self.x = data
self.p = np.ones(len(data))/len(data)
def shape(self):
... | 2,829 | 898 |
from __future__ import annotations
import operator
from copy import deepcopy
from dataclasses import dataclass, field
from itertools import combinations
from typing import ClassVar, Dict, List, Optional, Set, Tuple, Union
from .aligner import Aligner
from .enum import EditOperation, Side, SpanType
from .pairs import ... | 25,011 | 7,709 |
# External libraries
import numpy as np
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import json
import dash_table
# Internal modules
from processing.data_management import load_excel, load_geojson
import processing.preprocessors as pp
f... | 1,699 | 545 |
# Copyright (C) 2011 Lukas Lalinsky
# Distributed under the MIT license, see the LICENSE file for details.
import logging
from sqlalchemy import sql
from acoustic import tables as schema
logger = logging.getLogger(__name__)
def find_or_insert_format(conn, name):
"""
Find a format in the database, create it ... | 738 | 230 |
from transaction import Transaction
import pyfiglet
import requests
import pickle
import cmd
class Noobcash(cmd.Cmd):
intro = '\nWelcome to the noobcash client. Type help or ? to list commands.\n'
prompt = 'noobcash> '
def preloop(self):
print(pyfiglet.figlet_format('noobcash'))
self.port ... | 2,806 | 788 |
from get_CNN_data import get_CNN_data
import numpy as np
from keras.applications import resnet_v2
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras import optimizers
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import Decision... | 2,051 | 786 |
# an automated bird! kind of like a bird and droid
class Boid:
def __init__(self):
self.position = PVector(random(width), random(height))
self.velocity = PVector().random2D().setMag(random(2.5, 4.5))
self.acceleration = PVector()
self.max_force = random(0.15, 0.25)
self.max_... | 9,700 | 2,883 |
from django.contrib import admin
# Register your models here.
from .models import Job
admin.site.register(Job) | 112 | 31 |
# Generated by Django 2.2.7 on 2019-12-24 12:53
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... | 1,668 | 503 |
#Secret Messages. New character
alphabet = 'abcdefghijklmnopqrstuvwxyz'
key = int(input('Please input key '))
character = input('Please enter a character ')
position = alphabet.find(character)
print('Position of a character ', character, ' is ', position)
newPosition = (position + key) % 26
print('New position of a ch... | 480 | 134 |
from numpy import asarray, sin, cos, pi, cross, sqrt
from numpy.linalg import norm
from scipy.integrate import quad
from functools import partial
def biot_savart(pos, path, dpath, I):
x = quad(partial(lambda s, pos, path, dpath, I : I * ((pos[2] - path(s)[2]) * dpath(s)[1] - (pos[1] - path(s)[1]) * dpath(s)[2]) / ... | 1,343 | 628 |
import numpy as np
def floyd_warshall(matrix):
vertices = len(matrix)
fw_distance_matrix = matrix.copy() # make a copy of matrix, (if there is no distance keep the default ones)
fw_distance_matrix[np.isnan(fw_distance_matrix)] = np.inf # fill indirect paths as well in fw_distance_matrix
path_matrix ... | 2,023 | 613 |
import json
from django.test import TransactionTestCase
from people.models import Person, PersonWidgetDefinition
from domain_mappings.models import RelationshipType, MappingType, DomainMapping
from dashboards.models import Dashboard
from stacks.models import Stack, StackGroups
from owf_groups.models import OwfGro... | 11,577 | 3,616 |
v = 0
t = 0
aux = []
deslocamento = []
while True:
try:
aux = input().split()
calculo = (int(aux[1]) * 2) * int(aux[0])
deslocamento.append(calculo)
except EOFError:
break
for i in range(0,len(deslocamento)):
print(deslocamento[i])
| 279 | 108 |
# Copyright 2021 Google LLC. 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 applicable law or a... | 3,043 | 1,128 |
import logging
from functools import lru_cache
from import_export import fields, resources
from ..teryt.models import JednostkaAdministracyjna
from .models import MetaCategory, Organization
logger = logging.getLogger(__name__)
class MetaField(fields.Field):
def save(self, obj, data):
if not self.reado... | 2,779 | 859 |
import time
import logging
import serial
import threading
from threading import Thread
from flask import Flask, render_template, session, request
from flask_socketio import SocketIO, emit, join_room, leave_room, \
close_room, rooms, disconnect
logging.basicConfig(level=logging.DEBUG,
format='... | 14,194 | 4,267 |
from .bloch_redfield import *
from ._brtensor import bloch_redfield_tensor
from .correlation import *
from .countstat import *
from .floquet import *
from .mcsolve import *
from .mesolve import *
from . import nonmarkov
from .pdpsolve import *
from .piqs import *
from .propagator import *
from .rcsolve import *
from .s... | 526 | 175 |
from nobos_commons.data_structures.skeletons.joint_2d import Joint2D
from nobos_commons.data_structures.skeletons.skeleton_joints_base import SkeletonJointsBase
class SkeletonOpenPoseJoints(SkeletonJointsBase):
def __init__(self):
"""
Implementation only works on Python 3.6+
"""
se... | 3,042 | 1,168 |
"""Reddit fixtures"""
# pylint: disable=redefined-outer-name, unused-argument
from types import SimpleNamespace
import pytest
from channels import api
from channels.constants import CHANNEL_TYPE_PRIVATE, CHANNEL_TYPE_PUBLIC, LINK_TYPE_SELF
from channels.factories.models import PostFactory
from channels.factories.reddi... | 5,437 | 1,783 |
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.Elements)
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
doc = DocumentManager.Instance.CurrentDBDocument
params... | 1,329 | 433 |
import os
import tensorflow as tf
import numpy as np
class StereoDatasetCreator():
"""
Takes paths to left and right stereo image directories
and creates a tf.data.Dataset that returns a batch of left
and right images, (Optional) returns the disparities as a target
using the disparities directorie... | 11,170 | 3,294 |
#------------------------------------------------------------------------------
# Copyright (c) 2013, Enthought, Inc.
# All rights reserved.
#------------------------------------------------------------------------------
import gc
import os
from multiprocessing import Process
from multiprocessing.queues import Queue
... | 4,968 | 1,229 |
from flask import render_template
from flask_restful import Resource
from flask_wtf import Form
from flask_wtf.file import FileField
from werkzeug.utils import secure_filename
from app.main import api
@api.resource('/api/v1/version')
class Version(Resource):
def get(self):
return dict(version... | 702 | 226 |
import playsound
# 021.mp3 é o caminho com o nome do arquivo
print('\033[02;31;43mVoce ta ouvindo uma musica legal.\033[m')
playsound.playsound('021.mp3')
| 156 | 70 |
import io
import logging
import shutil
import sys
import threading
import time
from enum import Enum
from typing import Callable, Iterable, Union, Sized, Optional
from .LoggerUtils import temp_log
__all__ = ['Progress', 'GetInput', 'count_ordinal', 'TerminalStyle']
# noinspection SpellCheckingInspection
class Termi... | 7,721 | 2,685 |
import importlib
import ntpath
import os
import re
import subprocess
import time
import numpy as np
import pandas as pd
import xarray as xr
from openpyxl import load_workbook
from .ws.settings import NotLevels
try:
from StringIO import StringIO as BytesIO
except ImportError:
from io import BytesIO
class Py... | 71,623 | 19,611 |
import logging
import multiprocessing as mp
import threading
from datetime import datetime
from flask import request, current_app, g, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from sqlalchemy.exc import OperationalError
from dimensigon import defaults
from dimensigon.domain.entities import... | 6,813 | 2,207 |
animal = "Hippopotamus"
print(animal[3:6])
print(animal[-5])
print(animal[10:])
| 80 | 40 |
from .crypto import Crypto # noqa
from .alchemy_fields import EncryptedAlchemyBinaryField # noqa
from .django_fields import EncryptedBinaryField # noqa
__version__ = '1.1.3'
| 179 | 61 |
import enum
from lark import Lark, InlineTransformer
from lark.visitors import Interpreter
from lark.reconstruct import Reconstructor
from functools import reduce
from dae.variants.attributes import Role, Inheritance, VariantType, Sex
QUERY_GRAMMAR = """
?start: expression
?expression: logical_or
?log... | 14,745 | 4,700 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | 3,650 | 1,014 |
# -*- coding: utf-8 -*-
# @Author: VU Anh Tuan
# @Date: 2018-10-12 13:37:25
# @Last Modified by: VU Anh Tuan
# @Last Modified time: 2018-10-12 13:51:55
import sys, getopt
conf = {
'help': 'get_options.py -r url'
}
def get_options(argv):
url = None
try:
opts, args = getopt.getopt(argv,"hr:", ... | 779 | 317 |
from corus.record import Record
from . import (
load_mokoron,
load_wiki,
load_simlex,
load_omnia,
load_gramru,
load_corpora,
load_ruadrect,
load_factru,
load_gareev,
load_lenta,
load_lenta2,
load_librusec,
load_ne5,
load_wikiner,
load_bsnlp,
load_person... | 25,291 | 8,057 |
from pathlib import Path
import fault
import magma as m
from .common import pytest_sim_params
def pytest_generate_tests(metafunc):
pytest_sim_params(metafunc, 'system-verilog', 'verilator')
class MyAdder(m.Circuit):
io = m.IO(a=m.In(m.UInt[4]),
b=m.Out(m.UInt[4]))
io.b @= io.a + 1
def t... | 1,059 | 397 |
# -*- coding: utf-8 -*-
"""Automatic updates of items exported to the Kodi library"""
from __future__ import unicode_literals
from datetime import datetime, timedelta
import AddonSignals
import xbmc
from resources.lib.globals import g
import resources.lib.common as common
import resources.lib.kodi.library as library... | 4,094 | 1,151 |
import discord
from discord.ext import commands
class Error(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send(
'Pl... | 516 | 149 |
"""
recommender_system.py
Creates content-based recommendations
"""
import numpy as np
import pandas as pd
import re
import ast
import os
def col(df, colname = "artists"):
"""
:param df:
:param colname: (Default value = "artists")
"""
return np.array([int(x == colname) for x in df.columns]).ar... | 6,928 | 2,296 |
#!/usr/bin/env python
traindat = '../data/fm_train_real.dat'
testdat = '../data/fm_test_real.dat'
label_traindat = '../data/label_train_twoclass.dat'
parameter_list = [[traindat,testdat,label_traindat,1,1e-5],[traindat,testdat,label_traindat,0.9,1e-5]]
def classifier_mpdsvm_modular (train_fname=traindat,test_fname=te... | 955 | 398 |
# More about some useful concepts in Python language
import datetime
import crinita as cr
lead = """One of the common challenges when dealing with data is how to send the dataset from one place to another and how to store data effectively. These problems are interconnected, as they both require serialization of da... | 22,331 | 6,030 |
"""
Install the application
"""
from os import path
from setuptools import setup, find_packages
from flying_desktop import __version__
HERE = path.dirname(__file__)
with open(path.join(HERE, "requirements.txt"), "r") as f:
packages = list(map(str.strip, f))
setup(
name="flying-desktop",
version=__version... | 698 | 222 |
from django_userhistory.models import UserTrackedContent
class UserHistoryRegistry(object):
"""
Registry for UserHistory handlers. Necessary so that only one
receiver is registered for each UserTrackedContent object.
"""
def __init__(self):
self._registry = {}
self._handlers = {}
... | 1,733 | 446 |
gram = {
"E":["2E2","3E3","4"]
}
starting_terminal = "E"
inp = "2324232$"
"""
# example 2
gram = {
"S":["S+S","S*S","i"]
}
starting_terminal = "S"
inp = "i+i*i"
"""
stack = "$"
print(f'{"Stack": <15}'+"|"+f'{"Input Buffer": <15}'+"|" + 'Parsing Action')
print(f'{"-":-<50}')
while True:
action = Tr... | 948 | 502 |
#program to create sum of digits
num = int(input("Enter a number "))
copy = num
sum = 0
while num > 0:
r = num % 10
sum = sum + r
num //= 10
print("Sum of digits")
print("The sum of digits are",sum)
| 212 | 80 |
from zope.interface import Interface, Attribute, directlyProvides
from zope.interface.interfaces import IInterface
from zope.annotation.interfaces import IAnnotatable
from zope.componentvocabulary.vocabulary import InterfacesVocabulary
from zope.schema import Float
from zope.schema import Int
from zope.schema import AS... | 7,546 | 1,989 |
_base_ = [
'../_base_/models/oscar/oscar_nlvr2_config.py',
'../_base_/datasets/oscar/oscar_nlvr2_dataset.py',
'../_base_/default_runtime.py',
]
# cover the parrmeter in above files
model = dict(
params=dict(
model_name_or_path='/home/datasets/mix_data/model/oscar/large-vg-labels/ep_55_1617000'... | 949 | 425 |
import rospy
import rospkg
import time
from commander.executors.Executor import Executor
from commander.utils.Process import Process
class CameraExecutor(Executor):
"""
Executor class for adding and removing camera.
"""
def __init__(self):
Executor.__init__(self)
def execute(self, **kwar... | 1,608 | 471 |
"""md
# Mkdocs Simple Generator
`mkdocs_simple_gen` is a program that will automatically create a `mkdocs.yml`
configuration file (only if needed) and optionally install dependencies, build,
and serve the site.
## Installation
Install the plugin with pip.
```bash
pip install mkdocs-simple-plugin
```
_Python 3.x, ... | 4,022 | 1,252 |
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
import homeassistant.helpers.config_validation as cv
from .const import DOMAIN, PLATFORMS
CONFIG_SCHEMA = cv.deprecated(DOMAIN)
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
hass.conf... | 544 | 171 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This script merges one sample across lanes.
#
# This script will *only* be useful if you have the same multiplexed sample loaded into multiple lanes of a flowcell.
#
# This concatenates the same index's pared-end files (L*_R*_* .fastq.gz) across multiple
# lanes into on... | 7,851 | 2,670 |
import glob
import json
import os
import pandas as pd
from sklearn.preprocessing import StandardScaler
# Files and extensions
DATA_DIR = "/Users/Sergio/webserver/tartarus/dummy-data"
DEFAULT_TRAINED_MODELS_FILE = DATA_DIR+"/trained_models.tsv"
DEFAULT_MODEL_PREFIX = "model_"
MODELS_DIR = DATA_DIR+"/models"
PATCHES_DIR... | 2,840 | 1,082 |
#!/usr/bin/env python
'''
Prints kernel modules that depend on the module given, ending with the module itself.
Prints nothing if the module isn't loaded
'''
from __future__ import print_function
import argparse
import subprocess
def main():
args = get_args()
for module in get_module_dependencies(args.modu... | 1,633 | 483 |
# -*- coding: utf-8 -*-
import scrapy
from qiubaiproject.items import QiubaiprojectItem
class QiuSpider(scrapy.Spider):
name = 'qiu'
allowed_domains = ['www.qiushibaike.com']
start_urls = ['http://www.qiushibaike.com/']
# 实现爬取多页的代码
page = 1
url = 'https://www.qiushibaike.com/8hr/page/{}/'
... | 1,834 | 676 |
import torch
import torch.utils.data
from utils.data import SurrealDatasetWithVideoContinuity as SurrealDataset
from utils import Config
from models import StackedHourGlass, Linear
from utils import SurrealTrainer as Trainer
config = Config('./config')
device_type = "cuda" if torch.cuda.is_available() and config.devi... | 2,948 | 921 |
# Copyright 2017 The Wallaroo 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 applicable law or agreed ... | 30,607 | 8,505 |
# encoding: utf-8
from django.conf.urls import url
from . import views
urlpatterns = [
] | 92 | 33 |
#最初に入れておくとinputが早くなる
import sys
input = sys.stdin.readline
n, k = map(int, input().split())
a = list(map(int, input().split()))
ruisekiwa = [0]
for i in range(1,n+1):
ruisekiwa.append(ruisekiwa[i - 1] + a[i-1])
count = 0
i = 0
j = 0
#print(ruisekiwa)
while(i<n+1):
if (ruisekiwa[i] - ruisekiwa[j] >= k):
... | 392 | 195 |
import praw
reddit = praw.Reddit(
client_id="RyhoH9FE3QNpXIe5stCQ7A",
client_secret="YHm3cIWF90PbPykHZEdyYYa4_LgOrQ",
user_agent="appTester123"
)
def getUserData(user):
users_engagements_object = reddit.redditor(user).new(limit=100)
user_engagements_extracted = {'subreddit': [], 'user': [], '18+_engagem... | 639 | 265 |
# -*- coding: utf-8 -*-
"""
Plot swimming velocity roses.
USE: python SwimmingRose.py output.nc
"""
# =============================================================================
# IMPORTS
# =============================================================================
import numpy as np
from netCDF4 import Dataset
im... | 1,705 | 494 |
"""
Usage: python script.py search_string replace_string dir
Eg. python batchreplace.py galleries productions /Sites/cjc/application/modules/productions/
And it will search recursively in dir
and replace search_string in contents
and in filenames.
Case-sensitive
"""
from sys import argv
import os
def multi_replace(... | 1,449 | 414 |
STATE_OVEN_BAKE = "Bake"
STATE_OVEN_BAKE_TWO_TEMP = "Bake (Two Temp.)"
STATE_OVEN_BAKED_GOODS = "Baked Goods"
STATE_OVEN_BROIL_HIGH = "Broil (High)"
STATE_OVEN_BROIL_LOW = "Broil (Low)"
STATE_OVEN_CONV_BAKE = "Convection Bake"
STATE_OVEN_CONV_BAKE_TWO_TEMP = "Convection Bake (Two Temp.)"
STATE_OVEN_CONV_BROIL_CRISP = "... | 1,205 | 616 |
import csv
import sqlite3
import os.path
import sys
import time
import logging
import unicodedata
FILE_DIR = os.path.dirname(os.path.realpath(__file__))
CSV_FIELD_NAMES = ['UniqueId', 'Russian', 'SecondRussian', 'POS', 'POS_Subtype', 'Animacy', 'Level', 'English', 'Rank', 'Count', 'Chapter', 'AdjAdvProp', 'Collocatio... | 19,394 | 6,995 |
"""
python version of SurfStatReadSurf
"""
# Author: RRC
# License: BSD 3 clause
import numpy as np
@deprecated("BrainSpace dependency")
def py_SurfStatReadSurf(filenames, ab='a', numfields=2, dirname, maxmem=64):
"""Reads coordinates and triangles from an array of .obj or FreeSurfer files.
Parameters
... | 2,176 | 663 |
"""
The MIT License (MIT)
Copyright © 2015 RealDolos
Copyright © 2018 Szero
See LICENSE
"""
# pylint: disable=broad-except
import logging
import sys
import asyncio
from collections import namedtuple, defaultdict
from functools import wraps
from threading import Thread, Event, RLock, Condition, Barrier, get_ident
from... | 8,883 | 2,495 |
# (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from .check import check_run
from .ls import ls
from .prune import prune
from .start import start
from .stop import stop
ALL_COMMANDS = (
check_run,
ls,
prune,
start,
stop,
)
| 303 | 113 |
import warnings
from qutip.qip.operations.gates import *
warnings.warn(
"Importation from qutip.qip.gates is deprecated."
"Please use e.g.\n from qutip.qip.operations import cnot\n",
DeprecationWarning, stacklevel=2)
| 230 | 83 |
from natch.core import Decoration
from natch.rules import Gt
gt = Decoration.make_rule_decorator(Gt)
| 103 | 37 |
from setuptools import setup,find_packages
from codecs import open
import os
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here,'README.rst'),encoding="utf-8") as f:
long_desc = f.read()
setup(
name = "ml_py",
version = "0.0.003",
description="Python packge which contains ... | 1,349 | 443 |
#!/usr/bin/env python3
import json
import os
import pathlib
import re
import sys
from bs4 import BeautifulSoup
input_dir = pathlib.Path(sys.argv[2])
output_dir = pathlib.Path(sys.argv[1])
input_filenames = [p for p in pathlib.Path(input_dir).iterdir() if p.is_file()]
for filename in input_filenames:
sites = []... | 1,382 | 464 |
RECOMMENDED_FEE = 50000
COINBASE_MATURITY = 100
COIN = 100000000
# supported types of transaction outputs
TYPE_ADDRESS = 1
TYPE_PUBKEY = 2
TYPE_SCRIPT = 4
TYPE_CLAIM = 8
TYPE_SUPPORT = 16
TYPE_UPDATE = 32
# claim related constants
EXPIRATION_BLOCKS = 262974
RECOMMENDED_CLAIMTRIE_HASH_CONFIRMS = 1
NO_SIGNATURE = 'ff'... | 2,296 | 1,228 |
from temboo.Library.Salesforce.Searching.Search import Search, SearchInputSet, SearchResultSet, SearchChoreographyExecution
from temboo.Library.Salesforce.Searching.SearchScopeAndOrder import SearchScopeAndOrder, SearchScopeAndOrderInputSet, SearchScopeAndOrderResultSet, SearchScopeAndOrderChoreographyExecution
| 313 | 80 |
import qiime2
import argparse
from dask_jobqueue import SLURMCluster
from dask.distributed import Client
import dask
import dask.dataframe as dd
import dask.array as da
from biom import load_table
import pandas as pd
import numpy as np
import xarray as xr
import arviz as az
from q2_batch._batch import _batch_func, merg... | 1,838 | 592 |
# -*- coding: utf-8 -*-
"""
Generating the CF-FM synthetic calls
====================================
Module that creates the data for accuracy testing horseshoe bat type calls
"""
import h5py
from itsfm.simulate_calls import make_cffm_call
import numpy as np
import pandas as pd
import scipy.signal as signal
from t... | 2,304 | 857 |