input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
Loader
def __init__ (self, * args, ** kw) :
self.pathes = []
self.pop_to_self (kw, "pre_load_cb", "x_context", prefix = "_")
self.__super.__init__ (* args, ** kw)
# end def __init__
def cook (self, value, cao = None) :
from _TFL.load_config_file import load_config_file
path = self.__super.cook (value, cao)
r... | |
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.nn.functional as F
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
impo... | |
2.3
#bandpass_sig = iir_bandpass_filter_1(bandpass_sig, 0.8, 2, 20, 5, "cheby1") # Breath: 0.1 ~ 0.33 order=5, Hreat: 0.8 ~ 2.3
#bandpass_sig = firwin_filter(new_phase_diff, 0.8, 2, 20, 5)
#bandpass_sig = lowpass_filter(bandpass_sig, 2, 2, 20, 5)
N = len(bandpass_sig)
T = 1 / 20
bps_fft = fft(bandpass_sig)
bps_f... | |
"""
Base classes used in the `ChiantiPy.core.ion` and `ChiantiPy.core.spectrum`
classes. Mostly printing, plotting and saving routines.
"""
import copy
import time
import numpy as np
import matplotlib.pyplot as plt
import ChiantiPy.tools.util as util
import ChiantiPy.Gui as chGui
import ChiantiPy.tools.data as chdata
... | |
<gh_stars>10-100
#emacs, this is -*-Python-*- mode
"""
There are several ways we want to acquire data:
A) From live cameras (for indefinite periods).
B) From full-frame .fmf files (of known length).
C) From small-frame .ufmf files (of unknown length).
D) From a live image generator (for indefinite periods).
E) From ... | |
# Copyright 2020 The Google AI Team, Stanford University and The HuggingFace Inc. team.
# Copyright (c) 2020 <NAME>. 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
#
# h... | |
from sqlite3.dbapi2 import Cursor
from prettytable import PrettyTable
import vk_api
from vk_api.longpoll import VkLongPoll, VkEventType
from vk_api.keyboard import VkKeyboard, VkKeyboardColor
import random
import sqlite3
from game_math import RandomNumber
import psycopg2
import threading
import datetime
from... | |
#!/usr/bin/env python
# coding: utf-8
from xumm.resource import XummResource
from typing import Union, Dict, List
from ..misc import (
ReturnUrl,
Options,
Application,
Payload,
Response,
Result,
Next,
Refs,
)
xumm_tx_types = [
'SignIn'
]
xrpl_tx_types = [
'AccountDelete',
'AccountSet',
'CheckCancel',
'... | |
"for source node and destination node." \
"or three columns, the first column for source node, " \
"the second for destination node, " \
"and third for labels")
if edge_type != None and len(edge_type) != 3:
raise RuntimeError("edge_type should be None or a tuple of " \
"(src_type, relation_type, dst_type)")
if... | |
<gh_stars>1-10
"""Three-dimensional mobjects."""
from __future__ import annotations
__all__ = [
"ThreeDVMobject",
"Surface",
"ParametricSurface",
"Sphere",
"Dot3D",
"Cube",
"Prism",
"Cone",
"Arrow3D",
"Cylinder",
"Line3D",
"Torus",
]
from typing import *
import numpy as np
from colour import Color
fro... | |
develop your own SSH server with paramiko for a cetain
plattform like Linux, you should call C{krb5_kuserok()} in your
local kerberos library to make sure that the krb5_principal has
an account on the server and is allowed to log in as a user.
:see: `http://www.unix.com/man-page/all/3/krb5_kuserok/`
"""
if gss_au... | |
from bs4 import BeautifulSoup
import urllib.request
from dotenv import load_dotenv
import json
import requests
# import pyperclip
import time
import datetime
import os
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding=... | |
<filename>sarpy/utils/nitf_utils.py
"""
A utility for dumping a NITF header to the console. Contributed by <NAME> of L3/Harris.
To dump NITF header information to a text file from the command-line
>>> python -m sarpy.utils.nitf_utils <path to nitf file>
For a basic help on the command-line, check
>>> python -m sarp... | |
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'text/json', 'application/xml', 'text/xml']) # noqa: E501
# Authentication setting
auth_settings = ['fast... | |
<filename>rs/localization_files/AR.py
# -*- coding: utf-8 -*-
################################################################################
# LexaLink Copyright information - do not remove this copyright notice
# Copyright (C) 2012
#
# Lexalink - a free social network and dating platform for the Google App Engine.... | |
import re
import os
import tempfile
import shutil
import copy
import time
import random
import socket
import hashlib
from .log import LoggerFactory
from .gossip import gossiper
from .kv import kvmgr
from .stop import stopper
from .threadmgr import threader
from .perfdata import PerfDatas
from .evaluater import evaluat... | |
<filename>supra/GUI/Dialogs/SolutionGUI.py
################################################
# Credits:
# <NAME> - Supervisor
# <NAME> - General coding
# <NAME> - Ballistic code, WMPL
# <NAME> - Supracenter code
# <NAME> - Updated Supracenter code, Geminus
# <NAME> - Advice on atmospheric profiles
# Stack Overflow - Fre... | |
#!/usr/bin/env python
"""
Convert DICOM files to corresponding PNG files.
NOTE: Only works with DICOM files containing a single
layer!
"""
import sys, os, collections, toml, asyncio, hashlib, time, platform, queue
import numpy as np, png, pydicom, multiprocessing
from pathlib import Path
from PyQt5 import QtCore, QtWid... | |
= p
# now go there...
bestp = bestp * scale
self.SetPos( self.pos + bestp )
return bestp
def DrawMore(self, f):
# make current
vv.figure(f.nr)
if not hasattr(self, '_patch') or not hasattr(self, '_kw'):
return
a=vv.subplot(311)
vv.volshow(self._patch)
a.daspect = 1,-1,-1
a=vv.subplot(312)
vv.vo... | |
<reponame>Qm-Dev/figures-calculator
import math
import time
version = "Alpha 7.1"
lang = "ES"
redo = 0
while redo == 0:
try:
def main():
print("\n\n\n")
print("\t _____ _ _ ")
time.sleep(0.3)
print("\t/ __ \ (_) (_) ")
time.sleep(0.3)
print("\t| / \/ ___ _ __ ___ _ __ _ __ _ ___ _ _ _ _ __ ___ ")
time.sleep... | |
import os
import sys
sys.path.append('.')
sys.path.append('..')
import warnings
warnings.filterwarnings("ignore")
from datetime import datetime
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.lines as lines
import matplotlib.image as mpimg
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
f... | |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 03 13:46:22 2016
@author: kbefus
"""
# -*- coding: utf-8 -*-
"""
Created on Mon May 16 09:19:36 2016
@author: kbefus
"""
import sys,os
import numpy as np
import time
from shutil import copyfile
res_dir = r'/mnt/data2/CloudStation'
code_dir = os.pa... | |
<filename>performance/benchmarks/bm_unpack_sequence.py
"""Microbenchmark for Python's sequence unpacking."""
import perf
from six.moves import xrange
def do_unpacking(loops, to_unpack):
range_it = xrange(loops)
t0 = perf.perf_counter()
for _ in range_it:
# 400 unpackings
a, b, c, d, e, f, g, h, i, j = to_unpac... | |
"""
Services module forms
"""
from django import forms
from django.db.models import Q
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from anaf.core.conf import settings
from anaf.identities.models import Contact
from anaf.core.decorators import preprocess_form
from anaf.... | |
<filename>gget/gget_seq.py
import logging
# Add and format time stamp in logging messages
logging.basicConfig(
format="%(asctime)s %(levelname)s %(message)s",
level=logging.INFO,
datefmt="%c",
)
# Mute numexpr threads info
logging.getLogger("numexpr").setLevel(logging.WARNING)
import numpy as np
# Custom function... | |
from copy import deepcopy
import json
import logging
import os
import random
import re
import string
import subprocess
import time
import urllib
import boto3
from boto3.dynamodb.conditions import Attr
from citrination_client import CitrinationClient
import globus_sdk
import jsonschema
import mdf_toolbox
import request... | |
<filename>mrjob/runner.py
# Copyright 2009-2012 Yelp and Contributors
#
# 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 app... | |
data = {'content': "{'lr': 0.1}"}
assert self.queryset.first().params is None
with patch('scheduler.tasks.experiments.experiments_build.apply_async') as mock_fct:
resp = self.auth_client.post(self.url, data)
assert resp.status_code == status.HTTP_400_BAD_REQUEST
assert mock_fct.call_count == 0
assert self.querys... | |
# Copyright (c) 2013 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | |
<gh_stars>10-100
# Copyright 2009 <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 code must retain the above copyright notice,
# this list of conditions and ... | |
be set to False. Note that " +
"the container image property must not be specified via this " +
"attribute."
),
),
"export_configs": attr.bool(
doc = (
"Specifies whether to copy generated configs to the 'output_base' " +
"of the 'toolchain_config_suite_spec' (if configs are generated) " +
"If set to False, a ... | |
# Импорт системных библиотек
from __future__ import print_function
from shutil import copyfile
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from PyQt5 import QtWidgets, QtCore
import sys... | |
<reponame>theogruner/SimuRLacra
# Copyright (c) 2020, <NAME>, Honda Research Institute Europe GmbH, and
# Technical University of Darmstadt.
# 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. Re... | |
<reponame>Felicia56/flavio<filename>flavio/physics/bdecays/matrixelements.py
from math import pi
from cmath import sqrt, log, atan
import pkgutil
import numpy as np
from io import StringIO
import scipy.interpolate
from flavio.physics.running import running
from flavio.physics import ckm
from flavio.math.functions impor... | |
<gh_stars>0
# -*- coding: utf-8 -*-
import csv
import copy
import datetime
import logging
import io
import json
import re
import time
import zipfile
import codecs
from collections import defaultdict, deque, OrderedDict
from django.contrib import messages
from django.contrib.auth.decorators import login_required, user_p... | |
<filename>tf_agents/replay_buffers/tfrecord_replay_buffer_test.py
# coding=utf-8
# Copyright 2018 The TF-Agents 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.... | |
the System.Windows.Forms.ToolStripItem.RightToLeftChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnTextChanged(self, *args):
"""
OnTextChanged(self: ToolStripItem,e: EventArgs)
Raises the System.Windows.Forms.ToolStripItem.TextChanged event.
e: An Syst... | |
if figures == 'window': # possibly save the output
pass
elif figures == "png":
f.savefig(f"{png_path}/{fig_title}.png")
plt.close()
elif figures == 'png+window':
f.savefig(f"{png_path}/{fig_title}.png")
else:
pass
#%%
def signals_to_master_signal_comparison(signals, master_signal, density = False):
""" Give... | |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import numpy as np
import os
import cv2
import torch
import tqdm
from iopath.common.file_io import g_pathmgr
import slowfast.utils.checkpoint as cu
import slowfast.utils.logging as logging
from slowfast.datasets.ava_helper ... | |
<gh_stars>1-10
from collections import deque
class Process:
def __init__(self, process_name: str, arrival_time: int, burst_time: int) -> None:
self.process_name = process_name # process name
self.arrival_time = arrival_time # arrival time of the process
# completion time of finished process or last interrupted ti... | |
# Copyright 2019 Rackspace US 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 required by applicable law or... | |
channel changes.
Args:
event (dict): A NewCallerid event.
"""
channel = self._channels[event['Uniqueid']]
channel.caller_id = channel.caller_id.replace(
name=event['CallerIDName'],
num=event['CallerIDNum'],
)
channel.cid_calling_pres = event['CID-CallingPres']
def _on_new_connected_line(self, event):
"""
... | |
#!/usr/bin/env python
import numpy as np
from scipy.linalg import expm
from scipy.linalg import logm
from scipy.linalg import inv
import rospy
import rosbag
import rospkg
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
from cw2q4.youbotKineKDL import YoubotKinematicKDL
import PyKDL
from visualiza... | |
<reponame>quanganh2627/bytm-x64-L-w05-2015_external_chromium_org_third_party_WebKit
# Copyright (C) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source... | |
"""
This module defines common methods used in simulator specific build modules
@author <NAME>
"""
##########################################################################
#
# Copyright 2011 Okinawa Institute of Science and Technology (OIST), Okinawa
#
#############################################################... | |
size=1)
>>> cdll[::-1]
CDLList(head=Node(value=3, left=<class 'ds.cdll.Node'>, right=<class 'ds.cdll.Node'>), size=3)
>>> cdll[:3:2]
CDLList(head=Node(value=1, left=<class 'ds.cdll.Node'>, right=<class 'ds.cdll.Node'>), size=2)
>>> list(cdll[:3:2])
[1, 3]
>>> cdll[::'w']
Traceback (most recent call last):
...
... | |
XZ plane
zgrid = np.linspace(*zbounds, nperax)
xgrid = np.linspace(*xbounds, nperax)
fig = self.plot_phi_map(xgrid, zgrid, contour=contour, **kwargs)
ax = fig.axes[0]
# Add marker for stim position
ax.scatter([xstim * 1e-3], [zstim * 1e-3], label='electrode')
# Add markers for axon nodes
xnodes = self.axon.xnod... | |
<filename>examples/python/routing_example.py
# # Respecting Architecture Connectivity Constraints - Advanced Routing in tket
# Very few current or planned quantum architectures have all-to-all qubit connectivity. In consequence, quantum circuits must be modified before execution to ensure that every multi-qubit gate i... | |
self.scrollArea_chosen = QtWidgets.QScrollArea(self.groupBox_sage)
self.scrollArea_chosen.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.scrollArea_chosen.setWidgetResizable(True)
self.scrollArea_chosen.setObjectName("scrollArea_chosen")
self.scrollArea_chosen.setFocusPolicy(QtCore.Qt.ClickFocus)
self.scrollArea... | |
<filename>tensorflow_federated/python/research/optimization/shared/fed_avg_schedule.py
# Copyright 2019, The TensorFlow Federated 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
#
# ... | |
<reponame>MattGreav/test
# Copyright 2019 TerraPower, 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 law ... | |
<reponame>rieder/limepy<filename>limepy/spes.py
# -*- coding: utf-8 -*-
import numpy
import scipy
from scipy.interpolate import BPoly, interp1d, UnivariateSpline
from numpy import exp, sqrt, pi, sin, cos, log10
from scipy.special import gamma, gammainc, gammaincc, hyp1f1
from scipy.integrate import ode, simps
from mat... | |
<= 0)
m.c7583 = Constraint(expr= - m.b436 + m.b444 - m.b494 <= 0)
m.c7584 = Constraint(expr= - m.b436 + m.b445 - m.b495 <= 0)
m.c7585 = Constraint(expr= - m.b436 + m.b446 - m.b496 <= 0)
m.c7586 = Constraint(expr= - m.b436 + m.b447 - m.b497 <= 0)
m.c7587 = Constraint(expr= - m.b437 + m.b438 - m.b498 <= 0)
m.c7588 ... | |
<filename>polo2/polo_mallet.py
import os
import time
import re
import pandas as pd
from itertools import combinations
from lxml import etree
from scipy import stats
from polo2 import PoloDb
from polo2 import PoloFile
from polo2 import PoloMath as pm
class PoloMallet(PoloDb):
def __init__(self, config, trial='trial1... | |
import numpy as np
import sys
import math
from matplotlib import pyplot as plt
import time
np.random.seed(3141592)
# d_f(z) = dz/dx in terms of z = f(x)
def relu(z):
return np.maximum(z, 0.0)
def d_relu(z):
return np.where(z > 0, 1.0, 0.0)
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def d_sigmoid(z):
return z... | |
# Generated from StlParser.g4 by ANTLR 4.5.1
# encoding: utf-8
from __future__ import print_function
from antlr4 import *
from io import StringIO
def serializedATN():
with StringIO() as buf:
buf.write(u"\3\u0430\ud6d1\u8206\uad2d\u4417\uaef1\u8d80\uaadd\3")
buf.write(u"H\u010c\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\... | |
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.portals_id_designs_nk_folder_get(id, nk, callback=callback... | |
matricide matricides mattock mattocks maturation maturely
matzo matzoh matzohs matzos matzot matzoth maunder maundered
maundering maunders maven mavens maw mawed mawing mawkish mawkishly
maws maxed maxes maxilla maxillae maxillary maximally maximals maxing
mayday maydays mayflies mayflower mayflowers mayfly mayo mayora... | |
<filename>python/Strobe/StrobeFancy.py
"""
An example implementation of STROBE.
The key tree may be patented. Also, it may be easy to violate other
patents with this code, so be careful.
Copyright (c) <NAME>, Cryptography Research, 2015-2016.
I will need to contact legal to get a license for this; in the mean time
i... | |
= (list(self.params.sixtrack.keys()) +
list(self.params.phasespace.keys()) +
['wu_id', 'preprocess_id'])
# create a dict for each row. This is bulky due to the json.loads :(
six_wu_entries = []
for row in self.db.select('sixtrack_wu', six_keys):
d = {}
for k, v in zip(six_keys, row):
if isinstance(v, str):
try... | |
# In[12]:
# writer = SummaryWriter()
z_sample = 0.5 * torch.randn(64, z_dim).to(device)
_x, _ = iter(test_loader).next()
_x = _x.to(device)
for epoch in range(1, epochs + 1):
train_loss = train(epoch)
test_loss = test(epoch)
recon = plot_reconstrunction(_x[:8])
sample = plot_image_from_latent(z_sample)
#... | |
self.first_learner.model1.transform(df)
.withColumn("preds1", split_udf(pred_col))
.select([*df_cols, "preds0", "preds1"])
)
df = df.withColumn(
"D",
F.when(
F.col(self.treatment_colname) == self.treatment_value, F.col(self.target_colname) - F.col("preds0")
).otherwise(F.col("preds1") - F.col(self.target_colna... | |
<filename>src/test/python/test_scc_pacs.py
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Copyright (c) 2020, Sandflow Consulting LLC
#
# 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 co... | |
from __future__ import division
from typing_extensions import ParamSpecArgs
from django.shortcuts import render,redirect
from django.http import Http404, request
from .models import *
from django.db.models import Q
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import auth
from dj... | |
1, 2.3, -12, None, False, '']
elif param_name == 'CategoriesListFilter':
valid = [self.CategoriesListFilter]
invalid = ['a', 1, 2.3, -12, None, False, '']
else:
raise ValueError(f"test_data_validation(): parameter test not implemented: '{param_name}'. Please remove or implement it")
for data in valid:
self.asse... | |
import io
import time
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from scipy.ndimage import convolve
# numpy representation of the RPi camera module v1 Bayer Filter
bayerGrid = np.zeros((1944, 2592, 3), dtype=np.uint8)
bayerGrid[1::2, fc00:db20:35b:7399::5, 0] = 1 # Red
bayerGrid[0::2, ... | |
from __future__ import division
from builtins import str
from builtins import range
from past.utils import old_div
import proteus
from proteus.mprans.cNCLS import *
class SubgridError(proteus.SubgridError.SGE_base):
def __init__(self, coefficients, nd):
proteus.SubgridError.SGE_base.__init__(self, coefficients, nd,... | |
case
h = self.t_bound - t
y_new = y + h * self.f
self.h_previous = h
self.y_old = y
self.t = self.t_bound
self.y = y_new
self.f = None # signals _dense_output_impl
logging.warning(
'Linear extrapolation was used in the final step.')
return None, min_step
return h_abs, min_step
def _estimate_error(self, K,... | |
in ['CatalogNode']:
# blocks with header marker
pass
elif current_block in ['CatalogUGen', 'Parameters']:
# blocks without header marker
pass
elif current_block in ['Areas', 'Sites']:
# blocks without header marker
pass
elif current_block in ['Nodes', 'Branches', 'CatalogBranch']: # blocks without header ma... | |
'raster1*raster2',
'symbol_to_path_map': {
'raster1': r"C:\Users\Becky\Documents\cnc_project\optimization\critical-natural-capital-optimizations\stitched_solutions\8-21\H1_90_md5_7973783ac2786f9d521a4b8b4cf5d68d.tif",
'raster2': r"C:\Users\Becky\Documents\cnc_project\optimization\critical-natural-capital-optimiz... | |
<filename>databroker/v1.py
from collections import defaultdict
from datetime import datetime
import pandas
import re
import warnings
import time
import humanize
import jinja2
import os
from types import SimpleNamespace
import xarray
import event_model
# Toolz and CyToolz have identical APIs -- same test suite, docstr... | |
# API for accessing the core plugin of SublimePapyrus
import sublime, sublime_plugin, sys, os, json, threading, time
PYTHON_VERSION = sys.version_info
SUBLIME_VERSION = None
if PYTHON_VERSION[0] == 2:
SUBLIME_VERSION = int(sublime.version())
import imp
root, module = os.path.split(os.getcwd())
coreModule = "Sublime... | |
# Natural Language Toolkit: Viterbi Probabilistic Parser
#
# Copyright (C) 2001-2020 NLTK Project
# Author: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
from functools import reduce
from nltk.tree import Tree, ProbabilisticTree
from nltk.parse.api import Par... | |
<filename>src/panoptes/utils/images/fits.py
import os
import shutil
import subprocess
from warnings import warn
from astropy import units as u
from astropy.io import fits
from astropy.wcs import WCS
from panoptes.utils import error
from panoptes.utils.logging import logger
def solve_field(fname, timeout=15, solve_op... | |
u('\u6cb3\u5357\u7701\u5b89\u9633\u5e02')},
'861454354':{'en': '<NAME>', 'zh': u('\u5c71\u4e1c\u7701\u4e1c\u8425\u5e02')},
'861384920':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u9e64\u58c1\u5e02')},
'861384921':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u9e64\u58c1\u5e02')},
'861384922':{'en': '<NAME>', 'zh': ... | |
x.__repr__() <==> repr(x)
"""
pass
def __rmul__(*args, **kwargs):
"""
x.__rmul__(n) <==> n*x
"""
pass
def __setitem__(*args, **kwargs):
"""
x.__setitem__(i, y) <==> x[i]=y
"""
pass
def __setslice__(*args, **kwargs):
"""
x.__setslice__(i, j, y) <==> x[i:j]=y
Use of negative indices is... | |
<reponame>gda-score/code
import pprint
import matplotlib.pyplot as plt
import numpy as np
from gdascore.gdaTools import getInterpolatedValue
from matplotlib.patches import Rectangle
pp = pprint.PrettyPrinter(indent=4)
# Future use for static unchanged strings
doubleColumnScore = "doubleColumnScores"
singleColumnSco... | |
"""
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import json
import os
import pathlib
from argparse import ArgumentParser
from datetime import datetime
import matplotlib.pyplot as plt
impor... | |
<filename>src/python/dxpy/bindings/dxapplet.py
# Copyright (C) 2013-2016 DNAnexus, Inc.
#
# This file is part of dx-toolkit (DNAnexus platform client libraries).
#
# 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
#... | |
= res_data['detections']
img_meta = res_data['img_meta']
is_pcl = 'input_style' in img_meta and img_meta['input_style'] == 'pcl'
if not is_pcl:
img = res_data['img']
p = self._eval_img_size_aug
if p>0:
img = np.pad(img, (p,p,p,p,0,0), 'constant', constant_values=0)
else:
img_shape = res_data['img']
img_shape[... | |
from unittest import TestCase
from unittest import mock
import copy
from data import views, api_caller
@mock.patch.object(
api_caller, "load_committee_statement_of_organization", return_value=None
)
@mock.patch.object(api_caller, "load_endpoint_results")
@mock.patch.object(views, "load_reports_and_totals")
@mock.pa... | |
# coding=utf-8
# Copyright 2018 The TF-Agents 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 ... | |
<filename>api/twitter/flow/display.py
import logging
from math import ceil
from bottle import template, redirect, request, abort
from api.caching.temporal_analytics import getTemporalRange, getTemporalInfluenceCollection, getTimeIdFromTimestamp
from api.caching.tweet_user import readTweetsFromCache, readUsersFromCache,... | |
from typing import Optional
import warnings
import pandas as pd
from macpie._config import get_option
from macpie import lltools, validatortools
def date_proximity(
left,
right,
id_on=None,
id_left_on=None,
id_right_on=None,
date_on=None,
date_left_on=None,
date_right_on=None,
get: str = "all",
when: str ... | |
"""**repolygon**: create designs by spatial *re*petition of *polygon*s.
Created by <NAME>, 2017; tidied & uploaded to GitHub 2019.
This module contains the data that defines the original example designs as
well as some replications of famous designs.
"""
# Colour scheme for designs without use of the advanced colo... | |
type may apply to a resource at any point in time.
:param str message: A Message containing details about this condition's last transition from one status to another, if any.
"""
pulumi.set(__self__, "last_transition_time", last_transition_time)
pulumi.set(__self__, "reason", reason)
pulumi.set(__self__, "status",... | |
.text could be 'sw-2 cut' or 'thr imp'
# .attrib could be type=cut st=sw base=-2 or type=fat base=1d+1
_st = ''
_type = ''
_base = ''
if damage_element.text is not None and len(damage_element.text) > 0:
# For strength-based damage (like a knife): sw-3 cut
match = re.match(
'(?P<st>[a-zA-Z]+)' +
'(?P<base>[+-]... | |
self.assertEqual(1, out)
def test_get_key_not_in_cache(self):
lc = LIFOCache(1)
sentinel = object()
out = lc.get('key', sentinel)
self.assertEqual(sentinel, out)
def test_put_key_in_cache(self):
lc = LIFOCache(1)
lc.put('key', 1)
out = lc.get('key', object())
self.assertEqual(1, out)
self.assertEqual(1, lc... | |
<reponame>xiongxianzhu/qingmi
# coding: utf-8
import random
from datetime import datetime
from qingmi.base import db, cache
from qingmi.utils import today
class Item(db.Document):
""" 选项 """
MENU_ICON = 'gear'
TYPE = db.choices(INT='整数', FLOAT='浮点数', STRING='字符串', BOOLEAN='布尔值')
name = db.StringField(max_lengt... | |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
from matplotlib import cm
import torch
"""
Adapted from https://github.com/bamsumit/slayerPytorch and PySNN (https://github.com/BasBuller/PySNN)
"""
#########################################################
# Event base class
######... | |
"""
flask_clova
~~~~~~~~~~~
:copyright: (c) 2018 by <NAME>. <EMAIL>
:license: MIT, see LICENSE for more details.
:All the structure and ideas were copied after seeing flask-ask
:flask-ask github: https://github.com/johnwheeler/flask-ask
"""
import os
import yaml
import inspect
from functools import partial
fro... | |
<gh_stars>0
"""
Django views for interacting with Part app
"""
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.files.base import ContentFile
from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.utils import IntegrityError
from django.shor... | |
cc_1 = fac.CounterCondition(min=0, max=1, metadata=pyxb.utils.utility.Location('./pug_rest.xsd', 128, 6))
counters.add(cc_1)
cc_2 = fac.CounterCondition(min=0, max=1, metadata=pyxb.utils.utility.Location('./pug_rest.xsd', 129, 6))
counters.add(cc_2)
cc_3 = fac.CounterCondition(min=0, max=1, metadata=pyxb.utils.util... | |
"""Example module in template package."""
import os
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_validate, GridSearchCV
from sklearn.neighbors import KNeighborsClassifier, KNeig... | |
import logging
import os
import shutil
from pathlib import Path
from typing import Any, Dict, Optional, Union
import torch
from transformers import (
AutoConfig,
AutoModel,
AutoModelForCausalLM,
AutoModelForQuestionAnswering,
AutoModelForSequenceClassification,
AutoModelForTokenClassification,
AutoTokenizer,
P... | |
self, func, name=None, multioutput="uniform_average", sp=1, square_root=False
):
self.square_root = square_root
super().__init__(func=func, name=name, multioutput=multioutput, sp=sp)
class _PercentageForecastingErrorMetric(
_PercentageErrorMixin, BaseForecastingErrorMetricFunc
):
def __init__(self, func, name=No... | |
points for inequality data minimal bound
:param vIneqMin: (1-dimensional array or float or None) value
at conditioning points for inequality data minimal bound
(same type as xIneqMin)
:param xIneqMax: (1-dimensional array or float or None) coordinate of
conditioning points for inequality data maximal bound
:para... | |
import numpy as np
from scipy.stats import norm
import pandas
from tqdm import tqdm
import random
import torch
import statsmodels.api as sm
import statsmodels.formula.api as smf
# Load kcgof for testing conditional
import kcgof.util as util
import kcgof.cdensity as cden
import kcgof.cgoftest as cgof
import kcgof.kerne... | |
fixed ip on network %s', network['uuid'],
instance_uuid=instance_id)
self._allocate_fixed_ips(context, instance_id, host, [network])
return self.get_instance_nw_info(context, instance_id, rxtx_factor,
host)
# NOTE(russellb) This method can be removed in 2.0 of this API. It is
# deprecated in favor of the method ... | |
s):
# Solve
#
# [ P A' G' ] [ ux ] [ bx ]
# [ A 0 0 ] [ uy ] = [ by ]
# [ G 0 -W'*W ] [ W^{-1}*uz ] [ bz - W'*(lmbda o\ bs) ]
#
# us = lmbda o\ bs - uz.
#
# On entry, x, y, z, s contains bx, by, bz, bs.
# On exit they contain x, y, z, s.
# s := lmbda o\ s
# = lmbda o\ bs
misc.sinv(s, lmbda, dims)
# z :... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.