content stringlengths 5 1.05M |
|---|
import json
import os
import shutil
from .cwltool_deps import ref_resolver
from .parser import (
JOB_JSON_FILE,
load_job_proxy,
)
def handle_outputs(job_directory=None):
# Relocate dynamically collected files to pre-determined locations
# registered with ToolOutput objects via from_work_dir handling.... |
from concurrent.futures import ThreadPoolExecutor
from time import sleep
from controlling.AsyncProcessor import AsyncProcessor
class DummyMovementEngine:
x_pos = 0
speed = 0
def __init__(self):
self.is_moving = False
self._executor = AsyncProcessor(ThreadPoolExecutor(max_workers=2))
... |
import torch
import kymatio.scattering3d.backend as backend
from kymatio import HarmonicScattering3D
class BenchmarkHarmonicScattering3D:
params = [
[
{ # Small. 32x32x32, 2 scales, 2 harmonics
"J": 2,
"shape": (32, 32, 32),
"L": 2,
},... |
#!/usr/bin/python3
"""Surface Hopping Module.
.. moduleauthor:: Bartosz Błasiak <blasiak.bartosz@gmail.com>
"""
from abc import ABC, abstractmethod
import math
import psi4
import numpy
from .aggregate import Aggregate
from .trajectory import TimePoint, Trajectory
from .hamiltonian import Isolated_Hamiltonian
from ..p... |
import cv2
import numpy as np
from bounding_box import BoundingBox
from utils import open_file
from tqdm import tqdm
from typing import List, TypeVar
SheetReader = TypeVar('SheetReader')
class Detector:
def __init__(self,
reader: SheetReader,
templates: List[np.ndarray],
det... |
# Generated by Django 2.2 on 2022-03-16 08:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('projects', '0016_auto_20220316_0643'),
]
operations = [
migrations.AddField(
model_name='myimage',
name='dishes_url',
... |
from collections import Counter, defaultdict
from functools import partial
import math, random
def entropy(class_probabilities):
"""given a list of class probabilities, compute the entropy"""
return sum(-p * math.log(p, 2) for p in class_probabilities if p)
def class_probabilities(labels):
total_count = l... |
import stackless
from datetime import date, timedelta, datetime
from General.outsourcingTask import generateSol, stacklessTicker
from General.basicServer import CommunicationServer
from General.newProcess import StacklessProcess, getLock, getSharedObjects
def keepAlive():
while True:
stackless.schedule()
... |
import pandas as pd
from os import environ
from os.path import isfile, join, basename
from requests.exceptions import HTTPError as HTTPError1
from ..table_builder.cap_table_builder import CAPFileSource
TMP_DIR = environ.get('CAP2_TMP_DIR', '/tmp')
class PangeaFileSource(CAPFileSource):
def __init__(self, pange... |
"""This module was designed to help making `WePay <https://wepay.com>`_ API calls.
.. moduleauthor:: lehins <lehins@yandex.ru>
:platform: independent
"""
from wepay.calls import *
from wepay.utils import Post, cached_property
__all__ = ['WePay']
class WePay(object):
"""A full client for the WePay API.
... |
from django.db import models
from csat.acquisition.models import DataCollectorConfig
from django.utils.translation import ugettext_lazy as _
from . import graphs
class ExamplesConfig(DataCollectorConfig):
GRAPH_CHOICES = [(g.key, g.description) for g in graphs.get_graphs()]
example = models.CharField(_('Exa... |
import speech_recognition as sr
import sys
reload(sys)
sys.setdefaultencoding('utf8')
class YLSpeecher:
pass
if __name__ == '__main__':
# obtain audio from the microphone
r = sr.Recognizer()
with sr.Microphone() as source:
print("Say something!")
audio = r.listen(source)
# rec... |
# -*- coding: utf-8 -*-
import math
import random
from matplotlib import pyplot as plt
from helper.ambiente import Pontos
from helper.utils import colidir, simulate_points, definir_angulo, dist_euclidiana
import numpy as np
class Vector2d():
def __init__(self, x, y):
self.deltaX = x
self.deltaY = y... |
""" Module for defining user related models. """
from datetime import datetime
from sqlalchemy import Column, Integer, String, DateTime, Float
from sqlalchemy.orm import relationship
from utils import get_logger
from models import Base
LOGGER = get_logger(__name__)
class User(Base):
""" Table for tracking the... |
"""
This implements a class to control and present sensor data for a fishtank
"""
import socket
import time
import os
import random
try:
import network
import machine
import onewire
import ds18x20
import gc
import passwords
is_esp_device = True
except ImportError:
# not on esp dev... |
def x_pow(x):
def pow(n):
print(x ** n)
return pow
def fibonacci(nth):
# 1,1,2,3,5,8,13,21,34,55
if nth == 1 or nth == 2:
return 1
else:
return fibonacci(nth - 1) + fibonacci(nth - 2) |
# SPDX-FileCopyrightText: 2020 Foamyguy, written for Adafruit Industries
#
# SPDX-License-Identifier: Unlicense
"""
CircuitPython example for Monster M4sk.
Draws a basic eye dot on each screen. Looks at nose
when booped. Prints acceleration and light sensor
data when booped as well.
"""
import time
import... |
# coding: utf-8
from enum import Enum
from six import string_types, iteritems
from bitmovin_api_sdk.common.poscheck import poscheck_model
class H264NalHrd(Enum):
NONE = "NONE"
VBR = "VBR"
CBR = "CBR"
|
from rest_framework import serializers
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from rest_framework.compat import authenticate
from rest_framework.validators import UniqueValidator
from django.contrib.humanize.templatetags.humanize import naturaltime
from... |
from flask import Flask, request, jsonify
import json
import logging
import os
import random
import string
import sys
import sentencepiece as spm
import torch
import torchaudio
import numpy as np
from fairseq import options, progress_bar, utils, tasks
from fairseq.meters import StopwatchMeter, TimeMeter
from fairseq.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 20 14:19:54 2021
@author: gregstacey
"""
import os
import pandas as pd
import numpy as np
import sys
from itertools import chain
from rdkit import Chem
from tqdm import tqdm
if os.path.isdir("~/git/bespoke-deepgen"):
git_dir = os.path.expandus... |
import numpy as np
from scipy import spatial
import matplotlib.pyplot as plt
class KMeansClustering():
'''this implimentation is going to find the distances between
each point and every other point, then get the average distance, and use the minimums
to cluster. As I'm writing this I'm realizing that this... |
import nose
from helpers import parse_file, parse_string, check_visitor_return
from src.Generic import Generic
def test_sanity():
parse_file('./assets/empty.vhd')
parse_string('', 'design_file')
nose.tools.ok_(True)
def test_entity_declaration_empty():
entity = 'entity Adder is end entity Adder;'
... |
from qgis.core import QgsProcessingProvider
# from ndvi import Calculate_ndvi
from ndvi_raster_calculator import Calculate_ndvi
from split_band import Split_bands
class NDVIProvider(QgsProcessingProvider):
def loadAlgorithms(self, *args, **kwargs):
self.addAlgorithm(Calculate_ndvi())
self.addAl... |
import gym
from d3rlpy.algos import SAC
from d3rlpy.envs import AsyncBatchEnv
from d3rlpy.online.buffers import BatchReplayBuffer
if __name__ == '__main__':
env = AsyncBatchEnv([lambda: gym.make('Pendulum-v0') for _ in range(10)])
eval_env = gym.make('Pendulum-v0')
# setup algorithm
sac = SAC(batch_s... |
from brownie import accounts, web3, Wei, reverts
from brownie.network.transaction import TransactionReceipt
from brownie.convert import to_address
import pytest
from brownie import Contract
ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'
# reset the chain after every test case
@pytest.fixture(autouse=Tru... |
#!/usr/bin/env python
'''
Kick off the napalm-logs engine.
'''
# Import python stdlib
import os
import sys
import time
import signal
import logging
import optparse
# Import third party libs
import yaml
# Import napalm-logs
import napalm_logs
import napalm_logs.config as defaults
import napalm_logs.ext.six as six
lo... |
# -*- coding: utf-8 -*-
import tempfile
import contextlib
from datetime import datetime, timedelta
from dateutil.tz import tzlocal
from gevent import monkey
monkey.patch_all()
import os.path
import json
from gevent.subprocess import check_output, sleep
PAUSE_SECONDS = timedelta(seconds=120)
PWD = os.path.dirname(os... |
from os import path
from setuptools import setup
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='gostep',
long_description=long_description,
long_description_content_type='text/mar... |
"""This module contains the TerminalView."""
import sys
class TerminalView():
def __init__(self):
pass
def announce_database_truncated(self, truncated):
if truncated:
print('Truncating HDF5 database ...')
else:
print('Reusing HDF5 database ...')
... |
import json
from pprint import pprint
with open('plant_results_loop.json') as data_file:
data = json.load(data_file)
count = 0
for plant in data:
pprint(plant)
print " "
print " "
# print "*************{}*************".format(count)
# if 'value' in plant:
# for val in plant['value'... |
from test_utils import run_query, redshift_connector
import pytest
def test_tochildren_success():
results = run_query(
"""WITH tileContext AS(
SELECT 0 AS zoom, 0 AS tileX, 0 AS tileY UNION ALL
SELECT 1, 1, 1 UNION ALL
SELECT 2, 2, 3 UNION ALL
SELECT 3, 4, 5... |
#!/usr/bin/env python
import os
import os.path
import sys
import csv
def isexec (fpath):
if fpath == None: return False
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
def which(program):
fpath, fname = os.path.split(program)
if fpath:
if isexec (program):
... |
from setuptools import setup, find_packages
with open("README.md", "r") as fh:
long_description = fh.read()
print(find_packages())
setup(
name='efsync',
version='1.0.3',
packages=find_packages(),
entry_points={
"console_scripts": ["efsync=efsync.efsync_cli:main"]
},
author="Philip... |
import itertools
import math
import matplotlib.pyplot as plt
import numpy as np
from . import junction
from .circle_fit import fit
def distance(p1, p2):
return math.sqrt(((p1[0] - p2[0]) ** 2) + ((p1[1] - p2[1]) ** 2))
def collinear(points, epsilon=0.01):
""" determine if three points are collinear
:... |
personinfo = {'Name': 'John', 'Surname': 'Reese', 'Occupation': 'Killer'};
personinfo['Occupation'] = "Agent"; # Update
personinfo['Employer'] = "Harold Finch"; # Add
print personinfo['Name']
print "personinfo keys:", personinfo.keys();
print "personinfo values:", personinfo.values();
personinfo.clear();
print "person... |
mx = [-2,-1,1,2,2,1,-1,-2]
my = [1,2,2,1,-1,-2,-2,-1]
T = int(input())
def solve():
W = int(input())
curX, curY = map(int, (input().split()))
destX, destY = map(int, (input().split()))
isVisit = [[False for x in range(W)] for y in range(W) ]
q = []
q.append([ curX, curY ,0 ])
isVisit[curY][curX] = True... |
import torch.nn as nn
class PVN_Stage2_ActionHead(nn.Module):
"""
Outputs a 4-D action, where
"""
def __init__(self, h2=128):
super(PVN_Stage2_ActionHead, self).__init__()
self.linear = nn.Linear(h2, 16)
def init_weights(self):
pass
def forward(self, features):
... |
#!/sv/venv/T-PLE/bin/python2.7
from __future__ import print_function
from scripts.baseController import baseELOCalculations as ELOCal
vsDict = {}
for index, pName in enumerate(ELOCal.nameList):
vsDict[pName] = {'index': index, "wins": [0]*len(ELOCal.nameList)}
def main(logCount=None):
if not logCount:
... |
import mne
from mne.channels.layout import _merge_grad_data as grad_rms
import scipy.io as sio
import numpy as np
from my_settings import data_folder
std_info = np.load(data_folder + "std_info.npy").item()
subject = 1
planar = sio.loadmat(data_folder + "meg_data_%sa.mat" % subject)["planardat"]
events = mne.read_e... |
from django.http import HttpResponse, Http404
from django.template import loader
from applications.resume.models import Experience, Project, Education, Information, Certificate, Group
def resume_view(request, language):
if language == 'en':
temp = loader.get_template('resume/ltr-resume.html')
lan... |
# keeps track of the game's logic
class GameState:
def __init__(self): # this means it's the function of the class GameState itself.
# so when calling stuff from here just say Game.State.something.
# the board is read row, column, character/s inside.
# example: self.board[0][0][0] = 'b... |
'''
1. Write a Python program to find the largest palindrome made from the product of two 4-digit numbers.
According Wikipedia - A palindromic number or numeral palindrome is a number that remains the same when its digits are reversed. Like 16461, for example, it is "symmetrical". The term palindromic is derived from ... |
level = 3
name = 'Banjaran'
capital = 'Banjaran'
area = 42.92
|
from flask import Flask, render_template, url_for, flash, redirect, request
import pandas as pd
# from sklearn.feature_extraction.text import CountVectorizer
# from sklearn.metrics.pairwise import cosine_similarity
app = Flask(__name__)
#import pandas as pd
lko_rest = pd.read_csv("food1.csv")
def fav(lko_rest1):
l... |
import pydata_sphinx_theme
import datetime
import os
import sys
import cake
sys.path.append(os.path.abspath('../extensions'))
project = 'Documentation'
copyright = '2021, Mecha Karen'
author = 'Mecha Karen'
release = cake.__version__
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.coverage',
'sphinx.ext.... |
import random
from panda3d.core import LVector3f
import math
class Bone():
def __init__( self, joint, parent=None, static=False ):
self.axis = None
self.minAng = -math.pi
self.maxAng = math.pi
self.joint = joint
self.parent = parent
self.static = static
sel... |
#########################
# tcp服务器
#########################
"""
流程:
- socket创建一个套接字
- bind绑定ip和port
- listen使套接字变为可以被动链接
- accept等待客户端的链接
- recv/send接收发送数据
"""
from socket import *
# 创建socket
tcpSerSocket = socket(AF_INET, SOCK_STREAM)
# 绑定本地信息
address = ('', 8088)
tcpSerSocket.bind(address)
p... |
import csv
from urllib.parse import quote
import webbrowser
from . import geocoder_googs as geocoder
GOOGLE_STATIC_MAPS_ENDPOINT = (
'https://maps.googleapis.com/maps/api/staticmap?size=1280x720&markers=')
# Compute the max number of markers I can safely add before hitting the Static Map API char limit.
# String... |
# -*- coding: utf-8 -*-
import re
import json
import time
import random
import collections
import requests
from bs4 import BeautifulSoup
# http://www.usagain.com/find-a-collection-bin
# Post with data:
# cityInput=&stateInput=%23&zipInput=11207&Submit.x=48&Submit.y=4
class BinLocation():
@staticmethod
def from_di... |
#!/usr/bin/env python
import os
import click
import requests
from time import sleep
from models.trade import Trade
from models.stop import Stop
from pymongo import *
@click.group()
def cli():
pass
@cli.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your... |
import streamlit as st
import pandas as pd
import numpy as np
import re
import os
import nltk
import joblib
from nltk.corpus import stopwords
nltk.download('stopwords')
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow import keras
nltk.download('wordnet')
from nltk.stem import WordNetL... |
#!/usr/bin/env python3
# aids manually identifying sticons...
import csv
import os
dload_dir = '_sticon'
keywords_file = 'sticon_keywords.tsv'
with open(keywords_file) as tsvfile:
reader = csv.reader(tsvfile, delimiter='\t')
for keyword, path in reader:
folder = os.path.dirname(path)
path = ... |
import os
from unittest.mock import patch
from pytest import fixture, mark, raises
from configpp.evolution import Evolution, EvolutionException
from configpp.evolution.revision import Revision, gen_rev_number
from configpp.soil import YamlTransform
from voidpp_tools.mocks.file_system import mockfs
from .utils import... |
#!/usr/bin/env python3
############################################################################################
# #
# Program purpose: Finds whether a given string starts with a given character using #
# ... |
__all__ = ['MACD', 'KDJ', 'BIAS', 'BBANDS', 'RSI', 'WR']
def MACD(series, short=12, long=26, mid=9):
ema_short = series.ewm(adjust=False, span=short, ignore_na=True).mean()
ema_long = series.ewm(adjust=False, span=long, ignore_na=True).mean()
ema_diff = (ema_short-ema_long)
ema_dea = ema_diff.ewm(adjus... |
import requests
# Please NOTE: In this sample we're assuming Cloud Api Server is hosted at "https://localhost".
# If it's not then please replace this with with your hosting url.
url = "<insert presignedUrl generated by https://localhost/file/upload/get-presigned-url >"
payload = {}
files = [
('file', open('/User... |
import pandas as pd
from sqlalchemy import create_engine
from influxdb import InfluxDBClient
import time
def connectSQL():
connection_str = 'mssql+pyodbc://royg:Welcome1@SCADA'
engine = create_engine(connection_str)
conn = engine.connect()
return conn
def getData(conn,interval):
if (interval==1):... |
import configparser
import logging
import os
import pathlib
import sys
from typing import Union
from selenium.webdriver import Chrome, Remote
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.remote_connection import ChromeRemoteConnection
from selenium.webdriver.common.desired_capab... |
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
d = {}
for i, n in enumerate(nums):
try:
d[n].append(i)
except KeyError:
d[n] = [i]
for k in d:
if target - k in d:
if k =... |
#!/usr/bin/env python
from flask import Markup
import xlrd
class CopyException(Exception):
pass
class Error(object):
"""
An error object that can mimic the structure of the COPY data, whether the error happens at the Copy, Sheet or Row level. Will print the error whenever it gets repr'ed.
"""
_e... |
"""
Library to fetch and parse the public Princeton COS courses history as a
Python dictionary or JSON data source.
"""
__version__ = '1.0.0'
__author__ = "Jérémie Lumbroso <lumbroso@cs.princeton.edu>"
__all__ = [
"CosCourseInstance",
"CosCourseTerm",
"fetch_cos_courses",
]
from princeton_scraper_cos_... |
import glob
import cv2
from moviepy.editor import VideoFileClip, concatenate_videoclips
def createCombo(ComboWindow, inputFolder, outputFile):
"""
find all video files and combine it into one file
params:
ComboWindow : UI for the application, object of QWindow class
inputFolder : input files ... |
import itertools
import logging
import pathlib
import unittest
import rsa
from encrypted_config.crypto import encrypt, decrypt
_LOG = logging.getLogger(__name__)
_HERE = pathlib.Path(__file__).parent
class Tests(unittest.TestCase):
def test_encrypt_decrypt(self):
public_key_path = pathlib.Path(_HERE... |
"""
Parse and display test memory.
Uses pytest-monitor plugin from https://github.com/CFMTech/pytest-monitor
Lots of other metrics can be read from the file via sqlite parsing.,
currently just MEM_USAGE (RES memory, in MB).
"""
import sqlite3
import sys
from operator import itemgetter
def _get_big_mem_tests(cur):
... |
# list(map(int, input().split()))
# int(input())
def main():
S = input()
T = input()
# Sのi文字目をTの先頭として,それらの文字列の一致度を見る.
st = set()
for i in range(len(S)-len(T)+1):
cnt = 0
for s, t in zip(S[i:i+len(T)], T):
cnt += s == t
st.add(cnt)
print(len(T) - max(st))
i... |
import collections
from winnow.utils import deep_copy_dict as deepcopy
# from copy import deepcopy
from winnow import utils
from winnow.values.option_values import OptionWinnowValue
from winnow.values import value_factory, value_path_factory
from winnow.values.option_values import OptionResourceWinnowValue, OptionStr... |
#!/usr/bin/env python
# Copyright 2017 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 heapq
import logging
import os
import psutil
import sys
BYTE_UNITS = ['B', 'KiB', 'MiB', 'GiB']
def FormatBytes(value):
de... |
from . import equilibrium
from . import freeflame
from . import ignition
from . import minimal
from . import solution
|
import importlib
from parsel import Selector
def convert_html_to_selector(html):
return Selector(html)
class SelectorExtractor(object):
@staticmethod
def get_list_data(elements=None):
data_cleaned = []
data = elements.extract()
for i, datum in enumerate(data):
if dat... |
#!/usr/bin/env python
"""Tests for the howfairis module.
"""
import random
import pytest
import requests
from howfairis import Checker
from howfairis import Repo
from howfairis import Compliance
def get_urls(n=None):
software_api_url = "https://www.research-software.nl/api/software?isPublished=true"
try:
... |
import pandas as pd
import numpy as np
# TODO: cleanup this file, as it is almost unused in current solution (only for water and only small number
# of variables actually used)
N_Cls = 10
inDir = '../../data'
DF = pd.read_csv(inDir + '/train_wkt_v4.csv')
GS = pd.read_csv(inDir + '/grid_sizes.csv', names=['ImageId', 'X... |
import os
from day_12 import parse_input, count_paths, count_paths_2
def test_part_1() -> None:
os.chdir(os.path.dirname(__file__))
with open("data/test_day_12_1.in") as input_file:
caves = parse_input(input_file)
assert count_paths(caves) == 10
with open("data/test_day_12_2.in") as input_fil... |
from .analyzer import Analyzer
from .holdemai import HoldemAI
from .nn import NeuralNetwork
from .player import Player
from .playercontrol import PlayerControl, PlayerControlProxy
from .table import Table, TableProxy
from .teacher import Teacher, TeacherProxy
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from future.utils import raise_from, string_types
from builtins import (bytes, str, open, super, range,
zip, round, input, int, pow, object)
import os
import shutil
import traceback
from te... |
#!/usr/bin/env python3
"""
linkedin2username by initstring (github.com/initstring)
OSINT tool to discover likely usernames and email addresses for employees
of a given company on LinkedIn. This tool actually logs in with your valid
account in order to extract the most results.
"""
import os
import sys
import re
impo... |
import enum
import typing
import warnings
import attr
from uecp.commands.base import (
UECPCommand,
UECPCommandDecodeElementCodeMismatchError,
UECPCommandDecodeNotEnoughData,
UECPCommandException,
)
from uecp.commands.mixins import UECPCommandDSNnPSN
# PIN 0x06 / Programme Item Number not implemente... |
import tensorflow as tf
class VGG(tf.keras.layers.Layer):
def __init__(self):
super(VGG, self).__init__()
self.conv1 = tf.keras.layers.Conv2D(filters=64, kernel_size=3, strides=1, padding="same",
activation=tf.keras.activations.relu)
self.conv2 =... |
# Generated by Django 3.0.7 on 2020-06-10 16:01
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
import sys, codecs, json, re, time, os, getopt, traceback
import signal, psutil
from urlparse import urlparse
from multiprocessing import Process as Task, Queue
from subprocess import call, PIPE, STDOUT
import multiprocessing as mp
import random, calendar, shutil, sys, commands, hmac
from termcolor import colored
from ... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 28 10:42:09 2020
@author: User
"""
import numpy as np
import pandas as pd
from file_py_helper.PostChar import (
SampleSelection,
Characterization_TypeSetting,
SampleCodesChar,
)
def make_uniform_EvRHE(df, rounding_set=2):
lst = []
fo... |
import json
import cv2
import imutils as imutils
import requests
video_capture = cv2.VideoCapture(0)
# video_capture.set(3, 1024)
# video_capture.set(4, 768)
# video_capture.set(15, -8.0)
params = list()
params.append(cv2.IMWRITE_PNG_COMPRESSION)
params.append(9)
firstFrame = None
while True:
(grabbed, frame) =... |
# -*- coding: utf-8 -*-
# pylint: disable=R0201, R0903, C0116, C0103
"""Base Model unit tests."""
import pytest
from loglan_db.model_db.base_type import BaseType as Type
from loglan_db.model_db.base_word import BaseWord
from loglan_db.model_db.addons.addon_word_sourcer import AddonWordSourcer
from loglan_db.model_db.b... |
from artikel.models import Artikel
from rest_framework import serializers
from django.contrib.auth.models import User
class ArtikelSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Artikel
fields = ('a_id', 'titel', 'te... |
import json
import os
import pathlib
import subprocess
import numpy as np
import pydot
os.chdir(pathlib.Path(__file__).parent.parent / "tmp")
for k in range(1, 78+1):
proc = subprocess.run(["neato", f"{k}.dot"], capture_output=True, text=True)
graph, = pydot.graph_from_dot_data(proc.stdout)
positions = {... |
# encoding: utf-8
##################################################
# This script shows an example of arithmetic operators.
# First, it shows different options for using arithmetic operators.
# This operators allow to perform basic arithmetic calculus.
#
##################################################
#
##########... |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
***************************************************************************/
/***************************************************************************
* ... |
"""
Test the directory roster.
"""
import logging
import pytest
import salt.config
import salt.loader
import salt.roster.dir as dir_
@pytest.fixture
def roster_domain():
return "test.roster.domain"
@pytest.fixture
def expected(roster_domain):
return {
"basic": {
"test1_us-east-2_test_... |
import pytest
from zeroae.rocksdb.c import perfcontext
def test_fixture(rocksdb_perfcontext):
assert rocksdb_perfcontext is not None
def test_reset(rocksdb_perfcontext):
perfcontext.reset(rocksdb_perfcontext)
def test_report(rocksdb_perfcontext):
result = perfcontext.report(rocksdb_perfcontext, 0)
... |
# -*- coding: utf-8 -*-
# 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, softw... |
#!/usr/bin/python
# THIS TOOL, LIKE, GETS COMMENTS FROM A COMMUNITY OR WHATEVER.
import codecs, glob, os, pickle, pprint, logging, re, sys, time, urllib, urllib2
import xml.dom.minidom, xmlrpclib, socket
from xml.sax import saxutils
from optparse import OptionParser
import hswcsecret, hswcutil
import sqlite3
import d... |
from lxml import etree
def xml_to_string(xml_object: etree.Element) -> str:
return etree.tostring(xml_object).decode()
|
# Generated by Django 2.0.5 on 2018-09-01 06:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sunless_web', '0037_auto_20180901_1452'),
]
operations = [
migrations.AddField(
model_name='entity',
name='hash_v2',
... |
class GokoBot():
def __init__(self, bot):
self.__bot = bot
self.__id = bot.id
self.__first_name = bot.first_name
self.__is_bot = bot.is_bot
self.__user_name = bot.username
self.__can_join_groups = bot.can_join_groups
self.__can_read_all_group_messages = bot.can_read_all_group_mess... |
"""Collection of helper methods.
All containing methods are legacy helpers that should not be used by new
components. Instead call the service directly.
"""
from homeassistant.components.fan import (
ATTR_DIRECTION,
ATTR_OSCILLATING,
ATTR_PERCENTAGE,
ATTR_PERCENTAGE_STEP,
ATTR_PRESET_MODE,
ATTR... |
from django.urls import path
from scrumate.core.daily_scrum import views
urlpatterns = [
path('', views.daily_scrum_entry, name='daily_scrum'),
path('<int:deliverable_id>/set_actual_hour/', views.set_actual_hour, name='set_actual_hour'),
path('<int:deliverable_id>/update_actual_hour/', views.update_actual... |
# coding=utf-8
import os
import unittest
from mock import patch
import activity.activity_PostDecisionLetterJATS as activity_module
from activity.activity_PostDecisionLetterJATS import (
activity_PostDecisionLetterJATS as activity_object,
)
import tests.activity.settings_mock as settings_mock
from tests.activity.cl... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-04-20 18:04
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('validate', '0002_branch_contact'),
]
operations = [
migrations.AlterField(
... |
The loop ran 1 time
The loop ran 2 times
|
#!/usr/bin/env python3
#from HTMLParser import HTMLParser
import requests
from lxml import html
import jinja2
import boto3
import six
import os
import hashlib
URL = 'https://launchpad.net/~rquillo/+archive/ansible/+packages'
data = {}
packages = requests.get(URL)
tree = html.fromstring(packages.text)
data['author']... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.