text string | size int64 | token_count int64 |
|---|---|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2011, Nicolas Clairon
# 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 code must retain the abov... | 4,322 | 1,348 |
from kafka_cosumer_test import f
# i = 203
# f.push(i)
for i in range(200):
f.push(i)
| 93 | 49 |
# coding: utf-8
"""
CLOUD API
IONOS Enterprise-grade Infrastructure as a Service (IaaS) solutions can be managed through the Cloud API, in addition or as an alternative to the \"Data Center Designer\" (DCD) browser-based tool. Both methods employ consistent concepts and features, deliver similar power and ... | 5,920 | 1,735 |
"""
LeetCode Problem: 96. Unique Binary Search Trees
Link: https://leetcode.com/problems/unique-binary-search-trees/
Video Link: https://www.youtube.com/watch?v=CMaZ69P1bAc
Resources: https://en.wikipedia.org/wiki/Catalan_number
Written by: Mostofa Adib Shakib
Language: Python
For Catalan(3)
Catalan(2)
... | 1,169 | 391 |
class GenerateEmail:
def __init__(self, name):
self.names = name.lower().split()
local_part_list = []
for generator in self._get_all_generators():
local_part = self._call_generator(generator)
local_part_list.append(local_part)
self._list = list(map(self._c... | 1,921 | 644 |
#!/usr/bin/env python
import sys
import os
import re
import subprocess
import shellpython.config as config
from shellpython.preprocessor import preprocess_file
from argparse import ArgumentParser
from shellpython.constants import *
def main2():
main(python_version=2)
def main3():
main(python_version=3)
de... | 2,252 | 732 |
#!/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... | 3,833 | 1,159 |
# 이것이 코딩테스트다 p.152
# Sample Input:
# 5 6
# 101010
# 111111
# 000001
# 111111
# 111111
# Output : 10
from collections import deque
# Complexities : Time O(NM) | Space O(NM)
if __name__ == "__main__":
N, M = map(int, input().split())
maze = []
for _ in range(N):
maze.append(list(map(int, input()))... | 963 | 413 |
import os
import sys
import numpy as np
from scipy.io import wavfile
from time import *
import torch
import utils
from models import SynthesizerTrn
def save_wav(wav, path, rate):
wav *= 32767 / max(0.01, np.max(np.abs(wav))) * 0.6
wavfile.write(path, rate, wav.astype(np.int16))
# define mod... | 2,014 | 917 |
import utils.mysql.mysql_common_util as mysql_util
import configparser,os,time
cf = configparser.ConfigParser()
cf.read(os.path.dirname(__file__)+"/../conf.ini")
# conf对应的数据库key
key = "localhost"
# 创建当前数据库的连接池对象
class service(object):
def __init__(self):
environment = cf.get(key,"environment")
for... | 2,891 | 1,062 |
"""
题目:数组中出现次数超过一半的数字
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。
由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
思路一:可遍历整个数组 并且用字典记录每个元素出现的频率 然后再次遍历字典 如果出现频率超过一半 返回该元素 否则返回0 这是一种用空间换时间的做法
时间复杂度为O(n) 空间复杂度为O(n)
思路二:如果某个元素出现的频率超过长度的元素 则排序之后 该元素必然出现在中间位置 在此我们借用Partition函数 每次运行该函数 便能排好一个元素
... | 2,967 | 1,326 |
import pcl
import open3d as o3d
import numpy as np
import load
import plane_segmentation
import eulcidian_cluster
import manual_registration
import filter_outliers
import measure_cloud
import global_registration
import reg_grow_segmentation
import convert
import resample
import voxel_grid
import time
import uuid
from s... | 9,559 | 2,865 |
import os
import shutil
import subprocess
import numpy as np
import meshio
from .base import MoldflowAutomation
from .data_io import PatranMesh, convert_to_time_series_xdmf, read_moldflow_xml
class MoldflowResultsExporter(MoldflowAutomation):
"""
Export Autodesk Moldflow simulation results
... | 14,673 | 4,605 |
nums = """75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 4... | 819 | 600 |
# Copyright Amazon.com Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompany... | 2,738 | 890 |
# Copyright 2016 Pratyush Sahay
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | 2,071 | 670 |
from enum import Enum
import cv2
class Camera(Enum):
LEFT = 0,
RIGHT = 1
def OnClick(event, x, y, flags, params):
if event == cv2.EVENT_LBUTTONDOWN:
if (params == Camera.LEFT):
print ("DDD")
elif (params == Camera.RIGHT):
print ("MDR")
leftImage = cv2.imread("imag... | 792 | 296 |
import battlecode as bc
from enum import Enum
class BattleStrategy(Enum):
Deffensive = 0
Offensive = 1
class Strategy:
__instance = None
battle_strategy = None
min_nr_units_for_offense = None
enemy_start_close = False
research_strategy = [
bc.UnitType.Worker,
bc.UnitTy... | 7,674 | 2,247 |
# stackweb.py - Core classes for web-request stuff
from __future__ import print_function
from stackexchange.core import StackExchangeError
from six.moves import urllib
import datetime, operator, io, gzip, time
import datetime
try:
import json
except ImportError:
import simplejson as json
class TooManyRequests... | 6,162 | 1,759 |
# -*- coding: utf-8 -*-
"""
Setup try package.
"""
import ast
import re
from setuptools import setup, find_packages
def get_version():
"""Gets the current version"""
_version_re = re.compile(r"__VERSION__\s+=\s+(.*)")
with open("trypackage/__init__.py", "rb") as init_file:
version = str(ast... | 1,484 | 473 |
"""
mbed SDK
Copyright (c) 2011-2015 ARM Limited
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wr... | 5,470 | 1,566 |
from proxypool.crawlers.base import BaseCrawler
PROXY_TYPE = range(1, 3)
MAX_PAGE = 7
BASE_URL = 'http://www.ip3366.net/free/?stype={stype}&page={page}'
class Ip3366Crawl(BaseCrawler):
"""
ip3366 http://www.ip3366.net
如果不想获取器执行这个代理 可以设置:ignore = True
"""
urls = [BASE_URL.format(stype=... | 845 | 353 |
#!/Users/lindsaychuang/miniconda3/envs/obspy/bin/python
# this file defines all the layouts used in apps
import dash_core_components as dcc
import dash_html_components as html
import dash_table
import dash_daq as daq
from dash_table.Format import Format
import datetime
# ---- 01. map layout ------
map_layout = {
... | 10,982 | 3,411 |
from ... pyaz_utils import _call_az
def show():
return _call_az("az ad signed-in-user show", locals())
def list_owned_objects(type=None):
'''
Get the list of directory objects that are owned by the user
Optional Parameters:
- type -- object type filter, e.g. "application", "servicePrincipal" "g... | 413 | 130 |
import gym
import pybullet, pybullet_envs
import torch as th
from stable_baselines3 import PPO
from stable_baselines3.common.evaluation import evaluate_policy
# Create environment
# env = gym.make('LunarLanderContinuous-v2')
env = gym.make('BipedalWalker-v3')
# env.render(mode="human")
policy_kwargs ... | 1,342 | 504 |
#!/usr/bin/python
import matplotlib
matplotlib.use('Agg') # Force matplotlib to not use any Xwindows backend.
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
import elements
#print dir( elements )
import basUtils
print(" # ========== make & load ProbeParticle C++ library ")
def makecle... | 5,886 | 2,482 |
"""create table in postgresql"""
from config import config
import psycopg2
def create_tables():
sql = """CREATE TABLE astronauts_in_space (name VARCHAR(255) NOT NULL,
craft VARCHAR(20) NOT NULL)"""
conn = None
try:
# read connection parameters
params = config()
# connect to th... | 820 | 235 |
from pypy.rpython.lltypesystem import lltype
from pypy.rpython.lltypesystem.lloperation import llop
class SemiSpaceGCTests:
large_tests_ok = False
def test_finalizer_order(self):
import random
from pypy.tool.algo import graphlib
examples = []
if self.large_tests_ok:
... | 4,403 | 1,113 |
import numpy as np
from auxein.population import build_individual
from auxein.fitness.observation_based import ObservationBasedFitness, MultipleLinearRegression, MaximumLikelihood
def test_multiple_linear_regression():
xs = np.array([[23], [26], [30], [34], [43], [48], [52], [57], [58]])
y = np.array([651, 7... | 2,025 | 949 |
"""Taco app signals"""
from django.db.models.signals import pre_save
from django.dispatch import receiver
from .models import Order
@receiver(pre_save, sender=Order)
def update_subtotal(sender, instance, **kwargs):
taco_price = instance.taco.price
quantity = instance.quantity
instance.subtotal = taco_pric... | 403 | 118 |
from django.conf.urls import url
from . import views
urlpatterns = [
url('api/users', views.UserCreate.as_view(), name='account-create'),
url('tasks', views.TaskCreate.as_view(), name='tasks-create'),
url('tasks2', views.Task2Create.as_view(), name='tasks-create'),
url('project', views.ProjectCreate.a... | 418 | 135 |
from .accountant import KyberAccountant # noqa: F401
from .decoder import KyberDecoder # noqa: F401
| 102 | 39 |
from flask import render_template, url_for, redirect, request, Blueprint
from highbrow.posts.forms import PostForm
from highbrow.posts.utils import fetch_post, create_comment, fetch_comments, like_unlike_post
from highbrow.utils import fetch_notifications, if_is_liked, if_is_saved
from flask_login import current_user
... | 1,739 | 544 |
from tinycards.client import Tinycards
| 39 | 11 |
"""
This file is mainly for generating human-viewable images from completed predictions, given greyscale images.
Usually run after generate_predictions.py.
Further documentation can be found in each method / main function documentation.
-Blake Edwards / Dark Element
"""
import os, sys, h5py, pickle, cv2
import numpy... | 11,001 | 2,739 |
from genericpath import isfile
import os
for file in os.path.listdir(os.curdir):
if not isfile(file) or file.endswith(".npz"):
print("Skipping {}".format(file))
continue
| 191 | 63 |
import json
import os
from pathlib import Path
from fishbase.fish_logger import logger
from pydantic import BaseModel, Field
class AddonsError(Exception):
pass
class AddonsInfo(BaseModel):
identifier: str = Field(...)
name: str = Field(default='', title='', description='')
title: str = Field(...)
... | 3,540 | 970 |
#author Timothy Do
#RPiMorse Console: Prints Input in Morse Code to Console
#Note: Only works with Python3, For Python2, run morse2.py
from time import sleep
import sys
#Functions for Dots, Dashes
def dot():
print(".\a", end="")
sleep(0.1)
sys.stdout.flush()
def dash():
print("-\a\a\a", end="")
... | 9,377 | 3,049 |
net = dict(
type='Detector',
)
backbone = dict(
type='ResNetWrapper',
resnet='resnet18',
pretrained=True,
replace_stride_with_dilation=[False, False, False],
out_conv=False,
)
featuremap_out_channel = 512
griding_num = 100
num_classes = 6
heads = dict(type='LaneCls',
dim = (griding_num... | 2,319 | 965 |
def solve(s):
t=" "
c = ""
for i in s:
if t == ' ':
c += i.upper()
else:
c += i
t = i
return c
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = solve(s)
fptr.write(result + '\n')
... | 334 | 128 |
# Copyright 2020-present, Netherlands Institute for Sound and Vision (Blazej Manczak)
#
# 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
#
# Unl... | 4,429 | 1,216 |
"""
Create .serialize and .parse methods to handle json operations
Where orjson is installed, the performance impact is nil, without orjson, parsing is
about as fast as ujson, however serialization is slower, although still faster than the
native json library.
"""
from typing import Any, Union
import datetime
try:
... | 2,392 | 687 |
"""
@Version 0.3.3
@Author B1ACK917
@Contributor YuanWind
"""
import json
import os
from tqdm import tqdm
import time
import copy
import matplotlib.pyplot as plt
from genHTML import gen
import platform
def check_bomb(server, VMList, serverDict, VMDict, serverIDMap, VMIDMap, vmid2node):
"""
判断一个服务器是否发生资源溢出
... | 15,191 | 5,652 |
from ...settings.config import data
from rest_framework.views import APIView
from django.http import JsonResponse
from .order.diary_serializer import HomeDiarySerializer
from ...utils.AppFunctools import modelObject
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
class DiaryApi(APIView):
... | 1,215 | 436 |
"""PyTest cases related to the integration between FERC1 & EIA 860/923."""
import logging
import os
import sys
import geopandas as gpd
import pytest
import pudl
logger = logging.getLogger(__name__)
@pytest.fixture(scope="module")
def fast_out(pudl_engine, pudl_datastore_fixture):
"""A PUDL output object for us... | 4,120 | 1,639 |
import SCons
def exists(env):
return True
def generate(env):
env.Tool('install')
suffix_map = {
env.subst('$PROGSUFFIX') : 'bin',
'.dylib' : 'lib',
'.so' : 'lib',
}
def auto_install(env, target, source, **kwargs):
prefixDir = env.Dir('$INSTALL_DIR')
acti... | 3,645 | 1,040 |
from bitmovin_api_sdk.encoding.configurations.audio.eac3.customdata.customdata_api import CustomdataApi
| 104 | 34 |
#!/usr/bin/env python
import os
import imaplib
path = os.path.dirname(os.path.realpath(__file__))
mail_client = imaplib.IMAP4_SSL('imap.gmail.com', '993')
if not os.path.isfile(f"{path}/config.py"):
print(f"⚠ No mail config found. Check out \"{path}/config.py\"")
exit()
else:
from config import *
mail_c... | 637 | 242 |
#!/usr/bin/python
'''
sys is needed for argv
pilsuc = False for importing pil
try tries to import pillow but will install via pip if it fails
pillow used for image manipulation
open method opens the base image
truetype method opens font file
if arguments passed to, join method creats text of args
else in case no arg... | 1,069 | 344 |
import os
import sys
path = os.path.dirname(sys.path[0])
if path and path not in sys.path:
sys.path.append(path)
from flask import Flask
app = Flask("Product")
@app.route("/")
def welcome():
return "欢迎来到通达信数据分析的世界"
if __name__ == '__main__':
app.run()
| 271 | 117 |
#!/usr/bin/env python3
import os
import argparse
from typing import Iterator
from typing import Set
import sqlite3
import pandas as pd
from predectorutils.database import (
load_db,
ResultsTable,
ResultRow,
TargetRow
)
def cli(parser: argparse.ArgumentParser) -> None:
parser.add_argument(
... | 1,995 | 611 |
class Serial():
def __init__(self, port, baudrate, timeout):
self.baudrate = baudrate
def read(self, n): return [0,]*n
def close(self): pass
| 161 | 55 |
"""
A* implementation entry point.
Claire Durand
03/10/2017
"""
from graph import Graph
g = Graph()
# Add nodes
start = g.add_node('START', 0, 1)
a = g.add_node('A', 1, 1)
b = g.add_node('B', 2, 1)
c = g.add_node('C', 2, 0)
d = g.add_node('D', 3, 1)
f = g.add_node('F', 2, 2)
o = g.add_node('O', 4, 1)
h = g.add_node... | 539 | 297 |
"""Support for Python rostest scripts."""
# _expand_template is used to generate boilerplate files required by rostest.
def _expand_template_impl(ctx):
ctx.actions.expand_template(
template = ctx.file.template,
output = ctx.outputs.out,
substitutions = ctx.attr.substitutions,
)
_expand... | 3,898 | 1,222 |
#!/usr/bin/env python
"""
Operations over generic quantities of H5 files
"""
import h5py as h5
import sys
def mean_over_files(fnames, key):
"""
Calculate the mean of of a value over a list of h5 files
Parameters
----------
fnames: list of str
list of hdf5 files with identical keys
key... | 1,740 | 539 |
class TextBox(RibbonItem):
""" The TextBox object represents text-based control that allows the user to enter text. """
Image = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""The image of the TextBox.
Get: Image(self: TextBox) -> ImageSource
Set: Image(self: T... | 1,752 | 598 |
jogador = dict()
jogadores = list()
dec = ' '
while dec not in 'Nn':
jogador['nome'] = str(input('Qual o nome do jogador? ')).strip().title()
i = int(input(f'Quantas partidas {jogador["nome"]} jogou? '))
gols = []
for i in range(1, i+1):
gols.append(int(input(f'Quantos gols {jogador["nome"]} fez... | 1,455 | 599 |
"""
@author: Anthony Soulain (University of Sydney)
-------------------------------------------------------------------------
AMICAL: Aperture Masking Interferometry Calibration and Analysis Library
-------------------------------------------------------------------------
Function related to data cleaning (ghost, bac... | 25,168 | 8,690 |
import os
import sys
import salt.config
import salt.client
import salt.runner
import salt.key
import pymongo
from salt.output import highstate
from functools import wraps
def mproperty(fn):
attribute = "_memo_%s" % fn.__name__
@property
@wraps(fn)
def _property(self):
if not hasattr(self,... | 3,547 | 1,160 |
import graphene
from graphene_django import DjangoObjectType
from app.models import City
from app.models import Continent
from app.models import Country
from app.models import District
from app.models import Governor
from app.models import Mayor
from app.models import State
from leo_optimizer import gql_optimizer
... | 1,229 | 366 |
# import libraries
import os
import numpy as np
import torch
from six import BytesIO
from torchvision import datasets, models, transforms
import torch.nn as nn
# default content type is numpy array
NP_CONTENT_TYPE = 'application/x-npy'
def model_fn(model_dir):
"""Load the PyTorch model from the `model_dir` direc... | 2,633 | 823 |
# Copyright 2016 John Reese
# Licensed under the MIT license
import asyncio
import logging
from concurrent.futures import CancelledError
from typing import Any
from .task import Task
Log = logging.getLogger('tasky.tasks')
class QueueTask(Task):
'''Run a method on the asyncio event loop for each item inserted ... | 2,799 | 792 |
from __future__ import unicode_literals
from trebelge import api
def every_day_at_02_38():
api.check_all_ebelge_parties()
| 129 | 51 |
from flask import render_template, redirect, url_for, flash, make_response, session, json
from . import app, models, helper, websocket
from .forms import IndexForm, GameForm
@app.route('/', methods=['GET', 'POST'])
def index():
form = IndexForm()
if form.validate_on_submit():
#: check if the game alr... | 2,076 | 668 |
from context import fe621
import numpy as np
import pandas as pd
def truncationErrorAnalysis():
"""Function to analyze the truncation error of the Trapezoidal and Simpson's
quadature rules.
"""
# Objective function
def f(x: float) -> float:
return np.where(x == 0.0, 1.0, np.sin(x) / x)
... | 1,976 | 731 |
from astropy.stats import LombScargle as astropy_LombScargle
from astropy.stats.lombscargle.core import strip_units
from astropy.stats.lombscargle.implementations.main import _get_frequency_grid
from .nfftls import lombscargle_nfft
class LombScargle(astropy_LombScargle):
__doc__ = astropy_LombScargle.__doc__
... | 8,244 | 2,038 |
import librosa
from base.base_model import BaseModel
from keras.models import Sequential
from keras.layers import Dense, Conv2D, MaxPooling2D, Dropout, Flatten
class AccentModel(BaseModel):
def __init__(self, config):
super(AccentModel, self).__init__(config)
self.build_model()
def build_mo... | 1,188 | 395 |
import FWCore.ParameterSet.Config as cms
# Silicon Strip Digitizer running with APV Mode Deconvolution
from SimGeneral.MixingModule.stripDigitizer_cfi import *
stripDigitizer.APVpeakmode = False
| 199 | 67 |
from django.core.serializers.json import DjangoJSONEncoder
from django.http import JsonResponse, HttpResponse, Http404
from drf_yasg.openapi import Schema, TYPE_STRING, TYPE_OBJECT
from drf_yasg.utils import swagger_auto_schema
from rest_framework import status, serializers, permissions
from rest_framework.generics imp... | 5,480 | 1,518 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This script enable custom installation of Microsoft Office suite.
You can install/uninstall specific product.
"""
import argparse
import os
import sys
import xml.etree.ElementTree as ET
ALL_PRODUCTS = ['Word', 'Excel', 'PowerPoint', 'Access',
'Groove... | 5,267 | 1,523 |
from django.urls import path
from arike.visits.views import (
ScheduleCreateView,
ScheduleDeleteView,
ScheduleDetailView,
ScheduleListVeiw,
ScheduleUpdateView,
TreatmentNoteCreateView,
TreatmentsListVeiw,
VisitDetailsCreateView,
)
app_name = "visits"
urlpatterns = [
path("schedule/... | 954 | 326 |
import cv2
import numpy as np
from scipy import ndimage
def dog(img, size=(0,0), k=1.6, sigma=0.5, gamma=1):
img1 = cv2.GaussianBlur(img, size, sigma)
img2 = cv2.GaussianBlur(img, size, sigma * k)
return (img1 - gamma * img2)
def xdog(img, sigma=0.5, k=1.6, gamma=1, epsilon=1, phi=1):
aux = dog(img, s... | 1,790 | 770 |
import os
import platform
try:
from ConfigParser import ConfigParser
except ImportError:
from configparser import ConfigParser
class TestSetupError(Exception):
"""Generic Error with parsing Test Setup configuration"""
pass
class TestSetup(object):
"""Class used for accessing various settings in t... | 3,033 | 816 |
import base64
import dns.resolver
import json
import logging
import requests
import shlex
from vrs import is_base64, is_json
from configparser import ConfigParser
logger = logging.getLogger('pyvrs')
class VRSDecodeError(Exception):
"""Catchall VRS error for decoding issues."""
class Resolver:
"""Base resol... | 3,238 | 943 |
import unittest
from policy_sentry.writing.template import create_actions_template, create_crud_template
class TemplateTestCase(unittest.TestCase):
def test_actions_template(self):
desired_msg = """# Generate my policy when I know the Actions
mode: actions
name: myrole
description: '' # For human auditabi... | 1,166 | 348 |
<<<<<<< HEAD
res = 0
a= 100
for i in range(1, 3):
res = a >> i
#print(f' 중간값 {res}')
res = res + 1
#print(f' 중간값+1 {res}')
#print(f' 최종값 {res}')
print(res)
# 정처기 비트이동문제 구현
=======
coffee = {'아메리카노':2500,'카푸치노':3500,'카페라떼':3000,'레몬레이드':2000}
for c in sorted(coffee.items(),key=lambda x:x[1],reverse=T... | 460 | 317 |
from .private._curry2 import _curry2
objOf = _curry2(lambda key, val: {key: val})
"""
Since in JavaScript we can represent key-value as object,
but in Python, we can't.
So we treat objOf only works for dict in Python.
But for the naming convention, we keep the name of objOf.
"""
| 281 | 91 |
__author__ = "Oliver Lindemann"
__version__ = "0.3"
from ._config import DAQConfiguration
from ._pyATIDAQ import ATI_CDLL
from .. import USE_DUMMY_SENSOR
#### change import here if you want to use nidaqmx instead of pydaymx ####
try:
# from ._daq_read_Analog_pydaqmx import DAQReadAnalog
from ..daq._daq_read_... | 548 | 212 |
"""AI Feynman
"""
from .sklearn import AIFeynmanRegressor
from .S_run_aifeynman import run_aifeynman
from .get_demos import get_demos
__title__ = "aifeynman"
__version__ = "2.0.7.6"
__license__ = "MIT"
__copyright__ = "Copyright 2020 Silviu-Marian Udrescu"
__all__ = ["run_aifeynman", "AIFeynmanRegressor"]
| 310 | 139 |
# -*- coding: utf-8 -*-
import re
# resource_dir = "data_text_clean/test/text"
# target_dir = "data_text_clean/test/text_new"
# # remove illegal encode whiteblanks
# with open(resource_dir, 'r') as f:
# for line in f.readlines():
# new = re.sub('\u3000',' ',line)
# with open(target_dir, 'a') as w:
# w.write(n... | 4,776 | 2,344 |
import torch
import numpy as np
import torch.nn.functional as F
import torch.optim as optim
from deeprobust.graph.defense import GCN
from deeprobust.graph.global_attack import DICE
from deeprobust.graph.utils import *
from deeprobust.graph.data import Dataset
import argparse
parser = argparse.ArgumentParser()
parser.... | 2,566 | 926 |
""".. include:: ../README.md
.. include:: ../docs/design-notes.md"""
| 69 | 25 |
SECRET_KEY = "test"
BASE_DIR = "/tmp"
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": "/tmp/db.sqlite3"
}
}
INCLUDED_APPS = [
"protected_media"
]
PROTECTED_MEDIA_ROOT = "/tmp/protected-media-test/"
PROTECTED_MEDIA_URL = "/myprotectedmedia/"
PROTECTED_MEDIA_SERV... | 427 | 188 |
"""
.. module:: prototools.logger
:platforms: Unix
:synopsis: Custom logger with ANSI coloring
.. moduleauthor:: Graham Keenan 2020
"""
# System imports
import time
import logging
from typing import Optional
ANSI_COLORS = {
'black': '\u001b[30m',
'red': '\u001b[31m',
'green': '\u001b[32m',
'... | 3,742 | 1,187 |
#!/usr/bin/env python
import aruco_msgs.msg
import geometry_msgs.msg
import rospy
import tf2_ros
from tf import transformations as t
class ExternalCamera():
def __init__(self):
rospy.init_node("camera_transform_publisher")
one_time = rospy.get_param("~one_time", False)
rate = ros... | 3,236 | 984 |
# Copyright 2019 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 agreed to in writing, ... | 2,418 | 887 |
import unittest
from game_fool import Card
from game_fool import Deck
class Test_game_fool(unittest.TestCase):
def test_1_fool_init(self):
'''
Тест1
Создал карту с мастью (suit)=2
и достоинством (rank)=3
Здесь сравниваю suit
'''
game_foll_unitest = Card(2,3)... | 2,192 | 794 |
import logging
import re
from core.downloader import is_extension_forbidden
from sites import zoom, polybox
logger = logging.getLogger(__name__)
def remove_vz_id(name):
return re.sub(r"[0-9]{3}-[0-9]{4}-[0-9]{2}L\s*", "", name)
async def process_single_file_url(session, queue, base_path, download_settings, ur... | 1,848 | 484 |
from threading import Timer
class StubTimer:
timers = []
def __init__(self, times_faster=10):
self.t = None
self.callback = None
self.times_faster = times_faster
print('Created stubtimer')
def init(self, period, mode, callback):
self.callback = callback
se... | 966 | 303 |
import flask
from base64 import standard_b64decode
from engine import Engine, EngineException
from nsd_v1.ns_descriptors import ns_descriptors as nsd_v1_ns_descriptors
from nsd_v1.pnf_descriptors import pnf_descriptors as nsd_v1_pnf_descriptors
from nsd_v1.subscriptions import subscriptions as nsd_v1_subscriptions
f... | 3,524 | 1,190 |
from abc import ABCMeta, abstractclassmethod
import logging
import numpy as np
import pandas as pd
from causalml.inference.meta.explainer import Explainer
from causalml.inference.meta.utils import check_p_conditions, convert_pd_to_np
from causalml.propensity import compute_propensity_score
logger = logging.getLogger... | 13,009 | 3,494 |
# Password Generator
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPalette, QIcon, QFont, QPixmap
from random import shuffle
class Generator:
def __init__(self):
# Create frame
frame = QFrame()
vb.addWidget(frame)
# Add label
form = QFor... | 3,213 | 1,119 |
"""p2 LocalStorage App Config"""
from django.apps import AppConfig
class P2LocalStorageConfig(AppConfig):
"""p2 LocalStorage App Config"""
name = 'p2.storage.local'
label = 'p2_storage_local'
verbose_name = 'p2 Local Storage'
| 245 | 80 |
"""
Preprocess the uscis I485 Adjustment of status data
1. Download the csv files from the website
2. Rename the file and omit unnecessary files
3. Extract information from csv and save it into csv file
Currently works from 2014 qtr 1 through 2019 qtr 2
"""
# standard library
from os.path import basename
import os
fro... | 16,887 | 4,560 |
#!/usr/bin/env python3
__author__ = 'Michael Niewoehner <c0d3z3r0>'
__email__ = 'mniewoeh@stud.hs-offenburg.de'
import os
import sys
import re
import base64
import subprocess
import argparse
def checkDependencies():
dep = ['hoedown', 'wkhtmltopdf']
missing = []
for d in dep:
if subprocess.getsta... | 4,709 | 1,641 |
from falcon import HTTPUnauthorized
from falcon_auth2.exc import AuthenticationFailure
from falcon_auth2.exc import BackendNotApplicable
from falcon_auth2.exc import UserNotFound
def test_exc():
assert issubclass(AuthenticationFailure, HTTPUnauthorized)
assert issubclass(BackendNotApplicable, HTTPUnauthorize... | 639 | 187 |
#!/usr/bin/env python3
import os
import tensorflow as tf
import numpy as np
from realsafe import CrossEntropyLoss, BIM
from realsafe.model.loader import load_model_from_path
from realsafe.dataset import imagenet, dataset_to_iterator
batch_size = 25
session = tf.Session()
model_path = os.path.join(os.path.dirname(os... | 1,416 | 569 |
# -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License, Version 2.0 (the "Lice... | 3,692 | 1,200 |
import json
class JsonSetting:
def __init__(self, settingFilePath="./giotto_setting.json"):
self.setting = json.loads(open(settingFilePath,'r').read())
def get(self, settingName):
return self.setting[settingName]
if __name__ == "__main__":
settingStringPath = './connector_setting.json'
... | 408 | 124 |
import sys
import ctypes
from Phidget22.PhidgetSupport import PhidgetSupport
from Phidget22.Async import *
from Phidget22.CodeInfo import CodeInfo
from Phidget22.IRCodeEncoding import IRCodeEncoding
from Phidget22.IRCodeLength import IRCodeLength
from Phidget22.PhidgetException import PhidgetException
from Phidget22.P... | 5,584 | 2,355 |