text stringlengths 2 999k |
|---|
# -*- coding: utf-8 -*-
#
# Copyright 2017, 2018 dpa-infocom GmbH
#
# 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 appl... |
# coding: utf-8
import re
from ..extractor.nbc import NBCIE as Old
from ..utils import (
smuggle_url,
update_url_query,
int_or_none,
)
class NBCIE(Old):
def _real_extract(self, url):
try:
result = super(NBCIE, self)._real_extract(url)
if not result or not result.get('... |
import json
import sys
if len(sys.argv) == 2:
filename = sys.argv[1]
else:
print("Error - please specify one file name with the combined JSON")
with open(filename) as f:
data_json = json.load(f)
slot_stats = {}
def process_tutor_slots(tutor):
timeslots = tutor["timeSlots"]
officepref = tutor["of... |
import os
import sys
import time
import argparse
try:
import configparser
except:
import ConfigParser as configparser
from alize.script import AlizeTestCase
from blue.server import MinicapService
from blue.utility import *
from blue.utility import LOG as L
class TestCase_Unit(AlizeTestCase):
def __init__... |
#
# django-weblogparser
#
# Admin
#
from django.contrib import admin
from weblogparser.models import LogFilePath, LogFile, LogEntry
class LogFilePathAdmin(admin.ModelAdmin):
list_display = ['path']
admin.site.register(LogFilePath, LogFilePathAdmin)
class LogFileAdmin(admin.ModelAdmin):
list_display = ['pat... |
import random
import numpy as np
import pyswarms as ps
from pyswarms.utils.functions import single_obj as fx
def run_global_best_pso(n_dims, test_func, n_inds, n_gens, lower_bound, upper_bound,
initial_positions=None, random_seed=12345,
c1=0.5, c2=0.3, w=0.9
):
# check input
assert lower_bound < upper_bound... |
# Copyright (c) Facebook, Inc. and its affiliates.
import torch
from mmf.common.registry import registry
from torch import nn
from torch.nn.utils.weight_norm import weight_norm
class VisDialDiscriminator(nn.Module):
def __init__(self, config, embedding):
super().__init__()
self.config = config
... |
# input and print, with format strings
answer = input("What's your name? ")
print(f"hello, {answer}")
|
"""
Copyright 2020 EPAM Systems, 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 agreed... |
#!/usr/bin/env python
import rospy
from std_msgs.msg import Bool
from dbw_mkz_msgs.msg import ThrottleCmd, SteeringCmd, BrakeCmd, SteeringReport
from geometry_msgs.msg import TwistStamped
import math
from twist_controller import Controller
'''
You can build this node only after you have built (or partially built) th... |
import datasets
import addTorch
# order blocks
def compile(graph, inputs):
orderedBlocks = []
compiledBlocks = {}
for block in graph:
compiledBlocks[block] = False
for block in graph:
if not compiledBlocks[block]:
topologicalSort(graph, block, inputs, orderedBlocks, compiledBlocks)
... |
import discord
from discord.ext import commands
import sys
import io
import os
import json
import datetime
import re
import requests
def to_ascii(string):
string = string.replace("ä", "/ae").replace("ö", "/oe").replace("Ä", "/AE").replace("Ö", "/OE").replace("§", "/ss")
return string
def to_utf8(... |
import operator
import warnings
from collections.abc import Iterator, Sequence
from functools import wraps, partial
from numbers import Number, Integral
from operator import getitem
from pprint import pformat
import numpy as np
import pandas as pd
from pandas.util import cache_readonly
from pandas.api.types import (
... |
from rawserialised import *
from boostmappings import mappings
class Parser:
def __init__(self, funcs):
self.funcs = funcs
self.parsed = []
def parse(self):
for func in self.funcs:
self.parsed.append(Parser._parse(func))
##static methods below as they do not require i... |
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="skender-stock-indicators",
version="0.0.1",
author="Dave Skender",
maintainer="Dong-Geon Lee",
description="Stock indicators. Send in historical price quotes and get bac... |
"""
core layer, the core function module, provide the minimal function or features that data scientist may use
can be customized in services layer design
""" |
from PhaseNet_Analysis import run_phasenet
def test_run_phasenet(benchmark):
benchmark(run_phasenet) |
"""Test the Yeelight light."""
import logging
from unittest.mock import ANY, AsyncMock, MagicMock, call, patch
from yeelight import (
BulbException,
BulbType,
HSVTransition,
LightType,
PowerMode,
RGBTransition,
SceneClass,
SleepTransition,
TemperatureTransition,
transitions,
)
f... |
#!usr/bin/env python
import socket
import threading
import select
import time
def main():
class Chat_Server(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.running = 1
self.conn = None
self.addr = None
... |
import pygame
import os
from typing import List, Tuple
from itertools import count
PLAYER_WIDTH = 15
PLAYER_SPEED = 3
BLACK = (0, 0, 0)
ENEMY_HEIGHT = 8
ENEMY_WIDTH = 12
ENEMY_SCALE = 1
ENEMY_STEPS_PER_WIDTH = 4
ENEMY_SIDE_SPACE = 2
CRAB_WIDTH = 11
OCTOPUS_WIDTH = 12
SQUID_WIDTH = 8
CORPSE_WIDTH = 13
ROCKET_WIDTH... |
from gazette.spiders.base.fecam import FecamGazetteSpider
class ScArroioTrintaSpider(FecamGazetteSpider):
name = "sc_arroio_trinta"
FECAM_QUERY = "cod_entidade:24"
TERRITORY_ID = "4201604"
|
from http import HTTPStatus
from django.test import TestCase
from django.urls import resolve, reverse
from apps.core.views import CookiesView, CookieToggle
class CookieToggleTestCase(TestCase):
def test_choices(self):
toggle = CookieToggle()
toggle_label_choices = [v["label"] for k, v in toggle.... |
#
# Minimal settings for ReFrame tutorial on Piz Daint
#
class ReframeSettings:
job_poll_intervals = [1, 2, 3]
job_submit_timeout = 60
checks_path = ['checks/']
checks_path_recurse = True
site_configuration = {
'systems': {
'daint': {
'descr': 'Piz Daint',
... |
# -*- coding: utf-8 -*-
#
# Time-To-Recover Test documentation build configuration file, created by
# sphinx-quickstart on Fri May 4 13:58:22 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated ... |
import os
import pickle
import numpy as np
from sklearn import neighbors, svm
BASE_DIR = os.path.dirname(__file__) + '/'
PATH_TO_PKL = 'trained_classifier.pkl'
param_grid = [
{'C': [1, 10, 100, 1000],
'kernel': ['linear']},
{'C': [1, 10, 100, 1000],
'gamma': [0.001, 0.0001],
'kernel': ['rbf']
... |
# Copyright (C) 2012 Andy Balaam and The Pepper Developers
# Released under the MIT License. See the file COPYING.txt for details.
from assert_parser_result import assert_parser_result
def test_call_function():
assert_parser_result(
r"""
0001:0001 SYMBOL(f)
0001:0002 LPAREN
0001:0003 RPAREN
0... |
import numpy as np
import matplotlib as mpl
from matplotlib import gridspec
import matplotlib.pyplot as plt
from scipy.cluster import hierarchy
import seaborn as sns
import pandas as pd
from .utils import nullity_filter, nullity_sort
import warnings
def matrix(df,
filter=None, n=0, p=0, sort=None,
... |
from chispa import assert_df_equality
from cishouseholds.derive import assign_unique_id_column
def test_assign_unique_id_column(spark_session):
expected_df = spark_session.createDataFrame(
data=[("XAE-12", "XAE", "12"), ("BSE-53", "BSE", "53"), ("53", None, "53")],
schema=["id", "A", "B"],
)
... |
import sqlite3
from sqlite3 import Error
import time
from discord import user
import requests
from datetime import datetime
import os
class Connection:
'''
A class represent a connection to a database
This database will contain 3 tables, one for the last day a user upload image
the other is for all... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 10 21:33:22 2016
@author: Tobias Jachowski
"""
import matplotlib.pyplot as plt
import numpy as np
from pyoti.modification.modification import Modification, GraphicalMod
from pyoti import traces as tc
from pyoti.evaluate import signal as sn
class IAttachment(GraphicalMo... |
_base_ = [
'../../_base_/models/convswin_base.py', '../../_base_/datasets/kitti.py',
'../../_base_/iter_runtime.py', '../../_base_/schedules/schedule_cos24x_iter.py'
]
model = dict(
pretrained='./nfs/checkpoints/swin_large_patch4_window7_224_22k.pth', # noqa
backbone=dict(
pretrain_img_size=224... |
from robusta.api import *
class StressTestParams(ActionParams):
"""
:var n: Number of requests to run.
:var url: In cluster target url.
"""
n: int = 1000
url: str
@action
def http_stress_test(event: ExecutionBaseEvent, action_params: StressTestParams):
"""
Run an http stress test an... |
__all__ = [
'send_response',
'send_scheduledmessages_response',
'stop_scheduled_messages_response',
'get_messages_details_response',
'send_wrapper_response',
'get_message_query_response',
'get_scheduled_message_response',
] |
# This function will take a name and return the first initial of a name
# Create a function to return the first initial of a name
# Parameters:
# name: name of person
# Return value
# first letter of name passed in
def get_initial(name):
initial = name[0:1].upper()
return initial
# Ask for someone's name a... |
# Databricks notebook source
# MAGIC %run ../../notebooks/_modules/epma_global/functions
# COMMAND ----------
import os
import time
from pyspark.sql.functions import col,when,lit
import pyspark.sql.functions as F
import re
import pyspark.sql.types as pst
# COMMAND ----------
dbutils.widgets.removeAll()
# COMMAND -... |
DOMAIN = 'flask-seed.com'
ENV = 'production'
DEBUG = False
SECRET_KEY = '<FIXME>'
CACHE_TYPE = "SimpleCache"
CACHE_DEFAULT_TIMEOUT = 300
CACHE_THRESHOLD = 10240
ACCEPT_LANGUAGES = ['en', 'zh']
BABEL_DEFAULT_LOCALE = 'en'
BABEL_DEFAULT_TIMEZONE = 'UTC'
DEBUG_LOG = 'logs/debug.log'
ERROR_LOG = 'logs/error.log'
ADMI... |
import project1 as p1
import utils
import numpy as np
#-------------------------------------------------------------------------------
# Data loading. There is no need to edit code in this section.
#-------------------------------------------------------------------------------
train_data = utils.load_data('reviews_t... |
from .operator import CompoundOperator
|
# Copyright 2021 MosaicML. All Rights Reserved.
import os
import pathlib
import sys
import pytest
from torch.utils.data import DataLoader
from composer import Callback, Event, State, Trainer
from composer.loggers import FileLogger, FileLoggerHparams, Logger, LoggerDestination, LogLevel
from tests.common import Rando... |
#!/usr/bin/env python
# coding: utf-8
# # Deep Crossentropy method
#
# In this section we'll extend your CEM implementation with neural networks! You will train a multi-layer neural network to solve simple continuous state space games. __Please make sure you're done with tabular crossentropy method from the previous ... |
from models.loss.centernet_loss import centernet_Loss
import torch.nn as nn
import torch
class centernet_loss_module(nn.Module):
def __init__(self, config, stride=4, nstack=2):
super().__init__()
self.nstack = nstack
if nstack == 1:
self.center_loss = centernet_Loss(config["model"]["classes"], stride, config=... |
#!/usr/bin/env python
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
d = generate_distutils_setup(
packages=['rqt_runtime_monitor'],
package_dir={'': 'src'}
)
setup(**d)
|
import os
import shutil
import pytest
from jina import Flow, DocumentArray, Document
from .. import DocCache
cur_dir = os.path.dirname(os.path.abspath(__file__))
default_config = os.path.abspath(os.path.join(cur_dir, '..', 'config.yml'))
@pytest.mark.parametrize('cache_fields', ['[content_hash]', '[id]'])
def test... |
from .user import User
__all__ = ("User",)
|
from django.urls import path,include
from . import views
urlpatterns = [
path('',views.home, name='notice-home'),
]
|
from cu2 import exceptions
import threading
import click
import json
import os
import re
import requests
import sys
class BaseConfig(object):
def __init__(self):
self.load()
def __setattr__(self, name, value):
"""Ensures that changes made after loading with default values
are written ... |
from datetime import datetime, timedelta
from unittest.mock import Mock
from dateutil.tz import tzutc
from mock import patch
from app.data_models import QuestionnaireStore
from app.data_models.session_data import SessionData
from app.data_models.session_store import SessionStore
from app.questionnaire.questionnaire_s... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import nu... |
import numpy as np
import math
def model_evaluate(real_score,predict_score):
AUPR = get_AUPR(real_score,predict_score)
AUC = get_AUC(real_score,predict_score)
[f1,accuracy,recall,spec,precision] = get_Metrics(real_score,predict_score)
return np.array([AUPR,AUC,f1,accuracy,recall,spec,precision... |
import dataclasses
import yaml
pathNodeSettings = "/etc/cactus-indy/node-settings.yaml"
pathNodeValidatorRegistry = "/etc/cactus-indy/node-validator-registry.yaml"
pathValidatorSettings = "/etc/cactus-indy/validator-001-settings.yaml"
pathValidatorSecrets = "/etc/cactus-indy/validator-001-secrets.yaml"
#dataclass for... |
# This file is MACHINE GENERATED! Do not edit.
# Generated by: tensorflow/python/tools/api/generator/create_python_api.py script.
"""Public API for tf.random namespace.
"""
from __future__ import print_function as _print_function
from tensorflow.python import categorical
from tensorflow.python import get_seed
from te... |
###########################################################################
#
# Copyright 2021 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
#
# https://www.apache.org/l... |
class SessionHelper:
def __init__(self,app):
self.app = app
def login(self, username, password):
wd = self.app.wd
self.app.open_home_page()
wd.find_element_by_name("user").click()
wd.find_element_by_name("user").clear()
wd.find_element_by_name("user").send_keys(... |
# This file is part of sner4 project governed by MIT license, see the LICENSE.txt file.
"""
agent basic tests
"""
import json
from pathlib import Path
from uuid import uuid4
from flask import url_for
from sner.agent.core import main as agent_main
from sner.lib import file_from_zip
from sner.server.scheduler.models i... |
import collections
import copy
import typing
from river import stats
from river import optim
from river import utils
from . import base
__all__ = ['Baseline']
class Baseline(base.Recommender):
"""Baseline for recommender systems.
A first-order approximation of the bias involved in target. The model equat... |
import pickle
import gzip
import cv2
import face_recognition
#filename= 'c_object.obj'
# filename='newDump.pkl'
def compute(imge):
img = cv2.cvtColor(imge, cv2.COLOR_BGR2RGB)
encode = face_recognition.face_encodings(img)[0]
return encode
def save(object, filename, protocol = 0):
"""Saves a compresse... |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... |
import numpy as np
import math
class Section:
"""region"""
def __init__(self, x1, y1, x2, y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
def crop(self, img):
return img[self.y1: self.y2, self.x1: self.x2]
def coordinates(self):
return self.x... |
from flask_restx import fields
from recipes.restx import api
category_model = api.model('Category', {
# 'id': fields.Integer(readonly=True, description='The category unique identifier'),
'categoryName': fields.String(required=True, description='The category name'),
})
source_model = api.model('Source', {
... |
import getpass
userdb = {} # 用于存储用户名和密码
def register():
username = input('用户名: ').strip()
if username == '':
print('用户名不能为空')
elif not username.isalnum():
print('用户名只能包含字母和数字')
elif username in userdb:
print('用户已存在')
else:
password = input('密码: ')
userdb[u... |
#
# Tencent is pleased to support the open source community by making QTA available.
# Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved.
# Licensed under the BSD 3-Clause License (the "License"); you may not use this
# file except in compliance with the License. You may obtain a copy of the Li... |
"""Gaussian LSTM Policy.
A policy represented by a Gaussian distribution
which is parameterized by a Long short-term memory (LSTM).
"""
# pylint: disable=wrong-import-order
import akro
import numpy as np
import tensorflow as tf
from garage.experiment import deterministic
from garage.tf.models import GaussianLSTMModel... |
"""Provide access to Python's configuration information.
"""
import sys
import os
from os.path import pardir, realpath
_INSTALL_SCHEMES = {
'posix_prefix': {
'stdlib': '{base}/lib/{implementation_lower}{py_version_short}',
'platstdlib': '{platbase}/lib/{implementation_lower}{py_version_short}',
... |
from verbs import (
Verb1, Verb1B, Verb1C,
Verb2, Verb2B, Verb2C, Verb2D, Verb2E, Verb2F, Verb2G
)
class LUW(Verb1):
stem1 = "λυ+"
class TIMAW(Verb1B):
stem1 = "τιμα"
class POIEW(Verb1C):
stem1 = "ποιε"
class DHLOW(Verb1B):
stem1 = "δηλο"
class DIDWMI(Verb2):
stem1 = "διδο"
... |
# coding: utf-8
"""
NiFi Registry REST API
The REST API provides an interface to a registry with operations for saving, versioning, reading NiFi flows and components.
OUTPUTOpenAPI spec version: 0.3.0
Contact: dev@nifi.apache.org
Generated by: https://github.com/swagger-api/swagger-codegen.git
""... |
# !/usr/bin/env python
# -*- coding: UTF-8 -*-
from flask import Flask
app=Flask(__name__)
# app.config.from_pyfile('config.ini')
# app.config.from_envvar('FLASKCONFIG')
@app.route('/')
def index():
return 'hello python'
if __name__ == '__main__':
print(app.url_map)
app.run(host="0.0.0.0", port=5000, deb... |
import asyncio
import discord
from discord.ext import commands
from constants import *
from utils import *
from sqlite import Sql
from tibia import *
from guildstatseu import GuildStats
class Test(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.config = Config.load_config()
se... |
# Generated by Django 2.2.6 on 2019-10-25 09:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("surfsara", "0020_auto_20191024_1516")]
operations = [
migrations.AddField(
model_name="permission",
name="state",
fie... |
# c:\Python35\python -m venv c:\path\to\myenv |
from googletrans import Translator
translator = Translator()
with open('number.txt', 'w', encoding='utf-8') as num_2:
with open(r'C:\Users\Lonely_Wolf\OneDrive\Рабочий стол\work\number.txt', 'r', encoding='utf-8') as num:
numeral = num.read()
try:
num_2.write(translator.translate(numeral, dest=... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
import pytest
import copy
import collections
import json
import functools
import time
import sys
import test_config
@pytest.fixture(scope="function")
def device_... |
# Copyright (c) Facebook, Inc. and its affiliates.
import colorsys
import logging
import math
import numpy as np
from enum import Enum, unique
import cv2
import matplotlib as mpl
import matplotlib.colors as mplc
import matplotlib.figure as mplfigure
import pycocotools.mask as mask_util
import torch
from matplotlib.back... |
from logging import captureWarnings
import unittest
import sys,os
sys.path.append(os.path.join(os.path.dirname(__file__), '../app'))
from app import db, app
from models import *
from seeder import seeder
class BasicTest(unittest.TestCase):
@classmethod
def setUpClass(self):
# print('-----setUp-----'... |
def search(re, chars):
"""Given a regular expression and an iterator of chars, return True if
re matches some prefix of ''.join(chars); but only consume chars
up to the end of the match."""
states = set([re])
for ch in chars:
states = set(sum((after(ch, state) for state in states), []))
... |
# 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, Version 2.0 (the
# "License"); you may not u... |
import os
import torch
import numpy as np
from utils.loggers import Logger
class Exp_Basic(object):
def __init__(self, args, logger: Logger):
self.args = args
self.logger = logger
self.device = self._acquire_device()
self.model = self._build_model().to(self.device)
def _build... |
import typing as ty
from logging import getLogger
from xoto3.dynamodb.types import TableResource, ItemKey, Item
logger = getLogger(__name__)
def logged_update_item(
Table: TableResource, Key: ItemKey, update_args: ty.Mapping[str, ty.Any]
) -> Item:
"""A logged wrapper for Table.update_item"""
try:
... |
import logging
log = logging.getLogger("wfcli")
class NodeStore:
# a shallow wrapper for a dictionary.
# However, NodeStore implements a digest method
# these objects get stored in History in their entirety
def __init__(self):
self.nodes = {}
def __eq__(self, other_nds):
try:
... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
import json
import os
import zipfile
import shutil
from datetime import date
from django.http import HttpResponse, Http404
from django.shortcuts import get_object_or_404
from django.shortcuts import redirect
from django.template import RequestContext, loader
from django.template.defaultfilters import slugify
from dj... |
def add_subject_pronoun(sentence, lemma, gender=None, is_plural=None, position=None):
word = sentence.register_word(lemma)
word.set_tag("pronoun")
if lemma in ["il", "ils"]:
word.set_tag("gender", value="masc")
elif lemma in ["elle", "elles"]:
word.set_tag("gender", value="fem")
el... |
embedding_dim1 = 8
embedding_dim2 = 16
sequence_length = 10
# Attention
# dot product attention only allows vector/matrix of the same size
vector = torch.rand((1, embedding_dim1,))
matrix = torch.rand((1, sequence_length, embedding_dim1))
attention = DotProductAttention()
output = attention(vector, matrix)
print('Out... |
import numpy as np
import tqdm
from losses.dsm import dsm_score_estimation
import torch.nn.functional as F
import logging
import torch
import os
import shutil
import tensorboardX
import torch.optim as optim
from torchvision.datasets import MNIST, CIFAR10, FashionMNIST
import torchvision.transforms as transforms
from to... |
"""
Trains and validates models
"""
import os
import torch
import random
import pandas
import models
import warnings
import datasets
import argparse
import itertools
import numpy as np
from tqdm import tqdm
from sklearn.metrics import accuracy_score, recall_score
warnings.filterwarnings('always')
# Reproducibility
... |
#! /usr/bin/python3
import os, sys, re
with open('uni2pinyin.txt') as f:
u2p_table = f.read()
def unicode2pinyin(dir_name):
os.chdir(dir_name)
filenames = os.listdir(u'.')
for filename in filenames:
if os.path.isdir(filename):
unicode2pinyin(filename)
filename_tmp = ''
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name='pygments-style-soft-era',
version='1.0.3',
description='Pygments version of the soft-era theme.',
keywords=['pygments', 'style', 'soft-era'],
author='Audrey Moon',
maintainer='GinShio',
... |
import argparse
import random
def main():
n, e = parse_args()
generate_graph(n, e)
def parse_args():
parser = argparse.ArgumentParser(
description='Generate Graph for the FDEB benchmark')
parser.add_argument('num_nodes', metavar='N', type=int,
help='The number of nod... |
# Rasterize a shapefile with PNGCanvas
import shapefile
import pngcanvas
r = shapefile.Reader("hancock.shp")
xdist = r.bbox[2] - r.bbox[0]
ydist = r.bbox[3] - r.bbox[1]
iwidth = 400
iheight = 600
xratio = iwidth/xdist
yratio = iheight/ydist
pixels = []
for x,y in r.shapes()[0].points:
px = int(iwidth - ((... |
from distutils.version import LooseVersion
import six
from django.template import RequestContext
from django.utils.translation import override
import cms
from cms.api import add_plugin
from ..models import SelectedCategory
from .test_base import AldrynFaqTest
def _render_plugin(request, plugin):
def _render_... |
__author__ = 'ddustin'
import time
from twisted.trial import unittest
from market.btcprice import BtcPrice
class MarketProtocolTest(unittest.TestCase):
def test_BtcPrice(self):
btcPrice = BtcPrice()
btcPrice.start()
time.sleep(0.01)
rate = BtcPrice.instance().get("USD")
s... |
# -*- coding: utf-8 -*-
"""Timesketch scaffolder that generates analyzer plugins."""
import os
import logging
from typing import Dict
from typing import Iterator
from typing import Tuple
from l2tscaffolder.lib import definitions
from l2tscaffolder.lib import mapping_helper
from l2tscaffolder.scaffolders import interf... |
# Copyright 2013-2018 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
import sys
import os
class Ftgl(AutotoolsPackage):
"""Library to use arbitrary fonts in OpenGL a... |
#程序说明: 统计共有写过多少行程序,并分别列出来空行和注释
# 注意:没有考虑到行后的注释
import re, os
import string
filename = './2_Gen_ActiveCode.py'
total_line = 0
blank_line = 0
note_line = 0
f = open(filename, 'r', encoding='utf-8')
lines = f.readlines()
f.close()
total_line = len(lines)
line_index = 0
while line_index < total_line:
li... |
#! /usr/bin/python3.5
import sys
import linecache
def main():
prin("HELLO THERE")
# >>>>>>>>>>>>>>>>>>>>>>> MYDIE MODULE USED HERE <<<<<<<<<<<<<<<<<<<<<<<<<<<<
def mydie(exitCont_):
print(exitCont_)
print("*** ERROR OCCURRED *** : ROLL BACK PROCEDURES EXECUTING BELOW")
#... |
from .discovery import RoombaDiscovery
from .getpassword import RoombaPassword
from .roomba import Roomba, RoombaConnectionError, RoombaInfo
|
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.async.base.exchange import Exchange
from ccxt.base.errors import ExchangeError
class coinmate (Exchange):
def describe(sel... |
from typing import Optional
from apis.version1.route_login import get_current_user_from_token
from db.models.users import User
from db.repository.jobs import create_new_job
from db.repository.jobs import list_jobs
from db.repository.jobs import retreive_job
from db.repository.jobs import search_job
from db.session imp... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads_v2/proto/services/account_budget_service.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protob... |
# coding: utf-8
"""*****************************************************************************
* Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* re... |
# Copyright (c) Facebook, Inc. and its affiliates.
import csv
import json
import os
import torch
from torch.utils.data import DataLoader, Dataset
from torch.utils.data.distributed import DistributedSampler
from mmf.common.batch_collator import BatchCollator
from mmf.common.registry import registry
from mmf.utils.conf... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.