content stringlengths 1 1.04M | input_ids listlengths 1 774k | ratio_char_token float64 0.38 22.9 | token_count int64 1 774k |
|---|---|---|---|
from pathlib import Path
from wired_components.resource import Root
| [
6738,
3108,
8019,
1330,
10644,
198,
198,
6738,
28217,
62,
5589,
3906,
13,
31092,
1330,
20410,
628,
198
] | 3.944444 | 18 |
import math
from typing import List
import aiohttp_jinja2
from aiohttp import web
import sqlalchemy as sa
from terial.database import session_scope
from terial.models import Exemplar
@aiohttp_jinja2.template('list_exemplars.html')
| [
11748,
10688,
198,
6738,
19720,
1330,
7343,
198,
198,
11748,
257,
952,
4023,
62,
18594,
6592,
17,
198,
6738,
257,
952,
4023,
1330,
3992,
198,
11748,
44161,
282,
26599,
355,
473,
198,
198,
6738,
1059,
498,
13,
48806,
1330,
6246,
62,
29... | 3.189189 | 74 |
from typing import Any
| [
6738,
19720,
1330,
4377,
628
] | 4.8 | 5 |
from random import randint
import csv
#Used for generating grid dataset
if __name__ == "__main__":
main()
| [
6738,
4738,
1330,
43720,
600,
201,
198,
11748,
269,
21370,
201,
198,
201,
198,
2,
38052,
329,
15453,
10706,
27039,
201,
198,
201,
198,
201,
198,
201,
198,
201,
198,
361,
11593,
3672,
834,
6624,
366,
834,
12417,
834,
1298,
201,
198,
... | 2.55102 | 49 |
import re
from typing import Tuple
from utils.collection.collection_utils import flatten
from utils.converters.base_word_capitalizer import BaseWordCapitalizer
from utils.converters.symbol_name_formatter import SymbolNameFormatter
from utils.data.compound_symbol_name import CompoundSymbolName
from utils.data.compound_symbol_name import ComponentCase
| [
11748,
302,
198,
198,
6738,
19720,
1330,
309,
29291,
198,
198,
6738,
3384,
4487,
13,
43681,
13,
43681,
62,
26791,
1330,
27172,
268,
198,
6738,
3384,
4487,
13,
1102,
332,
1010,
13,
8692,
62,
4775,
62,
27544,
7509,
1330,
7308,
26449,
39... | 3.480392 | 102 |
"""
TODO write this
"""
from originexample import logger
from originexample.db import atomic
from originexample.tasks import celery_app
from originexample.technology import Technology
from originexample.services.datahub import DataHubService
service = DataHubService()
@celery_app.task(
name='import_technologies.import_technologies_and_insert_to_db',
autoretry_for=(Exception,),
retry_backoff=2,
max_retries=11,
)
@logger.wrap_task(
title='Importing technologies from DataHub',
pipeline='import_technologies',
task='import_technologies_and_insert_to_db',
)
@atomic
def import_technologies_and_insert_to_db(session):
"""
:param Session session:
"""
response = service.get_technologies()
# Empty table
session.query(Technology).delete()
# Insert imported
for technology in response.technologies:
session.add(Technology(
technology=technology.technology,
technology_code=technology.technology_code,
fuel_code=technology.fuel_code,
))
| [
37811,
198,
51,
3727,
46,
3551,
428,
198,
37811,
198,
6738,
1796,
500,
87,
1403,
1330,
49706,
198,
6738,
1796,
500,
87,
1403,
13,
9945,
1330,
17226,
198,
6738,
1796,
500,
87,
1403,
13,
83,
6791,
1330,
18725,
1924,
62,
1324,
198,
673... | 2.780423 | 378 |
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from posts.models import Post
from books import services
| [
6738,
42625,
14208,
13,
3642,
822,
13,
18439,
13,
12501,
273,
2024,
1330,
17594,
62,
35827,
198,
6738,
42625,
14208,
13,
19509,
23779,
1330,
8543,
198,
6738,
6851,
13,
27530,
1330,
2947,
198,
6738,
3835,
1330,
2594,
198
] | 3.973684 | 38 |
# Randomly selects ~500 queries to test from the 1.4mil query set
import random
if __name__ == "__main__":
main()
| [
2,
14534,
306,
40573,
5299,
4059,
20743,
284,
1332,
422,
262,
352,
13,
19,
25433,
12405,
900,
198,
198,
11748,
4738,
198,
198,
361,
11593,
3672,
834,
6624,
366,
834,
12417,
834,
1298,
198,
197,
12417,
3419,
198
] | 3.078947 | 38 |
import numpy as np
import scipy.sparse.linalg as sp
import itertools
# turn of warning for zero division (occurs due to vectorization)
np.seterr(divide='ignore', invalid='ignore')
# ----------------------------------- GRID ------------------------------------
Nx = 31 # number of voxels in x-direction
Ny = 31 # number of voxels in y-direction
Nz = 1 # number of voxels in z-direction
shape = [Nx,Ny,Nz] # number of voxels as list: [Nx,Ny,Nz]
ndof = 3**2*Nx*Ny*Nz # number of degrees-of-freedom
# ---------------------- PROJECTION, TENSORS, OPERATIONS ----------------------
# tensor operations/products: np.einsum enables index notation, avoiding loops
# e.g. ddot42 performs $C_ij = A_ijkl B_lk$ for the entire grid
trans2 = lambda A2 : np.einsum('ijxyz ->jixyz ',A2 )
ddot22 = lambda A2,B2: np.einsum('ijxyz ,jixyz ->xyz ',A2,B2)
ddot42 = lambda A4,B2: np.einsum('ijklxyz,lkxyz ->ijxyz ',A4,B2)
ddot44 = lambda A4,B4: np.einsum('ijklxyz,lkmnxyz->ijmnxyz',A4,B4)
dot11 = lambda A1,B1: np.einsum('ixyz ,ixyz ->xyz ',A1,B1)
dot22 = lambda A2,B2: np.einsum('ijxyz ,jkxyz ->ikxyz ',A2,B2)
dot24 = lambda A2,B4: np.einsum('ijxyz ,jkmnxyz->ikmnxyz',A2,B4)
dot42 = lambda A4,B2: np.einsum('ijklxyz,lmxyz ->ijkmxyz',A4,B2)
dyad22 = lambda A2,B2: np.einsum('ijxyz ,klxyz ->ijklxyz',A2,B2)
# identity tensor [single tensor]
i = np.eye(3)
# identity tensors [grid of tensors]
I = np.einsum('ij,xyz' , i ,np.ones([Nx,Ny,Nz]))
I4 = np.einsum('ijkl,xyz->ijklxyz',np.einsum('il,jk',i,i),np.ones([Nx,Ny,Nz]))
I4rt = np.einsum('ijkl,xyz->ijklxyz',np.einsum('ik,jl',i,i),np.ones([Nx,Ny,Nz]))
II = dyad22(I,I)
I4s = (I4+I4rt)/2.
I4d = (I4s-II/3.)
# projection operator (zero for zero frequency, associated with the mean)
# NB: vectorized version of "../linear-elasticity.py"
# - allocate / define support function
Ghat4 = np.zeros([3,3,3,3,Nx,Ny,Nz]) # projection operator
x = np.zeros([3 ,Nx,Ny,Nz],dtype='int64') # position vectors
q = np.zeros([3 ,Nx,Ny,Nz],dtype='int64') # frequency vectors
delta = lambda i,j: np.float(i==j) # Dirac delta function
# - set "x" as position vector of all grid-points [grid of vector-components]
x[0],x[1],x[2] = np.mgrid[:Nx,:Ny,:Nz]
# - convert positions "x" to frequencies "q" [grid of vector-components]
for i in range(3):
freq = np.arange(-(shape[i]-1)/2,+(shape[i]+1)/2,dtype='int64')
q[i] = freq[x[i]]
# - compute "Q = ||q||", and "norm = 1/Q" being zero for the mean (Q==0)
# NB: avoid zero division
q = q.astype(np.float64)
Q = dot11(q,q)
Z = Q==0
Q[Z] = 1.
norm = 1./Q
norm[Z] = 0.
# - set projection operator [grid of tensors]
for i, j, l, m in itertools.product(range(3), repeat=4):
Ghat4[i,j,l,m] = -(norm**2.)*(q[i]*q[j]*q[l]*q[m])+\
.5*norm*( delta(j,l)*q[i]*q[m]+delta(j,m)*q[i]*q[l] +\
delta(i,l)*q[j]*q[m]+delta(i,m)*q[j]*q[l] )
# (inverse) Fourier transform (for each tensor component in each direction)
fft = lambda x: np.fft.fftshift(np.fft.fftn (np.fft.ifftshift(x),[Nx,Ny,Nz]))
ifft = lambda x: np.fft.fftshift(np.fft.ifftn(np.fft.ifftshift(x),[Nx,Ny,Nz]))
# functions for the projection 'G', and the product 'G : K : eps'
G = lambda A2 : np.real( ifft( ddot42(Ghat4,fft(A2)) ) ).reshape(-1)
K_deps = lambda depsm: ddot42(K4,depsm.reshape(3,3,Nx,Ny,Nz))
G_K_deps = lambda depsm: G(K_deps(depsm))
# ------------------- PROBLEM DEFINITION / CONSTITIVE MODEL -------------------
# constitutive response to a certain loading (and history)
# NB: completely uncoupled from the FFT-solver, but implemented as a regular
# grid of quadrature points, to have an efficient code;
# each point is completely independent, just evaluated at the same time
# NB: all points for both models, but selectively ignored per materials
# this avoids loops or a problem specific constitutive implementation
# linear elasticity
# -----------------
# visco-plasticity
# ----------------
# laminate of two materials
# -------------------------
# ----------------------------- NEWTON ITERATIONS -----------------------------
# initialize: stress and strain tensor, history
sig = np.zeros([3,3,Nx,Ny,Nz])
eps = np.zeros([3,3,Nx,Ny,Nz])
eps_t = np.zeros([3,3,Nx,Ny,Nz])
epse_t = np.zeros([3,3,Nx,Ny,Nz])
ep_t = np.zeros([ Nx,Ny,Nz])
# set macroscopic loading increment
ninc = 200
DE = np.zeros([3,3,Nx,Ny,Nz])
DE[0,1] += 0.05/float(ninc)
DE[1,0] += 0.05/float(ninc)
dt = 1. /float(ninc)
# initial constitutive response / tangent
sig,K4,epse,ep = constitutive(eps,eps_t,epse_t,ep_t,dt)
# incremental loading
for inc in range(ninc):
print('=============================')
print('inc: {0:d}'.format(inc))
# initial residual: distribute "DE" over grid using "K4"
b = -G_K_deps(DE)
eps += DE
# compute DOF-normalization, set Newton iteration counter
En = np.linalg.norm(eps)
iiter = 0
# iterate as long as the iterative update does not vanish
while True:
# solve linear system
depsm,_ = sp.cg(tol=1.e-14,
A = sp.LinearOperator(shape=(ndof,ndof),matvec=G_K_deps,dtype='float'),
b = b,
)
# add solution of linear system to DOFs
eps += depsm.reshape(3,3,Nx,Ny,Nz)
# new residual
sig,K4,epse,ep = constitutive(eps,eps_t,epse_t,ep_t,dt)
b = -G(sig)
# check for convergence
print('{0:10.2e}'.format(np.linalg.norm(depsm)/En))
if np.linalg.norm(depsm)/En<1.e-8 and iiter>0: break
# update Newton iteration counter
iiter += 1
# store history
ep_t = np.array(ep ,copy=True)
epse_t = np.array(epse,copy=True)
eps_t = np.array(eps ,copy=True)
| [
11748,
299,
32152,
355,
45941,
198,
11748,
629,
541,
88,
13,
82,
29572,
13,
75,
1292,
70,
355,
599,
198,
11748,
340,
861,
10141,
198,
198,
2,
1210,
286,
6509,
329,
6632,
7297,
357,
13966,
1834,
2233,
284,
15879,
1634,
8,
198,
37659,... | 2.064637 | 2,924 |
def remove_digits(s):
"""
Returns a string with all digits removed.
"""
return ''.join(filter(lambda x: not x.isdigit(), s))
def remove_parentheticals(s):
"""
Removes any parenthetical expression from a string
Returns "Bolivia" from "Bolivia (Plurinational State of)"
"""
return get_string_before_delimeter(s, "(")
def get_string_before_delimiter(string, delimiter):
"""
Returns contents of a string before a given delimiter
Example: get_string_before_delimiter("banana-kiwi", "-") returns "banana"
"""
if delimiter in string:
return (string[:string.index(delimiter)]).strip()
else:
return string
def get_after_delimiter(string, delimiter):
"""
Returns the string contents after the first occurance of the provided delimiter
Example: get_after_delimiter("This, that, and the other", ",") returns "that, and the other"
"""
if string in delimiter:
return string[string.index(delimiter) + 1:].strip()
else:
return string
def get_after_comma(s):
"""
Returns the string contents after the first comma
Example: get_after_comma("This, that, and the other") returns "that, and the other"
"""
return get_after_delimiter(s, ",")
## Pandas's Little Helpers
# do `import pandas as pd` because these require pandas
def drop_matching_rows(df, column, values):
"""
Returns a dataframe excluding rows where a column value exists in the list of provided values
This is kind of like a reverse .filter method
Use this for when df.drop(['A', 'B']) throws "['A', 'B'] not found in axis"
"""
return df[df[column].apply(lambda x:x not in values)]
# apply a list of functions to an input
def unique_word_count(string):
"""
Returns the count of unique words in a string.
"""
words = string.split(" ")
unique_words = set(words)
return len(unique_words) | [
4299,
4781,
62,
12894,
896,
7,
82,
2599,
198,
220,
220,
220,
37227,
198,
220,
220,
220,
220,
220,
220,
220,
16409,
257,
4731,
351,
477,
19561,
4615,
13,
198,
220,
220,
220,
37227,
198,
220,
220,
220,
1441,
705,
4458,
22179,
7,
244... | 2.703552 | 732 |
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import permission_required
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.template import RequestContext
from django.template.loader import render_to_string
from django.utils.decorators import method_decorator
from django.views.generic import View
from django.views.generic.edit import FormMixin
from account.mixins import LoginRequiredMixin
from .forms import InviteForm
from .models import InvitationStat, JoinInvitation
| [
6738,
42625,
14208,
13,
3642,
822,
13,
18439,
1330,
651,
62,
7220,
62,
19849,
198,
6738,
42625,
14208,
13,
3642,
822,
13,
18439,
13,
12501,
273,
2024,
1330,
7170,
62,
35827,
198,
6738,
42625,
14208,
13,
4023,
1330,
449,
1559,
31077,
1... | 3.588608 | 158 |
# $Id: aim.py 23 2006-11-08 15:45:33Z dugsong $
# -*- coding: utf-8 -*-
"""AOL Instant Messenger."""
from __future__ import absolute_import
import struct
from . import dpkt
# OSCAR: http://iserverd1.khstu.ru/oscar/
class FLAP(dpkt.Packet):
"""Frame Layer Protocol.
See more about the FLAP on
https://en.wikipedia.org/wiki/OSCAR_protocol#FLAP_header
Attributes:
__hdr__: Header fields of FLAP.
data: Message data.
"""
__hdr__ = (
('ast', 'B', 0x2a), # '*'
('type', 'B', 0),
('seq', 'H', 0),
('len', 'H', 0)
)
class SNAC(dpkt.Packet):
"""Simple Network Atomic Communication.
See more about the SNAC on
https://en.wikipedia.org/wiki/OSCAR_protocol#SNAC_data
Attributes:
__hdr__: Header fields of SNAC.
"""
__hdr__ = (
('family', 'H', 0),
('subtype', 'H', 0),
('flags', 'H', 0),
('reqid', 'I', 0)
)
# TOC 1.0: http://jamwt.com/Py-TOC/PROTOCOL
# TOC 2.0: http://www.firestuff.org/projects/firetalk/doc/toc2.txt
| [
2,
720,
7390,
25,
4031,
13,
9078,
2242,
4793,
12,
1157,
12,
2919,
1315,
25,
2231,
25,
2091,
57,
288,
10339,
506,
720,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
37811,
32,
3535,
24470,
24306,
526,
1... | 2.14 | 500 |
from typing import Iterable
import numpy
from ..solver_interface.solver_interface import solve_milp, solve_lp
from ..utils.constraint_utilities import constraint_norm
from ..utils.general_utils import make_column
def chebyshev_ball(A: numpy.ndarray, b: numpy.ndarray, equality_constraints: Iterable[int] = None,
bin_vars: Iterable[int] = None, deterministic_solver='gurobi'):
r"""
Chebyshev ball finds the largest ball inside a polytope defined by Ax <= b. This is solved by the following LP.
.. math::
\min_{x,r} -r
.. math::
\begin{align*}
\text{s.t. } Ax + ||A_i||_2r &\leq b\\
A_{eq} x &= b_{eq}\\
r &\geq 0
\end{align*}
:param A: LHS Constraint Matrix
:param b: RHS Constraint column vector
:param equality_constraints: indices of rows that have strict equality A[eq] @ x = b[eq]
:param bin_vars: indices of binary variables
:param deterministic_solver: The underlying Solver to use, e.g. gurobi, ect
:return: the SolverOutput object, None if infeasible
"""
if bin_vars is None:
bin_vars = []
if equality_constraints is None:
equality_constraints = []
# shortcut for chebyshev ball of facet of 1D region
# if A.shape == 1 and len(equality_constraints) == 1:
# x_star = b[equality_constraints[0]]
# is_feasible = numpy.all((A@x_star - b) <= 0)
# if is_feasible:
# return SolverOutput(0, numpy.array([x_star, [0]]), )
# else:
# return None
c = numpy.zeros((A.shape[1] + 1, 1))
c[A.shape[1]][0] = -1
const_norm = constraint_norm(A)
const_norm = make_column(
[const_norm[i][0] if i not in equality_constraints else 0 for i in range(numpy.size(A, 0))])
A_ball = numpy.block([[A, const_norm], [c.T]])
b_ball = numpy.concatenate((b, numpy.zeros((1, 1))))
if len(bin_vars) == 0:
return solve_lp(c, A_ball, b_ball, equality_constraints, deterministic_solver=deterministic_solver)
else:
return solve_milp(c, A_ball, b_ball, equality_constraints, bin_vars, deterministic_solver=deterministic_solver)
# noinspection PyUnusedLocal
def chebyshev_ball_max(A: numpy.ndarray, b: numpy.ndarray, equality_constraints: Iterable[int] = None,
bin_vars: Iterable[int] = (), deterministic_solver='glpk'):
r"""
Chebyshev ball finds the smallest l-infinity ball the contains the polytope defined by Ax <= b. Where A has n
hyper planes and d dimensions.
This is solved by the following Linear program
.. math::
\min_{x_{c} ,r ,y_{j} ,u_{j}} \quad r
.. math::
\begin{align*}
A^Ty_{j} &= e_{j}, \forall j \in {1, .., d}\\
A^Tu_{j} &= -e_{j}, \forall j \in {1, .., d}\\
-x_{cj} + b^Ty_{j} &\leq r\\
x_{cj} + b^Tu_{j} &\leq r\\
r &\geq 0\\
y_{j} &\geq 0\\
u_{j} &\geq 0\\
r &\in R\\
y_{j} &\in R^n\\
u_{j} &\in R^n\\
x_c &\in R^d
\end{align*}
Source: Simon Foucart's excellent book.
:param A: LHS Constraint Matrix
:param b: RHS Constraint column vector
:param equality_constraints: indices of rows that have strict equality A[eq] @ x = b[eq]
:param bin_vars: indices of binary variables
:param deterministic_solver: The underlying Solver to use, e.g. gurobi, ect
:return: the SolverOutput object, None if infeasible
"""
pass
| [
6738,
19720,
1330,
40806,
540,
198,
198,
11748,
299,
32152,
198,
198,
6738,
11485,
82,
14375,
62,
39994,
13,
82,
14375,
62,
39994,
1330,
8494,
62,
25433,
79,
11,
8494,
62,
34431,
198,
6738,
11485,
26791,
13,
1102,
2536,
2913,
62,
315,... | 2.213836 | 1,590 |
"""Model definitions for the contact app."""
from wagtail.core.blocks import RichTextBlock, StreamBlock, StructBlock, TextBlock
from wagtail.core.fields import StreamField
from home.models import AbstractContentPage, DefaultPageHeaderImageMixin
class ContactTypeStreamBlock(StreamBlock):
"""Model allowing the CMS to bring together multiple struct block objects."""
contact_type_editor = StructBlock([
('heading', TextBlock()),
('description', RichTextBlock(required=False)),
('email', TextBlock())
], icon='title', classname='title')
class ContactPage(DefaultPageHeaderImageMixin, AbstractContentPage):
"""Model to define the overall fields for the contact page."""
parent_page_types = ['home.HomePage']
subpage_types = []
max_count = 1
contact_type = StreamField(ContactTypeStreamBlock, blank=True, null=True)
translation_fields = AbstractContentPage.translation_fields + ['contact_type']
| [
37811,
17633,
17336,
329,
262,
2800,
598,
526,
15931,
198,
198,
6738,
266,
363,
13199,
13,
7295,
13,
27372,
1330,
3998,
8206,
12235,
11,
13860,
12235,
11,
32112,
12235,
11,
8255,
12235,
198,
6738,
266,
363,
13199,
13,
7295,
13,
25747,
... | 3.44086 | 279 |
A = int(input())
print((A - 1)**A)
| [
32,
796,
493,
7,
15414,
28955,
201,
198,
4798,
19510,
32,
532,
352,
8,
1174,
32,
8,
201,
198
] | 1.947368 | 19 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Nada
"""
from menu import Menu
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
201,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
201,
198,
201,
198,
37811,
201,
198,
45,
4763,
201,
198,
37811,
201,
198,
201,
198,
6738,
6859,
1330,
21860,
201,
198... | 1.978723 | 47 |
import paramiko
import tempfile
import time
import socket
import logging
from rackattack.ssh import ftp
from rackattack.ssh import run
from rackattack.ssh import dirftp
from rackattack.ssh import tunnel
| [
11748,
5772,
12125,
198,
11748,
20218,
7753,
198,
11748,
640,
198,
11748,
17802,
198,
11748,
18931,
198,
6738,
19127,
20358,
13,
45824,
1330,
10117,
79,
198,
6738,
19127,
20358,
13,
45824,
1330,
1057,
198,
6738,
19127,
20358,
13,
45824,
1... | 3.886792 | 53 |
import traceback
from pygame.rect import Rect
import cmg
from cmg.color import Color
from cmg.widgets.layout_item import LayoutItem
from cmg.event import Event
from cmg.input import KeyShortcut
| [
11748,
12854,
1891,
198,
6738,
12972,
6057,
13,
2554,
1330,
48599,
198,
11748,
269,
11296,
198,
6738,
269,
11296,
13,
8043,
1330,
5315,
198,
6738,
269,
11296,
13,
28029,
11407,
13,
39786,
62,
9186,
1330,
47639,
7449,
198,
6738,
269,
112... | 3.482143 | 56 |
"""
analyze chemical input/output filetype
"""
import os
import re
import argparse
import configparser
import modlog
from . import fileutil
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DEFAULT_FILETYPE_REGEXP_CONF = 'default_filetype.conf'
DEFAULT_FILETYPE_REGEXP_CONF = os.path.join(
BASE_DIR, DEFAULT_FILETYPE_REGEXP_CONF)
REG_ANYSTRING = r'[\s\S]*?'
FILETYPE_SECTION_NAME = 'filetype'
MULTIFRAME_NAME = 'multiframe'
logger = modlog.getLogger(__name__)
global FORMATS_REGEXP, MULTIFRAME
FORMATS_REGEXP, MULTIFRAME = dict(), list()
PARTIAL_LENGTH = 100000
def filetype(fileobj=None, is_filename=True):
"""
>>> filetype("a.gjf")
gaussian
>>> filetype("1.gro")
gromacs
"""
filename = fileutil.get_absfilename(fileobj)
if fileutil.is_compressed_file(filename):
fileobj = fileutil.get_uncompressed_fileobj(filename)
filename = fileutil.get_uncompressed_filename(filename)
else:
filename = fileutil.get_filename(fileobj)
content = None
try:
content = fileutil.get_file_content(
fileobj, size=PARTIAL_LENGTH, is_filename=is_filename)
except TypeError:
pass
if filename is None and content is None:
return None
logger.debug("filename: %s, content: %s" % (filename, content))
for fmt_regexp, fmt_filetype in FORMATS_REGEXP.items():
name_regexp, content_regexp = (fmt_regexp.split('&&') + [None])[:2]
logger.debug(f"{name_regexp}, {content_regexp}")
if filename and re.match(re.compile(name_regexp.strip()), filename) or filename is None:
if content and content_regexp:
if not content_regexp.startswith('^'):
content_regexp = REG_ANYSTRING + content_regexp.strip()
if not content_regexp.endswith('$'):
content_regexp = content_regexp.strip() + REG_ANYSTRING
logger.debug("content_regexp: " + content_regexp)
if re.match(re.compile(content_regexp.strip()), content):
return fmt_filetype
else:
return fmt_filetype
logger.warning(f"filename: {filename} parse fail")
return None
update_config()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('filename', type=str)
args = parser.parse_args()
logger = modlog.getLogger("Atomtools: Filetype",
'normal', 'FILETYPE_LOGLEVEL')
print(filetype(args.filename))
| [
37811,
198,
38200,
2736,
5931,
5128,
14,
22915,
2393,
4906,
198,
37811,
628,
198,
11748,
28686,
198,
11748,
302,
198,
11748,
1822,
29572,
198,
11748,
4566,
48610,
198,
11748,
953,
6404,
198,
6738,
764,
1330,
2393,
22602,
628,
198,
33,
1... | 2.276423 | 1,107 |
from django.db import models, utils
from django.contrib.auth.models import AbstractUser
from django.contrib.sessions.base_session import AbstractBaseSession
from datetime import *
| [
6738,
42625,
14208,
13,
9945,
1330,
4981,
11,
3384,
4487,
198,
6738,
42625,
14208,
13,
3642,
822,
13,
18439,
13,
27530,
1330,
27741,
12982,
198,
6738,
42625,
14208,
13,
3642,
822,
13,
82,
6202,
13,
8692,
62,
29891,
1330,
27741,
14881,
... | 3.693878 | 49 |
#!/usr/bin/python
# coding: utf-8
import log
from osgeo import ogr
import os
import feature
SHAPE_DRIVER = ogr.GetDriverByName('ESRI Shapefile')
def read(path=''):
"""
读取SHP文件
:param path:
:return:
"""
# 读取数据层
datasource = SHAPE_DRIVER.Open(path, 0) # 0 means read-only. 1 means writeable.
layer = datasource.GetLayer(0)
# 获取这个数据层里的点数
n = layer.GetFeatureCount()
log.debug('Feature count:%d' % n)
# 读出上下左右边界
extent = layer.GetExtent()
log.debug('extent:%s' % str(extent))
log.debug('ul[%s, %s] lr[%s, %s]' % (extent[0], extent[3], extent[1], extent[2]))
# 复位
layer.ResetReading()
for feature in layer:
geom = feature.GetGeometryRef()
print(geom.Centroid().ExportToWkt())
layer.ResetReading()
layer_definition = layer.GetLayerDefn()
for i in range(layer_definition.GetFieldCount()):
field_name = layer_definition.GetFieldDefn(i).GetName()
field_type_code = layer_definition.GetFieldDefn(i).GetType()
field_type = layer_definition.GetFieldDefn(i).GetFieldTypeName(field_type_code)
field_width = layer_definition.GetFieldDefn(i).GetWidth()
precision = layer_definition.GetFieldDefn(i).GetPrecision()
log.debug(field_name + " - " + field_type + " " + str(field_width) + " " + str(precision))
if __name__ == '__main__':
main()
| [
2,
48443,
14629,
14,
8800,
14,
29412,
198,
2,
19617,
25,
3384,
69,
12,
23,
198,
11748,
2604,
198,
6738,
28686,
469,
78,
1330,
267,
2164,
198,
11748,
28686,
198,
11748,
3895,
198,
198,
9693,
45721,
62,
7707,
38757,
796,
267,
2164,
13... | 2.177394 | 637 |
from collections import namedtuple
with open('input.txt', 'r') as f:
data = f.read().splitlines()
# Figure out array size
x_size = max([int(line.split(', ')[0]) for line in data]) + 1
y_size = max([int(line.split(', ')[1]) for line in data]) + 1
grid_list = [[0 for y in range(y_size)] for x in
range(x_size)]
coordinate_list = []
disregard_set = set()
Point = namedtuple('Point', 'id x y')
# Load coodinates
for index, line in enumerate(data):
new_point = Point(index, *map(int, line.split(', ')))
coordinate_list.append(new_point)
# PART 1
for x in range(len(grid_list)):
for y in range(len(grid_list[x])):
grid_list[x][y] = manhattan_distance([x, y], coordinate_list)
if y == 0:
disregard_set.add(grid_list[x][y])
elif y == y_size-1:
disregard_set.add(grid_list[x][y])
disregard_set.update(grid_list[0])
disregard_set.update(grid_list[x_size - 1])
disregard_set.remove('.')
all_id_set = set([x for x in range(len(coordinate_list))])
check_set = all_id_set - disregard_set
max_total = 0
for item in check_set:
total = 0
for s in range(x_size):
total += grid_list[s].count(item)
if total > max_total:
max_total = total
print(max_total)
for x in range(len(grid_list)):
for y in range(len(grid_list[x])):
grid_list[x][y] = manhattan_distance_part2([x, y], coordinate_list)
total = 0
for s in range(len(grid_list)):
total += grid_list[s].count('.')
print(total)
| [
6738,
17268,
1330,
3706,
83,
29291,
628,
628,
198,
4480,
1280,
10786,
15414,
13,
14116,
3256,
705,
81,
11537,
355,
277,
25,
198,
220,
220,
220,
1366,
796,
277,
13,
961,
22446,
35312,
6615,
3419,
628,
220,
220,
220,
1303,
11291,
503,
... | 2.169514 | 761 |
from django.contrib.auth import get_user_model
from db.serializers.user_serializer import UserSerializer
from lib.lower_strip import strip_and_lower
from app.action import Action
from db.models.artist import Artist
from db.models.account import Account
from ..validations.validate_artist import RegisterArtistValidation
| [
6738,
42625,
14208,
13,
3642,
822,
13,
18439,
1330,
651,
62,
7220,
62,
19849,
198,
6738,
20613,
13,
46911,
11341,
13,
7220,
62,
46911,
7509,
1330,
11787,
32634,
7509,
198,
6738,
9195,
13,
21037,
62,
36311,
1330,
10283,
62,
392,
62,
21... | 3.86747 | 83 |
# -*- coding: utf-8 -*-
"""Player module."""
import datetime
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
37811,
14140,
8265,
526,
15931,
198,
11748,
4818,
8079,
198
] | 2.541667 | 24 |
# -*- coding: utf-8 -*-
import numpy as np
import theano
from theano import gof
import theano.tensor as tt
__all__ = ["spotYlmOp"]
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
262,
5733,
198,
6738,
262,
5733,
1330,
467,
69,
198,
11748,
262,
5733,
13,
83,
22854,
355,
256,
83,
198,
198,
834,
439,
834,... | 2.436364 | 55 |
#------------------------------------------------------------------------------
# Copyright (c) 2013, Enthought, Inc.
# All rights reserved.
#------------------------------------------------------------------------------
from types import FunctionType
from traits.api import (
Any, Property, Disallow, ReadOnly, CTrait, Instance, Uninitialized,
)
from .dynamic_scope import DynamicAttributeError
from .exceptions import DeclarativeNameError, OperatorLookupError
from .object import Object
from .operator_context import OperatorContext
from .trait_types import EnamlInstance, EnamlEvent
#------------------------------------------------------------------------------
# UserAttribute and UserEvent
#------------------------------------------------------------------------------
class UserAttribute(EnamlInstance):
""" An EnamlInstance subclass which implements the `attr` keyword.
"""
def get(self, obj, name):
""" The trait getter method.
This returns the value from the object's dict, or raises an
uninitialized error if the value doesn't exist.
"""
dct = obj.__dict__
if name not in dct:
self.uninitialized_error(obj, name)
return dct[name]
def set(self, obj, name, value):
""" The trait setter method.
This sets the value in the object's dict if it is valid, and
emits a change notification if the value has changed. The first
time the value is set the change notification will carry None
as the old value.
"""
value = self.validate(obj, name, value)
dct = obj.__dict__
if name not in dct:
old = None
else:
old = dct[name]
dct[name] = value
if old != value:
obj.trait_property_changed(name, old, value)
def uninitialized_error(self, obj, name):
""" Raise a DynamicAttributeError for an object and attr name.
"""
msg = "cannot access the uninitialized '%s' attribute of the %s object"
raise DynamicAttributeError(msg % (name, obj))
class UserEvent(EnamlEvent):
""" An EnamlEvent subclass which implements the `event` keyword.
This subclass contains no additional logic. Its type is simply used
to distinguish between events declared by the framework, and events
declared by the user.
"""
pass
#------------------------------------------------------------------------------
# Declarative Helpers
#------------------------------------------------------------------------------
def _compute_default(obj, name):
""" Compute the default value for an expression.
This is a private function used by Declarative for allowing default
values of attributes to be provided by bound expression objects
without requiring an explicit initialization graph.
"""
try:
return obj.eval_expression(name)
except DynamicAttributeError:
raise # Reraise a propagating initialization error.
except Exception:
import traceback
# XXX I'd rather not hack into Declarative's private api.
expr = obj._expressions[name]
filename = expr._func.func_code.co_filename
lineno = expr._func.func_code.co_firstlineno
args = (filename, lineno, traceback.format_exc())
msg = ('Error initializing expression (%r line %s). Orignal '
'exception was:\n%s')
raise DynamicAttributeError(msg % args)
_quiet = set()
def _set_quiet(obj, name, value):
""" Quietly set the named value on the object.
This is a private function used by Declarative for allowing default
values of attributes to be provided by bound expression objects
without requiring an explicit initialization graph. This is a
workaround for bug: https://github.com/enthought/traits/issues/26
"""
q = _quiet
owned = obj not in q
if owned:
obj._trait_change_notify(False)
q.add(obj)
setattr(obj, name, value)
if owned:
obj._trait_change_notify(True)
q.discard(obj)
def _wired_getter(obj, name):
""" The wired default expression getter.
This is a private function used by Declarative for allowing default
values of attributes to be provided by bound expression objects
without requiring an explicit initialization graph.
"""
itraits = obj._instance_traits()
itraits[name] = itraits[name]._shadowed
val = _compute_default(obj, name)
if val is not NotImplemented:
_set_quiet(obj, name, val)
return getattr(obj, name, val)
def _wired_setter(obj, name, value):
""" The wired default expression setter.
This is a private function used by Declarative for allowing default
values of attributes to be provided by bound expression objects
without requiring an explicit initialization graph.
"""
itraits = obj._instance_traits()
itraits[name] = itraits[name]._shadowed
setattr(obj, name, value)
def _wire_default(obj, name):
""" Wire an expression trait for default value computation.
This is a private function used by Declarative for allowing default
values of attributes to be provided by bound expression objects
without requiring an explicit initialization graph.
"""
# This is a low-level performance hack that bypasses a mountain
# of traits cruft and performs the minimum work required to make
# traits do what we want. The speedup of this over `add_trait` is
# substantial.
# A new 'event' trait type (defaults are overridden)
trait = CTrait(4)
# Override defaults with 2-arg getter, 3-arg setter, no validator
trait.property(_wired_getter, 2, _wired_setter, 3, None, 0)
# Provide a handler else dynamic creation kills performance
trait.handler = Any
shadow = obj._trait(name, 2)
trait._shadowed = shadow
trait._notifiers = shadow._notifiers
obj._instance_traits()[name] = trait
class ListenerNotifier(object):
""" A lightweight trait change notifier used by Declarative.
"""
def __call__(self, obj, name, old, new):
""" Called by traits to dispatch the notifier.
"""
if old is not Uninitialized:
obj.run_listeners(name, old, new)
def equals(self, other):
""" Compares this notifier against another for equality.
"""
return False
# Only a single instance of ListenerNotifier is needed.
ListenerNotifier = ListenerNotifier()
def scope_lookup(name, scope, description):
""" A function which retrieves a name from a scope.
If the lookup fails, a DeclarativeNameError is raised. This can
be used to lookup names for a description dict from a global scope
with decent error reporting when the lookup fails.
Parameters
----------
name : str
The name to retreive from the scope.
scope : mapping
A mapping object.
description : dict
The description dictionary associated with the lookup.
"""
try:
item = scope[name]
except KeyError:
lineno = description['lineno']
filename = description['filename']
block = description['block']
raise DeclarativeNameError(name, filename, lineno, block)
return item
def setup_bindings(instance, bindings, identifiers, f_globals):
""" Setup the expression bindings for a declarative instance.
Parameters
----------
instance : Declarative
The declarative instance which owns the bindings.
bindings : list
A list of binding dicts created by the enaml compiler.
identifiers : dict
The identifiers scope to associate with the bindings.
f_globals : dict
The globals dict to associate with the bindings.
"""
operators = instance.operators
for binding in bindings:
opname = binding['operator']
try:
operator = operators[opname]
except KeyError:
filename = binding['filename']
lineno = binding['lineno']
block = binding['block']
raise OperatorLookupError(opname, filename, lineno, block)
code = binding['code']
# If the code is a tuple, it represents a delegation
# expression which is a combination of subscription
# and update functions.
if isinstance(code, tuple):
sub_code, upd_code = code
func = FunctionType(sub_code, f_globals)
func._update = FunctionType(upd_code, f_globals)
else:
func = FunctionType(code, f_globals)
operator(instance, binding['name'], func, identifiers)
#------------------------------------------------------------------------------
# Declarative
#------------------------------------------------------------------------------
class Declarative(Object):
""" The most base class of the Enaml declarative objects.
This class provides the core functionality required of declarative
Enaml types. It can be used directly in a declarative Enaml object
tree to store and react to state changes. It has no concept of a
visual representation; that functionality is added by subclasses.
"""
#: A readonly property which returns the current instance of the
#: component. This allows declarative Enaml expressions to access
#: 'self' according to Enaml's dynamic scoping rules.
self = Property(fget=lambda self: self)
#: The operator context used to build out this instance. This is
#: assigned during object instantiation. It should not be edited
#: by user code.
operators = ReadOnly
#: The dictionary of bound expression objects. XXX These dicts are
#: typically small and waste space. We need to switch to a more
#: space efficient hash table at some point in the future. For
#: pathological cases of large numbers of objects, the savings
#: can be as high as 20% of the heap size.
_expressions = Instance(dict, ())
#: The dictionary of bound listener objects. XXX These dicts are
#: typically small and waste space. We need to switch to a more
#: space efficient hash table at some point in the future. For
#: pathological cases of large numbers of objects, the savings
#: can be as high as 20% of the heap size.
_listeners = Instance(dict, ())
def __init__(self, parent=None, **kwargs):
""" Initialize a declarative component.
Parameters
----------
parent : Object or None, optional
The Object instance which is the parent of this object, or
None if the object has no parent. Defaults to None.
**kwargs
Additional keyword arguments needed for initialization.
"""
super(Declarative, self).__init__(parent, **kwargs)
self.operators = OperatorContext.active_context()
#--------------------------------------------------------------------------
# Declarative API
#--------------------------------------------------------------------------
def populate(self, description, identifiers, f_globals):
""" Populate this declarative instance from a description.
This method is called when the object was created from within
a declarative context. In particular, there are two times when
it may be called:
- The first is when a type created from the `enamldef`
keyword is instatiated; in this case, the method is
invoked by the EnamlDef metaclass.
- The second occurs when the object is instantiated by
its parent from within its parent's `populate` method.
In the first case, the description dict will contain the key
`enamldef: True`, indicating that the object is being created
from a "top-level" `enamldef` block.
In the second case, the dict will have the key `enamldef: False`
indicating that the object is being populated as a declarative
child of some other parent.
Subclasses may reimplement this method to gain custom control
over how the children for its instances are created.
*** This method may be called multiple times ***
Consider the following sample:
enamldef Foo(PushButton):
text = 'bar'
enamldef Bar(Foo):
fgcolor = 'red'
enamldef Main(Window):
Container:
Bar:
bgcolor = 'blue'
The instance of `Bar` which is created as the `Container` child
will have its `populate` method called three times: the first
to populate the data from the `Foo` block, the second to populate
the data from the `Bar` block, and the third to populate the
data from the `Main` block.
Parameters
----------
description : dict
The description dictionary for the instance.
identifiers : dict
The dictionary of identifiers to use for the bindings.
f_globals : dict
The dictionary of globals for the scope in which the object
was declared.
Notes
-----
The caller of this method should enter the child event context
of the instance before invoking the method. This reduces the
number of child events which are generated during startup.
"""
ident = description['identifier']
if ident:
identifiers[ident] = self
bindings = description['bindings']
if len(bindings) > 0:
setup_bindings(self, bindings, identifiers, f_globals)
children = description['children']
if len(children) > 0:
for child in children:
cls = scope_lookup(child['type'], f_globals, child)
instance = cls(self)
with instance.children_event_context():
instance.populate(child, identifiers, f_globals)
#--------------------------------------------------------------------------
# Private API
#--------------------------------------------------------------------------
@classmethod
def _add_user_attribute(cls, name, attr_type, is_event):
""" A private classmethod used by the Enaml compiler machinery.
This method is used to add user attributes and events to custom
derived enamldef classes. If the attribute already exists on the
class and is not a user defined attribute, an exception will be
raised. The only method of overriding standard trait attributes
is through traditional subclassing.
Parameters
----------
name : str
The name of the attribute to add to the class.
attr_type : type
The type of the attribute.
is_event : bool
True if the attribute should be a UserEvent, False if it
should be a UserAttribute.
"""
class_traits = cls.__class_traits__
if name in class_traits:
trait_type = class_traits[name].trait_type
if trait_type is not Disallow:
if not isinstance(trait_type, (UserAttribute, UserEvent)):
msg = ("can't add '%s' attribute. The '%s' attribute on "
"enamldef '%s.%s' already exists.")
items = (name, name, cls.__module__, cls.__name__)
raise TypeError(msg % items)
trait_cls = UserEvent if is_event else UserAttribute
try:
user_trait = trait_cls(attr_type)
except TypeError:
msg = ("'%s' is not a valid type for the '%s' attribute "
"declaration on enamldef '%s.%s'")
items = (attr_type, name, cls.__module__, cls.__name__)
raise TypeError(msg % items)
# XXX HasTraits.add_class_trait will raise an exception if the
# the trait is already defined. There does not appear to be a
# way to turn this off, nor does there appear to be a way to
# formally remove a class trait. So, we just do what the traits
# metaclass does when adding traits and directly add the ctrait
# to the appropriate class dictionaries. The add_class_trait
# classmethod does some extra work to make sure that the trait
# is added to all subclasses, but that does not appear to be
# needed in this case, since this method will only be called by
# the compiler machinery for brand new subclasses.
ctrait = user_trait.as_ctrait()
class_traits[name] = ctrait
cls.__base_traits__[name] = ctrait
if '@' in cls.__prefix_traits__:
anytrait_handler = cls.__prefix_traits__['@']
ctrait._notifiers(1).append(anytrait_handler)
#--------------------------------------------------------------------------
# Public API
#--------------------------------------------------------------------------
def bind_expression(self, name, expression):
""" Bind an expression to the given attribute name.
This method can be called to bind a value-providing expression
to the given attribute name. If the named attribute does not
exist, an exception is raised.
Parameters
----------
name : string
The name of the attribute on which to bind the expression.
expression : AbstractExpression
A concrete implementation of AbstractExpression. This value
is not type checked for performance reasons. It is assumed
that the caller provides a correct value.
"""
curr = self._trait(name, 2)
if curr is None or curr.trait_type is Disallow:
msg = "Cannot bind expression. %s object has no attribute '%s'"
raise AttributeError(msg % (self, name))
dct = self._expressions
if name not in dct:
_wire_default(self, name)
dct[name] = expression
def bind_listener(self, name, listener):
""" A private method used by the Enaml execution engine.
This method is called by the Enaml operators to bind the given
listener object to the given attribute name. If the attribute
does not exist, an exception is raised. A strong reference to
the listener object is kept internally.
Parameters
----------
name : string
The name of the attribute on which to bind the listener.
listener : AbstractListener
A concrete implementation of AbstractListener. This value
is not type checked for performance reasons. It is assumed
that the caller provides a correct value.
"""
curr = self._trait(name, 2)
if curr is None or curr.trait_type is Disallow:
msg = "Cannot bind listener. %s object has no attribute '%s'"
raise AttributeError(msg % (self, name))
dct = self._listeners
if name not in dct:
dct[name] = [listener]
self.add_notifier(name, ListenerNotifier)
else:
dct[name].append(listener)
def eval_expression(self, name):
""" Evaluate a bound expression with the given name.
Parameters
----------
name : str
The name of the attribute with the bound expression.
Returns
-------
result : object or NotImplemented
The result of evaluating the expression, or NotImplemented
if there is no expression bound to the given name.
"""
dct = self._expressions
if name in dct:
return dct[name].eval(self, name)
return NotImplemented
def refresh_expression(self, name):
""" Refresh the value of a bound expression.
Parameters
----------
name : str
The attribute name to which the invalid expression is bound.
"""
value = self.eval_expression(name)
if value is not NotImplemented:
setattr(self, name, value)
def run_listeners(self, name, old, new):
""" Run the listeners bound to the given attribute name.
Parameters
----------
name : str
The name of the attribute with the bound listeners.
old : object
The old value to pass to the listeners.
new : object
The new value to pass to the listeners.
"""
dct = self._listeners
if name in dct:
for listener in dct[name]:
listener.value_changed(self, name, old, new)
| [
2,
10097,
26171,
198,
2,
220,
15069,
357,
66,
8,
2211,
11,
2039,
28895,
11,
3457,
13,
198,
2,
220,
1439,
2489,
10395,
13,
198,
2,
10097,
26171,
198,
6738,
3858,
1330,
15553,
6030,
198,
198,
6738,
12796,
13,
15042,
1330,
357,
198,
... | 2.808058 | 7,372 |
n1 = int(input("Input first number: ")
n2 = int(input("Input second number: ")
sum = n1+n2
print("Sum:",sum)
| [
77,
16,
796,
493,
7,
15414,
7203,
20560,
717,
1271,
25,
366,
8,
198,
77,
17,
796,
493,
7,
15414,
7203,
20560,
1218,
1271,
25,
366,
8,
198,
16345,
796,
299,
16,
10,
77,
17,
198,
4798,
7203,
13065,
25,
1600,
16345,
8,
198
] | 2.477273 | 44 |
"""Actions to manage challenge clusters"""
from .commands import vlan_ifname, BrctlCmd, ComposeCmd
from .db import DB
import docker
import logging
import subprocess
logger = logging.getLogger(__name__)
dockerc = docker.from_env()
def cluster_check(user, vpn, cluster):
"""Check that the cluster is up when Redis says it is up"""
if cluster.status in (DB.Cluster.UP, DB.Cluster.EXPIRING):
if not cluster_bridge_exists(cluster):
logger.warning("Cluster bridge not found for %s marked as %s; marking as down", cluster.id, cluster.status)
cluster.status = DB.Cluster.DOWN
if vpn.links[user.vlan] == DB.Vpn.LINK_BRIDGED:
vpn.links[user.vlan] = DB.Vpn.LINK_UP
else:
logger.debug("Verified cluster bridge is up for %s", cluster.id)
| [
37811,
32,
2733,
284,
6687,
4427,
23163,
37811,
198,
198,
6738,
764,
9503,
1746,
1330,
410,
9620,
62,
361,
3672,
11,
1709,
34168,
40109,
11,
3082,
577,
40109,
198,
6738,
764,
9945,
1330,
20137,
198,
11748,
36253,
198,
11748,
18931,
198,... | 2.498471 | 327 |
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 13 15:08:56 2019
@author: w
"""
import __init__
import ffn
from pyetf.data import eod
from pyetf.alloc import rpw_standard, rpw_ledoit_wolf
from pyetf.alloc import rpw_garch
from pyetf.alloc import rpw_future
from pyetf.alloc import to_weights
from pyetf.figure import plot_chart
etf_tickers=['SHY','SPY','XLB','XLE','XLF','XLI','XLK','XLP','XLU','XLV','XLY']
basic_tickers = ['SHY','SPY']
#etf_tickers = basic_tickers; mc_budget = [0.1, 0.9]
mc_budget = [0.05, 0.55]
# retrieve data from eod and combine
start_date_str = '2013-01-01'
prices = ffn.get(tickers=etf_tickers, market='US',
provider=eod,
start=start_date_str)
# calc portfolio weights
#w1 = prices.to_weights(func_weighting=rpw_standard, risk_weights=mc_budget).dropna()
#w2 = prices.to_weights(func_weighting=rpw_garch, risk_weights=mc_budget).dropna()
w3 = prices.to_weights(func_weighting=rpw_future, hist_length=-30, risk_weights=mc_budget).dropna()
# calc portfolio performance
#pf1 = prices.to_NAV(w1)
#pf2 = prices.to_NAV(w2)
pf3 = prices.to_NAV(w3)
#pf1.calc_stats().display()
#pf2.calc_stats().display()
pf3.calc_stats().display()
# plot portfolio
pl = pf3.copy()
w = w3.copy()
pl.dropna()
pl = pl.rebase()
w.dropna()
plot_chart(pl[['NAV','spy']], sub_fill=w) | [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
37811,
198,
41972,
319,
7031,
5979,
1511,
1315,
25,
2919,
25,
3980,
13130,
198,
198,
31,
9800,
25,
266,
198,
37811,
198,
11748,
11593,
15003,
834,
198,
11748,
277,
22184... | 2.264957 | 585 |
# -*- coding: utf-8 -*-
import re
import scrapy
from locations.items import GeojsonPointItem
from locations.hours import OpeningHours
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
11748,
302,
198,
198,
11748,
15881,
88,
198,
198,
6738,
7064,
13,
23814,
1330,
2269,
13210,
1559,
12727,
7449,
198,
6738,
7064,
13,
24425,
1330,
25522,
39792,
628
] | 3.261905 | 42 |
import json
import os
import sys
import tempfile
from typing import Any
from typing import Optional
import lib.core as constances
from lib import __file__ as lib_path
from lib.app.helpers import split_project_path
from lib.app.input_converters.conversion import import_annotation
from lib.app.interface.base_interface import BaseInterfaceFacade
from lib.app.interface.sdk_interface import attach_document_urls_to_project
from lib.app.interface.sdk_interface import attach_image_urls_to_project
from lib.app.interface.sdk_interface import attach_video_urls_to_project
from lib.app.interface.sdk_interface import create_folder
from lib.app.interface.sdk_interface import create_project
from lib.app.interface.sdk_interface import upload_annotations_from_folder_to_project
from lib.app.interface.sdk_interface import upload_images_from_folder_to_project
from lib.app.interface.sdk_interface import upload_preannotations_from_folder_to_project
from lib.app.interface.sdk_interface import upload_videos_from_folder_to_project
from lib.core.entities import ConfigEntity
from lib.infrastructure.controller import Controller
from lib.infrastructure.repositories import ConfigRepository
controller = Controller.get_instance()
class CLIFacade(BaseInterfaceFacade):
"""
With SuperAnnotate CLI, basic tasks can be accomplished using shell commands:
superannotatecli <command> <--arg1 val1> <--arg2 val2> [--optional_arg3 val3] [--optional_arg4] ...
"""
@staticmethod
def version():
"""
To show the version of the current SDK installation
"""
with open(
f"{os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(lib_path))))}/version.py"
) as f:
version = f.read().rstrip()[15:-1]
print(version)
sys.exit(0)
@staticmethod
def init():
"""
To initialize CLI (and SDK) with team token
"""
repo = ConfigRepository()
config = repo.get_one(uuid=constances.TOKEN_UUID)
if config:
if not input(
f"File {repo.config_path} exists. Do you want to overwrite? [y/n] : "
).lower() in ("y", "yes"):
return
token = input(
"Input the team SDK token from https://app.superannotate.com/team : "
)
config_entity = ConfigEntity(uuid=constances.TOKEN_UUID, value=token)
repo.insert(config_entity)
if config:
print("Configuration file successfully updated.")
else:
print("Configuration file successfully created.")
sys.exit(0)
def create_project(self, name: str, description: str, type: str):
"""
To create a new project
"""
create_project(name, description, type)
sys.exit(0)
def create_folder(self, project: str, name: str):
"""
To create a new folder
"""
create_folder(project, name)
sys.exit(0)
def upload_images(
self,
project: str,
folder: str,
extensions: str = constances.DEFAULT_IMAGE_EXTENSIONS,
set_annotation_status: str = constances.AnnotationStatus.NOT_STARTED.name,
exclude_file_patterns=constances.DEFAULT_FILE_EXCLUDE_PATTERNS,
recursive_subfolders=False,
image_quality_in_editor=None,
):
"""
To upload images from folder to project use:
If optional argument recursive is given then subfolders of <folder_path> are also
recursively scanned for available images.
Optional argument extensions accepts comma separated list of image extensions to look for.
If the argument is not given then value jpg,jpeg,png,tif,tiff,webp,bmp is assumed.
"""
if not isinstance(extensions, list):
extensions = extensions.split(",")
upload_images_from_folder_to_project(
project,
folder_path=folder,
extensions=extensions,
annotation_status=set_annotation_status,
exclude_file_patterns=exclude_file_patterns,
recursive_subfolders=recursive_subfolders,
image_quality_in_editor=image_quality_in_editor,
)
sys.exit(0)
def upload_preannotations(
self, project, folder, data_set_name=None, task=None, format=None
):
"""
To upload preannotations from folder to project use
Optional argument format accepts input annotation format. It can have COCO or SuperAnnotate values.
If the argument is not given then SuperAnnotate (the native annotation format) is assumed.
Only when COCO format is specified dataset-name and task arguments are required.
dataset-name specifies JSON filename (without extension) in <folder_path>.
task specifies the COCO task for conversion. Please see import_annotation_format for more details.
The annotation classes will be created during the execution of this command.
"""
self._upload_annotations(
project=project,
folder=folder,
format=format,
data_set_name=data_set_name,
task=task,
pre=True,
)
sys.exit(0)
def upload_annotations(
self, project, folder, data_set_name=None, task=None, format=None
):
"""
To upload annotations from folder to project use
Optional argument format accepts input annotation format. It can have COCO or SuperAnnotate values.
If the argument is not given then SuperAnnotate (the native annotation format) is assumed.
Only when COCO format is specified dataset-name and task arguments are required.
dataset-name specifies JSON filename (without extension) in <folder_path>.
task specifies the COCO task for conversion. Please see import_annotation_format for more details.
The annotation classes will be created during the execution of this command.
"""
self._upload_annotations(
project=project,
folder=folder,
format=format,
data_set_name=data_set_name,
task=task,
pre=False,
)
sys.exit(0)
def attach_image_urls(
self, project: str, attachments: str, annotation_status: Optional[Any] = None
):
"""
To attach image URLs to project use:
"""
attach_image_urls_to_project(
project=project,
attachments=attachments,
annotation_status=annotation_status,
)
sys.exit(0)
@staticmethod
def upload_videos(
self,
project,
folder,
target_fps=None,
recursive=False,
extensions=constances.DEFAULT_VIDEO_EXTENSIONS,
set_annotation_status=constances.AnnotationStatus.NOT_STARTED.name,
start_time=0.0,
end_time=None,
):
"""
To upload videos from folder to project use
If optional argument recursive is given then subfolders of <folder_path> are also recursively scanned for available videos.
Optional argument extensions accepts comma separated list of image extensions to look for.
If the argument is not given then value mp4,avi,mov,webm,flv,mpg,ogg is assumed.
target-fps specifies how many frames per second need to extract from the videos (approximate).
If not specified all frames will be uploaded.
start-time specifies time (in seconds) from which to start extracting frames, default is 0.0.
end-time specifies time (in seconds) up to which to extract frames. If it is not specified, then up to end is assumed.
"""
upload_videos_from_folder_to_project(
project=project,
folder_path=folder,
extensions=extensions,
exclude_file_patterns=(),
recursive_subfolders=recursive,
target_fps=target_fps,
start_time=start_time,
end_time=end_time,
annotation_status=set_annotation_status,
image_quality_in_editor=None,
)
sys.exit(0)
| [
11748,
33918,
198,
11748,
28686,
198,
11748,
25064,
198,
11748,
20218,
7753,
198,
6738,
19720,
1330,
4377,
198,
6738,
19720,
1330,
32233,
198,
198,
11748,
9195,
13,
7295,
355,
1500,
1817,
198,
6738,
9195,
1330,
11593,
7753,
834,
355,
9195... | 2.511514 | 3,257 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_pandits
----------------------------------
Tests for `pandits` module.
"""
##############################################################################
from scipy import stats
from pandits import strategies
from pandits.bandit import Bandit
import pytest
##############################################################################
@pytest.mark.parametrize("StrategyCls,params", [
(strategies.RoundRobin, None),
(strategies.Random, None),
(strategies.EpsilonGreedy, {"epsilon": .1}),
(strategies.EpsilonGreedy, {"epsilon": .5}),
(strategies.MaxMean, None),
(strategies.UCB1, None),
(strategies.UCB1Tuned, None),
])
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
37811,
198,
9288,
62,
79,
392,
896,
198,
3880,
438,
198,
198,
51,
3558,
329,
4600,
79,
392,
896,
63,
8265,
13,... | 3.012766 | 235 |
import requests
headers = {
'Origin': 'http://www.realtor.ca',
# 'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'en-US,en;q=0.8',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Accept': '*/*',
'Referer': 'http://www.realtor.ca/Residential/Map.aspx',
'Connection': 'keep-alive',
}
data = {
'CultureId': '1',
'ApplicationId': '1',
'RecordsPerPage': '200',
'MaximumResults': '200',
'PropertyTypeId': '300',
'TransactionTypeId': '2',
'StoreyRange': '0-0',
'BuildingTypeId': '1',
'BedRange': '0-0',
'BathRange': '0-0',
'LongitudeMin': '-79.3676805496215',
'LongitudeMax': '-79.27300930023185',
'LatitudeMin': '43.660358732823845',
'LatitudeMax': '43.692390574029936',
'SortOrder': 'A',
'SortBy': '1',
'viewState': 'm',
'Longitude': '-79.4107246398925',
'Latitude': '43.6552047278685',
'ZoomLevel': '13',
'CurrentPage': '1',
}
response = requests.post('http://localhost:28139/api/Listing.svc/PropertySearch_Post', headers=headers, data=data)
| [
11748,
7007,
198,
198,
50145,
796,
1391,
198,
220,
220,
220,
705,
39688,
10354,
705,
4023,
1378,
2503,
13,
260,
2501,
273,
13,
6888,
3256,
198,
220,
220,
220,
1303,
705,
38855,
12,
27195,
7656,
10354,
705,
70,
13344,
11,
825,
17660,
... | 2.241758 | 546 |
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
gen_correlation() | [
11748,
19798,
292,
355,
279,
67,
198,
11748,
384,
397,
1211,
355,
3013,
82,
198,
11748,
2603,
29487,
8019,
13,
9078,
29487,
355,
458,
83,
198,
198,
5235,
62,
10215,
49501,
3419
] | 2.875 | 32 |
import os
import glob
import logging
logger = logging.getLogger("api_log")
| [
11748,
28686,
198,
11748,
15095,
198,
11748,
18931,
198,
6404,
1362,
796,
18931,
13,
1136,
11187,
1362,
7203,
15042,
62,
6404,
4943,
198
] | 3.26087 | 23 |
#!/usr/bin/env python
import hashlib,string
from numbers import Number
from base64 import standard_b64encode,standard_b64decode
import filehash
try:
import warnings
except ImportError:
warnings = None
try:
import json
except ImportError:
json = None
#######CONSTANTS#######
_PRINTABLE = ''.join(map(chr,range(0x09,0x0E))+map(chr,range(0x20,0x7F)))
_IDENT_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'
#
#
# Manifest files are placed (programatically) in each directory holding relevant files.
# Each file in the directory should hold AT MOST one user.
#
# ENCODING: b74cb12d
# b 7 4 c b 1 2 d
# Magic: '\x62\x37\x34\x63\x62\x31\x32\x64'
# 0 1 2 3 4 5 6 7
# Header:
# Starts at the first '\x01'.
# Header parts are started with '\x01' and followed by an ascii character
# representing their particular function.
# Manifest identifier: '\x01N'+ IDENT(see Misc. below)
# ....
# Manifest Version #: '\x01V'+ IDENT
# Manifest Extension: '\x01X'+ IDENT
# Manifest Hash: '\x01H'+ md5-hash (hex) of concat(02F,02D)
# Attributes: '\x01A'+IDENT+'\x1E'+ DATA(see Misc. below)
# End of header: '\x01E'
#
# Sections:
# Non-header sections start with '\x02' and followed by an ascii character
# representing their particular function.
# '\x02F' : Section for the list of files relevant in this directory.
# List entities are separated by '\x1C'.
# Each entity is of the form base64(fname) +'\x1E'+ base64(username) +'\x1E'+ md5_hex
# (username is 'none' if not relevant)
# (md5_hex is '0'*32 if hash cannot be taken)
# '\x02D' : Section for the list of subdirectories (with manifests) in this directory.
# List entities are separated by '\x1D'.
# Each entity is of the form base64(dirname) +'\x1E'+ manifest-hash(of dir's mfst)
# '\x02E' : End of Sections
#
# End of Manifest:
# The end of manifest-related data is marked by '\x04', aka EOT.
#
# Misc.:
# strings: '\x90'+'content here'+'\x9C'
# only allows characters in _PRINTABLE
# IDENT: identifier of the form "[A-Za-z0-9_-]+"
# DATA: The first byte determines the type of value.
# '\x90' for a string (tailed by '\x9C', as above)
# 'I' for an int/float (in ASCII, not hex/binary)
# 'L' for an iterable containing either/both of the above two, each preceded by '\x1F'.
#
# C0/C1 Meanings
#
# \x01 Start of Heading
# \x02 Start of text
# \x90 Device Control String
# \x9C String Terminator
# \x1D Group Separator
# \x1E Record Seperator
# \x1F Unit Seperator
''' _ ___ ___
|\ | / \ | | WHEN USING THE FUNCTIONS BELOW, DO
| \ | | | | |--- * NOT PRE-FORMAT ANY DATA.
| \| \_/ | |___ * ALL FORMATTING IS HANDLED BY THE MODULE.
'''
'''[(Above) NOTE: WHEN USING THE FUNCTIONS BELOW, DO NOT PRE-FORMAT ANY DATA. ALL FORMATTING IS HANDLED BY THE MODULE.]'''
#leading
#first must build sections (02F and 02D)
#second make manifest hash for header
#third build header
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
198,
11748,
12234,
8019,
11,
8841,
198,
6738,
3146,
1330,
7913,
198,
6738,
2779,
2414,
1330,
3210,
62,
65,
2414,
268,
8189,
11,
20307,
62,
65,
2414,
12501,
1098,
198,
11748,
2393,
1783... | 2.084889 | 1,661 |
import pandas as pd
import requests
def update_data():
"""
Downloads the data and writes them to a new csv file.
:return: None
"""
confirmed_url = "https://data.humdata.org/hxlproxy/api/data-preview.csv?" \
"url=https%3A%2F%2Fraw.githubusercontent.com%2FCSSEGISandData%2FCOVID-19%" \
"2Fmaster%2Fcsse_covid_19_data%2Fcsse_covid_19_time_series%" \
"2Ftime_series_covid19_confirmed_global.csv&filename=time_series_covid19_confirmed_global.csv"
deaths_url = "https://data.humdata.org/hxlproxy/api/data-preview.csv?url=https%3A%2F%" \
"2Fraw.githubusercontent.com%2FCSSEGISandData%2FCOVID-19%2Fmaster%" \
"2Fcsse_covid_19_data%2Fcsse_covid_19_time_series%2Ftime_series_covid19_deaths_global.csv&" \
"filename=time_series_covid19_deaths_global.csv"
recovered_url = "https://data.humdata.org/hxlproxy/api/data-preview.csv?" \
"url=https%3A%2F%2Fraw.githubusercontent.com%2FCSSEGISandData%2FCOVID-19%" \
"2Fmaster%2Fcsse_covid_19_data%2Fcsse_covid_19_time_series%" \
"2Ftime_series_covid19_recovered_global.csv&filename=time_series_covid19_recovered_global.csv"
download_data(confirmed_url, "../Datasets/covid19_confirmed_global.csv")
download_data(deaths_url, "../Datasets/covid19_deaths_global.csv")
download_data(recovered_url, "../Datasets/covid19_recovered_global.csv")
def read_data():
"""
Reads the data and adjusts them.
:return: Dictionary of the data
"""
confirmed = pd.read_csv("../Datasets/covid19_confirmed_global.csv")
deaths = pd.read_csv("../Datasets/covid19_deaths_global.csv")
recovered = pd.read_csv("../Datasets/covid19_recovered_global.csv")
confirmed = adjust(confirmed)
deaths = adjust(deaths)
recovered = adjust(recovered)
return {'confirmed': confirmed, 'deaths': deaths, 'recovered': recovered}
| [
11748,
19798,
292,
355,
279,
67,
198,
11748,
7007,
628,
198,
4299,
4296,
62,
7890,
33529,
198,
220,
220,
220,
37227,
198,
220,
220,
220,
50093,
262,
1366,
290,
6797,
606,
284,
257,
649,
269,
21370,
2393,
13,
198,
220,
220,
220,
1058... | 2.151087 | 920 |
from flask import Flask, request
import ujson as json
kv = {}
app = Flask(__name__)
@app.route('/kv')
if __name__=="__main__":
app.run(port=8080)
| [
6738,
42903,
1330,
46947,
11,
2581,
198,
11748,
334,
17752,
355,
33918,
198,
198,
74,
85,
796,
23884,
198,
198,
1324,
796,
46947,
7,
834,
3672,
834,
8,
198,
198,
31,
1324,
13,
38629,
10786,
14,
74,
85,
11537,
198,
198,
361,
11593,
... | 2.396825 | 63 |
from expression import *
changeDegreeGpio([0],[0],5,0.03)
time.sleep(0.5)
changeDegreeGpio([0],[90],5,0.03)
time.sleep(0.5)
changeDegreeGpio([0],[180],5,0.03)
time.sleep(0.5)
changeDegreeGpio([0],[90],5,0.03)
time.sleep(0.5)
| [
6738,
5408,
1330,
1635,
198,
198,
3803,
35,
1533,
631,
38,
79,
952,
26933,
15,
38430,
15,
4357,
20,
11,
15,
13,
3070,
8,
198,
2435,
13,
42832,
7,
15,
13,
20,
8,
198,
3803,
35,
1533,
631,
38,
79,
952,
26933,
15,
38430,
3829,
43... | 1.923729 | 118 |
import ctypes
import sys
from pydigilent.lowlevel.common import HIF
if sys.platform.startswith("win"):
_depp = ctypes.cdll.depp
else:
_depp = ctypes.cdll.LoadLibrary("libdepp.so")
_DeppGetVersion = _depp.DeppGetVersion
_DeppGetVersion.argtypes = [ctypes.POINTER(ctypes.c_char * 32)]
_DeppGetVersion.restype = bool
_DeppGetPortCount = _depp.DeppGetPortCount
_DeppGetPortCount.argtypes = [HIF, ctypes.POINTER(ctypes.c_int32)]
_DeppGetPortCount.restype = bool
_DeppGetPortProperties = _depp.DeppGetPortProperties
_DeppGetPortProperties.argtypes = [HIF, ctypes.c_int32, ctypes.POINTER(ctypes.c_uint32)]
_DeppGetPortProperties.restype = bool
DeppEnable = _depp.DeppEnable
DeppEnable.argtypes = [HIF]
DeppEnable.restype = bool
DeppEnableEx = _depp.DeppEnableEx
DeppEnableEx.argtypes = [HIF, ctypes.c_int32]
DeppEnableEx.restype = bool
DeppDisable = _depp.DeppDisable
DeppDisable.argtypes = [HIF]
DeppDisable.restype = bool
DeppPutReg = _depp.DeppPutReg
DeppPutReg.argtypes = [HIF, ctypes.c_ubyte, ctypes.c_ubyte, ctypes.c_ubyte]
DeppPutReg.restype = bool
_DeppGetReg = _depp.DeppGetReg
_DeppGetReg.argtypes = [HIF, ctypes.c_ubyte, ctypes.POINTER(ctypes.c_ubyte), ctypes.c_ubyte]
_DeppGetReg.restype = bool
DeppPutRegSet = _depp.DeppPutRegSet
DeppPutRegSet.argtypes = [HIF, ctypes.POINTER(ctypes.c_ubyte), ctypes.c_uint32, ctypes.c_ubyte]
DeppPutRegSet.restype = bool
DeppGetRegSet = _depp.DeppGetRegSet
DeppGetRegSet.argtypes = [HIF, ctypes.POINTER(ctypes.c_ubyte), ctypes.POINTER(ctypes.c_ubyte), ctypes.c_uint32, ctypes.c_ubyte]
DeppGetRegSet.restype = bool
DeppPutRegRepeat = _depp.DeppPutRegRepeat
DeppPutRegRepeat.argtypes = [HIF, ctypes.c_ubyte, ctypes.POINTER(ctypes.c_ubyte), ctypes.c_uint32, ctypes.c_ubyte]
DeppPutRegRepeat.restype = bool
DeppGetRegRepeat = _depp.DeppGetRegRepeat
DeppGetRegRepeat.argtypes = [HIF, ctypes.c_ubyte, ctypes.POINTER(ctypes.c_ubyte), ctypes.c_uint32, ctypes.c_ubyte]
DeppGetRegRepeat.restype = bool
__all__ = [
'DeppGetVersion', 'DeppGetPortCount', 'DeppGetPortProperties', 'DeppEnable', 'DeppEnableEx', 'DeppDisable',
'DeppPutReg', 'DeppGetReg', 'DeppPutRegSet', 'DeppGetRegSet', 'DeppPutRegRepeat', 'DeppGetRegRepeat'
]
| [
11748,
269,
19199,
198,
11748,
25064,
198,
198,
6738,
279,
5173,
27187,
298,
13,
9319,
5715,
13,
11321,
1330,
367,
5064,
198,
198,
361,
25064,
13,
24254,
13,
9688,
2032,
342,
7203,
5404,
1,
2599,
198,
220,
220,
220,
4808,
2934,
381,
... | 2.332623 | 938 |
for i in range(int(input())):
n,k = [int(j) for j in input().split()]
m,s = set(),set()
for j in range(k):
a,b = [int(p) for p in input().split()]
m.add(a-1)
s.add(b-1)
c = 0
l = []
for j in range(n):
if(j not in m):
for k in range(n):
if(k not in s):
c+=1
l.append(j+1)
l.append(k+1)
m.add(j)
s.add(k)
break
print(c,*l)
| [
1640,
1312,
287,
2837,
7,
600,
7,
15414,
28955,
2599,
198,
220,
220,
220,
299,
11,
74,
796,
685,
600,
7,
73,
8,
329,
474,
287,
5128,
22446,
35312,
3419,
60,
198,
220,
220,
220,
285,
11,
82,
796,
900,
22784,
2617,
3419,
198,
220,... | 1.481793 | 357 |
# -*- coding: utf-8 -*-
# numerical.py
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
import re
import numpy as np
from collections import Counter, OrderedDict
from mipqctool.config import ERROR, LOGGER, DEFAULT_MISSING_VALUES
# Regex unicode support
def infer_integer(value, **options):
"""Find if the given string value it represents an integer.
"""
result = None
suffix = None
strval = str(value)
match = re.match(_INT, strval, flags=re.UNICODE)
if match:
result = 'd'
if match.group('suffix'):
suffix = match.group('suffix')
result += suffix
else:
result = ERROR
return result
def describe_integer(pattern, uniques, maxlevels=10):
"""Return a descriptor object based on given pattern.
Arguments:
:param pattern: string with qctype pattern
:param uniques: set with unique values found
:param maxlevels: threshold value for considering an integer
type value as nominal ie (0,1), (1,2,3,4)
:return: dictionary descriptor
"""
match = re.match(_PAT, pattern, flags=re.UNICODE)
if match:
if match.group('suffix'):
return {
'type': 'integer',
'format': 'default',
'MIPType': 'integer',
'bareNumber': False,
'suffix': match.group('suffix')
}
else:
if uniques == set(['0', '1']):
return {
'type': 'boolean',
'format': 'default',
'MIPType': 'nominal',
'trueValues': ['1'],
'falseValues': ['0'],
}
elif len(uniques) <= maxlevels:
levels = list(uniques)
levels.sort()
try:
are_integers = [int(enum) for enum in levels]
return {
'type': 'integer',
'format': 'default',
'MIPType': 'nominal',
'constraints': {
'enum': levels
}
}
except ValueError:
# there are enumerations with type other than
# integers, return string type field
return {
'type': 'string',
'format': 'default',
'MIPType': 'nominal',
'constraints': {
'enum': levels
}
}
else:
return {
'type': 'integer',
'format': 'default',
'MIPType': 'integer',
'bareNumber': True,
}
else:
return ERROR
def profile_integer(pairs, **options):
"""Return stats for the integer field
Arguments:
:param pairs: list with pairs (row, value)
:return: dictionary with stats
"""
result = OrderedDict()
# Get the values in an numpy array
values = np.asarray([r[1] for r in pairs])
c = Counter(values)
result['mode'], result['freq'] = c.most_common(1)[0]
result['min'] = np.min(values)
result['max'] = np.max(values)
# convert those stats to integer in case of zeros values
result['q1'] = int(np.quantile(values, 0.25))
result['median'] = int(np.median(values))
result['q3'] = int(np.quantile(values, 0.75))
return result
def suggestc_integer(value, **options):
"""Suggest a value for the given value that violates the constraint.
"""
null = options.get('missing_values', DEFAULT_MISSING_VALUES)[0]
return null
def suggestd_integer(value, **options):
"""Suggest a value in the given datatype.
"""
null = options.get('missing_values', DEFAULT_MISSING_VALUES)[0]
try:
# case value is float, try to round it
suggested = str(int(float(value)))
except ValueError:
suggested = null
return suggested
# Internal
_INT = (r'^(?P<sign>[+-])?\d+'
r'(?P<suffix>(\s?[^0-9\s^&!*\-_+=~,\.`@\"\'\\\/]{1,5}\d?)\)?)?$')
_PAT = (r'^[d]'
r'(?P<suffix>(\s?[^0-9\s^&!*-+=~,\.`@\"\'\\\/]{1,5}\d{0,3})\)?)?$')
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
2,
29052,
13,
9078,
198,
198,
6738,
11593,
37443,
834,
1330,
7297,
198,
6738,
11593,
37443,
834,
1330,
3601,
62,
8818,
198,
6738,
11593,
37443,
834,
1330,
4112,
62,
1174... | 1.995027 | 2,212 |
import unittest
from django.test import TestCase
from django.test.utils import override_settings
from .test_backends import BackendTests
@override_settings(WAGTAILSEARCH_BACKENDS={
'default': {
'BACKEND': 'wagtail.search.backends.database.fallback',
}
})
| [
11748,
555,
715,
395,
198,
198,
6738,
42625,
14208,
13,
9288,
1330,
6208,
20448,
198,
6738,
42625,
14208,
13,
9288,
13,
26791,
1330,
20957,
62,
33692,
198,
198,
6738,
764,
9288,
62,
1891,
2412,
1330,
5157,
437,
51,
3558,
628,
198,
31,... | 2.722772 | 101 |
import torch
from .. import FF
class PositionwiseFF(torch.nn.Module):
"""Positionwise Feed-forward layer.
Arguments:
Input:
Output:
"""
| [
11748,
28034,
198,
198,
6738,
11485,
1330,
18402,
628,
198,
4871,
23158,
3083,
5777,
7,
13165,
354,
13,
20471,
13,
26796,
2599,
198,
220,
220,
220,
37227,
26545,
3083,
18272,
12,
11813,
7679,
13,
628,
220,
220,
220,
20559,
2886,
25,
6... | 2.745763 | 59 |
""" This example evaluates the volume potential and its derivatives
over [-1,1]^3 with the Laplace kernel.
"""
from __future__ import absolute_import, division, print_function
__copyright__ = "Copyright (C) 2019 Xiaoyu Wei"
__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import logging
import numpy as np
import pyopencl as cl
import boxtree as bt
import sumpy as sp
import volumential as vm
import pymbolic as pmbl
import pymbolic.functions
from volumential.tools import ScalarFieldExpressionEvaluation as Eval
from functools import partial
verbose = True
logger = logging.getLogger(__name__)
if verbose:
logging.basicConfig(level=logging.INFO)
else:
logging.basicConfig(level=logging.CRITICAL)
print("*************************")
print("* Setting up...")
print("*************************")
dim = 3
table_filename = "nft_laplace3d.hdf5"
logger.info("Using table cache: " + table_filename)
q_order = 2 # quadrature order
n_levels = 7 # 2^(n_levels-1) subintervals in 1D, must be at least 2 if not adaptive
use_multilevel_table = False
adaptive_mesh = False
n_refinement_loops = 100
refined_n_cells = 5e5
rratio_top = 0.2
rratio_bot = 0.5
dtype = np.float64
m_order = 15 # multipole order
force_direct_evaluation = False
logger.info("Multipole order = " + str(m_order))
logger.info("Quad order = " + str(q_order))
logger.info("N_levels = " + str(n_levels))
# a solution that is nearly zero at the boundary
# exp(-40) = 4.25e-18
alpha = 80
x = pmbl.var("x")
y = pmbl.var("y")
z = pmbl.var("z")
expp = pmbl.var("exp")
norm2 = x ** 2 + y ** 2 + z ** 2
source_expr = -(4 * alpha ** 2 * norm2 - 6 * alpha) * expp(-alpha * norm2)
solu_expr = expp(-alpha * norm2)
solu_dx_expr = (-alpha) * solu_expr * (2*x)
solu_dy_expr = (-alpha) * solu_expr * (2*y)
solu_dz_expr = (-alpha) * solu_expr * (2*z)
logger.info("Source expr: " + str(source_expr))
logger.info("Solu expr: " + str(solu_expr))
# bounding box
a = -0.5
b = 0.5
root_table_source_extent = 2
ctx = cl.create_some_context()
queue = cl.CommandQueue(ctx)
# logger.info("Summary of params: " + get_param_summary())
source_eval = Eval(dim, source_expr, [x, y, z])
# {{{ generate quad points
import volumential.meshgen as mg
# Show meshgen info
mg.greet()
mesh = mg.MeshGen3D(q_order, n_levels, a, b)
if not adaptive_mesh:
mesh.print_info()
q_points = mesh.get_q_points()
q_weights = mesh.get_q_weights()
q_radii = None
else:
iloop = -1
while mesh.n_active_cells() < refined_n_cells:
iloop += 1
cell_centers = mesh.get_cell_centers()
cell_measures = mesh.get_cell_measures()
density_vals = source_eval(
queue,
np.array([[center[d] for center in cell_centers] for d in range(dim)]),
)
crtr = np.abs(cell_measures * density_vals)
mesh.update_mesh(crtr, rratio_top, rratio_bot)
if iloop > n_refinement_loops:
print("Max number of refinement loops reached.")
break
mesh.print_info()
q_points = mesh.get_q_points()
q_weights = mesh.get_q_weights()
q_radii = None
if 0:
mesh.generate_gmsh("box_grid.msh")
legacy_msh_file = True
if legacy_msh_file:
import os
os.system("gmsh box_grid.msh convert_grid -")
assert len(q_points) == len(q_weights)
assert q_points.shape[1] == dim
q_points_org = q_points
q_points = np.ascontiguousarray(np.transpose(q_points))
from pytools.obj_array import make_obj_array
q_points = make_obj_array([cl.array.to_device(queue, q_points[i]) for i in range(dim)])
q_weights = cl.array.to_device(queue, q_weights)
# q_radii = cl.array.to_device(queue, q_radii)
# }}}
# {{{ discretize the source field
logger.info("discretizing source field")
source_vals = cl.array.to_device(
queue, source_eval(queue, np.array([coords.get() for coords in q_points]))
)
# particle_weigt = source_val * q_weight
# }}} End discretize the source field
# {{{ build tree and traversals
from boxtree.tools import AXIS_NAMES
axis_names = AXIS_NAMES[:dim]
from pytools import single_valued
coord_dtype = single_valued(coord.dtype for coord in q_points)
from boxtree.bounding_box import make_bounding_box_dtype
bbox_type, _ = make_bounding_box_dtype(ctx.devices[0], dim, coord_dtype)
bbox = np.empty(1, bbox_type)
for ax in axis_names:
bbox["min_" + ax] = a
bbox["max_" + ax] = b
# tune max_particles_in_box to reconstruct the mesh
# TODO: use points from FieldPlotter are used as target points for better
# visuals
print("building tree")
from boxtree import TreeBuilder
tb = TreeBuilder(ctx)
tree, _ = tb(
queue,
particles=q_points,
targets=q_points,
bbox=bbox,
max_particles_in_box=q_order ** 3 * 8 - 1,
kind="adaptive-level-restricted",
)
from boxtree.traversal import FMMTraversalBuilder
tg = FMMTraversalBuilder(ctx)
trav, _ = tg(queue, tree)
# }}} End build tree and traversals
# {{{ build near field potential table
from volumential.table_manager import NearFieldInteractionTableManager
tm = NearFieldInteractionTableManager(
table_filename, root_extent=root_table_source_extent
)
if use_multilevel_table:
logger.info("Using multilevel tables")
assert (
abs(
int((b - a) / root_table_source_extent) * root_table_source_extent - (b - a)
)
< 1e-15
)
nftable_list = []
nftable_dx_list = []
nftable_dy_list = []
nftable_dz_list = []
for l in range(0, tree.nlevels + 1):
if 1:
print("Getting table at level", l)
tb, _ = tm.get_table(dim, "Laplace", q_order,
source_box_level=l, compute_method="DrosteSum",
queue=queue, n_brick_quad_points=120,
adaptive_level=False, use_symmetry=True,
alpha=0, n_levels=1,
)
nftable_list.append(tb)
if 1:
print("Getting table Dx at level", l)
tb, _ = tm.get_table(dim, "Laplace-Dx", q_order,
source_box_level=l, compute_method="DrosteSum",
queue=queue, n_brick_quad_points=120,
adaptive_level=False, use_symmetry=False,
alpha=0, n_levels=1,
)
nftable_dx_list.append(tb)
print("Using table list of length", len(nftable))
nftable = {
nftable_list[0].integral_knl.__repr__(): nftable_list,
nftable_dx_list[0].integral_knl.__repr__(): nftable_dx_list,
# nftable_dy_list[0].integral_knl.__repr__(): nftable_dy_list,
}
else:
logger.info("Using single level table")
if 1:
print("Getting table")
tb, _ = tm.get_table(dim, "Laplace", q_order,
compute_method="DrosteSum", queue=queue,
n_brick_quad_points=120, adaptive_level=False,
use_symmetry=True,
alpha=0, n_levels=1,
)
if 1:
print("Getting table Dx")
tb_dx, _ = tm.get_table(dim, "Laplace-Dx", q_order,
compute_method="DrosteSum", queue=queue,
n_brick_quad_points=120, adaptive_level=False,
use_symmetry=False,
alpha=0, n_levels=1,
)
if 1:
print("Getting table Dy")
tb_dy, _ = tm.get_table(dim, "Laplace-Dy", q_order,
compute_method="DrosteSum", queue=queue,
n_brick_quad_points=120, adaptive_level=False,
use_symmetry=False,
alpha=0, n_levels=1,
)
if 1:
print("Getting table Dz")
tb_dz, _ = tm.get_table(dim, "Laplace-Dz", q_order,
compute_method="DrosteSum", queue=queue,
n_brick_quad_points=120, adaptive_level=False,
use_symmetry=False,
alpha=0, n_levels=1,
)
nftable = {
tb.integral_knl.__repr__(): tb,
tb_dx.integral_knl.__repr__(): tb_dx,
tb_dy.integral_knl.__repr__(): tb_dy,
tb_dz.integral_knl.__repr__(): tb_dz,
}
# }}} End build near field potential table
# {{{ sumpy expansion for laplace kernel
from sumpy.expansion import DefaultExpansionFactory
from sumpy.kernel import LaplaceKernel, AxisTargetDerivative
knl = LaplaceKernel(dim)
knl_dx = AxisTargetDerivative(0, knl)
knl_dy = AxisTargetDerivative(1, knl)
knl_dz = AxisTargetDerivative(2, knl)
out_kernels = [knl, knl_dx, knl_dy, knl_dz]
expn_factory = DefaultExpansionFactory()
local_expn_class = expn_factory.get_local_expansion_class(knl)
mpole_expn_class = expn_factory.get_multipole_expansion_class(knl)
exclude_self = True
from volumential.expansion_wrangler_fpnd import (
FPNDExpansionWranglerCodeContainer,
FPNDExpansionWrangler)
wcc = FPNDExpansionWranglerCodeContainer(
ctx,
partial(mpole_expn_class, knl),
partial(local_expn_class, knl),
out_kernels,
exclude_self=exclude_self,
)
if exclude_self:
target_to_source = np.arange(tree.ntargets, dtype=np.int32)
self_extra_kwargs = {"target_to_source": target_to_source}
else:
self_extra_kwargs = {}
wrangler = FPNDExpansionWrangler(
code_container=wcc,
queue=queue,
tree=tree,
near_field_table=nftable,
dtype=dtype,
fmm_level_to_order=lambda kernel, kernel_args, tree, lev: m_order,
quad_order=q_order,
self_extra_kwargs=self_extra_kwargs,
)
# }}} End sumpy expansion for laplace kernel
print("*************************")
print("* Performing FMM ...")
print("*************************")
# {{{ conduct fmm computation
from volumential.volume_fmm import drive_volume_fmm
import time
queue.finish()
t0 = time.time()
pot = drive_volume_fmm(
trav,
wrangler,
source_vals * q_weights,
source_vals,
direct_evaluation=force_direct_evaluation,
)
t1 = time.time()
print("Finished in %.2f seconds." % (t1 - t0))
print("(%e points per second)" % (
len(q_weights) / (t1 - t0)
))
# }}} End conduct fmm computation
print("*************************")
print("* Postprocessing ...")
print("*************************")
# {{{ postprocess and plot
solu_eval = Eval(dim, solu_expr, [x, y, z])
solu_dx_eval = Eval(dim, solu_dx_expr, [x, y, z])
solu_dy_eval = Eval(dim, solu_dy_expr, [x, y, z])
solu_dz_eval = Eval(dim, solu_dz_expr, [x, y, z])
test_x = q_points[0].get()
test_y = q_points[1].get()
test_z = q_points[2].get()
test_nodes = make_obj_array(
# get() first for CL compatibility issues
[
cl.array.to_device(queue, test_x),
cl.array.to_device(queue, test_y),
cl.array.to_device(queue, test_z),
]
)
from volumential.volume_fmm import interpolate_volume_potential
ze = solu_eval(queue, np.array([test_x, test_y, test_z]))
zs = interpolate_volume_potential(test_nodes, trav, wrangler, pot[0]).get()
ze_dx = solu_dx_eval(queue, np.array([test_x, test_y, test_z]))
zs_dx = interpolate_volume_potential(test_nodes, trav, wrangler, pot[1]).get()
ze_dy = solu_dy_eval(queue, np.array([test_x, test_y, test_z]))
zs_dy = interpolate_volume_potential(test_nodes, trav, wrangler, pot[2]).get()
ze_dz = solu_dz_eval(queue, np.array([test_x, test_y, test_z]))
zs_dz = interpolate_volume_potential(test_nodes, trav, wrangler, pot[3]).get()
print_error = True
if print_error:
err = np.max(np.abs(ze - zs))
print("Error =", err)
err_dx = np.max(np.abs(ze_dx - zs_dx))
print("Error Dx =", err_dx)
err_dy = np.max(np.abs(ze_dy - zs_dy))
print("Error Dy =", err_dy)
err_dz = np.max(np.abs(ze_dz - zs_dz))
print("Error Dz =", err_dz)
# Boxtree
if 0:
import matplotlib.pyplot as plt
if dim == 2:
plt.plot(q_points[0].get(), q_points[1].get(), ".")
from boxtree.visualization import TreePlotter
plotter = TreePlotter(tree.get(queue=queue))
plotter.draw_tree(fill=False, edgecolor="black")
# plotter.draw_box_numbers()
plotter.set_bounding_box()
plt.gca().set_aspect("equal")
plt.draw()
plt.show()
# plt.savefig("tree.png")
# Direct p2p
if 0:
print("Performing P2P")
pot_direct, = drive_volume_fmm(
trav, wrangler, source_vals * q_weights, source_vals, direct_evaluation=True
)
zds = pot_direct.get()
zs = pot.get()
print("P2P-FMM diff =", np.max(np.abs(zs - zds)))
print("P2P Error =", np.max(np.abs(ze - zds)))
# Write vtk
if 0:
from meshmode.mesh.io import read_gmsh
modemesh = read_gmsh("box_grid.msh", force_ambient_dim=None)
from meshmode.discretization.poly_element import (
LegendreGaussLobattoTensorProductGroupFactory,
)
from meshmode.discretization import Discretization
box_discr = Discretization(
ctx, modemesh, LegendreGaussLobattoTensorProductGroupFactory(q_order)
)
box_nodes_x = box_discr.nodes()[0].with_queue(queue).get()
box_nodes_y = box_discr.nodes()[1].with_queue(queue).get()
box_nodes_z = box_discr.nodes()[2].with_queue(queue).get()
box_nodes = make_obj_array(
# get() first for CL compatibility issues
[
cl.array.to_device(queue, box_nodes_x),
cl.array.to_device(queue, box_nodes_y),
cl.array.to_device(queue, box_nodes_z),
]
)
visual_order = 1
from meshmode.discretization.visualization import make_visualizer
vis = make_visualizer(queue, box_discr, visual_order)
from volumential.volume_fmm import interpolate_volume_potential
volume_potential = interpolate_volume_potential(box_nodes, trav, wrangler, pot)
source_density = interpolate_volume_potential(
box_nodes, trav, wrangler, source_vals
)
# qx = q_points[0].get()
# qy = q_points[1].get()
# qz = q_points[2].get()
exact_solution = cl.array.to_device(
queue, solu_eval(queue, np.array([box_nodes_x, box_nodes_y, box_nodes_z]))
)
# clean up the mess
vtu_filename = "laplace3d.vtu"
clean_file(vtu_filename)
vis.write_vtk_file(
vtu_filename,
[
("VolPot", volume_potential),
# ("SrcDensity", source_density),
("ExactSol", exact_solution),
("Error", volume_potential - exact_solution),
],
)
print("Written file " + vtu_filename)
# }}} End postprocess and plot
# vim: filetype=python.pyopencl:foldmethod=marker
| [
37811,
770,
1672,
47850,
262,
6115,
2785,
290,
663,
28486,
198,
220,
220,
220,
625,
25915,
16,
11,
16,
60,
61,
18,
351,
262,
4689,
5372,
9720,
13,
198,
37811,
198,
6738,
11593,
37443,
834,
1330,
4112,
62,
11748,
11,
7297,
11,
3601,
... | 2.289058 | 6,708 |
import urlparse
import os
from bs4 import BeautifulSoup
import re
from article_parser import ArticleParser
| [
11748,
19016,
29572,
198,
11748,
28686,
198,
6738,
275,
82,
19,
1330,
23762,
50,
10486,
198,
11748,
302,
198,
6738,
2708,
62,
48610,
1330,
10172,
46677,
198
] | 3.962963 | 27 |
# Copyright (c) 2011, Roger Lew [see LICENSE.txt]
# This software is funded in part by NIH Grant P20 RR016454.
import unittest
import warnings
import os
import math
from random import shuffle, random
from collections import Counter,OrderedDict
from dictset import DictSet,_rep_generator
from math import isnan, isinf, floor
import numpy as np
from pprint import pprint as pp
from pyvttbl import PyvtTbl
from pyvttbl import DataFrame
from pyvttbl.plotting import *
from pyvttbl.stats import *
from pyvttbl.misc.support import *
if __name__ == "__main__":
# run tests
runner = unittest.TextTestRunner()
runner.run(suite())
| [
198,
198,
2,
15069,
357,
66,
8,
2813,
11,
13637,
8260,
685,
3826,
38559,
24290,
13,
14116,
60,
198,
2,
770,
3788,
318,
10588,
287,
636,
416,
37483,
12181,
350,
1238,
26067,
27037,
34229,
13,
198,
198,
11748,
555,
715,
395,
198,
1174... | 3.042453 | 212 |
from itertools import repeat
from typing import List, Optional, Dict
from conditional import conditional
from django.core.checks import Error
from django.core.exceptions import ValidationError
from django.db import transaction, models, IntegrityError, connections
from django.db.models import SlugField
from django.utils.text import slugify
from model_clone.apps import ModelCloneConfig
from model_clone.utils import (
clean_value,
transaction_autocommit,
get_unique_value,
context_mutable_attribute,
get_fields_and_unique_fields_from_cls,
)
class CloneMixin(object):
"""CloneMixin mixin to duplicate an object using the model cls.
:param _clone_fields: Restricted List of fields to copy from the instance.
:type _clone_fields: collections.Iterable
:param _clone_m2m_fields: Many to many fields (Example: TestModel.tags).
:type _clone_m2m_fields: collections.Iterable
:param _clone_m2o_or_o2m_fields: Many to one/One to many fields.
:type _clone_m2o_or_o2m_fields: collections.Iterable
:param _clone_o2o_fields: One to One fields.
:type _clone_o2o_fields: collections.Iterable
:param _clone_excluded_fields: Excluded model fields.
:type _clone_excluded_fields: collections.Iterable
:param _clone_excluded_m2m_fields: Excluded many to many fields.
:type _clone_excluded_m2m_fields: collections.Iterable
:param _clone_excluded_m2o_or_o2m_fields: Excluded many to many
and one to many fields.
:type _clone_excluded_m2o_or_o2m_fields: collections.Iterable
:param _clone_excluded_o2o_fields: Excluded one to one fields.
:type _clone_excluded_o2o_fields: collections.Iterable
:Example:
>>> # Using explicit fields
>>>
>>> class TestModel(CloneMixin, models.Model):
>>> field_1 = models.CharField(max_length=200)
>>> tags = models.ManyToManyField(Tags)
>>> audiences = models.ManyToManyField(Audience)
>>> user = models.ForiegnKey(
>>> settings.AUTH_USER_MODEL,
>>> on_delete=models.CASCADE,
>>> )
>>> _clone_m2m_fields = ['tags', 'audiences']
>>> _clone_m2o_or_o2m_fields = ['user']
>>> ...
>>> # Using implicit all except fields.
>>> class TestModel(CloneMixin, models.Model):
>>> field_1 = models.CharField(max_length=200)
>>> tags = models.ManyToManyField(Tags)
>>> audiences = models.ManyToManyField(Audience)
>>> user = models.ForiegnKey(
>>> settings.AUTH_USER_MODEL,
>>> on_delete=models.CASCADE,
>>> null=True,
>>> )
>>> # Clones any other m2m field excluding "audiences".
>>> _clone_excluded_m2m_fields = ['audiences']
>>> # Clones all other many to one or one to many fields excluding "user".
>>> _clone_excluded_m2o_or_o2m_fields = ['user']
>>> ...
"""
# Included fields
_clone_fields = [] # type: List[str]
_clone_m2m_fields = [] # type: List[str]
_clone_m2o_or_o2m_fields = [] # type: List[str]
_clone_o2o_fields = [] # type: List[str]
# Excluded fields
_clone_excluded_fields = [] # type: List[str]
_clone_excluded_m2m_fields = [] # type: List[str]
_clone_excluded_m2o_or_o2m_fields = [] # type: List[str]
_clone_excluded_o2o_fields = [] # type: List[str]
UNIQUE_DUPLICATE_SUFFIX = "copy" # type: str
USE_UNIQUE_DUPLICATE_SUFFIX = True # type: bool
MAX_UNIQUE_DUPLICATE_QUERY_ATTEMPTS = 100 # type: int
@classmethod
@classmethod
@transaction.atomic
def make_clone(self, attrs=None, sub_clone=False):
"""Creates a clone of the django model instance.
:param attrs: Dictionary of attributes to be replaced on the cloned object.
:type attrs: dict
:param sub_clone: Internal boolean used to detect cloning sub objects.
:type sub_clone: bool
:rtype: :obj:`django.db.models.Model`
:return: The model instance that has been cloned.
"""
attrs = attrs or {}
if not self.pk:
raise ValidationError(
"{}: Instance must be saved before it can be cloned.".format(
self.__class__.__name__
)
)
if sub_clone:
duplicate = self
duplicate.pk = None
else:
duplicate = self._create_copy_of_instance(self)
for name, value in attrs.items():
setattr(duplicate, name, value)
duplicate.save()
duplicate = self.__duplicate_o2o_fields(duplicate)
duplicate = self.__duplicate_o2m_fields(duplicate)
duplicate = self.__duplicate_m2o_fields(duplicate)
duplicate = self.__duplicate_m2m_fields(duplicate)
return duplicate
@staticmethod
def _create_copy_of_instance(instance, force=False, sub_clone=False):
"""Create a copy of an instance
:param instance: The instance to be duplicated.
:type instance: `django.db.models.Model`
:param force: Flag to skip using the current model clone declared attributes.
:type force: bool
:param sub_clone: Flag to skip cloning one to one fields for sub clones.
:type sub_clone: bool
:return: A new transient instance.
:rtype: `django.db.models.Model`
"""
cls = instance.__class__
clone_fields = getattr(cls, "_clone_fields", CloneMixin._clone_fields)
clone_excluded_fields = getattr(
cls, "_clone_excluded_fields", CloneMixin._clone_excluded_fields
)
clone_o2o_fields = getattr(
cls, "_clone_o2o_fields", CloneMixin._clone_o2o_fields
)
clone_excluded_o2o_fields = getattr(
cls, "_clone_excluded_o2o_fields", CloneMixin._clone_excluded_o2o_fields
)
unique_duplicate_suffix = getattr(
cls, "UNIQUE_DUPLICATE_SUFFIX", CloneMixin.UNIQUE_DUPLICATE_SUFFIX
)
use_unique_duplicate_suffix = getattr(
cls,
"USE_UNIQUE_DUPLICATE_SUFFIX",
CloneMixin.USE_UNIQUE_DUPLICATE_SUFFIX,
)
max_unique_duplicate_query_attempts = getattr(
cls,
"MAX_UNIQUE_DUPLICATE_QUERY_ATTEMPTS",
CloneMixin.MAX_UNIQUE_DUPLICATE_QUERY_ATTEMPTS,
)
fields, unique_fields = get_fields_and_unique_fields_from_cls(
cls=cls,
force=force,
clone_fields=clone_fields,
clone_excluded_fields=clone_excluded_fields,
clone_o2o_fields=clone_o2o_fields,
clone_excluded_o2o_fields=clone_excluded_o2o_fields,
)
new_instance = cls()
for f in fields:
value = getattr(instance, f.attname, f.get_default())
if isinstance(f, (models.DateTimeField, models.DateField)):
if f.auto_now or f.auto_now_add:
f.pre_save(new_instance, add=True)
continue
if all(
[
not f.auto_created,
f.concrete,
f.editable,
f.name in unique_fields,
]
):
# Do not try to get unique value for enum type field
if isinstance(f, models.CharField) and not f.choices:
value = clean_value(value, unique_duplicate_suffix)
if use_unique_duplicate_suffix:
value = get_unique_value(
obj=instance,
fname=f.attname,
value=value,
transform=(slugify if isinstance(f, SlugField) else str),
suffix=unique_duplicate_suffix,
max_length=f.max_length,
max_attempts=max_unique_duplicate_query_attempts,
)
elif isinstance(f, models.OneToOneField) and not sub_clone:
sub_instance = getattr(instance, f.name, f.get_default())
if sub_instance is not None:
sub_instance = CloneMixin._create_copy_of_instance(
sub_instance,
force=True,
sub_clone=True,
)
sub_instance.save()
value = sub_instance.pk
setattr(new_instance, f.attname, value)
return new_instance
def __duplicate_o2o_fields(self, duplicate):
"""Duplicate one to one fields.
:param duplicate: The transient instance that should be duplicated.
:type duplicate: `django.db.models.Model`
:return: The duplicate instance with all the one to one fields duplicated.
"""
for f in self._meta.related_objects:
if f.one_to_one:
if any(
[
f.name in self._clone_o2o_fields
and f not in self._meta.concrete_fields,
self._clone_excluded_o2o_fields
and f.name not in self._clone_excluded_o2o_fields
and f not in self._meta.concrete_fields,
]
):
rel_object = getattr(self, f.name, None)
if rel_object:
new_rel_object = CloneMixin._create_copy_of_instance(
rel_object,
force=True,
sub_clone=True,
)
setattr(new_rel_object, f.remote_field.name, duplicate)
new_rel_object.save()
return duplicate
def __duplicate_o2m_fields(self, duplicate):
"""Duplicate one to many fields.
:param duplicate: The transient instance that should be duplicated.
:type duplicate: `django.db.models.Model`
:return: The duplicate instance with all the one to many fields duplicated.
"""
fields = set()
for f in self._meta.related_objects:
if f.one_to_many:
if any(
[
f.get_accessor_name() in self._clone_m2o_or_o2m_fields,
self._clone_excluded_m2o_or_o2m_fields
and f.get_accessor_name()
not in self._clone_excluded_m2o_or_o2m_fields,
]
):
fields.add(f)
# Clone one to many fields
for field in fields:
for item in getattr(self, field.get_accessor_name()).all():
try:
item.make_clone(attrs={field.remote_field.name: duplicate})
except IntegrityError:
item.make_clone(
attrs={field.remote_field.name: duplicate}, sub_clone=True
)
return duplicate
def __duplicate_m2o_fields(self, duplicate):
"""Duplicate many to one fields.
:param duplicate: The transient instance that should be duplicated.
:type duplicate: `django.db.models.Model`
:return: The duplicate instance with all the many to one fields duplicated.
"""
fields = set()
for f in self._meta.concrete_fields:
if f.many_to_one:
if any(
[
f.name in self._clone_m2o_or_o2m_fields,
self._clone_excluded_m2o_or_o2m_fields
and f.name not in self._clone_excluded_m2o_or_o2m_fields,
]
):
fields.add(f)
# Clone many to one fields
for field in fields:
item = getattr(self, field.name)
try:
item_clone = item.make_clone()
except IntegrityError:
item_clone = item.make_clone(sub_clone=True)
setattr(duplicate, field.name, item_clone)
return duplicate
def __duplicate_m2m_fields(self, duplicate):
"""Duplicate many to many fields.
:param duplicate: The transient instance that should be duplicated.
:type duplicate: `django.db.models.Model`
:return: The duplicate instance with all the many to many fields duplicated.
"""
fields = set()
for f in self._meta.many_to_many:
if any(
[
f.name in self._clone_m2m_fields,
self._clone_excluded_m2m_fields
and f.name not in self._clone_excluded_m2m_fields,
]
):
fields.add(f)
for f in self._meta.related_objects:
if f.many_to_many:
if any(
[
f.get_accessor_name() in self._clone_m2m_fields,
self._clone_excluded_m2m_fields
and f.get_accessor_name()
not in self._clone_excluded_m2m_fields,
]
):
fields.add(f)
# Clone many to many fields
for field in fields:
if hasattr(field, "field"):
# ManyToManyRel
field_name = field.field.m2m_reverse_field_name()
through = field.through
source = getattr(self, field.get_accessor_name())
destination = getattr(duplicate, field.get_accessor_name())
else:
through = field.remote_field.through
field_name = field.m2m_field_name()
source = getattr(self, field.attname)
destination = getattr(duplicate, field.attname)
if all(
[
through,
not through._meta.auto_created,
]
):
objs = through.objects.filter(**{field_name: self.pk})
for item in objs:
if hasattr(through, "make_clone"):
try:
item.make_clone(attrs={field_name: duplicate})
except IntegrityError:
item.make_clone(
attrs={field_name: duplicate}, sub_clone=True
)
else:
item.pk = None
setattr(item, field_name, duplicate)
item.save()
else:
destination.set(source.all())
return duplicate
| [
6738,
340,
861,
10141,
1330,
9585,
198,
6738,
19720,
1330,
7343,
11,
32233,
11,
360,
713,
198,
198,
6738,
26340,
1330,
26340,
198,
6738,
42625,
14208,
13,
7295,
13,
42116,
1330,
13047,
198,
6738,
42625,
14208,
13,
7295,
13,
1069,
11755,... | 1.946024 | 7,596 |
# coding: utf-8
# 2019/12/30 @ tongshiwei
from PIL import Image, ImageDraw, ImageFont
__all__ = ["character_glyph"]
| [
2,
19617,
25,
3384,
69,
12,
23,
198,
2,
13130,
14,
1065,
14,
1270,
2488,
10479,
44019,
42990,
198,
198,
6738,
350,
4146,
1330,
7412,
11,
7412,
25302,
11,
7412,
23252,
198,
198,
834,
439,
834,
796,
14631,
22769,
62,
10853,
746,
8973,... | 2.704545 | 44 |
#!/usr/bin/env python
import os.path
import sys
from setuptools import setup
# This is needed for versioneer to be importable when building with PEP 517.
# See <https://github.com/warner/python-versioneer/issues/193> and links
# therein for more information.
sys.path.append(os.path.dirname(__file__))
from _datalad_buildsupport.setup import BuildManPage # noqa: E402
import versioneer # noqa: E402
cmdclass = versioneer.get_cmdclass()
cmdclass.update(build_manpage=BuildManPage)
# Give setuptools a hint to complain if it's too old a version
# 30.3.0 allows us to put most metadata in setup.cfg
# Should match pyproject.toml
SETUP_REQUIRES = ["setuptools >= 30.3.0"]
# This enables setuptools to install wheel on-the-fly
SETUP_REQUIRES += ["wheel"] if "bdist_wheel" in sys.argv else []
if __name__ == "__main__":
setup(
name="datalad-fuse",
version=versioneer.get_version(),
cmdclass=cmdclass,
setup_requires=SETUP_REQUIRES,
)
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
11748,
28686,
13,
6978,
198,
11748,
25064,
198,
198,
6738,
900,
37623,
10141,
1330,
9058,
198,
198,
2,
770,
318,
2622,
329,
2196,
28153,
284,
307,
1330,
540,
618,
2615,
351,
350,
8905,... | 2.749296 | 355 |
#! /usr/bin/env python3
#
# Requires requests
#
import json
import requests
import sys
WEATHER_URL = "https://example.net/api.php?degree=C&location="
if __name__ == '__main__':
main()
| [
2,
0,
1220,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
2,
198,
2,
26848,
7007,
198,
2,
198,
198,
11748,
33918,
198,
11748,
7007,
198,
11748,
25064,
198,
198,
8845,
45226,
62,
21886,
796,
366,
5450,
1378,
20688,
13,
3262,
14,
15042,... | 2.694444 | 72 |
# -*- coding: UTF-8 -*-.
# Author Sazxt
# My Team : Black Coder crush
import os as _osx
from py_compile import compile as comp
INC = {
"onc":["cek","syntax"],
"nca":["ok","not"]
}
class bytecode:
"""
Memaparkan Pesan ke dalam bytcode
"""
class cek_ascii:
"""
Cek Systax ascii mungkin saja tidak bisa di encode oleh beberapa fungsi
"""
daftar_nick = (lambda : """
{ Black Coder Crush }
~ since 2020/2021 ~
──────────────────────────────────
[+] - 4K17
[+] - Dfv47
[+] - Mr.Tr3v!0n
[+] - Holilul Anwar
[+] - R.I.P XerXez7
[+] - Mr.Đ`HACK
[+] - kiiroi senko
[+] - Mr.g0y4n9
[+] - mie gelas
[+] - Tampansky ID
[+] - Mr. Karwek
[+] - Zhu Bai Lee
[+] - BL4CK DR460N
[+] - Mr. XsZ
[+] - EvCf1703
[+] - z34
[+] - Phantomblizt
[+] - Tn. Crash
[+] - CapthaCode404_
[+] - Gboy
──────────────────────────────────""")
about = (lambda x : \
"https://wa.me/+6283892081021" if x == "contact" else """
[+] Author : Sazxt
[+] Banner : Tr3v!0n
[-] Available Version Update 1.6
[+] Support only python2
{ Black Coder Crush }
──────────────────────────────────
< python source code obfuscator. only obfuscator >
< My Whatsapp : 0838-9208-1021 >
""")
#cek_ascii("uc.py").run() | [
2,
532,
9,
12,
19617,
25,
41002,
12,
23,
532,
9,
34507,
198,
2,
6434,
311,
1031,
742,
198,
2,
2011,
4816,
1058,
2619,
327,
12342,
19813,
198,
11748,
28686,
355,
4808,
418,
87,
198,
6738,
12972,
62,
5589,
576,
1330,
17632,
355,
552... | 2.18264 | 553 |
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 07 14:31:53 2019
@author: Dominic O'Kane
"""
from math import sqrt
from numba import njit, float64, int32
##########################################################################
@njit(float64(float64[:]), fastmath=True, cache=True)
def mean(x):
''' Calculate the arithmetic mean of a vector of numbers x. '''
n = len(x)
m = 0.0
for i in range(0, n):
m += x[i]
m = m / n
return m
##########################################################################
@njit(float64(float64[:]), fastmath=True, cache=True)
def stdev(x):
''' Calculate the standard deviation of a vector of numbers x. '''
n = len(x)
m = mean(x)
v = 0.0
for i in range(0, n):
v += (x[i] - m) * (x[i] - m)
sd = sqrt(v / n)
return sd
##########################################################################
@njit(float64(float64[:]), fastmath=True, cache=True)
def stderr(x):
''' Calculate the standard error estimate of a vector of numbers x. '''
n = len(x)
s = stdev(x)
serr = s / sqrt(n)
return serr
##########################################################################
@njit(float64(float64[:]), fastmath=True, cache=True)
def var(x):
''' Calculate the variance of a vector of numbers x. '''
s = stdev(x)
v = s * s
return v
##########################################################################
@njit(float64(float64[:], int32), fastmath=True, cache=True)
def moment(x, m):
''' Calculate the m-th moment of a vector of numbers x. '''
n = len(x)
s = 0.0
for i in range(0, n):
s += pow(x[i], m)
s = s / n
return s
##########################################################################
@njit(float64(float64[:], float64[:]), fastmath=True, cache=True)
def correlation(x1, x2):
''' Calculate the correlation between two series x1 and x2. '''
n1 = len(x1)
n2 = len(x2)
if n1 != n2:
raise ValueError("Vectors have different lengths")
m1 = mean(x1)
m2 = mean(x2)
sd1 = stdev(x1)
sd2 = stdev(x2)
prod = 0.0
for i in range(0, n1):
prod += x1[i] * x2[i]
prod /= n1
num = prod - m1 * m2
den = sd1 * sd2
corr = num / den
return corr
##########################################################################
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
37811,
198,
41972,
319,
3825,
3158,
8753,
1478,
25,
3132,
25,
4310,
13130,
198,
198,
31,
9800,
25... | 2.624588 | 911 |
# -*- coding=utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import textwrap
from functools import partial
import pytest
from pip_shims import (
FAVORITE_HASH,
USER_CACHE_DIR,
BadCommand,
BestVersionAlreadyInstalled,
CandidatePreferences,
CommandError,
ConfigOptionParser,
DistributionNotFound,
FormatControl,
FrozenRequirement,
InstallationError,
InstallCommand,
InstallRequirement,
Link,
LinkCollector,
PackageFinder,
PipError,
PreviousBuildDirError,
PyPI,
RequirementSet,
RequirementsFileParseError,
SafeFileCache,
SearchScope,
SelectionPreferences,
SourceDistribution,
TargetPython,
UninstallationError,
VcsSupport,
Wheel,
_strip_extras,
build_one,
build_wheel,
cmdoptions,
get_installed_distributions,
get_package_finder,
get_resolver,
global_tempdir_manager,
index_group,
install_req_from_editable,
install_req_from_line,
install_req_from_req_string,
is_archive_file,
is_file_url,
is_installable_dir,
make_abstract_dist,
make_option_group,
make_preparer,
parse_version,
path_to_url,
pip_version,
resolve,
shim_unpack,
url_to_path,
wheel_cache,
)
from pip_shims.compat import ensure_resolution_dirs, get_session
from pip_shims.utils import call_function_with_correct_args
STRING_TYPES = (str,)
if sys.version_info < (3, 0):
STRING_TYPES = (str, basestring)
@pytest.mark.parametrize(
"exceptionclass, baseclass",
[
(DistributionNotFound, Exception),
(PipError, Exception),
(InstallationError, Exception),
(UninstallationError, Exception),
(DistributionNotFound, Exception),
(RequirementsFileParseError, Exception),
(BestVersionAlreadyInstalled, Exception),
(BadCommand, Exception),
(CommandError, Exception),
(PreviousBuildDirError, Exception),
],
)
@pytest.mark.skipif(
parse_version(pip_version) >= parse_version("21.3"), reason="Removed in pip 21.3"
)
| [
2,
532,
9,
12,
19617,
28,
40477,
12,
23,
532,
9,
12,
198,
6738,
11593,
37443,
834,
1330,
4112,
62,
11748,
11,
3601,
62,
8818,
11,
28000,
1098,
62,
17201,
874,
198,
198,
11748,
28686,
198,
11748,
25064,
198,
11748,
2420,
37150,
198,
... | 2.479405 | 874 |
"""
The channel handler, accessed from this module as CHANNEL_HANDLER is a
singleton that handles the stored set of channels and how they are
represented against the cmdhandler.
If there is a channel named 'newbie', we want to be able to just write
newbie Hello!
For this to work, 'newbie', the name of the channel, must be
identified by the cmdhandler as a command name. The channelhandler
stores all channels as custom 'commands' that the cmdhandler can
import and look through.
> Warning - channel names take precedence over command names, so make
sure to not pick clashing channel names.
Unless deleting a channel you normally don't need to bother about the
channelhandler at all - the create_channel method handles the update.
To delete a channel cleanly, delete the channel object, then call
update() on the channelhandler. Or use Channel.objects.delete() which
does this for you.
"""
from django.conf import settings
from evennia.commands import cmdset, command
from evennia.utils.logger import tail_log_file
from evennia.utils.utils import class_from_module
from django.utils.translation import gettext as _
# we must late-import these since any overloads are likely to
# themselves be using these classes leading to a circular import.
_CHANNEL_HANDLER_CLASS = None
_CHANNEL_COMMAND_CLASS = None
_CHANNELDB = None
class ChannelCommand(command.Command):
"""
{channelkey} channel
{channeldesc}
Usage:
{lower_channelkey} <message>
{lower_channelkey}/history [start]
{lower_channelkey} off - mutes the channel
{lower_channelkey} on - unmutes the channel
Switch:
history: View 20 previous messages, either from the end or
from <start> number of messages from the end.
Example:
{lower_channelkey} Hello World!
{lower_channelkey}/history
{lower_channelkey}/history 30
"""
# ^note that channeldesc and lower_channelkey will be filled
# automatically by ChannelHandler
# this flag is what identifies this cmd as a channel cmd
# and branches off to the system send-to-channel command
# (which is customizable by admin)
is_channel = True
key = "general"
help_category = "Channel Names"
obj = None
arg_regex = r"\s.*?|/history.*?"
def parse(self):
"""
Simple parser
"""
# cmdhandler sends channame:msg here.
channelname, msg = self.args.split(":", 1)
self.history_start = None
if msg.startswith("/history"):
arg = msg[8:]
try:
self.history_start = int(arg) if arg else 0
except ValueError:
# if no valid number was given, ignore it
pass
self.args = (channelname.strip(), msg.strip())
def func(self):
"""
Create a new message and send it to channel, using
the already formatted input.
"""
global _CHANNELDB
if not _CHANNELDB:
from evennia.comms.models import ChannelDB as _CHANNELDB
channelkey, msg = self.args
caller = self.caller
if not msg:
self.msg(_("Say what?"))
return
channel = _CHANNELDB.objects.get_channel(channelkey)
if not channel:
self.msg(_("Channel '%s' not found.") % channelkey)
return
if not channel.has_connection(caller):
string = _("You are not connected to channel '%s'.")
self.msg(string % channelkey)
return
if not channel.access(caller, "send"):
string = _("You are not permitted to send to channel '%s'.")
self.msg(string % channelkey)
return
if msg == "on":
caller = caller if not hasattr(caller, "account") else caller.account
unmuted = channel.unmute(caller)
if unmuted:
self.msg("You start listening to %s." % channel)
return
self.msg("You were already listening to %s." % channel)
return
if msg == "off":
caller = caller if not hasattr(caller, "account") else caller.account
muted = channel.mute(caller)
if muted:
self.msg("You stop listening to %s." % channel)
return
self.msg("You were already not listening to %s." % channel)
return
if self.history_start is not None:
# Try to view history
log_file = channel.attributes.get("log_file", default="channel_%s.log" % channel.key)
tail_log_file(log_file, self.history_start, 20, callback=send_msg)
else:
caller = caller if not hasattr(caller, "account") else caller.account
if caller in channel.mutelist:
self.msg("You currently have %s muted." % channel)
return
channel.msg(msg, senders=self.caller, online=True)
def get_extra_info(self, caller, **kwargs):
"""
Let users know that this command is for communicating on a channel.
Args:
caller (TypedObject): A Character or Account who has entered an ambiguous command.
Returns:
A string with identifying information to disambiguate the object, conventionally with a preceding space.
"""
return _(" (channel)")
class ChannelHandler(object):
"""
The ChannelHandler manages all active in-game channels and
dynamically creates channel commands for users so that they can
just give the channel's key or alias to write to it. Whenever a
new channel is created in the database, the update() method on
this handler must be called to sync it with the database (this is
done automatically if creating the channel with
evennia.create_channel())
"""
def __init__(self):
"""
Initializes the channel handler's internal state.
"""
self._cached_channel_cmds = {}
self._cached_cmdsets = {}
self._cached_channels = {}
def __str__(self):
"""
Returns the string representation of the handler
"""
return ", ".join(str(cmd) for cmd in self._cached_channel_cmds)
def clear(self):
"""
Reset the cache storage.
"""
self._cached_channel_cmds = {}
self._cached_cmdsets = {}
self._cached_channels = {}
def add(self, channel):
"""
Add an individual channel to the handler. This is called
whenever a new channel is created.
Args:
channel (Channel): The channel to add.
Notes:
To remove a channel, simply delete the channel object and
run self.update on the handler. This should usually be
handled automatically by one of the deletion methos of
the Channel itself.
"""
global _CHANNEL_COMMAND_CLASS
if not _CHANNEL_COMMAND_CLASS:
_CHANNEL_COMMAND_CLASS = class_from_module(settings.CHANNEL_COMMAND_CLASS)
# map the channel to a searchable command
cmd = _CHANNEL_COMMAND_CLASS(
key=channel.key.strip().lower(),
aliases=channel.aliases.all(),
locks="cmd:all();%s" % channel.locks,
help_category="Channel names",
obj=channel,
is_channel=True,
)
# format the help entry
key = channel.key
cmd.__doc__ = cmd.__doc__.format(
channelkey=key,
lower_channelkey=key.strip().lower(),
channeldesc=channel.attributes.get("desc", default="").strip(),
)
self._cached_channel_cmds[channel] = cmd
self._cached_channels[key] = channel
self._cached_cmdsets = {}
add_channel = add # legacy alias
def remove(self, channel):
"""
Remove channel from channelhandler. This will also delete it.
Args:
channel (Channel): Channel to remove/delete.
"""
if channel.pk:
channel.delete()
self.update()
def update(self):
"""
Updates the handler completely, including removing old removed
Channel objects. This must be called after deleting a Channel.
"""
global _CHANNELDB
if not _CHANNELDB:
from evennia.comms.models import ChannelDB as _CHANNELDB
self._cached_channel_cmds = {}
self._cached_cmdsets = {}
self._cached_channels = {}
for channel in _CHANNELDB.objects.get_all_channels():
self.add(channel)
def get(self, channelname=None):
"""
Get a channel from the handler, or all channels
Args:
channelame (str, optional): Channel key, case insensitive.
Returns
channels (list): The matching channels in a list, or all
channels in the handler.
"""
if channelname:
channel = self._cached_channels.get(channelname.lower(), None)
return [channel] if channel else []
return list(self._cached_channels.values())
def get_cmdset(self, source_object):
"""
Retrieve cmdset for channels this source_object has
access to send to.
Args:
source_object (Object): An object subscribing to one
or more channels.
Returns:
cmdsets (list): The Channel-Cmdsets `source_object` has
access to.
"""
if source_object in self._cached_cmdsets:
return self._cached_cmdsets[source_object]
else:
# create a new cmdset holding all viable channels
chan_cmdset = None
chan_cmds = [
channelcmd
for channel, channelcmd in self._cached_channel_cmds.items()
if channel.subscriptions.has(source_object)
and channelcmd.access(source_object, "send")
]
if chan_cmds:
chan_cmdset = cmdset.CmdSet()
chan_cmdset.key = "ChannelCmdSet"
chan_cmdset.priority = 101
chan_cmdset.duplicates = True
for cmd in chan_cmds:
chan_cmdset.add(cmd)
self._cached_cmdsets[source_object] = chan_cmdset
return chan_cmdset
# set up the singleton
CHANNEL_HANDLER = class_from_module(settings.CHANNEL_HANDLER_CLASS)()
CHANNELHANDLER = CHANNEL_HANDLER # legacy
| [
37811,
198,
464,
6518,
21360,
11,
17535,
422,
428,
8265,
355,
5870,
22846,
3698,
62,
39,
6981,
39878,
318,
257,
198,
12215,
10565,
326,
17105,
262,
8574,
900,
286,
9619,
290,
703,
484,
389,
198,
33469,
1028,
262,
23991,
30281,
13,
198... | 2.376521 | 4,438 |
from django.conf import settings
from django.test import tag, TestCase
from django.test.client import Client
from django.urls import resolve, reverse
from django_otp.plugins.otp_totp.models import TOTPDevice
from aidants_connect_web.constants import JournalActionKeywords
from aidants_connect_web.models import Journal
from aidants_connect_web.tests.factories import (
AidantFactory,
AutorisationFactory,
MandatFactory,
OrganisationFactory,
UsagerFactory,
)
from aidants_connect_web.views import espace_aidant, usagers
@tag("usagers")
@tag("usagers")
@tag("usagers")
@tag("usagers")
@tag("responsable-structure")
@tag("aidants", "totp")
| [
6738,
42625,
14208,
13,
10414,
1330,
6460,
198,
6738,
42625,
14208,
13,
9288,
1330,
7621,
11,
6208,
20448,
198,
6738,
42625,
14208,
13,
9288,
13,
16366,
1330,
20985,
198,
6738,
42625,
14208,
13,
6371,
82,
1330,
10568,
11,
9575,
198,
198... | 2.969027 | 226 |
# ====================================================================
# This is old code intended for testing the attenuation algorithm.
# Not for use in beamline operations.
# ====================================================================
import logging
import h5py
import numpy as np
from ophyd import EpicsSignal, EpicsSignalRO
from ophyd.device import Component as Cpt
from ophyd.device import Device
from ophyd.device import FormattedComponent as FCpt
from ophyd.status import wait as status_wait
from pcdsdevices.inout import TwinCATInOutPositioner
logger = logging.getLogger(__name__)
class HXRFilter(Device):
"""
A single attenuation blade.
Parameters:
-----------
prefix : ``str``
filter_data : ``file``
index : ``int``
"""
_transmission = {} # TODO: this would be good to be dynamically set.
# It will be set by Satt using eV RBV callback
blade = FCpt(TwinCATInOutPositioner,
'{prefix}:MMS:{self.index_str}', kind='normal')
material = FCpt(EpicsSignalRO,
'{prefix}:FILTER:{self.index_str}:MATERIAL',
string=True, kind='normal')
thickness = FCpt(EpicsSignalRO,
'{prefix}:FILTER:{self.index_str}:THICKNESS',
kind='normal')
stuck = FCpt(EpicsSignal,
'{prefix}:FILTER:{self.index_str}:IS_STUCK',
kind='normal')
tab_whitelist = ['inserted', 'removed', 'insert', 'remove', 'transmission']
def load_data(self, h5file):
"""
Loads HDF5 physics data into tables.
"""
table = np.asarray(h5file['{}_table'.format(self.material.get())])
constants = np.asarray(
h5file['{}_constants'.format(self.material.get())])
eV_min = table[0, 0]
eV_max = table[-1, 0]
eV_inc = (table[-1, 0] - table[0, 0])/len(table[:, 0])
return constants, table, eV_min, eV_inc, eV_max
def _closest_eV(self, eV):
"""
Return the closest tabulated photon energy to ``eV``
and its lookup table index. If ``eV`` is outside
the range of the table, the function will return
either the lowest or highest value available.
"""
i = int(np.rint((eV - self._eV_min)/self._eV_inc))
if i < 0:
i = 0 # Use lowest tabulated value.
if i > self._data.shape[0]:
i = -1 # Use greatest tabulated value.
closest_eV = self._data[i, 0]
return closest_eV, i
def get_vals(self, eV):
"""
Return closest photon energy to ``eV`` and its transmission.
"""
close_eV, i = self._closest_eV(eV)
T = np.exp(-self._data[i, 2]*self.d)
return close_eV, T
def transmission(self, eV):
"""
Return beam transmission at photon energy closest ``eV``.
"""
return self.get_vals(eV)[1]
def inserted(self):
"""
True if filter is inserted ('IN').
"""
return self.blade.inserted
def removed(self):
"""
True if filter is removed ('OUT').
"""
return self.blade.removed
def is_stuck(self):
"""
True if filter has been set as stuck.
Unable to move. Hopefully retracted.
"""
return self.stuck.get()
def set_stuck(self):
"""
Flag the filter blade as stuck.
"""
return self.stuck.put("True")
class HXRSatt(Device):
"""
LCLS II Hard X-ray solid attenuator system.
"""
cbid = None
retries = 3
tab_component_names = True
tab_whitelist = []
eV = FCpt(EpicsSignalRO, "LCLS:HXR:BEAM:EV", kind='hinted')
locked = FCpt(EpicsSignalRO, '{prefix}:SYS:LOCKED',
kind='hinted') # lock the system (all motion)
unlock = FCpt(EpicsSignalRO, '{prefix}:SYS:UNLOCK',
kind='hinted') # unlock the system
set_mode = FCpt(EpicsSignal, '{prefix}:SYS:SET_MODE',
kind='hinted') # select best lowest or highest
T_actual = FCpt(EpicsSignal, '{prefix}:SYS:T_ACTUAL',
kind='hinted') # current transmission
T_high = FCpt(EpicsSignal, '{prefix}:SYS:T_HIGH',
kind='hinted') # closest achievable high
T_low = FCpt(EpicsSignal, '{prefix}:SYS:T_LOW',
kind='hinted') # closest achievable low
T_des = FCpt(EpicsSignal, '{prefix}:SYS:T_DESIRED',
kind='hinted')
T_3omega = FCpt(EpicsSignal, '{prefix}:SYS:T_3OMEGA',
kind='hinted')
run = FCpt(EpicsSignal, '{prefix}:SYS:RUN',
kind='hinted')
running = FCpt(EpicsSignal, '{prefix}:SYS:MOVING',
kind='hinted')
# mirror_in = FCpt(EpicsSignalRO, '{prefix}:SYS:T_VALID',
# kind='hinted')
# transmission_valid = FCpt(EpicsSignalRO, '{prefix}:SYS:T_VALID',
# kind='hinted')
# pv_config = FCpt(EpicsSignalRO, '{prefix}:SYS:CONFIG',
# kind='hinted') # not implemented
def _startup(self):
"""
Connect to PVs in order to generate
information about filter configurations
and photon energy.
"""
self.N_filters = len(self.filters)
self.config_arr = self._curr_config_arr()
self.config_table = self._load_configs()
self.curr_transmission()
self.eV.subscribe(self._eV_callback)
self.T_des.subscribe(self._T_des_callback)
self.run.subscribe(self._run_callback)
def blade(self, index):
"""
Returns the filter device at `index`.
"""
return self.filters.get(str(index))
def insert(self, index):
"""
Insert filter at `index` into the 'IN' position.
"""
inserted = self.blade(index).blade.insert()
self._curr_config_arr()
return inserted
def remove(self, index):
"""
Retract filter at `index` into the 'OUT' position.
"""
removed = self.blade(index).blade.remove()
self._curr_config_arr()
return removed
def config(self):
"""
Return a dictionary of filter states indexed
by filter number.
"""
config_dict = {}
for f in self.filters:
blade = self.filters.get(f)
if blade.inserted():
config_dict.update({blade.index: 'IN'})
if blade.removed():
config_dict.update({blade.index: 'OUT'})
if not blade.inserted() and not blade.removed():
config_dict.update({blade.index: 'UKNOWN'})
if blade.is_stuck():
config_dict.update({blade.index: 'STUCK'})
return config_dict
def _load_configs(self):
"""
Load the HDF5 table of possible configurations.
"""
self.config_table = self.configs['configurations']
return self.config_table
# Need a callback on every blade to grab its state and update config...
def _curr_config_arr(self):
"""
Return the current configuration of filter states
as an array.
"""
config = np.ones(self.N_filters)
for i in range(self.N_filters):
if self.blade(i+1).inserted():
config[i] = 1
else:
config[i] = np.nan
self.config_arr = config
return config
def _all_transmissions(self, eV):
"""
Calculates and returns transmission at
photon energy ``eV`` for all non-stuck filters.
"""
T_arr = np.ones(self.N_filters)
for i in range(self.N_filters):
if self.blade(i+1).is_stuck():
T_arr = np.nan
else:
T_arr[i] = self.blade(i+1).transmission(eV)
return T_arr
def curr_transmission(self, eV=None):
"""
Calculates and returns transmission at
photon energy ``eV`` through current filter configuration.
"""
print("updating transmission")
if not eV:
eV = self.eV.get()
self.transmission = np.nanprod(
self._all_transmissions(eV)*self._curr_config_arr())
self.T_actual.put(self.transmission)
self.get_3omega_transmission()
return self.transmission
def _eV_callback(self, value=None, **kwargs):
"""
To be run every time the ``eV`` signal changes.
"""
self.transmission = self.curr_transmission(self.eV.get())
def _T_des_callback(self, value=None, **kwargs):
"""
To be run every time the ``T_des`` signal changes.
"""
config_bestLow, config_bestHigh, T_bestLow, T_bestHigh = self._find_configs(self.eV.get(),
T_des=self.T_des.get())
self.T_high.put(T_bestHigh)
self.T_low.put(T_bestLow)
def _run_callback(self, old_value=None, value=None, **kwargs):
"""
To be run every time the ``run`` sgianl changes.
"""
if old_value == 0 and self.running.get() == 0 and value == 1:
print("run value changed to 1, attenuating")
self.attenuate()
for i in range(self.retries):
try:
print("returning run to 0")
self.run.put(0)
except Exception:
print("could not set run to 0")
pass
def _find_configs(self, eV, T_des=None):
"""
Find the optimal configurations for attaining
desired transmission ``T_des`` at photon
energy ``eV``.
Returns configurations which yield closest
highest and lowest transmissions and their
transmission values.
"""
if not T_des:
T_des = self.T_des.get()
T_set = self._all_transmissions(eV)
T_table = np.nanprod(T_set*self.config_table,
axis=1)
T_config_table = np.asarray(sorted(np.transpose([T_table[:],
range(len(self.config_table))]),
key=lambda x: x[0]))
i = np.argmin(np.abs(T_config_table[:, 0]-T_des))
closest = self.config_table[T_config_table[i, 1]]
T_closest = np.nanprod(T_set*closest)
if T_closest == T_des:
config_bestHigh = config_bestLow = closest
T_bestHigh = T_bestLow = T_closest
if T_closest < T_des:
config_bestHigh = self.config_table[T_config_table[i+1, 1]]
config_bestLow = closest
T_bestHigh = np.nanprod(T_set*config_bestHigh)
T_bestLow = T_closest
if T_closest > T_des:
config_bestHigh = closest
config_bestLow = self.config_table[T_config_table[i-1, 1]]
T_bestHigh = T_closest
T_bestLow = np.nanprod(T_set*config_bestLow)
return config_bestLow, config_bestHigh, T_bestLow, T_bestHigh
def get_3omega_transmission(self):
"""
Calculates 3rd harmonic transmission through the current
configuration and sets the ``T_3omega`` attribute.
"""
return self.T_3omega.put(np.nanprod(
self._all_transmissions(3*self.eV.get())*self._curr_config_arr()))
def transmission_desired(self, T_des):
"""
Set the desired transmission.
"""
config_bestLow, config_bestHigh, T_bestLow, T_bestHigh = self._find_configs(
self.eV.get())
self.T_low.put(T_bestLow)
self.T_high.put(T_bestHigh)
return self.T_des.put(T_des)
def attenuate(self, timeout=None):
"""
Will execute the filter selection procedure and
move the necessary filters into the beam in order
to achieve the closest transmission to ``T_des``.
"""
print("setting running to high")
self.running.put(1)
config_bestLow, config_bestHigh, T_bestLow, T_bestHigh = self._find_configs(
self.eV.get())
if self.set_mode.get() == 0:
config = config_bestLow
T = T_bestLow
if self.set_mode.get() == 1:
config = config_bestHigh
T = T_bestHigh
to_insert = list()
to_remove = list()
for i in range(len(self.config_arr)):
blade = self.blade(i+1)
if not blade.is_stuck() and blade.removed() and config[i] == 1:
to_insert.append(i+1)
if not blade.is_stuck() and blade.inserted() and np.isnan(config[i]):
to_remove.append(i+1)
insert_st = list()
in_status = None
remove_st = list()
out_status = None
# logger.debug("Inserting blades {}".format(to_insert))
print("inserting blades")
for f in to_insert:
insert_st.append(self.insert(f))
for st in insert_st:
print("waiting on insert status", st)
status_wait(st, timeout=timeout)
# if len(insert_st) >= 1:
# in_status = insert_st.pop(0)
# for st in insert_st:
# in_status = in_status & st
logger.debug("Waiting for motion to finish...")
# status_wait(in_status, timeout=timeout)
if in_status:
inserted = in_status
else:
inserted = True # Not correct, this should be a status object.
# TODO: if any inserted motion fails then do not remove any filters!
# logger.debug("Removing blades {}".format(to_remove))
print("removing blades")
for f in to_remove:
remove_st.append(self.remove(f))
if len(remove_st) >= 1:
out_status = remove_st.pop(0)
for st in remove_st:
out_status = out_status & st
logger.debug("Waiting for motion to finish...")
status_wait(out_status, timeout=timeout)
if out_status:
removed = out_status
else:
removed = True
self._curr_config_arr()
self.curr_transmission()
print("resetting running to 0")
self.running.put(0)
# return inserted & removed
| [
2,
38093,
18604,
198,
2,
220,
770,
318,
1468,
2438,
5292,
329,
4856,
262,
31919,
2288,
11862,
13,
198,
2,
220,
1892,
329,
779,
287,
15584,
1370,
4560,
13,
198,
2,
38093,
18604,
198,
198,
11748,
18931,
198,
198,
11748,
289,
20,
9078,... | 2.074229 | 6,911 |
import os
import platform
import pygments, markdown
from flask import render_template_string
from flask_flatpages import FlatPages, pygmented_markdown, pygments_style_defs
from app import debug
# setup articles, this is where you can do code highlight templates and stuff.
BLOG_NAME = "blog name"
APP_URL = get_url()
SECRET_KEY = "GOOD_SECRET_KEY"
TARGET_MAILBOX = "where_you_want@emails_to_go"
GEOIPIFY_API_KEY = "GEOIPKEY"
FLATPAGES_EXTENSION = ".md"
FLATPAGES_HTML_RENDERER = the_markdown
FLATPAGES_MARKDOWN_EXTENSIONS = [
"codehilite",
"tables",
"fenced_code",
"md_in_html",
"wikilinks",
"smarty",
]
MAIL_SERVER = "smtp.sendgrid.net"
MAIL_PORT = 587
MAIL_USE_TLS = True
MAIL_USE_SSL = False
MAIL_DEBUG = "1"
MAIL_USERNAME = "apikey"
MAIL_PASSWORD = "your_sendgrid_password"
MAIL_DEFAULT_SENDER = "your_default_sender"
MAIL_MAX_EMAILS = "None"
MAIL_ASCII_ATTACHMENTS = "False"
RECAPTCHA_PUBLIC_KEY = ""
RECAPTCHA_PRIVATE_KEY = ""
| [
11748,
28686,
198,
11748,
3859,
198,
11748,
12972,
11726,
11,
1317,
2902,
198,
6738,
42903,
1330,
8543,
62,
28243,
62,
8841,
198,
6738,
42903,
62,
38568,
31126,
1330,
21939,
47798,
11,
12972,
5154,
276,
62,
4102,
2902,
11,
12972,
11726,
... | 2.40796 | 402 |
#!/usr/bin/env python3
# encoding=utf8
from mylib.easy.text import regex_find
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
2,
21004,
28,
40477,
23,
198,
198,
6738,
616,
8019,
13,
38171,
13,
5239,
1330,
40364,
62,
19796,
628,
198
] | 2.7 | 30 |
"""Settings for dev environments (overrides base settings)."""
import os
from .base import * # noqa: F401, F403 # pylint: disable=unused-wildcard-import, wildcard-import
ALLOWED_HOSTS = ['*']
SECRET_KEY = '-sg0o=f6(j3!4u6^86!j@0&l^3clslh-#f@02d2^p_4vy0ma0y'
if 'TRAVIS' in os.environ:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'travisci',
'USER': 'postgres',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '',
}
}
USE_TZ = False
MEDIA_ROOT = os.path.join(BASE_DIR, 'test_media') # noqa
try:
from .local import * # # noqa: F401, F403 # pylint: disable=unused-wildcard-import, wildcard-import
except ImportError:
pass
| [
37811,
26232,
329,
1614,
12493,
357,
2502,
81,
1460,
2779,
6460,
21387,
15931,
198,
11748,
28686,
198,
6738,
764,
8692,
1330,
1635,
220,
1303,
645,
20402,
25,
376,
21844,
11,
376,
31552,
1303,
279,
2645,
600,
25,
15560,
28,
403,
1484,
... | 2.005195 | 385 |
# -*- coding: utf-8 -*-
#
# Teak for Adobe AIR documentation build configuration file, created by
# sphinx-quickstart on Thu Aug 31 12:44:59 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
import os, re, subprocess, errno
from functools import cmp_to_key
read_the_docs_build = os.environ.get('READTHEDOCS', None) == 'True'
import importlib
import sys
sys.path.append('.')
docs_common = importlib.import_module('teak-docs-common')
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = []
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Teak for Adobe AIR'
copyright = u'2017-2019, GoCarrot Inc'
author = u'Teak'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# x.y.z[-short-sha]
git_version = subprocess.check_output(['git', 'describe', '--tags', '--always'])
# The short X.Y version.
version = str(git_version.split(b'-')[0], 'utf-8')
# The full version, including alpha/beta/rc tags.
release = str(git_version, 'utf-8')
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', 'versions',
'ios/index.rst', 'ios/versions', 'android/index.rst', 'android/versions']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
import sphinx_rtd_theme
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# This is required for the alabaster theme
# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars
html_sidebars = {
'**': [
'about.html',
'navigation.html',
'relations.html', # needs 'show_related': True theme option to display
'searchbox.html',
'donate.html',
]
}
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'TeakforAdobeAIRdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'TeakforAdobeAIR.tex', u'Teak for Adobe AIR Documentation',
u'GoCarrot Inc', 'manual'),
]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'teakforadobeair', u'Teak for Adobe AIR Documentation',
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'TeakforAdobeAIR', u'Teak for Adobe AIR Documentation',
author, 'TeakforAdobeAIR', 'One line description of project.',
'Miscellaneous'),
]
# -- Sidebar --------------------------------------------------------------
docs_common.generate_sidebar(globals(), 'air', './_sidebar.rst.inc')
####
# Global include
with open('global.irst', 'r') as f:
rst_prolog = f.read()
#####
# Setup
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
2,
198,
2,
1665,
461,
329,
21771,
31600,
10314,
1382,
8398,
2393,
11,
2727,
416,
198,
2,
599,
20079,
87,
12,
24209,
9688,
319,
26223,
2447,
3261,
1105,
25,
2598,
25,
... | 3.24686 | 1,831 |
"""
test_credit_cards.py
Copyright 2011 Andres Riancho
This file is part of w3af, http://w3af.org/ .
w3af is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.
w3af is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with w3af; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
import os
import unittest
import w3af.core.data.kb.knowledge_base as kb
from w3af import ROOT_PATH
from w3af.plugins.grep.credit_cards import credit_cards
from w3af.core.data.dc.headers import Headers
from w3af.core.data.url.HTTPResponse import HTTPResponse
from w3af.core.data.request.fuzzable_request import FuzzableRequest
from w3af.core.data.parsers.doc.url import URL
| [
37811,
198,
9288,
62,
43082,
62,
27761,
13,
9078,
198,
198,
15269,
2813,
843,
411,
371,
666,
6679,
198,
198,
1212,
2393,
318,
636,
286,
266,
18,
1878,
11,
2638,
1378,
86,
18,
1878,
13,
2398,
14,
764,
198,
198,
86,
18,
1878,
318,
... | 3.276276 | 333 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
https://en.wikipedia.org/wiki/Jones_calculus
"""
import numpy as np
import math
import cmath
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
__author__ = 'Christian Noelleke (https://github.com/Kricki)'
class JonesMatrix(np.matrix):
"""
Base class for a Jones matrix.
Parameters
==========
:param complex a, b, c, d: The elements of the 2x2 matrix or 2x2 matrix ([[a, b], [c, d]])
"""
def rotate(self, angle):
"""
Rotate the optical element (described by the JonesMatrix) around the angle "angle".
:param float angle: Rotation angle in rad
:return:
"""
rot_jm = JonesMatrix(rotation_matrix(-angle)*self*rotation_matrix(angle))
self[0, 0] = rot_jm[0, 0]
self[0, 1] = rot_jm[0, 1]
self[1, 0] = rot_jm[1, 0]
self[1, 1] = rot_jm[1, 1]
class JonesVector(np.matrix):
"""
Base class for a Jones vector.
Parameters
==========
:param float x, y: Optional. Elements of the 2x1 matrix or 2x1 matrix ([[x], [y]]).
:param str preset: Optional. Jones vector is set to a pre-defined state, that can be one of the following:
'H': Horizontal, 'V': Vertical, 'D': Diagonal, 'A': Anti-diagonal,
'R': Right-hand circular, 'L': Left-hand circular.
If "preset" is given, then x,y, normalize are ignored.
:param bool normalize: If True (default) power of vector is normalized to 1.
"""
@property
def x(self):
"""
:return: The x-component of the Jones vector
"""
return self[0, 0]
@property
def y(self):
"""
:return: The y-component of the Jones vector
"""
return self[1, 0]
@property
def power(self):
"""
:return: The "power" of the vector, i.e. the sqrt of the sum of the squares of x and y.
"""
return math.sqrt(abs(self.x)**2 + abs(self.y)**2)
@property
def x_angle(self):
"""
Return the angle of the polarization ellipse relative to the x-axis
Reference: Saleh, Bahaa EA, and Malvin Carl Teich. "Fundamentals of Photonics." 2nd edition (2007)
:return: The angle (in rad) of the polarization vector relative to the x-axis.
"""
# Can probably be simplified...
r = abs(self.y)/abs(self.x)
dphase = cmath.phase(self.y)-cmath.phase(self.x)
if self.x > 0 and self.y >= 0:
if self.x > self.y:
angle = 1/2*(math.atan(2*r/(1-r**2)*math.cos(dphase)))
else:
angle = 1/2*(np.arctan(2*r/(1-r**2)*math.cos(dphase))) + math.pi/2
elif self.x < 0 < self.y:
if abs(self.x) < self.y:
angle = 1/2*(math.atan(2*r/(1-r**2)*math.cos(dphase))) + math.pi/2
else:
angle = 1/2*(math.atan(2*r/(1-r**2)*math.cos(dphase))) + math.pi
elif self.x < 0 and self.y < 0:
if abs(self.x) > abs(self.y):
angle = 1/2*(math.atan(2*r/(1-r**2)*math.cos(dphase)))
else:
angle = 1/2*(math.atan(2*r/(1-r**2)*math.cos(dphase))) + math.pi/2
else:
if self.x < abs(self.y):
angle = 1/2*(math.atan(2*r/(1-r**2)*math.cos(dphase))) + math.pi/2
else:
angle = 1/2*(math.atan(2*r/(1-r**2)*math.cos(dphase))) + math.pi
return angle
@property
def ellipticity(self):
"""
Return the ellipticity of the polarization state.
The ellipticity is defined as the ratio between the semi-minor and the semi-major axis of the polarization
ellipses.
Reference: Saleh, Bahaa EA, and Malvin Carl Teich. "Fundamentals of Photonics." 2nd edition (2007)
:return float: Ellipticity
"""
r = abs(self.y) / abs(self.x)
dphase = cmath.phase(self.y) - cmath.phase(self.x)
chi = 1/2*(math.asin(2*r/(1+r**2)*math.sin(dphase)))
return math.tan(chi)
def normalize(self):
"""
Normalize the Jones vector to a power of 1.
"""
norm = self.power
self[0, 0] = self[0, 0]/norm
self[1, 0] = self[1, 0]/norm
def plot(self):
"""
Plot the polarization ellipse.
"""
dphase = cmath.phase(self.y) - cmath.phase(self.x)
x_angle = self.x_angle
# semi-minor and semi-major axis of ellipse
# see https://en.wikipedia.org/wiki/Elliptical_polarization
a = math.sqrt((1+math.sqrt(1-math.sin(2*x_angle)**2*math.sin(dphase)**2))/2)
b = math.sqrt((1-math.sqrt(1-math.sin(2*x_angle)**2*math.sin(dphase)**2))/2)
el = Ellipse(xy=(0, 0), width=a, height=b, angle=math.degrees(x_angle), edgecolor='r', fc='None', lw=1)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.add_patch(el)
ax.set_xlim(-0.5, 0.5)
ax.set_ylim(-0.5, 0.5)
ax.grid(color='black')
plt.show()
if __name__ == '__main__':
jv1 = JonesVector(preset='H')
hwp = HalfWavePlate(math.radians(22.5))
qwp = QuarterWavePlate(math.radians(45))
jv1 = qwp*jv1
jv1.plot()
| [
2,
48443,
14629,
14,
8800,
14,
29412,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
37811,
198,
5450,
1378,
268,
13,
31266,
13,
2398,
14,
15466,
14,
25784,
62,
9948,
17576,
198,
37811,
198,
198,
11748,
2... | 2.028266 | 2,618 |
from pydantic import BaseModel
| [
6738,
279,
5173,
5109,
1330,
7308,
17633,
628
] | 4 | 8 |
import os
import setuptools
here = os.path.abspath(os.path.dirname(__file__))
info = {}
with open(os.path.join(here, 'enmon', '__info__.py'), 'r') as f:
exec(f.read(), info)
with open('requirements.txt', 'r') as f:
requirements = f.read()
with open('README.md', 'r') as f:
readme = f.read()
setuptools.setup(
name=info['TITLE'],
version=info['VERSION'],
author=info['AUTHOR'],
author_email=info['EMAIL'],
description=info['DESCRIPTION'],
long_description=readme,
long_description_content_type='text/markdown',
url=info['URL'],
license=info['LICENSE'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: POSIX :: Linux'
'Operating System :: MacOS',
'Programming Language :: Python :: 3',
'Topic :: Utilities'
],
keywords='hardwario iot mqtt bridge sensor cli temperature humidity pressure altitude illuminance',
platforms='any',
packages=setuptools.find_packages(),
install_requires=requirements,
entry_points={
'console_scripts': [
'{}={}:main'.format(info['TITLE'], info['TITLE'])
]
}
)
| [
11748,
28686,
198,
11748,
900,
37623,
10141,
198,
198,
1456,
796,
28686,
13,
6978,
13,
397,
2777,
776,
7,
418,
13,
6978,
13,
15908,
3672,
7,
834,
7753,
834,
4008,
198,
198,
10951,
796,
23884,
198,
4480,
1280,
7,
418,
13,
6978,
13,
... | 2.482375 | 539 |
import datetime
from django.urls import reverse
from django_webtest import WebTest
from employees.views import parse_date
from employees.models import UserData
from test_common import ProtectedViewTestCase
| [
11748,
4818,
8079,
198,
198,
6738,
42625,
14208,
13,
6371,
82,
1330,
9575,
198,
198,
6738,
42625,
14208,
62,
12384,
9288,
1330,
5313,
14402,
198,
198,
6738,
4409,
13,
33571,
1330,
21136,
62,
4475,
198,
6738,
4409,
13,
27530,
1330,
11787... | 3.836364 | 55 |
import os
p, f = os.path.split(__file__)
root_p = os.path.normpath(p)
from HSTB.kluster import __version__ as kluster_version
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
# -- Project information -----------------------------------------------------
project = 'kluster'
copyright = '2020, Eric Younkin'
author = 'Eric Younkin'
# The full version, including alpha/beta/rc tags
release = kluster_version
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
# m2r to translate the readme.md to rst
extensions = ['sphinx_automodapi.automodapi',
'sphinx.ext.napoleon',
'sphinx.ext.graphviz',
'sphinx_autodoc_typehints'
]
numpydoc_show_class_members = False
# we disabled class inheritance diagrams, so this won't even be used
graphviz_dot = os.path.normpath(os.path.join(root_p, r"..\..\..\..\..\..\envs\Pydro38_Test\Library\bin\graphviz\dot.exe"))
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = []
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
| [
11748,
28686,
198,
79,
11,
277,
796,
28686,
13,
6978,
13,
35312,
7,
834,
7753,
834,
8,
198,
15763,
62,
79,
796,
28686,
13,
6978,
13,
27237,
6978,
7,
79,
8,
198,
198,
6738,
367,
2257,
33,
13,
41582,
5819,
1330,
11593,
9641,
834,
... | 3.331978 | 738 |
from flask import request
from app.api.responses import Responses
from app.api.routes.models.office import offices
| [
6738,
42903,
1330,
2581,
198,
198,
6738,
598,
13,
15042,
13,
16733,
274,
1330,
20549,
274,
198,
6738,
598,
13,
15042,
13,
81,
448,
274,
13,
27530,
13,
31810,
1330,
9730,
628
] | 3.65625 | 32 |
import setuptools
from src.version import VERSION
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="fce-ipmi",
version=VERSION,
author="Przemyslaw Hausman",
description="Wrapper for various IPMI-related utilities",
license="MIT",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/phausman/fce-ipmi",
packages=setuptools.find_packages("src"),
package_dir={"": "src"},
py_modules=["app", "main", "messages", "utils", "version"],
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: Linux",
],
python_requires=">=3.6.9",
entry_points={
"console_scripts": [
"fce-ipmi=main:cli",
],
},
setup_requires=["wheel"],
install_requires=["click>=7.1.2", "PyYAML>=5.3.1", "colorlog>=4.6.2"],
)
| [
11748,
900,
37623,
10141,
198,
198,
6738,
12351,
13,
9641,
1330,
44156,
2849,
198,
198,
4480,
1280,
7203,
15675,
11682,
13,
9132,
1600,
366,
81,
4943,
355,
277,
71,
25,
198,
220,
220,
220,
890,
62,
11213,
796,
277,
71,
13,
961,
3419... | 2.372549 | 408 |
#!/usr/bin/env python
from Tkinter import Button, END, Label, W
from Pmw import initialise, ComboBox, Counter
top = initialise()
lb = Label(top,
text='Animals (in pairs; min: pair, max: dozen)')
lb.pack()
ct = Counter(top, labelpos=W, label_text='Number:',
datatype='integer', entryfield_value=2,
increment=2, entryfield_validate={'validator':
'integer', 'min': 2, 'max': 12})
ct.pack()
cb = ComboBox(top, labelpos=W, label_text='Type:')
for animal in ('dog', 'cat', 'hamster', 'python'):
cb.insert(END, animal)
cb.pack()
qb = Button(top, text='QUIT',
command=top.quit, bg='red', fg='white')
qb.pack()
top.mainloop()
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
201,
198,
201,
198,
6738,
309,
74,
3849,
1330,
20969,
11,
23578,
11,
36052,
11,
370,
201,
198,
6738,
350,
76,
86,
1330,
4238,
786,
11,
34257,
14253,
11,
15034,
201,
198,
201,
198,
4852,
... | 2.368421 | 285 |
from django.contrib import admin
from bike.models import Version,Brand,Category,Bike,Address
from message.models import Message
# Register your models here.
#单车通过验证代码
bike_verify.short_description = "单车通过验证"
#单车未通过验证
bike_fail.short_description = "单车未通过验证"
@admin.register(Address)
@admin.register(Bike)
@admin.register(Category)
@admin.register(Version)
@admin.register(Brand)
| [
6738,
42625,
14208,
13,
3642,
822,
1330,
13169,
198,
6738,
7161,
13,
27530,
1330,
10628,
11,
38416,
11,
27313,
11,
33,
522,
11,
20231,
198,
6738,
3275,
13,
27530,
1330,
16000,
198,
2,
17296,
534,
4981,
994,
13,
198,
2,
39355,
243,
1... | 2.195402 | 174 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
urlfetch
~~~~~~~~~~
An easy to use HTTP client based on httplib.
:copyright: (c) 2011-2013 by Yue Du.
:license: BSD 2-clause License, see LICENSE for more details.
'''
__version__ = '0.5.3.1'
__author__ = 'Yue Du <ifduyue@gmail.com>'
__url__ = 'https://github.com/ifduyue/urlfetch'
__license__ = 'BSD 2-Clause License'
import os, sys, base64, codecs, uuid, stat
from functools import partial, wraps
from io import BytesIO
import time
try:
import simplejson as json
except ImportError:
import json
if sys.version_info >= (3, 0):
py3k = True
unicode = str
else:
py3k = False
if py3k:
from http.client import HTTPConnection, HTTPSConnection
from urllib.parse import urlencode
import urllib.parse as urlparse
import http.cookies as Cookie
basestring = (str, bytes)
b = lambda s: s.encode('latin-1')
u = lambda s: s
else:
from httplib import HTTPConnection, HTTPSConnection
from urllib import urlencode
import urlparse
import Cookie
b = lambda s: s
u = lambda s: unicode(s, 'unicode_escape')
__all__ = ('request', 'fetch', 'Session',
'get', 'head', 'put', 'post', 'delete', 'options', 'trace', 'patch'
'UrlfetchException')
class cached_property(object):
''' A property that is only computed once per instance and then replaces
itself with an ordinary attribute. Deleting the attribute resets the
property. '''
###############################################################################
# Core Methods and Classes #####################################################
###############################################################################
class Response(object):
'''A Response object.
>>> import urlfetch
>>> response = urlfetch.get("http://docs.python.org/")
>>> r.total_time
0.033042049407959
>>> response.status, response.reason, response.version
(200, 'OK', 10)
>>> type(response.body), len(response.body)
(<type 'str'>, 8719)
>>> type(response.text), len(response.text)
(<type 'unicode'>, 8719)
>>> response.getheader('server')
'Apache/2.2.16 (Debian)'
>>> response.getheaders()
[
('content-length', '8719'),
('x-cache', 'MISS from localhost'),
('accept-ranges', 'bytes'),
('vary', 'Accept-Encoding'),
('server', 'Apache/2.2.16 (Debian)'),
('last-modified', 'Tue, 26 Jun 2012 19:23:18 GMT'),
('connection', 'close'),
('etag', '"13cc5e4-220f-4c36507ded580"'),
('date', 'Wed, 27 Jun 2012 06:50:30 GMT'),
('content-type', 'text/html'),
('x-cache-lookup', 'MISS from localhost:8080')
]
>>> response.headers
{
'content-length': '8719',
'x-cache': 'MISS from localhost',
'accept-ranges': 'bytes',
'vary': 'Accept-Encoding',
'server': 'Apache/2.2.16 (Debian)',
'last-modified': 'Tue, 26 Jun 2012 19:23:18 GMT',
'connection': 'close',
'etag': '"13cc5e4-220f-4c36507ded580"',
'date': 'Wed, 27 Jun 2012 06:50:30 GMT',
'content-type': 'text/html',
'x-cache-lookup': 'MISS from localhost:8080'
}
'''
def read(self, chunk_size=8192):
''' read content (for streaming and large files)
chunk_size: size of chunk, default: 8192
'''
chunk = self._r.read(chunk_size)
return chunk
next = __next__
@classmethod
def from_httplib(cls, r, **kwargs):
'''Generate a :class:`~urlfetch.Response` object from a httplib
response object.
'''
return cls(r, **kwargs)
@cached_property
def body(self):
'''Response body.'''
content = b("")
for chunk in self:
content += chunk
if self.length_limit and len(content) > self.length_limit:
raise UrlfetchException("Content length is more than %d "
"bytes" % self.length_limit)
# decode content if encoded
encoding = self.headers.get('content-encoding', None)
decoder = self.__CONTENT_DECODERS.get(encoding)
if encoding and not decoder:
raise UrlfetchException('Unknown encoding: %s' % encoding)
if decoder:
content = decoder(content)
return content
# compatible with requests
#: An alias of :attr:`body`.
@cached_property
@cached_property
def text(self):
'''Response body in unicode.'''
return mb_code(self.content)
@cached_property
def json(self):
'''Load response body as json'''
return json.loads(self.text)
@cached_property
def headers(self):
'''Response headers.
Response headers is a dict with all keys in lower case.
>>> import urlfetch
>>> response = urlfetch.get("http://docs.python.org/")
>>> response.headers
{
'content-length': '8719',
'x-cache': 'MISS from localhost',
'accept-ranges': 'bytes',
'vary': 'Accept-Encoding',
'server': 'Apache/2.2.16 (Debian)',
'last-modified': 'Tue, 26 Jun 2012 19:23:18 GMT',
'connection': 'close',
'etag': '"13cc5e4-220f-4c36507ded580"',
'date': 'Wed, 27 Jun 2012 06:50:30 GMT',
'content-type': 'text/html',
'x-cache-lookup': 'MISS from localhost:8080'
}
'''
return dict((k.lower(), v) for k, v in self.getheaders())
@cached_property
def cookies(self):
'''Cookies in dict'''
c = Cookie.SimpleCookie(self.getheader('set-cookie'))
sc = [(i.key, i.value) for i in c.values()]
return dict(sc)
@cached_property
def cookiestring(self):
'''Cookie string'''
cookies = self.cookies
return '; '.join(['%s=%s' % (k, v) for k, v in cookies.items()])
@cached_property
def raw_header(self):
'''Raw response header.'''
if self.version == 11:
version = 'HTTP/1.1'
elif self.version == 10:
version = 'HTTP/1.0'
elif self.version == 9:
version = 'HTTP/0.9'
status = self.status
reason = self.reason
return b'\r\n'.join([b'%s %s %s' % (version, status, reason)] + [b'%s: %s' % (k, v) for k, v in self.getheaders()])
@cached_property
def close(self):
'''Close the connection'''
self._r.close()
class Session(object):
'''A session object.
:class:`urlfetch.Session` can hold common headers and cookies.
Every request issued by a :class:`urlfetch.Session` object will bring u
these headers and cookies.
:class:`urlfetch.Session` plays a role in handling cookies, just like a
cookiejar.
:param headers: init headers
:type headers: dict, optional
:param cookies: init cookies
:type cookies: dict, optional
:param auth: (username, password) for basic authentication
:type auth: tuple, optional
'''
def __init__(self, headers={}, cookies={}, auth=None):
'''init a :class:`~urlfetch.Session` object
'''
self._headers = {}
self._cookies = cookies.copy()
for k, v in headers.items():
self._headers[k.title()] = v
if auth is not None and isinstance(auth, (list, tuple)):
auth = '%s:%s' % tuple(auth)
auth = base64.b64encode(auth.encode('utf-8'))
self._headers['Authorization'] = 'Basic ' + auth.decode('utf-8')
def putheader(self, header, value):
'''Add an header to default headers'''
self._headers[header.title()] = value
def popheader(self, header):
'''Remove an header from default headers'''
return self._headers.pop(header.title())
def putcookie(self, key, value=""):
'''Add an cookie to default cookies'''
self._cookies[key] = value
def popcookie(self, key):
'''Remove an cookie from default cookies'''
return self._cookies.pop(key)
@property
@property
@property
def dump(self, fileobj, cls='marshal'):
'''pack a session and write packed bytes to fileobj
>>> s = urlfetch.Session({'User-Agent': 'urlfetch'}, {'foo': 'bar'})
>>> f = open('session.jar', 'wb')
>>> s.dump(f)
>>> f.close()
:param fileobj: a file(-like) object which have ``write`` method
:type fileobj: file
:param cls: use which class to pack the session
:type cls: string, ``marshal``, ``pickle``, etc...
'''
dump = import_object('%s.dump' % cls)
return dump(self.snapshot(), fileobj)
def dumps(self, cls='marshal'):
'''pack a seesion and return packed bytes
>>> s = urlfetch.Session({'User-Agent': 'urlfetch'}, {'foo': 'bar'})
>>> s.dumps()
...
:param cls: use which class to pack the session
:type cls: string, ``marshal``, ``pickle``, etc...
:rtype: packed bytes
'''
dumps = import_object('%s.dumps' % cls)
return dumps(self.snapshot())
def load(self, fileobj, cls='marshal'):
'''unpack a session from fileobj and load it into current session
>>> s = urlfetch.Session()
>>> s = open('session.jar', 'rb')
>>> s.load(f)
>>> f.close()
:param fileobj: a file(-like) object which have ``read`` method
:type fileobj: file
:param cls: use which class to unpack the session
:type cls: string, ``marshal``, ``pickle``, etc...
:rtype: unpacked session
'''
load = import_object('%s.load' % cls)
session = load(fileobj)
self._headers.update(session['headers'])
self._cookies.update(session['cookies'])
return session
def loads(self, string, cls='marshal'):
'''unpack a seesion from string and load it into current session
>>> s = urlfetch.Session({'User-Agent': 'urlfetch'}, {'foo': 'bar'})
>>> s.loads(s.dumps())
{'headers': {'User-Agent': 'urlfetch'}, 'cookies': {'foo': 'bar'}}
:param string: the string to be unpacked
:type string: bytes
:param cls: use which class to pack the session
:type cls: string, ``marshal``, ``pickle``, etc...
:rtype: unpacked session
'''
loads = import_object('%s.loads' % cls)
session = loads(string)
self._headers.update(session['headers'])
self._cookies.update(session['cookies'])
return session
def request(self, *args, **kwargs):
'''Issue a request'''
headers = self.headers.copy()
if self.cookiestring:
headers['Cookie'] = self.cookiestring
headers.update(kwargs.get('headers', {}))
kwargs['headers'] = headers
r = request(*args, **kwargs)
cookies = r.cookies
self._cookies.update(cookies)
return r
def fetch(self, *args, **kwargs):
'''Fetch an URL'''
data = kwargs.get('data', None)
files = kwargs.get('files', {})
if data is not None and isinstance(data, (basestring, dict)) or files:
return self.post(*args, **kwargs)
return self.get(*args, **kwargs)
def get(self, *args, **kwargs):
'''Issue a get request'''
kwargs['method'] = 'GET'
return self.request(*args, **kwargs)
def post(self, *args, **kwargs):
'''Issue a post request'''
kwargs['method'] = 'POST'
return self.request(*args, **kwargs)
def put(self, *args, **kwargs):
'''Issue a put request'''
kwargs['method'] = 'PUT'
return self.request(*args, **kwargs)
def delete(self, *args, **kwargs):
'''Issue a delete request'''
kwargs['method'] = 'DELETE'
return self.request(*args, **kwargs)
def head(self, *args, **kwargs):
'''Issue a head request'''
kwargs['method'] = 'HEAD'
return self.request(*args, **kwargs)
def options(self, *args, **kwargs):
'''Issue a options request'''
kwargs['method'] = 'OPTIONS'
return self.request(*args, **kwargs)
def trace(self, *args, **kwargs):
'''Issue a trace request'''
kwargs['method'] = 'TRACE'
return self.request(*args, **kwargs)
def patch(self, *args, **kwargs):
'''Issue a patch request'''
kwargs['method'] = 'PATCH'
return self.request(*args, **kwargs)
def fetch(*args, **kwargs):
''' fetch an URL.
:func:`~urlfetch.fetch` is a wrapper of :func:`~urlfetch.request`.
It calls :func:`~urlfetch.get` by default. If one of parameter ``data``
or parameter ``files`` is supplied, :func:`~urlfetch.post` is called.
'''
data = kwargs.get('data', None)
files = kwargs.get('files', {})
if data is not None and isinstance(data, (basestring, dict)) or files:
return post(*args, **kwargs)
return get(*args, **kwargs)
def request(url, method="GET", params=None, data=None, headers={}, timeout=None,
files={}, randua=False, auth=None, length_limit=None, proxies=None,
trust_env=True, max_redirects=0, **kwargs):
''' request an URL
:param url: URL to be fetched.
:param method: (optional) HTTP method, one of ``GET``, ``DELETE``, ``HEAD``,
``OPTIONS``, ``PUT``, ``POST``, ``TRACE``, ``PATCH``.
``GET`` by default.
:param params: (optional) dict or string to attach to url as querystring.
:param headers: (optional) HTTP request headers in dict
:param timeout: (optional) timeout in seconds
:param files: (optional) files to be sended
:param randua: (optional) if ``True`` or ``path string``, use a random
user-agent in headers, instead of ``'urlfetch/' + __version__``
:param auth: (optional) (username, password) for basic authentication
:param length_limit: (optional) if ``None``, no limits on content length,
if the limit reached raised exception 'Content length
is more than ...'
:param proxies: (optional) HTTP proxy, like {'http': '127.0.0.1:8888',
'https': '127.0.0.1:563'}
:param trust_env: (optional) If ``True``, urlfetch will get infomations
from env, such as HTTP_PROXY, HTTPS_PROXY
:param max_redirects: (integer, optional) Max redirects allowed within a
request. Default is 0, which means redirects are not
allowed.
:rtype: A :class:`~urlfetch.Response` object
'''
def make_connection(conn_type, host, port, timeout):
''' return HTTP or HTTPS connection '''
if conn_type == 'http':
conn = HTTPConnection(host, port, timeout=timeout)
elif conn_type == 'https':
conn = HTTPSConnection(host, port, timeout=timeout)
else:
raise UrlfetchException('Unknown Connection Type: %s' % conn_type)
return conn
via_proxy = False
method = method.upper()
if method not in ALLOWED_METHODS:
raise UrlfetchException("Method should be one of " +
", ".join(ALLOWED_METHODS))
if params:
if isinstance(params, dict):
url = url_concat(url, params)
elif isinstance(params, basestring):
if url[-1] not in ('?', '&'):
url += '&' if ('?' in url) else '?'
url += params
parsed_url = parse_url(url)
# Proxy support
scheme = parsed_url['scheme']
if proxies is None and trust_env:
proxies = PROXIES
proxy = proxies.get(scheme)
if proxy and parsed_url['host'] not in PROXY_IGNORE_HOSTS:
via_proxy = True
if '://' not in proxy:
proxy = '%s://%s' % (scheme, proxy)
parsed_proxy = parse_url(proxy)
h = make_connection(scheme, parsed_proxy['host'], parsed_proxy['port'],
timeout)
else:
h = make_connection(scheme, parsed_url['host'], parsed_url['port'],
timeout)
# is randua bool or path
if randua and isinstance(randua, basestring) and \
os.path.isfile(randua):
randua_file = randua
randua = True
else:
randua_file = None
randua = bool(randua)
# default request headers
reqheaders = {
'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate, compress, identity, *',
'User-Agent': random_useragent(randua_file) if randua else \
'urlfetch/' + __version__,
'Host': parsed_url['host'],
}
if parsed_url['username'] is not None and parsed_url['password'] is not \
None and auth is None:
auth = (parsed_url['username'], parsed_url['password'])
if auth is not None:
if isinstance(auth, (list, tuple)):
auth = '%s:%s' % tuple(auth)
auth = base64.b64encode(auth.encode('utf-8'))
reqheaders['Authorization'] = 'Basic ' + auth.decode('utf-8')
if files:
content_type, data = encode_multipart(data, files)
reqheaders['Content-Type'] = content_type
elif isinstance(data, dict):
data = urlencode(data, 1)
if isinstance(data, basestring) and not files:
# httplib will set 'Content-Length', also you can set it by yourself
reqheaders["Content-Type"] = "application/x-www-form-urlencoded"
# what if the method is GET, HEAD or DELETE
# just do not make so much decisions for users
for k, v in headers.items():
reqheaders[k.title()] = v
start_time = time.time()
if via_proxy:
h.request(method, url, data, reqheaders)
else:
h.request(method, parsed_url['uri'], data, reqheaders)
_response = h.getresponse()
end_time = time.time()
total_time = end_time - start_time
history = []
response = Response.from_httplib(_response, reqheaders=reqheaders,
connection=h, length_limit=length_limit,
history=history, url=url,
total_time=total_time)
while (response.status in (301, 302, 303, 307) and
'location' in response.headers and max_redirects):
response.body, response.close(), history.append(response)
if len(history) > max_redirects:
raise UrlfetchException('max_redirects exceeded')
method = 'GET'
location = response.headers['location']
if location[:2] == '//':
url = parsed_url['scheme'] + ':' + location
else:
url = urlparse.urljoin(url, location)
parsed_url = parse_url(url)
reqheaders['Host'] = parsed_url['host']
# Proxy support
scheme = parsed_url['scheme']
if proxies is None and trust_env:
proxies = PROXIES
proxy = proxies.get(scheme)
if proxy and parsed_url['host'] not in PROXY_IGNORE_HOSTS:
if '://' not in proxy:
proxy = '%s://%s' % (scheme, proxy)
parsed_proxy = parse_url(proxy)
h = make_connection(scheme, parsed_proxy['host'], parsed_proxy['port'],
timeout)
else:
h = make_connection(scheme, parsed_url['host'], parsed_url['port'],
timeout)
start_time = time.time()
if via_proxy:
h.request(method, url, None, reqheaders)
else:
h.request(method, parsed_url['uri'], None, reqheaders)
_response = h.getresponse()
end_time = time.time()
response = Response.from_httplib(_response, reqheaders=reqheaders,
connection=h, length_limit=length_limit,
history=history, url=url)
return response
###############################################################################
# Shortcuts and Helpers ########################################################
###############################################################################
get = _partial_method("GET")
post = _partial_method("POST")
put = _partial_method("PUT")
delete = _partial_method("DELETE")
head = _partial_method("HEAD")
options = _partial_method("OPTIONS")
trace = _partial_method("TRACE")
patch = _partial_method("PATCH")
def _flatten(lst):
'''flatten nested list/tuple/set.
modified from https://gist.github.com/1308410'''
return reduce(lambda l, i: l + _flatten(i)
if isinstance(i, (list,tuple,set))
else l + [i], lst, [])
def decode_gzip(data):
''' decode gzipped content '''
import gzip
gzipper = gzip.GzipFile(fileobj=BytesIO(data))
return gzipper.read()
def decode_deflate(data):
''' decode deflate content '''
import zlib
try:
return zlib.decompress(data)
except zlib.error:
return zlib.decompress(data, -zlib.MAX_WBITS)
def parse_url(url):
'''returns dictionary of parsed url:
scheme, netloc, path, params, query, fragment, uri, username, password,
host and port
'''
result = dict()
parsed = urlparse.urlsplit(url)
result['scheme'] = parsed.scheme
result['netloc'] = parsed.netloc
result['path'] = parsed.path
result['query'] = parsed.query
result['fragment'] = parsed.fragment
result['uri'] = parsed.path
if parsed.query:
result['uri'] += '?' + parsed.query
result['username'] = parsed.username
result['password'] = parsed.password
result['host'] = result['hostname'] = parsed.hostname
result['port'] = parsed.port
return result
def get_proxies_from_environ():
'''get proxies from os.environ'''
proxies = {}
http_proxy = os.getenv('http_proxy') or os.getenv('HTTP_PROXY')
https_proxy = os.getenv('https_proxy') or os.getenv('HTTPS_PROXY')
if http_proxy:
proxies['http'] = http_proxy
if https_proxy:
proxies['https'] = https_proxy
return proxies
def mb_code(s, coding=None, errors='replace'):
'''encoding/decoding helper'''
if isinstance(s, unicode):
return s if coding is None else s.encode(coding, errors=errors)
for c in ('utf-8', 'gb2312', 'gbk', 'gb18030', 'big5'):
try:
s = s.decode(c)
return s if coding is None else s.encode(coding, errors=errors)
except: pass
return unicode(s, errors=errors)
def sc2cs(sc):
'''Convert Set-Cookie header to cookie string.
Set-Cookie can be retrieved from a :class:`~urlfetch.Response` instance::
sc = response.getheader('Set-Cookie')
:param sc: (string) Set-Cookie
:rtype: cookie string, which is name=value pairs joined by ``;``.
'''
c = Cookie.SimpleCookie(sc)
sc = ['%s=%s' % (i.key, i.value) for i in c.values()]
return '; '.join(sc)
def random_useragent(filename=None, *filenames):
'''Returns a User-Agent string randomly from file.
>>> ua = random_useragent('file1')
>>> ua = random_useragent('file1', 'file2')
>>> ua = random_useragent(['file1', 'file2'])
>>> ua = random_useragent(['file1', 'file2'], 'file3')
:param filename: path to the file from which a random useragent
is generated
:type filename: string, optional
'''
import random
from time import time
filenames = list(filenames)
if filename is None:
filenames.extend([
os.path.join(os.path.abspath(os.path.dirname(__file__)),
'urlfetch.useragents.list'),
os.path.join(sys.prefix, 'share', 'urlfetch',
'urlfetch.useragents.list'),
])
else:
filenames.append(filename)
filenames = set(_flatten(filenames))
for filename in filenames:
st = os.stat(filename)
if stat.S_ISREG(st.st_mode) and os.access(filename, os.R_OK):
break
else:
return 'urlfetch/%s' % __version__
with open(filename, 'rb') as f:
filesize = st.st_size
r = random.Random(time())
pos = 0
# try getting a valid line for no more than 64 times
for i in range(64):
pos += r.randint(0, filesize)
pos %= filesize
f.seek(pos)
# in case we are in middle of a line
f.readline()
line = f.readline()
if not line:
if f.tell() == filesize:
# end of file
f.seek(0)
line = f.readline()
line = line.strip()
if line and line[0] != '#':
return line
return 'urlfetch/%s' % __version__
def import_object(name):
"""Imports an object by name.
import_object('x.y.z') is equivalent to 'from x.y import z'.
>>> import tornado.escape
>>> import_object('os.path') is os.path
True
>>> import_object('os.path.dirname') is os.path.dirname
True
"""
parts = name.split('.')
obj = __import__('.'.join(parts[:-1]), None, None, [parts[-1]], 0)
return getattr(obj, parts[-1])
def url_concat(url, args, keep_existing=True):
"""Concatenate url and argument dictionary
>>> url_concat("http://example.com/foo?a=b", dict(c="d"))
'http://example.com/foo?a=b&c=d'
:param url: (string) url being concat to.
:param args: (dict) args being concat.
:param keep_existing: (bool, optional) Whether to keep the args which are
alreay in url, default is ``True``.
"""
if not args:
return url
if keep_existing:
if url[-1] not in ('?', '&'):
url += '&' if ('?' in url) else '?'
return url + urlencode(args, 1)
else:
url, seq, query = url.partition('?')
query = urlparse.parse_qs(query, True)
query.update(args)
return url + '?' + urlencode(query, 1)
def choose_boundary():
'''Generate a multipart boundry.
:rtype: string
'''
global BOUNDARY_PREFIX
if BOUNDARY_PREFIX is None:
BOUNDARY_PREFIX = "urlfetch"
try:
uid = repr(os.getuid())
BOUNDARY_PREFIX += "." + uid
except AttributeError:
pass
try:
pid = repr(os.getpid())
BOUNDARY_PREFIX += "." + pid
except AttributeError:
pass
return "%s.%s" % (BOUNDARY_PREFIX, uuid.uuid4().hex)
def encode_multipart(data, files):
'''Encode multipart.
:param data: (dict) data to be encoded
:param files: (dict) files to be encoded
:rtype: encoded binary string
'''
body = BytesIO()
boundary = choose_boundary()
part_boundary = b('--%s\r\n' % boundary)
if isinstance(data, dict):
for name, value in data.items():
body.write(part_boundary)
writer(body).write('Content-Disposition: form-data; '
'name="%s"\r\n' % name)
body.write(b'Content-Type: text/plain\r\n\r\n')
if py3k and isinstance(value, str):
writer(body).write(value)
else:
body.write(value)
body.write(b'\r\n')
for fieldname, f in files.items():
if isinstance(f, tuple):
filename, f = f
elif hasattr(f, 'name'):
filename = os.path.basename(f.name)
else:
filename = None
raise UrlfetchException("file must has filename")
if hasattr(f, 'read'):
value = f.read()
elif isinstance(f, basestring):
value = f
else:
value = str(f)
body.write(part_boundary)
if filename:
writer(body).write('Content-Disposition: form-data; name="%s"; '
'filename="%s"\r\n' % (fieldname, filename))
body.write(b'Content-Type: application/octet-stream\r\n\r\n')
else:
writer(body).write('Content-Disposition: form-data; name="%s"'
'\r\n' % name)
body.write(b'Content-Type: text/plain\r\n\r\n')
if py3k and isinstance(value, str):
writer(body).write(value)
else:
body.write(value)
body.write(b'\r\n')
body.write(b('--' + boundary + '--\r\n'))
content_type = 'multipart/form-data; boundary=%s' % boundary
return content_type, body.getvalue()
###############################################################################
# Constants and Globals ########################################################
###############################################################################
ALLOWED_METHODS = ("GET", "DELETE", "HEAD", "OPTIONS", "PUT", "POST", "TRACE",
"PATCH")
PROXY_IGNORE_HOSTS = ('127.0.0.1', 'localhost')
PROXIES = get_proxies_from_environ()
writer = codecs.lookup('utf-8')[3]
BOUNDARY_PREFIX = None
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
7061,
6,
198,
333,
1652,
7569,
198,
15116,
4907,
198,
198,
2025,
2562,
284,
779,
14626,
5456,
1912,
319,
1841,
489,
5... | 2.212137 | 13,331 |
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
start_page_keyboard = InlineKeyboardMarkup(row_width=2)
new_list_but = InlineKeyboardButton(
text='Новый список', callback_data='new_list')
user_lists_but = InlineKeyboardButton(
text='Мои списки', callback_data='user_lists')
start_page_keyboard.insert(new_list_but)
start_page_keyboard.insert(user_lists_but)
new_list_keyboard = InlineKeyboardMarkup()
list_but = InlineKeyboardButton(
text='Новый список', callback_data='new_list')
new_list_keyboard.insert(list_but)
| [
6738,
257,
72,
21857,
13,
19199,
1330,
554,
1370,
9218,
3526,
9704,
929,
11,
554,
1370,
9218,
3526,
21864,
198,
198,
9688,
62,
7700,
62,
2539,
3526,
796,
554,
1370,
9218,
3526,
9704,
929,
7,
808,
62,
10394,
28,
17,
8,
198,
198,
36... | 2.404348 | 230 |
from django.forms import ModelForm
from .models import MainPersonData
| [
6738,
42625,
14208,
13,
23914,
1330,
9104,
8479,
198,
198,
6738,
764,
27530,
1330,
8774,
15439,
6601,
628
] | 4 | 18 |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import xarray as xr
from scipy import stats
def plot(data, x, y, type=None, **kwargs):
"""
Function to plot the corr coeff plot
--------------------------
input 3 values data, x and y in this order
and use this example -
data = dataframe_name
x = data['column_name']
y = data['column_name']
"""
r, p = stats.pearsonr(x,y)
# checking value of p for reporting p in figure
if p < 0.001:
p_string = " and $p < .001$"
else:
p_string = f" and p = {np.round(p,3)}"
# r = x - ((x.describe()[1]) *
# (y - y.describe()[1])).describe()[1] / (y.describe()[2]*x.describe()[2])
plt.scatter(
x, y, label=f'r = {np.round(r, 3)}' + p_string, **kwargs)
if type == 'compare':
lineStartx = x.min() - 3
lineEndx = x.max() + 3
lineStarty = y.min() - 3
lineEndy = y.max() + 3
sns.regplot(x=x, y=y, data=data, color='k', scatter=False,
fit_reg=True, truncate=False, label='Linear Fit').set(xlabel=None, ylabel=None)
# plt.plot([lineStartx, lineEndx], [
# lineStarty, lineEndy], 'k-', color='k')
# plt.plot([lineStartx, lineEndx], [lineStarty, 0.5773*lineEndy],
# 'k--', color='k', alpha=0.5)
# plt.plot([lineStartx, lineEndx], [lineStarty, 1.7321*lineEndy],
# 'k--', color='k', alpha=0.5)
plt.xlim(lineStartx, lineEndx)
plt.ylim(lineStarty, lineEndy)
plt.legend(frameon = True, loc=0, prop={'size': 10})
if type == 'logistic':
lineStartx = x.min()
lineEndx = x.max()
lineStarty = y.min()
lineEndy = y.max()
sns.regplot(x=x, y=y, data=data, color='k', scatter=False,
fit_reg=True, logx = True, truncate=False, label='Regression Fit').set(xlabel=None, ylabel=None)
# plt.plot([lineStartx, lineEndx], [
# lineStarty, lineEndy], 'k-', color='k')
# plt.plot([lineStartx, lineEndx], [lineStarty, 0.5773*lineEndy],
# 'k--', color='k', alpha=0.5)
# plt.plot([lineStartx, lineEndx], [lineStarty, 1.7321*lineEndy],
# 'k--', color='k', alpha=0.5)
plt.xlim(lineStartx, lineEndx)
plt.ylim(lineStarty, lineEndy)
plt.legend(frameon = True, loc=0, prop={'size': 10})
if type == None:
if x.min() < y.min():
lineStart = x.min()
else:
lineStart = y.min()
if x.max() > y.max():
lineEnd = x.max()
else:
lineEnd = y.max()
sns.regplot(x=x, y=y, data=data, color='r', scatter=False,
fit_reg=True, truncate=False, label='Linear Fit').set(xlabel=None, ylabel=None)
plt.plot([lineStart, lineEnd], [lineStart, lineEnd], 'k-', alpha = 0.7)
# plt.plot([lineStart, lineEnd], [lineStart, 0.5773*lineEnd],
# 'k--', color='k', alpha=0.5)
# plt.plot([lineStart, lineEnd], [lineStart, 1.7321*lineEnd],
# 'k--', color='k', alpha=0.5)
plt.xlim(lineStart, lineEnd)
plt.ylim(lineStart, lineEnd)
plt.legend(frameon = True, loc=0, prop={'size': 12})
def plot_binning(data, x, y, bins, **kwargs):
"""
Function to plot the corr coeff plot for the binned data
--------------------------
input 3 values dataset, x and y in this order
and use this example -
data = dataset_name
x = data['column_name']
y = data['column_name']
"""
binned_x = data[x].groupby_bins(data[x], bins).mean()
binned_y = data[y].groupby_bins(data[x], bins).mean()
binned_yerr = data[y + '_stdev'].groupby_bins(data[x], bins).mean()
slope, intercept, r, p, _ = stats.linregress(binned_x, binned_y)
plt.scatter(data[x], data[y], **kwargs)
if p < 0.001:
plt.plot(binned_x, slope*binned_x + intercept, color = kwargs['color'], label = f'R = {np.round(r,3)}; p < 0.001')
else:
plt.plot(binned_x, slope*binned_x + intercept, color = kwargs['color'], label=f'R = {np.round(r,3)} and p = {np.round(p,3)}')
(_, caps, _) = plt.errorbar(binned_x, binned_y, yerr=binned_yerr,
alpha=0.9, ecolor='k', fmt='^',
mfc='k', markersize=6, capsize=4, label='binned average')
plt.legend(frameon=False, loc=0)
| [
11748,
299,
32152,
355,
45941,
198,
11748,
2603,
29487,
8019,
13,
9078,
29487,
355,
458,
83,
198,
11748,
384,
397,
1211,
355,
3013,
82,
198,
11748,
19798,
292,
355,
279,
67,
198,
11748,
2124,
18747,
355,
2124,
81,
198,
6738,
629,
541,... | 2.034212 | 2,163 |
from factory import DjangoModelFactory, Faker, SubFactory
from .boards import BoardFactory
from .users import UserFactory
from ...models import Topic
class TopicFactory(DjangoModelFactory):
"""
Defines topic factory
"""
subject = Faker("sentence", nb_words=3)
board = SubFactory(BoardFactory)
starter = SubFactory(UserFactory)
| [
6738,
8860,
1330,
37770,
17633,
22810,
11,
376,
3110,
11,
3834,
22810,
198,
198,
6738,
764,
12821,
1330,
5926,
22810,
198,
6738,
764,
18417,
1330,
11787,
22810,
198,
6738,
2644,
27530,
1330,
47373,
628,
198,
4871,
47373,
22810,
7,
35,
7... | 3.308411 | 107 |
from __future__ import print_function
from math import log10
import numpy
import h5py
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from torch.utils.data import DataLoader
from model import NetARCNN_deform
import argparse
from datetime import datetime
logfile = "log/log_deform_" + str(datetime.now()) + ".txt"
train_data_path = "dataset/train_data.h5"
test_data_path = "dataset/test_data.h5"
checkpoint_path = "checkpoint_deform/"
parser = argparse.ArgumentParser(description="Pytorch Deblocking Example")
parser.add_argument("--batchSize", type=int, default=100, help="training batch size")
parser.add_argument("--testBatchSize", type=int, default=30, help="testing batch size")
parser.add_argument("--nEpochs", type=int, default=30, help="number of epochs to train for")
parser.add_argument("--lr", type=float, default=0.0001, help="Learning Rate")
# Notice: it is "action" for cuda options, not type
parser.add_argument("--cuda", action="store_true", help="use cuda?") # what is "store true"?
# parser.add_argument("--threads", type=int, default=4, help="number of threads for data loader to use")
parser.add_argument("--seed",type=int, default=123, help="random seed to use. Default = 123")
# parser.add_argument("--logfile",type=str, default=logfile, help="name of log file for training")
opt = parser.parse_args()
print(opt)
print("===> Building logfile")
output = open(logfile,'a+')
# output = open("log_"+str(datetime.now())+".txt")
# output = open("train_result.txt")
output.write("Model: ARCNN_deform\nbatchSize: {}\ntestBatchSize: {}\nnEpochs: {}\nlearningRate: {}\n\nEpoch |PSNR before |PSNR after".format(opt.batchSize, opt.testBatchSize, opt.nEpochs, opt.lr))
output.close()
cuda = opt.cuda
if cuda and not torch.cuda.is_available():
raise Exception("No GPU found, please run without --cuda")
torch.manual_seed(opt.seed)
if cuda:
torch.cuda.manual_seed(opt.seed)
# print("===> Loading datasets")
print("===> Building model")
model = NetARCNN_deform()
# model.load_state_dict(torch.load(checkpoint_path+".pkl"))
criterion = nn.MSELoss()
if cuda:
model = model.cuda()
criterion = criterion.cuda()
optimizer = optim.Adam(model.parameters(), lr=opt.lr)
# can I open 2 files at one time?
# A: Sure
train_data = h5py.File(train_data_path, "r")
test_data = h5py.File(test_data_path, "r")
for epoch in range(1, opt.nEpochs + 1):
train(epoch, train_data, opt.batchSize)
test(epoch, test_data, opt.testBatchSize)
checkpoint(epoch)
| [
6738,
11593,
37443,
834,
1330,
3601,
62,
8818,
198,
198,
6738,
10688,
1330,
2604,
940,
198,
198,
11748,
299,
32152,
198,
11748,
289,
20,
9078,
198,
198,
11748,
28034,
198,
11748,
28034,
13,
20471,
355,
299,
77,
198,
11748,
28034,
13,
... | 2.813466 | 906 |
from tokenizers import Tokenizer
from tokenizers.models import BPE
from tokenizers.pre_tokenizers import *
from tokenizers.trainers import BpeTrainer
import tokenizers
# Required functions
def dict_sort(dictionary: dict) -> list:
"""Takes in a dictionary with integer values and outputs a list of the keys sorted by their associated values in descending order."""
return list(reversed(sorted(dictionary, key=dictionary.__getitem__)))
class TokenNumberizer:
"""Simple class for token-based string-int conversion."""
trainer = BpeTrainer(special_tokens=["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"]) | [
6738,
11241,
11341,
1330,
29130,
7509,
198,
6738,
11241,
11341,
13,
27530,
1330,
347,
11401,
198,
6738,
11241,
11341,
13,
3866,
62,
30001,
11341,
1330,
1635,
198,
6738,
11241,
11341,
13,
27432,
364,
1330,
347,
431,
2898,
10613,
198,
11748... | 3.31016 | 187 |
__doc__ = 'Auxiliary file for test98.py'
class BaseGood:
'Nice base init'
class BaseBad:
'Error should print as coming from this file'
| [
834,
15390,
834,
796,
705,
32,
2821,
28129,
2393,
329,
1332,
4089,
13,
9078,
6,
198,
198,
4871,
7308,
10248,
25,
198,
220,
220,
220,
705,
35284,
2779,
2315,
6,
198,
198,
4871,
7308,
22069,
25,
198,
220,
220,
220,
705,
12331,
815,
... | 2.843137 | 51 |
import json
import unittest
from flask import Flask
from api import api
from database.AudioSchema import Song, Podcast, Audiobook
# Define test data
headers = dict(api_key="2c5a16d9-a951-4f62-ac68-e4df97e7b15d",
api_client="jane.doe@email.com"
)
# Change ID on run
podcastTestID = "6046fcc995184fd26e82cac1"
songTestID = "60471b3a669529b65c5ffb72"
audiobookTestID = "60470a51b95704ef06d9925c"
test_song = {
"audioFileType": "song",
"audioFileMetadata": {
"name_of_song": "Paradise by Coldplay",
"duration": 40
}
}
test_podcast = {
"audioFileType": "podcast",
"audioFileMetadata": {
"name_of_podcast": "Loose Talk",
"duration": 1909,
"host": "AOT2",
"participants": ["AOT2", "Bad Girl Mo", "Jess Jess Finess", "Steve Dede Canada"]
}
}
test_audiobook = {
"audioFileType": "audiobook",
"audioFileMetadata": {
"title_of_audiobook": "Born a Crime",
"author_of_title": "Trevor Noah",
"narrator": "Trevor Noah",
"duration": 390492
}
}
if __name__ == "__main__":
unittest.main()
| [
11748,
33918,
198,
11748,
555,
715,
395,
198,
6738,
42903,
1330,
46947,
198,
6738,
40391,
1330,
40391,
198,
6738,
6831,
13,
21206,
27054,
2611,
1330,
10940,
11,
16036,
11,
26686,
49776,
628,
198,
2,
2896,
500,
1332,
1366,
198,
50145,
79... | 2.179537 | 518 |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
#class for check open ssl Heartbleed vulnerability
import socket
import urllib2
import httplib
import HTMLParser
import base64
import sys
import time
import select
import struct
import shodan
server_vulnerable =[]
hello = h2bin('''
16 03 02 00 dc 01 00 00 d8 03 02 53
43 5b 90 9d 9b 72 0b bc 0c bc 2b 92 a8 48 97 cf
bd 39 04 cc 16 0a 85 03 90 9f 77 04 33 d4 de 00
00 66 c0 14 c0 0a c0 22 c0 21 00 39 00 38 00 88
00 87 c0 0f c0 05 00 35 00 84 c0 12 c0 08 c0 1c
c0 1b 00 16 00 13 c0 0d c0 03 00 0a c0 13 c0 09
c0 1f c0 1e 00 33 00 32 00 9a 00 99 00 45 00 44
c0 0e c0 04 00 2f 00 96 00 41 c0 11 c0 07 c0 0c
c0 02 00 05 00 04 00 15 00 12 00 09 00 14 00 11
00 08 00 06 00 03 00 ff 01 00 00 49 00 0b 00 04
03 00 01 02 00 0a 00 34 00 32 00 0e 00 0d 00 19
00 0b 00 0c 00 18 00 09 00 0a 00 16 00 17 00 08
00 06 00 07 00 14 00 15 00 04 00 05 00 12 00 13
00 01 00 02 00 03 00 0f 00 10 00 11 00 23 00 00
00 0f 00 01 01
''')
hb = h2bin('''
18 03 02 00 03
01 40 00
''')
#Obtain info IP
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
2,
532,
9,
12,
21004,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
2,
4871,
329,
2198,
1280,
264,
6649,
8894,
903,
276,
15131,
198,
198,
11748,
17802,
198,
11748,
2956,
297,
571,
... | 2.259336 | 482 |
from direct.showbase.ShowBase import ShowBase
from panda3d.core import CollisionTraverser, CollisionNode
from panda3d.core import CollisionHandlerQueue, CollisionRay
from panda3d.core import TextNode
from panda3d.core import LPoint3, LVector3, BitMask32
from direct.actor.Actor import Actor
from direct.gui.OnscreenText import OnscreenText
from direct.gui.DirectGui import *
from direct.gui.DirectFrame import DirectFrame
from direct.gui.DirectButton import DirectButton
from direct.gui.OnscreenImage import OnscreenImage
from direct.gui.DirectGuiBase import DGG
from direct.task.Task import Task
from direct.actor.Actor import Actor
from pandac.PandaModules import *
import board,piece,rules,chessAI
import sys
import copy
# Initialize buttons on init screen
# Initialize buttons on play screen
# Initialize buttons on tutorial screen
| [
6738,
1277,
13,
12860,
8692,
13,
15307,
14881,
1330,
5438,
14881,
201,
198,
6738,
279,
5282,
18,
67,
13,
7295,
1330,
7778,
1166,
15721,
690,
263,
11,
7778,
1166,
19667,
201,
198,
6738,
279,
5282,
18,
67,
13,
7295,
1330,
7778,
1166,
... | 3.380392 | 255 |
from connect_four.evaluation.evaluator import ProofStatus
from connect_four.evaluation.evaluator import Evaluator
from connect_four.evaluation.evaluator import NodeType
from connect_four.evaluation.victor.victor_evaluator import Victor
| [
6738,
2018,
62,
14337,
13,
18206,
2288,
13,
18206,
84,
1352,
1330,
29999,
19580,
198,
6738,
2018,
62,
14337,
13,
18206,
2288,
13,
18206,
84,
1352,
1330,
26439,
84,
1352,
198,
6738,
2018,
62,
14337,
13,
18206,
2288,
13,
18206,
84,
1352... | 3.575758 | 66 |
import pytest
import filecmp
import litmus.compose
import os
import pathlib
this_path = pathlib.Path(__file__).parent.resolve() | [
11748,
12972,
9288,
198,
11748,
2393,
48991,
198,
11748,
6578,
14664,
13,
785,
3455,
198,
11748,
28686,
198,
11748,
3108,
8019,
198,
5661,
62,
6978,
796,
3108,
8019,
13,
15235,
7,
834,
7753,
834,
737,
8000,
13,
411,
6442,
3419
] | 3.175 | 40 |
# -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""This module implements the abstract base class for backend jobs
When creating a new backend module it is also necessary to implement this
job interface.
"""
from abc import ABC, abstractmethod
import enum
class BaseJob(ABC):
"""Class to handle asynchronous jobs"""
@abstractmethod
def __init__(self):
"""Initializes the asynchronous job"""
pass
@abstractmethod
def result(self):
"""Return backend result"""
pass
@abstractmethod
def cancel(self):
"""Attempt to cancel job."""
pass
# Property attributes
#####################
@property
@abstractmethod
def status(self):
"""Get backend status dictionary"""
pass
@property
@abstractmethod
def running(self):
"""True if job is currently running."""
pass
@property
@abstractmethod
def done(self):
"""True if call was successfully finished."""
pass
@property
@abstractmethod
def cancelled(self):
"""True if call was successfully cancelled"""
pass
class JobStatus(enum.Enum):
"""Class for job status enumerated type."""
INITIALIZING = 'job is being initialized'
QUEUED = 'job is queued'
RUNNING = 'job is actively running'
CANCELLED = 'job has been cancelled'
DONE = 'job has successfully run'
ERROR = 'job incurred error'
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
2,
15069,
2177,
11,
19764,
13,
198,
2,
198,
2,
770,
2723,
2438,
318,
11971,
739,
262,
24843,
13789,
11,
10628,
362,
13,
15,
1043,
287,
198,
2,
262,
38559,
24290... | 2.846975 | 562 |
# ----------------------------------------------------------------------------
# Gimel Studio Copyright 2019-2022 by the Gimel Studio project 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 applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------
from gimelstudio import api
api.RegisterNode(StringNode, "corenode_string")
| [
2,
16529,
10541,
198,
2,
41123,
417,
11733,
15069,
13130,
12,
1238,
1828,
416,
262,
41123,
417,
11733,
1628,
20420,
198,
2,
198,
2,
49962,
739,
262,
24843,
13789,
11,
10628,
362,
13,
15,
357,
1169,
366,
34156,
15341,
198,
2,
345,
74... | 4.505263 | 190 |
from ._nodes import model_fit, forward_selection, make_report, hyperopt_fit, model_single_fit, onefactor
__all__ = ['model_fit', 'forward_selection', 'make_report', 'hyperopt_fit', 'model_single_fit', 'onefactor'] | [
198,
6738,
47540,
77,
4147,
1330,
2746,
62,
11147,
11,
2651,
62,
49283,
11,
787,
62,
13116,
11,
8718,
8738,
62,
11147,
11,
2746,
62,
29762,
62,
11147,
11,
530,
31412,
198,
198,
834,
439,
834,
796,
37250,
19849,
62,
11147,
3256,
705,... | 3.115942 | 69 |
import json
from sanic.log import logger
from pubgate.db import User
from pubgate.utils import random_object_id
| [
11748,
33918,
198,
198,
6738,
5336,
291,
13,
6404,
1330,
49706,
198,
198,
6738,
2240,
10494,
13,
9945,
1330,
11787,
198,
6738,
2240,
10494,
13,
26791,
1330,
4738,
62,
15252,
62,
312,
628,
628
] | 3.441176 | 34 |
"""
Bounding regions and bounding boxes.
"""
__version__='$Revision$'
from numpy import inf
### JABALERT: The aarect information should probably be rewritten in
### matrix notation, not list notation, so that it can be scaled,
### translated, etc. easily.
###
import param
from param.parameterized import get_occupied_slots
class BoundingRegion(object):
"""
Abstract bounding region class, for any portion of a 2D plane.
Only subclasses can be instantiated directly.
"""
__abstract = True
__slots__ = ['_aarect']
def centroid(self):
"""
Return the coordinates of the center of this BoundingBox
"""
return self.aarect().centroid()
# CEBALERT: same as methods on Parameter
class BoundingBox(BoundingRegion):
"""
A rectangular bounding box defined either by two points forming
an axis-aligned rectangle (or simply a radius for a square).
"""
__slots__ = []
def __str__(self):
"""
Return BoundingBox(points=((left,bottom),(right,top)))
Reimplemented here so that 'print' for a BoundingBox
will display the bounds.
"""
l,b,r,t = self._aarect.lbrt()
if r == -l and t == -b and r == t:
return 'BoundingBox(radius=%s)'%(r)
else:
return 'BoundingBox(points=((%s,%s),(%s,%s)))'%(l,b,r,t)
def __init__(self,**args):
"""
Create a BoundingBox.
Either 'radius' or 'points' can be specified for the AARectangle.
If neither radius nor points is passed in, create a default
AARectangle defined by (-0.5,-0.5),(0.5,0.5).
"""
# if present, 'radius', 'min_radius', and 'points' are deleted from
# args before they're passed to the superclass (because they
# aren't parameters to be set)
if 'radius' in args:
r = args['radius']
del args['radius']
self._aarect=AARectangle((-r,-r),(r,r))
elif 'points' in args:
self._aarect = AARectangle(*args['points'])
del args['points']
else:
self._aarect = AARectangle((-0.5,-0.5),(0.5,0.5))
super(BoundingBox,self).__init__(**args)
def contains(self,x,y):
"""
Returns true if the given point is contained within the
bounding box, where all boundaries of the box are
considered to be inclusive.
"""
left,bottom,right,top = self.aarect().lbrt()
return (left <= x <= right) and (bottom <= y <= top)
def contains_exclusive(self,x,y):
"""
Return True if the given point is contained within the
bounding box, where the bottom and right boundaries are
considered exclusive.
"""
a=self._aarect
left,bottom,right,top = a._left,a._bottom,a._right,a._top
return (left <= x < right) and (bottom < y <= top)
def containsbb_exclusive(self,x):
"""
Returns true if the given BoundingBox x is contained within the
bounding box, where at least one of the boundaries of the box has
to be exclusive.
"""
left,bottom,right,top = self.aarect().lbrt()
leftx,bottomx,rightx,topx = x.aarect().lbrt()
return (left <= leftx) and (bottom <= bottomx) and (right >= rightx) and (top >= topx) and (not ((left == leftx) and (bottom == bottomx) and (right == rightx) and (top == topx)))
def containsbb_inclusive(self,x):
"""
Returns true if the given BoundingBox x is contained within the
bounding box, including cases of exact match.
"""
left,bottom,right,top = self.aarect().lbrt()
leftx,bottomx,rightx,topx = x.aarect().lbrt()
return (left <= leftx) and (bottom <= bottomx) and (right >= rightx) and (top >= topx)
def upperexclusive_contains(self,x,y):
"""
Returns true if the given point is contained within the
bounding box, where the right and upper boundaries
are exclusive, and the left and lower boundaries are
inclusive. Useful for tiling a plane into non-overlapping
regions.
"""
left,bottom,right,top = self.aarect().lbrt()
return (left <= x < right) and (bottom <= y < top)
def lbrt(self):
"""
return left,bottom,right,top values for the BoundingBox.
"""
return self._aarect.lbrt()
class Cartesian2DPoint(param.Parameter):
"""
Parameter whose value represents a point in a 2D Cartesian plane.
"""
### JABALERT: Should accept and respect a BoundingBox bounds.
class BoundingEllipse(BoundingBox):
"""
Similar to BoundingBox, but the region is the ellipse
inscribed within the rectangle.
"""
__slots__ = []
# CEBALERT: various subclasses of BoundingRegion, such as
# BoundingCircle, do not set _aarect during __init__. Should
# BoundingRegion have an __init__ that includes setting _aarect?
# Currently, BoundingRegion only sets _aarect when certain methods are
# called, such as translate(). Other subclasses (such as BoundingBox)
# set _aarect during __init__. I'm a bit confused about the point.
# Anyway, the situation as it is now means BoundingCircle and other
# such classes can't be pickled.
class BoundingCircle(BoundingRegion):
"""
A circular BoundingRegion.
Takes parameters center (a single 2D point (x,y)) and radius (a
scalar radius).
"""
__slots__ = ['radius','center']
#radius = param.Number(0.5,bounds=(0.0,None))
#center = Cartesian2DPoint((0.0,0.0))
### This class is valid only for BoundingBoxes, because it
### only deals with the aarect(), ignoring arbitrarily shaped
### BoundingRegions. To be a real Intersection(BoundingRegion) class,
### it would need to have a contains() function that computes a
### logical AND of the contains() for each of the regions supplied.
### Scale, rotate, and translate would also need to be applied to the
### individual regions each time.
### Could be simpler to write this as a function, because it just
### ends up with a simple BoundingBox after construction.
class BoundingBoxIntersection(BoundingBox):
"""A BoundingBox initialized as the intersection of the supplied list of BoundingBoxes."""
def __init__(self,*boxes,**params):
"""
Given a list of BoundingBoxes, computes a new BoundingBox that is
the intersection of all of the supplied boxes.
"""
super(BoundingBoxIntersection,self).__init__(**params)
bounds = [r.aarect().lbrt() for r in boxes]
left = max([l for (l,b,r,t) in bounds])
bottom = max([b for (l,b,r,t) in bounds])
right = min([r for (l,b,r,t) in bounds])
top = min([t for (l,b,r,t) in bounds])
# JABALERT: Why is this one __aarect, and BoundingBox
# _aarect? Probably should change this one to _aarect and
# eliminate aarect(self).
self.__aarect = AARectangle((left,bottom),(right,top))
# JABALERT: Should probably remove top, bottom, etc. accessor functions,
# and use the slot itself instead.
###################################################
class AARectangle(object):
"""
Axis-aligned rectangle class.
Defines the smallest axis-aligned rectangle that encloses a set of
points.
Usage: aar = AARectangle( (x1,y1),(x2,y2), ... , (xN,yN) )
"""
__slots__ = ['_left','_bottom','_right','_top']
# support for pickling because this class has __slots__ rather
# than __dict__
def top(self):
"""Return the y-coordinate of the top of the rectangle."""
return self._top
def bottom(self):
"""Return the y-coordinate of the bottom of the rectangle."""
return self._bottom
def left(self):
"""Return the x-coordinate of the left side of the rectangle."""
return self._left
def right(self):
"""Return the x-coordinate of the right side of the rectangle."""
return self._right
def lbrt(self):
"""Return (left,bottom,right,top) as a tuple."""
return (self._left,self._bottom,self._right,self._top)
def centroid(self):
"""
Return the centroid of the rectangle.
"""
left,bottom,right,top = self.lbrt()
return (right+left)/2.0,(top+bottom)/2.0
### JABALERT: Should classes like this inherit from something like
### ClassInstanceParameter, which takes a class name and verifies that
### the value is in that class?
###
### Do we also need a BoundingBoxParameter?
class BoundingRegionParameter(param.Parameter):
"""
Parameter whose value can be any BoundingRegion instance, enclosing a region in a 2D plane.
"""
__slots__=['set_hook']
def __set__(self,obj,val):
"""
Set a non default bounding box, use the installed set hook to
apply any conversion or transformation on the coordinates and
create a new bounding box with the converted coordinate set.
"""
coords = [self.set_hook(obj,point) for point in val.lbrt()]
if coords != val.lbrt():
val = BoundingBox(points=[(coords[0],coords[1]),(coords[2],coords[3])])
if not isinstance(val,BoundingRegion):
raise ValueError("Parameter must be a BoundingRegion.")
else:
super(BoundingRegionParameter,self).__set__(obj,val)
| [
37811,
198,
33,
9969,
7652,
290,
5421,
278,
10559,
13,
198,
37811,
198,
198,
834,
9641,
834,
11639,
3,
18009,
1166,
3,
6,
198,
198,
6738,
299,
32152,
1330,
1167,
198,
198,
21017,
449,
6242,
1847,
17395,
25,
383,
257,
533,
310,
1321,... | 2.601161 | 3,618 |
#!/usr/bin/env python3
import sys
if __name__ == "__main__":
main()
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
11748,
25064,
628,
198,
198,
361,
11593,
3672,
834,
6624,
366,
834,
12417,
834,
1298,
198,
220,
220,
220,
1388,
3419,
198
] | 2.34375 | 32 |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from decimal import Decimal
from bitarray import bitarray
import __builtin__
import group_resouces_list
import slot_resouces_list
class resources(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module brocade-openflow-operational - based on the path /openflow-state/resources. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: Openflow Meter Resources
"""
__slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_rest_name', '_extmethods', '__meter_max','__meter_used','__meter_free','__tcam_profile','__group_resouces_list','__slot_resouces_list',)
_yang_name = 'resources'
_rest_name = 'resources'
_pybind_generated_by = 'container'
def _get_meter_max(self):
"""
Getter method for meter_max, mapped from YANG variable /openflow_state/resources/meter_max (uint32)
YANG Description: MAX
"""
return self.__meter_max
def _set_meter_max(self, v, load=False):
"""
Setter method for meter_max, mapped from YANG variable /openflow_state/resources/meter_max (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_meter_max is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_meter_max() directly.
YANG Description: MAX
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="meter-max", rest_name="meter-max", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-openflow-operational', defining_module='brocade-openflow-operational', yang_type='uint32', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """meter_max must be of a type compatible with uint32""",
'defined-type': "uint32",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="meter-max", rest_name="meter-max", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-openflow-operational', defining_module='brocade-openflow-operational', yang_type='uint32', is_config=False)""",
})
self.__meter_max = t
if hasattr(self, '_set'):
self._set()
def _get_meter_used(self):
"""
Getter method for meter_used, mapped from YANG variable /openflow_state/resources/meter_used (uint32)
YANG Description: Used
"""
return self.__meter_used
def _set_meter_used(self, v, load=False):
"""
Setter method for meter_used, mapped from YANG variable /openflow_state/resources/meter_used (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_meter_used is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_meter_used() directly.
YANG Description: Used
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="meter-used", rest_name="meter-used", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-openflow-operational', defining_module='brocade-openflow-operational', yang_type='uint32', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """meter_used must be of a type compatible with uint32""",
'defined-type': "uint32",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="meter-used", rest_name="meter-used", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-openflow-operational', defining_module='brocade-openflow-operational', yang_type='uint32', is_config=False)""",
})
self.__meter_used = t
if hasattr(self, '_set'):
self._set()
def _get_meter_free(self):
"""
Getter method for meter_free, mapped from YANG variable /openflow_state/resources/meter_free (uint32)
YANG Description: Free
"""
return self.__meter_free
def _set_meter_free(self, v, load=False):
"""
Setter method for meter_free, mapped from YANG variable /openflow_state/resources/meter_free (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_meter_free is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_meter_free() directly.
YANG Description: Free
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="meter-free", rest_name="meter-free", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-openflow-operational', defining_module='brocade-openflow-operational', yang_type='uint32', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """meter_free must be of a type compatible with uint32""",
'defined-type': "uint32",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="meter-free", rest_name="meter-free", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-openflow-operational', defining_module='brocade-openflow-operational', yang_type='uint32', is_config=False)""",
})
self.__meter_free = t
if hasattr(self, '_set'):
self._set()
def _get_tcam_profile(self):
"""
Getter method for tcam_profile, mapped from YANG variable /openflow_state/resources/tcam_profile (string)
YANG Description: Tcam Profile
"""
return self.__tcam_profile
def _set_tcam_profile(self, v, load=False):
"""
Setter method for tcam_profile, mapped from YANG variable /openflow_state/resources/tcam_profile (string)
If this variable is read-only (config: false) in the
source YANG file, then _set_tcam_profile is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_tcam_profile() directly.
YANG Description: Tcam Profile
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=unicode, is_leaf=True, yang_name="tcam-profile", rest_name="tcam-profile", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-openflow-operational', defining_module='brocade-openflow-operational', yang_type='string', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """tcam_profile must be of a type compatible with string""",
'defined-type': "string",
'generated-type': """YANGDynClass(base=unicode, is_leaf=True, yang_name="tcam-profile", rest_name="tcam-profile", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-openflow-operational', defining_module='brocade-openflow-operational', yang_type='string', is_config=False)""",
})
self.__tcam_profile = t
if hasattr(self, '_set'):
self._set()
def _get_group_resouces_list(self):
"""
Getter method for group_resouces_list, mapped from YANG variable /openflow_state/resources/group_resouces_list (list)
YANG Description: Group resources
"""
return self.__group_resouces_list
def _set_group_resouces_list(self, v, load=False):
"""
Setter method for group_resouces_list, mapped from YANG variable /openflow_state/resources/group_resouces_list (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_group_resouces_list is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_group_resouces_list() directly.
YANG Description: Group resources
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("group_type",group_resouces_list.group_resouces_list, yang_name="group-resouces-list", rest_name="group-resouces-list", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='group-type', extensions={u'tailf-common': {u'callpoint': u'openflow-group-resources', u'cli-suppress-show-path': None}}), is_container='list', yang_name="group-resouces-list", rest_name="group-resouces-list", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'openflow-group-resources', u'cli-suppress-show-path': None}}, namespace='urn:brocade.com:mgmt:brocade-openflow-operational', defining_module='brocade-openflow-operational', yang_type='list', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """group_resouces_list must be of a type compatible with list""",
'defined-type': "list",
'generated-type': """YANGDynClass(base=YANGListType("group_type",group_resouces_list.group_resouces_list, yang_name="group-resouces-list", rest_name="group-resouces-list", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='group-type', extensions={u'tailf-common': {u'callpoint': u'openflow-group-resources', u'cli-suppress-show-path': None}}), is_container='list', yang_name="group-resouces-list", rest_name="group-resouces-list", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'openflow-group-resources', u'cli-suppress-show-path': None}}, namespace='urn:brocade.com:mgmt:brocade-openflow-operational', defining_module='brocade-openflow-operational', yang_type='list', is_config=False)""",
})
self.__group_resouces_list = t
if hasattr(self, '_set'):
self._set()
def _get_slot_resouces_list(self):
"""
Getter method for slot_resouces_list, mapped from YANG variable /openflow_state/resources/slot_resouces_list (list)
YANG Description: Slot Resources
"""
return self.__slot_resouces_list
def _set_slot_resouces_list(self, v, load=False):
"""
Setter method for slot_resouces_list, mapped from YANG variable /openflow_state/resources/slot_resouces_list (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_slot_resouces_list is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_slot_resouces_list() directly.
YANG Description: Slot Resources
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("slot_id",slot_resouces_list.slot_resouces_list, yang_name="slot-resouces-list", rest_name="slot-resouces-list", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='slot-id', extensions={u'tailf-common': {u'callpoint': u'openflow-slot-resources', u'cli-suppress-show-path': None}}), is_container='list', yang_name="slot-resouces-list", rest_name="slot-resouces-list", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'openflow-slot-resources', u'cli-suppress-show-path': None}}, namespace='urn:brocade.com:mgmt:brocade-openflow-operational', defining_module='brocade-openflow-operational', yang_type='list', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """slot_resouces_list must be of a type compatible with list""",
'defined-type': "list",
'generated-type': """YANGDynClass(base=YANGListType("slot_id",slot_resouces_list.slot_resouces_list, yang_name="slot-resouces-list", rest_name="slot-resouces-list", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='slot-id', extensions={u'tailf-common': {u'callpoint': u'openflow-slot-resources', u'cli-suppress-show-path': None}}), is_container='list', yang_name="slot-resouces-list", rest_name="slot-resouces-list", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'openflow-slot-resources', u'cli-suppress-show-path': None}}, namespace='urn:brocade.com:mgmt:brocade-openflow-operational', defining_module='brocade-openflow-operational', yang_type='list', is_config=False)""",
})
self.__slot_resouces_list = t
if hasattr(self, '_set'):
self._set()
meter_max = __builtin__.property(_get_meter_max)
meter_used = __builtin__.property(_get_meter_used)
meter_free = __builtin__.property(_get_meter_free)
tcam_profile = __builtin__.property(_get_tcam_profile)
group_resouces_list = __builtin__.property(_get_group_resouces_list)
slot_resouces_list = __builtin__.property(_get_slot_resouces_list)
_pyangbind_elements = {'meter_max': meter_max, 'meter_used': meter_used, 'meter_free': meter_free, 'tcam_profile': tcam_profile, 'group_resouces_list': group_resouces_list, 'slot_resouces_list': slot_resouces_list, }
| [
198,
6738,
10088,
1330,
708,
81,
1136,
353,
198,
11748,
12972,
648,
21653,
13,
8019,
13,
87,
6978,
2978,
525,
355,
2124,
6978,
2978,
525,
198,
6738,
12972,
648,
21653,
13,
8019,
13,
17859,
19199,
1330,
8324,
20941,
6719,
16005,
10707,
... | 2.729175 | 5,306 |
import numpy as np
from pandas import DataFrame
import matplotlib.pyplot as plt
class anosim(object):
'''
Docstring for function ecopy.anosim
====================
Conducts analysis of similarity (ANOSIM) on a distance matrix given
one or two factors (groups)
Use
----
anosim(dist, factor1, factor2=None, nested=False, nperm=999)
Returns an object of class anosim
Parameters
----------
dist: A square-symmetric distance matrix
factor1: The first grouping factor
factor2: The second grouping factor
nested: Whether or not the first factor is nested within the second.
If true, levels of factor1 are permuted only within the nesting groups
nperm: Number of permutations for the test.
Attributes (see online documentation for descriptions)
---------
r_perm1: Permuted R-statistics of the null distribution for factor1
r_perm2: Permuted R-statistics of the null distribution for factor2
R_obs1: The observed R-statistic of factor1
R_obs2: The observed R-statistic of factor2
pval: List of pvals for factor1 and factor2
perm: Number of permutations
Methods
--------
summary(): provides a summary of test results
plot(): plots histograms of random vs. observed
R-statistics
Example
--------
import ecopy as ep
data1 = ep.load_data('dune')
data2 = ep.load_data('dune_env')
duneDist = ep.distance(data1, 'bray')
group1 = data2['Management']
group2map = {'SF': 'A', 'BF': 'A', 'HF': 'B', 'NM': 'B'}
group2 = group1.map(group2map)
t1 = ep.anosim(duneDist, group1, group2, nested=True, nperm=9999)
print(t1.summary())
t1.plot()
'''
| [
11748,
299,
32152,
355,
45941,
198,
6738,
19798,
292,
1330,
6060,
19778,
198,
11748,
2603,
29487,
8019,
13,
9078,
29487,
355,
458,
83,
198,
198,
4871,
281,
418,
320,
7,
15252,
2599,
198,
220,
220,
220,
705,
7061,
198,
220,
220,
220,
... | 2.800979 | 613 |
from unittest.mock import MagicMock
from unittest.mock import patch
import pytest
from kuber import kube_api
from kuber.latest import core_v1
def test_execute():
"""Should execute the specified action on the service without error."""
service = core_v1.Service()
service.metadata.name = "foo"
api = MagicMock()
code = MagicMock()
code.co_varnames = ("bob", "foo", "namespace")
api.create_namespaced_service.__code__ = code
with patch.object(service, "get_resource_api") as get_api:
get_api.return_value = api
service.create_resource(namespace="foo")
api.create_namespaced_service.assert_called_once()
def test_execute_no_name():
""" "Should raise error when no api client function name exists."""
resource = MagicMock()
resource.get_resource_api.return_value = None
with pytest.raises(ValueError):
kube_api.execute(action="foo", resource=resource, names=["spam", "ham"])
| [
6738,
555,
715,
395,
13,
76,
735,
1330,
6139,
44,
735,
198,
6738,
555,
715,
395,
13,
76,
735,
1330,
8529,
198,
198,
11748,
12972,
9288,
198,
198,
6738,
479,
18478,
1330,
479,
3266,
62,
15042,
198,
6738,
479,
18478,
13,
42861,
1330,
... | 2.808824 | 340 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on Tue May 12 21:03:53 2020
@author: xange
"""
import pytesseract
import os
from matplotlib import pyplot as plt
import numpy as np
import cv2
from PIL import Image
from difflib import SequenceMatcher
import sys
if __name__ == '__main__':
localizeCorrectAnswer(str(sys.argv[1]))
| [
2,
48443,
14629,
14,
8800,
14,
29412,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
37811,
198,
41972,
319,
30030,
1737,
1105,
2310,
25,
3070,
25,
4310,
12131,
198,
198,
31,
9800,
25,
2124,
858,
198,
37811,
1... | 2.653846 | 130 |
# SPDX-FileCopyrightText: 2018 Dean Miller for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
`adafruit_epd.ssd1608` - Adafruit SSD1608 - ePaper display driver
====================================================================================
CircuitPython driver for Adafruit SSD1608 display breakouts
* Author(s): Dean Miller, Ladyada
"""
import time
from micropython import const
import adafruit_framebuf
from adafruit_epd.epd import Adafruit_EPD
__version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_EPD.git"
_SSD1608_DRIVER_CONTROL = const(0x01)
_SSD1608_GATE_VOLTAGE = const(0x03)
_SSD1608_SOURCE_VOLTAGE = const(0x04)
_SSD1608_DISPLAY_CONTROL = const(0x07)
_SSD1608_NON_OVERLAP = const(0x0B)
_SSD1608_BOOSTER_SOFT_START = const(0x0C)
_SSD1608_GATE_SCAN_START = const(0x0F)
_SSD1608_DEEP_SLEEP = const(0x10)
_SSD1608_DATA_MODE = const(0x11)
_SSD1608_SW_RESET = const(0x12)
_SSD1608_TEMP_WRITE = const(0x1A)
_SSD1608_TEMP_READ = const(0x1B)
_SSD1608_TEMP_CONTROL = const(0x1C)
_SSD1608_TEMP_LOAD = const(0x1D)
_SSD1608_MASTER_ACTIVATE = const(0x20)
_SSD1608_DISP_CTRL1 = const(0x21)
_SSD1608_DISP_CTRL2 = const(0x22)
_SSD1608_WRITE_RAM = const(0x24)
_SSD1608_READ_RAM = const(0x25)
_SSD1608_VCOM_SENSE = const(0x28)
_SSD1608_VCOM_DURATION = const(0x29)
_SSD1608_WRITE_VCOM = const(0x2C)
_SSD1608_READ_OTP = const(0x2D)
_SSD1608_WRITE_LUT = const(0x32)
_SSD1608_WRITE_DUMMY = const(0x3A)
_SSD1608_WRITE_GATELINE = const(0x3B)
_SSD1608_WRITE_BORDER = const(0x3C)
_SSD1608_SET_RAMXPOS = const(0x44)
_SSD1608_SET_RAMYPOS = const(0x45)
_SSD1608_SET_RAMXCOUNT = const(0x4E)
_SSD1608_SET_RAMYCOUNT = const(0x4F)
_SSD1608_NOP = const(0xFF)
_LUT_DATA = b'\x02\x02\x01\x11\x12\x12""fiiYX\x99\x99\x88\x00\x00\x00\x00\xf8\xb4\x13Q5QQ\x19\x01\x00' # pylint: disable=line-too-long
class Adafruit_SSD1608(Adafruit_EPD):
"""driver class for Adafruit SSD1608 ePaper display breakouts"""
# pylint: disable=too-many-arguments
def begin(self, reset=True):
"""Begin communication with the display and set basic settings"""
if reset:
self.hardware_reset()
self.power_down()
def busy_wait(self):
"""Wait for display to be done with current task, either by polling the
busy pin, or pausing"""
if self._busy:
while self._busy.value:
time.sleep(0.01)
else:
time.sleep(0.5)
def power_up(self):
"""Power up the display in preparation for writing RAM and updating"""
self.hardware_reset()
self.busy_wait()
self.command(_SSD1608_SW_RESET)
self.busy_wait()
# driver output control
self.command(
_SSD1608_DRIVER_CONTROL,
bytearray([self._width - 1, (self._width - 1) >> 8, 0x00]),
)
# Set dummy line period
self.command(_SSD1608_WRITE_DUMMY, bytearray([0x1B]))
# Set gate line width
self.command(_SSD1608_WRITE_GATELINE, bytearray([0x0B]))
# Data entry sequence
self.command(_SSD1608_DATA_MODE, bytearray([0x03]))
# Set ram X start/end postion
self.command(_SSD1608_SET_RAMXPOS, bytearray([0x00, self._height // 8 - 1]))
# Set ram Y start/end postion
self.command(
_SSD1608_SET_RAMYPOS,
bytearray([0, 0, self._height - 1, (self._height - 1) >> 8]),
)
# Vcom Voltage
self.command(_SSD1608_WRITE_VCOM, bytearray([0x70]))
# LUT
self.command(_SSD1608_WRITE_LUT, _LUT_DATA)
self.busy_wait()
def power_down(self):
"""Power down the display - required when not actively displaying!"""
self.command(_SSD1608_DEEP_SLEEP, bytearray([0x01]))
time.sleep(0.1)
def update(self):
"""Update the display from internal memory"""
self.command(_SSD1608_DISP_CTRL2, bytearray([0xC7]))
self.command(_SSD1608_MASTER_ACTIVATE)
self.busy_wait()
if not self._busy:
time.sleep(3) # wait 3 seconds
def write_ram(self, index):
"""Send the one byte command for starting the RAM write process. Returns
the byte read at the same time over SPI. index is the RAM buffer, can be
0 or 1 for tri-color displays."""
if index == 0:
return self.command(_SSD1608_WRITE_RAM, end=False)
raise RuntimeError("RAM index must be 0")
def set_ram_address(self, x, y): # pylint: disable=unused-argument, no-self-use
"""Set the RAM address location, not used on this chipset but required by
the superclass"""
# Set RAM X address counter
self.command(_SSD1608_SET_RAMXCOUNT, bytearray([x]))
# Set RAM Y address counter
self.command(_SSD1608_SET_RAMYCOUNT, bytearray([y >> 8, y]))
| [
2,
30628,
55,
12,
8979,
15269,
8206,
25,
2864,
11325,
7920,
329,
1215,
1878,
4872,
20171,
198,
2,
198,
2,
30628,
55,
12,
34156,
12,
33234,
7483,
25,
17168,
198,
198,
37811,
198,
63,
324,
1878,
4872,
62,
538,
67,
13,
824,
67,
1433,... | 2.115688 | 2,282 |
tablename = 'users'
| [
8658,
11925,
480,
796,
705,
18417,
6,
198
] | 2.5 | 8 |
import subprocess
import re
import helper
#obj = MULSolve(-3, 7)
#r = obj.solve()
#print(r) | [
11748,
850,
14681,
198,
11748,
302,
198,
11748,
31904,
198,
198,
2,
26801,
796,
337,
6239,
50,
6442,
32590,
18,
11,
767,
8,
198,
2,
81,
796,
26181,
13,
82,
6442,
3419,
198,
2,
4798,
7,
81,
8
] | 2.421053 | 38 |
n = 10
a = [[0 for x in range(n)] for x in range(n)]
b = [[0 for x in range(n)] for x in range(n)]
c = [[0 for x in range(n)] for x in range(n)]
for i in range(n):
for j in range(n):
c[i][j] = 0
for k in range(n):
c[i][j] = c[i][j] + a[i][k] * b[k][j] | [
77,
796,
838,
198,
64,
796,
16410,
15,
329,
2124,
287,
2837,
7,
77,
15437,
329,
2124,
287,
2837,
7,
77,
15437,
198,
65,
796,
16410,
15,
329,
2124,
287,
2837,
7,
77,
15437,
329,
2124,
287,
2837,
7,
77,
15437,
198,
66,
796,
16410,... | 1.893333 | 150 |
# Copyright 2014 Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import mock
from manila.network.linux import ip_lib
from manila import test
NETNS_SAMPLE = [
'12345678-1234-5678-abcd-1234567890ab',
'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb',
'cccccccc-cccc-cccc-cccc-cccccccccccc']
LINK_SAMPLE = [
'1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN \\'
'link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00',
'2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP '
'qlen 1000\ link/ether cc:dd:ee:ff:ab:cd brd ff:ff:ff:ff:ff:ff'
'\ alias openvswitch',
'3: br-int: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN '
'\ link/ether aa:bb:cc:dd:ee:ff brd ff:ff:ff:ff:ff:ff',
'4: gw-ddc717df-49: <BROADCAST,MULTICAST> mtu 1500 qdisc noop '
'state DOWN \ link/ether fe:dc:ba:fe:dc:ba brd ff:ff:ff:ff:ff:ff',
'5: eth0.50@eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc '
' noqueue master brq0b24798c-07 state UP mode DEFAULT'
'\ link/ether ab:04:49:b6:ab:a0 brd ff:ff:ff:ff:ff:ff']
ADDR_SAMPLE = ("""
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000
link/ether dd:cc:aa:b9:76:ce brd ff:ff:ff:ff:ff:ff
inet 172.16.77.240/24 brd 172.16.77.255 scope global eth0
inet6 2001:470:9:1224:5595:dd51:6ba2:e788/64 scope global temporary dynamic
valid_lft 14187sec preferred_lft 3387sec
inet6 2001:470:9:1224:fd91:272:581e:3a32/64 scope global temporary """
"""deprecated dynamic
valid_lft 14187sec preferred_lft 0sec
inet6 2001:470:9:1224:4508:b885:5fb:740b/64 scope global temporary """
"""deprecated dynamic
valid_lft 14187sec preferred_lft 0sec
inet6 2001:470:9:1224:dfcc:aaff:feb9:76ce/64 scope global dynamic
valid_lft 14187sec preferred_lft 3387sec
inet6 fe80::dfcc:aaff:feb9:76ce/64 scope link
valid_lft forever preferred_lft forever
""")
ADDR_SAMPLE2 = ("""
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000
link/ether dd:cc:aa:b9:76:ce brd ff:ff:ff:ff:ff:ff
inet 172.16.77.240/24 scope global eth0
inet6 2001:470:9:1224:5595:dd51:6ba2:e788/64 scope global temporary dynamic
valid_lft 14187sec preferred_lft 3387sec
inet6 2001:470:9:1224:fd91:272:581e:3a32/64 scope global temporary """
"""deprecated dynamic
valid_lft 14187sec preferred_lft 0sec
inet6 2001:470:9:1224:4508:b885:5fb:740b/64 scope global temporary """
"""deprecated dynamic
valid_lft 14187sec preferred_lft 0sec
inet6 2001:470:9:1224:dfcc:aaff:feb9:76ce/64 scope global dynamic
valid_lft 14187sec preferred_lft 3387sec
inet6 fe80::dfcc:aaff:feb9:76ce/64 scope link
valid_lft forever preferred_lft forever
""")
GATEWAY_SAMPLE1 = ("""
default via 10.35.19.254 metric 100
10.35.16.0/22 proto kernel scope link src 10.35.17.97
""")
GATEWAY_SAMPLE2 = ("""
default via 10.35.19.254 metric 100
""")
GATEWAY_SAMPLE3 = ("""
10.35.16.0/22 proto kernel scope link src 10.35.17.97
""")
GATEWAY_SAMPLE4 = ("""
default via 10.35.19.254
""")
DEVICE_ROUTE_SAMPLE = ("10.0.0.0/24 scope link src 10.0.0.2")
SUBNET_SAMPLE1 = ("10.0.0.0/24 dev qr-23380d11-d2 scope link src 10.0.0.1\n"
"10.0.0.0/24 dev tap1d7888a7-10 scope link src 10.0.0.2")
SUBNET_SAMPLE2 = ("10.0.0.0/24 dev tap1d7888a7-10 scope link src 10.0.0.2\n"
"10.0.0.0/24 dev qr-23380d11-d2 scope link src 10.0.0.1")
| [
2,
15069,
1946,
7381,
20836,
3457,
13,
198,
2,
1439,
6923,
33876,
13,
198,
2,
198,
2,
220,
220,
220,
49962,
739,
262,
24843,
13789,
11,
10628,
362,
13,
15,
357,
1169,
366,
34156,
15341,
345,
743,
198,
2,
220,
220,
220,
407,
779,
... | 2.18495 | 1,887 |
from .mongodb import MongoDBConnection
from .pandas import DataFrameConnection
from .sqlite import SQLiteConnection
| [
6738,
764,
31059,
375,
65,
1330,
42591,
35,
2749,
261,
1606,
295,
198,
6738,
764,
79,
392,
292,
1330,
6060,
19778,
32048,
198,
6738,
764,
25410,
578,
1330,
16363,
578,
32048,
198
] | 3.625 | 32 |