input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
"L" or word[1] == "l" :
toGuess = toGuess[:1] + "l" + toGuess[2:]
if word[2] == "L" or word[2] == "l" :
toGuess = toGuess[:2] + "l" + toGuess[3:]
if word[3] == "L" or word[3] == "l" :
toGuess = toGuess[:3] + "l" + toGuess[4:]
if word[1] != "L" and word[1] != "l" and word[2] != "L" and word[2] != "l... | |
conds.append(cond)
return sm.And(*conds)
def passes_cursor(self, cursor: FlowCursor) -> Tuple[
FlowCursor, List['FlowRule'], bool]:
"""
Runs cursor through the rule. If the rule passes,
return a copy of cursor modified to reflect the changes applied
by the rule, along with a list rules this one branches to and
... | |
<gh_stars>1-10
from collections import OrderedDict, namedtuple
from functools import partial
from inspect import isclass
from itertools import product, repeat
import torch
from tqdm import tqdm
from attorch.layers import Elu1
from attorch.losses import PoissonLoss
import datajoint as dj
import numpy as np
from attor... | |
# Accumulator for mean and variance.
self.mean_var_accumulator = variance_util.MeanVarAccumulator()
# Keep track of partial weighted numeric stats.
if has_weights:
# Summary of the weighted quantiles for the values in this feature.
self.weighted_quantiles_summary = make_quantiles_sketch_fn()
# Accumulator for wei... | |
"BLAST progress: Indexing file '%s'..." % (input_file)
record_index = SeqIO.index( input_file, "fasta", key_function=GetRecordACC)
n_records = len( record_index)
print "BLAST progress: Read %i sequence records from file '%s'" % (n_records, input_file)
if n_records <= 0:
sys.stderr.write( "ERROR: No records to p... | |
def inserted_keys_count(self):
return self._inserted_keys_count
def rejected_keys_count(self):
return self._rejected_keys_count
# smart functin that gives you sth you can use to
# get inserted keys
# we should just expose an iterator instead which
# generates the key,values on fly
def keys_set(self):
# let's... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import json
sys.path.insert(0, os.path.abspath('..'))
from helpers import unittest
from pycaustic import Scraper
from pycaustic.errors import InvalidInstructionError
FILE_PATH = os.path.abspath(__file__)
class TestSetup(object):
def setUp(self):
... | |
correct = jnp.any(
jnp.transpose(top_k_pred) == target, axis=0).astype(jnp.float32)
if self.per_position:
return MeanStat.new(correct * target_weight, target_weight)
return MeanStat.new(
jnp.sum(correct * target_weight), jnp.sum(target_weight))
@dataclasses.dataclass
class SequenceTokenCount(Metric):
"""Metric ... | |
we are not combining reports, generate the reports
elif combine_reports is False:
self.generate_report()
campaign_counter += 1
except Exception as e:
print("[!] There was a problem processing campaign ID {}!".format(CAM_ID))
print("L.. Details: {}".format(e))
sys.exit()
def lookup_ip(self, ip):
"""Lookup the ... | |
"XamUserGetUserFlagsFromXUID"
elif id == 0x00000217: funcName = "XamUserGetMembershipTierFromXUID"
elif id == 0x00000218: funcName = "XamUserGetOnlineCountryFromXUID"
elif id == 0x00000219: funcName = "XamUserReadProfileSettings"
elif id == 0x0000021A: funcName = "XamUserWriteProfileSettings"
elif id == 0x0000021B... | |
# importing required modules
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeRegressor
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import KFold, cross_val_score
from sklearn.metrics import roc_auc_score
# ... | |
'''
All ldap operations for test.
@author: quarkonics
'''
from apibinding.api import ApiError
import apibinding.inventory as inventory
import apibinding.api_actions as api_actions
import zstackwoodpecker.test_util as test_util
import account_operations
import config_operations
import os
import inspec... | |
# -*- coding: utf-8 -*-.
from .auth import Auth
from . import config as Config
from .lib.Gen.ttypes import *
from typing import Union, Any, List
from .connections import Connection
from random import randint
import asyncio, json
class Talk(Connection):
_unsendMessageReq = 0
def __init__(self, auth):
super().__in... | |
b2( 0 )
ld = b2( 1 )
st = b2( 2 )
# X stage result mux select
xm_x = b2( 0 ) # don't care
xm_a = b2( 0 ) # Arithmetic
xm_m = b2( 1 ) # Multiplier
xm_p = b2( 2 ) # Pc+4
# Write-back mux select
wm_x = b2( 0 )
wm_a = b2( 0 )
wm_m = b2( 1 )
wm_c = b2( 2 )
# Control signal
s.cs = Wire( Bits20 )
# contr... | |
Record has been edited')
#Update teh vPhysicalMessage to reflecr physicalmessage
#We Must Update the vContactMessage to reflect the value of the contactmessage variable
#we must update vNamesMessage to inlcude the namesmessage
#We must update vRefMessage to reflect The Message Related to refmessage
User.clsPri... | |
7z
# will create relative paths in the archive (via ..):
command=['7z', 'a', '-sfx', WithProperties(sfx_file),
WithProperties('..\\build\\' + install_dir +
'\\*')],
haltOnFailure=True,
name='create sfx archive',
description='create sfx archive')
self.AddStep(FileUpload,
slavesrc=WithProperties(src_file),
mast... | |
5.5,
"delta_FR1_QIB": 0,
"delta_S1_QIB": 0,
"delta_S2_QIB": 0,
"delta_H1_QIB": 0,
"delta_H2_QIB": 5.2,
"eco": 1,
"DM": 860,
"ash": 95,
"OM": 905,
"OMD": 0.66,
"CP": 133,
"CPD": 0.59,
"EE": 30,
"EED": 0.46,
"CF": 284,
"CFD": 0.64,
"NFE": 458,
"NFED": 0.69,
"NDF": 582,
"starch": 0,
"sugar": 80
},
{... | |
import logging
import pytest
import time
from thrift.transport import TSocket
from thrift.transport import TTransport
from tests.common import config_reload
from tests.common.utilities import wait_until
from tests.common.helpers.assertions import pytest_assert as pt_assert
from tests.common.broadcom_data import is_b... | |
u''.join(g(n))
s = a.build_types(f, [int])
assert s.knowntype == unicode
assert s.no_nul
def test_str_split(self):
a = self.RPythonAnnotator()
def g(n):
if n:
return "test string"
def f(n):
if n:
return g(n).split(' ')
s = a.build_types(f, [int])
assert isinstance(s, annmodel.SomeList)
s_item = s.listdef... | |
in all get functions
"""
imin, imax = 0, nr_of_elements - 1
buffer_start, buffer_end = self._set_buffer_limits()
candidate_start, candidate_index, move_buffer = self._choose_next_candidate_index_in_leaf(leaf_start,
self._calculate_key_position(leaf_start,
(imin + imax) / 2,
'l'),
buffer_start,
buffer_end,
imi... | |
RestrictionsAndPrivilegesPolicyDetail
class DateRange(GeneratedsSuper):
__hash__ = GeneratedsSuper.__hash__
subclass = None
superclass = None
def __init__(self, Begins=None, Ends=None, gds_collector_=None, **kwargs_):
self.gds_collector_ = gds_collector_
self.gds_elementtree_node_ = None
self.original_tagname_... | |
locally.
"""
if _get_package_type(package) == PROCESS_WORKFLOW:
return "CWL package defines a [{}] process that uses remote step-processes.".format(PROCESS_WORKFLOW)
requirement = get_application_requirement(package)
req_class = requirement["class"]
req_local = [CWL_REQUIREMENT_APP_BUILTIN, CWL_REQUIREMENT_APP_DO... | |
import copy
from PIL import Image
from PIL import ImageEnhance
from torch.utils.data import DataLoader, Dataset
import torch
import numpy as np
import glob
import torchvision
import matplotlib.pyplot as plt
import random
import cv2
from torchvision import transforms
np.seterr(divide='ignore', invalid='ignore')
def ta... | |
available
only when the following formula is satisfied.
``interval >= 0.0001 + 0.00002 * (number of measurement
channels-1)``
number: Number of samples. Integer expression. 1 to the
following value. Initial value is 1000. For the linear
sampling: ``100001 / (number of measurement channels)``.
For the log samplin... | |
if is_not_amortization:
result.append(bond)
logging.info("After filtering by amortization " + str(len(result)) + " bonds left")
return result
@staticmethod
def filter_bonds_by_offer(bonds_list):
result = []
for bond in bonds_list:
is_not_offer = BondsMOEXFilter.check_not_offer(bond)
if is_not_offer:
result.a... | |
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if oprot._fast_encode is not None and self.thrift_spec is not None:
oprot.trans.write(oprot._fast_... | |
pixbuf along with button's sate.
if widget.state == gtk.STATE_NORMAL:
image = normal_dpixbuf.get_pixbuf()
elif widget.state == gtk.STATE_PRELIGHT:
image = hover_dpixbuf.get_pixbuf()
elif widget.state == gtk.STATE_ACTIVE:
image = press_dpixbuf.get_pixbuf()
# Init size.
image_width = image.get_width()
image_hei... | |
= onos_ctrl.activate()
assert_equal(status, True)
time.sleep(3)
for i in range(0,4):
log_test.info("Sending DHCP Request after DHCP server is up.")
log_test.info('')
new_cip, new_sip = self.dhcp.only_request(cip, mac)
if new_cip == None and new_sip == None:
log_test.info('')
log_test.info("DHCP Request timed o... | |
same IGID group
comment : str; default=''
a comment for the card
"""
paero = PAERO1(pid, caero_body_ids=caero_body_ids, comment=comment)
self._add_paero_object(paero)
return paero
def add_paero2(self, pid: int, orient: str, width: float, AR: float,
thi: List[int], thn: List[int],
lrsb: Optional[int]=None,
l... | |
import argparse
import numpy as np
import scipy
import sklearn.pipeline
from pathlib import Path
from typing import List, Any
from lime.lime_text import LimeTextExplainer
from tqdm import tqdm
import spacy
METHODS = {
'textblob': {
'class': "TextBlobExplainer",
'file': None
},
'vader': {
'class': "VaderExplainer... | |
<reponame>sidhikabalachandar/lig_clash_score<gh_stars>0
"""
Manipulate atom coordinates with matrix operations.
Provides array methods to translate and rotate atoms in a
structure.Structure. The coin of the realm is a four by four numpy array.
The first 3x3 is a rotation matrix, the last 3x1 is translation matrix,
and... | |
str) -> Tuple[str, str]:
""" Function to parse together the FFMPEG command to a string.
This function parses together the FFMPEG command from that data the user entered on the setup page,
and returns that command as well as the converted file path and name.
Args:
ffmpeg_config (list): The list output from the da... | |
<reponame>sakibguy/fbthrift
#
# Autogenerated by Thrift
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
# @generated
#
from __future__ import absolute_import
import sys
from thrift.util.Recursive import fix_spec
from thrift.Thrift import TType, TMessageType, TPriority, TRequestContext, TProcessorE... | |
# -*- coding: UTF-8 -*-
# Copyright 2009-2017 <NAME>
# License: BSD (see file COPYING for details)
"""Import legacy data from TIM (basic version).
Usage:
- :attr:`legacy_data_path <lino.core.site.Site.legacy_data_path>` must
point to the TIM data path, e.g.::
legacy_data_path = '~/vbshared2/drives/L/backup/data/p... | |
PathElement (fixed point in BezierPath), ctrl2 tells us how the curve arrives.
# For DynamicPathElement (returnd from BezierPath.point()), ctrl1 tell how the curve arrives.
ctrl = isinstance(pt, bezier.DynamicPathElement) and pt.ctrl1 or pt.ctrl2
angle = geometry.angle(ctrl.x, ctrl.y, pt.x, pt.y)
elif 0 < i < n-1 a... | |
height_2
# print("Height difference: {}".format(height_diff_12))
obj_size_1 = self.ctrls['standard 1 measure'].value()
obj_size_2 = self.ctrls['standard 2 measure'].value()
# print("Object sizes: {} - {}".format(obj_size_1, obj_size_2))
# mm/px ratio
mm_px_1 = obj_size_1 / img_size_1
mm_px_2 = obj_size_2 / img_s... | |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 23 15:29:41 2021.
@author: pielsticker
"""
import numpy as np
import h5py
from sklearn.utils import shuffle
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from .utils import ClassDistribution, SpectraPlot
#%%
class DataHandle... | |
""" Helper utilities for using Google Cloud Storage
"""
import fnmatch
import functools
import io
import json
import logging
import os
from pathlib import Path
import re
from google.cloud import storage
from google.oauth2 import service_account
import ee
from stems.utils import renamed_upon_completion
logger = logg... | |
region,
# move it to a data section
seg_offset = 0
need_move = (seg.perm & idaapi.SEGPERM_EXEC) != 0
if need_move:
free_data = findFreeData()
seg_offset = free_data - start
DEBUG("Data Segment {0:x} moved to: {1:x}\n".format(start, start+seg_offset))
D = M.internal_data.add()
D.base_address = start+seg_offset... | |
# -*- coding: utf-8 -*-
#==============================================================================
#
# location.py - Locations file, dictionary and global fields
#
# After copying playlists between locations use:
#
# cd ~/.config/mserve/L??? # Where ??? is 001, 002, etc.
# sed -i 's#/mnt/chromeos/removable#/media/... | |
<reponame>p2irc/friendly_ground_truth<gh_stars>0
"""
File Name: model.py
Authors: <NAME>
Date: 11-05-2020
Description: Model Classes
"""
import logging
import numpy as np
from skimage import io, img_as_float, img_as_uint, img_as_ubyte, img_as_bool
from skimage.util.shape import view_as_blocks
from skimage.filters ... | |
key in myEnemies:
currVal = myEnemies[key][1]
abilityArray.append(currVal)
if abilityDistributionType == 2:
myEnemies = randomizeGroupByAbility(myEnemies, abilityArray)
else:
myEnemies = randomizeGroup(myEnemies, abilityArray, abilityDistributionType != 3, True)
myObjects = shuffleDict(objects)
if object... | |
when generically requesting an Artist
kodi.AddSongsToPlaylist(songs_array, True)
kodi.StartAudioPlaylist()
if shuffle:
op = render_template('shuffling_empty').encode("utf-8")
else:
op = render_template('playing_empty').encode("utf-8")
return render_template('playing_action', action=op, movie_name=artist_label).e... | |
value in
- col - column to set the value in
- values - single scalar
:returns: 1 if the map was present, 0 if nothing was done
"""
self.setviaAPI[mapname] = 1
if hasattr(self._userModel(), mapname):
ar = pcr.pcr2numpy(getattr(self._userModel(), mapname), -999)
ar[row, col] = value
arpcr = pcr.numpy2pcr(pcr.Sc... | |
2
/path/to/file2:
file.managed:
- contents: |
This is line 1
This is line 2
contents_pillar
.. versionadded:: 0.17.0
.. versionchanged: 2016.11.0
contents_pillar can also be a list, and the pillars will be
concatinated together to form one file.
Operates like ``contents``, but draws from a value stored ... | |
class LegalMove():
"""
Tests proposed moves for correct cardinal direction and for obstacles in path
Called by propagate_board method in Class TowerkriegGame
"""
def __init__(self, gameboard, fp, fp_total, dir):
"""
Initializes parameters passed from Class TowerkriegGame, used to determine legality of move
:p... | |
RooRealVar and ``number''
def _rrv_rsub_ ( s , o ) :
"""(right) subtraction of RooRealVar and ``number''
>>> var = ...
>>> num = ...
>>> res = num - var
"""
if not isinstance ( o , val_types ) : return NotImplemented
if isinstance ( o , _RRV_ ) and not o.isConstant() : o = o.ve ()
elif hasattr ( o , 'get... | |
(267.736023ms)
"""
def do_v8_bench(scoutts_cmd, scoutts_working_dir):
print("running v8 benchmark...\n{}".format(scoutts_cmd))
scoutts_cmd = shlex.split(scoutts_cmd)
stdoutlines = []
with subprocess.Popen(scoutts_cmd, cwd=scoutts_working_dir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, universal_n... | |
self : None;
XdmfArrayList_swigregister = _Xdmf.XdmfArrayList_swigregister
XdmfArrayList_swigregister(XdmfArrayList)
TagNameToArray = _Xdmf.TagNameToArray
PrintAllXdmfArrays = _Xdmf.PrintAllXdmfArrays
GetCurrentArrayTime = _Xdmf.GetCurrentArrayTime
class XdmfDOM(XdmfLightData):
__swig_setmethods__ = {}
for _s in [Xd... | |
of voters from each candidate numbering `b`.
"""
voters = np.atleast_2d(voters)
candidates = np.atleast_2d(candidates)
num_voters = len(voters)
# distance shape (a, b) for `a` num voters, `b` num candidates.
distances = vcalcs.voter_distances(voters,
candidates,
weights=weights,
order=order)
avg_distances =... | |
# Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
"""Tests for converting between resource names and external ids."""
from __future__ import prin... | |
axis?
@param show: show figure?
@param save: if set saves figure to this filename
@param fig: use this figure for plots
@param ax: use this ax for plot
@param connect_event: connect scaling event for line plot
@param plotinfo: plot information in additional axes
plotinfo should be 'sum' or a header entry or two
... | |
"""Messages for natural language understanding."""
import re
import typing
from dataclasses import dataclass
from dataclasses_json import LetterCase, dataclass_json
from .base import Message
from .intent import Intent, Slot
@dataclass
class NluQuery(Message):
"""Request intent recognition from NLU component.
.. ... | |
<filename>slackbot/slack_bot.py
import slack
import json
import json5
from collections import OrderedDict
import string
from airflow_api import get_variable, run_segmentation, \
update_slack_connection, check_running, dag_state, set_variable, \
sanity_check, chunkflow_set_env, run_inference, run_contact_surface, \
m... | |
"""A multithreaded web crawler and scraper."""
from __future__ import (print_function, division, absolute_import,
unicode_literals)
from abc import abstractmethod
from collections import deque, defaultdict
import logging
try:
from Queue import Queue, Full
except ImportError:
from queue import Queue, Full
import ... | |
<filename>trac/ticket/roadmap.py<gh_stars>0
# -*- coding: utf-8 -*-
#
# Copyright (C) 2004-2009 Edgewall Software
# Copyright (C) 2004-2005 <NAME> <<EMAIL>>
# Copyright (C) 2006-2007 <NAME> <<EMAIL>>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have r... | |
l1 for local dw (64, 64) nZ
mat_l1_ldw_nZ = tik_inst.Tensor("float16",
(block_size // 16,
block_size // 16, 16, 16),
name="mat_l1_ldw_nZ",
scope=tik.scope_cbuf)
# move local dw from ub to l1
# the shape of local dw in ub is nZ
# the shape of local dw in l1 is nZ
# the stride between each (16, 64) is 2... | |
#!/usr/bin/python
# (c) 2019, NetApp, Inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'communit... | |
def get_adaptive_precision_floor(self, X, y, range = (1e-6, 1e-1), nonzero_ratio = 0.5):
num_zero_loss_list = []
U = deepcopy(self)
for dl in np.logspace(np.log10(range[1]), np.log10(range[0]), 200):
U.set_loss_core("DL", dl)
num_zero_loss = (U.get_losses(X, y, mode = "loss_with_domain", is_mean = False)["loss_wit... | |
import collections
import discord
from discord.ext import commands
import asyncio
import random
bot = commands.Bot(command_prefix='!')
token_file = "token.txt"
with open(token_file) as f:
TOKEN = f.read()
accounts_data = {"id" : [], "account type" : [], "account name" : [], "account registered" : [], "account regis... | |
# Palanteer scripting library
# Copyright (C) 2021, <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later ver... | |
from initialise_parameters import params, control_data, categories, calculated_categories, change_in_categories
from math import exp, ceil, log, floor, sqrt
import numpy as np
from scipy.integrate import ode
from scipy.stats import norm, gamma
import pandas as pd
import statistics
import os
import pickle
from tqdm impo... | |
7.964 13.667 1.00 12.29 C
ATOM 247 N ALA A 71 22.620 6.290 16.320 1.00 11.50 N
ATOM 248 CA ALA A 71 22.609 4.998 17.000 1.00 12.25 C
ATOM 249 C ALA A 71 21.494 4.864 18.036 1.00 12.23 C
ATOM 250 O ALA A 71 20.573 4.063 17.870 1.00 15.23 O
ATOM 251 CB ALA A 71 23.959 4.748 17.658 1.00 12.60 C
ATOM 252 N ALA A 72 21.584 ... | |
"mutualresistancebc",
"mutualresistanceca",
"mutualreactanceab",
"mutualreactancebc",
"mutualreactanceca",
],
mapp_line_unbalanced,
{"type": "unbalanced_line"},
)
)
#########################################
# #
# SPACING TABLE #
# #
#########################################
#
self.spacings.update(
sel... | |
<gh_stars>100-1000
#!/usr/bin/env python
# coding=utf8
from __future__ import unicode_literals
from datetime import timedelta
import collections
import functools
import os
import re
import string
from io import StringIO
import pytest
from hypothesis import given, settings, HealthCheck, assume
import hypothesis.strate... | |
# coding: utf-8
"""
Defines the DEQATN class and sub-functions.
The capitalization of the sub-functions is important.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
import numpy as np
from numpy import (
cos, sin, tan, log, log10, mean, exp, sqrt, square, mod, abs, sum,
arcsin as asin, arcc... | |
<filename>pyEX/stocks.py<gh_stars>1-10
import itertools
import requests
import pandas as pd
from io import BytesIO
from IPython.display import Image as ImageI
from multiprocessing.pool import ThreadPool
from PIL import Image as ImageP
from .common import _TIMEFRAME_CHART, _TIMEFRAME_DIVSPLIT, _LIST_OPTIONS, _COLLECTION... | |
@property
def origin(self):
return parse_int_vector(self._raw_data.get('origin', "0 0 0"))
pass
class logic_director_query(Targetname):
@property
def origin(self):
return parse_int_vector(self._raw_data.get('origin', "0 0 0"))
@property
def minAngerRange(self):
return parse_source_value(self._raw_data.get('... | |
settings = {
# path and name of the sqlite3 database to use
# use only a file name to use the database in
# the current working directory
# Leave empty to disable the database
'database': r'/var/twonky/TwonkyServer/tw-video-scraper.db',
# Path where to download and extract the files
# downloaded from T... | |
<filename>tests/test_v3_auth.py
# Copyright 2012 OpenStack LLC
#
# 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... | |
<reponame>iscai-msft/azure-sdk-for-python<filename>sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/models/_models_py3.py
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.... | |
###################################################################################################
# Project : Global Challenges Research Fund (GCRF) African SWIFT (Science for Weather
# Information and Forecasting Techniques.
#
# Program name : dewpoint_HL.py
#
# Author : <NAME>, University of Leeds, NCAS
#
# Date ... | |
a psychometric function from some example data and derive bootstrap confidence
intervals for a threshold
>>> x = [0,2,4,6,8,10]
>>> k = [26,30,38,46,50,49]
>>> n = [50]*len(k)
>>> B = BootstrapInference ( zip(x,k,n), priors=("flat","flat","Uniform(0,0.1)"), sample=True )
>>> B.estimate
array([ 3.80593409, 1.093... | |
import textwrap
from abc import ABC
from functools import lru_cache
from typing import Optional, Type, TypeVar, Union
import aioarangodb.exceptions
import pydantic
from aioarangodb.collection import StandardCollection
from aioarangodb.database import StandardDatabase
from pydantic import Field
from arangodantic.arang... | |
<gh_stars>1-10
#!/usr/bin/env python3
import optparse
import os
import sys
from distutils.spawn import find_executable
import chpl_platform, chpl_locale_model, overrides
from utils import error, memoize, warning
#
# If we can't find a file $CHPL_HOME/make/Makefile.<compiler_val>,
# that suggests that this is a comp... | |
Load NEURON GUI
# except:
# print('Error! File: {} not found!'.format(dataVar.value))
# return
##### Brian bar functions #####
def onBrianLoad(name):
print('Loading: "',brianFile.value, '"...', end=' ')
try: # Load mechanism and set some appropriate parameters
print('Finish me!!!')
except:
print('Error! F... | |
<filename>pgAdmin4/pgAdmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/utils/driver/psycopg2/__init__.py
##########################################################################
#
# pgAdmin 4 - PostgreSQL Tools
#
# Copyright (C) 2013 - 2018, The pgAdmin Development Team
# This software is released under the Postgre... | |
#######################################################################################################
# Copyright (c) 2010
#
# <NAME>
# Molecular Foundary
# Lawrence Berkeley National Laboratories
#
# Python module to read in VAMAS files for use with SciPy.
#
# Data import and export proceeds according to the specif... | |
import random
import json
def generate_object_question(tmp_verb, tmp_object, name, question_number):
raw_data = """<fieldset><label>""" + str(
question_number) + """. <font color="red"><b>('""" + tmp_verb + """', '""" + tmp_object + """')</b></font> : In your opinion, how suitable is <font color="red"><b>'""" + t... | |
import os
import sys
import platform
import requests
import time
from metaflow import util
from metaflow import R, current
from metaflow.decorators import StepDecorator
from metaflow.plugins import ResourcesDecorator
from metaflow.plugins.timeout_decorator import get_run_time_limit_for_task
from metaflow.metadata imp... | |
: int
Number of unique truths in pure linkages only (not in partial linkages but can be in mixed
linkages).
"unique_in_partial_linkages_only" : int
Number of unique truths in partial linkages only (not in pure linkages but can be in mixed
linkages).
"unique_in_pure_and_partial_linkages" : int
Number of unique t... | |
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if... | |
ss._privileged_start()
finally:
server.get_listening_tcp_socket = get_listening_tcp_socket_orig
self.assertEqual(ss.sock, 'sock')
self.assertEqual(get_listening_tcp_socket_calls, [(('*', 80), {
'keyfile': None, 'style': 'eventlet', 'retry': 30,
'certfile': None, 'backlog': 4096})])
def test_start(self, output=F... | |
security server clients tab')
self.wait_until_visible(type=By.CSS_SELECTOR, element=sidebar_constants.CLIENTS_BTN_CSS).click()
'''Get parameters member_code and subsystem_code from clients_table_vm.py'''
member_code = clients_table_vm.ONE_SS_CLIENT[0]
subsystem_code = clients_table_vm.ONE_SS_CLIENT[1]
'''Add cli... | |
from unittest import TestCase
from mock import Mock, patch, call
from samtranslator.public.sdk.resource import SamResource, SamResourceType
from samtranslator.public.exceptions import InvalidEventException, InvalidResourceException, InvalidDocumentException
from samtranslator.plugins.api.implicit_rest_api_plugin impor... | |
u"""Neural Causation Coefficient.
Author : <NAME>
Ref : <NAME>. and <NAME>. and <NAME>. and <NAME>. and <NAME>.,
"Discovering Causal Signals in Images", CVPR 2017.
.. MIT License
..
.. Copyright (c) 2018 <NAME>
..
.. Permission is hereby granted, free of charge, to any person obtaining a copy
.. of this software and... | |
cooked, braised
23596: [], # Beef, brisket, flat half, separable lean only, trimmed to 1/8" fat, all grades, raw
23597: [], # Beef, round, eye of round, roast, separable lean only, trimmed to 1/8" fat, all grades, raw
23598: [], # Beef, round, eye of round, roast, separable lean only, trimmed to 1/8" fat, all grades... | |
* FROM mgstat", connection)
# hack until good way to detect date format is mmm/dd/yyyy or not
if False:
df["Date"] = df.apply(
lambda row: make_mdy_date(row["Date"]), axis=1
)
# Add a datetime column
df["datetime"] = df["Date"] + " " + df["Time"]
# Format the data for Altair
# Cut down the df to just the th... | |
<gh_stars>0
import re
import dateutil
import pandas as pd
from datetime import datetime
from textblob.classifiers import NaiveBayesClassifier
from colorama import init, Fore, Style
from tabulate import tabulate
class BankClassify:
def __init__(self, db, data="sql"):
"""Load in the previous data (by default from `... | |
<reponame>JackNg88/glbase3
"""
SOMPY was released under an MIT license:
The MIT License (MIT)
Copyright (c) 2014 <NAME>, www.vahidmoosavi.com
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
wi... | |
count):
if not count:
count = 20
point = {"type": "Point", "coordinates": [lng, lat]}
f = {"loc": {"$near": {"$geometry": point}}}
c = {"_id": 0, "loc":1, "id": 1, "time": 1, "level": 1, "distance": 1}
db = self.connect.get_database(global_db_name)
coll = db.get_collection(global_db_calc_collection)
it = coll.f... | |
<reponame>gibbss21/Cayley
"""
Filename: functions.py
Provides key functions to setting up a game between senators.
"""
import csv
import Cayley as cy
import numpy as np
import random
import math
import openpyxl
import xlsxwriter
#For personal reference when using the CSV
name_of_data_from_csv = ['rank_from_low', 'ra... | |
hashlib.sha256(query).hexdigest())
try:
os.makedirs('/tmp/user_exports')
except OSError as e:
if e.errno != errno.EEXIST:
raise e
try:
with open(tmp_path, 'w') as f:
cur.copy_expert(query, f)
except psycopg2.Error as e:
# Delete the temporary files of failed exports.
os.remove(tmp_path)
_convert_pg_excepti... | |
#!/bin/python
# Copyright 2018 <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 in wri... | |
# $ANTLR 3.5 Expr.g 2013-04-12 19:22:24
import sys
from antlr3 import *
from antlr3.compat import set, frozenset
from antlr3.tree import *
# for convenience in actions
HIDDEN = BaseRecognizer.HIDDEN
# token types
EOF=-1
T__68=68
T__69=69
T__70=70
T__71=71
T__72=72
T__73=73
T__74=74
T__75=75
T__76=76
T__77=77
T__... | |
numpy.ndarray(keys.shape, view_dtype, keys.data)
return keys
def _cast_back(self, keys):
if keys.dtype != self.cast_dtype:
if not keys.dtype.hasobject and not self.cast_dtype.hasobject:
keys = keys.view(self.cast_dtype)
else:
# HACK! numpy doesn't allow views with object, so we use a workaround
# warning: SegF... | |
#!/usr/bin/env python3
import sys
import subprocess
import os
import os.path
if len(sys.argv) > 1:
pythonpath = sys.argv[1]
else:
pythonpath = sys.executable
homepath = os.path.realpath(os.path.dirname(sys.argv[0]))
ophispath = os.path.join(homepath, "..", "bin", "ophis")
failed = 0
# These are some simple routin... | |
in base pairs to extend the read. If a strand is present it will expand
from the 3' end of the read.
row_labels (Optional, default= from the peak.name)
row labels for the heatmaps;
col_labels (Optional, default=from the trk['name'])
column labels
bins (Optional, default=100)
number of bins to use for the pile... | |
import torch
from numpy import prod
from torch import nn
from torch.hub import load_state_dict_from_url
model_urls = {
"vgg11": "https://download.pytorch.org/models/vgg11-bbd30ac9.pth",
"vgg13": "https://download.pytorch.org/models/vgg13-c768596a.pth",
"vgg16": "https://download.pytorch.org/models/vgg16-397923af.pt... | |
<gh_stars>1-10
# Copyright (c) 2014, HashFast Technologies LLC
# 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 code must retain the above copyright
# notice, this l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.