text string | size int64 | token_count int64 |
|---|---|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 2020, Jan Cervenka
import argparse
import asdc.core
import asdc.service
from . import version
def _create_arg_parser():
"""
Creates the CLI argument parser.
"""
parser = argparse.ArgumentParser(conflict_handler='resolve',
... | 1,457 | 437 |
from sqlalchemy import create_engine
import os
class DatabaseEngine():
"""Helper for database connections using SQLAlchemy engines"""
def __init__(self):
"""Constructor"""
self.engines = {}
def db_engine(self, conn_str, service_suffix=None):
"""Return engine."""
# conn_st... | 1,612 | 456 |
from collections import namedtuple
import requests, pickle
from abc import ABCMeta, abstractmethod
from bs4 import BeautifulSoup
from utilities import *
from random import randint
from threading import Thread
# Tuple object
Quote = namedtuple('Quote', ['text', 'author'])
class QuoteException(Exception):
def __... | 4,681 | 1,285 |
data = [list(map(int,line.strip())) for line in open("inputday9")]
def fieldVal(f):
i,j = f
return data[i][j]
def adjacent(field):
fields = []
i, j = field
if i > 0:
fields.append((i-1, j))
if j > 0:
fields.append((i, j-1))
if i < len(data) - 1:
fields.append((i+1, j))
if j < len(data[0]) ... | 1,085 | 414 |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
# Copyright HiWonder.hk
# Further development by ians.moyes@gmail.com
# Translation by Google
# Library to control the hexapod using reverse kinematics of
# lower servo values on the port side lead to
# forward positions at the shoulder
# Lifting the knee
# Dropping the ank... | 8,879 | 3,342 |
import logging
from timeit import default_timer as timer
from pathlib import Path
import os
logger = logging.getLogger(__name__)
class S3IO(object):
# S3 storage utility functions
def __init__(self, s3_client, graph_utils_obj, utils):
self.s3_client = s3_client
self.gutils = graph_utils_obj
... | 3,474 | 1,083 |
import logging
import logging.config
from config.conf import *
def get_logger():
logging.config.dictConfig(log_config)
log = logging.getLogger()
return log
| 172 | 52 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# подсказка: тут надо погуглить методы pop, index, extend, insert
# пример гугл запроса: python pop list
# есть список животных в зоопарке
zoo = ['lion', 'kangaroo', 'elephant', 'monkey', ]
# TODO посадите медведя (bear) между львом и кенгуру
# и выведите список на кон... | 637 | 269 |
# -*- coding: utf-8 -*-
# pylint: disable=missing-docstring
# pylint: disable=redefined-outer-name
# pylint: disable=wildcard-import
# pylint: disable=unused-wildcard-import
# pylint: disable=no-self-use
#############################################################
# Copyright (c) 2021-2021 Maurice Karrenbrock ... | 5,242 | 1,698 |
from rubin_sim.photUtils import SignalToNoise
from rubin_sim.photUtils import PhotometricParameters
from rubin_sim.photUtils import Bandpass, Sed
from rubin_sim.data import get_data_dir
import numpy as np
from scipy.constants import *
from functools import wraps
import os
import h5py
import multiprocessing
from astrop... | 55,822 | 18,598 |
class InvalidLoginException(Exception):
pass | 50 | 14 |
from pluginbase import PluginBase
import logging
class CoreCommands(PluginBase):
"""Provides basic commands."""
def __init__(self):
PluginBase.__init__(self)
self.name = 'CoreCommands'
self.logger = logging.getLogger('teslabot.plugin.corecommands')
self.set_cmd... | 6,818 | 1,975 |
def bkdr_hash(code):
seed = 131 # 通常使用素数, 31, 131, 1313, 13131, 131313 等
hash_result = 0
for i in range(len(code)):
hash_result = (hash_result * seed) + ord(code[i])
return hash_result
print(bkdr_hash('JKiidalk'))
| 242 | 124 |
import unittest
from reinvent_chemistry import Conversions
from reinvent_chemistry.library_design.fragment_reactions import FragmentReactions
from unittest_reinvent.library_design.fixtures import FRAGMENT_REACTION_SUZUKI, SCAFFOLD_SUZUKI
from unittest_reinvent.fixtures.test_data import CELECOXIB, ASPIRIN, CELECOXIB_FR... | 2,587 | 914 |
"""
administrar la plataforma, aca ira todo el diseño de obstaculos
"""
import pygame
from funcion_sprites import Sprite
# variables que se tomaran para pintar las plataformas
#nombre objeto x y xtam/ytam
################################# nivel 1
suelo_inicio = (140, 0, 70, 40)
... | 4,998 | 2,306 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
@python_2_unicode_compatible
class Category(models.Model):
name = models.CharField(_(... | 1,781 | 576 |
from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from django.forms import ModelForm
from danceschool.core.admin import EventChildAdmin, EventOccurrenceInline
from danceschool.core.models import Event
from danceschool.core.forms import LocationWithDataWidget
from .models import P... | 2,357 | 655 |
import itertools
import os
import pickle
import re
from collections import defaultdict
import matplotlib.pyplot as plt
plt.style.use('seaborn-white')
import numpy as np
import pandas as pd
import ast
import dill
from tqdm import tqdm
from active_learner.Phrases import Phrases
class PosTag_Query_Fetcher:
def __in... | 8,124 | 2,497 |
# The MIT License (MIT).
# Copyright (c) 2015, Nicolas Sebrecht & contributors.
from imapfw.interface import implements, checkInterfaces
from imapfw.conf import Parser
from .interface import ActionInterface
# Annotations.
from imapfw.annotation import ExceptionClass
@checkInterfaces()
@implements(ActionInterface)
... | 2,595 | 761 |
from tkinter import *
janela = Tk()
Label(janela, text="Ola mundo com interface grafica").pack()
janela.mainloop()
| 118 | 42 |
from __future__ import (division, unicode_literals)
import numpy as np
from .algebraic import fit_ellipse
import matplotlib.pyplot as plt
def circle_deviation(coords):
""" Fits a circle to given coordinates using an algebraic fit. Additionally
returns the deviations from the circle radius in a list sorted on... | 5,569 | 1,883 |
from typing import Tuple, List
import pygame
from Contact.Contact import handle_contact
from Forces.Bond import Bond
from Forces.Gravity import Gravity
from Forces.PairForce import PairForce
from Forces.SingleForce import SingleForce
from Objects.Circle import Circle
from Objects.Particle import Particle
from Vec2 im... | 2,083 | 769 |
from sprites import str_to_sprite, ONEUP_STR
SYMBOLS = '''
.*******.
*=~~-~~=*
*~~---~~*
*=*****=*
**-*-*-**
.*-----*.
..*****..
'''
NUMBERS = [
[0,4,4,4,4,4,4,4,0],
[4,3,2,2,0,2,2,3,4],
[4,2,2,0,0,0,2,2,4],
[4,3,4,4,4,4,4,3,4],
[4,4,0,4,0,4,0,4,4],
[0,4,0,0,0,0,0,4,0],
[0,0,4,4,4,4,4,0,0],
]
def tes... | 409 | 264 |
from django.db import models
from django.test import TestCase
from factories import UserFactory, BucketlistFactory, BucketlistItemFactory
class UserModelTest(TestCase):
def setUp(self):
self.user = UserFactory.create(username='kiura')
def test_user_creation(self):
user = UserFactory.create(... | 843 | 269 |
import torch
import torch.nn
import torch.nn.functional as F
from tqdm import tqdm
import gc
from run_nerf_helpers import *
import numpy as np
import matplotlib.pyplot as plt
from collections import deque
import argparse
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
def save_model(global_step... | 10,455 | 3,602 |
import random
N = int(input("Number of users needed : "))
last_address_id = int(input("Last address id : "))
last_user_id = int(input("Last user id : "))
file = open('users.sql', 'w+')
questions = {
1: {'unique': True, 'criteria': 'random', 'answers': [1, 2, 3]},
2: {'unique': True, 'criteria': 'random', 'answers'... | 4,864 | 2,028 |
# class Item:
# """角色和武器的工具类。"""
#
# # items == [{"item_id":"1022","name":"温迪","item_type":"角色","rank_type":"5"}, ...]
# items = http_get_json(
# url='https://webstatic.mihoyo.com/hk4e/gacha_info/cn_gf01/items/zh-cn.json'
# )
#
# # ###########################################################... | 2,453 | 901 |
# -*- coding: utf-8 -*-
# @Time : 2020/9/18 11:33
# @Author : Hui Wang
# @Email : hui.wang@ruc.edu.cn
"""
SASRec
################################################
Reference:
Wang-Cheng Kang et al. "Self-Attentive Sequential Recommendation." in ICDM 2018.
Reference:
https://github.com/kang205/SASRec
"""... | 506 | 203 |
from django import template
from django.contrib.auth import get_user_model
register = template.Library()
@register.simple_tag(takes_context=True)
def room_slug(context, subject):
request = context['request']
if isinstance(subject, get_user_model()):
if not request.user.is_authenticated:
... | 614 | 196 |
import logging
import requests
from .config import MeshConfiguration, ChebiConfiguration, EntrezConfiguration
from .parser import BasicParser, ChebiObjectParser
from .objbase import MeshObject
from .sparql import SparqlQuery, QueryTerm2UI
__all__ = ['MeshURI', 'MeshRDFRequest', 'MeshRDFResponse', 'MeshSearchRequest', ... | 6,919 | 2,034 |
# -*- coding:utf-8 -*-
__author__ = 'yangjian'
"""
Denoise Auto-encoder
Denosing auto encoders are an important and crucial tools for feature selection and extraction.
"""
import numpy as np
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
from tensorflow.keras.layers import Dense, Input
from te... | 5,815 | 1,858 |
"""
给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
"""
非递归方法进行中序遍历,因为递归可以用栈来进行模拟,故而需要借助于数据结构栈。
左右孩子节点需要以根节点为基础,在知道根节点的情况下才可以访问左右孩子节点。故而... | 1,133 | 665 |
def calculate_result(p_answer,answer):
result=0
for i in range(len(answer)):
if p_answer[i%len(p_answer)] == answer[i]:
result+=1
return result
def solution(answers):
p1_answer=[1,2,3,4,5]
p2_answer=[2,1,2,3,2,4,2,5]
p3_answer=[3,3,1,1,2,2,4,4,5,5]
p1=calculat... | 690 | 318 |
import glob
import json
import os
import shutil
from pathlib import Path
from typing import List
from bqq import const
from bqq.types import JobInfo
from google.cloud.bigquery.schema import SchemaField
class Schemas:
def __init__(self):
self.path = const.BQQ_SCHEMAS
def clear(self):
dirs = g... | 1,154 | 367 |
import datetime
import async_parse_irc
yesterday = datetime.date.today() - datetime.timedelta(days=1)
start = yesterday.strftime("%Y-%m-%d")
async_parse_irc.parse(start=start, quiet=True)
| 190 | 66 |
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from apis.models import UserApiModel,PostApiModel
from ..utils import (get_new_post,
get_serialized_data,
create_api_posts)
from ..se... | 5,929 | 1,533 |
#!/usr/bin/python3
import configparser
if __name__ == "__main__":
# initialize ConfigParser
config_parser = configparser.ConfigParser()
# Let's read the config file
config_parser.read('raspi.cfg')
device_id = config_parser.get('AppInfo', 'id')
debug_switch = config_parser.get('AppInfo', 'debug_switch')
senso... | 550 | 185 |
import shutil
def test_slash_not_full(host):
total, used, free = shutil.disk_usage('/')
assert free > 0
def test_export_not_full(host):
total, used, free = shutil.disk_usage('/export')
assert free > 0
def test_var_not_full(host):
total, used, free = shutil.disk_usage('/var')
assert free > 0
| 301 | 115 |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 10 10:18:55 2021
@author: giaco
"""
#code useful to shift from min resolution to hourly, such that the csv load demand can be fed as input to MicrogridsPy
#yearly profile is required
import numpy as np
import pandas as pd
#minute and hour indexes
minute_in... | 748 | 320 |
import os
from os import path
from datetime import datetime
import subprocess
# Checking the default location
# add remote location
home = (path.expanduser("~"))
git_gamer_location = path.join(home, "GitGamer")
current_cwd = os.getcwd()
#hide console
# si = subprocess.STARTUPINFO()
# si.dwFlags |= subprocess.STARTF_U... | 2,314 | 820 |
import numpy as np
import theano as th
import sympy as sm
import theano.tensor as tt
from typing import *
def slow_fdiff_1(n: int) -> np.ndarray:
K = np.diag(np.ones(n) * -1, 0)
K += np.diag(np.ones(n - 1) * 1, 1)
K = np.vstack((np.zeros(n), K))
K[0, 0] = 1.
K[-1, -1] = -1.
return K
def slow... | 2,564 | 1,088 |
import lib
from lib import extra_char_class, general
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-d",
help="target directory")
parser.add_argument("-n",
help="name of regex offense")
args = parser.par... | 649 | 178 |
"""
This module defines objects used to explore information about a Radarly User.
For security reasons, you can only retrieve information about the
current user of the API.
"""
from .api import RadarlyApi
from .model import SourceModel
from .project import InfoProject
class User(SourceModel):
"""Object used to e... | 2,200 | 586 |
from z3 import *
def movsx(v):
return ZeroExt(32 - 8, v)
def imul(a, b, c = None):
if c is None:
return a * b
return b * c
def xor_(r, v):
return r ^ v
def or_(r, v):
return r | v
def mov(_, r2):
return r2
def shr(r1, c):
return LShR(r1, c)
def shl(r1, c):
return r1 <... | 11,300 | 6,886 |
# Copyright 2016 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
"""Datastore model for GCE Backend."""
from google.appengine.ext import ndb
from google.appengine.ext.ndb import msgprop
from components.machine... | 6,388 | 1,852 |
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
),
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle',
'core.throttling.PreSingUpThrottle',
),
'DEFAULT_THRO... | 456 | 176 |
from driver import driver
driver.printWhatIneed(driver)
| 57 | 17 |
import argparse
import json
from tqdm import tqdm
import numpy as np
params = {
'src':{
'train': './data/{ds}/statement/train.statement.jsonl',
'dev': './data/{ds}/statement/dev.statement.jsonl',
},
'tgt':{
'train': './data/{ds}/statement/train.statement_.jsonl',
'dev': './d... | 1,430 | 530 |
# Copyright 2015 Mirantis, Inc.
#
# 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,813 | 578 |
import platform, os
try:
if platform.system() == 'Windows':
os.system('cls')
else:
os.system('clear')
except:
pass
# Foreground colors
def black():
return '\u001b[30;1m'
def red():
return '\u001b[31;1m'
def green():
return '\u001b[32;1m'
def yellow():
return '\u001b[33;1... | 1,016 | 476 |
from .hash import HashUtil
from .log import log, LogUtil
from .choice import Choice, ChoiceUtil
from .parameter_keys import ParameterKeys
from .page import PageAdapter, Page, PageListABC
from .response import get_serializer_error_code
| 235 | 63 |
## @ingroup Optimization
# line_plot.py
#
# Created: Oct 2017, M. Vegh
# Modified: Nov 2017, M. Vegh
# May 2021, E. Botero
# ----------------------------------------------------------------------
# Imports
# -------------------------------------------
from SUAVE.Core import Data
import numpy as np
imp... | 3,164 | 996 |
import numpy as np
import pytest
import torch
from d3rlpy.models.torch import ContinuousQRQFunction, DiscreteQRQFunction
from d3rlpy.models.torch.q_functions.qr_q_function import _make_taus
from d3rlpy.models.torch.q_functions.utility import (
pick_quantile_value_by_action,
)
from ..model_test import (
DummyE... | 4,725 | 1,894 |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | 1,636 | 472 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | 2,553 | 779 |
import json
import datetime
import imghdr
import os
from ebooklib import epub
from .util import Log, do_hash, downoad_image, format_filename
from .util import ImageData, TmpImageData
class Chapter:
def __init__(self, title='', content=''):
self.title = title
self.content = content
self.f... | 5,730 | 1,715 |
def soma(num1, num2):
soma1 = num1
soma2 = num2
soma_total = soma1 + soma2
return soma_total
def sub(num1, num2):
sub1 = num1
sub2 = num2
sub_total = sub1 - sub2
return sub_total
def mult(num1, num2):
mult1 = num1
mult2 = num2
mult_total = mult1 * mult2
return mult_tota... | 537 | 236 |
import os
from setuptools import setup, find_packages
# Get the README.md text
with open(os.path.join(os.path.dirname(__file__), 'README.md'), 'r') as f:
readme = f.read()
# Parse vfxwindow/__init__.py for a version
with open(os.path.join(os.path.dirname(__file__), 'vfxwindow/__init__.py'), 'r') as f:
for li... | 2,510 | 825 |
import pytest
import tamr_client as tc
from tests.tamr_client import fake
@fake.json
def test_from_project():
s = fake.session()
project = fake.mastering_project()
unified_dataset = tc.dataset.unified.from_project(s, project)
assert unified_dataset.name == "dataset 1 name"
assert unified_dataset... | 1,085 | 358 |
from __future__ import annotations
import pytest
import stk
def build_kagome(
lattice_size: tuple[int, int, int],
) -> stk.ConstructedMolecule:
bb1 = stk.BuildingBlock('BrCCBr', [stk.BromoFactory()])
bb2 = stk.BuildingBlock(
smiles='BrC1C(Br)CC(Br)C(Br)C1',
functional_groups=[stk.BromoFa... | 827 | 328 |
# Write your solution here
def who_won(game_board: list):
score1 = 0
score2 = 0
for row in game_board:
for square in row:
if square == 1:
score1 += 1
if square == 2:
score2 += 1
if score1 > score2:
return 1
elif score1 <score2:
... | 363 | 115 |
"""
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agr... | 4,538 | 1,482 |
"""
This script allows a trained policy to control the simulator.
Usage:
"""
import sys
import argparse
import pyglet
import math
from pyglet import clock
import numpy as np
import gym
import gym_miniworld
import torch
from policy import DDPGActor
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
device = torch... | 3,027 | 1,076 |
import numpy as np
import scipy.optimize as sciopt
def UniformBeamBendingModes(Type,EI,rho,A,L,w=None,x=None,Mtop=0,norm='tip_norm',nModes=4):
"""
returns Mode shapes and frequencies for a uniform beam in bending
References:
Inman : Engineering variation
Author: E. Branlard"""
if x is N... | 7,000 | 3,006 |
## =================================================================== ##
# this is file calor1d-mdf.py, created at 10-Aug-2021 #
# maintained by Gustavo Rabello dos Anjos #
# e-mail: gustavo.rabello@gmail.com #
## =======================... | 2,095 | 839 |
# **********************************************************************
#
# Copyright (c) 2019, Autonomous Systems Lab
# Author: Dongho Kang <eastsky.kang@gmail.com>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
... | 3,115 | 1,074 |
from matplotlib import pyplot as plt
import numpy as np
gene_names = ("Hxt1", "Has1", "Tda1", "Gal1", "Gal7", "Gal10", "Gal3", "Gal4", "Gal2")
sgds = np.array(["YHR094C", "YMR290C", "YMR291W", "YBR020W", "YBR018C", "YBR019C", "YDR009W", "YPL248C", "YLR081W"])
logfcs = np.zeros((len(sgds), 1))
with open("rnaseq_counts... | 1,130 | 558 |
from datetime import datetime, time, timedelta
import requests
class Api:
"""
Base class for interfacing with the Basketball API.
"""
def __init__(self):
self.url = 'https://v1.basketball.api-sports.io/'
with open('secrets/api_key') as f:
self.api_key = f.readline()
... | 1,221 | 383 |
try:
from .local import *
except Exception:
from .production import *
| 78 | 22 |
from torch.utils.data import Dataset
import numpy as np
import os
import random
import torchvision.transforms as transforms
from PIL import Image, ImageOps
import cv2
import torch
from PIL.ImageFilter import GaussianBlur
import trimesh
import logging
import json
from math import sqrt
import datetime
log = logging.getL... | 18,619 | 6,452 |
import re
from corehq.apps.app_manager.management.commands.helpers import AppMigrationCommandBase
from corehq.apps.app_manager.models import Application, load_app_template, ATTACHMENT_REGEX
from corehq.apps.app_manager.util import update_unique_ids
from corehq.apps.es import AppES
def _get_first_form_id(app):
ret... | 1,452 | 453 |
from .create_epoch import sim_data
| 35 | 12 |
import os, sys
R = '\x1b[1;31m'
N = '\x1b[0m'
Y = '\x1b[1;33m'
G = '\x1b[1;37m'
print '%s+---------------------------------------------------+%s' % (R, N)
print '%s||[#]%s--------------%s[ VBug Maker ]%s---------------%s[#]||%s' % (Y, R, Y, R, Y, N)
print '%s||%s |___________%s[ Simple Virus Maker ]%s____________|%s ||... | 1,582 | 736 |
from django import forms
from django.utils.translation import ugettext_lazy as _
from .models import Voucher, VoucherUser, Campaign
from .settings import VOUCHER_TYPES
class VoucherGenerationForm(forms.Form):
quantity = forms.IntegerField(label=_("Quantity"))
value = forms.IntegerField(label=_("Voucher Code"))... | 3,131 | 890 |
revision = '5a99c71e171'
down_revision = '1b8378b8914'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
op.create_table('position',
sa.Column('id', postgresql.UUID(), nullable=False),
sa.Column('title', sa.Text(), nullable=True),
sa.... | 603 | 202 |
import typing as ty
from . import base
class Section(base.SectionBase):
@base.returns_no_item
def forward(self, protocol: str, peer_id: str, port: str, **kwargs: base.CommonArgs):
"""Forward connections to libp2p service
Forward connections made to the specified port to another IPFS node.
... | 3,401 | 904 |
import teek
from teek._tcl_calls import make_thread_safe
# there's no after_info because i don't see how it would be useful in
# teek
class _Timeout:
def __init__(self, after_what, callback, args, kwargs):
if kwargs is None:
kwargs = {}
self._callback = callback
self._args =... | 2,562 | 749 |
"""Utils to work with executors"""
from typing import Any, Dict
import plynx.db.node
import plynx.utils.exceptions
import plynx.utils.plugin_manager
def materialize_executor(node_dict: Dict[str, Any]):
"""
Create a Node object from a dictionary
Parameters:
node_dict (dict): dictionary representation... | 704 | 234 |
from django.urls import path, include
urlpatterns = [
path('model_viewer/', include('cyder.models.urls')),
path('projects/', include('cyder.projects.urls')),
path('api/', include('cyder.api.urls', namespace='api')),
path('', include('cyder.main.urls')),
]
| 273 | 92 |
# -*- coding: utf-8 -*-
import cherrypy
from microblog.web import MICROBLOG_SESSION_PROFILE
from microblog.web.oidtool import DEFAULT_SESSION_NAME
from microblog.profile.manager import ProfileManager
from microblog.profile.user import EmptyUserProfile, UserProfile
from microblog.web.speakup import SpeakUpWebApplication... | 4,173 | 1,259 |
#! /usr/bin/env python2
# -*- coding: utf-8 -*-
import sf
import sys
def main():
window = sf.RenderWindow(sf.VideoMode(640, 480), 'RenderImage example')
window.framerate_limit = 60
running = True
rect0 = sf.Shape.rectangle(5, 5, 90, 50, sf.Color.GREEN, 2, sf.Color.BLUE)
rect1 = sf.Shape.rect... | 879 | 377 |
#!/usr/bin/env python
"""
this module need easy_logging
"""
import os
import pandas as pd
import numpy as np
from easy_logging.easylogging import EasyVerboseLogging
EVLobj = EasyVerboseLogging()
EVLobj.set_class_logger_level('INFO')
EVLobj.get_class_logger()
class HitZombieRoad(object):
def __init__(self):
... | 21,867 | 6,636 |
# proxy module
from __future__ import absolute_import
from envisage.i_application import *
| 91 | 26 |
from .executor import ScriptExecutor
import logging
SCRIPT_CONFIG = [
# health check script before install package
{
"name": 'install_package_pre_check',
"search_path": ["${TESTCASE_PATH}/AreaCI/${PID}/install_package_pre_check",
"${BRANCH_ROOT}/PlatformCI/${PID}/${PRODUCT}/${TES... | 4,085 | 1,313 |
# -*- coding: utf_8 -*-
SCOPES = ['https://www.googleapis.com/auth/photoslibrary']
API_SERVICE_NAME = 'photoslibrary'
API_VERSION = 'v1'
CLIENT_SECRET_FILE = 'client_secret.json'
CREDENTIAL_FILE = 'credential.json'
AQUIRED_MEDIA_LIST = 'aquired_list.json'
TMP_DIR = 'tmp'
DESTINATION_DIR = '/gpbk'
QUERY_FILTER = True
PA... | 453 | 212 |
class Starter:
def start(self, notification_sender, server_actor_ref):
raise NotImplementedError
| 109 | 31 |
import logging
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http import JsonResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.views.generic import CreateView, DetailView, Update... | 10,968 | 2,972 |
from django import template
from ..models import News
register = template.Library()
@register.simple_tag(takes_context=True)
def cms_news_list(context, num_items=10):
page = context['request'].GET.get('page', 1);
page = int(page)
#todo: add num pages, total items..
return News.objects.language().all()... | 351 | 116 |
import sqlite3
db = sqlite3.connect("database.db")
cursor = db.cursor()
cursor.execute("CREATE TABLE model (VARCHAR models)") | 127 | 38 |
# Copyright (c) 2006-2009 The Trustees of Indiana University.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without ... | 6,143 | 2,433 |
from itertools import permutations
if __name__ == "__main__":
map = { }
with open('../input.txt', 'r') as fp:
while True:
line=fp.readline()
if line is None or line == '':
break
parts = line.split(" ")
person = parts[0]
value = int(parts[3])
if parts[2] == 'lose':
value = value * -1
ne... | 1,049 | 434 |
# Generated by Django 3.1.6 on 2021-02-19 15:45
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("memberaudit", "0004_wallet_transactions"),
]
operations = [
migrations.CreateModel(
name="Chara... | 2,755 | 674 |
"""Just an empty models file to let the testrunner recognize this as app."""
from django.conf import settings
from django.contrib.contenttypes import fields
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_... | 13,031 | 3,621 |
"""
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agr... | 2,170 | 739 |
#!/usr/bin/env python
import webapp2
downloads_html = """<html>
<body>
download the latest build at:
<table>
<tr>
<th>os</th>
<th>download link</th>
</tr>
<tr>
<td>linux amd64</td>
<td><a href='https://go-lanscan.appspot.com/go-lanscan'>https://go-lanscan.appspot.com/go-lanscan</a></td>
</tr>
</table>
Source code at <... | 618 | 254 |
import pandas as pd
from tqdm import tqdm
from schools3.data.datasets.datasets_generator import DatasetsGenerator
from schools3.ml.experiments.models_experiment import ModelsExperiment
from schools3.config import main_config
# an experiment that trains models and reports metrics for multiple grades
class MultiDataset... | 1,437 | 432 |
# AUTOGENERATED! DO NOT EDIT! File to edit: 00_scrapers.ipynb (unless otherwise specified).
__all__ = ['make_session', 'make_browser', 's', 'browsers', 'cache_db', 'RS_URLS', 'ITEM_FORM', 'KW_OPTIONS', 'FORMATS',
'LOCATIONS', 'ACCESS', 'AGENCY_FORM', 'AGENCY_LOCATIONS', 'AGENCY_STATUS', 'SERIES_FORM', 'RSBa... | 43,906 | 12,769 |
__author__ = "Johannes Köster"
__copyright__ = "Copyright 2016, Johannes Köster"
__email__ = "koester@jimmy.harvard.edu"
__license__ = "MIT"
from snakemake.shell import shell
shell(
"bcftools view {snakemake.params} {snakemake.input[0]} " "-o {snakemake.output[0]}"
)
| 276 | 117 |
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | 4,728 | 1,945 |
import uvicorn
HOST = "127.0.0.1"
PORT = 8000
ENV = ".misc/env/dev.env"
SERVICE = "app.main:service"
LOG_LEVEL = "trace"
if __name__ == "__main__":
uvicorn.run(SERVICE, host=HOST, port=PORT, log_level=LOG_LEVEL, workers=4, env_file=ENV, reload=True)
| 256 | 118 |