input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/04_template.blocks.ipynb (unless otherwise specified).
__all__ = ['Block', 'MolBlock', 'ConstantBlock', 'ConstantMolBlock', 'BlockTemplate', 'RGroupBlockTemplate',
'DoubleRGroupBlockTemplate', 'LinkerBlockTemplate', 'ScaffoldBlockTemplate']
# Cell
from ..imports import... | |
postCellId="../AIZL/0/"/>
</projection>
<projection id="NC_HSNR_AIZR_Serotonin_Acetylcholine" postsynapticPopulation="AIZR" presynapticPopulation="HSNR" synapse="">
<connection id="0" preCellId="../HSNR/0/" postCellId="../AIZR/0/"/>
</projection>
<projection id="NC_HSNR_AS5_Serotonin_Acetylcholine" postsynapticPop... | |
from functools import reduce
import time
import math
import copy
import types
import cv2
import numpy as np
import json
from typing import List, Union, Tuple, Any
from ..thresholds.color import built_in_colors
from ..exceptions.exceptions import InvalidCustomFunctionError, CameraError
from ..camera.camera import Camer... | |
import gevent
import pytest
from raiden.api.python import RaidenAPI
from raiden.app import App
from raiden.storage.sqlite import RANGE_ALL_STATE_CHANGES
from raiden.tests.utils.detect_failure import raise_on_failure
from raiden.tests.utils.events import (
raiden_events_search_for_item,
search_for_item,
wait_for_rai... | |
<reponame>discoverygarden/dgi_repo<gh_stars>0
"""
Functions to help with FOXML.
"""
import logging
import base64
from io import BytesIO
import os
try:
from os import scandir as scandir
except ImportError:
from scandir import scandir
import requests
from lxml import etree
from psycopg2 import IntegrityError
from psyc... | |
import math
import re
from collections import defaultdict
from GlyphsApp import Glyphs, OFFCURVE, GSLayer
from Foundation import NSPoint
class layerPositions:
def __init__(self, l, all_indic_headlines=None):
self.layer = l
self.layer_flat = l.copyDecomposedLayer()
self.layer_flat.removeOverlap()
try:
self.ita... | |
(class + entity_name)."""
return mapper_registry[self.class_key]
def is_assigned(self, instance):
"""Return True if this mapper handles the given instance.
This is dependent not only on class assignment but the
optional `entity_name` parameter as well.
"""
return instance.__class__ is self.class_ and getattr(... | |
if len(pol['btn_points']):
pol['btn_points'][self.index].state = 'down'
else:
self.remove_gap(pol)
self.pol = None
self.index = None
except (LookupError, TypeError) as er:
print('on remove_point: ', er)
else:
if state:
self.save_state('Removed point {} from polygon {}'
.format(i, p))
self.draw()
def remov... | |
"""
Copyright 2019 by <NAME> (alohawild)
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, ... | |
ImportError: no flate decompressor in Python.
zd = zlib.decompressobj()
elif compress_algo == 3:
import bz2 # ImportError: no bzip2 decompressor in Python.
zd = bz2.BZ2Decompressor()
else:
raise ValueError('Unknown compress_algo: %d' % compress_algo)
zdml = None
if zd:
zd_decompress = zd.decompress
try:
zd_d... | |
# # if query failed, refresh school info
# if not user_conf_dict:
# # school info not exist, refresh this school; # {user_name:'',schl_abbr:'', 'open_time':'', school_name:'', classroom:[{'classroom_name':classroom_name,'libid':libid, 'path':classroom_path,'seat_map':''},{},{}...]}
# user_conf_dict = crawldata.refre... | |
setting up the rfmstruct is collecting
# all the information needed to automatically generate it.
# Step 5 and onwards implements this algorithm, using the
# *generic functional form* of the hatted quantities (as
# opposed to the exact closed-form expressions of the
# hatted quantities) computed above.
# Step 5:... | |
# Day 6 Python for chemists
import os
import sys
import csv
import numpy as np
import matplotlib.pyplot as plt
def read_file(path):
"""
Arguments is the path to the file
reads a text file input of x and y coordinates and returns the values as a
2 dimensional array
"""
# open the file in read... | |
Iii1 . action == LISP_SEND_MAP_REQUEST_ACTION ) :
if 75 - 75: II111iiii . O0 . I1Ii111 * O0 / OoooooooOO
if 60 - 60: OOooOOo - Oo0Ooo * OOooOOo / OoO0O00
if 55 - 55: I1ii11iIi11i * II111iiii * iIii1I11I1II1
if 38 - 38: iIii1I11I1II1 % I1ii11iIi11i . Ii1I + I1IiiI % i11iIiiIii - i11iIiiIii
if 62 - 62: I1Ii111 + I1I... | |
<reponame>rpatil524/t2wml<filename>backend/causx/country_entities.py
country_entities={
"Q1000": {
"description": "equatorial country in West Africa",
"label": "Gabon"
},
"Q1005": {
"description": "sovereign state in West Africa",
"label": "The Gambia"
},
"Q1006": {
"description": "sovereign state in West Afr... | |
<reponame>samwaseda/clartbeat
import numpy as np
from scipy import ndimage
from scipy.spatial import cKDTree
from sklearn.cluster import DBSCAN
from clartbeat.area import Area
import matplotlib.pylab as plt
from scipy.spatial import ConvexHull
from skimage import feature
from skimage import filters
from sklearn.cluster... | |
except:
raise Exception('Failed to generate lidar DEM to estimate height range!')
minHeight = lidarMin
maxHeight = lidarMax
# Get the min/max height in the reference DEM region
# - The lidar field is narrower than the image so sometimes it can miss terrain features
# that show up in the lower resolution DEM.
t... | |
IDD field `Relative Ratios of Air Flow Rates Passing
through Zone 7`"""
self[
"Relative Ratios of Air Flow Rates Passing through Zone 7"] = value
@property
def cross_sectional_areas_of_air_channel_inlet_7(self):
"""field `Cross Sectional Areas of Air Channel Inlet 7`
| Units: m2
Args:
value (float): value f... | |
hasattr( listener, "enterSymbolPlusTail" ):
listener.enterSymbolPlusTail(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitSymbolPlusTail" ):
listener.exitSymbolPlusTail(self)
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitSymbolPlusTail" ):
return visitor... | |
<reponame>SwampDolphin97/Social_Networking_Website<gh_stars>0
from flask import Flask, flash, app, request, session, render_template, url_for,\
logging, redirect
from wtforms import Form, StringField, TextAreaField, PasswordField, validators
from passlib.hash import sha256_crypt
from functools import wraps
from datetim... | |
"清新", "fresh", 1939],
["Mohu", "模胡", "fuzzy", 1935],
["Konghuang", "恐慌", "scared", 1919],
["Kaixin", "开心", "happy", 1917],
["Gaowei", "高位", "high level", 1910],
["Koutou", "口头", "oral", 1902],
["Kaikuo", "开阔", "open", 1889],
["Hemu", "和睦", "harmonious", 1888],
["Youyong", "有用", "useful", 1887],
["Yanming", "严明... | |
consumable supplies & those which will get turned into Assets at their destination.': 'Itens de invenrário incluem ambos suprimentos consumíveis & aqueles que se transformarão em Ativos no seu destino.',
'Inventory Management': 'Gerenciamento de Inventário',
'Inventory Stock Position': 'Inventory Stock Position',
'I... | |
<filename>filmatyk/filmweb.py
from datetime import date
import binascii
import html
import json
import pickle
from bs4 import BeautifulSoup as BS
import requests_html
import containers
ConnectionError = requests_html.requests.ConnectionError
class UnauthenticatedError(ConnectionError):
"""Raised by API functions... | |
self.AddLayer(self.DrawPolygonLayer, draw_data, map_rel,
visible=visible, show_levels=show_levels,
selectable=selectable, name=name,
type=self.TypePolygon, update=update)
def AddImageLayer(self, data, map_rel=True, visible=True,
show_levels=None, selectable=False,
name='<image_layer>', **kwargs):
"""Add a layer... | |
<reponame>tobspr/Panda3D-Bam-Exporter
# -*- encoding: utf-8 -*-
import os
import bpy
import time
import math
import mathutils
from ExportException import ExportException
from TextureWriter import TextureWriter
from GeometryWriter import GeometryWriter
from MaterialWriter import MaterialWriter
from pybamwriter.panda_ty... | |
'''
Feature Extraction and Image Processing
<NAME> & <NAME>
http://www.southampton.ac.uk/~msn/book/
ImageRegionUtilities: Helper module to process regions and line segments
'''
# Images
from ImageUtilities import imageReadL, createImageF, createImageL, showImageL, createVectorF
from ImageOperatorsUtilities import ap... | |
<filename>bot.py
""" Copyright (c) 2021 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.1 (the "License"). You may obtain a copy of the
License at
https://developer.cisco.com/docs/licenses
All use of the material herein must be in accordance wit... | |
% (basename,
' '.join(sorted(project_names))))
else:
raise BadArgsError(
'No such Project "%s". There are no Projects in the current Folder.'
% basename)
def _LookupFolder(state, argument):
"""Returns the specified Folder and its parent Container.
Args:
state: State
argument: basestring
Returns:
Folder
R... | |
tenant_id from parent namespace cache.
tenant_id = self._parent_class.tenant_id
elif not tenant_id:
# No value for tenant_id.
raise TypeError("tenant_id is required but not set or cached.")
cur_ctlr = self._parent_class.controller
url = str(cur_ctlr) + "/{}/api/tenants/{}/accounts/password/change".format(api_ver... | |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import numpy as np
import pandas as pd
import random
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.keras.layers import Dense,Flatten,GlobalAveragePooling2D,Input,Lambda
from tensorflow.keras.models import Model,load_model
import tensorflow.kera... | |
from __future__ import print_function, division
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from train_steering_wheel.train import (
MODEL_HEIGHT as CNN_MODEL_HEIGHT,
MODEL_HEIGHT as CNN_MODEL_WIDTH,
ANGLE_BIN_SIZE as CNN_ANGLE_BIN_SIZE,
extract_steering_wheel_image as cnn_... | |
<reponame>slayer96/keepa
"""Interface module to download Amazon product and history data from
keepa.com
"""
from tqdm import tqdm
import aiohttp
import asyncio
import datetime
import json
import logging
import numpy as np
import pandas as pd
import time
from keepa.query_keys import DEAL_REQUEST_KEYS, PRODUCT_REQUEST_... | |
Node category (ACTIVE|INACTIVE|MIGRATION|TEST|DUPLICATE|INTEGRATED) (optional)
:param configuration: The configuration as a JSON hash of key values pairs (optional)
:param ctc_bucket: Name of the S3 bucket to use for a cloud to cloud gateway (optional)
:param facility_contact: Name of the facility contact (optional)... | |
<filename>pyFileFixity/lib/profilers/memory_profiler/memory_profiler.py
"""Profile the memory usage of a Python program"""
# .. we'll use this to pass it to the child script ..
_clean_globals = globals().copy()
__version__ = '0.31'
_CMD_USAGE = "python -m memory_profiler script_file.py"
import time
import sys
impor... | |
"""Definitions and implementations for data-path expressions to query and manipulate (insert, update, delete)."""
from . import urlquote
import copy
from datetime import date
import itertools
import logging
import re
from requests import HTTPError
import warnings
__all__ = ['DataPathException', 'Min', 'Max', 'Sum', '... | |
from enum XlChartType
xlSurfaceWireframe = 84 # from enum XlChartType
xlXYScatter = -4169 # from enum XlChartType
xlXYScatterLines = 74 # from enum XlChartType
xlXYScatterLinesNoMarkers = 75 # from enum XlChartType
xlXYScatterSmooth = 72 # from enum XlChartType
xlXYScatterSmoothNoMarkers = 73 # from enum XlChartT... | |
import os
from cs50 import SQL
from flask import Flask, flash, jsonify, redirect, render_template, request, session, url_for
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
from werkzeug.security import check_password... | |
<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 15 10:32:22 2018
@author: Shin2018
"""
import numpy as np
def generate_traindata_for_train(traindata_all,traindata_labels,input_size,label_size,batch_size,Setting02_AngualrViews):
"""
input: traindata_all (16x512x512x9x9x3) uint8
traindata_label (16x5... | |
<gh_stars>1-10
from copy import copy
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type, cast
from pypika import Table
from pypika.terms import Criterion
from tortoise.exceptions import FieldError, OperationalError
from tortoise.fields.relational import BackwardFKRelation, ManyToManyFieldInstanc... | |
six.iterkeys(kwargs) if _key not in expected_kwargs]
if extra_kwargs:
raise ValueError(
"create_folder got unknown kwargs: {!r}".format(extra_kwargs))
path_params = {
"catalogId": catalog_id,
"dataAssetKey": data_asset_key
}
path_params = {k: v for (k, v) in six.iteritems(path_params) if v is not missing}
f... | |
<filename>spots_objects.py
import glob
import io
import os
import json
import subprocess
import html
import logging
import spotipy
import spotipy.util as util
from jinja2 import Environment, PackageLoader, select_autoescape
# Keywords for use in the HTML template
# (key is Jinja variable name,
# value is Jinja varia... | |
<reponame>tarrade/proj_NLP_text_classification_with_GCP
"""
Created on Wed Nov 7 2018
@author: <NAME> <EMAIL>
<NAME> <EMAIL>
<NAME> <EMAIL>
"""
import numpy as np
from sklearn.base import BaseEstimator, ClassifierMixin, TransformerMixin
from sklearn.utils.validation import check_is_fitted
from sklearn.utils.multicla... | |
<reponame>jovial/refstack
# Copyright (c) 2015 Mirantis, 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 ... | |
string
:param ParameterGroupName: **[REQUIRED]**
The name of the parameter group to be deleted.
Constraints:
* Must be the name of an existing cluster parameter group.
* Cannot delete a default cluster parameter group.
:returns: None
"""
pass
def delete_cluster_security_group(self, ClusterSecurityGroupName: s... | |
fullchain_dest: /etc/httpd/ssl/sample.com-fullchain.crt
register: sample_com_challenge
# Alternative first step:
- name: Create a challenge for sample.com using a account key file.
acme_certificate:
account_key_src: /etc/pki/cert/private/account.key
csr: /etc/pki/cert/csr/sample.com.csr
dest: /etc/httpd/ssl/sampl... | |
'return_failure_list': [ return_failure_list, 'return-failure-list', [ bool, 'None' ], False ],
'query': [ query, 'query', [ SnapmirrorInfo, 'None' ], False ],
}, {
'num-succeeded': [ int, False ],
'num-failed': [ int, False ],
'success-list': [ SnapmirrorPromoteIterInfo, True ],
'failure-list': [ SnapmirrorPromo... | |
import os
from os.path import getsize
import logging
import sys
import copy
import clique
import errno
import six
from pymongo import DeleteOne, InsertOne
import pyblish.api
from avalon import io
from avalon.vendor import filelink
# this is needed until speedcopy for linux is fixed
if sys.platform == "win32":
from s... | |
dataset_0
Id: 6
Wavelength: 10
Number of columns: 2
label #valid %valid min max type
column_9 0 0.00% None None B: BATCH number
column_10 0 0.00% None None ?: *** UNDEFINED column type ***
Dataset 2:
Name: dataset_1
Id: 7
Wavelength: 9
Number of columns: 3
label #valid %valid min max type
column_11 0 0.00%... | |
sibling hidden state and add to parent state
# This way we can choose to add some sibling information in parent information
# Think about the case when there are two func declarations,
# without this add gate, e.g. the function names would get exactly the same parent state
sibling_mul_state = self.sigmoid(self.W_s... | |
# INFO : ini merupakan copy source code dari repo one4ubot, dan sudah mendapatkan izin dari pemilik.
# INFO : This is a copy of the source code from the One4ubot repo, and has the permission of the owner.
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.d ... | |
<filename>src/medigan/generators.py<gh_stars>1-10
# -*- coding: utf-8 -*-
# ! /usr/bin/env python
""" Base class providing user-library interaction methods for config management, and model selection and execution.
.. codeauthor:: <NAME> <<EMAIL>>
.. codeauthor:: <NAME> <<EMAIL>>
"""
# Import python native libs
from _... | |
visibility.
# TODO: Let renderer actually use the visibility to decide whether to render or not.
def isVisible(self) -> bool:
if self._parent is not None and self._visible:
return self._parent.isVisible()
else:
return self._visible
## Set the visibility of this SceneNode.
def setVisible(self, visible: bool) ->... | |
import ctypes
import numpy
from numpy.ctypeslib import ndpointer
import pkg_resources
import enum
import os
import platform
import sys
import struct
import json
from typing import List, Set, Dict, Tuple
from nptyping import NDArray, Float64
from brainflow.exit_codes import BrainflowExitCodes
class BoardIds(enum.Int... | |
import math
from itertools import combinations
from collections import namedtuple, defaultdict
import cvxpy as cvx
import numpy as np
import numpy.linalg as LA
import scipy.optimize
import matplotlib.pyplot as plt
PI2 = math.pi * 2
MAX_ANGLE = PI2 / 8 / 10
cmap = plt.get_cmap("brg")
def vp_from_lines(x1, y1, x2, y2... | |
"""
"MooseGesture 0.1" a mouse gestures recognition library.
<NAME> <EMAIL>
http://coffeeghost.net/2011/05/09/moosegesture-python-mouse-gestures-module
Usage:
import moosegesture
gesture = moosegesture.getGesture(points)
Where "points" is a list of x, y coordinate tuples, e.g. [(100, 200), (1234, 5678), ..... | |
from __future__ import print_function
import os
import re
import subprocess
import io
import threading
import shlex
import sys
import shutil
import filecmp
from optparse import OptionParser
import stat
import glob
import platform
import zipfile
from xml.dom.minidom import parse
import contextlib
def abort(msg):
"""P... | |
db_refs={'HGNC': '7989'},
bound_conditions=[BoundCondition(gtp1, True)])
nrasgtp2 = Agent('NRAS', db_refs={'HGNC': '7989'},
bound_conditions=[BoundCondition(gtp2, True)])
st1 = Phosphorylation(src, nrasgtp1, 'tyrosine', '32')
st2 = Phosphorylation(src, nrasgtp2, 'tyrosine', '32')
# The top-level list should conta... | |
#
# Copyright 2021-2022 <NAME>
# 2021 <NAME>
#
# ### MIT license
#
# 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 rights
# to use, copy,... | |
import sys
sys.path.append('..')
import copy
import numpy as np
import sys
import random
import config
import threading
from warnings import simplefilter
from datetime import datetime
from sklearn import metrics
from agent import Agent
from message import Message
from utils.dp_mechanisms import laplace
import utils.... | |
latency data
is now available as Distribution Metrics. Existing monitors have been migrated automatically but all terraformed
monitors can still use the existing metrics. We strongly recommend updating monitor definitions to query the new
metrics. To learn more, or to see examples of how to update your terraform def... | |
now
# Set the path if applicable
if '_path' in session_data:
self._path = session_data['_path']
self.update(session_data)
self.accessed_dict = session_data.copy()
finally:
self.namespace.release_read_lock()
if timed_out:
self.invalidate()
def save(self, accessed_only=False):
"""Saves the data for this sess... | |
<reponame>andyzt/convai_router_bot
import json
import os
import random
from collections import defaultdict
from datetime import datetime, timedelta
from typing import TextIO
from uuid import uuid4
import yaml
from mongoengine import errors, QuerySet
from mongoengine.queryset.visitor import Q
from . import... | |
df_all[curc]=buffer
df_all[curc]=df_all.groupby('trade_date')[curc].rank(pct=True)
#df_all[curc]=df_all[curc]*9.9//2
df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','real_price_pos'],1)
df_all=FEsingle.OldFeaturesRank(df_all,['sm_amount','lg_amount','net_mf_amount'],1)
df_all=FEsingle.Old... | |
is the rebinning factor, e.g it returns::
xr = array([x[k*pack:k*(pack+1)].sum()/pack for k in range(int(floor((stop-start)/pack)))])
strstp = [start,stop] is a list of slice indices
rebinning of x, y [,e] is done on the slice truncated to the approrpiate pack multiple, stopm
x[start:stopm], y[start:stopm], ... | |
<reponame>dendisuhubdy/tomlplusplus<gh_stars>0
#!/usr/bin/env python3
# This file is a part of toml++ and is subject to the the terms of the MIT license.
# Copyright (c) 2019-2020 <NAME> <<EMAIL>>
# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
import sys
import re
import os... | |
be
parsed by :func:`time.strptime` or if it returns a value which isn't a
time tuple.
Class attributes:
.. attribute:: min
The earliest representable :class:`DateTime`.
.. attribute:: max
The latest representable :class:`DateTime`.
.. attribute:: resolution
The smallest possible difference between non-e... | |
= self.elements
if empty in self.show.flatten(): # not even finished yet
return False
for i in range(n ** 2):
if elements != set(self.submatrix(i + 1).flatten()):
return False
elif elements != set(self.row(i).flatten()):
return False
elif elements != set(self.col(i).flatten()):
return False
return True
def... | |
<reponame>0x326/clingo<filename>examples/clingo/robots/visualize.py
#!/usr/bin/env python
import clingo
try:
import Tkinter
except ImportError:
import tkinter as Tkinter
# {{{1 class Board
class Board:
def __init__(self):
self.size = 1
self.blocked = set()
self.barriers = set()
self.targets = set()
self.pos =... | |
{
i.split("== ")[-1][1:-2]: {
"ylim": tt.split("\n")[n + 1].split("=")[-1].split()[0:2]
}
for (n, i) in enumerate(tt.split("\n"))
if "==" in i
}
def gas_plot(self):
gas = self.par
if "N2" in gas:
ms = "^"
alpha = 0.6
elif "O2" in gas:
ms = "o"
alpha = 0.9
else:
ms = "*"
alpha = 0.4
# return ms, alpha... | |
# Copyright 2021, <NAME>, mailto:<EMAIL>
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtai... | |
"""
This is an object-orient plotting library.
A procedural interface is provided by the companion pylab module,
which may be imported directly, e.g::
from pylab import *
or using ipython::
ipython -pylab
For the most part, direct use of the object-oriented library is
encouraged when programming rather than work... | |
Relation fields
Accomplishes: RelationField = RelationField(
name='Accomplishes',
rule='min 1 Task',
inverse_of=['Is_Accomplished_By'],
semantic_manager=semantic_manager)
"""
A Relationship Between A Certain Entity (E.G., A Device) And The Task It
Accomplishes
"""
Consists_Of: RelationField = RelationFi... | |
<gh_stars>1-10
import praw
import prawcore
import postgresConfig
import psycopg2
import time
import unidecode
import os
# COMMENT THIS OUT FOR PRODUCTION
#import config
def authenticate():
is_prod = os.environ.get('IS_HEROKU', None)
# grab all user configs from the config file
# Note: File is not shared to reduce... | |
c = atoms.get_cell()[2][2] / self.properties[structure + '_size'][2]
self.values[('lattice_constant_a', structure, elements)] = a
self.values[('lattice_constant_c', structure, elements)] = c
#self.latticeconstants[(structure, elements)] = [a, c]
E = atoms.get_potential_energy() / len(atoms)
self.values[('energy',... | |
line options
which have arguments ('--my-opt somepath') we might get some
false positives. All builtin and 3rd party plugins will have
been loaded, however, so common options will not confuse our logic
here.
"""
current = py.path.local()
self._confcutdir = (
current.join(namespace.confcutdir, abs=True)
if name... | |
grp --> list, groups to which the user belogns
Returns
-------
(file['_id'], file_id, h, inserted_documents, updatedone_documents, deletedone_documents) --> tuple(bson.objectid.ObjectId class, bson.objectid.ObjectId class, list, list, list, list), the source object id, the destination object id, the list of the da... | |
'async with'"):
await python_script.stderr(CAPTURE)
async def test_redirect_error_to_logger(python_script, capfd, caplog):
"Test redirection options with both stdout and stderr output (logger)."
test_logger = logging.getLogger("test_logger")
result = await python_script.stderr(test_logger)
assert result == "hi s... | |
+ m.x1308 + m.x1408 + m.x1508 + m.x1608 + m.x1708 + m.x1808
+ m.x1908 + m.x2008 + m.x2108 + m.x2208 + m.x2308 + m.x2408 + m.x2508 + m.x2608 + m.x2708
+ m.x2808 + m.x2908 == 1)
m.c3010 = Constraint(expr= m.x9 + m.x109 + m.x209 + m.x309 + m.x409 + m.x509 + m.x609 + m.x709 + m.x809 + m.x909
+ m.x1009 + m.x1109 + m.x12... | |
<gh_stars>1000+
# -*- coding: utf-8 -*-
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
import base64
import logging
import sys
import inspect
import re
import traceback
import json
from functools import partial
import numpy as np
... | |
)
#-------------------------------------------------------------------------------
# Name: nodeInfo()
# Role: Return a dictionary having the primary key being the unique
# node names, and the values being the associated configID
# for each node.
# History:
# when who ver what
# -------- --- ---- ----------
# 10/04/16... | |
<reponame>ecoo-app/ecoo-backend
import base64
import secrets
import string
from enum import Enum
from urllib.parse import urlencode
import pysodium
import pytezos
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.db import mod... | |
<chord>
... <duration base="1/2"/>
... <lyric>
... <verse i="0">das,</verse>
... <verse i="1">scherz,</verse>
... </lyric>
... <heads>
... <head pitch="G4"/>
... </heads>
... </chord>
... <chord>
... <duration base="1/2"/>
... <lyric>
... <verse i="0">so</verse>
... <verse i="1">der</verse>
... </lyric>
... | |
<filename>code/player.py
#<NAME>
#Settlers of Catan, 2020
#Imports
from board import *
import numpy as np
#Class definition for a player
class player():
'Class Definition for Game Player'
#Initialize a game player, we use A, B and C to identify
def __init__(self, playerName, playerColor):
self.name = playerName
... | |
#
logger.debug("%s journal abbreviation issn %r current %r normalized %r", rcsbId, issn, curAbbrev, revAbbrev)
cObj.setValue(revAbbrev, atName, ii)
return True
except Exception as e:
logger.exception("Failing for %r with %s", dataContainer.getName(), str(e))
return False
def __updateJournalAbbreviation(self, rc... | |
if not resource:
return None
res = job_pb2.RunAlphaJobTemplateTemplateContainersEnvValueSourceSecretKeyRef()
if Primitive.to_proto(resource.secret):
res.secret = Primitive.to_proto(resource.secret)
if Primitive.to_proto(resource.version):
res.version = Primitive.to_proto(resource.version)
return res
@classmet... | |
database."""
if self.partials_display_pw.pane(self.partials_pw, "weight"):
# Size is assumed to be (1,1) as created at first call and grid
# will be filled after <Configure> event to size the widget.
# Subsequent calls are not associated with a <Configure> event so
# fill the widget by after_idle(...).
if self.b... | |
for h in self.head:
r = Record(datfile = self.datfile,
idstr = h.strip().replace('<>', '_'))
if not (r.exists() or r.removed()):
try:
res = self.node.talk('/get/%s/%d/%s' %
(self.datfile, r.stamp, r.id))
first = re.sub(r'[\r\n]*$', '', iter(res).next())
yield first
except StopIteration, err:
sys.stderr.write(... | |
the root of the library
path) that indicates the actual resource file.
:param depends: optionally, a list of resources that this resource
depends on. Entries in the list are :py:class:`Resource`
instances.
:param supersedes: optionally, a list of :py:class:`Resource`
instances that this resource supersedes as a... | |
# This file is part of QuTiP: Quantum Toolbox in Python.
#
# Copyright (c) 2011 and later, <NAME> and <NAME>.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source cod... | |
time steps (with interpolation steps and starting point)
nt = xin.shape[1]
# SAVE VERSION OF TRACPY USED
# Save file into a local directory called tracks. Make directory if it
# doesn't exist.
if 'tracks' not in name:
if not os.path.exists('tracks'):
os.makedirs('tracks')
name = 'tracks/' + name
# Open file... | |
roles e.g. 'PI' or 'Co-PI' (note: if the investigator has a Dimensions researcher ID, that is returned as well).",
'long_description':
None,
'is_entity':
False,
'is_filter':
True,
'is_facet':
False
},
'title': {
'type':
'string',
'description':
'Title of the grant in English (if the grant language is not ... | |
= "(" + self.__who_am_i() + ") The passed argument " + \
"'data' is a " + str(type(data))
self.dp.v_debug(message)
message = "(" + self.__who_am_i() + ") The passed argument " + \
"'conffile' is a " + str(type(conffile))
self.dp.v_debug(message)
# End of if self.debug :
for item in data:
if "item" in item:
ke... | |
\"-d, --densityMapFile \" to specify density map file name and try again." % OptionsInfo["Infile"])
DensityMapFile = None
MapFileRoot = "emd_%s" % EMDBID
MapFile1 = "%s.map.gz" % MapFileRoot
MapFile2 = "%s.map" % MapFileRoot
if os.path.exists(MapFile1):
DensityMapFile = MapFile1
elif os.path.exists(MapFile2):
... | |
means sorted oldest to latest, False opposite
:param max_ticks: Only the most recent max_ticks trades. Default None
:param timeout: Wait upto timeout seconds. Default None
:return: A numpy array of dtype HistoryConn.tick_type
HTT,[Symbol],[BeginDate BeginTime],[EndDate EndTime],[MaxDatapoints],
[BeginFilterTime],... | |
0
for line in content:
line = line.split()
if len(line) > 1:
if line[0] == 'Data_store:':
# If another Data Store detected we ensure to keep same
# length of all the elements in the dictionary
self._data_stores = \
self._add_none_to_empty_fields(self._data_stores)
pos = self._how_many_brackets_following(line[2... | |
search(prima_feats, "name", name)
if result is None:
return await bot.say("Feat not found.")
strict = result[1]
results = result[0]
if strict:
result = results
else:
if len(results) == 1:
result = results[0]
else:
result = await get_selection(ctx, [(r["name"], r) for r in results])
if result is No... | |
search for Markdown files and build a cache of `Meta`
from metadata in the Markdown.
:param root: str: The path to search for files from.
"""
doc_files = glob.iglob(root + '/**/*.md', recursive=True)
def _meta(path):
with open(path, 'r', encoding='utf-8') as f:
md = markdown.Markdown(extensions=mdextensions)
m... | |
# April 12, 2019
# <NAME>
from __future__ import division
import sys, os, argparse, operator, numpy, pandas, fuzzysearch
from collections import Counter
## set up parser for user inputs
parser = argparse.ArgumentParser()
optional = parser._action_groups.pop()
required = parser.add_argument_group('required argument... | |
<gh_stars>0
"""
"""
import sqlite3
import numpy as np
import math
class SQL:
def __init__(self):
self.path = None
self.connexion = None
self.cursor = None
self.verbose = False
def to_SQL_type(self, type_, mode = "format"):
"""
Function allowing to convert element type expressed in Python syntax ... | |
def OnStylusButtonDown(self,*args):
"""
OnStylusButtonDown(self: UIElement,e: StylusButtonEventArgs)
Invoked when an unhandled System.Windows.Input.Stylus.StylusButtonDown�attached event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.