text string | size int64 | token_count int64 |
|---|---|---|
# Generated by Django 3.2.8 on 2022-02-14 23:01
import ckeditor_uploader.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ProjectSite', '0028_remove_blog_test2'),
]
operations = [
migrations.AddField(
model_name='blog',
... | 449 | 152 |
from typing import List, Optional, Union, Dict, Any
import logging
from copy import deepcopy
import numpy as np
from tqdm.auto import tqdm
try:
from elasticsearch.helpers import bulk
from elasticsearch.exceptions import RequestError
except (ImportError, ModuleNotFoundError) as ie:
from haystack.utils.imp... | 35,729 | 9,014 |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import numpy as np
import tables
convnet_datafile = '/home/vincent/data/emotiw2015/Datasets/convnet_data.h5'
mean_std_file = '/home/vincent/data/emotiw2015/Datasets/fertfd_mean_std.h5'
from data_provider import EmotionData
numpy_rng = np.random.RandomState(1)
fer_path =... | 1,617 | 693 |
import os
import sys
import urlparse
import traceback
from sqlalchemy.orm import scoped_session, sessionmaker
from flask import Flask, request, redirect, url_for, escape
from flask.ext.admin import Admin, BaseView, expose
if __name__ == '__main__':
sys.path.insert(0, '.')
from weblab.core.exc import SessionNotF... | 11,591 | 3,420 |
"""
Given an array of integers nums and a positive integer k, find whether it's possible to divide this array into
k non-empty subsets whose sums are all equal.
Example 1:
Input: nums = [4, 3, 2, 3, 5, 2, 1], k = 4
Output: True
Explanation: It's possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal... | 2,142 | 696 |
import os
import csv
basedir = os.path.abspath(os.path.dirname(__file__))
path = basedir + "/CallRecorders/"
lst = os.listdir(path)
with open("call_data.csv","w") as new_file:
fieldnames = ['Mobile No', 'Year', 'Month', 'Date', 'Hour', 'Minute', 'Second', 'Call Type', 'Audio']
csv_writer = csv.DictWriter(new_f... | 769 | 290 |
# Water Jug problem
print("Solution for Water Jug problem!")
x = int(input("Enter the capacity of jug1 : "))
y = int(input("Entert the capacity of jug2 : "))
target = int(input("Enter the target volume : "))
def bfs(start, target, x, y):
path = []
front = []
front.append(start)
visited = []
while(n... | 1,683 | 722 |
from django.apps import AppConfig
class ApiRestInterfaceConfig(AppConfig):
name = 'api_rest_interface'
| 109 | 32 |
from games.models import GameCategory
from games.models import Game
from games.models import Player
from games.models import PlayerScore
from games.serializers import GameCategorySerializer
from games.serializers import GameSerializer
from games.serializers import PlayerSerializer
from games.serializers import PlayerSc... | 4,837 | 1,357 |
from __future__ import annotations
from spark_auto_mapper_fhir.fhir_types.uri import FhirUri
from spark_auto_mapper_fhir.value_sets.generic_type import GenericTypeCode
from spark_auto_mapper.type_definitions.defined_types import AutoMapperTextInputType
# This file is auto-generated by generate_classes so do not edi... | 817 | 300 |
import PA_IMU
from machine import SoftI2C, Pin
import padog
#中间变量定义
q=[]
Sta_Pitch=0
Sta_Roll=0
kp_sta=0.05
p_origin=0
r_origin=0
time_p=0
filter_data_p=0
filter_data_r=0
gyro_cal_sta=0
gyro_x_fitted=0
gyro_y_fitted=0
acc_z_fitted=0
#设置陀螺仪 IIC 接口
print("IMU启动中...")
i2cc = SoftI2C(scl=Pin(22), sda=Pin(21)) #集成板
acc ... | 2,096 | 1,163 |
import paddle.fluid as fluid
import numpy as np
import cv2
def bboxes_intersection(bbox_ref, bboxes):
"""Compute relative intersection between a reference box and a
collection of bounding boxes. Namely, compute the quotient between
intersection area and box area.
Args:
bbox_ref: (N, 4) or (4,) T... | 2,879 | 1,236 |
from textwrap import dedent
from httpie.cli.argparser import HTTPieManagerArgumentParser
from httpie import __version__
CLI_SESSION_UPGRADE_FLAGS = [
{
'flags': ['--bind-cookies'],
'action': 'store_true',
'default': False,
'help': 'Bind domainless cookies to the host that session be... | 4,559 | 1,257 |
import os
from yaml import load, dump
try:
from yaml import CLoader as Loader
except ImportError:
from yaml import Loader
FILE_PATH = os.path.dirname(__file__)
DATA_PATH = os.path.join(FILE_PATH, 'en-th.yml')
with open(DATA_PATH, 'r') as file:
en_th = load(file)
text = input("Enter text to Convert: "... | 402 | 142 |
import torch
from torch import nn
class ConvLayer(nn.Sequential):
def __init__(self, in_channels, out_channels, kernel_size,
stride=1, padding=0, dilation=1, groups=1,
bias=True, norm=True, relu=True):
super().__init__()
if padding > 0:
self.add_modul... | 9,014 | 2,461 |
import http.server
import socketserver
import json
import os
import string
import pandas as pd
import numpy as np
import argparse
from urllib.parse import urlparse, parse_qs
from preprocessing.lyrics_preprocess import preprocess_lyrics
from preprocessing.dict_preprocess import preprocess_dict
from preprocessing.merge_... | 7,857 | 2,581 |
#%%
import arcpy
from arcpy import env
from arcpy.sa import *
import os.path
import glob
import pathlib
import shutil
def create_majority_raster(
aecs,
aecPaths,
outputDirWorking):
print("Creating majority raster...")
print("... running cell statistics on {} rasters".format(len(aecs)))
maj... | 6,415 | 2,198 |
from collections import namedtuple
import json
from os import listdir, makedirs
from os.path import join as p, isdir, isfile
import transaction
from unittest.mock import patch
from tempfile import TemporaryDirectory
import pytest
import rdflib
from rdflib.term import URIRef
from owmeta_core.bundle import (Installer, ... | 17,303 | 6,431 |
# Copyright (c) 2017, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
from ..._deps import _HAS_KERAS_TF
from ..._deps import _HAS_KERAS2_TF
if _HAS_KERAS_TF or _HAS_KERAS2_... | 667 | 238 |
import os
import sys
from datetime import datetime
import joblib
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, multilabel_confusion_matrix
from config.config import global_config
from utils.path import create_dirs
from utils.logging.csvinterface import write_log
from utils.logging.log import... | 2,451 | 843 |
#!/usr/bin/env python
'''Test content tree construction from HTML source.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
from layout.content import *
from layout.builders.htmlbuilder import *
class HTMLBuilderTest(unittest.TestCase):
def check(self, test, expected):
documen... | 2,987 | 1,079 |
import numpy as np
from scipy import constants
from scipy.optimize import curve_fit
import os
from numpy.polynomial import polynomial as poly
from scipy.special import lambertw
# use absolute file path so tests work
path_const = os.path.join(os.path.dirname(__file__), '..', 'constants')
def AM15G_resample(wl):
'... | 11,541 | 4,296 |
# Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.com/)
#
# 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 appli... | 4,590 | 1,352 |
# -*- coding: utf-8 -*-
from qcloudsdkcore.request import Request
class CreateFunctionRequest(Request):
def __init__(self):
super(CreateFunctionRequest, self).__init__(
'scf', 'qcloudcliV1', 'CreateFunction', 'scf.api.qcloud.com')
def get_code(self):
return self.get_params().get(... | 2,352 | 735 |
import os
import numpy
from amuse.lab import *
from prepare_figure import single_frame
from distinct_colours import get_distinct
from matplotlib import pyplot
def read_triple_data(filename):
t = []
ain = []
aout = []
ein = []
eout = []
a0in = 0
a0out = 0
for line in open(filename):
... | 1,585 | 600 |
import getpass
from collections import namedtuple
from lxml import objectify
from project import Project
from importer import Importer
from labelcolourselector import LabelColourSelector
def read_xml_sourcefile(file_names):
files = list()
for file_name in file_names.split(';'):
all_text = open(file_na... | 1,658 | 524 |
import logging
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
from rest_framework import exceptions
from rest_framework.reverse import reverse
from rest_framework.views import excep... | 3,293 | 875 |
import os
from argparse import ArgumentParser
import model as md
from utils import create_link
import test as tst
# To get arguments from commandline
def get_args():
parser = ArgumentParser(description='cycleGAN PyTorch')
parser.add_argument('--epochs', type=int, default=200)
parser.add_argument('--decay_... | 2,334 | 803 |
import pandas as pd
import numpy.random as rdm
df=pd.read_csv('../Output/OA_info_for_movement_model.csv')
IZ_list=list(set(df['intermediate_zone'].tolist()))
OAs_in_IZ={}
for IZ in IZ_list:
IZ_df=df[(df['intermediate_zone']==IZ)]
OAs_in_IZ[IZ]=list(set(IZ_df['output_area']))
# worker and household densi... | 4,060 | 1,380 |
# Generated by Django 3.2 on 2021-05-06 08:04
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0004_recipe'),
]
operations = [
migrations.RenameField(
model_name='recipe',
old_name='time_minuts',
new_n... | 357 | 126 |
"""Emoji
Available Commands:
.angry"""
from telethon import events
import asyncio
from userbot.utils import admin_cmd
@borg.on(admin_cmd("angry"))
async def _(event):
if event.fwd_from:
return
animation_interval = 3
animation_ttl = range(0, 18)
#await event.edit(input_str)
await eve... | 909 | 333 |
import asyncio
def _run_when(obj, time_method: str, period_name: str, queue_blocking='abandon'):
'''
Decorator, run the decorated when obj is at the exact moment or period.
:param time_method: enter, exit, inside, outside
:param obj:
:param period_name:
:param queue_blocking: When the decorat... | 4,587 | 1,201 |
from decimal import Decimal
def filter_bold(obj):
if (
obj["object_type"] == "char"
and obj["fontname"] == "YUQOTN+OpenSans-Semibold"
):
return True
elif obj["object_type"] == "char" and obj["fontname"] == "UZGVXX+OpenSans":
return True
return False
def header_text(ob... | 958 | 326 |
import unittest
import sys
import site
def get_main_path():
test_path = sys.path[0] # sys.path[0] is current path in lib subdirectory
split_on_char = "/"
return split_on_char.join(test_path.split(split_on_char)[:-1])
main_path = get_main_path()
site.addsitedir(main_path+'/tests')
site.addsitedir(main_path... | 1,804 | 582 |
# datasets.py
# B11764 Chapter 11
# ==============================================
import os
import numpy as np
import scipy.ndimage as nd
import scipy.io as io
import torch
from torch.utils.data import Dataset
def getVoxelFromMat(path, cube_len=64):
voxels = io.loadmat(path)['instance']
voxels = np.pad(voxe... | 986 | 361 |
import numpy as np
from cmaes import CMA
def quadratic(x1, x2):
return (x1 - 3) ** 2 + (10 * (x2 + 2)) ** 2
def main():
optimizer = CMA(mean=np.zeros(2), sigma=1.3)
print(" g f(x1,x2) x1 x2 ")
print("=== ========== ====== ======")
while True:
solutions = []
for _... | 741 | 280 |
#!/usr/bin/env python
# Copyright 2016 Coursera
#
# 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 ag... | 9,696 | 3,158 |
#!/usr/bin/env python3
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import os.path
import re
import shutil
import subprocess
import sys
# Prefix for all custom linker driver arguments.
LINKE... | 12,581 | 3,678 |
import requests
import discord
from discord.ext import commands
class AffirmationCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def affirmation(self, ctx):
"""Tells you a positive affirmation"""
r = requests.get("https://www.affirmations.dev/"... | 451 | 150 |
from falcor import *
def render_graph_DefaultRenderGraph():
g = RenderGraph('DefaultRenderGraph')
loadRenderPassLibrary('BSDFViewer.dll')
loadRenderPassLibrary('AccumulatePass.dll')
loadRenderPassLibrary('TemporalDelayPass.dll')
loadRenderPassLibrary('Antialiasing.dll')
loadRenderPassLibrary('B... | 1,980 | 616 |
"""Provide common functions for both RDF and SHACL generators."""
from typing import MutableMapping, Tuple, Optional, List, Union
from icontract import ensure
from aas_core_codegen import intermediate, specific_implementations
from aas_core_codegen.rdf_shacl import naming as rdf_shacl_naming
from aas_core_codegen.com... | 5,549 | 1,620 |
from abc import abstractmethod, ABC
from bomber_monkey.features.physics.rigid_body import RigidBody
from bomber_monkey.features.player.player_action import PlayerAction
from bomber_monkey.game_inputs import GameInputs
from python_ecs.ecs import Component, Simulator
class InputMapping(Component, ABC):
def __init_... | 599 | 180 |
from typing import Type
from api.user_view_mixin import UserViewMixin
from crud.crud import c
from pycurd.crud.base_crud import BaseCrud
from slim.base.web import JSONResponse
from slim.retcode import RETCODE
from slim.view import CrudView
class BaseCrudView(CrudView):
crud: BaseCrud = c
is_base_class = True... | 1,136 | 363 |
from deeds.models import Origin, Person
from geonames_place.models import Place
from graphene import ObjectType, relay
from graphene_django import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField
class OriginNode(DjangoObjectType):
class Meta:
model = Origin
filter_f... | 1,058 | 297 |
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class Tree:
def __init__(self, arr):
self.root = None
for i in arr:
self.insert(self.root, Node(i))
def insert(self, root, node):
if root is ... | 1,853 | 553 |
# -*- coding: utf-8 -*-
"""GUI labeling tool
Notic
Please modify AppWindow attribute dir to your dataset dir
"""
import sys
import os
from PySide2.QtGui import QPixmap, QImage, QIcon
from PySide2.QtWidgets import QApplication, QMainWindow, QFileDialog, QSizePolicy, QMenu, QMessageBox
from PySide2.QtC... | 4,215 | 1,468 |
from matplotlib.pyplot import plot
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import math
import os
import csv
from tripedal_kinematics import TripedalKinematics
COS120 = math.cos(math.pi * 2 / 3)
SIN120 = math.sin(math.pi * 2 / 3)
COS240 = math.cos(-math.... | 24,316 | 9,054 |
from os import makedirs
import socket as sk
from appdirs import user_config_dir
from argparse import ArgumentParser
from ast import literal_eval
from os.path import isfile, join, dirname
def main():
parser = ArgumentParser(description='Lights control script for coosa smart plugs')
parser.add_argument('comman... | 2,091 | 658 |
import time
__all__ = ['tic', 'toc', 'timed', 'pretty_duration']
_tic_times = []
def tic():
"""Set a start time"""
global _tic_times
_tic_times.append(time.time())
def toc(message=""):
"""Print the elapsed time from the last :func:`.tic`
Parameters
----------
message : str
Pri... | 2,669 | 973 |
from ..helper import ActionOnExit
from botocore.exceptions import ClientError
import json
# TODO:support reverting Drop:true operation by either cancelling deletion or recreating the keys
def configure_kms_keys(account: object, region):
keys_config = account.config.get('kms', {})
kms_client = account.session.... | 4,077 | 1,035 |
import numpy as np
import sys
def arrange_cspad_tiles(img, ntiles=32, tile_size=(185,388), inverse=False, common_mode=False):
ffg = 0
ffg2 = 0
tile_location = np.array([[2,2], [3,2], [0,2], [0,3],
[1,0], [0,0], [2,0], [2,1],
[4,2], [4,3], [5,0], ... | 3,184 | 1,525 |
import cv2
import numpy as np
def decode_poly(poly, shape):
full_mask = np.zeros(shape, dtype="uint8")
pts = [np.round(np.array(p).reshape(-1, 2)).astype(int) for p in poly]
return cv2.fillPoly(full_mask, pts, color=1).astype(bool)
def decode_rle(rle, shape):
full_mask = np.zeros(np.prod(shape), dty... | 948 | 329 |
#!/usr/bin/env python3
import mysql.connector as mysql
import datetime
from math import floor
from threading import RLock
from configparser import ConfigParser
class PlaylistDatabase():
'''
This database is designed to manage songs played by a
internet radio station. It stores the web address of the sta... | 21,028 | 5,951 |
"""
"""
from .dist import SAM, SID, chebyshev, NormXCorr, classify | 70 | 32 |
import glob
import json
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
result_files = glob.glob('data/' + 'results*.json')
# df = pd.read_json('data/results_macbookpro.json')
for file in result_files:
df_full = pd.read_json(file)
df_seq = df_full[df_full['partype'] == 'sequential']
... | 1,907 | 722 |
# -*- coding: utf-8 -*-
from __future__ import print_function, division, unicode_literals
from __future__ import absolute_import
"""
interface for FTLAB GDK 101 gamma radiation detector
attention: I²C interface needs level shifter 5.0 <-> 3.3 V
"""
import sys
from smbus2 import SMBus
# default addresses
I2CAD... | 3,129 | 1,167 |
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
from itemloaders.processors import TakeFirst , MapCompose
class SteamGamesItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
... | 970 | 296 |
import unittest
from unittest.mock import *
from zad2 import Car
class TestCarMock(unittest.TestCase):
def setUp(self):
self.test_object = Car()
"""needsFuel TESTS"""
@patch.object(Car, 'needsFuel')
def test_needsFuel_dont(self, mock_method):
mock_method.return_value = False
... | 2,078 | 661 |
from fastapi import BackgroundTasks, FastAPI, HTTPException
from typing import Optional
from utils.client import HeaterClient
from utils import errors, types
app = FastAPI(root_path='/heater')
api = HeaterClient()
async def _set_temp_limit(temp: types.TempData) -> None: await api.set_temp_limit(temp.temp)
@app.get(... | 1,179 | 372 |
from Spheral3d import *
import random, time
ngens = 50000
ngencheck = ngens
nxcell = KeyTraits.maxKey1d/4
nxycell = nxcell*nxcell
ncell = nxycell*nxcell
dx = 1.0/nxcell
# Randomly generate some generators in a unit cube.
print "Creating %i generators." % ngens
generators = vector_of_Vector()
for i in random.sample(xr... | 1,070 | 419 |
from datetime import timedelta
from ebu_tt_live.bindings import get_xml_parsing_context
from ebu_tt_live.errors import LogicError, SemanticValidationError, OutsideSegmentError, OverlappingActiveElementsError
from ebu_tt_live.strings import ERR_SEMANTIC_VALIDATION_TIMING_TYPE
import itertools
class TimingValidationMi... | 19,389 | 5,122 |
import torch.nn as nn
import torch
class VGG(nn.Module):
def __init__(self, features, num_classes=5, init_weights=False):
super(VGG, self).__init__()
self.features = features
#32:1 128:4 224:7
self.classifier1 = nn.Sequential(
nn.Dropout(p=0.5),
nn.Linear... | 3,243 | 1,433 |
# Copyright 2015-2016 Palo Alto Networks, 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... | 16,656 | 5,565 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/Users/bibsian/Desktop/git/database-development/Views/ui_dialog_cbind.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.Q... | 6,088 | 2,121 |
from PIL import Image
from lib.lips_marger import detection
import cv2, imutils, io
import numpy as np
def imageProcessor(image, colors):
"""
"""
blob = image.read()
B, G, R = colors.split(',')
b = io.BytesIO(blob)
pimg = Image.open(b).convert('RGB')
# converting RGB to BGR, as opencv s... | 601 | 211 |
# -*- coding: UTF-8 -*-
from basic import BasicCtrl
import pdb
class LoginCtrl(BasicCtrl):
def get(self):
self.render('login.html', next = self.input('next', '/shell'))
def post(self):
pdb.set_trace()
if not self.human_valid():
self.flash(0, {'msg': '验证码错误'})
r... | 1,202 | 386 |
from datetime import datetime, timezone
import os
import json
# Simple json file to be used for storing data between runs
class Db:
FILE = os.path.join(os.path.dirname(__file__), "db.json")
def __init__(self):
# if the file doesn't exist yet, set the defaults
if not os.path.isfile(self.FILE):... | 1,149 | 355 |
# -*- ecoding: utf-8 -*-
####################################################
# サンプルコード
# スティックアーミング~離陸~着陸をスクリプトで実装
####################################################
print('Start Script')
# 1~9チャンネルをニュートラルに
for chan in range(1,9):
Script.SendRC(chan,1500,False)
# スロットルをローに設定
Script.SendRC(3,Script.... | 1,616 | 955 |
import numpy as np
import csv
from scipy.optimize import minimize
from scipy.spatial.transform import Rotation as R
ID = np.array([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]
])
def random_unit_vector():
"""Generate a random 3D unit vector
Returns:
np.array: a random 3D un... | 13,444 | 4,691 |
#!/usr/bin/python2
# -*- coding: utf-8 -*-
"""
Mergesort. Not much to explain here...
"""
__author__ = "Maurice Tollmien"
__maintainer__ = "Maurice Tollmien"
__email__ = "maurice.tollmien@gmail.com"
import random
import time
def merge (l1, l2):
i = 0
j = 0
newList = []
while i < len(l1) and j < len(l2... | 1,070 | 437 |
"""This script converts each CUSTOM unit in a list to a decoration, using 'h038' as the base unit.
Does not function for default units, as the _parent object field is overriden.
"""
import os
from myconfigparser import MyConfigParser, load_unit_data, get_decorations
fields_to_keep = [
'Name', 'EditorSuffix', 'Tip... | 954 | 380 |
import numpy as np
from openmdao.api import Group, Problem
from hyperloop.Python.pod import pod_mach
def create_problem(component):
root = Group()
prob = Problem(root)
prob.root.add('comp', component)
return prob
class TestPodMach(object):
def test_case1_vs_npss(self):
component = pod_m... | 1,023 | 419 |
#! python3
# Your one stop destination for all your assignment needs
# Convert your assignments to PDFs, watermark them, merge them and encrypt them, all in one place
# Get to know the birthdays of your classmates and send them a birthday wish to show you care
# Convert your PDF into audiobook and learn on the go
#W... | 17,781 | 5,237 |
import numpy as np
__version__ = '1.0.1'
def approximate_natural_frequency_from_stress(m, a, sigma, ro):
return m * np.pi / a * np.sqrt(sigma / ro)
def approximate_stress_from_natural_frequency(m, a, omega, ro):
return (omega * a / (m * np.pi))**2 * ro
| 266 | 107 |
# Data cleaning
import pandas as pd
import string
def clean_text(text):
x = text.translate(str.maketrans('', '', string.punctuation)) # remove punctuation
x = x.lower().split() # lower case and split by whitespace to differentiate words
return x
example_text = pd.read_csv('https://raw.githubuserconten... | 3,845 | 1,465 |
class Expense:
def __init__(self, name, amount):
self._name = name
self._amount = amount
def get_name(self):
return self._name
def set_name(self, new_name):
self._name = new_name
def get_amount(self):
return self._amount
def set_amount(self, new_amount):
... | 351 | 110 |
#!/usr/bin/env python
import rospy
from geometry_msgs.msg import Twist
from motors_driver import SteeringMotor, DriveMotor, TamiyaVehicle
steering = SteeringMotor(pwm_pin=33, pwm_min=6.5,
pwm_max=10.5,
pwm_init_duty_cycle=8.45,
pwm_neutral=8... | 776 | 325 |
import numpy as np
import h5py
import scipy.io as io
import sys
import scipy.special as sp
import pyfftw
from astropy import units as u
import matplotlib.pyplot as pl
from ipdb import set_trace as stop
from soapy import confParse, SCI, atmosphere
def progressbar(current, total, text=None, width=30, end=False):
"""... | 4,475 | 1,632 |
f = open("pylint.log", "r")
report = 0
for line in f:
if "/10" in line:
report = line
break
f.close()
init = report.index("at ")
end = report.index("/")
grade = report[init:end]
space = grade.index(" ")
grade = grade[space+1:end]
grade = float(grade)
print(grade)
| 285 | 106 |
# Python modules
import os
import sys
# 3rd party modules
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter, NullFormatter
# Our modules
import vespa.analysis.util_import as util_import
import vespa.common.util.ppm as util_ppm
import vespa.common.util... | 15,211 | 5,356 |
def getting(item, atom_indices=None, **kwargs):
from .api_get_parmed_Structure import getting as _get
return _get(item, atom_indices, **kwargs)
| 154 | 54 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class LNode(object):
"""
单链表节点类
使用:
node_object = LNode(elem, next_)
elem: 该节点的值
next_: 该节点的下一节点,默认为None
"""
def __init__(self, elem, next_=None):
self.elem = elem
self.next = next_
class LinkedListUnderflow(ValueError):
"""
链表的异常定制类
"""
... | 641 | 356 |
import aspose.slides as slides
# ExStart:GetTextFromSmartArtNode
# The path to the documents directory.
dataDir = "./examples/data/"
outDir = "./examples/out/"
with slides.Presentation(dataDir + "smart_art_access.pptx") as presentation:
slide = presentation.slides[0]
smartArt = slide.shapes[0]
smartArtN... | 560 | 177 |
#from krakask.api import API
#from krakask.pyapi import KrakenAPI, KrakenAPIError
import pytest
@pytest.fixture
def mock_srv():
return "127.0.0.1"
# @pytest.fixture
# def api(mock_srv):
# """A flaky webserver with pathological behavior for testing purposes"""
# api = API()
# # to make sure we can ... | 468 | 176 |
from datasets import load_metric
metric = load_metric("./rouge")
# Language: en-English
references = ["The quick brown fox jumps over the lazy dog"]
predictions = ["The quick brown fox jumps over the lazy dog"]
result = metric.compute(predictions=predictions, references=references, language="en")
result = {key: roun... | 1,463 | 564 |
import uuid
import pytest
from sirius_sdk import Agent
from sirius_sdk.agent.storages import InWalletImmutableCollection
from sirius_sdk.storages import InMemoryKeyValueStorage, InMemoryImmutableCollection
@pytest.mark.asyncio
async def test_inmemory_kv_storage():
kv = InMemoryKeyValueStorage()
await kv.sel... | 2,538 | 868 |
# Copyright (c) 2021 PaddlePaddle 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 appli... | 9,199 | 2,675 |
#!/usr/bin/env python
__author__ = "Graham Klyne (GK@ACM.ORG)"
__copyright__ = "Copyright 2011-2013, University of Oxford"
__license__ = "MIT (http://opensource.org/licenses/MIT)"
import sys, unittest, os
if __name__ == "__main__":
# Add main project directory and ro manager directories at start of py... | 3,305 | 1,102 |
from os.path import join
import time
from mcm.lottery import random_positions
from mcm.measurements import roll_peak_to_val, where_is_this_val, sum_peak_to_one
from mcm.peak_reader import read_one_peak
import numpy as np
def quality(sum_peak):
domain = sum_peak[0]
values = sum_peak[1]
ind_begin = where_... | 2,255 | 891 |
# Copyright (c) 2015, Daniel Svensson <dsvensson@gmail.com>
#
# Permission to use, copy, modify, and/or distribute this software for
# any purpose with or without fee is hereby granted, provided that the
# above copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND T... | 2,275 | 735 |
'''
#listens for restart command
'''
import datetime
import json
from threading import Thread
from queue import Queue
from colorama import Fore
from helpers import antminerhelper
from helpers.queuehelper import QueueName
from domain.mining import MinerCommand
from domain.logging import MinerLog
import backend.fcmutils ... | 3,772 | 1,167 |
__author__ = 'Wei Xie'
__email__ = 'linegroup3@gmail.com'
__affiliation__ = 'Living Analytics Research Centre, Singapore Management University'
__website__ = 'http://mysmu.edu/phdis2012/wei.xie.2012'
import os
from ctypes import cdll
if os.name == 'posix':
hashBase = cdll.LoadLibrary('./c/mlh.so')
if os.name == '... | 617 | 247 |
import pandas as pd
import os
def normalize(df, new_col_name, col_to_norm):
'''
ref: https://en.wikipedia.org/wiki/Normalization_(statistics)
'''
if (col_to_norm == 'word_count'):
max = 1718
min = 74
elif (col_to_norm == 'avg_word_len'):
max = 0.0010981580557913647
m... | 787 | 315 |
# ------------------------------------------------------------------------------
# CodeHawk Binary Analyzer
# Author: Henny Sipma
# ------------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2016-2020 Kestrel Technology LLC
# Copyright (c) 2020 Henny Si... | 5,765 | 1,722 |
import os
import shutil
def mkdir(dir_name, root_dir='.'):
temp_dir = os.path.join(os.path.expanduser(root_dir), dir_name)
if not os.path.exists(temp_dir):
os.mkdir(temp_dir)
print("Folder created: {}".format(temp_dir))
return temp_dir
def rmdir(dir_name, root_dir='.'):
temp_dir = os.path... | 507 | 200 |
# coding: utf-8
from jplib import utils
def test_my_shuffle():
array = [1, 2, 3]
assert len(utils.my_shuffle(array)[::-1]) == 3
last = utils.my_shuffle(array)[-1]
assert 1 <= last <= 3
def test_inc_string():
assert utils.inc_string('a') == 'b'
assert utils.inc_string('f') == 'g'
assert ... | 1,210 | 583 |
from django.contrib.auth import get_user_model
from django.contrib.gis.db import models
from django.contrib.postgres.fields import ArrayField
from django.core.exceptions import ValidationError
from django.db.models import Q
from django.db.models.fields.json import JSONField
from django.urls import reverse
from django.u... | 15,106 | 4,514 |
"""test template tags commands"""
from django.shortcuts import reverse
from django.test import RequestFactory, TestCase
from pyazo.core.templatetags.pyazo import back
class TemplateTagTest(TestCase):
"""Test django template tags"""
def setUp(self):
super().setUp()
self.factory = RequestFacto... | 839 | 244 |
#!/usr/bin/env python
# Copyright (C) 2011 Michael Ranieri <michael.d.ranieri at gmail.com>
# System imports
import urllib2
import json
import sys
import re
from xml.dom import minidom
# Misty imports
import settings_local as settings
def main(params):
msg, user, channel, users = params
searchTerm... | 1,836 | 574 |
# TO DO def DivisiblePad(x,y= None, trans_xy= False, k):
import numpy as np
import tensorflow as tf
def addGaussianNoise(x, y=None, trans_xy=False, noise_mean=0.0, noise_std=0.1):
"""Add Gaussian noise to input and label.
Usage:
```python
>>> x = [[[1., 1., 1.]]]
>>> x_out = intensity_transforms.... | 9,410 | 3,579 |