input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
np.ndarray, city_name: str) -> np.ndarray:
"""
Check whether each point is likely to be from the ground surface
Args:
point_cloud: Numpy array of shape (N,3)
city_name: either 'MIA' for Miami or 'PIT' for Pittsburgh
Returns:
is_ground_boolean_arr: Numpy array of shape (N,) where ith entry is True if the LiDAR ... | |
# -*- coding: utf-8 -*-
"""
Microsoft-Windows-AppModel-Exec
GUID : eb65a492-86c0-406a-bace-9912d595bd69
"""
from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct
from etl.utils import WString, CString, SystemTime, Guid
from etl.dtyp import Sid
from e... | |
<reponame>hjkuijf/MidsagittalApp
# **InsertLicense** code
from mevis import *
from TestSupport import Base, Fields, Logging, ScreenShot
from TestSupport.Macros import *
from AlgorithmModuleTestSupport import Checks as AMChecks
from AlgorithmModuleTestSupport import Tests as AMTests
from AlgorithmModule.Definitions imp... | |
will be ``x[k:]``. Looking at this split, elements in
``x[:k]`` are ordered exactly like those in ``init_y``.
* ``taps`` -- Temporal taps of the output that will be pass to
``fn``. They are provided as a list of *negative* integers,
where a value ``k`` implies that at iteration step ``t`` scan
will pass to ``fn`` ... | |
limit
)
)
current_app.logger.debug(q2)
result = db.session.execute(q2)
trackjson = result.fetchall()
if trackjson:
# if we have only one point
if len(trackjson) == 1:
y = trackjson[0][0]
# if we want multiple points
else:
y = ""
z = 0
for x in trackjson:
if z != 0:
y += ", "
y += x[0]
z += 1
data = '... | |
<filename>afa/core.py
import traceback
import contextlib
import statsmodels.api as sm
import pandas as pd
import numpy as np
import time
from collections import OrderedDict
from concurrent import futures
from functools import partial
from tqdm.auto import tqdm
from scipy import signal, stats
from numpy import fft
fro... | |
# coding=utf-8
import json
import luigi
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np
import os
import pandas as pd
import seaborn as sns
import sys
sys.path.append("..")
import cfg
from constants import DANGEROUS_GROUPS
from collectio... | |
# Decompiled by HTR-TECH | <NAME>
# Github : https://github.com/htr-tech
#---------------------------------------
# Auto Dis Parser 2.2.0
# Source File : fb_1.pyc
# Bytecode Version : 2.7
# Time : Sun Aug 9 11:47:46 2020
#---------------------------------------
import os
import sys
import time
import datetime
import ... | |
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.7.1
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # House Price Prediction
# ## 1. Environment S... | |
<reponame>wrattler/wrattler
# Mainly text manipulation utils
from src.utils import create_folders
# Latex, and visualization utils
from src.utils import print_to_file, save_object
import csv
import numpy as np
import os
from src.Config import Config
from src.Model import PtypeModel
from src.PFSMRunner import PFSMRun... | |
Head NMS 0%', 'grid' : False, 'algo': 'lightnet', 'config_filepath' : 'seaturtle', 'weight_filepath' : 'seaturtle', 'nms': True, 'nms_thresh': 0.00, 'species_set' : set(['turtle_hawksbill+head'])},
# {'label': 'Hawksbill Head NMS 10%', 'grid' : False, 'algo': 'lightnet', 'config_filepath' : 'seaturtle', 'weight_filepa... | |
import argparse
import collections
import datetime
import os
import shutil
import time
import dataset
import mlconfig
import toolbox
import torch
import util
import madrys
import numpy as np
from evaluator import Evaluator
from tqdm import tqdm
from trainer import Trainer
mlconfig.register(madrys.MadrysLoss)
# General... | |
from __future__ import annotations
import functools
import logging
import numpy as np
import torch
import torch.nn as nn
import torch_geometric
import torchmetrics
from envs import shipping_assignment_state
from envs.shipping_assignment_env import ShippingAssignmentEnvironment
from torch import Tensor
from torch_geom... | |
as initial
state for the sample of index i in the following batch.
unroll: Boolean (default False).
If True, the network will be unrolled,
else a symbolic loop will be used.
Unrolling can speed-up a RNN,
although it tends to be more memory-intensive.
Unrolling is only suitable for short sequences.
input_dim: di... | |
"""
All parameters (excluding superparameters) in the model should be in theano var-
iables or theano shared values. In the training part, these variables should be
organized into "theano.function"s. So there should be no theano.function in the
definition of models here. Except for analysis part of codes.
"""
import n... | |
import numpy as np
import string
import re
__all__ = ['BADAA',
'AALPHABET',
'convertHLAAsterisk',
'isvalidmer',
'isvalidHLA',
'rankEpitopes',
'rankKmers',
'rankMers',
'getIC50',
'getMers',
'getMerInds',
'grabKmer',
'grabKmerInds',
'findpeptide',
'grabOverlappingKmer',
'overlappingMers']
BADAA = '-*BX#Z... | |
<filename>python/train_and_eval.py<gh_stars>1-10
import torch, random, sys, torch.nn as nn, re
from utils import *
def train(args, encoder, decoder, criterion, encoder_optimizer, decoder_optimizer, train_dl, epoch, visualize=False, params=None):
"""
One epoch
"""
if encoder:
encoder.train()
decoder.train()
t... | |
<gh_stars>1-10
from textwrap import dedent
def get_static_part(protocol):
s = dedent("""
Communication protocol specification
====================================
Communication protocol v{0}
.. contents::
:local:
Protocol description
--------------------
Controller can be controlled from the PC using ser... | |
* mask
# if bias is not None and ctx.needs_input_grad[2]:
if ctx.needs_input_grad[2]:
grad_bias = grad_output.sum(0).squeeze(0)
return grad_input, grad_weight, grad_bias, grad_mask
class SparseLinear(nn.Module):
def __init__(self, input_features, output_features, bias=True, mask=None):
"""
Argumens
--------... | |
<reponame>codedsk/hubcheck-hubzero-tests<gh_stars>1-10
import unittest
import sys
import os
import pytest
import re
from string import Template
import hubcheck
from hubcheck.testcase import TestCase2
from hubcheck.shell import ContainerManager
pytestmark = [ pytest.mark.container,
pytest.mark.rappture,
pytest.mark... | |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | |
IdealSolution) and not self.has_henry_components
self.Hfs = Hfs
self.Gfs = Gfs
self.Sfs = Sfs
if T is not None and P is not None and zs is not None:
self.T = T
self.P = P
self.zs = zs
def to_TP_zs(self, T, P, zs):
T_equal = hasattr(self, 'T') and T == self.T
new = self.__class__.__new__(self.__class__)
ne... | |
of the Traffic Manager profile to use, if
it exists. Traffic Manager resource ID is of the form
/subscriptions/{subId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficManagerProfiles/{profileName}.
:paramtype traffic_manager_profile_id: str
:keyword traffic_manager_profile_name: Name of Traffi... | |
fft(u) = w*fft(p), see (6) Stanley & <NAME>. 119(3), 481-485
(Jul 01, 1997).
For the infinite halfspace,
.. math ::
w = q E^* / 2
q is the wavevector (:math:`2 \pi / wavelength`)
WARNING: the paper is dimensionally *incorrect*. see for the correct
1D formulation: Section 13.2 in
<NAME>. (1985). Contact Mech... | |
<gh_stars>1-10
#!/usr/bin/env python3
import asyncio
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from functools import partial
from io import BytesIO, TextIOWrapper
import os
from pathlib import Path
import re
import sys
from tempfile import TemporaryDirectory
from typing imp... | |
"""Subclass of prediction specialized in representing numeric predictions, thus
a prediction where both fitted and real data are either ints or floats.
It allows to compute accuracy metrics that represent the distance between
the prediction and the real values."""
from __future__ import annotations
from typing import... | |
<reponame>langmead-lab/FORGe
#! /usr/bin/env python
"""
Given a SAM file with read names in Mason 1 format, Qsim tandem read format,
Extended wgsim format, or Bowtie 2 --hints format, measure how many are
correct.
"""
from __future__ import print_function
import sys
import re
"""
Example: 10_26049747_26049846_0:0:0... | |
is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-l2vpn-cfg:aps'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self.enable is not None:
return Tru... | |
# -*- coding: utf-8 -*-
#
# A module to interface with PullString's Web API.
#
# Copyright (c) 2016 PullString, Inc.
#
# The following source code is licensed under the MIT license.
# See the LICENSE file, or https://opensource.org/licenses/MIT.
#
"""
PullString Python SDK
This package provides a module to access the... | |
# -*- coding: utf-8 -*-
###########################################################################
## Python code generated with wxFormBuilder (version Oct 26 2018)
## http://www.wxformbuilder.org/
##
## PLEASE DO *NOT* EDIT THIS FILE!
###########################################################################
impor... | |
<reponame>jmflorez/pymatgen
#!/usr/bin/env python
"""
Module which defines basic entries for each ion and oxide to compute a
Pourbaix diagram
"""
from __future__ import division
__author__ = "<NAME>"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "0.0"
__maintainer__ = "<NAME>"
__email__ = "<E... | |
<gh_stars>1-10
import numpy as np
import math
def prod(it):
p = 1
for n in it:
p *= n
return p
def Ufun(x, a, k, m):
y = k * ((x - a) ** m) * (x > a) + k * ((-x - a) ** m) * (x < (-a))
return y
class F1:
def __init__(self, num_dimensions):
self.dimensions = num_dimensions
self.low = -100... | |
# No Bugs in Production (NBP) Library
# https://github.com/aenachescu/nbplib
#
# Licensed under the MIT License <http://opensource.org/licenses/MIT>.
# SPDX-License-Identifier: MIT
# Copyright (c) 2019-2020 <NAME> <https://github.com/aenachescu>
#
# Permission is hereby granted, free of charge, to any person obtaining ... | |
import os
import tempfile
import pandas
import tensorflow as tf
import zipfile
import cloudpickle
import numpy as np
import random
import gym
from gym_gazebo.envs import gazebo_env
import baselines.common.tf_util as U
from baselines import logger
from baselines.common.schedules import LinearSchedule
from baselines imp... | |
'0584', 'region_code': '05',
'region_name': 'Östergötlands län', 'hits': 6,
'ad_ids': ['24636656', '24631849', '24613868', '24605632', '24597399', '24579124']},
{'id': 'stqv_JGB_x8A', 'name': 'Mjölby', 'type': 'municipality', 'code': '0586', 'region_code': '05',
'region_name': 'Östergötlands län', 'hits': 17,
'ad... | |
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import time
import logging
from sklearn.metrics import roc_auc_score
from sklearn.cluster import KMeans
from sklearn.manifold import TSNE
from src.models.optim.Loss_Functions import DMSADLoss
from src.utils.utils import print_progessbar
... | |
5/2017 2 0.0004
c -ni 292.3 1.4330 5/2017 3 0.0055
cy-n2 301.9 1.4240 5/2017 3 0.0008
op-p5 342.6 1.6180 5/2017 3 0.0012
cx-sp 190.9 1.8240 5/2017 3 0.0172
hn-nl 442.6 1.0480 5/2017 3 0.0410
nn-p5 279.9 1.6650 5/2017 2
nj-p5 208.6 1.7630 5/2017 2 0.0519
cc-sq 218.4 1.7770 5/2017 3 0.0006
c2-cv 484.2 1.3330 5/2... | |
vessel_ownership_data.get(key)})
# overwrite vessel_data.id with correct value
if type(instance.child_obj) == MooringLicenceApplication and vessel_data.get('readonly'):
# do not write vessel_data to proposal
pass
else:
serializer = SaveDraftProposalVesselSerializer(instance, vessel_data)
serializer.is_valid(rais... | |
#!/usr/bin/python3.5
from time import time
from datetime import datetime
import requests
import logging
import coloredlogs
from bs4 import BeautifulSoup
# import tldextract
from urllib.parse import urljoin # , urlparse
from tld import get_tld
from pytrie import StringTrie
from multiprocessing import Pool # processes
i... | |
shape (batch_size, num_candidates), in which each prediction is a
num_candidates-long binary vector (with 0 or more 1's and the rest 0).
(num_candidates may vary over batches; in that case the metrics macro- microP/R/F1 are not available,
but Acc and MRR are)
target:
binary targets; either for each instance as ind... | |
<reponame>jalayrupera/Sentiment-analysis-on-amazon-product
# -*- coding: utf8 -*-
import numpy as np
import pickle
import Tree
class RNN(object):
"""Class to use Recursive Neural Network on Tree
Usage
-----
Methods
-------
"""
def __init__(self, vocab={}, dim=30, r=0.0001, reg=1):
self.dim = dim
#Initia... | |
Dict) -> 'GetSecret':
"""Initialize a GetSecret object from a json dictionary."""
args = {}
if 'metadata' in _dict:
args['metadata'] = CollectionMetadata.from_dict(_dict.get('metadata'))
else:
raise ValueError('Required property \'metadata\' not present in GetSecret JSON')
if 'resources' in _dict:
args['resourc... | |
@classmethod
def poll(cls, context):
ob = context.active_object
return(ob and ob.type == 'MESH' and context.mode == 'EDIT_MESH')
def draw(self, context):
layout = self.layout
col = layout.column()
col.prop(self, "interpolation")
col.prop(self, "input")
col.prop(self, "iterations")
col.prop(self, "regular"... | |
= col.getLiteralSeg(False, segments[op], best[-1][-1])
if best[-1][-1] is not None:
cands.append(Extension(self.constraints.getSSetts(), best))
return cands
################################################################### PAIRS METHODS
###################################################################
def com... | |
<filename>final_pipeline/lp_solver.py
import cvxpy as cp
import numpy as np
import geopandas as gpd
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
import matplotlib.cm as cm
from shapely.geometry import box, Point, LineString, Polygon, MultiPolygon
import shapely.geometry
from shapely... | |
clear : boolean
Clear the color, stencil and depth buffer.
"""
# if monoscopic, nop
if self._monoscopic:
warnings.warn("`setBuffer` called in monoscopic mode.", RuntimeWarning)
return
# check if the buffer name is valid
if buffer not in ('left', 'right'):
raise RuntimeError("Invalid buffer name specified.")
... | |
import geopandas
import pandas as pd
import xarray as xr
import dataimports.waterboundary as wbd
from shapely.geometry import Polygon
def aggregateprocessedfiles(directory: str, years: range) -> pd.DataFrame:
'''
Generates a new dataframe in the form:
index 1 2 ... n-1 n
<year 1>
<year 2>
.
.
.
<year t -... | |
after
it completes.
:param int status: the exit code of the process
.. versionadded:: 1.2
"""
# in many cases, the channel will not still be open here.
# that's fine.
m = Message()
m.add_byte(cMSG_CHANNEL_REQUEST)
m.add_int(self.remote_chanid)
m.add_string('exit-status')
m.add_boolean(False)
m.add_int(sta... | |
in source["url"] or "pypi.org" in source["url"]
for source in sources
):
pkg_url = "https://pypi.org/pypi/{0}/json".format(name)
session = _get_requests_session()
try:
# Grab the hashes from the new warehouse API.
r = session.get(pkg_url, timeout=10)
api_releases = r.json()["releases"]
cleaned_releases = {}
f... | |
default ([Any], optional): Value if not found. Defaults to None.
fontem (dict): An nested object to search
Returns:
[Any]: Return the result. Defaults to default
"""
if fontem is None:
fontem = self.crudum
keys = dotted_key.split('.')
return reduce(
lambda d, key: d.get(
key) if d else default, keys, fontem... | |
<filename>kakao/kakao.py
import sys
import struct
import base64
import rsa as RSA
import socket
import bson
import json
import urllib, urllib2
import httplib
from bson import BSON
from bson.py3compat import b
from Crypto.Cipher import AES
from pkcs7 import PKCS7Encoder
encoder = PKCS7Encoder()
aes_key='\<KEY>'
sKey =... | |
<reponame>houqp/rp2
# Copyright 2021 eprbell
#
# 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 ... | |
# Copyright (c) 2021 AccelByte Inc. All Rights Reserved.
# This is licensed software from AccelByte Inc, for limitations
# and restrictions contact your company contract manager.
#
# Code generated. DO NOT EDIT!
# template file: justice_py_sdk_codegen/__main__.py
# justice-iam-service (5.10.1)
# pylint: disable=dup... | |
from glob import glob
import random
from statistics import mode
import sys
def ko(dataarray, name):
#winnerlist = []
playeramount = int(dataarray.pop(0))
playerlist = dataarray
if playeramount % 2 == 1:
print("Deine Spielerzahl ist leider ungerade somit geht das KO System nicht auf")
ask = input("Es wird nun ein ... | |
weak mpifcmb3_
#pragma weak MPIFCMB3__
#pragma weak mpifcmb3__
#pragma weak MPIFCMB4
#pragma weak mpifcmb4
#pragma weak MPIFCMB4_
#pragma weak mpifcmb4_
#pragma weak MPIFCMB4__
#pragma weak mpifcmb4__
/* Argonne Fortran MPI wrappers */
#pragma weak MPIR_F_MPI_BOTTOM
#pragma weak MPIR_F_MPI_IN_PLACE
#pragma weak MPI_F_M... | |
# doctest: +NORMALIZE_WHITESPACE
★
/ ★
/ ★
/ ★
<BLANKLINE>
★
/ / ★
/ ★
<BLANKLINE>
/ ★
/ / ★
<BLANKLINE>
★
/ ★
/ / ★
<BLANKLINE>
★
/ / / ★
>>> print(next(representations)) # doctest: +NORMALIZE_WHITESPACE
★
/ ★
/ ★
/ ★
/ ★
<BLANKLINE>
★
/ / ★
/ ★
/ ★
<BLANKLINE>
/ ★
/ / ★
/ ★
<BLANKLIN... | |
elif isinstance(desc[key], dict) and 'constraint__' in desc[key]: # This is a constraint
res.append([(1, path + [key], desc[key])])
elif isinstance(desc[key], dict):
res += walk_props_for_constraints(desc[key], path + [key])
elif key != "name" or path != "": # Add an equality constraint for a value, except the obje... | |
# -*- coding: utf-8 -*-
# *****************************************************************************
# Copyright (C) 2003-2006 <NAME>.
# Copyright (C) 2006 <NAME>. <<EMAIL>>
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
# ********... | |
<filename>coredis/tokens.py
from __future__ import annotations
from coredis._utils import CaseAndEncodingInsensitiveEnum
class PureToken(CaseAndEncodingInsensitiveEnum):
"""
Enum for using pure-tokens with the redis api.
"""
#: Used by:
#:
#: - ``ACL LOG``
RESET = b"RESET"
#: Used by:
#:
#: - ``BGSAVE``
... | |
import json
import os
import numpy as np
from keras.optimizers import RMSprop, Optimizer
from keras.models import Model
from keras.layers import Input, Dense
from keras.initializers import RandomNormal
from keras.utils import plot_model
from keras.layers import Layer
import keras.backend as K
from PIL import Image
from... | |
<filename>mmedit/datasets/pipelines/bsrgan_degradation.py
import warnings
warnings.filterwarnings('ignore')
import os
from concurrent.futures import ThreadPoolExecutor
import numpy as np
import cv2
from scipy.interpolate import interp2d
from ..registry import PIPELINES
# blur
class BlurKernel2D(object):
def check... | |
<gh_stars>0
"""
This module contains Fab's `main` method plus related subroutines.
`main` is executed as the command line ``fab`` program and takes care of
parsing options and commands, loading the user settings file, loading a
fabfile, and executing the commands given.
The other callables defined in this module are ... | |
Integer, ForeignKey(apply_schema('series.id', 'musicbrainz'), name='series_tag_raw_fk_series'), primary_key=True, nullable=False)
editor_id = Column('editor', Integer, ForeignKey(apply_schema('editor.id', 'musicbrainz'), name='series_tag_raw_fk_editor'), primary_key=True, nullable=False)
tag_id = Column('tag', Intege... | |
= False):
h_C, h_C_new, h_r, h_lamb, h_part,h_step = history[:]
plt.figure()
iters = np.arange(len(h_C))
plt.subplot(6,1,1)
plt.plot(iters,np.log(h_C),':')
#plt.plot(iters,np.log(h_C_new),'o:')
step_logic = np.asarray(h_step) == 1
plt.plot(iters[step_logic],np.log(h_C_new)[step_logic],'og')
plt.plot(iters[~s... | |
lots=[
api_stubs.lot(slug='digital-specialists', allows_brief=True),
]
)
data_api_client.get_brief.return_value = api_stubs.brief()
content_fixture = ContentLoader('tests/fixtures/content')
content_fixture.load_manifest('dos', 'data', 'edit_brief')
content_loader.get_manifest.return_value = content_fixture.get_... | |
<filename>teslakit/plotting/wts.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# common
import os
import os.path as op
from datetime import datetime, timedelta
# pip
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.dates as mdates
import matplotlib.colors ... | |
'''
This repository is used to implement all blocks and tools for Efficient SR
@author
<NAME> from SIAT
<NAME> from SIAT
'''
from functools import partial
import torch
import torch.nn as nn
import math
import torch.nn.functional as F
from distutils.version import LooseVersion
# 1*1卷积使用nn.Linear实现
class DepthWiseC... | |
save_bags=True):
self.div_func = div_func
self.K = K
self.tuning_folds = tuning_folds
self.n_proc = n_proc
self.sigma_vals = sigma_vals
self.scale_sigma = scale_sigma
self.weight_classes = weight_classes
self.cache_size = cache_size
self.tuning_cache_size = tuning_cache_size
self.svm_tol = svm_tol
self.tunin... | |
from kivy.config import Config
Config.read("BattleBox.ini")
from kivy.app import App
from kivy.animation import Animation
from kivy.clock import Clock
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.uix.textinput import TextInput
from kivy.uix.dropdown import DropDown
from kivy.uix.button imp... | |
= pickler()
p.dump(spectrum, filename, gzip = 0)
self.debug('Time: %ss' % str(clock()-t))
self.message('Assigned spectrum "%s" written to file %s"' \
% (spectrum.getName(), filename))
def _dump_ccpn(self, iteration, path, is_water_refinement=False):
from aria.Singleton import ProjectSingleton
project = Proj... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# This material is part of "The Fuzzing Book".
# Web site: https://www.fuzzingbook.org/html/RailroadDiagrams.html
# Last change: 2019-01-04 16:03:17+01:00
#
#!/
# Copyright (c) 2018-2019 Saarland University, CISPA, authors, and contributors
#
# Permission is hereby grante... | |
""" This module deals with support of the color in the terminal through ANSI
escape codes. It defines the high level class ColoredStr which is a string
containing color escape codes ready to be printed in color to the terminal.
"""
import re
# There are three possible types of ANSI escape codes to print text in colo... | |
from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
from future.moves.urllib.parse import urlparse
from future.utils import text_to_native_str
import os
import logging
import base64
import re
from datetime import datetime
fro... | |
copy to the same tree otherwise it will be on infinite loop
if recursive and (self.page == destination or destination.is_descendant_of(self.page)):
return False
# reject inactive users early
if not self.user.is_active:
return False
# reject early if pages of this type cannot be created at the destination
if no... | |
for x in self.ont_graph if bad_content in str(x[0]) or bad_content in str(x[2])]
for e in bad_triple: # repair bad triple -- assuming for now the errors are mis-typed string errors
self.ont_graph.add((e[0], e[1], Literal(str(e[2]), datatype=schema.string))); self.ont_graph.remove(e)
self.ontology_info[key]['ValueEr... | |
import os
import sys
import re
import json
import pickle
import h5py
import nltk
import numpy as np
import jsonlines
from collections import defaultdict
from sklearn.model_selection import StratifiedKFold
import config
def pickle_loader(filename):
if sys.version_info[0] < 3:
return pickle.load(open(filename, 'rb'... | |
SOCCOM float profiles in text format from FloatViz FTP server.
Args:
save_to_root: path of main Argo data directory of interest
"""
save_to_floats = save_to_root + 'SOCCOM_HiResQC_ftp_' + datetime.today().strftime('%Y-%m-%d') + '/'
os.mkdir(save_to_floats)
ftp_root = 'ftp.mbari.org'
url_root = 'pub/SOCC... | |
<reponame>marioskatsak/lxmert<filename>src/tasks/rosmi_backup.py
# coding=utf-8
# Copyleft 2019 project LXRT.
import os, time
import collections
import torch, json
import torch.nn as nn
import numpy as np
import difflib
from torch.autograd import Variable
from torch.utils.data.dataloader import DataLoader
from tqdm ... | |
<reponame>thesamesam/pkgcore
"""Utilities for writing commandline utilities.
pkgcore scripts should use the :obj:`ArgumentParser` subclass here for a
consistent commandline "look and feel" (and it tries to make life a
bit easier too). They will probably want to use :obj:`main` from an C{if
__name__ == '__main__'} bloc... | |
<filename>test/integration/test_gen1.py
# coding: utf-8
# (C) Copyright IBM Corp. 2020.
#
# 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
#
# Unl... | |
"""
Fields
======
.. note::
Always remember that you can model the JSON API completly with the fields
in :mod:`~aiohttp_json_api.schema.base_fields`.
.. sidebar:: Index
* :class:`String`
* :class:`Integer`
* :class:`Float`
* :class:`Complex`
* :class:`Decimal`
* :class:`Fraction`
* :class:`DateTime`
* :cl... | |
import os
import io
import cv2
import sys
import time
import pickle
import getopt
import torch
import random
import numpy as np
import torch.utils.data as data
import xml.etree.ElementTree as ET
import torchvision.transforms as transforms
from cv2 import cv2
from visdom import Visdom
import matplotlib as mpl
mpl.use(... | |
import os
from collections import OrderedDict
import numpy as np
from PIL import Image
from io import BytesIO
from gcg.envs.env import Env
from gcg.envs.env_spec import EnvSpec
from gcg.envs.spaces.box import Box
from gcg.envs.spaces.discrete import Discrete
from gcg.data.logger import logger
import matplotlib.pyplot a... | |
<reponame>yoozze/lulc-classification<gh_stars>0
"""Miscellaneous utilities
"""
import hashlib
import json
import math
import os
import re
import time
from datetime import datetime
# from pathlib import Path
import geopandas as gpd
import numpy as np
from eolearn.core import EOPatch
from src.utils import const
def g... | |
<gh_stars>1-10
import os
import pandas as pd
from datetime import datetime
def stripTags(string):
if "<" in string and ">" in string and string.find("<") < string.find(">"):
iFirst = string.find("<")
iEnd = string.find(">")
strOut = string[:iFirst] + string[iEnd + 1:]
return stripTags(strOut)
else:
return str... | |
import logging as log
from multiprocessing import Event
import socket
from odf.config import config
import time
import uuid
from enum import Enum
from typing import ClassVar, Generator, List
from collections import defaultdict
from odf.utils import delay
import struct
from datetime import datetime, timedelta
import js... | |
# ------------------------------------------------------------------------------
# Project: legohdl
# Script: workspace.py
# Author: <NAME>
# Description:
# The Workspace class. A Workspace object has a path and a list of available
# vendors. This is what the user keeps their work's scope within for a given
# "organiza... | |
continue
self.run([self.cmd_rm, '-rf', '%s/%s/migrations' % (self.dist_kong_plugins_folder, plugin)])
self.run([self.cmd_rm, '-R', '%s/%s/daos.lua' % (self.dist_kong_plugins_folder, plugin)])
def install_jre(self):
self.log_it("Installing server JRE 1.8 %s..." % self.jre_version)
jre_archive = 'server-jre-8u%s-li... | |
<filename>tcex/profile/interactive.py
"""TcEx testing profile Class."""
# standard library
import json
import math
# import os
import re
import sys
from base64 import b64encode
from typing import Optional, Union
# third-party
import colorama as c
# autoreset colorama
c.init(autoreset=True, strip=False)
class Inter... | |
#!/usr/bin/env python3
from __future__ import division, print_function
from string import Template
from CommandRunner import *
from ECUtils import *
import tempfile
import xml.etree.ElementTree as ET
import logging
import sys,os,re
import subprocess
import signal
import argparse
import string
import glob
import trace... | |
self.parcube[:,int(y),int(x)] = blank_value
self.errcube[:,int(y),int(x)] = blank_value
if integral:
self.integralmap[:,int(y),int(x)] = blank_value
self._counter += 1
if verbose:
if ii % (min(10**(3-verbose_level),1)) == 0:
snmsg = " s/n=%5.1f" % (max_sn) if max_sn is not None else ""
npix = len(valid_pixels... | |
count
def generate_Prophet_features_sip_diff(lPsm, config_dict):
# get some statistics
global num_forward_psms_before_filtering
num_forward_psms_before_filtering = 0
for one_psm in lPsm:
if one_psm.RealLabel == LabelFwd:
num_forward_psms_before_filtering += 1
simple_feature_bool = False
if float(num_forward_psm... | |
<filename>tests/patterns/test_size_.py
"""Test plant size trait matcher."""
# pylint: disable=missing-function-docstring, too-many-public-methods
import unittest
from tests.setup import test
class TestSize(unittest.TestCase):
"""Test plant size trait parsers."""
# def test_size_00(self):
# test('Leaf (12-)23-3... | |
# $Id$
# $HeadURL$
################################################################
# The contents of this file are subject to the BSD 3Clause (New) License
# you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://directory.fsf.org/wiki/License:BSD_3Clause
... | |
1)], 2: [(2, 0)]}
sage: t = WeakTableau([[None, None, 1, 1, 4], [1, 4], [3]], 3)
sage: t.dictionary_of_coordinates_at_residues(1)
{2: [(0, 2)], 3: [(0, 3), (1, 0)]}
sage: t = WeakTableau([], 3)
sage: t.dictionary_of_coordinates_at_residues(1)
{}
"""
d = {}
for r in self.residues_of_entries(v):
d[r] = []
fo... | |
<filename>plctag_gui.py
'''
Create a simple Tkinter window to display fetched tags and selected tag value(s).
Tkinter doesn't come preinstalled on all Linux distributions, so you may need to install it.
For Ubuntu: sudo apt-get install python-tk
Tkinter vs tkinter
Reference: https://stackoverflow.com/questions/1... | |
import html
from typing import Optional, List
from telegram import Message, Chat, Update, Bot, User
from telegram.error import BadRequest
from telegram.ext import CommandHandler, Filters
from telegram.ext.dispatcher import run_async
from telegram.utils.helpers import mention_html
from telegram import InlineKeyboardBut... | |
from functools import wraps, cached_property
from typing import Mapping, Optional, Union, Iterable
from collections.abc import KeysView, ValuesView, ItemsView
from collections import ChainMap
from pymongo import MongoClient
from dol import KvReader
from dol import Collection as DolCollection
from mongodol.constants ... | |
<reponame>ankitarorabit/azure-sdk-for-python
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsof... | |
имени
l_table_name=p_table.queue_name
else:
l_table_name=p_table.name
l_schema=C_SCHEMA_TABLE_TYPE.get(p_table.type,None) # схема таблицы
l_sql="DROP VIEW IF EXISTS "+l_schema+"."+'"'+l_table_name+'";'
return l_sql
def get_source_table_delete_sql(p_source_table: object):
"""
SQL-запрос удаления строк из таблиц... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.