content stringlengths 5 1.05M |
|---|
import logging
import re
from sklearn.feature_extraction.text import TfidfVectorizer
import pandas
import pathlib
LOG = logging.getLogger(__name__)
DATA_FILE_NAME_PATTERN = re.compile(r'dnsSummary_(.*)\.pcap\.csv-proc\.csv') #dnsSummary_user292.pcap.csv-proc.csv
def normalize_domain_name(domain_name):
return do... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from loguru import logger
logger.enable("imma")
# import funkcí z jiného adresáře
import os.path
import unittest
import numpy as np
import os
# import io3d
import io3d.datasets
import imma.labeled as imlb
import imma.image as imim
class LabeledTest(unittest.TestCa... |
# -*- coding: utf-8 -*-
"""
:copyright: Copyright 2020 Sphinx Confluence Builder Contributors (AUTHORS)
:license: BSD-2-Clause (LICENSE)
"""
def apply_defaults(conf):
"""
applies default values for select configurations
This call will populate default values for various configuration options.
This met... |
# coding: utf-8
import pickle
import pytest
import uuid
from leady import LeadyTracker, LeadyTrackerError, InvalidInputError
HTTP_HOST = 'imper.cz'
HTTP_X_FORWARDED_FOR = '1.2.3.4'
HTTP_USER_AGENT = 'Browser/2.0'
TEST_KEY = 'a' * 16
TEST_LOCATION = 'https://example.com/?hallo=there are lions&12345#remove-thi-part-pl... |
# The MIT License (MIT)
#
# Copyright (c) 2015 University of East Anglia, Norwich, UK
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the r... |
import os.path
import json
class Matrix:
# Matrix Class is used to handle raw node data and parse it into a Json File for Dijkstra
graph = {} # Matrix holds graph
NodeArray = [] # Array with all nodes of the network
JsonFile = "data.json" # Link to Json File (Set as a blank string)
JSON... |
import logging
import os
import re
from typing import Tuple, Optional
from urllib.parse import unquote_plus
from sqlalchemy.orm import Session
from backend.corpora.common.entities import Collection
from backend.corpora.common.upload import upload
from backend.corpora.common.utils.db_session import db_session_manager
... |
"""Mixin class for analytics submodule containing vector analytics tools.
"""
from .dimensionality_reduction import *
from .viz import *
class ViAnalyticsMixin(VizMixin):
"""
Vi Analytics Mixin.
Currently includes visualisation mixin.
"""
pass
|
# Generated by Django 3.0.7 on 2020-06-28 18:24
from decimal import Decimal
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('polls', '0003_allfields'),
]
operations = [
migrations.RemoveField(
model_name='allfield... |
import os
import glob
import logging
import subprocess
from pathlib import Path
from platform import system, version
import wheel.bdist_wheel as orig
import site
import shutil
try:
from setuptools import setup, find_packages, Extension
from setuptools.command.install import install
except ImportError:
from... |
# @l2g 1745 python3
# [1745] Palindrome Partitioning IV
# Difficulty: Hard
# https://leetcode.com/problems/palindrome-partitioning-iv
#
# Given a string s,
# return true if it is possible to split the string s into three non-empty palindromic substrings.
# Otherwise,return false.
# A string is said to be palindrom... |
from app.extensions import signals
from .handlers import _user_register
USER_REGISTER_SIGNAL = signals.register_signal('user.register', _user_register) |
from fnmatch import fnmatch
from os.path import splitext
import argparse
import json
import os
import requests
import sys
import traceback
import xml.etree.ElementTree as ET
from github import Github, UnknownObjectException
try:
token = os.environ['GITHUB_TOKEN']
except KeyError:
print(('GITHUB_TOKEN environm... |
import sys
from engine import *
from engine.utils import vector2
import random
from block import Block
from ogre import Ogre
def generate_platform(scene,x,y,l):
for i in range(0,l):
j=random.randint(6,9)
if i==0: j=5
if i==(l-1): j=10
b=Block(1,j)
b.set_position(x,y)
... |
from decimal import Decimal
from simfile.timing import BeatValues
from simfile.timing._private.sscproxy import ssc_proxy
from typing import NamedTuple, Union
from ..ssc import SSCChart
from ..types import Simfile
__all__ = [
'StaticDisplayBPM', 'RangeDisplayBPM', 'RandomDisplayBPM', 'DisplayBPM',
'displaybpm... |
from functools import wraps
from django.utils.decorators import available_attrs
from .toolbox import auth_handler_response
def oauth_required(scope: str = None, scope_auto: bool = False):
"""Views decorator checking user oauth token.
:param scope: scope identifier string to check token has access to the sc... |
import re
class Circuit:
def __init__(self, desc):
self.desc = desc
self.wires = {}
self.ops = {
'AND': lambda a, b: a & b,
'OR': lambda a, b: a | b,
'LSHIFT': lambda a, b: a << b,
'RSHIFT': lambda a, b: a >> b,
'NOT': lambda a: 2**16 + (~a),
}
def run(self):
lines = self.desc.copy()
wh... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Paul Arthur <paul.arthur@flowerysong.com>
# Copyright: (c) 2019, XLAB Steampunk <steampunk@xlab.si>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_fun... |
"""Unit tests for starlark helpers
See https://docs.bazel.build/versions/main/skylark/testing.html#for-testing-starlark-utilities
"""
load("@bazel_skylib//lib:unittest.bzl", "asserts", "unittest")
load("//lib/private:expand_make_vars.bzl", "expand_variables")
def _variables_test_impl(ctx):
env = unittest.begin(ct... |
import logging
from flask_appbuilder.baseviews import BaseView, expose
from . import db
from .models import AdminHomeData
"""
Home view
"""
def fetch_admin_home_data():
try:
results = \
db.session.\
query(AdminHomeData).\
filter(AdminHomeData.admin_data_tag=="produ... |
class BRepType(Enum, IComparable, IFormattable, IConvertible):
"""
This class defines an enumerative type used to specify the type of output geometry expected from a BRepBuilder.
enum BRepType,values: OpenShell (0),Solid (1),Void (2)
"""
def __eq__(self, *args):
""" x.__eq__(y) <==> x=... |
"""
ASGI config for enfight project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
# Fetch Django ASGI application ear... |
# Copyright 2014-2018 The PySCF Developers. 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 appl... |
# Copyright (C) 2021 ETH Zurich and University of Bologna
#
# 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 ... |
from ifgraphviz.ifgraphviz import *
|
"""
https://leetcode-cn.com/problems/number-of-islands/
https://leetcode-cn.com/problems/number-of-islands/solution/dao-yu-shu-liang-by-leetcode/
https://leetcode-cn.com/problems/number-of-islands/solution/dfs-bfs-bing-cha-ji-python-dai-ma-java-dai-ma-by-l/
"""
from typing import List
class Solution:
"""
... |
#-------------------------------------------------------------------------------
# $Id$
#
# Project: EOxServer <http://eoxserver.org>
# Authors: Fabian Schindler <fabian.schindler@eox.at>
#
#-------------------------------------------------------------------------------
# Copyright (C) 2014 EOX IT Services GmbH
#
# Per... |
# -*- coding: UTF-8 -*-
# vim: ts=4 sts=4 sw=4 tw=100 sta et
class NotInRole(Exception):
pass
def check_role(my_roles, requested_roles):
if not my_roles:
return True
for role in my_roles:
if role in requested_roles:
return True
raise NotInRole()
|
from sklearn.base import TransformerMixin
class PercentChangeTransformer(TransformerMixin):
def __init__(self, column,outputname="Pct_Change",lookback=1):
self.column = column
self.cols = [column]
self.outputname = outputname
self.lookback = lookback
def fit(self, x, y=None):
... |
''' Learning algorithms for tractography'''
import numpy as np
from . import track_metrics as tm
import dipy.core.track_performance as pf
from scipy import ndimage as nd
import itertools
import time
import numpy.linalg as npla
def larch(tracks,
split_thrs=[50.**2,20.**2,10.**2],
ret_atracks=Fals... |
import json
from dds_web import db
from dds_web.database import models
import tests
first_new_email = {"email": "first_test_email@mailtrap.io"}
first_new_user = {**first_new_email, "role": "Researcher"}
first_new_user_extra_args = {**first_new_user, "extra": "test"}
first_new_user_invalid_role = {**first_new_email, "r... |
"""City Name and Sketch Name properties"""
#
# Ideally we would like some sort of hybrid entry field
# that combines display of the sketchname with entry of the
# city name -- this is why the file is named as it is. The
# hybrid entry field would have a different pattern when
# text is being entered than when displayed... |
from ._ImageFileWriter import ImageFileWriter
from ._VideoFileWriter import VideoWriter
|
"""Tests for Tag related views."""
from webtest import TestApp
def test_GET_tags(testapp: TestApp, democontent: None) -> None:
"""Test GET /api/tags."""
res = testapp.get("/api/tags", status=200)
assert res.json == {"tags": ["dogs", "cats"]}
|
class Solution:
# def removeElement(self, nums: List[int], val: int) -> int:
def removeElement(self, nums, val) :
if len(nums) == 0:
return 0
# for _ in range(len(nums)):
# num = nums.pop()
# if num == val:
# continue
# nums.insert... |
from collections import defaultdict
stream_cache = defaultdict(list)
|
# -*- coding: utf-8 -*-
from ocelot.transformations.cutoff.cleanup import (
drop_rp_activity_links,
drop_zero_amount_activity_links,
remove_consequential_exchanges,
)
def test_remove_consequential_exchanges():
given = [{
'name': 'a name',
'exchanges': [{
'name': 'exchange 1... |
from io import BufferedIOBase
from ps1_argonaut.BaseDataClasses import BaseDataClass
from ps1_argonaut.configuration import Configuration
class ScriptData(BaseDataClass):
def __init__(self, data: bytes):
self.data = data
@property
def size(self):
return len(self.data)
@classmethod
... |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from ellipsoid_fit import ellipsoid_fit, ellipsoid_plot, data_regularize
if __name__=='__main__':
data = np.loadtxt("mag_out.txt")
data2 = data_regularize(data, divs=8)
center, radii, evecs, v = ellipsoid_fit(data... |
# Generated by Django 3.0.5 on 2020-06-08 09:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("posthog", "0063_team_completed_snippet_onboarding"),
]
operations = [
migrations.AddField(
model_name="user",
name="... |
# -*- coding: utf-8 -*-
import os
import argparse
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
import numpy as np
import pandas as pd
import json
class COCOeval2(COCOeval):
def __init__(self, cocoGt=None, cocoDt=None, iouType='bbox'):
super().__init__(cocoGt=cocoGt, cocoD... |
# -*- coding: utf-8 -*-
from flask import current_app, request, json
def render_json(*args):
kwargs = dict(indent=None if request.is_xhr else 2)
return current_app.response_class(
json.dumps(*args, **kwargs),
mimetype='application/json')
|
bl_info = {
"name": "Batch Exporter",
"description": "",
"author": "Mitch McCollum",
"version": (1, 8, 17),
"blender": (2, 80, 0),
"location": "3D View > Tools",
"warning": "", # used for warning icon and text in addons panel
"wiki_url": "",
"tracker_url": "",
"category": "Develo... |
#!/usr/bin/env python
import paramiko
def ssh_command(ip, port, user, passwd, command):
client = paramiko.SSHClient()
# client.load_host_keys('/home/_/.ssh/known_hosts')
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=ip, port=port, username=user, password=passwd)... |
import j1939
class ParameterGroupNumber:
"""Parameter Group Number (PGN).
The PGN are described in SAE J1939/21 and consists of four parts:
* 1-bit Reserved (sometimes referred to as Extended Data Page)
* 1-bit Data Page (DP)
* 8-bit PDU Format (PF)
* 8-bit PDU Specific (PS)
Prede... |
"""Database migrations manager"""
import os
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app.models import User, UserType
from app import db, create_app
app = create_app(config_name=os.getenv('APP_MODE'))
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_comman... |
import pytest
from csp_tool.csp_analyser import get_domains_per_directive, rollup_data_by_header, \
check_unsafe_inline_used_without_domains, extract_policies_without_domains, \
check_keyword_used_without_domains, extract_policies_using_localhost
def generate_known_test_data():
# for reference expected da... |
import os
import sys
import argparse
import cv2
import numpy as np
import torch
import torchvision
sys.path.insert(0, "../")
import stylegan2
from stylegan2 import utils
from pspencoder import CreateEncoder
import torch.nn.functional as F
#torch.set_grad_enabled(False)
def encode_images(device, G, encoder, dlate... |
class GenerateRawInfo:
def __init__(self, conf_interface,
md_interface,
algorithms_interface):
self.__md_interface = md_interface
self.__conf_interface = conf_interface
self.__algorithms_interface =algorithms_interface
def d... |
# @Author: Your name
# @Date: 2021-03-24 07:01:27
# @Last Modified by: Abdellah Oulahyane
# @Last Modified time: 2021-03-28 16:43:14
from Model.sys.Model import Model
class Book(Model):
def __init__(self=None,
id=None,
title=None,
author=None,
... |
from functools import wraps
from threading import Thread, Lock
import os
import sys
import time
from pprint import pprint
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from lock import a, b
counter = 0
def synchronized(lock):
""" Synchronization decorator. """
def real_wrapper(function):
... |
import pickle
import re
import random
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import community
from typing import List
from data import Graph_load, Graph_load_batch
def citeseer_ego():
_, _, G = Graph_load(dataset="citeseer")
G = max(nx.connected_component_subgraphs(G), key=... |
import logging
from collections import defaultdict
from typing import Dict, List
from Util import AICommand, Position, Path
from ai.Algorithm.path_partitionner import PathPartitionner, Obstacle
from ai.GameDomainObjects import Player
from ai.states.game_state import GameState
MIN_DISTANCE_FROM_OBSTACLE = 200
class... |
#!/usr/bin/env python3
"""
MongoDB Setup
This file takes as input a YAML configuration of the AWS instances and
MongoDB cluster topology and brings up a cluster on the remote machines.
"""
import sys
from functools import partial
import logging
import argparse
import common.atlas_setup as atlas_setup
from common.del... |
#Created by Timothy Chua
#Implementation of Breadth First Search in Python
#References:
# - https://csacademy.com/app/graph_editor/
# - https://www.tutorialspoint.com/data_structures_algorithms/graph_data_structure.htm
def BFS(graph, point, explored, to_explore):
if(len(graph) == len(explored)): #If we have expl... |
# Graphing the equation 4x + 5y = N where it becomes y = (N-4x)/5
# if x as a whole number has y as a whole number then counter++
def find_4s_and_5s(N):
counter = 0
x = 0
while (N-4*x)/5 >= 0:
if (N-4*x) % 5 == 0:
counter+=1
x += 1
return counter
N = int(input())
print(find_4s_and_5s(N))
|
# SPDX-FileCopyrightText: 2019 Scott Shawcroft for Adafruit Industries
# SPDX-FileCopyrightText: 2019 Melissa LeBlanc-Williams for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
`adafruit_st7735`
====================================================
Displayio driver for ST7735 based displays.
* Author(s): M... |
import unittest
from the_fastest_horse import fastest_horse
class Tests(unittest.TestCase):
TESTS = {
"Basics": [
{
"input": [
['1:13', '1:26', '1:11'],
['1:10', '1:18', '1:14'],
['1:20', '1:23', '1:15'],
... |
# Code on Sobol sequences generation adapted from SALib: https://github.com/SALib/
# The MIT License (MIT)
# Copyright (c) 2013-2017 Jon Herman, Will Usher, and others.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software")... |
import random
import subprocess
def genWrite(sectorSize, sectorCount, startOffset, writeSizeMin, writeSizeMax):
''' Generate the parameters used in dd to create a random write of specified size.
The writeSizeMin and writeSizeMax should be of type int, and together they form
the range used to determien the ... |
import os
import sounddevice as sd
import pylab as pl
import spectrogram as s
duration = 1
fs = 44100
saveupload = False
arrs = []
print('Recording, Ctrl+C to stop...')
stop = False
while not stop:
try:
tmp = sd.rec(int(duration * fs), samplerate=fs, channels=2, blocking=True)
arrs.append(tmp)
... |
#!/usr/bin/env python
#
# Copyright 2016 MIT Lincoln Laboratory, Massachusetts Institute of Technology
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use these files except in compliance with
# the License.
#
# You may obtain a copy of the License at
#
# http://www.apache.org/lice... |
from execution_of_scrap import *
import pandas as pd
import numpy as np
df = pd.DataFrame(list_object)
df.id = pd.to_numeric(df.id, errors='coerce').fillna(0).astype(np.int64)
df = df.fillna('Not Find')
#retrer des données non pertirnante en g
del df[df.columns[-1]]
del df['is_manufacturable']
del df['manufacturable... |
from __future__ import annotations
import random
import re
from bot.config import Config
from bot.data import format_msg
from bot.data import handle_message
from bot.message import Message
@handle_message(r'.*\bth[oi]nk(?:ing)?\b', flags=re.IGNORECASE)
async def msg_think(config: Config, msg: Message) -> str | None... |
'''
Dear nT analyser,
if you want to complain please contact: chiara@physik.uzh.ch, gvolta@physik.uzh.ch, kazama@isee.nagoya-u.ac.jp
'''
import datetime
import strax
import numba
import numpy as np
# This makes sure shorthands for only the necessary functions
# are made available under straxen.[...]
export, __all__ =... |
# -*- coding: utf-8 -*-
import os
from prometheus_client import (
multiprocess,
CollectorRegistry,
REGISTRY,
make_wsgi_app,
)
__all__ = ["get_method_name", "get_registry", "create_wsgi_app"]
def get_method_name(request):
m = request.method
if m not in ('GET', 'HEAD', 'POST', 'PUT', 'DELETE',... |
#!/usr/bin/python3
class Const(object):
SETTING_FILE_PATH = './config.json'
PUBLIC_DIR = 'public'
PRIVATE_DIR = 'private'
RAW_VIEW_DIR = '/'.join([PRIVATE_DIR, 'views', 'raw'])
TEMPLATE_VIEW_DIR = '/'.join([PRIVATE_DIR, 'views', 'template'])
COOKIE_SESSION_ID = 'session_id'
AUTHENTICATION_... |
import psi4
import pdft
import matplotlib.pyplot as plt
import libcubeprop
import numpy as np
bondlength = 1.426
Full_Molec = psi4.geometry( """
nocom
noreorient
0 3
H %f 0.0 0.00
@H 0 0.7 0
@H 0 -0.7 0
H -%f 0.0 0.00
units bohr
symmetry c1
""" % (bondlength / 2, bondlength / 2))
Monomer_1 = psi4.geometry("""
no... |
from file1 import function_1
from file2 import function_2
function_1()
function_2() |
#!/usr/bin/env python
import os
import sys
sys.path.insert(0, os.pardir)
from testing_harness import TestHarness, PyAPITestHarness
import openmc
class ScoreNuScatterNTestHarness(PyAPITestHarness):
def _build_inputs(self):
filt = openmc.Filter(type='cell', bins=(21, 22, 23))
t = openmc.Tally(tally... |
from anlffr.helper import biosemi2mne as bs
import mne
import numpy as np
import os
import fnmatch
import pylab as pl
# Adding Files and locations
froot = '/Users/Hari/Documents/Data/ABRmoduleBiosemi/'
subjlist = ['I13']
for subj in subjlist:
fpath = froot + subj + '/'
# These are so that the generated fil... |
import random
random.seed(a=2021)
import lime
import pandas as pd
import numpy as np
np.random.seed(seed=2021)
from lime import lime_text
from lime.lime_text import LimeTextExplainer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Model, Input
from keras.layers import GRU, LSTM, Embeddin... |
from torchelie.callbacks.callbacks import *
|
from flask import Flask, jsonify, request, abort, Response
from .util import *
app = Flask(__name__)
app.proc = None
@app.route('/', methods=['GET'])
def ping():
"""
Returns when the server is ready.
"""
return '{} is alive'.format(app.proc.name)
@app.route('/find/<int:key>', methods=['GET'])
def fi... |
import pytest
from brownie import reverts, Contract, PriceFeedProxy, ZERO_ADDRESS
@pytest.fixture(scope='module')
def admin(accounts):
return accounts[7]
@pytest.fixture(scope='function')
def price_feed(deploy_price_feed, deployer, admin):
return deploy_price_feed(max_safe_price_difference=500, deployer=dep... |
"""
ScanNet
"""
from scan_lib import scan_data as sd
from PIL import Image
import cv2
import imutils
from imutils.perspective import four_point_transform
from skimage.filters import threshold_local
import numpy as np
# param file_path: str
# param to_gray_scale: bool
# return: numpy array
def find_im_in_docs(file_pa... |
import argparse
import torch
import os
from deep_rl import random_seed, set_one_thread, select_device, Config, generate_tag, Task, TDAuxNet, NatureConvBody, \
LinearSchedule, AsyncReplay, ImageNormalizer, SignNormalizer, run_steps, mkdir
from deep_rl.agent.TDAux_agent import TDAuxAgent
def td_aux_many(config: C... |
from typing import List
import pytorch_lightning as pl
import torch
import torch.optim
from src.models.BaseAutoEncoder import BaseAutoEncoder
class LitBaseAutoEncoder(pl.LightningModule):
def __init__(
self,
n_layers: int = 3,
features_list: List[int] = [16, 8, 4, 2],
activation_... |
import pandas
import os
import logging
from src.simulator.simulator import Simulator
from src.utils.utils import lookup_pandas_dataframe
import src.benchmarks.benchmarks as benchmarks
from nn_dataflow import ConvLayer
class SimulatorSweep(object):
def __init__(self, csv_filename, config_file='conf.ini', verbose=F... |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 26 20:52:45 2020
@author: mavch
"""
def generateLayout():
for i in range(16):
r = i//4
c = i%4
msg = '<cell name="{:}"><x_val>{:}</x_val><y_val>{:}</y_val></cell>'
print(msg.format(i, 20+20*r, 5+20*c))
print(msg.format("update", 20... |
import os
import csv
import shbus.realtime
import shbus.lineinfo
def readTableFromDir(path, postfix=".csv"):
data = dict()
if os.path.isdir(path):
files = os.listdir(path)
for file in files:
if not os.path.isdir(file):
if os.path.splitext(file)[1] == postfix:
with open(os.path.join(path,file),'r') as... |
import pickle
import random
from lhotse import CutSet
from lhotse.serialization import LazyIteratorMultiplexer
from lhotse.testing.dummies import DummyManifest
def test_multiplexer():
mux = LazyIteratorMultiplexer(range(10), range(900, 903), seed=0) # len 10 # len 3
assert sorted(list(mux)) == [0, 1, 2, 3... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2014 Ciro Mattia Gonano <ciromattia@gmail.com>
# Copyright (c) 2013-2019 Pawel Jastrzebski <pawelj@iosphe.re>
#
# 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 n... |
#!/usr/bin/env python
import sys, time, operator, datetime
""""
$ pip2 install pytz tzlocal
"""
try:
import pytz
timezones = pytz.all_timezones
except:
print("ERROR: `pytz` package not exists!")
sys.exit(0)
try:
import tzlocal
default_timezone = tzlocal.get_localzone().zone
except:
p... |
from __future__ import annotations
from typing import TYPE_CHECKING
from typing import cast
import matplotlib.pyplot as plt
from glotaran.io.prepare_dataset import add_svd_to_dataset
from matplotlib.axis import Axis
from pyglotaran_extras.io.load_data import load_data
from pyglotaran_extras.plotting.plot_svd import ... |
# Python 2/3 compatibility
from __future__ import print_function
import sys
import os
import random
import math
# import cv2
import numpy as np
import matplotlib.pyplot as plt
import skimage.io as skio
from skimage import feature
from skimage.color import rgb2gray
from sklearn.decomposition import PCA
from sklearn.... |
# Copyright (c) 2018, The Regents of the University of California
# 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 copyright
# notice, thi... |
# -*- coding: utf-8 -*-
# @Time : 2019/9/16 09:50
# @Author : Azrael.Bai
# @File : excute_bash.py
# coding:utf-8
import subprocess
import sys
import time
import os
import io
def read(filename):
fh = io.open(filename, 'r', encoding='utf-8')
lines = fh.readlines()
fh.close()
return lines
lines =... |
from projectreport.finder.base import Finder
class PythonPackageFinder(Finder):
"""
Finder which automatically looks for projects with Python packages.
"""
def __init__(self, recursive: bool = True):
super().__init__(recursive=recursive, required_files=("__init__.py",))
|
import sys
def clasifyThalasemia(inputFile , knowledgeFile , outputFile):
phenotypeDB = {}
firstLine_Flag = True
result = []
# Read knowledge File and create knowledge Dictionary
with open(knowledgeFile) as knowledge:
for line in knowledge:
info = line.split()
HbVar... |
import errno
import logging
import xml.etree.ElementTree
from collections import namedtuple
import galaxy.auth.providers
from galaxy.exceptions import Conflict
from galaxy.security.validate_user_input import validate_publicname
from galaxy.util import plugin_config, string_as_bool
log = logging.getLogger(__name__)
... |
# -*- coding: utf-8 -*-
__author__ = 'Eric Z. Eisberg'
__copyright__ = 'Copyright 2018 Eric Z. Eisberg'
__license__ = 'Licensed under MIT license'
import json
import os
import requests
SLACK_KEY = os.environ.get('SLACK_KEY') or None
SLACK_URL = 'https://slack.com/api/chat.postMessage'
def send_to_slack(email, blurb... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class ConvS2S(nn.Module):
def __init__(self, n_src_words, n_tgt_words, src_pdx=-1, tgt_pdx=-1,
d_model=512, n_head=8, n_layers=6, p_drop=0.1,
max_seq_len=512) -> None:
super().__init__()
self.d_mod... |
from aether.ontology.politics.state import PoliticalState
class UnitedEmpireOfEarth(PoliticalState):
def __init__(self):
super().__init__("United Empire of Earth")
self.abbreviation = "UEE"
|
import json
import uuid
import os
import thread
import random
from os import listdir
from os.path import isfile, join
import pyrebase
import RPi.GPIO as GPIO #Import GPIO library
import time #Import time library
GPIO.setmode(GPIO.BCM)
SUCCESS_LED = 25
GPIO.setup(SUCCESS_LED,GPIO.OUT)
... |
from keras.layers import Dense, Conv2D, MaxPool2D, Flatten
from keras.models import Sequential
from keras import layers
from keras import callbacks
from tensorflow.examples.tutorials.mnist import input_data
from kerassurgeon import identify
from kerassurgeon.operations import delete_channels
def main():
training... |
import numpy as np
def xgcd(vals):
_xgcd = Xgcd(vals)
return _xgcd.run()
class Xgcd(object):
def __init__(self, vals):
self._vals = np.array(vals, dtype='intc')
def run(self):
r0, r1 = self._vals
s0 = 1
s1 = 0
t0 = 0
t1 = 1
for i in range(1000... |
import os, numpy
from dolfin import FunctionSpace, parameters, compile_extension_module
from dolfin.cpp.io import File
from dolfin.cpp.common import Timer, Parameters, IntArray, DoubleArray, MPI
from dolfin.cpp.mesh import Mesh, CellFunction, MeshFunction
from common import pid, comm, print0
# TODO: Add capability of... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import requests
from mock import patch, Mock
from pygithub3.tests.utils.core import TestCase
from pygithub3.resources.base import json
from pygithub3.services.gists import Gist, Comments
from pygithub3.tests.utils.base import (mock_response, mock_response_result,
... |
import logging
from django.utils.six import StringIO
from django.test import TestCase, override_settings
from students.models import Student, Group
from students import signals
@override_settings(LANGUAGE_CODE='en')
class StudentSignalsTests(TestCase):
def test_log_student_updated_added_event(self):
"""C... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.