input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
# -*- coding: utf-8 -*-
from __future__ import print_function, division
# QuSpin modules
# numpy modules
import numpy as _np # generic math functions
# _scipy modules
import scipy as _scipy
import scipy.sparse as _sp
from scipy.sparse.linalg import expm_multiply as _expm_multiply
# multi-processing modules
from multip... | |
self.ruler_delta <= self.MIN_SCALE_DELTA:
return False
delta = self.upbound - self.lowbound
rate = delta /self.ruler_delta
if rate < self.ZOOM_IN_RATE:
return True
def change_upbound_in_ruler(self, value):
self.set_action('上限設為{}'.format(value))
tmp_step = (value - self.upbound ) / self.parent.animate_num
... | |
timezone.localize(eta_or_arrival)
logger.debug("Arrival time for this sailing was {}".format(eta_or_arrival))
arrived = True
else:
logger.debug("No ETA or arrival time")
eta_or_arrival = None
arrived = False
# Get or create a Status object for this sailing
status_o, created = Status.objects.get_or_create(
sta... | |
Leakage': 0.00611897,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00348781,
'Renaming Unit/Peak Dynamic': 4.56169,
'Renaming Unit/Runtime Dynamic': 0.366125,
'Renaming Unit/Subthreshold Leakage': 0.070483,
'Renaming Unit/Subthreshold Leakage with power gating': 0.0362779,
'Runtime ... | |
for
details. Defaults to False.
name : str or None (optional)
Name for model, to be used in plots and in saving files.
load_from_file : str or None (optional)
This module uses an iterative approach to fitting models.
For complicated models with lots of data, each iteration
can take a long time (though the number... | |
<reponame>ktelep/Zabbix-DellEMC-PowerMax<filename>zabbix_powermax.py<gh_stars>1-10
#!/usr/bin/python3
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
import sys
import json
import PyU4V
import argparse
import traceback
import logging
import logging.handlers
from pyzabbix import ZabbixMetric, ZabbixSender
# Upda... | |
"""
rotate = np.random.random() < self.rotate_ratio
if rotate:
angle = self.angle
for key in self.keys:
img = results[key].copy()
results[key] = self._rotate_img(img, angle)
else:
angle = 0
results['rotate'] = rotate
results['rotate_angle'] = angle
return results
def __repr__(self):
repr_str = self.__cl... | |
<gh_stars>10-100
""" Data objects in group "Zone Airflow"
"""
from collections import OrderedDict
import logging
from pyidf.helper import DataObject
logger = logging.getLogger("pyidf")
logger.addHandler(logging.NullHandler())
class ZoneInfiltrationDesignFlowRate(DataObject):
""" Corresponds to IDD object `ZoneIn... | |
kwargs['labeler_algo'] = 'densenet'
if labeler_weight_filepath is None:
# kwargs['labeler_weight_filepath'] = 'zebra_v1'
# kwargs['labeler_weight_filepath'] = 'seaturtle'
# kwargs['labeler_weight_filepath'] = 'giraffe_v1'
# kwargs['labeler_weight_filepath'] = 'lynx_v3'
# kwargs['labeler_weight_filepath'] = 'seatu... | |
<reponame>haisenzhao/CarpentryCompiler
# -*- coding: utf-8 -*-
#!/usr/bin/python
import xml.etree.ElementTree as ET
import sys
import os
import re
import itertools
import shutil
# static variables
uuid_rgxp = r"[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}"
statENodes = 0
def mk_se... | |
"""
This module contains report class for classification estimators. Report includes:
* features scatter plots, distributions, correlations
* learning curve
* roc curve
* efficiencies
* metric vs cut
* feature importance
* feature importance by shuffling the feature column
All methods return objects, which hav... | |
IPv6 interface statistics last reset: never
IPv6 interface RP-traffic statistics: (forwarded/originated/consumed)
Unicast packets: 0/0/0
Unicast bytes: 0/0/0
Multicast packets: 0/12/9
Multicast bytes: 0/1144/640
'''
ShowRoutingVrfAll = {
'vrf':
{'VRF1':
{'address_family':
{'vpnv4 unicast':
{'bgp_distance_in... | |
from __future__ import division, print_function
import numpy as np
from math import factorial
from functools import wraps
from itertools import combinations, permutations
from collections import defaultdict
from pyknotid.representations.gausscode import GaussCode
from pyknotid.utils import vprint
def _to_GaussCode(r... | |
<gh_stars>0
## LSDMap_VectorTools.py
##=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
## These functions are tools to deal with vector data using shapely
##=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
## FJC
## 26/06/17
##=-=-=-=-=-=-=-=-=-=-=-=-=-=-... | |
graph
update_grouping(diagram, diagram.connectivity_graph)
# Reset RST graph if requested
if mode == 'rst':
# Create a new RST graph for the Diagram object
diagram.rst_graph = nx.DiGraph()
# Update grouping information from the grouping graph to the new RST
# graph
update_grouping(diagram, diagram.rst_graph)... | |
import cStringIO, sys, csv, copy, ImageDraw, Image, ImageClass
from FindCenter import findCenter, showIm, getBiImList, getEllipse, getView
from PyQt4 import QtGui
from myFunc import detect_peaks, pil16pil8, a16a8, getStrVal
from myMath import fitLine, fitCirc
from myFigure import myFigure
from scipy import ndimage, opt... | |
co-exist on the NetScaler appliance.<br/>Possible values = ON, OFF
"""
try :
self._l2conn = l2conn
except Exception as e:
raise e
@property
def oracleserverversion(self) :
"""Oracle server version.<br/>Default value: 10G<br/>Possible values = 10G, 11G.
"""
try :
return self._oracleserverversion
... | |
a tuple of `pint.Quantity`, otherwise, if
neither `coordinates` nor `deltas` are given, the attached coordinate information belonging
to `axis` will be used and the gradient will be returned as a tuple of `xarray.DataArray`.
Parameters
----------
f : array-like
Array of values of which to calculate the derivativ... | |
True, don't block waiting for artifact to exist if we fail to
immediately find it.
Raises:
ArtifactDownloadError: If the artifact fails to download from Google
Storage for any reason or that the regexp
defined by name is not specific enough.
"""
if not self._process_lock:
self._process_lock = _build_artifact_l... | |
#print('2',self.docks[relatedTo]['actual_plot'].getViewBox().viewRange()[1])
self.update_zoom_plot(dock_name,relatedTo)
elif self.docks[dock_name]['type'] == 'plot2D':
self.create_PlotWidget(dock_name)
# Attribution of the curves to the plots
flag = 0
self.docks[dock_name]['curve'] = {}
for variable in self.... | |
<gh_stars>1-10
import os
import skimage
import numpy as np
import platform
import cv2
import time
import csv
from skimage import io, morphology, exposure, filters, measure, util, segmentation
from scipy import signal, ndimage
from itertools import zip_longest
from .common import imimposemin
from .cellseg import ReSegCe... | |
lowercase alphanumeric characters, '-' or '.'
* start with an alphanumeric character
* end with an alphanumeric character
See https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#dns-subdomain-names
"""
)
DNSLabelName = pydantic.constr(
strip_whitespace=True,
min_length=1,
max_length=63,
... | |
<filename>tools/hum_proto/hum_proto/apploop.py
# Copyright (C) 2017 by <NAME> <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you
# may not use this file except in compliance with the License. You may
# obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unle... | |
<reponame>keiserlab/LUNA<filename>luna/interaction/calc.py
from openbabel import openbabel as ob
from operator import le, ge
from itertools import combinations, product
from collections import defaultdict
import json
from luna.interaction.config import DefaultInteractionConfig, InteractionConfig
from luna.interaction.... | |
<gh_stars>0
"""
Code source https://github.com/amdegroot/ssd.pytorch
"""
import os.path as osp
import sys
import torch
import torch.utils.data as data
from pycocotools.coco import COCO
import cv2
import numpy as np
COCO_ROOT = osp.join("dataset")
IMAGES = 'images'
ANNOTATIONS = 'annotations'
COCO_API = 'PythonAPI'
I... | |
import numpy as np
import pymc3 as pm
import theano.tensor as T
import theano.tensor.signal.conv as C
from epimodel import EpidemiologicalParameters
from epimodel.pymc3_distributions.asymmetric_laplace import AsymmetricLaplace
class RandomWalkMobilityModel(pm.Model):
def __init__(self, data, cm_plot_style=None, nam... | |
= User.objects.create_user(username=username, password=password, email=email, )
usr.user_permissions.set(perms)
self.client.login(username=username, password=password)
deadline = timezone.now() + datetime.timedelta(days=32)
postfix = ' 1'
project_1 = create_project(**{
'project_name': 'Project name' + postfix,
... | |
_SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=url, headers=header_parameters, **kwargs)
def build_paths_date_time_null_request(date_time_path: datetime.datetime, **kwargs: Any) -> HttpRequest:
accept = "application/json"
# Construct URL
url = "/paths/datetime/null/{dateTimePath... | |
0
1 1
2 2
3 3
4 4
More efficient:
>>> pd.concat([pd.DataFrame([i], columns=['A']) for i in range(5)],
... ignore_index=True)
A
0 0
1 1
2 2
3 3
4 4
"""
if isinstance(other, (Series, dict)):
if isinstance(other, dict):
other = Series(other)
if other.name is None and not ignore_index:
raise TypeError... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os, sys, re
sys.path.append("{0}/Desktop/cbmi/reproduce/python/MedicalResearchTool/objects".format(os.environ['HOME'])) #TODO
sys.path.append("{0}/Desktop/cbmi/reproduce/python/MedicalResearchTool".format(os.environ['HOME']))
import nltk
import requests
from pprin... | |
"""
primitive.py
----------
Process detected planar primitives.
Primitives are supported in vertex group format (.vg, .bvg).
Mapple as in [Easy3D](https://github.com/LiangliangNan/Easy3D)
can be used to generate such primitives from point clouds.
Otherwise, one can refer to the vertex group file format specification
... | |
if top:
self.check_top_u += u[self.slice_top]
self.check_top_v += v[self.slice_top]
self.check_top_snx += sxy[self.slice_top]*self.normal_top[1]
self.check_top_sny += syy[self.slice_top]*self.normal_top[1]
def __internal_call__(self, source, reflection_distance, forces, dipstr, dipvec, target, compute_source_veloc... | |
for the training data (combining X, Y, treatment).
dataMissing: boolean, optional (default = False)
An indicator for if data are missing or not.
Returns
-------
tree.results, tree.upliftScore :
The results in the leaf node.
'''
def classifyWithoutMissingData(observations, tree):
'''
Classifies (prediction)... | |
a callback "
"interface",
[self.implementor.location])
if not isinstance(implementee, IDLInterface):
raise WebIDLError("Right-hand side of 'implements' is not an "
"interface",
[self.implementee.location])
if implementee.isCallback():
raise WebIDLError("Right-hand side of 'implements' is a callback "
"interfac... | |
<gh_stars>10-100
#NodoContenedor
class NodoArbol:
#Constructor
def __init__(self, ValorI = [-1, ""], AnteriorI = None):
self.Valores = []
self.Hijos = []
self.Anterior = None
#Si solo se creo el Nodo
if ValorI[0]==-1 and AnteriorI == None:
for i in range(4):
if i!=3:
self.Valores.append([-1, ""])
... | |
no previous LCD
lcid_cache = getattr(c, 'lcid_cache', '')
if lcid_cache != '' and path in lcid_cache:
return lcid_cache[path]
try:
log_iter = commit.repo.log(commit._id, path, id_only=True, limit=2)
next(log_iter)
rev = next(log_iter)
return commit.repo.rev_to_commit_id(rev)
except StopIteration:
return None
... | |
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean CLI v1.0. Copyright 2021 QuantConnect Corporation.
#
# 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... | |
#Botpic:https://upload.wikimedia.org/wikipedia/commons/thumb/b/b8/Red_Rose_Photography.jpg/800px-Red_Rose_Photography.jpg
#Botpic:https://commons.wikimedia.org/wiki/File:Red_Rose_Photography.jpg
#reference:https://www.youtube.com/watch?v=SPTfmiYiuok
import discord
import os
import requests
import json
import math, ra... | |
<reponame>widgetti/react-ipywidgets<gh_stars>10-100
"""Write ipywidgets like React
ReactJS - ipywidgets relation:
* DOM nodes -- Widget
* Element -- Element
* Component -- function
"""
import copy
import logging
import sys
import threading
from dataclasses import dataclass, field
from inspect import isclass
from t... | |
<reponame>SeanCondon/onos-config-demo<filename>ocbind/lacp/interfaces/interface/config/__init__.py
# -*- coding: utf-8 -*-
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClas... | |
<gh_stars>0
"""
Simple table class.
Note that this module depends only on the Python standard library.
You can "install" it just by dropping it into your working directory.
A SimpleTable is inherently (but not rigidly) rectangular.
You should create it from a *rectangular* (2d!) iterable of data.
A SimpleTable can be ... | |
which holds an array of target lengths. For example, use the following code to find all occurrences of the ASCII string "Test" in a file:
"""
matches_iter = _find_helper(params, ctxt, scope, stream, coord, interp)
matches = list(matches_iter)
types = interp.get_types()
res = types.TFindResults()
res.count = len... | |
# Natural Language Toolkit: Classifier Utility Functions
#
# Copyright (C) 2001-2020 NLTK Project
# Author: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>> (minor additions)
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
"""
Utility functions and classes for classifiers.
"""
import math
# from nltk.util im... | |
to generate the
attribute path.
:param attribute: the name of the attribute.
:param missing: optional value to use when attribute value is None.
:param visitor: optional function responsible for obtaining the
attribute value from a node.
:return: a list of values of the required `attribute` of the
ancestor p... | |
_("Restaurants et services de restauration mobile")),
('5610', _("Restaurants et services de restauration mobile")),
('5610A', _("Restauration traditionnelle")),
('5610B', _("Cafétérias et autres libres-services")),
('5610C', _("Restauration de type rapide")),
('562', _("Traiteurs et autres services de restauration")),... | |
<gh_stars>0
#!/usr/bin/env python
"""
MIT License
Copyright (c) 2020 <NAME> <<EMAIL>>
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 limitat... | |
numpy arrays)
# # (det_scores[i] has shape: (num_detections_i)) (num_detections_i <= num_guided_anchors_in_pc_i)
# (det_fs is a list of batch_size numpy arrays)
# # (det_fs[i] has shape: (num_detections_i))
# (det_bboxes is a list of batch_size numpy arrays)
# # (det_bboxes[i] has shape: (num_detections_i, 7))
# ... | |
'Yongzhou, Hunan', 'zh': u('\u6e56\u5357\u7701\u6c38\u5dde\u5e02')},
'861399529':{'en': 'Yinchuan, Ningxia', 'zh': u('\u5b81\u590f\u94f6\u5ddd\u5e02')},
'861454768':{'en': 'TaiAn, Shandong', 'zh': u('\u5c71\u4e1c\u7701\u6cf0\u5b89\u5e02')},
'86145313':{'en': 'Tianjin', 'zh': u('\u5929\u6d25\u5e02')},
'861454766':{'... | |
it if it does not exist'''
try:
with open(EVENTS_FILE) as f:
pass
except IOError:
with open(EVENTS_FILE, "w+") as f:
pass
with open(EVENTS_FILE, "r") as f:
lines = csv.reader(f, delimiter = ',')
ids, dates, names, statuses = [], [], [], []
try:
for line in lines:
repetitions = int(line[5])
# For recurrin... | |
# 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 writing, software
... | |
accelerator.
FrameworkValueValuesEnum: Type of framework.
Fields:
acceleratorType: Type of device accelerator.
description: Description of the edge ml model. Max 8192 bytes.
framework: Type of framework.
inputTensors: List of input tensors.
inputTopics: List of input topics.
modelUri: Required. URI that points... | |
<filename>rk/rk.py
# -*- coding: utf-8 -*-
from argparse import ArgumentParser
from errno import EACCES, ENOTDIR
from getpass import getuser
from json import dumps, load
from os import link, listdir, makedirs, remove, strerror
from os.path import dirname, exists, expanduser, isdir, isfile, join
from shutil import copy... | |
<reponame>aws-solutions/serverless-transit-network-orchestrator
# !/bin/python
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""State Machine Handler module"""
from os import environ
import inspect
from time import sleep
from datetime import datetime, timede... | |
required. Alternatively where more response
headers are required setting ResponseDatesAsStrings to True will suppress
conversion of LastModified, Expires etc. to datetime, instead returning
them as strings, which canimprove performance if datetime representation
of those fields is not required.
"""
"""
response ... | |
mypandas = mypandas.loc[(mypandas['date'] >= dico['when_beg']) & (mypandas['date'] <= dico['when_end'])]
mypandas[input_field[0]] = mypandas[input_field[0]].astype(float)
mypandas = mypandas[['date', 'clustername', input_field[0]]]
mypivot = pd.pivot_table(mypandas, index='date', columns='clustername', values=input... | |
#-*- coding: utf-8 -*-
import copy
import datetime
import functools
import json
import logging
import random
import re
from contextlib import nested
import celery
import httpretty
import mock # noqa
from django.utils import timezone
from django.db import IntegrityError
from mock import call
import pytest
from nose.too... | |
# GENERATED BY KOMAND SDK - DO NOT EDIT
import komand
import json
class Component:
DESCRIPTION = "Monitors a list of groups for user membership changes"
class Input:
GROUP_IDS = "group_ids"
INTERVAL = "interval"
class Output:
USERS_ADDED_FROM_GROUPS = "users_added_from_groups"
USERS_REMOVED_FROM_GROUPS ... | |
Reply")
except Exception:
logger.exception("An error occurred handling MHP Reply!")
self.issue_err(err=self.ERR_OTHER)
def _extract_mhp_reply(self, result):
"""
Extracts the MHP processing results from the passed data.
:param result: tuple containing generation results
:return:
"""
try:
r, mhp_seq, aid, pr... | |
# coding: utf-8
"""
BillForward REST API
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
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
htt... | |
#!/usr/bin/env python
"""Utility functions and classes for creating mixture models"""
########################################################################
# File: mixture_model.py
#
# Author: <NAME>
# History: 1/7/19 Created
########################################################################
import os
import... | |
299792458. # speed of light in m/s
ceq = spfit.spfitPrediction(fname = fegy)
ceq.read_egy()
ceq.read_cat()
self.egy_mhz = ceq.egy_content['egy']*c*100./1.e6
self.egy_qn = ceq.egy_content['qn']
self.cat_qn = ceq.cat_content['qn']
self.cat_mhz = ceq.cat_content['freq']
self.cat_logint = ceq.cat_content['lgint']... | |
<reponame>gonzalesMK/MetaHeuristic<filename>feature_selection/meta_base.py<gh_stars>10-100
from abc import ABCMeta
from warnings import warn
from itertools import compress
from random import sample
import random
import numpy as np
from sklearn.base import BaseEstimator, MetaEstimatorMixin, TransformerMixin, clone
from ... | |
<reponame>yxzoro/pypy
"""The builtin str implementation"""
from rpython.rlib.objectmodel import (
compute_hash, compute_unique_id, import_from_mixin,
enforceargs)
from rpython.rlib.rstring import StringBuilder, UnicodeBuilder
from rpython.rlib.runicode import (
make_unicode_escape_function, str_decode_ascii, str_de... | |
PackagesUploadNpm data:
:return: AlpinePackageUpload
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.packages_upload_npm_with_http_info(owner, repo, **kwargs)
else:
(data) = self.packages_upload_npm_with_http... | |
<filename>src/api-server/venv/lib/python3.8/site-packages/aniso8601/tests/test_duration.py
# -*- coding: utf-8 -*-
# Copyright (c) 2021, <NAME>
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the BSD license. See the LICENSE file for details.
import unittest
import aniso8... | |
home_team_data.pop("pitching_stats", None)
home_team_data["batting_stats"] = bat_stats_home
home_team_data["pitching_stats"] = pitch_stats_home
game_meta_info = self.boxscore.game_meta_info.as_dict()
game_meta_info.pop("__bbref_boxscore_meta__", None)
game_meta_info["game_time_hour"] = self.game_start_time.hour
... | |
import csv
import logging
from apps.projects.models import ProjectBudgetLine
from bluebottle.payments.models import OrderPayment
import os
from registration.models import RegistrationProfile
from django.utils import timezone
from django.conf import settings
from apps.cowry_docdata.models import payment_method_mapping
f... | |
= response.text #Получаем HTML код страницы
if "строения" in html: #Получаем информацию о строениях
soup = BS(html, "html.parser")
elems = soup.findAll("a", class_="lwhite")
for elem in elems:
elem = elem.text
if "из" in elem:
if "Академия" in elem:
data["academy_level"] = elem.split("(")[1].split("из")... | |
each pair
input/output.
speed_range : array
Array with the frequencies.
velc_resp : array
Array with the velocity response for each node for each pair
input/output.
accl_resp : array
Array with the acceleration response for each node for each pair
input/output.
Examples
--------
>>> rotor = rotor_example()... | |
<filename>2 Evaluating Passes/Christian Gilson - Evaluating Passes Assignment.py<gh_stars>1-10
#!/usr/bin/env python
# coding: utf-8
# ## Evaluating Passes Assignemnt
# In[1]:
# standard imports
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from collections import Counter
import json
import ... | |
from __future__ import absolute_import, division, print_function
import cStringIO
import sys, os, re
from six.moves import zip
def check_bin_format(bin):
try :
d_max, d_min = float(bin[0]), float(bin[1])
except ValueError as e :
raise RuntimeError("%s\nOffending values: %s, %s"%(str(e),bin[0],bin[1]))
def float_... | |
#Imports
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from datetime import datetime
import os
import glob
import random
# import imgaug
# from imgaug import augmenters as iaa
from PIL import Image
from tqdm import tqdm
import matplotlib.pyplot as plt
im... | |
adaptive stepsize.
#
# For now, we use a heuristic that catches very bad gradients, but is not
# perfectly accurate.
type_eps = {'float64': 1e-7,
'float32': 3e-4,
numpy.dtype('float64'): 1e-7,
numpy.dtype('float32'): 3e-4}
def __init__(self, f, pt, eps=None, out_type=None):
"""Return the gradient of f at pt.
... | |
<gh_stars>0
import os
import torch
import copy
import time
import random
from arguments import get_args
import numpy as np
import cma
import json
import deepspeed
from sklearn.metrics import f1_score
from tokenization_enc_dec import EncDecTokenizer
from fastNLP import cache_results, DataSet
from tester import Tester
im... | |
#!/bin/python
import sys
import numpy as np
class TITAN:
'''Titan orbit functions and parametes'''
def __init__(self):
'''Init default parameters'''
self.Tday = 15.945 # Earth days / 1 Saturn orbit
# Default orbit parameters calculated with NAIF Space Kernels
self.date = [np.datetime64('1980-01-02'),np.datetim... | |
a = self.RPythonAnnotator()
t = a.translator
s = a.build_types(f, [])
assert s.knowntype == int
graph = tgraphof(t, A.__del__.im_func)
assert graph.startblock in a.annotated
def test_annotate_type(self):
class A:
pass
x = [A(), A()]
def witness(t):
return type(t)
def get(i):
return x[i]
def f(i):
witnes... | |
<gh_stars>0
"""
File: my_drawing
Name: <NAME>
----------------------
TODO:
"""
from campy.graphics.gobjects import GOval, GRect, GLine, GPolygon, GArc, GLabel
from campy.graphics.gwindow import GWindow
# globe variable
window = GWindow(width=600, height=800, title='We are coming in.')
def main():
"""
the idea is... | |
<filename>oahapi/ratechecker/management/commands/load_daily_data.py
import os
import sys
import re
import zipfile
import StringIO
import contextlib
from datetime import datetime
from csv import reader
from decimal import Decimal
from operator import itemgetter
try:
import xml.etree.cElementTree as ET
except ImportErr... | |
assert round(calc_attr.alpha_rad_outer_rt, 5) == 5.0
assert round(calc_attr.alpha_comb_outer_rt, 1) == 25.0
# window
assert round(calc_attr.ua_value_win, 16) == 32.87895310796074
assert round(calc_attr.area_win, 1) == 18.0
assert round(calc_attr.r_conv_inner_win, 19) == 0.032679738562091505
assert round(calc_att... | |
#!/usr/bin/python
def param_gui(self):
param_gui = [
self.K1, self.P1, self.e1, self.om1, self.ma1, self.incl1, self.Omega1,
self.K2, self.P2, self.e2, self.om2, self.ma2, self.incl2, self.Omega2,
self.K3, self.P3, self.e3, self.om3, self.ma3, self.incl3, self.Omega3,
self.K4, self.P4, self.e4, self.om4, self.... | |
<gh_stars>1-10
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report
from sklearn.metrics import roc_auc_score
from sklearn.metrics import f1_score
from scipy import stats
import li... | |
<reponame>ru-gh/Password-Manager
import sqlite3
import pathlib
from PyQt5 import QtCore, QtGui, QtWidgets
s = None
accounts = pathlib.Path("Accounts.db")
user = pathlib.Path("User.db")
lam = [[user, 0], [accounts, 1]]
for file in lam:
print(file[0])
if file[0].exists():
print("File exist")
elif file[1] == 0:
prin... | |
0.00635083268962935*m.x834 + m.x2334 == 0)
m.c1335 = Constraint(expr= - m.x825 - 0.11270166537926*m.x830 - 0.00635083268962935*m.x835 + m.x2335 == 0)
m.c1336 = Constraint(expr= - m.x836 - 0.5*m.x841 - 0.125*m.x846 + m.x2336 == 0)
m.c1337 = Constraint(expr= - m.x837 - 0.5*m.x842 - 0.125*m.x847 + m.x2337 == 0)
m.c133... | |
<gh_stars>0
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import re
from datetime import datetime
from django.db import models
from django.core.urlresolvers import reverse
from rapidsms.webui.managers import *
from patterns.models import Pattern
from locations.models import *
# TODO: remove this. it's a slight... | |
video_mapping = {'Algebra': [(u'Simple Equations', u'9Ek61w1LxSc', u'simple-equations'),
(u'Equations 2', u'XoEn1LfVoTo', u'equations-2'),
(u'Equations 3', u'f15zA0PhSek', u'equations-3'),
(u'Algebra Linear Equations 4',
u'9IUEk9fn2Vs',
u'algebra--linear-equations-4'),
(u'Algebra Solving Inequalities',
u'VgDe_D8... | |
type: str
# type
self.type = type # type: str
# upload_id
self.upload_id = upload_id # type: str
def validate(self):
if self.domain_id is not None:
self.validate_max_length(self.domain_id, 'domain_id', 50)
self.validate_pattern(self.domain_id, 'domain_id', '[a-z0-9]{1,50}')
if self.drive_id is not None:
self... | |
= []
self.blockEditListSizer = blockEditListSizer = wx.BoxSizer(wx.VERTICAL)
for idx in range(0, 3):
p = rompanel.SpritePanel(blockWindow, wx.ID_ANY, 24, 24, self.palette, scale=2, bg=None, xpad=4, ypad=4, func=self.OnClickBlockEditPanel)
p.index = idx
self.blockEditPanels.append(p)
t = wx.StaticText(bloc... | |
# -*- coding: utf-8 -*-
#---------------------------------------------------------------------------
# Copyright 2019 VMware, Inc. All rights reserved.
# AUTO GENERATED FILE -- DO NOT MODIFY!
#
# vAPI stub file for package com.vmware.vmc.orgs.sddcs.
#--------------------------------------------------------------------... | |
or not this task supports offline caching.
"""
if not _VALID_TASK_NAME_REGEX.match(name):
raise ValueError(
"Task name '%s' contains invalid characters. Must match regex: %s" % (
name, _VALID_TASK_NAME_REGEX.pattern))
_validate_args(dataset_fn, ["split", "shuffle_files"])
for metric_fn in metric_fns:
_validate_... | |
#!/usr/bin/env python
import sys, tarfile, getopt, urllib, ConfigParser, os, os.path
import re, itertools
# Check python version as script doesn't run on 3.x
if sys.version_info >= (3, 0):
sys.stdout.write("Sorry, requires Python 2.x, not Python 3.x. You can try:\n")
sys.stdout.write("$ sudo /usr/bin/python2.7 /usr/... | |
guessChar == "Q" or guessChar == "q" :
if word[1] == "Q" or word[1] == "q" :
toGuess = toGuess[:1] + "q" + toGuess[2:]
if word[2] == "Q" or word[2] == "q" :
toGuess = toGuess[:2] + "q" + toGuess[3:]
if word[3] == "Q" or word[3] == "q" :
toGuess = toGuess[:3] + "q" + toGuess[4:]
if word[1] != "Q"... | |
are:
# 1. Replacing the userid and password with another userid and pasword
# 2. Replacing the ssh_key with another ssh_key (may or may not have a password)
# 3. Replacing the userid and password with an ssh_key
# 4. Replacing the ssh_key with a userid nad password
# 5. Not changing anything just the ip address
#... | |
<filename>egg/zoo/sum_game/play.py
# 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 argparse
import numpy as np
import torch
import torch.nn.functional as F
from torch.utils.data impor... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright 2013 Kitware 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... | |
# -*- coding: utf-8 -*-
# TODO: This thing is a beast! Refactor.
import cmd
import os
import sys
import time
import traceback
from typing import Optional, List, Iterator, Tuple, Dict
from pyramids.categorization import Category
from pyramids.model import Model
from pyramids.rules.parse_rule import ParseRule
try:
f... | |
from logging.config import dictConfig
dictConfig({
'version': 1,
'formatters': {'default': {
'format': '%(levelname)s/%(module)s %(message)s',
}},
'handlers': {'wsgi': {
'class': 'logging.StreamHandler',
'stream': 'ext://flask.logging.wsgi_errors_stream',
'formatter': 'default'
}},
'root': {
'level': 'INFO'... | |
# the node in the nodal
# equivalence table, and DOF
# is the DOF reference
# number.
#
# --- dp 1 nrf Reaction forces. The force
# values are ordered
# according to the DOF order
# shown above in the DOF
# number reference table.
# pointer to result reaction forces
rnum = self.parse_step_substep(rnum)
rpo... | |
= self._content_parsers.GetData( only_selected = True )
for content_parser in content_parsers:
with ClientGUITopLevelWindows.DialogEdit( self, 'edit content parser', frame_key = 'deeply_nested_dialog' ) as dlg:
test_context = self._test_context_callable()
panel = EditContentParserPanel( dlg, content_parser,... | |
#import cv
import cv2
import math
import numpy as np
from numpy import linalg as npla
import sys
import scipy.interpolate
import scipy.sparse
import weave
import unittest
import common
import config
def CompareMatricesWithNanElements(M1, M2):
assert M1.shape == M2.shape;
assert M1.ndim == 2;
for r in range(M1.s... | |
<reponame>astrobot/omnifit
import numpy as np
import matplotlib.pyplot as plt
from astropy import units as u
from astropy import convolution
import warnings
import pickle
import os, sys
from .. import utils
from copy import deepcopy
from functools import wraps
def clonable(func):
@wraps(func)
def wrapper(self,*args,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.