content stringlengths 5 1.05M |
|---|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
from builtins import zip
import pycrfsuite
def compareTaggers(model1, model2, string_list, module_name):
"""
Compare two models. Given a list of strings, prints out tokens & tags
whenever the two taggers parse a string differe... |
load("@npm//jest-cli:index.bzl", _jest_test = "jest_test")
load("@npm//@bazel/typescript:index.bzl", "ts_library")
#load("@npm_bazel_typescript//:index.bzl", "ts_library")
def jest_test(name, srcs, deps, jest_config, data = [], **kwargs):
"""Wrapper for running jest tests with the jest cli
Args:
name:... |
#!/usr/bin/env python
import sys, psycopg2
if len(sys.argv) < 2:
print "usage: %s <max> [min]" % sys.argv[0]
sys.exit(1)
upper = int(sys.argv[1])
if len(sys.argv) > 2:
lower = int(sys.argv[2])
else:
lower = 0
con = psycopg2.connect("")
cur = con.cursor()
print "Ready?"
sys.stdin.readline()
for i i... |
#! /usr/bin/env python
# This file is part of Scapy
# Scapy is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# any later version.
#
# Scapy is distributed in the hope that i... |
# EXP model from PG-GAN.
# Wang et al. 2021, https://doi.org/10.1111/1755-0998.13386
import pathlib
import demes
import msprime
import numpy as np
import dinf
population_name = "CEU"
samples = dinf.get_samples_from_1kgp_metadata(
"20130606_g1k_3202_samples_ped_population.txt", [population_name]
)
contig_lengths... |
# DO NOT EDIT! This file is automatically generated
import marshmallow
import marshmallow_enum
from commercetools import helpers, types
from commercetools._schemas._common import BaseResourceSchema, LocalizedStringField
from commercetools._schemas._type import FieldContainerField
__all__ = [
"MyCartAddDiscountCod... |
"""add_unique_in_class
Revision ID: 91c0103d0284
Revises: 237031a776fb
Create Date: 2021-03-04 08:38:55.907674
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '91c0103d0284'
down_revision = '237031a776fb'
branch_labels = ()
depends_on = None
def upgrade():
... |
ten_thing = "Apple Orange Crow Telephone Light Sugar"
print("Wait there are not 10 thing in that list. Let's fix that.")
thing_list = ten_thing.split(' ')
more_thing = ['Day', 'Night', 'Song', 'Frisbee',
'Corn', 'Banana', 'Girl', 'Boy']
while len(thing_list) < 10:
next_one = more_thing.pop()
pr... |
import torch
from torch.autograd import Function
from .._C import focal_loss
class SigmoidFocalLossFunction(Function):
def __init__(self, gamma, alpha, num_classes):
self.gamma = gamma
self.alpha = alpha
self.num_classes = num_classes
self.weight_pos = None
self.preds = ... |
# encoding: utf-8
import logging
import os
import grpc
from api.v1alpha1.grpc_proto.grpc_algorithm.python3 import (api_pb2,
api_pb2_grpc)
logger = logging.getLogger("grpc_algorithm-client")
logger.setLevel(logging.INFO)
console = logging.StreamHandler()
con... |
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
from torch.nn.utils.rnn import pad_packed_sequence as unpack
from torch.nn.utils.rnn import pack_padded_sequence as pack
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class LSTMEncoder(nn.Module):
... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
lastsum = 0
def order(self, root):
if root is None:
return
self.order(root.right)
root.val += self.lastsum
self.lastsum = root.val
... |
import tensorflow as tf
from tensorflow.keras.layers import (Activation, Concatenate, Conv2D, Reshape)
from typing import List
from .block import anchor_detect_head_block
from .layer import AnchorBoxes
class AnchorDetectHead(tf.keras.Model):
def __init__(self,
n_classes: int,
ima... |
import numpy as np
import torch
from medpy import metric
from scipy.ndimage import zoom
import torch.nn as nn
import SimpleITK as sitk
def one_hot_encoder(input_tensor,dataset,n_classes = None):
tensor_list = []
if dataset == 'MMWHS':
dict = [0,205,420,500,550,600,820,850]
for i in dict:
... |
class Film:
def __init__(self, width, height):
self.width = width
self.height = height
def aspect_ratio(self):
return self.width / self.height
|
import os
import synapseclient
class Env:
"""Provides access to all the environment variables the package uses."""
@staticmethod
def SYNAPSE_CONFIG_PATH():
"""Gets the path to the Synapse Config file.
Returns:
String
"""
return os.environ.get('SYNAPSE_CONFIG_P... |
import utils
boards = []
sequence = []
def day4(lines):
sequence = utils.str_to_int_arr(lines[0], ',')
print(sequence)
board = []
for line in lines[2:]:
if line == '':
if len(board) > 0:
boards.append(board)
board = []
else:
board.a... |
import os
os.environ[ "ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS" ] = "4"
os.environ[ "ANTS_RANDOM_SEED" ] = "3"
import ants
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from numpy.polynomial import Legendre
from scipy import linalg
from scipy.stats.stats import pearsonr
# exec(open("src/sfJointReg... |
from api.schemas import error_schema
from api.models import Error
from flask import jsonify
def error_response(code):
"""
Construct json response from error code
Args:
code(int): Error Code specified in error table json file
Returns:
Tuple of those items
... |
#This program will count how many minimum steps will be taken to reach the end if we will add the element of the index of the last added number of index
def minimum_number_of_jumps(x):#function defined for a list 'x'
print('Original list:\t',l)
k = []#defined an empty list for further operations
size = len... |
from .base import Base
from sqlalchemy import Column, ForeignKey, Integer, String
class ModelPeople(Base):
"""People model."""
__tablename__ = 'people'
id = Column('id', Integer, primary_key=True, doc="Id of the person.")
name = Column('name', String, doc="Name of the person.")
height = Column('... |
#!/usr/bin/env python
from __future__ import print_function
import os
import sys
import json
from ase.visualize import view
from ase.spacegroup import crystal
from ase.calculators.espresso import Espresso
# Read input JSON file
infile = sys.argv[1]
print(infile)
with open(infile) as handle:
system = json.loads(... |
# -*- coding: utf-8 -*-
import sys, os
import pandas as pd
import openpyxl
from openpyxl.styles import PatternFill
import numpy as np
from collections import defaultdict
from scanner_map import searchKey, CertifiedManufacturerModelNameCTDict, CertifiedManufacturerCTDict, TrueManufacturerModelNameCTDict, TrueManufacture... |
import sys
import struct
import array
import math
# import vpython as vp # pip install vpython
# from vypthon import rotate
# from vpython import vector
def VectorMagnitude(x,y,z):
return math.sqrt(x*x+y*y+z*z)
def Magnitude_ThreeC_TimeSeries(x,y,z):
nptsx=len(x)
nptsy=len(y)
nptsz=len(z)
if npt... |
import os
import win32com.client as win32
# only work in windows
path = os.getcwd()
successFile = "./success.txt"
failFile = "./fail.txt"
excel = win32.gencache.EnsureDispatch('Excel.Application')
for fname in os.listdir():
# print((fname+'x') in os.listdir())
if (fname[-3:] =='xls' and (fname+'x') not in os.listdir(... |
#
# @lc app=leetcode id=645 lang=python3
#
# [645] Set Mismatch
#
# https://leetcode.com/problems/set-mismatch/description/
#
# algorithms
# Easy (41.23%)
# Likes: 519
# Dislikes: 269
# Total Accepted: 61.1K
# Total Submissions: 147.5K
# Testcase Example: '[1,2,2,4]'
#
#
# The set S originally contains numbers ... |
# -*- coding: utf-8 -*-
'''
Created on Sep 12, 2012
@author: moloch
Copyright 2012 Root the Box
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/licen... |
"""empty message
Revision ID: 9f39b0404f06
Revises: 31fe8b0f3a0d
Create Date: 2019-05-09 12:25:19.389310
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '9f39b0404f06'
down_revision = '31fe8b0f3a0d'
branch_labels = Non... |
""" Utility functions for *pysg*."""
import inspect
import math
from functools import wraps
from pysg.error import PyrrTypeError
import numpy as np
def pyrr_type_checker(var: object, var_type: type) -> object:
""" Makes sure that pyrr types are used as input. Tries to cast and raises PyrrTypeError if not possibl... |
from email.mime.text import MIMEText
import smtplib, configparser
class sendMail():
def __init__(self, to):
self.to = to
self.config = configparser.ConfigParser()
self.config.read('smtpconfig.ini')
self.user = self.config.get('SMTP', 'user')
self.pswd = self.config.get('SMTP', 'pswd')
content = 'ζ¨ε₯½οΌζ¨ε¨ι εζ΅·ε€§... |
# -*- coding: utf-8 -*-
"""
The :mod:`coclust.io.data_loading` module provides functions to load data
from files of different types.
"""
# Author: Severine Affeldt <severine.affeldt@parisdescartes.fr>
import logging
import os.path
import numpy as np
from scipy.sparse import coo_matrix
from scipy.io import whosmat,... |
# Return true iff a depends on b,
# i.e. b is in the dependencies of a
def depends_on(a, b, dependencies):
if not a in dependencies:
return False
first_levels_deps = dependencies[a]
# first level dependency
if b in first_levels_deps:
return True
for a_dep in first_levels_deps:
... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2011 Nicira Networks, Inc. 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.apac... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == '__main__':
sum = 10
x = 10
for i in range(6):
x = x * 1.1
sum += x
print(sum)
|
# Copyright (c) 2003-2008 Ralph Meijer
# See LICENSE for details.
"""
Tests for L{wokkel.generic}.
"""
from twisted.trial import unittest
from twisted.words.xish import domish
from wokkel import generic
from wokkel.test.helpers import XmlStreamStub
NS_VERSION = 'jabber:iq:version'
class VersionHandlerTest(unittest... |
#!python3.6
### WORK IN PROGRESS ###
import threading
import fileinput
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import linregress as linear
from scipy import interpolate
#fname = input("Filename: ")
fname = "data/arhiv/cd5.csv"
content = open(fname).readlines()
print(len(content))
wavelen =... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for the dask_cassandra_loader module.
"""
import unittest
import pytest
import pandas as pd
from cassandra.cluster import Cluster
from cassandra.protocol import NumpyProtocolHandler
from cassandra.auth import PlainTextAuthProvider
from dask_cassandra_loader import... |
import wx
import math
import datetime
import wx.lib.newevent
CountdownEvent, EVT_COUNTDOWN = wx.lib.newevent.NewEvent()
tCos60 = [math.cos((i/60.0)*2.0*math.pi-math.pi/2.0) for i in range(60)]
tSin60 = [math.sin((i/60.0)*2.0*math.pi-math.pi/2.0) for i in range(60)]
def GetCos( pos ):
return math.cos(pos*2.0*math.pi... |
# flake8: noqa
from marshmallow.validate import ContainsNoneOf
from marshmallow.validate import ContainsOnly
from marshmallow.validate import Email
from marshmallow.validate import Equal
from marshmallow.validate import Length
from marshmallow.validate import NoneOf
from marshmallow.validate import OneOf
from marshmall... |
from .vec2 import Vec2
from .box import Box
# from .phys import Phys
|
from playhouse.shortcuts import model_to_dict
from datetime import datetime
import os
from msph.app import Command, current_app
from ... import settings, wsp
from ...models import WspTarget, Target
from ...validators import ActiveTargetRequired
from ... import utils
from . import msgs
export = Command('export', __na... |
from .pvt import pvt_small_impr1_peg
from .pvt_v2_ap import pvt_v2_b2_ap,pvt_v2_b0_ap
from .pvt_v2 import pvt_v2_b5,pvt_v2_b2, pvt_v2_b0,pvt_v2_b1
from .swin import SwinTransformer
|
import sys
import os
import json
import re
import io
import urllib
import hashlib
import string
import random
import requests
import math
import logging
import shutil
import time
import traceback
from requests_toolbelt import MultipartEncoder
from multiprocessing import Pool
#from functools import partial
import subpro... |
#################################################################################################
# ev3_remoted.Ev3RobotMessage class #
# Version 1.0 #
# ... |
import os
from bentoml.configuration import get_local_config_file, BENTOML_HOME
def test_get_local_config_file():
config_file = get_local_config_file()
assert config_file == os.path.join(BENTOML_HOME, "bentoml.cfg")
os.environ["BENTOML_CONFIG"] = "/tmp/bentoml.cfg"
config_file = get_local_config_fil... |
from collections import defaultdict
class VariableStore():
def __init__(self):
self.store = defaultdict(int)
def getRef(self, name):
self.store[name] += 1
return name
def getVarList(self):
variables = []
for key, value in self.store.items():
variables.a... |
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation.
# All rights reserved.
# mypy: allow-untyped-defs, allow-untyped-calls
"""Tokenization help for Python programs.
generate_tokens(readline) is a generator that breaks a stream of
text into Python tokens. It accepts a readline-like method ... |
# Borrowed for testing with real test data from https://github.com/AFNetworking/AFNetworking
OBJC_TEST_FILES = {"AFHTTPSessionManager.m": """
// AFHTTPSessionManager.m
// Copyright (c) 2011β2016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person ob... |
'''
Blocks
Fairgame, Fall 2015
Patrick Biernat
RPISEC
'''
from twisted.internet import reactor, protocol
from Crypto.Cipher import AES
import os
import base64
import random
PORT = 9001
FLAG = "flag{Sw@pp!n_Bl0x_liek_l3g0z}"
KEY = os.urandom(32)
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKG... |
from multiprocessing import *
from ctypes import *
def f(x):
print(1)
string_at(1)
print(2)
if __name__ == '__main__':
p = Pool(1)
p.apply(f, [0])
print(3) |
from django.db import models
from jsonfield import JSONField
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
import datetime
import json
# λΈλλ
class Brand(models.Model):
brand_name = models.CharField(max_length=100, default="")
de... |
from datasets import load_dataset, load_metric, Audio
import os
import codecs
import pandas as pd
print("Loading dataset Common Voice..")
#common_voice = load_dataset("common_voice", "it", split="train")
common_voice = load_dataset("mozilla-foundation/common_voice_7_0", "it", use_auth_token=True, split="train")
# conc... |
from .models import Invoice, Ref, Address
from mysite import settings
from mysite.utils import httpRequests, context
from .InvoiceUtils import services, LineDetailHelper
import json
import jsonpickle
from urllib.parse import quote
def createInvoice(context):
invoice = Invoice()
invoice.CustomerRef = Ref(value... |
from termcolor import colored
import datetime
ENABLED = True
def warn(msg):
if ENABLED:
d = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print (colored("%s %s" % (d,msg), "yellow"))
def error(msg):
if ENABLED:
d = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print (colored("%s %s" % (d,msg... |
def test_case(args, random) -> str:
# Reading args passed to the stress testing command
n_limit = int(args[0])
num_limit = int(args[1])
# Generating the size of the array randomly
n = random.randint(1, n_limit)
# Populating the array with random numbers as strings
nums = ' '.join([str(rand... |
'''
10 - Changing the output in generator expressions
Great! At this point, you already know how to write a basic generator expression.
In this exercise, you will push this idea a little further by adding to the output
expression of a generator expression. Because generator expressions and list
comprehensions are so ... |
import re
tmp=re.match("\d+_(\d+)\.txt", '324_324.txt').group(1)
print(tmp) |
from PIL import Image
from io import BytesIO
from oarepo_iiif import current_oarepo_iiif
def test_rest_opener(app, db, client):
def test_opener(image_id, **kwargs):
img = Image.new('RGB', (int(image_id), int(image_id)), color='red')
f = BytesIO()
img.save(f, format='PNG')
f.seek(0... |
# Copyright (c) 2019 XebiaLabs
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
import sets
import sys
import unicodedata
import logging
import com.xhaus.jyson.JysonCodec as json
import xml.etree.ElementTree as ET
# from rqmjazz.core.HttpRequestPlus import HttpRequestPlus
fr... |
from math import log
from numpy import nextafter, inf
def calculate_tau(pheromone_matrix, current_node, node, alpha):
tau = pheromone_matrix[current_node.id][node.id]**alpha
if tau == 0.0:
tau = nextafter(0.1, inf)
return tau
def calculate_eta(distance_matrix, current_node, node, beta):
re... |
from django.shortcuts import render
from django.views.generic import CreateView,TemplateView
from django.urls import reverse_lazy
from . import forms
class SignCreateView(CreateView):
form_class = forms.UserCreateForm
success_url = reverse_lazy('accounts:login')
template_name = "accounts/signup.html"
|
from django.contrib import admin
from django.contrib.admin import ModelAdmin
from automationcommon.models import Audit
class AuditAdmin(ModelAdmin):
list_display = ('when', 'who', 'model', 'model_pk', 'field', 'old', 'new')
admin.site.register(Audit, AuditAdmin)
|
banner = """\u001b[36;1m
ββββββ ββββββ βββ βββββ ββββββ ββββ ββββ ββββ βββ β
βββ ββββββ β βββββββββ βββ ββββββ βββ βββββββ β βββ ββ β ββ ββ β
βββ βββββ ββ ββββ βββ ββββββββββββ ββ βββ ββββ ββ ββββ ββ ββ βββ
ββββ ββββββββ βββββββββ βββ ββββββ ββββββ βββ βββββββββ... |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
"""Top-level structure for skeletor """
from . import proc
from . import models
from . import datasets
from . import optimizers
from .launcher import supply_args, supply_postprocess, execute
__all__ = ['proc', 'supply_args', 'supply_postprocess', 'execute', 'models',
'datasets', 'optimizers']
name = 'skele... |
import random
import time
from common.challenge import MatasanoChallenge
from common.random.mt19937 import MersenneTwister
class Clock(object):
_timestamp = int(time.time())
@classmethod
def advance(cls, seconds):
cls._timestamp += seconds
@classmethod
def now(cls):
... |
''' Incremental-Classifier Learning
Authors : Khurram Javed, Muhammad Talha Paracha
Maintainer : Khurram Javed
Lab : TUKL-SEECS R&D Lab
Email : 14besekjaved@seecs.edu.pk '''
from torchvision import datasets, transforms
import torch
import numpy as np
# To incdude a new Dataset, inherit from Dataset an... |
# Copyright 2020 Huy Le Nguyen (@usimarit)
#
# 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 t... |
#!/usr/bin/env python3
"""Project Euler - Problem 42 Module"""
import math
import os
import string
def is_triangle_number(x):
n = math.sqrt(1 + (8 * x))
return n == int(n) and n % 2 == 1
def problem42(filename):
"""Problem 42 - Coded triangle numbers"""
words = []
# read file
with open(file... |
#!/usr/bin/env python
import os
import re
import sys
import argparse
import logging
import pandas
def create_if_does_not_exist(input_path):
if not os.path.exists(input_path):
logging.info('Path {} does not exist. Creating...'.format(input_path))
os.makedirs(input_path)
def string_to_safe_filen... |
import json
from nkn_client.jsonrpc.rpc import call_rpc
class NknJsonRpcApi(object):
"""
A client for the NKN JSON-RPC API. Communicates over plaintext HTTP to submit
RPC requests according to the JSON-RPC 2.0 specification.
Args:
hostname (str) : The hostname on which the API is served.
"""
def __in... |
import torch
from torch.functional import F
'''
--- S T A R T O F F U N C T I O N B A C K P R O P _ K E R N E L _ I N D I C E S ---
[About]
Function for finding the indices of specific kernels in previous layers that are above a certain threshold.
The function iterates over all chosen kernel... |
from django.urls import path
from .views import bundle_view
urlpatterns = [path("<str:slug>/", bundle_view)]
|
"""
..module:: add_static_values
:synopsis: Given the full dictionary of possible static value xml entries,
this module decides which portions to actually add to the caomlist based
on various conditions. (This is expected to grow as the list of static
values does as well)
"""
import logging
from lib.... |
# ===--- SwiftFloatingPointTypes.py ------------------*- coding: utf-8 -*-===//
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.t... |
import pytest
from tenable.nessus.schema.scans import ScanExportSchema
def test_scan_export_echema():
schema = ScanExportSchema()
l = schema.load({'format': 'db',
'password': 'abc',
'template_id': 1
})
assert schema.dump(l) == {'format': 'db',... |
import ast
import re
MENTION_REGEX = re.compile(r"<@(!?)([0-9]*)>")
def iter_dict(d: dict):
stack = list(d.items())
visited = {}
while stack:
k, v = stack.pop()
if isinstance(v, dict):
for i, x in v.items():
visited[i] = x
else:
visited[k]... |
import datetime
import unittest
import config
import utils
class XsrfToolTests(unittest.TestCase):
TEST_NOW = datetime.datetime(2010, 1, 31, 18, 0, 0)
def setUp(self):
utils.set_utcnow_for_test(XsrfToolTests.TEST_NOW)
def testGenerateAndVerifyGoodToken(self):
config.set(xsrf_token_key=... |
import os
from app import db
from werkzeug.security import generate_password_hash, check_password_hash
class DBHelper:
"""DB helper class"""
@staticmethod
def add(entity):
"""Add entity to db"""
db.session.add(entity)
db.session.commit()
@staticmethod
def delete(entity):
... |
import logging
from pyrogram import Client as Animefilter_bot1, filters as Worker, emoji
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, InlineQueryResultCachedDocument
from Animefilter_bot1.database._utils import get_size
from Animefilter_bot1.database.autofilter_db import get_search_results, is... |
"""test for NetboxVlan model."""
import os
import yaml
import pytest
import pynetbox
from diffsync.exceptions import ObjectNotFound
from network_importer.adapters.netbox_api.models import NetboxVlan, NetboxDevice
ROOT = os.path.abspath(os.path.dirname(__file__))
FIXTURE_28 = "../fixtures/netbox_28"
FIXTURE_29 = "../... |
#! /usr/bin/env python
# Copyright (c) 2010, Washington University in St. Louis
# 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 above co... |
# -*- coding: utf-8 -*-
"""
This code is auto generated from troposphere_mate.code_generator.__init__.py scripts.
"""
import sys
if sys.version_info.major >= 3 and sys.version_info.minor >= 5: # pragma: no cover
from typing import Union, List, Any
import troposphere.sagemaker
from troposphere.sagemaker import ... |
from mikecore.DfsDLL import DfsDLL
from mikecore.DfsFile import TimeAxisType, DfsFile, DfsDLLUtil
from mikecore.DfsFileFactory import DfsFileFactory
def test_timeaxis():
dfs = DfsFileFactory.DfsGenericOpen("testdata/TemporalEqCal.dfs0")
timeaxistype = dfs.FileInfo.TimeAxis.TimeAxisType
dfs.Close()
as... |
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class NotifyFieldExt(object):
def __init__(self):
self._accessable = None
self._desc = None
self._field = None
self._name = None
@property
def accessable(self):... |
import signal
import argparse
import os
from model.metatile import METATILE_TYPES
from solver import Solver
from utils import get_filepath, read_pickle, read_json, error_exit, get_basepath_filename
"""
Run clingo solver on the given prolog file with the specified params
"""
def keyboard_interrupt_handler(signal, fr... |
import copy
import time
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import albumentations
from albumentations.pytorch import ToTensorV2, ToTensor
from C2C.dataloader import *
from C2C.eval_model import *
from C2C.utils import *
from C2C.cluster import run_clustering
def train... |
import torch
import torch.nn as nn
import lightconvpoint.nn as lcp_nn
class ResnetBlock(nn.Module):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
K,
ConvNet,
Search,
stride=1,
npoints=-1,
):
super().__init__()
... |
from app.main import main
from flask import g, url_for, render_template, redirect, request
from app import db
from app.models import Registrant, Clerk
from app.decorators import InSession
from app.services import SessionManager
from app.services.steps import Step_VR_7
@main.route('/vr/submission', methods=["GET"])
@In... |
import gym
import numpy as np
from gym import spaces
from dm_alchemy import symbolic_alchemy
from dm_alchemy.encode import chemistries_proto_conversion
from dm_alchemy.types.utils import ChemistrySeen, ElementContent
LEVEL_NAME = 'alchemy/perceptual_mapping_randomized_with_rotation_and_random_bottleneck'
CHEM_NAME = ... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# encoding: utf-8
# Copyright 2018 Orange
#
# 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
#
# Un... |
import sys
def progress(count, total, suffix=''):
bar_len = 60
filled_len = int(round(bar_len * count / float(total)))
percents = round(100.0 * count / float(total), 1)
bar = '=' * filled_len + '-' * (bar_len - filled_len)
sys.stderr.write('[%s] %s%s ...%s\r' % (bar, percents, '%', suffix))
|
import ctypes
from struct import unpack
c_uint8 = ctypes.c_uint8
c_uint16 = ctypes.c_uint16
class Buttons_bits(ctypes.LittleEndianStructure):
_fields_ = [
("R1", c_uint8, 1),
("L1", c_uint8, 1),
("start", c_uint8, 1),
("select", c_uint8, 1),
("R2", c_uint8, 1),
("L2... |
#
# This file contains the Python code from Program 15.14 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm15_14.txt
#
class TwoWayMerge... |
import pandas as pd
import numpy as np
import datetime
import scipy.stats as stats
from imblearn.over_sampling import SMOTE
from sklearn import preprocessing
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
from sklearn.mo... |
class AbstractDirectModel(object):
def __init__(self):
pass
def train(self, x, t, y, num_treatment):
raise NotImplementedError()
def predict_y_t(self, x, t_val):
raise NotImplementedError()
|
# Copyright 2004-2008 Roman Yakovenko.
# Distributed under the Boost Software License, Version 1.0. (See
# accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
import os
import sys
import unittest
import autoconfig
import fundamental_tester_base
from pyplusplus import code_creators
cla... |
from datetime import datetime
import re
__formatted_date_regex__ = "(\d{2,4}[\/|.|\-])?\d{1,2}(\/|\.|-)\d{1,2}( \d{1,2}:\d{1,2}(:\d{1,2})?)?"
__formatted_date_pattern__ = re.compile(__formatted_date_regex__)
__DATETIME__ = 0
__YEAR__ = 1
__DELIMITER__ = 2
__TIME__ = 3
__SECOND__ = 4
def parse(sentence)... |
from django.shortcuts import render
# Create your views here.
def git_self_pull():
import git
# pull from remote origin to the current working dir
git.cmd.Git().pull('https://github.com/Ratgor/iLikeit-voting-platform','master')
# https://blog.bearer.sh/consume-webhooks-with-python/
from djang... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.