content stringlengths 5 1.05M |
|---|
"""This REST service allows real-time curation and belief updates for
a corpus of INDRA Statements."""
import json
import yaml
import boto3
import pickle
import logging
import argparse
from botocore.exceptions import ClientError
from flask import Flask, request, jsonify, abort, Response
# Note: preserve EidosReader ins... |
import gc
import json
import os
import re
import warnings
import unittest
import pymysql
from .._compat import CPYTHON
if CPYTHON:
import atexit
gc.set_debug(gc.DEBUG_UNCOLLECTABLE)
@atexit.register
def report_uncollectable():
import gc
if not gc.garbage:
print("No garbag... |
from collections import deque, defaultdict
import numpy as np
import torch
from .distributed import all_reduce
class SmoothedValue:
"""Track a series of values and provide access to smoothed values over a
window or the global series average.
"""
def __init__(self, window_size=10):
self.deque... |
'''
Importing all the libraries needed
'''
import pandas as pd
import numpy as np
class Table:
"""
Table takes a csv file as input and converts to
a datframe to perform specific operations.
"""
def __init__(self, filename):
self.data = pd.read_csv(filename)
def columns(self):
... |
import sys
import sty
import numpy as np
import tensorflow as tf
def get_pretained_glove(word2idx, fpath):
"""
Construct a numpy embedding matrix.
The column number indicates the word index.
For the words do not appear in pretrained embeddings,
we use random embeddings.
Inputs:
word2... |
import sys
from Smartiome.Core.EventManager import *
class ConsoleEventSource:
def __init__(self, eventManager, type):
self.__eventManager = eventManager
self.__type=type
def SendMessage(self):
event = Event(type_=self.__type)
while True:
event.data["Event"] = inpu... |
"""
A collection of utility functions for querying and checking Ethereum data
"""
import aiohttp
from hummingbot.client.config.global_config_map import global_config_map
from hummingbot.core.utils import async_ttl_cache
import itertools as it
import logging
from typing import List
from web3 import Web3
def is_connec... |
from utils import *
import argparse
from colorama import Fore, Style,init
from pyngrok import ngrok,conf
clearDirec()
# _ _____ _______
# /\ | | | __ \ /\|__ __|
# / \ _ __ __| |_ __ ___ | |__) | / \ | |
# / /\ \ | '_ \ / _` | '__/ _... |
"""
==================
Reprojecting a Map
==================
How to apply differential rotation to a Map.
The example uses the `~sunpy.coordinates.metaframes.RotatedSunFrame` coordinate
metaframe in `sunpy.coordinates` to apply differential rotation to a
Map. See :ref:`sunpy-coordinates-rotatedsunframe` for more det... |
import numpy as np
def Tmin(E_R, A, m_x):
"""
Minimum DM kinetic energy for recoil of energy E_R
Parameters
----------
* `E_R` [float]:
Nuclear recoil energy in keV
* `A` [float]:
Nuclear mass in atomic mass units
* `m_x` [float]:
DM mass in GeV
Return... |
import streamlit as st
import pandas as pd
import numpy as np
from patsy import dmatrices
import statsmodels.api as sm
from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error
from statsmodels.sandbox.regression.predstd import wls_prediction_std
import matplotlib as mpl
import matplotlib.pyplot a... |
def unbiased_coder_test_layer_function():
print ('Hello this is a test from the Layer to see if it works')
|
"""
Copyright (c) 2020 Image Processing Research Group of University Federico II of Naples ('GRIP-UNINA').
All rights reserved. This work should only be used for nonprofit purposes.
"""
import math
import torch.nn as nn
def conv_with_padding(in_planes, out_planes, kernelsize, stride=1, dilation=1, bias=Fal... |
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding: utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
# fluctmatch --- https://github.com/tclick/python-fluctmatch
# Copyright (c) 2013-2017 The fluctmatch Development Team and contributors
# (see the file AUTHORS for the full list of names)
#
... |
# Copyright (c) 2014 Johns Hopkins University Applied Physics Laboratory
#
# 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 ... |
load(
"//private:rules.bzl",
_nix_bundleable = "nix_bundleable",
_nix_cc = "nix_cc",
_nix_deps_layer = "nix_deps_layer",
_nix_package_repository = "nix_package_repository",
)
load(
"//private:aspects.bzl",
_nix_deps_aspect = "nix_deps_aspect",
)
_SUPPORT_NIX = "@io_tweag_rules_nixpkgs//nixp... |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.13.7
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %% [markdown] slideshow={"slide_type": "slide"}
# ... |
# Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
from datetime import datetime
from django.test import TestCase
from accounts.models import User
from leave_tracker.models import Leave, Season
class TestMixing(object):
def setUp(self):
self.season = Season.objects.create()
self.user = User.objects.create_user(username='jacob', email='jacob@test.c... |
"""
OpenAI GPT-2
============
"""
from .base_model import BaseModel
from pytorch_pretrained_bert.modeling_gpt2 import GPT2PreTrainedModel, GPT2Model, GPT2LMHeadModel, GPT2Config, WEIGHTS_NAME, CONFIG_NAME
from pytorch_pretrained_bert.tokenization_gpt2 import GPT2Tokenizer
from torch.utils.data.dataset import Dataset
f... |
import os
import time
import pytest
from plantumlcli.utils import linear_process, timing_func
from ..test import unittest
@unittest
class TestUtilsConcurrent:
def test_linear_process(self):
for _ in range(0, 1000):
_list = []
linear_process(
items=[2, 3, 5, 7],
... |
{
"target_defaults": {
"cflags" : ["-std=c++11", "-Wall", "-Wextra", "-Wno-unused-parameter", "-fexceptions"],
"cflags_cc" : ["-std=c++11", "-Wall", "-Wextra", "-Wno-unused-parameter", "-fexceptions"],
"defines": [ "V8_DEPRECATION_WARNINGS=1" ],
"include_dirs": ["<!(node -e \"require('nan')\")"],
"target_con... |
for name in ['Christopher','Susan']:
print(name)
for index in range(0,2): # use built-in function range create list like [0,1]
print(index)
names=['Christopher','Susan']
index=0
while index < len(names):
print(names[index])
# change the condition!
index=index+1
# lesson 2
people=['Christopher','S... |
"""initialisation for package and importing purposes"""
from . import SR830_ControlClient
from . import SR860_ControlClient
|
import math
__all__ = ['Gaussian']
class Gaussian:
μ = 0
σ = 0
n = 0
def update(self, x):
self.n += 1
μ = self.μ
self.μ += (x - self.μ) / self.n
self.σ += ((x - μ) * (x - self.μ) - self.σ) / self.n
def cdf(self, x):
return .5 * (1 + math.erf((x - self.μ... |
def generateXArray(team, arr):
arrayTeamX = []
for val in arr:
if val != team:
arrayTeamX.append(team + '.' + val)
return arrayTeamX
|
# converts the grid based 'oddq' method of storing map into the cubed
# coordinate system this makes it easiser to run search algorthems (apparently)
def oddq_to_cube(col, row):
x = col
z = row - (col - (col & 1)) / 2
y = -x-z
cube = {
'x': x,
'y': y,
'z': z
}
return (cub... |
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. 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 requir... |
"""
Example unit tests.
"""
from datetime import datetime, timedelta
from io import StringIO
from pathlib import Path
import pydiner
from . import fixtures
def test_batcher(nseq=100, nbatch=23, joined=list):
seq = joined(range(nseq))
subseqs = [seq[i : i + nbatch] for i in range(0, nseq, nbatch)]
batches... |
import requests
from common import config
def send(phone_num,code):
params = config.YZX_SMS_PARAMS.copy()
print(type(phone_num),type(code))
params['mobile']=phone_num
params['param']=code
print(phone_num,code)
resp = requests.post(config.YZX_SMS_URL,json=params)
print(resp.status_code)
... |
"""
Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved.
The Universal Permissive License (UPL), Version 1.0
"""
from oracle.weblogic.deploy.aliases import AliasException
from wlsdeploy.exception import exception_helper
class AliasHelper(object):
"""
This class simply wraps the alias ... |
# tkinter run with OOP and click
#using CLICK
from tkinter import *
class Appli(Frame): # built Frame of Appli
def __init__ (self , x): # passing through a variable
Frame.__init__(self , x)
self.grid()
self.button_click = 0 # run after click button
self.create_widget()
... |
import os
import pandas as pd
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, BatchNormalization, Activation, Dropout
from tensorflow.keras import optimizers
from tensorflow.keras import backend as K
from args import printArgs
def lo... |
from flask import Flask, render_template, Response, request
from flask import jsonify
from . import core, constants
from . import exceptions
app = Flask(__name__)
@app.route('/', methods=['GET'])
def index():
channels = list(range(1, constants.CHANNELS + 1))
devices = list(range(1, constants.CHANNELS * len(co... |
from time import time
def sum_reverse(n):
return n + int(str(n)[::-1])
def is_palindrome(n):
return str(n) == str(n)[::-1]
def main(n, l):
res = 0
for idx in range(n):
z = 0
m = idx
while z < l:
m = sum_reverse(m)
z += 1
if is_palindrome(... |
from abc import ABC, abstractmethod
from typing import Any, Generic, Optional, TypeVar
from tgtypes.models import Update
TResult = TypeVar("T", bound=type)
class Trait(Generic[TResult]):
"""
Marks a type parameter as originating from any type of update, but returns the
"""
def __init__(self, from_q... |
#!/usr/bin/env python
import tf
import math
import rospy
import geometry_msgs.msg
class LinearMove(object):
def __init__(self, robot_name=''):
self.frame_base = rospy.get_param('~base_frame', robot_name+'/base_link')
self.frame_odom = rospy.get_param('~odom_frame', robot_name+'/odom')
sel... |
from evocraftsearch import OutputRepresentation
from evocraftsearch.utils.torch_utils import roll_n
import torch
class ImageRepresentation(OutputRepresentation):
@staticmethod
def default_config():
default_config = OutputRepresentation.default_config()
default_config.env_size = (16,16,16)
... |
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modif... |
from talon import Module, actions, cron
mod = Module()
mod.tag("scroll")
scroll_direction = None
scroll_job = None
scroll_speed = 100
@mod.action_class
class Actions:
def scroll_up():
"""Scroll up"""
def scroll_down():
"""Scroll down"""
def scroll_left():
"""Scroll left"""
def... |
# Copyright 2018 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import subprocess
import argparse
from argparse import ArgumentParser
import re
import glob
import collections
import time
import os
import pysam
import pandas as pd
class parseError(Exception):
pass
def get_option():
argparser = ArgumentParser(formatter_class=a... |
from OpenGLCffi.EGL import params
@params(api='egl', prms=['dpy', 'stream'])
def eglStreamConsumerGLTextureExternalKHR(dpy, stream):
pass
@params(api='egl', prms=['dpy', 'stream'])
def eglStreamConsumerAcquireKHR(dpy, stream):
pass
@params(api='egl', prms=['dpy', 'stream'])
def eglStreamConsumerReleaseKHR(dpy, st... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 25 18:12:59 2019
@author: Administrator
"""
import pdblp
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import date
plt.style.use('seaborn')
#con = pdblp.BCon(debug=True, port=8194, timeout... |
class Migration:
@property
def schema(self):
return
@property
def db(self):
return self._connection
|
from json import dumps, loads
from twisted.internet.defer import succeed, fail, inlineCallbacks
from twisted.web.http_headers import Headers
from fluiddb.testing.basic import FluidinfoTestCase
from fluiddb.testing.doubles import FakeRequest
from fluiddb.testing.resources import LoggingResource
from fluiddb.web.jsonrp... |
# -*- coding: utf-8 -*-
import json
from amhappy.utility.happinstance_db import HappinstanceDB
from compose.cli.docker_client import docker_client
from compose.config import from_dictionary
from compose.project import Project, ConfigurationError
from compose.service import ConfigError
from amhappy.utility.error_respons... |
from django.urls import path
from . import views
urlpatterns = [
# user paths
path('register', views.userRegister, name='register'),
path('login', views.userLogin, name='login'),
path('logout', views.userLogout, name='logout'),
path('user', views.userPage, name='user-page'),
# project paths
... |
"""Deals with HealthCheck route."""
from flask import jsonify
from pymongo import MongoClient
import os
def healthcheck():
"""Returns health information"""
status = {
"mongodb" : True
}
try:
client = MongoClient(os.getenv('MONGODB_URI', 'mongodb://localhost:27017'))
except Exception... |
from scapy.all import *
import sys
ip_list = ""
ports_list = []
def detect_ip(packet):
if 'IP' in packet:
global ip_list
ip_src = packet['IP'].src
if ip_src not in ip_list:
ip_list += " " + ip_src
return ip_list
def detect_ports(packet):
global ports_list
if... |
# -*- coding: utf-8 -*-
# @Time : 2020/7/13 21:06
# @Author : Seventy
# @Site : 批量删除空白文件夹
# @File : kill_folder.py
# @Software: PyCharm
import os
def del_emp_dir(path):
for (root, dirs, files) in os.walk(path):
for item in dirs:
dir = os.path.join(root, item)
try:
... |
# encoding: utf-8
"""
@author:
@file: config.py
@time: 2017/7/13 16:39
"""
'''配置文件,后台一些需要的配置需要在这里进行配置'''
import os
from apscheduler.jobstores.redis import RedisJobStore
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
... |
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, ValidationError
from wtforms.validators import Required, Email, Regexp, StopValidation
class FeedbackForm(FlaskForm):
feedback = StringField('Feedback', [Required()])
|
import pytest
from pathlib import Path
import json
from brukerapi.folders import Folder
def pytest_addoption(parser):
parser.addoption("--test_data", action="store", default="")
parser.addoption("--test_suites", action="store", default="")
parser.addoption("--properties_reference", action="store", default=... |
from .global_options import *
class DeleteGroupParser:
"""
Parser for the command deletegroup
"""
@staticmethod
def delete_group_parser(manager, command):
"""Method to parse delete group arguments passed by the user"""
delete_group_parser = manager.include(command)
delete_g... |
import re
from recipe_parser.helper import improve_fractions, text_to_number, is_number
import json
def parse_ingredients(texts):
# list to save dictionaries
ingredients = []
# improve parsability and transform into an iterabel format:
# line by line, word by word
recipe = texts[0].desc... |
import subprocess
import re
import time
import json
count = 10
def __fish() -> list[dict[str, str]]:
result = []
for _ in range(count):
start = time.time()
subprocess.check_output("fish -i -c exit", shell=True)
elapsed = time.time() - start
result.append(elapsed)
average ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2017-18 Richard Hull and contributors
# See LICENSE.rst for details.
import pytest
from PIL import Image
from luma.led_matrix.device import neosegment
from luma.core.device import dummy
from luma.core.render import canvas
import luma.core.error
from help... |
# -*- coding: utf-8 -*-
__about__ = """
This is a minimalistic project that just has basic account features and a
simple, static reader
"""
default_app_config = "basic.apps.AppConfig"
|
# Lint as: python3
#
# Copyright 2020 The XLS Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
import json
from datetime import datetime, timedelta
def to_time_string(seconds):
outstring = ''
hours = 0
minutes = 0
if seconds >= 3600:
hours = seconds // 3600
seconds = seconds % 3600
outstring += f'{hours}h'
if seconds > 60:
minutes = seconds // 60
seco... |
import cv2, glob
import numpy as np
class CameraCalibration():
def __init__(self, itr=30, eps=0.001):
self.criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, itr, eps)
self.obj_points = []
self.img_points = []
self.objp = np.zeros((7*9,3), dtype="float32")
self.... |
# -*- coding: utf-8 -*-
#
# ibptws/tests/test_calculadoras.py
#
# Copyright 2015 Base4 Sistemas Ltda ME
#
# 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/... |
import unittest
from mockito import mock, when, verify
from pygglz.feature_snapshot import FeatureSnapshot
from pygglz.feature_state import FeatureState
class FeatureSnapshotTest(unittest.TestCase):
def setUp(self) -> None:
self.state_repo = mock()
def test_pass_through_to_repo_if_missing(self):
... |
import sys
from unicodedata import category
from collections import Counter, defaultdict
import pandas as pd
from nltk.util import ngrams
from nesta.packages.misc_utils.jaccard import fast_nested_jaccard
from nesta.packages.misc_utils.jaccard import fast_jaccard
from nesta.packages.geo_utils.lookup import get_disputed_... |
# -*- coding:utf-8 -*-
"""
搬砖套利
Project: alphahunter
Author: HJQuant
Description: Asynchronous driven quantitative trading framework
"""
import sys
import asyncio
from quant import const
from quant.state import State
from quant.utils import tools, logger
from quant.config import config
from quant.market import Mark... |
import time
import paho.mqtt.client as mqtt
import sys
#sys.path.append('WifiUnhacking')
#sys.path.append('ZeldaAutomation')
#sys.path.append('BattleAI')
#IMPORTS OF THE WIFI UNHACKING ENIGMA
#from wifi_Puzzlebox import *
#from wifiUnhackingSolved import *
#IMPORTS OF THE WIFI BATTLE AI
#from zelda_home_public impo... |
def weighted_of_masked_data(data_in,data_mask,data_cond):
#data_in = input xarray data to have weighted mean
#data_mask = nan mask eg. land values
#LME mask T or F values
global_attrs = data_in.attrs
R = 6.37e6 #radius of earth in m
grid_dy,grid_dx = (data_in.lat[0]-data_in.lat[1]).data,(data_in... |
import systemcheck
from systemcheck.systems import ABAP
from systemcheck.checks.models import Check
from systemcheck.utils import Result, Fail, datecalc
from pprint import pformat
from systemcheck.models.meta import Base, ChoiceType, Column, ForeignKey, Integer, QtModelMixin, String, qtRelationship, relationship, Rich... |
from sqlalchemy import Column, DateTime, String, Integer, ForeignKey, Binary, Enum, Text
from sqlalchemy.orm import relationship, backref
from .database import BASE
import pickle
import json
from .filters import *
from helper.image_creator import ImageCreator
import enum
ALL_FILTERS = list()
ALL_FILTERS.append(EdgeDi... |
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from scipy.signal import find_peaks
class Household:
def __init__(self, dataframe, stoves, fuels, hh_id, temp_threshold=15, time_between_events=60,weight_threshold=0.2):
'''Verifying that the input arguments a... |
# -*- coding: utf-8 -*-
from django.db import models
class IndexModel(models.Model):
name = models.TextField(max_length=500)
year = models.DateField()
|
import numpy as np
def Wheel(P):
r = np.random.random() * np.sum(P)
C = np.cumsum(P)
A = np.argmax(r <= C)
return A
|
from wargaming.version import get_version # noqa
import six
from wargaming.meta import BaseAPI, MetaAPI, WGAPI
from wargaming.settings import DEFAULT_REGION
from wargaming.exceptions import ValidationError
@six.add_metaclass(MetaAPI)
class WoT(BaseAPI):
def __init__(self, application_id, language, region=DEFAU... |
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
#
# Copyright (C) 2006 Fluendo, S.A. (www.fluendo.com).
# Copyright 2006, Frank Scholz <coherence@beebits.net>
# Copyright 2018, Pol Canelles <canellestudi@gmail.com>
'''
:class:`MSearch`
----------------
A class representing a protocol... |
from contextlib import contextmanager
from os.path import abspath, dirname, exists, join
from django.core.management import call_command
from django.db import IntegrityError, connection
from django.db.backends.sqlite3.base import DatabaseWrapper
from django.db.models.fields import NOT_PROVIDED
from django.forms import... |
from invana_py import InvanaGraph
import random
class TestSchema:
def test_get_graph_schema(self, graph: InvanaGraph):
label = "UserProfile"
graph.vertex.create(label, name="Ravi {random.randint(1, 1000)}").to_list()
result = graph.backend.schema_reader.get_graph_schema()
assert l... |
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
print(mnist.train.images.shape, mnist.train.labels.shape)
print(mnist.test.images.shape, mnist.test.labels.shape)
print(mnist.validation.images.shape,mnist.validation.label... |
#!/usr/bin/python
import socket
import struct
ip_addr = '192.168.199.130'
port = 9999
print "GMON Command - Verify Offsets\n"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((ip_addr, int(port)))
except Exception as e:
print "[-] Failed to connect to service %s" % e
else:
print "... |
#!/usr/bin/python
# Given several pairs of one-column files with each pair corresponding
# to the x and y components of CCD artifact correction for a certain
# TDI and scan direction, concatenate the two files in each pair and
# write them as a row in the output TIF image. Use only 4 digits of
# precision.
import sy... |
from datetime import datetime
from django import forms
from ..dso.models import DSOList
from ..observe.models import ObservingLocation
from ..misc.models import TimeZone
from ..site_parameter.helpers import find_site_parameter
from ..solar_system.models import Planet, Asteroid, Comet
from ..tech.models import Telescope... |
__author__ = 'Allison MacLeay'
import sys
import os
import argparse
import time
from glob import glob
from tempfile import mkdtemp
"""
Run a command on every file in a directory
"""
def get_cmd(fname, cmd, params):
""" return command """
out_name = os.path.join(params['out'], params['name'] + fname)
cmd... |
from django.contrib.auth import get_user_model
def get_sentinel_user():
return get_user_model().objects.get_or_create(username='deleted')[0]
|
from .base import APIConsumer as BaseConsumer
from django.utils import timezone
from backend.models import (
Clan,
ClanHistory,
Player,
PlayerClanStatsHistory,
PlayerClanHistory,
ClanWar,
PlayerClanWar
)
# Since the list is ordered, we only have to find the position of the given clan in t... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#------------------------------------------------------------------------------------------#
# This file is part of Pyccel which is released under MIT License. See the LICENSE file or #
# go to https://github.com/pyccel/pyccel/blob/master/LICENSE for full license details. #... |
from io import StringIO
import pandas as pd
from MSMetaEnhancer.libs.converters.web.WebConverter import WebConverter
class NLM(WebConverter):
"""
National Library of Medicine databases give access to structure and
nomenclature authority files used to identify chemical substances.
Available online a... |
from datetime import date
from io import StringIO
from account_tools.provider.unified import *
def test_write_unified_format():
"""
Test that writing a single unified record produces the output expected
"""
ostream = StringIO()
unified_record = StatementEntry(date(1970, 1, 1), '1 JAN 70 FOOBAR LT... |
# -*- coding:utf-8 -*-
import os
import catsup.parser
from catsup.options import g
from catsup.reader import txt_reader
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
def test_post_permalink():
post_path = os.path.join(BASE_DIR, "post.txt")
post = txt_reader(post_path)
g.config = catsup.parser.c... |
import cv2
import os
import numpy as np
import pickle
from dataset_preparation import mean_method,load_pickle
from tqdm import tqdm
# ----- grid size adjusting ----- #
def grid_adjust(init_grid, im_shape):
h_im, w_im = im_shape
if len(init_grid) == 1:
grid = (init_grid[0], init_grid[0])
ret... |
from django.urls import path
from .views import download_video
urlpatterns = [
path('', download_video)
]
|
a = 9
b = source(a)
c = s(b)
d = z(c)
e = function(d) |
import tkinter as tk
class MenuItem(tk.Menubutton):
def __init__(self, master, text, command, *args, **kwargs):
super().__init__(master, *args, **kwargs)
self.base = master.base
self.master = master
self.config(text=text, anchor=tk.W, font=("Segoe UI", 10),
... |
gradePoints = {'A': 4, 'B': 3, 'C': 2, 'D': 1, 'F': 0}
N = int(input())
print(sum(gradePoints[r] for r in input()) / N)
|
#!/usr/bin/env python3
import argparse
from enum import Enum
from functools import reduce
class OutputFormat(Enum):
COE = 1
HEX = 2
BINARY = 3
class Ops(Enum):
SL = 0
SR = 1
NOT = 2
AND = 3
OR = 4
XOR = 5
ADD = 6
SLT = 7
LW = 8
SW = 9
LI = 10
LUI = 11
J... |
import sys, subprocess
import re
def run_dot(dot):
from IPython.display import SVG
dot = dot.encode('utf8')
process = subprocess.Popen(['dot', '-Tsvg'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subpr... |
# Copyright 2018 Morningstar 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 ag... |
import random
import axelrod as axl
import numpy as np
import opt_mo
def test_get_repeat_length_in_history_with_single_element():
history_with_single_element_cycle = (
np.array([0.3, 0.4, 0.3, 0.3]),
np.array([0.3, 0.7, 0.3, 0.8]),
np.array([0.3, 0.4, 0.3, 0.3]),
np.array([0.3, 0... |
# coding: utf-8
import gensim
import math
from copy import copy
from math import log,sqrt
from collections import defaultdict
'''
(f) helper class, do not modify.
provides an iterator over sentences in the provided BNC corpus
input: corpus path to the BNC corpus
input: n, number of sentences to retrieve (optional, sta... |
from django.apps import AppConfig
class IrodsbackendConfig(AppConfig):
name = 'irodsbackend'
|
from django.urls import path
from . import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('home/', views.home, name='home'),
path('logout/', views.logout, name='logout'),
path('', views.login, name='login'),
]
urlpatterns += static(settings.MEDIA_URL... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.