input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<gh_stars>1-10
# create plot as in Figure 4d to study joint occupancy at neighboring CTCF sites
# ## <NAME>
# ## 06.30.21
import sys
import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pysam
import multiprocessing
from joblib import Parallel, delayed
from pybedt... | |
import os
import sys
import json
import torch
import random
import inspect
import requests
import argparse
import importlib
import numpy as np
from pathlib import Path
from itertools import product
from tqdm import tqdm
from PyInquirer import prompt, Separator, Validator, ValidationError
DATA_FOLDER = 'data/'
class F... | |
search_locations(self, search_token, query="name"):
"""Function to search for location data from the database based on a given search token (or from the dictionary if in local mode)
Searches based on either location name or by author name or to just retrieve all location data from the DB
By default it searches base... | |
any command line parameters.'}),
('pid', {'ptype': 'int', 'doc': 'The process ID.'}),
('time', {'ptype': 'time', 'doc': 'The start time for the process.'}),
('user', {'ptype': 'inet:user', 'doc': 'The user name of the process owner.'}),
('path', {'ptype': 'file:path', 'doc': 'The path to the executable of the proce... | |
import itertools
import json
import operator
import pathlib
import pickle
import random
import shutil
from zplib import datafile
class _DataclassBase:
"""Basic methods for "data classes" that have a defined set of fields with
which to compare and hash class instances."""
_FIELDS = () # subclasses should provide a ... | |
"""Return the weights of the specified indeces or, if None, return all.
Parameters
----------
normalize : boolean or float > 0
If True, the weights will be normalized to 1 (the mean is 1).
If a float is provided, the mean of the weights will be equal
to *normalize*. So *True* and *1* will yield the same results.... | |
lbl.set_verticalalignment('center')
# Grid lines around the pixels
if grid:
offset = -.5
xlim = [-.5, len(df.columns)]
ylim = [-.5, len(df.index)]
segments = []
for x in range(ylim[1]):
xdata = [x + offset, x + offset]
ydata = ylim
segment = list(zip(xdata, ydata))
segments.append(segment)
for y in range(x... | |
:param int page: [``optional``] : Sets the page of results to retrieve
from the server.
:param bool include_total_count: [``optional``] : Return the total
number of results for a query. This should typically be used only
for the first page of a large result set.
:param str out_format: [``optional``] : The format i... | |
either a PSL, PSLX, or BLAST-XML file!'.format(str(database)))
else:
raise FileNotFoundError()
except FileNotFoundError:
raise SearchError('Database file "{}" was not found!'.format(str(database)))
return rec
def id_search(id_rec, id_type='brute', verbose=2, indent=0, custom_regex=None, regex_only=False):
"""
... | |
import numpy as np, copy, matplotlib.pyplot as plt
from matplotlib import colors
cmap = colors.ListedColormap(['#000000', '#0074D9', '#FF4136', '#2ECC40', '#FFDC00', '#AAAAAA', '#F012BE', '#FF851B', '#7FDBFF', '#870C25'])
norm = colors.Normalize(0, 9)
class Object():
def __init__(self, points = [], low_coord = None, ... | |
import logging
from datetime import datetime
import xml.etree.ElementTree as ET
from indra.statements import *
from indra.statements.statements import Migration
from indra.statements.context import MovementContext
from indra.util import UnicodeXMLTreeBuilder as UTB
logger = logging.getLogger(__name__)
class CWMSEr... | |
import datetime
import json
import responses
from django.contrib.auth.models import User
from django.core.management import call_command
from django.db.models.signals import post_save
from django.test import TestCase
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framewor... | |
the motivation for having it on Alignment __init__
is that it's easy for users to construct Alignment objects directly.
Parameters:
data: Data to convert into a SequenceCollection
Names: Order of Names in the alignment. Should match the
names of the sequences (after processing by
label_to_name if present).
... | |
<filename>ai4good/models/abm/np_impl/model.py<gh_stars>10-100
import random
import numpy as np
import numba as nb
from ai4good.models.abm.np_impl.parameters import Parameters
from ai4good.utils.logger_util import get_logger
logger = get_logger(__name__)
# very small float number to account for floating precision los... | |
# -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
import os
import sys
import time
import re
import tensorflow as tf
from vocab_utils import Vocab
from SentenceMatchDataStream import SentenceMatchDataStream
from SentenceMatchModelGraph import SentenceMatchModelGraph
import namespace_utils
... | |
"""
Frame encoders and decoders for each frame type. Note that we have encoders
for frames that the server does not use; it's for testing, and in case someone
wants to write a Python Minerva client.
"""
import re
import sys
import operator
from simplejson import dumps
from simplejson.decoder import JSONDecodeError
fr... | |
# -*- coding: utf-8 -*-
# Copyright 2015 moco_beta
#
# 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 agr... | |
this object directly, use :meth:`DSSSubpopulationAnalyses.get_analysis(feature)` instead
"""
def __init__(self, analysis, prediction_type):
self._internal_dict = analysis
self.computed_as_type = analysis["computed_as_type"]
self.modalities = [DSSSubpopulationModality(analysis["feature"], self.computed_as_type, m,... | |
a problem. Skipping.", newname)
def getGuildInfo(self, guildname):
'''
Lookup guild by name. If such a guild exists (and the API is available)
the info as specified on https://wiki.guildwars2.com/wiki/API:2/guild/:id is returned.
Else, None is returned.
'''
ids = request("https://api.guildwars2.com/v2/guild/... | |
DEBUG = False
UNIT_TEST_DEBUG = False
import re
import os
import string
from os import path
PACKAGE_NAME = "ClassesAndTests"
def plugin_loaded():
global settings
settings = sublime.load_settings(PACKAGE_NAME+ '.sublime-settings')
global PACKAGE_DIR
global TEMPLATES_DIR
PACKAGE_DIR = os.path.join(sublime.package... | |
for _ in range(34)]
# change first one to total_loss
all_losses[0] = total_loss
# all_loss_weights - 34 is the number of outputs
# We're giving a weight of 0.5 for the final outputs to the total weight
all_loss_weights = [0.5 for _ in range(34)]
all_loss_weights[0] = 1.
model.compile(optimizer=optimizers.Adam(... | |
eq:
counter_phosphorylated_form += 1
self.differential_equations[i] = eq + f" + v[{line_num:d}]"
if counter_unphosphorylated_form == 0:
self.differential_equations.append(
f"dydt[V.{unphosphorylated_form}] = - v[{line_num:d}]"
)
if counter_phosphorylated_form == 0:
self.differential_equations.append(
f"dydt[V.... | |
<reponame>j-wilson/Ax
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import warnings
from dataclasses import dataclass
from typing import TYPE_CHECKING, Dict, List,... | |
<filename>CS/CSC148/exercises/ex2/ex2.py
"""CSC148 Exercise 2: Inheritance and Introduction to Stacks
=== CSC148 Fall 2016 ===
<NAME>, <NAME>, and <NAME>
Department of Computer Science,
University of Toronto
=== Module description ===
This file contains starter code for Exercise 2.
It is divided into two par... | |
<gh_stars>10-100
# Copyright (c) 2019 <NAME>
#
# 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 ... | |
attach to a worker replica.
service_account (str):
The service account that the DeployedModel's container runs as. Specify the
email address of the service account. If this service account is not
specified, the container runs as a service account that doesn't have access
to the resource project.
Users deploying t... | |
getCogNameString(self):
numCogs = self.getNumCogs()
if numCogs == 1:
return TTLocalizer.ASupervisor
else:
return TTLocalizer.SupervisorP
def doesCogCount(self, avId, cogDict, zoneId, avList):
return bool(CogQuest.doesCogCount(self, avId, cogDict, zoneId, avList) and cogDict['isSupervisor'])
class SupervisorNe... | |
#!/usr/bin/env python
"""Helper for observatory and device computed attributes, including aggregate status values"""
__author__ = '<NAME>, <NAME>'
from pyon.core import bootstrap
from pyon.core.exception import BadRequest
from pyon.public import RT, PRED, log
from interface.objects import DeviceStatusType, Aggregat... | |
float]]:
"""Returns the geometries' bounding box.
Returns:
tuple (xmin, ymin, xmax, ymax) for the bounding box or None if the LineCollection
is empty
"""
if len(self._lines) == 0:
return None
else:
return (
float(min((line.real.min() for line in self._lines))),
float(min((line.imag.min() for line in self._l... | |
import copy
import enum
import json
import os
import iwp.labels
# module for all things related to Scalabel frames.
# NOTE: we encode slice parameters in the Scalabel frame's name to support a
# full round trip during labeling. without this, we do not have a way to
# convey metadata about the frame that is needed wh... | |
<reponame>muntaza/Open-Aset<filename>openaset/gedungbangunan/migrations/0001_initial.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('umum', '0001_initial'),
]
operations = [
migrations.CreateM... | |
import torch
import math
from torch.nn import functional as F
class DenseBlock(torch.nn.Module):
def __init__(self, input_size, output_size, bias=True, activation='relu', norm='batch'):
super(DenseBlock, self).__init__()
self.fc = torch.nn.Linear(input_size, output_size, bias=bias)
self.norm = norm
if self.norm ... | |
<reponame>chrisdjscott/Atoman
# -*- coding: utf-8 -*-
"""
Analysis is performed using an *Analysis pipeline*, found on the *Analysis toolbar* on the left of the application (see
right). Multiple pipelines can be configured at once; a pipeline is viewed in a renderer window.
An individual pipeline takes a reference an... | |
' + str(j)
if len(sources.getSources(self.Message,self.manager_sourcelist,self.manager_network_name_nxt.get(),'network')) == 0 or self.Networks_UpdateSource():
sourcedict = {'network':self.manager_network_name_nxt.get(),'networkid':sources.getSource(self.Message,self.manager_networklist,self.manager_network_name... | |
di = {
'абрикос': 30,
'абрикосы (консервированные в сиропе)': 60,
'авокадо': 10,
'айва': 35,
'амарант (семена)': 35,
'амарант воздушный (аналог попкорна)': 70,
'амилоза': 48,
'ананас': 60,
'ананас (консервированные в сиропе)': 65,
'ананасовый сок без сахара': 50,
'апельсин': 35,
'апельсиновый сок': 45,
'ар... | |
<filename>tests/examples/minlplib/camshape400.py
# NLP written by GAMS Convert at 04/21/18 13:51:13
#
# Equation counts
# Total E G L N X C B
# 801 400 0 401 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc si
# Total cont binary integer sos1 sos2 scont sint
# 800 800 0 0 0 0 0 0
# FX 0 0 0 0 0 0 0 0
#
# Nonzero count... | |
<gh_stars>10-100
import openmmtools.cache as cache
import os
import copy
from perses.dispersed.utils import *
from openmmtools.states import ThermodynamicState, CompoundThermodynamicState, SamplerState
import numpy as np
import mdtraj as md
import simtk.unit as unit
import logging
import time
from collections import n... | |
'TaskExecutionId': 'string',
'Status': 'PENDING'|'IN_PROGRESS'|'SUCCESS'|'FAILED'|'TIMED_OUT'|'CANCELLING'|'CANCELLED'|'SKIPPED_OVERLAPPING',
'StatusDetails': 'string',
'StartTime': datetime(2015, 1, 1),
'EndTime': datetime(2015, 1, 1),
'TaskArn': 'string',
'TaskType': 'RUN_COMMAND'|'AUTOMATION'|'STEP_FUNCTIONS'|... | |
version, use_downloads=False)
return None, None, None, None # Cannot find the correct version!
else:
return results
def delete(self, project, version=None):
"""Delete all of the downloaded and installed files for the given project and version.
Args:
project (str): Project name.
version (str)[None]: Project ve... | |
#
# For licensing see accompanying LICENSE file.
# Copyright (C) 2019 Apple Inc. All Rights Reserved.
#
'''Capsule in PyTorch
TBD
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import math
from .bilinear_sparse_routing import BilinearSparseRouting, BilinearRo... | |
"""
Tasks for managing tasks, targets and scanners in GVM.
"""
import configparser
import logging
import uuid
from fps.client import GMPClient
from fps.utils import (export_results, get_hosts, get_key_by_value,
reset_discovery_attribute, update_discovered_hosts,
update_host_attribute)
config = configparser.ConfigPa... | |
{p3} )
) ; (
{router_to_router_pol}
))
+
((
( {p4} )
+
( {p6} )
+
( {p7} )
) ; (
{l2}
))
+
( {p5} )
+
( {p8} )
""".format(
l2=l2,
p1=p1,
p2=p2,
p3=p3,
p4=p4,
p5=p5,
p6=p6,
p7=p7,
p8=p8,
router_to_router_pol=spec2.router_to_router_pol))
spec3 = Spec3(
'\n+ '.join(preface),
'\n\n+... | |
<reponame>networmix/NetSim
# pylint: disable=protected-access,invalid-name
import pprint
from netsim.simulator.core.simcore import SimTime
from netsim.simulator.netsim_base import (
PacketInterfaceTx,
PacketQueue,
PacketSink,
PacketSource,
PacketSize,
)
from netsim.simulator.netsim_simulator import NetSim
def t... | |
<filename>auth_api/api/api_users/endpoint_usr_register.py<gh_stars>1-10
# -*- encoding: utf-8 -*-
"""
endpoint_usr_register.py
"""
from auth_api.api import *
log.debug(">>> api_users ... creating api endpoints for USER_REGISTER")
from . import api, document_type
### create namespace
ns = Namespace('register', des... | |
subnet_address: Network address of the subnet that is the container
of this address.
subnet_cidr: CIDR of the subnet that is the container of this
address.
subnet_id: Subnet ID that is the container of this address.
tenant: The Cloud API Tenant object.
vm_availability_zone: Availability zone of the VM.
vm_commen... | |
'''serialize/deserialize almost any kind of python object'''
# TODO:
# memoryview -- not possible? .tolist or .tobytes will return the data, but i haven't found a way to get the object that it references
# bytearray -- use str() to get the data
# operator.methodcaller -- can be done by using an object with __getattr__... | |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | |
and isinstance(self.payload, IPv6ExtHdrHopByHop):
nh = self.payload.nh
if self.nh == 60 and isinstance(self.payload, IPv6ExtHdrDestOpt):
foundhao = None
for o in self.payload.options:
if isinstance(o, HAO):
foundhao = o
if foundhao:
nh = self.payload.nh # XXX what if another extension follows ?
ss = foundhao... | |
<filename>tests/test_customers.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import json
import unittest
from six.moves.urllib.parse import parse_qs, urlparse
from optimove.client import Client
from optimove.constants import DEFAULT_URL
import responses
from tests.constants impo... | |
"iso2": "NG",
"admin_name": "Borno",
"capital": "minor",
"population": "",
"population_proper": ""
},
{
"city": "Augie",
"lat": "12.8903",
"lng": "4.5996",
"country": "Nigeria",
"iso2": "NG",
"admin_name": "Kebbi",
"capital": "minor",
"population": "",
"population_proper": ""
},
{
"cit... | |
required and takes effect only when ListenerSync is set to off.
:param pulumi.Input[str] sticky_session_type: Mode for handling the cookie. If `sticky_session` is "on", it is mandatory. Otherwise, it will be ignored. Valid values are `insert` and `server`. `insert` means it is inserted from Server Load Balancer; `serv... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
r"""
FIXME:
sometimes you have to chown -R user:user ~/.theano or run with sudo the
first time after roboot, otherwise you get errors
CommandLineHelp:
python -m wbia_cnn --tf netrun <networkmodel>
--dataset, --ds = <dstag>:<subtag>
dstag is the main dataset name (eg ... | |
"""
Mohr Circle - explains how Mohr's Circle can be used to identify different stresses
"""
###################################
# Imports
###################################
# general imports
from math import pi, sin, cos, atan
import yaml
# bokeh imports
from bokeh.io import curdoc
from bokeh.plotting i... | |
<reponame>tnnfnc/skipkey<gh_stars>0
'''Crypto fachade...'''
import cryptography.hazmat.primitives.keywrap as keywrap
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.... | |
"""
Ver 1.6
"""
from telegram import InlineKeyboardMarkup, InlineKeyboardButton, ParseMode
from telegram.ext import Updater, CommandHandler, ConversationHandler, CallbackQueryHandler
from sendMenu import getMenuURL
from databasefn import Database
from buildMenu import build_menu
import os
import logging
import datetim... | |
data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
data["location_time"] = str(datetime.now())
data["device_id"] = "mh2000"
self.client.credentials(HTTP_AUTHORIZATION=self.token)
response = self.client.post(self.create_url, data, format='json')
self.assertEqual(response.status_c... | |
# program for the little one to practice spelling (and Spanish!)
import cv2
import enum
import tensorflow as tf
import pandas as pd
import numpy as np
import os
from PIL import Image as im
from translate import Translator
from threading import Thread
from datetime import datetime
# only play the spanish word if found ... | |
# -*- coding: utf-8 -*-
import subprocess
import sys
import json
import tempfile
import requests
import logging
import time
from datetime import datetime
from shapely.geometry import mapping
from pyramid.httpexceptions import HTTPBadRequest
from pyramid_oereb import Config
from pyramid_oereb.lib.renderer.extract.jso... | |
import wx
import wx.lib.mixins.listctrl as listmix
import wx.lib.intctrl
import sys
import os
import re
import six
import time
import math
import json
import threading
import socket
import atexit
import time
import platform
import webbrowser
from six.moves.queue import Queue, Empty
import CamServer
from roundbutton imp... | |
<filename>rampwf/hyperopt/hyperopt.py<gh_stars>0
"""Hyperparameter optiomization for ramp-kits."""
from __future__ import print_function
import re
import os
import shutil
import numpy as np
import pandas as pd
from tempfile import mkdtemp
from ..utils import (
assert_read_problem, import_file, run_submission_on_cv_fo... | |
plans.
* ``codegen``: Print a physical plan and generated codes if they are available.
* ``cost``: Print a logical plan and statistics if they are available.
* ``formatted``: Split explain output into two sections: a physical plan outline \
and node details.
Examples:
>>> ds.explain()
"""
self._data.explain( e... | |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 28 16:35:59 2020
@author: agarwal.270a
"""
#from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
import numpy as np
import time
import matplotlib.pyplot as plt
import sys
import os
from tensorflow.keras import layers
... | |
[subent]
# Inset main menu entries.
self._menu_handler.insert(
MENU_OPTIONS['del'], callback=self._delete_primitive_cb)
self._grasp_menu_entries = []
if self._current_grasp_list:
self._menu_handler.insert(
MENU_OPTIONS['regen'], callback=self._regenerate_grasps_cb)
grasp_choice_entry = self._menu_handler.ins... | |
'chat_id': chat_id,
'user_id': user_id,
}
data = await self._get('kickChatMember', args)
return data
async def leave_chat(self, chat_id: Union[int, str]) -> Awaitable[bool]:
args = {
'chat_id': chat_id,
}
data = await self._get('leaveChat', args)
return data
async def unban_chat_member(self, chat_id: Uni... | |
<filename>grblas/_agg.py<gh_stars>0
from functools import partial
import numpy as np
from . import agg, binary, monoid, semiring, unary
from .dtypes import lookup_dtype, unify
from .matrix import Matrix
from .monoid import any as _any
from .operator import _normalize_type
from .scalar import Scalar
from .ss import di... | |
mode=mode,
save_output=save_output,
output_format=output_format,
structure_style="filenames",
)
def test_mg_z003_mg_z003_v(mode, save_output, output_format):
"""
TEST :model groups (ALL) : test derivation by ext. with all with
base=empty content
"""
assert_bindings(
schema="msData/modelGroups/mgZ003.xsd",
... | |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is govered by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
"""Tests for the ast2select module."""
import datetime
import time
import unittest
from framew... | |
import pkgutil
import traceback
import re
import sys
from os import path
import types
import threading
__running = {}
REPOS = ['https://github.com/martinpihrt/OSPy-plugins/archive/master.zip'] # repository with plugins
################################################################################
# Plugin Options #... | |
<reponame>robszewczyk/openweave-tlv-schema
#!/usr/bin/env python3
#
# Copyright (c) 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.apa... | |
(self.time_shifts_df.round(1) <= self.time_slider.v_model[0])) | \
((self.time_shifts_df.round(1) >= self.time_slider.v_model[1]) &
(self.time_shifts_df.round(1) <= self.time_slider.max))
else:
boolean_time_shifts = ((self.time_shifts_df.round(1) >= self.time_slider.v_model[0]) &
(self.time_shifts_df.round(1) <= s... | |
<filename>yaxil/__init__.py
import io
import os
import csv
import sys
import gzip
import json
import time
import arrow
import random
import sqlite3
import zipfile
import logging
import requests
from requests_toolbelt.adapters.socket_options import TCPKeepAliveAdapter
import itertools
import getpass as gp
import tempfil... | |
t_chunks.pop()
t_chunks[-1] = np.hstack([t_chunks[-1], last_chunk])
n_chunks = len(t_chunks)
self.logger.info(
f"simulate with n_times_per_chunk={n_times_per_chunk}"
f" n_times={len(t)} n_chunks={n_chunks}")
# construct the simulator payload
def data_generator():
with simobj.mapping_context(
mapping=mapping, ... | |
increase the
overall speed.
:param skip_save_processed_input: (bool, default: `False`) if input
dataset is provided it is preprocessed and cached by saving an HDF5
and JSON files to avoid running the preprocessing again. If this
parameter is `False`, the HDF5 and JSON file are not saved.
:param output_directory: ... | |
<gh_stars>0
# -*- coding: utf-8 -*-
# Copyright 2015 <NAME> <<EMAIL>>
#
# 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... | |
- At first object of list...'
else:
newent = np.where(self.objlist == self.currentobj)[0]-1
self.currentobj = self.objlist[newent][0]
self.openpngs()
self.labelvar.set(self.infostring())
self.updateimage()
if self.Npa != 2: self.checkboxes2(self.cbpos2,disable=True) # disable checkboxes2 if Npa not 2
# load ne... | |
copying pass
"""
if self in memo:
return memo[self]
robot = memo.get(self.robot, self.robot) # copy.deepcopy(self.robot, memo)
joints = copy.deepcopy(self.joints)
bounds = copy.deepcopy(self.bounds)
kp = copy.deepcopy(self.kp)
kd = copy.deepcopy(self.kd)
max_force = copy.deepcopy(self.max_force)
discrete_valu... | |
<gh_stars>1-10
"""
Script to verify all examples in the readme.
Run from the project directory (i.e. parent) with
python test_readme_examples.py
"""
from __future__ import print_function, division
#import sys
#import os
#sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import numpy as np
from scipy imp... | |
to also check if the `to` value is None
has_more = False
logger.info(f"No more results left to retrieve, ending loop after {loop_counter} iterations")
return results
else:
offset = response.get('to')
sleep_counter = 0
logger.debug(f"Results: {response}")
results.append(deepcopy(response))
logger.info(f"Loop c... | |
#!/usr/bin/env python
#
# Copyright (c) 2019 by VMware, Inc. ("VMware")
# Used Copyright (c) 2018 by Network Device Education Foundation, Inc. ("NetDEF")
# in this file.
#
# Permission to use, copy, modify, and/or distribute this software
# for any purpose with or without fee is hereby granted, provided
# that the abov... | |
in Refs:
if k in D:
#print"k is", k, "value", D[k]
D[k] = document.Reference(D[k])
dict = PDFDictionary(D)
return format(dict, document)
def showOutline(self):
self.setPageMode("UseOutlines")
def showFullScreen(self):
self.setPageMode("FullScreen")
def setPageLayout(self,layout):
if layout:
self.PageLayo... | |
normalize):
self.normalize = normalize
def forward(self, input):
if self.mode == 'loss':
loss = self.crit(input, self.target)
if self.normalize:
loss = ScaleGradients.apply(loss, self.strength)
self.loss = loss * self.strength
elif self.mode == 'capture':
self.target = input.detach()
return input
########... | |
# (c) British Crown Copyright 2020, the Met Office.
# 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 cond... | |
use bsmBI
tail = 'taaattCGTCTCA'
return bsmBI, tail, 2
if not bseFlag:
# use bsmBI
tail = 'taaattGAGGAGattcccta'
return bseRI, tail, 1
return 0, 0, 0
#given a parent plasmid and a desired product plasmid, design the eipcr primers
#use difflib to figure out where the differences are
#if there is a convenient re... | |
from flopter.core.ivanalyser import IVAnalyser
import numpy as np
import pathlib as pth
import matplotlib.pyplot as plt
import flopter.magnum.adcdata as md
import flopter.core.ivdata as iv
import pandas as pd
import scipy.signal as sig
import xarray as xr
# import flopter.databases.magnum as mag
import flopter.magnum.r... | |
Liquid Densities of Normal Fluids."
AIChE Journal 24, no. 6 (November 1, 1978): 1127-31.
doi:10.1002/aic.690240630
'''
Tr = T/Tc
if Tr <= 0.98:
lnU0 = 1.39644 - 24.076*Tr + 102.615*Tr**2 - 255.719*Tr**3 \
+ 355.805*Tr**4 - 256.671*Tr**5 + 75.1088*Tr**6
lnU1 = 13.4412 - 135.7437*Tr + 533.380*Tr**2-1091.453*Tr**3... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Tree structure in `treelib`.
The :class:`Tree` object defines the tree-like structure based on :class:`Node` objects.
A new tree can be created from scratch without any parameter or a shallow/deep copy of another tree.
When deep=True, a deepcopy operation is performed... | |
<filename>ddc_packages/hddump/hddump/hddumpMain.py
"""
Demonstration handle dump for CMIP/ESGF files ..
USAGE
=====
-h: print this message;
-v: print version;
-t: run a test
-f <file name>: examine file, print path to replacement if this file is obsolete, print path to sibling files (or replacements).
-id <track... | |
<filename>django_tables/tests/test_models.py
"""Test ModelTable specific functionality.
Sets up a temporary Django project using a memory SQLite database.
"""
from unittest.mock import Mock
from nose.tools import assert_raises, assert_equal
from django.conf import settings
from django.core.paginator import Paginator,... | |
# Copyright 2020 The DDSP Authors.
#
# 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... | |
<reponame>ArenaNetworks/dto-digitalmarketplace-api
from flask import json
import mock
from freezegun import freeze_time
from nose.tools import assert_equal, assert_not_equal, assert_in, assert_is_none
from app import db, encryption
from app.models import Address, User, Supplier, Application, Brief
import pendulum
from ... | |
# Copyright 2019 the V8 project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can
# be found in the LICENSE file.
# This file is automatically generated by mkgrokdump and should not
# be modified manually.
# List of known V8 instance types.
INSTANCE_TYPES = {
0: "INT... | |
from exif_read import ExifRead
import json
import os
import urllib2
import urllib
import httplib
import datetime
import socket
import mimetypes
import random
import string
import copy
from Queue import Queue
import threading
import time
import config
import getpass
import sys
import processing
import requests
from tqdm... | |
# mask[3] tells us whether there's a gap 2 tiles to the right - which means the next tile will be sprite 2
if previous_mid_segment == 4 and mask[3]:
return 5, None
else:
# Alternate between 3 and 4
if previous_mid_segment == None or previous_mid_segment == 4:
sprite_x = 3
elif previous_mid_segment == 3:
sprite_... | |
"LD B,B", 1),
0x41 : (0, [ LDrs('B', 'C'), ], [], "LD B,C", 1),
0x42 : (0, [ LDrs('B', 'D'), ], [], "LD B,D", 1),
0x43 : (0, [ LDrs('B', 'E'), ], [], "LD B,E", 1),
0x44 : (0, [ LDrs('B', 'H'), ], [], "LD B,H", 1),
0x45 : (0, [ LDrs('B', 'L'), ], [], "LD B,L", 1),
0x46 : (0, [], [ MR(indirect="HL", action=LDr("B")... | |
<filename>statsmodels/gam/tests/results/results_mpg_bs.py
import numpy as np
class Bunch(dict):
def __init__(self, **kw):
dict.__init__(self, kw)
self.__dict__ = self
mpg_bs = Bunch()
mpg_bs.smooth0 = Bunch()
mpg_bs.smooth0.term = 'weight'
mpg_bs.smooth0.bs_dim = 12
mpg_bs.smooth0.dim = 1
mpg_bs.smooth0.p_ord... | |
= Error.from_json(error) if error else None
result_ = [FilesystemDetails.from_json(o) for o in result or []]
# Validate arguments against known Juju API types.
if error_ is not None and not isinstance(error_, (dict, Error)):
raise Exception("Expected error_ to be a Error, received: {}".format(type(error_)))
if r... | |
<reponame>bgraedel/arcos4py
"""Module to plot different metrics generated by arcos4py functions.
Examples:
>>> # Data Plots
>>> from arcos4py.plotting import dataPlots
>>> data_plots = dataPlots(df,'time', 'meas', 'track_id')
>>> hist = data_plots.histogram()
>>> dens = data_plots.density_plot()
>>> xt_p... | |
<reponame>ekwska/ffai
#!/usr/bin/env python3
import ffai
from ffai import Action, ActionType, Square, BBDieResult, Skill, PassDistance, Tile, Rules, Formation, ProcBot
import ffai.ai.pathfinding as pf
import time
class MyScriptedBot(ProcBot):
def __init__(self, name):
super().__init__(name)
self.my_team = None
... | |
<filename>nlp.py
import requests
import xml.etree.ElementTree as xET
import csv
import random
import re
from library import HackerLibrary
from database import DataBase
class LuisAI:
NLP_REGION = 'westus'
NLP_SUBSCRIPTION_KEY = '19da1eb81e9740dd888d0eb4af6ca042'
NLP_APP_ID = 'b5365948-56b0-46bb-b58c-05d5a1ab3a59'
... | |
from anytree import Node, RenderTree, PreOrderIter
import random as rnd
from matplotlib import pyplot as plt
import datetime
# Tic Tac Toe Stats and Game simulator.
# Allows us to estimate for arbitrary grid sizes whether there is a first mover advantage or not.
# Also allows us to estimate which is the best grid refe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.