input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
"""
Defines log curves
:copyright: 2021 Agile Scientific
:license: Apache 2.0
"""
import copy
import warnings
import numpy as np
import pandas as pd
from scipy.interpolate import interp1d
from welly.plot import plot_2d_curve, plot_curve, plot_kde_curve
from welly.quality import quality_score_curve, qflags_curve, qua... | |
return dist
def clear_atoms(self):
"""Clears object from atoms and all topological structures."""
self.atoms = []
self.bonds = []
self.angles = []
self.dihedrals = []
self.impropers = []
self.cycles = [None, None, None]
self.molecules = []
self.atom_types = []
self.bond_types = []
self.angle_types = []
se... | |
<filename>Scripts/simulation/drama_scheduler/drama_node.py
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\drama_scheduler\drama_node.py
# Compiled ... | |
query results:', file=logfile)
#print(bindings, file=logfile)
if len(bindings) == 0:
if cmpFlag:
print('\nLINE_MODEL_VALIDATOR PerLengthPhaseImpedance: NO LINE MATCHES', flush=True)
print('\nLINE_MODEL_VALIDATOR PerLengthPhaseImpedance: NO LINE MATCHES', file=logfile)
return line_count
Zabc = {}
for obj in bi... | |
(700, 400), "angle": 0.0, "speed": 80},
{"position": (800, 400), "angle": 0.0, "speed": 80},
{"position": (0, 200), "angle": 0.0, "speed": 0},
{"position": (100, 200), "angle": 0.0, "speed": 0},
{"position": (200, 200), "angle": 0.0, "speed": 0},
{"position": (300, 200), "angle": 0.0, "speed": 0},
{"position": (4... | |
from keras.models import load_model
import glob
import os
from skimage.io import imread, imsave
from skimage.transform import resize
import cv2
import matplotlib.pyplot as plt
from create_individual_lettuce_train_data import construct_ground_truth, fix_noise
from skimage.color import rgb2grey, grey2rgb
from skimage.dr... | |
able to reconstruct
# the full paths.
# TODO(maruel): cwd should be saved at each process creation, so forks needs
# to be traced properly.
if os.path.isfile(logname):
with open(logname) as f:
content = f.read()
with open(logname, 'w') as f:
pid = content.split(' ', 1)[0]
f.write('%s chdir("%s") = 0\n' % (pid,... | |
# in order to check if the reroll has an account in database
victim = Users(target.id)
victim_id = target.id
counter += 1
# calculate random integer 1-100
# if the result is within 1 through fail chance, they failed the rob
if fail_chance >= random.randint(1, 100) >= 1:
robber_level = robber.get_user_level(0)
... | |
elif op.id == Id.Expr_NotDTilde:
return not libc.fnmatch(right, left)
elif op.id == Id.Expr_TildeDEqual:
# Approximate equality
if not isinstance(left, str):
e_die('~== expects a string on the left', span_id=op.span_id)
left = left.strip()
if isinstance(right, str):
return left == right
if isinstance(right,... | |
<gh_stars>0
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2020 FABRIC Testbed
#
# 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 ... | |
from radixlib.network import Network
from radixlib.actions import (
CreateTokenDefinition,
UnregisterValidator,
RegisterValidator,
TransferTokens,
UnstakeTokens,
StakeTokens,
MintTokens,
BurnTokens,
ActionType
)
from typing import Union, List, overload, Optional
import radixlib as radix
class ActionBuilder():... | |
r + s) for i in xrange(N)]
total = sum(A)
totalsum = [a for a in A]
for i in xrange(1, N):
totalsum[i] += totalsum[i - 1]
return totalsum
def func_d06f6698c2a846998ba7071fd9458b55(p, N, q, s, r):
A = [((i * p + q) % r + s) for i in xrange(N)]
total = sum(A)
totalsum = [a for a in A]
for i in xrange(1, N):
t... | |
import pprint
import copy
from collections import defaultdict
from itertools import groupby
from numpy import array
from six.moves import xrange, StringIO
from scrapely.extraction.pageobjects import AnnotationTag
from scrapely.extraction.regionextract import (
RecordExtractor, BasicTypeExtractor, RepeatedDataExtrac... | |
Generates:
Depending on how called it can also generate a plot image. This is meant to
be default for the command line; however, it can be included when calling
main function in Jupyter or IPython.
Main function of script.
Takes a dataframe either as a file or passed directly along some information
about colum... | |
<gh_stars>0
import numpy as np
import matplotlib.pyplot as plt
import time
import _pickle as cPickle
# Function used for loading the CIFAR10 dataset
def unpickle(file):
with open(file, 'rb') as fo:
dict = cPickle.load(fo)
return dict
# Compute the softmax function of the output
def softmax(y):
max_of_rows = np.m... | |
<reponame>yanikou19/pymatgen
# coding: utf-8
from __future__ import division, unicode_literals
import unittest
import os
import json
import numpy as np
from pymatgen.analysis.structure_matcher import StructureMatcher, \
ElementComparator, FrameworkComparator, OrderDisorderElementComparator
from monty.json import Mo... | |
<gh_stars>10-100
"""Module FSA -- methods to manipulate finite-state automata
Created by: <NAME> // Modified and enlarged by: <NAME>
This module defines an FSA class, for representing and operating on
finite-state automata (FSAs). FSAs can be used to represent regular expressions
and to test sequences for membership... | |
<gh_stars>0
from functools import partial
from typing import List, Dict, Optional, Union
from collections import Counter, OrderedDict
import pandas as pd
import pandas.api.types
from ray.data import Dataset
from ray.data.preprocessor import Preprocessor
class OrdinalEncoder(Preprocessor):
"""Encode values within c... | |
disable export if wrong vertex count
if valid == False:
bpy.context.scene.export_flag = False
#add a base shape key
bpy.context.view_layer.objects.active = obj
bpy.ops.object.shape_key_add(from_mix=False)
#apply modifiers on the extracted meshes
for o in extracted_shape... | |
<gh_stars>1-10
# encoding: utf-8
from migrate import *
import uuid
import datetime
def upgrade(migrate_engine):
id = uuid.uuid4()
make_missing_revisions = '''
-- make sure all tables have an entry in the revision_table
insert into revision values ('%(id)s' , '%(timestamp)s', 'admin', 'Admin: make sure every obj... | |
<filename>genetic_algorithm/genetic_algorithm.py
import argparse # parsing command line arguments
import importlib # dynamically importing modules
import random # randint
import time # delay & timing
from math import log # used in mutation
import sys # to exit and append to path
sys.path.append('../utils')
sys.path.ap... | |
= QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGu... | |
<reponame>SrGambiarra/KivyStudioDesigner<filename>core/project_manager.py
__all__ = [
'ProjectEventHandler', 'ProjectWatcher', 'CallWrapper',
'AppWidget', 'Project', 'ProjectManager']
from utils.utils import (
get_app_widget, get_designer,
show_error_console, show_message,
)
from kivy.event import EventDispatcher... | |
thread in threads:
thread.join()
def verify_igmp_data_traffic_in_thread(self, group, intf='veth0', source='1.2.3.4', data_pkt =50, negative = None):
log_test.info('Verifying multicast traffic for group %s from source %s'%(group,source))
self.success = False
def recv_task():
def igmp_recv_cb(pkt):
#log_test.info... | |
EAP_MASTER_SESSION_KEY_AVP_CODE)
self.assertFalse(avps[0].is_vendor_id())
self.assertFalse(avps[0].is_mandatory())
self.assertFalse(avps[0].is_protected())
self.assertEqual(avps[0].get_length(), 72)
self.assertIsNone(avps[0].vendor_id)
self.assertEqual(avps[0].data.hex(), "ec3208c43154f60862858afa650dd875e8a095df... | |
boundary option: must be one of {BOUNDARY_OPTIONS}")
if nan_treatment not in ('interpolate', 'fill'):
raise ValueError("nan_treatment must be one of 'interpolate','fill'")
# OpenMP support is disabled at the C src code level, changing this will have
# no effect.
n_threads = 1
# Keep refs to originals
passed_k... | |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Parse your Windows Registry files using preg.
preg is a simple Windows Registry parser using the plaso Registry plugins and
image parsing capabilities. It uses the back-end libraries of plaso to read
raw image files and extract Registry files from VSS and restore points and... | |
#!/usr/bin/env python3
#
# Copyright (C) 2010-2020 Arm Limited or its affiliates. All rights reserved.
#
# SPDX-License-Identifier: Apache-2.0
#
# 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
#
... | |
# Copyright 2020 NXP Semiconductors
# Copyright 2020 <NAME>
#
# This file was copied from NXP Semiconductors PyeIQ project respecting its
# rights. All the modified parts below are according to NXP Semiconductors PyeIQ
# project`s LICENSE terms.
#
# Reference: https://source.codeaurora.org/external/imxsupport/pyeiq/
#
... | |
'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00248228,
'Renaming Unit/Peak Dynamic': 3.58947,
'Renaming Unit/Runtime Dynamic': 0.0933986,
'Renaming Unit/Subthreshold Leakage': 0.0552466,
'Renaming Unit/Subthreshold Leakage with power gating': 0.0276461,
'Runtime Dynamic': 1.66885,
'... | |
import torch
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
# @neelabh17 implementation
class CCELoss(torch.nn.Module):
def __init__(self, n_classes, n_bins = 10, mode = "eval"):
'''
output = [n_Class, h , w] np array: The complete probability vector of an image
target = [h , w] np array: T... | |
<reponame>J-E-J-S/aaRS-Pipeline<filename>resources/mgltools_x86_64Linux2_1.5.6/MGLToolsPckgs/Pmv/computeIsovalue.py
## Automatically adapted for numpy.oldnumeric Jul 23, 2007 by
from geomutils.surface import findComponents, meshVolume, triangleArea
try:
from UTpackages.UTisocontour import isocontour
except:
pass
tr... | |
<reponame>Sette/autokeras
import functools
import pickle
import kerastuner
import tensorflow as tf
from tensorflow.python.util import nest
from autokeras.hypermodel import base
from autokeras.hypermodel import compiler
class Graph(kerastuner.engine.stateful.Stateful):
"""A graph consists of connected Blocks, Hyper... | |
<reponame>gemsouls/scalene<gh_stars>0
import shutil
import sys
import tempfile
from collections import OrderedDict
from operator import itemgetter
from rich.console import Console
from rich.markdown import Markdown
from rich.syntax import Syntax
from rich.table import Table
from rich.text import Text
from rich import ... | |
an IPv4/6 prefix for this route, e.g. 192.168.1.0/24
:type prefix: type string
:parm nexthop: The gateway to use for this route, which should be
the IP address of one of `router`'s logical router
ports or the IP address of a logical port
:type nexthop: string
:param port: If specified, packets that match this rou... | |
occurred " + type(e).__name__ + " " + str(e))
return "Unknown Error " + type(e).__name__
else:
return ob.link
async def cmd_calm(self, args: Args, src: Src, **_):
"""Bring up a random image from the "calm" gallery, or add one.
Syntax: `{p}calm [<link to add to calm>]`
"""
gal = self.config.get("calmGallery")
... | |
<reponame>825477418/XX
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/3/21 17:25
# @File : SaaS
# @Des :
# @Email : <EMAIL>
from BaseModel.BaseModel import *
from sqlalchemy import Column, String, TIMESTAMP, Text, text, DateTime
from sqlalchemy.dialects.mysql import INTEGER, LONGTEXT, TINYINT
from sqlalc... | |
<gh_stars>10-100
import argparse
import ast
import collections
import difflib
import fnmatch
import io
import logging
import os
import re
import tempfile
import tokenize
from typing import Dict
from typing import IO
from typing import Iterable
from typing import Iterator
from typing import List
from typing import Mappi... | |
#MIT License
#Copyright (c) 2021 K3v1nNZ
import discord
import requests
import json
import pycoingecko
from discord.ext import commands
from discord.ext.commands import Bot
from pycoingecko import CoinGeckoAPI
cg = CoinGeckoAPI()
client = commands.Bot(command_prefix = '$', case_insensitive = True)
client.remove_comma... | |
#!/usr/bin/env python
#
# Copyright 2014 <NAME>
# See LICENSE.txt for distribution terms
#
from bc4py.bip32.base58 import check_decode, check_encode
from bc4py_extension import PyAddress
from ecdsa.curves import SECP256k1
from ecdsa.keys import SigningKey, VerifyingKey, square_root_mod_prime as mod_sqrt
from ecdsa.ecd... | |
<reponame>suquant/magnum
# Copyright 2015 Rackspace 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.apache.org/licenses/LICENSE-2.0
#
# Unless require... | |
'0.00000000', '0.00000000', '0.00000000',
# '1.00000000', '0.00000000']
# [IDL] If the data we are processing is a Single Voxel
# Spectroscopy data, interchange rows and columns. Due to an error
# in the protocol used.
if is_svs:
image_orientation = image_orientation[3:] + image_orientation[:3]
# Convert the ... | |
<reponame>Zari01/NLChk
#=============================================================================================#
import re
import sys
#=============================================================================================#
def main():
global ivscollect,natcollect
ivscollect = re.compile('\d+')
natcollec... | |
return self._RunMethod(
config, request, global_params=global_params)
Get.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v2/projects/{projectsId}/agent/sessions/{sessionsId}/contexts/{contextsId}',
http_method=u'GET',
method_id=u'dialogflow.projects.agent.sessions.contexts.get',
ordered_params=[u'na... | |
#!/usr/bin/env python
# CCP4ScalerHelpers.py
# Copyright (C) 2006 CCLRC, <NAME>
#
# This code is distributed under the BSD license, a copy of which is
# included in the root directory of this package.
#
# 3rd November 2006
#
# Helpers for the "CCP4" Scaler implementation - this contains little
# functions which wrap th... | |
#! /usr/bin/env python3
"""
This utility does the following:
1. Check that all the following are synchronized:
- The google spreadsheet (as csv: File->Download->csv[current sheet])
> Checks that the list count is proper.
- The ini files: test_
- The ini files: assessment_
- The setupEnv.json files (+ description... | |
<filename>ChiantiPy/tools/io.py
"""
Reading and writing functions
"""
import os
from datetime import date
import pickle
import configparser
import numpy as np
import ChiantiPy.tools.util as util
import ChiantiPy.tools.constants as const
import ChiantiPy.Gui as chgui
from ChiantiPy.fortranformat import FortranRecordRe... | |
<filename>assessments/Assignments-2/model_v1.py
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Project : acs-project-krr
@File : model_v1.py
@Author : <NAME>
@Contact : <EMAIL>
@Date : 2020/11/21 10:40 上午
@Version : 1.0.0
@License : Apache License 2.0
@Desc : None
"""
MODELS = [
{
'DOMAIN': {'v_5', 't_3', '... | |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 2.0.10
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info
if version_info >= (3,0,0):
new_instancemethod = lambda func, inst, cls: _Bnd.SWIG_P... | |
resource"""
return self.__edit
@edit.setter
def edit(self, value: Tuple[str, ...]):
self.__edit = value
self._property_changed('edit')
@property
def admin(self) -> Tuple[str, ...]:
"""Permission to edit all details of the resource, including entitlements. Can also delete the resource"""
return self.__admin
... | |
import discord
import config
import requests
import json
import libraries.helper as Helper
import os
import shutil
line_return = '\n' # needed later for f-strings because finicky interpreter
if not os.path.exists("../config/config.json"):
shutil.copyfile("../config/config_example.json", "../config/config.json")
with... | |
<filename>psydac/api/ast/utilities.py
import re
import string
import random
from sympy import Symbol, IndexedBase, Indexed, Idx
from sympy import Mul, Pow, Function, Tuple
from sympy import sqrt as sympy_sqrt, Range
from sympy.utilities.iterables import cartes
from sympde.topology.space import ScalarFunction
from sym... | |
<reponame>tacorna/taco<filename>taco/lib/splice_graph.py<gh_stars>10-100
'''
TACO: Multi-sample transcriptome assembly from RNA-Seq
'''
import logging
import collections
import bisect
from itertools import chain
from array import array
import numpy as np
from base import Exon, Strand, TacoError
from graph import Graph... | |
<reponame>smorad/ray
import hashlib
import logging
import json
from filelock import FileLock
from pathlib import Path
from zipfile import ZipFile
from ray._private.thirdparty.pathspec import PathSpec
from ray.job_config import JobConfig
from enum import Enum
from ray.experimental.internal_kv import (_internal_kv_put,... | |
10.0], ["animal", 3.0]],
"title": "Snake",
"description": "Snake",
"types": {"hyena": ["animal"]},
"relations": [{"relatiion": "sibbbling", "object": "Q123"}],
}
# Test new bad relation format
with self.assertRaises(ValueError) as context:
entity_profile.add_entity(new_entity)
assert type(context.exception) i... | |
<gh_stars>0
from __future__ import absolute_import
import re # noqa: F401
import six
from ionoscloud.api_client import ApiClient
from ionoscloud.exceptions import ( # noqa: F401
ApiTypeError,
ApiValueError
)
class DataCenterApi(object):
def __init__(self, api_client=None):
if api_client is None:
api_client = ... | |
iterator over the CallSets fulfilling the specified
conditions from the specified VariantSet.
:param str variant_set_id: Find callsets belonging to the
provided variant set.
:param str name: Only CallSets matching the specified name will
be returned.
:param str biosample_id: Only CallSets matching this id will
... | |
"""
@file
@brief provides some functionalities to upload file to a website
"""
from ftplib import FTP, FTP_TLS, error_perm
import os
import sys
import time
import datetime
from io import BytesIO
from ..loghelper.flog import noLOG
class CannotReturnToFolderException(Exception):
"""
raised when a transfer is interrup... | |
TESTS::
sage: p = Polyhedron(backend='normaliz') # optional - pynormaliz
sage: from sage.geometry.polyhedron.backend_normaliz import Polyhedron_normaliz # optional - pynormaliz
sage: Polyhedron_normaliz._init_from_Hrepresentation(p, [], []) # indirect doctest # optional - pynormaliz
"""
if normaliz_field is None:... | |
<gh_stars>0
from pprint import pprint as pretty
from collections import deque as dq
from math import floor, ceil, inf
from copy import deepcopy as dp
# My first thought is to basically have a que and then just go through them one by one.
# The real problem is trying to figure out how to select the model numbers
# One ... | |
# -*- coding: utf-8 -*-
'''
=============================================
Open Facebook - A generic Facebook API
=============================================
This API is actively maintained, just fork on github if you wan
to improve things.
Follow the author: <NAME> (@tschellenbach)
blog: http://www.mellowmorning.com... | |
= nm.zeros( (conn_in.shape[0],), nm.int32 )
for ii, el in enumerate( conn_in ):
if (el[4] == el[5]):
if (el[5] == el[6]):
flag[ii] = 2
else:
flag[ii] = 1
conn = []
desc = []
mat_id = []
ib = nm.where( flag == 0 )[0]
if (len( ib ) > 0):
conn.append( conn_in[ib] )
mat_id.append(mat_id_in[ib])
desc.append... | |
<reponame>IlhamriSKY/vanika-chatbot-line
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
""" Database """
from controler.config import Config
class Email(object):
def kirimEmail(email, username, user... | |
# Copyright (c) 2019-2020 <NAME>
# License: MIT License
from typing import TYPE_CHECKING, Iterable, Sequence, Tuple, Union, List, Dict
import array
import copy
from itertools import chain
from contextlib import contextmanager
from ezdxf.lldxf import validator
from ezdxf.lldxf.attributes import (
DXFAttr, DXFAttributes... | |
# import
import datetime
from django.utils import timezone
from django import template
from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
from django.urls import reverse
from applications.academic_information.models import Student
from applications.glob... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""This file contains tests for the mrt_parser.py file.
For speciifics on each test, see the docstrings under each function.
Note that if tests are failing, the self.start and self.end may need
updating to be more recent. Possibly same with the api_param_mods.
"""
__aut... | |
Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_
**Note:** Type conversions are performed if necessary. Dummy values
are converted to "*" string.
"""
ret_val = self._get_int(row, col)
return ret_val
def get_string(self, row, col, str_val):
"""
Get a ... | |
<filename>flair/datasets/treebanks.py
import logging
import re
from pathlib import Path
from typing import List, Union
import flair
from flair.data import Corpus, FlairDataset, Sentence, Token
from flair.datasets.base import find_train_dev_test_files
from flair.file_utils import cached_path
log = logging.getLogger("f... | |
r"""Tests for parallel implementation of triangulations."""
import nose.tools as nt
import numpy as np
import os
import time
from cgal4py import _use_multiprocessing
from cgal4py import parallel, delaunay
from cgal4py.domain_decomp import GenericTree
from cgal4py.tests.test_cgal4py import make_points, make_test, MyTest... | |
in community['tags']]
except KeyError:
pass
communities = list(set(communities))
for community in communities:
if in_code_list('DONL:Communities', 'taxonomy', community):
logger.info('community %s added to dataset', community)
data[('communities',)].append(community)
else:
logger.warning('community %s remove... | |
import time
import pandas as pd
import warnings
warnings.filterwarnings('ignore')
import re
import datetime
import json
import pickle
# log
import logging
LOGGER = logging.getLogger('run-time-adaptive_automl')
# LOG_LEVEL = 'INFO'
LOG_LEVEL = 'DEBUG'
LOGGER.setLevel(getattr(logging, LOG_LEVEL))
simple_formatter = log... | |
<filename>peak_list_dialog.py
# -*- coding: utf-8 -*-
# pylint: disable=invalid-name
"""
New Peak List Dialog for iPick and Cross-Validation Modules
@author: <NAME>
"""
import sys
if sys.version_info[0] == 2:
import Tkinter as tk
import tkMessageBox
import tkFont
else:
import tkinter as tk
import tkinter.messag... | |
2 for row in models.Telescope.query]
if request.method == 'POST':
if form.validate():
telescope = form.telescope.data
json_data, queue_name = get_json_data_manual(form)
group(
tasks.scheduler.submit_manual.s(
telescope, json_data, queue_name),
tasks.email.compose_too.s(
telescope, queue_name)
).delay()
fl... | |
[ymin, ymax],
'ls': '-', 'lw': 0.8, 'alpha':1., 'color':'gray', 'ds': 'default',
'xscale': None, 'yscale': None,
}
o_plot.set_plot_dics.append(y_err_dic)
dic = {
'task': 'scatter', 'ptype': 'cartesian', # 'aspect': 1.,
'xarr': xarr, "yarr": yarr, "zarr": colarr,
'position': (1, i_col), # 'title': '[{:.1f} ms]'... | |
#!/usr/bin/env python
# Copyright 2014-2019 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
#
# Unles... | |
_decoratorlock.acquire()
self._addThread(target=self._doItSharer)
self.assertRaises(Queue.Empty, self.done.get_nowait)
_decoratorlock.release()
self._waitThreads()
self.failUnlessEqual(self.done.get_nowait(), "SHR")
@_Repeat
def testSharerBlocksExclusive(self):
_decoratorlock.acquire(shared=1)
self._addThread... | |
up the scores when subject is in each pile by A.ids.
"""
from jcvi.formats.base import SetFile
from jcvi.formats.fasta import Fasta
p = OptionParser(score.__doc__)
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
blastfile, fastafile, idsfile = args
ids = SetFile(idsfile)
bl... | |
<filename>src/prepare.py
"""
This file contains the main emulation loop.
We first prepare the data.
"""
import random
import gzip
import ipaddress
import gc
from operator import itemgetter
import time
from cfg import Config
from . import get_config
from . import libemulate
COUNTERMEASURES, ADDRMAN_PARAMS, EMU_PARAMS,... | |
from __future__ import division
import matplotlib
from __builtin__ import dict
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import os
import logging
import numpy as np
from sklearn.metrics import roc_curve, auc, f1_score, confusion_matrix, classification_report
import datetime
from scipy import integrate
impor... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from .. import TestUnitBase
class TestHexLoad(TestUnitBase):
def test_hexdump_01(self):
dump = (
'dump: 000: 4D 5A 90 00 03 00 00 00 04 00 00 00 FF FF 00 00\n'
'dump: 010: B8 00 00 00 00 00 00 00 40 00 00 00 00 00 00 00\n'
'dump: 020: 00 00 00 00 00 00 00 00 00 00 ... | |
<reponame>Ator97/dataMiningDataviz
import base64
import datetime
import io
import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import dash_table
import pandas as pd
import plotly.express as px
from apyori import apriori
from scipy.spatia... | |
<filename>module/imsng/gw.py
# SELECT GW HOST GALAXY CANDIDATES
# 2019.02.10 MADE BY <NAME>
# 2019.08.29 UPDATED BY <NAME>
#============================================================#
import os, glob, sys
import matplotlib.pyplot as plt
import numpy as np
import healpy as hp
from astropy.table import Table, vstack, h... | |
the same as pressure units.
self.u_te = self.u_e / self.u_t * self.u_l # Box therm. em. [erg/(s ster cm2)]
self.u_n = 3.00e+10 # Density number n_0 * 1/cm^3
self.pi = const.pi
self.u_b = self.u_u * np.sqrt(4. * self.pi * self.u_r)
# self.uni tells how to convert from simu. units to cgs units, for simple vars.
se... | |
<reponame>bradleyhenke/cortex<filename>test/IECoreHoudini/ToHoudiniCompoundObjectConverter.py
##########################################################################
#
# Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modifica... | |
= len(lono)
except:
msg = 'CANNOT CREATE INSTANCE - Output longitude must be an array. Can have length of 1'
raise TypeError, msg
# make sure that the arrays are numpy arrays
if usefilled == 'yes':
lati = numpy.ma.filled(lati)
loni = numpy.ma.filled(loni)
lato = numpy.ma.filled(lato)
lono = numpy.ma.filled(... | |
<filename>fabry/core/ringsum.py
from __future__ import division, print_function
import numpy as np
import matplotlib.pyplot as plt
import multiprocessing as mp
from numba import jit
"""
Core module contains ringsum codes that are the basis of this
analysis.
Functions:
get_binarr: returns binarr for ringsums
smAng_r... | |
layer
if i == 0:
self.layers[i].prev = self.input_layer
self.layers[i].next = self.layers[i + 1]
# All layers except for the first and the last
elif i < len(self.layers) - 1:
self.layers[i].prev = self.layers[i - 1]
self.layers[i].next = self.layers[i + 1]
# The next layer of the last layer is the l... | |
###
# Copyright (c) 2020, oddluck <<EMAIL>>
# 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,
# this list of conditions, ... | |
<reponame>TransientObject/labMTComparison<gh_stars>0
#!/usr/bin/python
#
# storyLab.py
#
# a python module for using the labMT1.0 dataset
# no dependencies, unless using the plot function
# (then we use matplotlib)
#
# USAGE
#
# In python:
# tmpstr = 'a happy sentence'
# from storyLab import emotionFileReader
# lens = ... | |
<reponame>brotherelric/deezcord.py
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
Copyright (c) 2021-present 404kuso
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 S... | |
<filename>ztfin2p3/metadata.py<gh_stars>0
""" Handling metadata """
import os
import numpy as np
import pandas
import warnings
from .utils.tools import parse_singledate
def get_rawmeta(which, date, ccdid=None, fid=None,
getwhat='metadata',
**kwargs):
"""
which: [string]
- flat
- bias
- starflat [not implement... | |
<filename>html2vec/base/features/html2attrib.py
#
# Module: Base HTML 2(to) HTML Attributes
#
# Author: <NAME>
#
# License: BSD Style
#
# Last update: Please refer to the GIT tracking
#
""" html2vect.base.features.html2attrib: submodule of `html2tf` module defines the class BaseHTML2Attributes """
import re
import un... | |
y)\n'
'implicit none\n'
'INTEGER*4, intent(in) :: m\n'
'INTEGER*4, intent(in) :: n\n'
'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n'
'REAL*8, intent(in), dimension(1:n) :: x\n'
'REAL*8, intent(out), dimension(1:m) :: y\n'
'end subroutine\n'
'end interface\n'
)
def test_dummy_loops_f95():
from sympy.tensor... | |
<gh_stars>0
import numpy as np
import pandas as pd
import time
from collections import defaultdict
from argparse import ArgumentParser
class GridWorld:
def __init__(self, path):
self.path = path # loaded file path
self.grid = np.loadtxt(self.path, dtype='str') # initial grid
self.n_row, self.n_col = np.shape(self... | |
# Source : http://www.sam.math.ethz.ch/~gradinar/Teaching/NumPhys/SomeTemplates/ode45.py
from numpy import double, sign, finfo, array, zeros, dot, mod, size, inf, all, max, min, abs, mat
from numpy.linalg import norm
def warning(type, string):
print('warning: ' + type)
print(string)
def error(type, string):
prin... | |
from transformers import pipeline
from sentence_transformers import SentenceTransformer, util
from SSIM_PIL import compare_ssim
from PIL import Image
import numpy as np
import pandas as pd
import random
import cv2
from pyjarowinkler import distance
from strsimpy.cosine import Cosine
from ux import outputHTML
from ml im... | |
<filename>py3/nn/experiments/tf_vae_pixel/resnet_viz.py
"""
Multilayer VAE + Pixel CNN
<NAME>
"""
import os, sys
sys.path.append(os.getcwd())
sys.path.append('/u/ahmedfar/Tmp/lsun_viz/nn/')
N_GPUS = 1
try: # This only matters on Ishaan's computer
import experiment_tools
experiment_tools.wait_for_gpu(tf=True, n_gpu... | |
self._tzinfo.utcoffset(None)
_check_utc_offset("utcoffset", offset)
return offset
def tzname(self):
"""Return the timezone name.
Note that the name is 100% informational -- there's no requirement that
it mean anything in particular. For example, "GMT", "UTC", "-500",
"-5:00", "EDT", "US/Eastern", "America/New ... | |
by multiple bindings.
#
# These files are 'orphans' in the Sphinx sense: they are not in
# any toctree.
logging.info('updating :orphan: files for %d bindings', len(bindings))
num_written = 0
# First, figure out which compatibles map to multiple bindings. We
# need this information to decide which of the genera... | |
= generate_rsa(pkey=private_key)
except Exception,err:
self.error = _(u'您导入的密钥格式不正确,请重新生成: %s')%str(err)
self.verify_failure = True
else:
attr, _ = DomainAttr.objects.get_or_create(item=self.ItemKey, type=self.ItemType, domain_id=self.domain_id)
attr.value = private_key
attr.save()
self.private_key = private_ke... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.