text stringlengths 957 885k |
|---|
"""
Code derived and rehashed from: https://www.github.com/kyubyong/transformer
"""
from __future__ import print_function
import numpy as np
import codecs
import regex
import random
import torch
def load_de_vocab(min_cnt):
vocab = [line.split()[0] for line in codecs.open('preprocessed/de.vocab.tsv', 'r', 'utf-8'... |
<gh_stars>1-10
"""
Linkedlist
:file: server.py
:author: <NAME>
:date: March, 2016
:description:
The implementation of our server which runs as a python script,
using the schema.sql file in this directory to initialize the db
"""
from contextlib import closing
import sqlite3
from flask import Flask, Respons... |
import numpy as np
from sklearn.datasets import make_blobs, make_moons
from sklearn.cluster import KMeans
import mglearn
import matplotlib.pyplot as plt
# 生成模拟的二维数据
X, y = make_blobs(random_state=1)
# 构建聚类模型
kmeans = KMeans(n_clusters=3)
kmeans.fit(X)
plt.figure(figsize=(11, 4.5))
plt.subplots_adjust(left=0.32, righ... |
"""Adapted from:
Licensed under The MIT License [see LICENSE for details]
"""
from __future__ import print_function
import argparse
import os, os.path as osp
import time
import numpy as np
import cv2
import torch
from torch.autograd import Variable
from lib.utils.config import cfg, merge_cfg_from_file
from lib.d... |
<reponame>milescsmith/cDNA_Cupcake<gh_stars>0
#!/usr/bin/env python
import re
import sys
from collections import defaultdict
from csv import DictReader, DictWriter
from pathlib import Path
from typing import Optional, Tuple
import typer
from Bio import SeqIO
from cupcake import version_callback
from cupcake import c... |
# coding: utf-8
import random
def partition(lst, start, end):
"""
move elements below pivot value to left half of list and bigger to right half
return the new position of the pivot element
"""
# use pivot as the last element in list
# get it value
x = lst[end]
# initial store_index
... |
<reponame>xgess/btctxstore
# coding: utf-8
# Copyright (c) 2015 <NAME> <<EMAIL>>
# License: MIT (see LICENSE file)
from __future__ import print_function
from __future__ import unicode_literals
import binascii
from btctxstore import serialize
from btctxstore import deserialize
from btctxstore import control
from btc... |
# Copyright 2017 Google 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
<filename>average/gather_data.py<gh_stars>0
"""
Arthur: <NAME>
Purpose: This module is used for gathering data. That is 30 data plots to be later used for
boxplots.
Date: 29/03/21
"""
import default
TITLE_LR = "Learning Rate"
TITLE_BATCH_SIZE = "Batch Size"
TITLE_NUM_EPOCHES = "Number Of Ep... |
import datetime
import pytest
import numpy as np
from htcanalyze.htcanalyze import HTCAnalyze, gen_time_dict, sort_dict_by_col
def test_gen_time_dict():
strp_format = "%Y-%m-%dT%H:%M:%S"
strf_format = "%m/%d %H:%M:%S"
today = datetime.datetime.now()
today = today.replace(microsecond=0)
submissi... |
#!/usr/bin/env python3
import logging
import os
import sys
import time
import faust
from cassandra.auth import PlainTextAuthProvider
from cassandra.cluster import Cluster
from paho.mqtt import client as mqtt_client
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=logging.WARN)
mqtt_broke... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" jsontool - Perform some actions with json using CLI
http://msztolcman.github.io/jsontool
Author: <NAME> (<EMAIL>)
Get help with: jsontool --help
Information about version: jsontool --version
"""
from __future__ import print_function, unicode_literals
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from . import read_input as rin
def out_rslt(rslt_data):
# ---------- asc in Struc_ID or Gen
with open('./data/cryspy_rslt', 'w') as frslt:
if rin.algo == 'RS' or rin.algo == 'LAQA':
frslt.write(rslt_data.sort_values(by=['Struc_ID'], ascending... |
<filename>polls/tests.py
import datetime
from django.test import TestCase
from django.utils import timezone
from django.core.urlresolvers import reverse
from .models import Question
# Create your tests here.
class QuestionMethodTests(TestCase):
"""
was_published_recently should return false for questions w... |
import requests
from requests.auth import AuthBase
RED_COLOR = "\033[91m"
GREEN_COLOR = "\033[92m"
WARN_BG_COLOR = "\033[43m"
WARN_COLOR = "\033[93m"
BLUE_COLOR = "\033[94m"
ENDTERM = "\033[0m"
class TokenAuth(AuthBase):
"""Implements a custom authentication scheme."""
def __init__(self, token):
sel... |
<filename>ScrappingTool/utils/get_etym.py<gh_stars>1-10
'''
Date: 2021-02-20 22:05:36
LastEditors: Jecosine
LastEditTime: 2021-02-21 15:38:24
'''
from bs4 import BeautifulSoup as bs
import requests
import sqlite3
import time
import random
import re
import sys
requests.adapters.DEFAULT_RETRIES = 5
session = requests.ses... |
<gh_stars>0
# md5 : a0cd017919ae710459270dbdf15d2ab5
# sha1 : c1d7117f1fe991fc7e5d17ce0a437bbd1c32aa11
# sha256 : 9d18d8a88a7b5dfdd44e5e371e96a3fac90df9a901aa22ddf55d6774a9a3b811
ord_names = {
109: b'FileBearsMarkOfTheWeb',
110: b'GetPortFromUrlScheme',
118: b'GetPropertyFromName',
119: b'GetPropertyNa... |
<filename>BackBones/utils.py<gh_stars>0
import torch
from torch import nn
from torch.nn.init import kaiming_normal_
import os
import json
from termcolor import colored
from datetime import datetime as dt
def init_weights(model):
for layer in model.features:
if type(layer) in [nn.Conv2d, nn.Linear]:
kaiming_norma... |
<filename>infra/tools/dockerbuild/source.py
# 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.
"""Manages the raw sources needed to build wheels.
A source has a remote (public) address. That file is then dow... |
import torch
from torch import nn
from core.config import config
import models.frame_modules as frame_modules
import models.prop_modules as prop_modules
import models.map_modules as map_modules
import models.fusion_modules as fusion_modules
import models.textual_modules as textual_modules
class CDN(nn.Module):
def... |
import cv2
from PIL import Image
import numpy as np
from osr2mp4.ImageProcess.Curves.curves import getclass
from osr2mp4.ImageProcess import imageproc
from itertools import chain
def convertlist(longlist):
tmp = list(chain.from_iterable(longlist))
return np.array(tmp, dtype=np.int32).reshape((len(longlist), len(lon... |
from random import randint, random
# Implement a 2D Lattice with a hexagonal unit cell
class Lattice:
def __init__(self, _size, _prob_boundaries, _prob_reaction):
# size = (N,M)
self.size = _size
# A[i] = [(i,j),id]
self.color_A = []
self.color_B = []
self.reacti... |
from django.core.exceptions import ValidationError
from django.db.models import Case, When
from django_directed.models.abstract_base_graph_models import base_edge, base_graph, base_node
def cyclic_graph_factory(config):
"""
Type: Subclassed Abstract Model
Abstract methods of the Graph base model are impl... |
import random
#import tools
from deap import tools
def varAnd(population, toolbox, cxpb, mutpb):
"""Part of an evolutionary algorithm applying only the variation part
(crossover **and** mutation). The modified individuals have their
fitness invalidated. The individuals are cloned so returned population... |
'''Some utilities to manipulate strings.'''
import re
__all__ = ['straighten', 'text_filename']
def straighten(s, length, align_left=True, delimiter=' '):
'''Straighten a Unicode string to have a fixed length.
Parameters
----------
s : str
string to be trimmed
length : int
numbe... |
import ast
import builtins
import cinder
from compiler.readonly import (
readonly_compile,
ReadonlyCodeGenerator,
ReadonlyTypeBinder,
)
from compiler.static import StaticCodeGenerator
from contextlib import contextmanager
from typing import Any, List, NewType, Optional, Tuple
from ..test_static.common impo... |
<reponame>MarquesThiago/sumarize-text<gh_stars>0
import re
import string
import nltk
import pandas as pd
import numpy as np
from common import (simple_clear, stop_word, wiegth_sentency, normalize_text, init)
def check_index(phrase, word):
'''
check index in phrase and return or index of words in a list
... |
<reponame>dangerousbeak/tpc
from game import Zone, State, Exit
from random import randrange
from buttons import Button
ATTRACT ="ATTRACT"
PRESTAGE = "PRESTAGE"
WAITING_FOR_STAGE = "WAITING_FOR_STAGE"
STAGE = "STAGE"
BLINK = "BLINK"
FAULT = "FAULT"
GO = "GO"
RUNNING = "RUNNING"
WAITING_TO_CROSS = "WAITING TO CROSS"
GA... |
<filename>pisti.py
import random
def desteYap():
renkL = ["♥️","♦️","♣️","♠️"]
renk = [i for i in range(2,11)]
renk.insert(0, "A")
renk.append("J")
renk.append("Q")
renk.append("K")
deste = []
for i in renkL:
for j in renk:
deste.append(str(j)+i)
random.shuffle(deste) #K... |
"""
Command-line interface for interacting with Luigi scheduler.
"""
import json
import requests
import datetime
import click
from fnmatch import fnmatch
import sys
from os.path import join
from collections import Counter
from babel.numbers import format_number
class TooManyTasksError(Exception):
def __init__(sel... |
from skillmap.main import generate
from skillmap.nodes.common import SECTION_SEPARATOR
from skillmap.nodes.skillmap_node import create_skillmap_graph
from skillmap.nodes.group_node import create_group_subgraph
from skillmap.nodes.skill_node import create_skill_node
def test_generate():
skillmap_file = "tests/url_... |
# Aliases for commands. The keys of the given dictionary are the
# aliases, while the values are the commands they map to.
# Type: Dict
c.aliases = {'w': 'session-save', 'wq': 'quit --save', 'mpv': 'spawn -d mpv --force-window=immediate {url}', 'nicehash': 'spawn --userscript nicehash', 'pass': 'spawn -d pass -c'}
# R... |
<reponame>jadecastro/imitation
"""Configuration settings for train_rl, training a policy with RL."""
import sacred
import highway_env
from imitation.scripts.common import common, rl, train
train_rl_ex = sacred.Experiment(
"train_rl",
ingredients=[common.common_ingredient, train.train_ingredient, rl.rl_ingred... |
<reponame>xmings/IdeaNote
#!/bin/python
# -*- coding: utf-8 -*-
# @File : service.py
# @Author: wangms
# @Date : 2019/8/3
import zlib, requests
from core.model import Catalog, Image, db
from datetime import datetime
from app import app
from flask import session
from sqlalchemy.sql import functions
from common import ... |
from plotly.basedatatypes import BaseTraceType
import copy
class Scatterternary(BaseTraceType):
# a
# -
@property
def a(self):
"""
Sets the quantity of component `a` in each data point. If `a`,
`b`, and `c` are all provided, they need not be normalized,
only the relati... |
<filename>3D_CNN/MiniBatchGenerator.py
import numpy as np
import matplotlib.pyplot as plt
from random import randint
from DataAugmentation import DataAugmentation
class MiniBatchGenerator:
# Create minibatches of a given size from a dataset.
# Preserves the original sample order unless shuffle() is used.
nSeq = 0;
... |
"""Examples for spanned() decorator with peer-to-peer based tracing."""
import logging
import os
import random
import sys
import time
import coloredlogs # type: ignore[import]
import pika # type: ignore[import]
if "examples" not in os.listdir():
raise RuntimeError("Script needs to be ran from root of reposito... |
from pyowm import OWM
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5 import QtCore, QtGui, QtWidgets
from datetime import datetime
import threading
import openpyxl
import random
import webbrowser
API_key = "<KEY>" #openweathermap API
owm = OWM(API_key)
datetime.today() ... |
<gh_stars>1-10
#coding=utf-8
import base64
import utils
import json
import hashlib
import urllib, urllib2
import re
import os
import tempfile
import random
import xml.dom.minidom as minidom
from cookielib import MozillaCookieJar
import requests
from bs4 import BeautifulSoup
from bilibili_config import *
class Bilibil... |
<filename>network/ds_transforms.py
import torch
import numpy as np
import torch.nn.functional as F
class ToTensor(object):
def __init__(self, hdf5=False):
self.hdf5 = hdf5
def __call__(self, sample):
if self.hdf5:
return torch.from_numpy(sample['image'][()]), torch.from_numpy(samp... |
import sid
# import ssim
import msssim
import dataloader
import paddle
import paddle.nn as nn
import os
train_path = 'data/train/moire_train_dataset'
# print(train_path)
train_data = dataloader.TrainData(train_path, patch_size=512, file_type='*', hr_dir='gts', lr_dir='images', scale = 1, start=100, end=999999)
train_... |
<gh_stars>1-10
from tool.runners.python import SubmissionPy
def parse(s):
depth = 0
res = [] # List of []
for char in s:
if char == "[":
depth += 1
continue
if char == "]":
depth -= 1
continue
if char == ",":
continue
... |
<gh_stars>10-100
import os
import numpy as np
import sys
import json
import pickle
sys.path.append('./')
import matplotlib
from .ResultMerge_multi_process import mergebypoly_multiprocess
from .dota_evaluation_task1 import do_eval
matplotlib.use('Agg')
wordname_15 = ['plane', 'baseball-diamond', 'bridge', 'ground-track-... |
# Copyright (c) 2020, Huawei Technologies.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 License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable la... |
<reponame>redart-2021-final/backend
#!/bin/env python3
import asyncio
import datetime
import httpx
import pandas as pd
from redis import Redis
from rq import Queue
from rq_scheduler import Scheduler
from scipy.stats import mstats
from tortoise import Tortoise
import config
from models import Event
redis = Redis.fro... |
#!/usr/bin/env python3
# encoding: utf-8
from typing import Dict
import numpy as np
from rls.algorithms.base.marl_policy import MarlPolicy
from rls.common.data import Data
from rls.common.decorator import iton
from rls.common.when import Every
from rls.common.yaml_ops import load_config
from rls.utils.np_utils impor... |
<filename>Ramen Warrior Game/main.py
# importing modules
import pygame
import random
import math
from pygame import mixer
# initializing it
pygame.init()
# starting the display
start = pygame.display.set_mode((600, 600))
# background sound
mixer.music.load('background.wav')
mixer.music.play(-1)
# background
bg =... |
from PySide6.QtGui import *
from PySide6.QtCore import *
from PySide6.QtWidgets import *
from config import *
__all__ = ['PreferenceDialog']
class PrimerTagLabel(QLabel):
base_url = "https://primer3.org/manual.html#{}"
def __init__(self, name, tag, parent=None):
super().__init__(parent)
self.tag = tag
self.... |
import os
import datetime
from pyspark import SparkContext
from pyspark.conf import SparkConf
from pyspark.sql import SparkSession, Row, DataFrame, Column
from pyspark.sql import functions as F
from pyspark.ml import Pipeline
from pyspark.ml.evaluation import RegressionEvaluator
from pyspark.ml.recommendation import AL... |
<reponame>easyopsapis/easyops-api-python
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: delete_container.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.protobuf i... |
<gh_stars>1-10
import unittest
from datetime import date, datetime
from pypika import Criterion, EmptyCriterion, Field, Table
from pypika import functions as fn
from pypika.queries import QueryBuilder
from pypika.terms import Mod
__author__ = "<NAME>"
__email__ = "<EMAIL>"
class CriterionTests(unittest.TestCase):
... |
from django.db import models
from django.contrib.auth.models import AbstractUser
class Menu(models.Model):
"""
菜单
"""
name = models.CharField(max_length=30, unique=True, verbose_name="菜单名")
icon = models.CharField(max_length=50, null=True, blank=True, verbose_name="图标")
path = models.CharField(... |
<gh_stars>0
from testqtgui._common import *
if has_qt4:
import srllib.qtgui.util
from srllib.qtgui import models
@only_qt4
class UndoItemModelTest(QtTestCase):
def test_construct(self):
model = self.__construct()
self.assertIs(model.undo_stack, self.__undo_stack)
def test_construct_wi... |
# -*- coding:utf-8 -*-
import time
import tornado.escape
from torcms.core import tools
from torcms.model.wiki_model import MWiki
class TestMWiki():
def setup(self):
print('setup 方法执行于本类中每条用例之前')
self.uu = MWiki()
self.title = 'tyyyitle'
self.uid = '6985'
def add_page(self, *... |
<reponame>cnstark/awesome_gpu_scheduler<filename>notification/email_notification.py
import traceback
from django.core.mail import send_mail
from gpu_tasker.settings import EMAIL_NOTIFICATION
TASK_START_NOTIFICATION_TITLE = '任务开始运行'
TASK_START_NOTIFICATION_TEMPLATE = \
'''任务[{}]开始运行
任务运行详情:
任务名称:{}
工作目录:{}
命令:
-----... |
# Copyright (C) 2021 <NAME>
#
# SPDX-License-Identifier: MIT
import warnings
import gmsh
from mpi4py import MPI
warnings.filterwarnings("ignore")
__all__ = ["create_disk_mesh", "create_sphere_mesh"]
def create_disk_mesh(LcMin=0.005, LcMax=0.015, filename="disk.msh"):
"""
Create a disk mesh centered at ... |
<filename>cbinterface/psc/sessions.py
"""All things LR sessions."""
import io
import os
import time
import logging
import threading
from cbapi.psc import Device
from cbapi.psc.threathunter import CbThreatHunterAPI
from cbapi.psc.cblr import (
LiveResponseSession,
LiveResponseSessionManager,
LiveResponseJo... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 7 20:15:19 2021
@author: Christian
"""
import hysteresis as hys
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.widgets import Button
# from matplotlib.animation import FuncAnimation
import numpy as np
# Add this function to s... |
#
# Copyright (c) 2015-2020 <NAME> <tflorac AT ulthar.net>
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE... |
# coding: utf-8
"""
ThingsBoard REST API
ThingsBoard open-source IoT platform REST API documentation. # noqa: E501
OpenAPI spec version: 3.3.3-SNAPSHOT
Contact: <EMAIL>
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from ... |
import argparse
import csv
import json
import logging
import sys
import os
import urllib2
import unix_converter as unix
__author__ = '<NAME> & <NAME>'
__date__ = '20150920'
__version__ = 0.03
__description__ = 'This scripts downloads address transactions using blockchain.info public APIs'
def main(address, output_di... |
#!/usr/bin/python3.6
# SQLlite3 : https://docs.python.org/3/library/sqlite3.html
import sqlite3
import re
import pandas as pd
# Files
database = "../database/test.db"
# connection to database
databaseConnection = sqlite3.connect(database)
dbSql = databaseConnection.cursor();
# SELECT titles from movies
# movie... |
#!/usr/bin/env python
# Copyright 2011 Google 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... |
from sqlalchemy.orm.dynamic import AppenderMixin
from typing import Union
class Field(object):
"""
Configure a ModelSerializer field
"""
def __init__(self, dump_only=False, load_only=False, serializer=None):
self.dump_only = dump_only
self.load_only = load_only
self._serialize... |
from cardboard import types
from cardboard.ability import (
AbilityNotImplemented, spell, activated, triggered, static
)
from cardboard.cards import card, common, keywords, match
@card("Lifespinner")
def lifespinner(card, abilities):
def lifespinner():
return AbilityNotImplemented
return lifespi... |
"""Module for dealing with the toolbar.
"""
import math
import os
import ipyevents
import ipyleaflet
import ipywidgets as widgets
from ipyfilechooser import FileChooser
from .common import *
from .pc import *
def tool_template(m=None):
"""Generates a tool GUI template using ipywidgets. Icons can be found at https... |
<reponame>niyoushanajmaei/gpt-neo
import numpy as np
import tensorflow.compat.v1 as tf
from functools import partial
from data.encoders import encode
import random
import re
import logging
from itertools import cycle
from utils import natural_sort
### IN USE ###
def _get_number_of_documents(filename):
# extracts... |
<filename>atomic/bin/batch.py<gh_stars>0
import csv
from multiprocessing import Pool
import os
import subprocess
from atomic.parsing.replayer import filename_to_condition
home = '/home/david/working/atomic'
multi = True
profile = False
analyze = False
def run_inference(args):
fname, sub_args = args
root, log_name... |
#!/usr/bin/python
#
# aws.py
#
# Spin up Ceph cluster in AWS.
#
# Cluster is defined in the aws.yaml file.
#
# Generate pseudo-code from #PC comments:
# $ grep -E '^ *#PC' aws.py | sed -e 's/#PC //'g
#
import argparse
from aws_lib import SpinupError
import init_lib
from pprint import pprint
import sys
import yaml... |
# Copyright 2018 Google 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 to in writing,... |
<filename>app/customer/models/first_charge_activity.py<gh_stars>1-10
# coding=utf-8
import datetime
import logging
from base.settings import CHATPAMONGO
from django.conf import settings
from mongoengine import *
from app.customer.models.user import *
from app.customer.models.tools import *
from app.customer.models.vi... |
#!/usr/bin/python
# Copyright (c) 2012 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.
"""Checks third-party licenses for the purposes of the Android WebView build.
The Android tree includes a snapshot of Chromium in orde... |
"""YIN output plugin"""
import optparse
import re
from xml.sax.saxutils import escape
from xml.sax.saxutils import quoteattr
from .. import grammar
from .. import plugin
from .. import statements
from .. import syntax
from .. import util
yin_namespace = "urn:ietf:params:xml:ns:yang:yin:1"
def pyang_plugin_init():
... |
#!/home/francisco/Projects/Pycharm/py-binary-trees-draw/venv/bin/python
# -*- coding: utf-8 -*-
from node import Node
class AVLTree:
def __init__(self):
self.root = None
self.leaf = Node(None)
self.leaf.height = -1
self.nodes_dict_aux = {}
self.nodes_dict = {}
def ins... |
from chainer.links import BatchNormalization, GroupNormalization
from chainermn.links import MultiNodeBatchNormalization
from chainer.functions import softmax_cross_entropy
from chainer.optimizers import Adam
from chainer.iterators import MultiprocessIterator, SerialIterator
from chainer.optimizer import WeightDecay
fr... |
<filename>tiwen.py
import requests, json, base64, hashlib
import jstyleson
import re
import os
import sys
import time
from typing import *
FieldVal = NewType('FieldVal', Any)
FieldCode = NewType('FieldCode', str)
Field = Union[Tuple[FieldVal, FieldCode], FieldVal]
FieldKv = Tuple[str, Field]
templateItem = Tuple[str, ... |
<filename>vindauga/widgets/color_selector.py
# -*- coding: utf-8 -*-
import logging
from vindauga.constants.colors import cmColorForegroundChanged, cmColorBackgroundChanged, cmColorSet
from vindauga.constants.event_codes import evBroadcast, evMouseDown, evKeyDown, evMouseMove
from vindauga.constants.keys import kbLeft... |
import numpy as np
import MulensModel as mm
def test_magnification_type():
"""
Check type of magnification returned for model with t_eff.
At some point it was astropy quantity.
"""
parameters = mm.ModelParameters({'t_0': 1., 't_eff': 0.2, 't_E': 3.})
magnification_curve = mm.MagnificationCurv... |
<reponame>AIshutin/arthistorian<gh_stars>1-10
import requests
import csv
import argparse
from tqdm import tqdm
import hashlib
from urllib import parse as urlparse
import urllib
import os
from PIL import Image
import aiohttp
import asyncio
from contextlib import closing
parser = argparse.ArgumentParser(description='Dow... |
#! /usr/bin/env python
"""
Use the pre-trained Haar classifier from OpenCV to detect cat faces
"""
import cv2
import dlib
import numpy as np
from constants.constants import debug_cat_frontal_face_detection
# pre-trained classifier from OpenCV
HAAR_CLASSIFIER = 'data/haarcascade_frontalcatface.xml'
DETECTOR = 'data/c... |
# Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at
# the Lawrence Livermore National Laboratory.
# LLNL-CODE-743438
# All rights reserved.
# This file is part of MGmol. For details, see https://github.com/llnl/mgmol.
# Please also read this link https://github.com/llnl/mgmol/LICENSE
#
# Python... |
folders = ['1-EastRiver', '2-DryCreek','3-SagehenCreek','4-AndrewsForest','5-Baltimore',
'6-BonanzaCreek','7-CaliforniaCurrentEcosystem','8-CentralArizona','9-Coweeta','10-FloridaCoastalEverglades',
'11-GeorgiaCoastalEcosystems','12-HarvardForest','13-HubbardBrook','14-JornadaBasin','15-Kellog... |
# Copyright 2017--2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License
# is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" fi... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. 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 cop... |
from unittest import TestCase
from unittest.mock import MagicMock
from basketball_reference_web_scraper.html import BasicBoxScoreRow
class TestBasicBoxScoreRow(TestCase):
def setUp(self):
self.html = MagicMock()
def test_playing_time_when_cells_exist(self):
cell = MagicMock(text_content=Magi... |
"""Builds and runs TF model training and evaluation.
Defined model and training based on input arguments.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
from datetime import datetime
import json
import os
import posixpath
import sys
i... |
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. 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 requir... |
<filename>lib/ext/gnuradio-tools/examples/snr_estimators.py
#!/usr/bin/env python
import sys
try:
import scipy
from scipy import stats
except ImportError:
print "Error: Program requires scipy (www.scipy.org)."
sys.exit(1)
try:
import pylab
except ImportError:
print "Error: Program requires Ma... |
<reponame>xiejx5/GeoSpace<filename>geospace/gee_export.py
import os
import ee
import zipfile
import requests
import pandas as pd
# gee initialization
def gee_initial():
try:
ee.Initialize()
except Exception:
ee.Authenticate()
ee.Initialize()
def gee_export_tif(image, filename, crs=No... |
<reponame>nickovs/pypssst
import pssst
import pytest
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
@pytest.fixture(scope="session")
def keys():
server_private_key, server_public_key = pssst.generate_key... |
<reponame>mrForce/immunoGalaxy
#!/usr/bin/python
import sys
import argparse
import subprocess
import shutil
import csv
from collections import Counter, namedtuple
import io
import os
import uuid
import zipfile
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib_venn import venn2
fro... |
import random
epsilon = 0.000001
scores = [0.0]*39366 #2*3^9
board = 9*[1]
board[8]=0
ties_allowed = False
done = False
def board_to_value(board, turn):
val = 0
for i in range(0, 9):
val = 3*val + (board[8-i]*(3*board[8-i] - 1))//2
return 2*val + turn
def value_to_board(value):... |
<filename>app/broadcast_areas/__init__.py
from notifications_utils.formatters import formatted_list
from notifications_utils.polygons import Polygons
from notifications_utils.serialised_model import SerialisedModelCollection
from werkzeug.utils import cached_property
from .populations import CITY_OF_LONDON
from .repo ... |
# coding=utf-8
import hashlib
import hmac
import json
import logging
from typing import Dict, Set
import requests
from ikeawatcher.model import CollectLocation, ShoppingCart
LOGGER = logging.getLogger(__name__)
_HMAC_ALGO = hashlib.sha1
_HMAC_KEY = "<KEY>"
class IkeaApi:
def __init__(self, country, locale):
... |
<reponame>scottdermott/etl-parser
# -*- coding: utf-8 -*-
"""
Parse an event record
:see: https://docs.microsoft.com/fr-fr/windows/desktop/api/evntcons/ns-evntcons-_event_record
"""
from construct import Struct, Int16ul, Enum, Int32ul, Int64ul, FlagsEnum, Int8ul, Bytes, Aligned, RepeatUntil, Computed, \
AlignedStr... |
"""
model from
A Self-Reasoning Framework for Anomaly Detection Using Video-Level Labels
1 video clip each 16 frame
2 c3d feature extractor
3 fc
3.1 fc 4096->512
Real-world Anomaly Detection in Surveillance Videos
arXiv:1801.04264v3
WEAKLY SUPERVISED VIDEO ANOMALY DETECTION VIA CENTER-GUIDED DISCRIMINATIVE LEARNI... |
<gh_stars>10-100
"""
Copyright (c) 2021, FireEye, Inc.
Copyright (c) 2021 <NAME>
In order to run any mitigation experiment, first run the desired attack for 1 iteration setting the save
parameter of the configuration file to a valid path in the system, and "defense": true.
The attack script will save there a set of ar... |
<filename>main_Screen/main_controller.py<gh_stars>0
import tkinter as tk
from test_one import ToDo
"""
This is the controller file - will act as the traffic director for active and non-active windows based
upon end user.
"""
#Color designations for the app theme to be used with widgets-------------
BG = '#0C1021'
... |
<gh_stars>10-100
#!/usr/bin/env python
#
# Copyright (c), 2016-2020, SISSA (International School for Advanced Studies).
# All rights reserved.
# This file is distributed under the terms of the MIT License.
# See the file 'LICENSE' in the root directory of the present
# distribution, or http://opensource.org/licenses/MI... |
<filename>Tools/Scripts/webkitpy/tool/commands/rebaseline.py
# Copyright (c) 2010 Google Inc. 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 t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.