content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
#https://codeforces.com/problemset/problem/9/C
#failed @ 100
def f(n):
m = n
k = 0
s = 0
while m>0:
m = m//10
k += 1
s = s*10 + 1
return (2**k)-(1 if n>=s else 2)
n = int(input())
print(f(n))
|
from moto import mock_dynamodb2
import io
from parent import ParentTest
from tests.guest_helper import save_guest, list_guests, clear_all_guests, EXAMPLE_GUEST_1, EXAMPLE_GUEST_2, INVALID_GUEST
import test_csvhandler
@mock_dynamodb2
class TestAdminCSVHandling(ParentTest):
def create_app(self):
app = Pare... |
class Solution:
def search(self, reader, target):
"""
:type reader: ArrayReader
:type target: int
:rtype: int
"""
hi = 1
while reader.get(hi) < target:
hi <<= 1
lo = hi >> 1
while lo <= hi:
mid = (lo + hi) >> 1
... |
import numpy as np
import os.path as osp
from gym import utils
from brl_gym.wrapper_envs.bayes_env import BayesEnv
from brl_gym.wrapper_envs.env_sampler import DiscreteEnvSampler
from brl_gym.envs.mujoco.point_mass import PointMassEnv
from brl_gym.envs.mujoco.point_mass_slow import PointMassSlowEnv
from brl_gym.envs.m... |
from pathlib import Path
def part_one(filename='input.txt'):
"""[summary]
Parameters
----------
filename : str, optional
[description], by default 'input.txt'
Returns
-------
[type]
[description]
"""
lines = Path(filename).read_text().split('\n')
valid_passwo... |
'''
实验名称:点亮LED灯
版本:v1.0
日期:2021.4
作者:01Studio
社区:www.01studio.org
实验平台:01Studio - 达芬奇
'''
#导入Pin模块
from machine import Pin
LED = Pin('C7', Pin.OUT) #构建LED对象
LED.value(1) #点亮LED,高电平点亮 |
from leapp.exceptions import StopActorExecutionError
from leapp.libraries.stdlib import api
# The devel variable for target product channel can also contain 'beta'
SUPPORTED_TARGET_CHANNELS = {'ga', 'tuv', 'e4s', 'eus', 'aus'}
def get_env(name, default=None):
"""Return Leapp environment variable value if matche... |
import os
import shutil
import sys
import tempfile
from unittest import TestCase
from aws_lambda_builders.builder import LambdaBuilder
from aws_lambda_builders.exceptions import WorkflowFailedError
class TestPythonPipWorkflow(TestCase):
"""
Verifies that `python_pip` workflow works by building a Lambda that... |
version = '0.0.7'
time = '2021-10-22 16:08:00'
|
from dataclasses import dataclass, field
from typing import List, Optional, Union
from bindings.wfs.abstract_adhoc_query_expression import AbstractAdhocQueryExpression
from bindings.wfs.abstract_query_expression import AbstractQueryExpression
from bindings.wfs.base_request_type import BaseRequestType
from bindings.wfs.... |
from gensim.models import Word2Vec
from sklearn.manifold import TSNE
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
def tsne_plot_similar_words(title, labels, embedding_clusters, word_clusters, a, filename=None):
plt.figure(figsize=(16, 9))
colors = cm.rainbow(np.linspace(0, 1, l... |
import tensorflow as tf
from keras.engine import Layer
from keras.layers import *
from bilinear_upsampling import BilinearUpsampling
import config
from custom_ops import BatchNorm3d, InstanceNorm5d
PADDING = "SAME"
DATA_FORMAT="channels_last"
class BatchNorm(BatchNormalization):
def call(self, inputs... |
# Note lengths
L1 = 24*4
L2 = L1/2
L4 = L1/4
L8 = L1/8
L16 = L1/16
L32 = L1/32
# Defaults
DEFAULT_VELOCITY=127
DEFAULT_NOTE_LENGTH=L4
|
text = """
(function($) {
$(function() {
queryProgress("a9463d8b340d466b8b1dc973b7549c60");
});
function queryProgress(progressId) {
$.get( $ctx + "/progressManager.jsp?progressId=" + progressId, function(data) {
if (!data) {
$("#progress").text("无任务!");
} else if (data.finished) {
... |
from tensorflow import keras
from tensorflow.keras import layers
def EVT(nin, hidden_sizes, nout):
input_layer = [layers.Input(shape=nin)]
hidden_layers = [layers.Dense(hidden_sz, activation='tanh',
kernel_initializer='he_normal') for hidden_sz in hidden_sizes]
output_layer... |
import requests
import bs4
import string
import random
from multiprocessing.dummy import Pool
def get_response(code):
response = requests.get(
"https://gpay.app.goo.gl/" + code)
if "Dynamic Link Not Found" in response.text:
return
html = bs4.BeautifulSoup(
response.text, features=... |
import os
import zipfile
import zlib
def make_rel_archive(a_parent, a_name):
archive = zipfile.ZipFile("build/" + a_name + ".zip", "w", zipfile.ZIP_DEFLATED)
def do_write(a_relative):
archive.write(a_parent + a_relative, a_relative)
do_write("SKSE/Plugins/" + a_name + ".dll")
do_write("SKSE/Plugins/" + a_name +... |
'''
This module creates a web map. The web map displays information
about the locations of films that were shot in a given year.
'''
from flask import Flask, render_template, request
import tweepy, folium, certifi, ssl
import geopy.distance
from geopy.distance import geodesic
from geopy.exc import GeocoderUnavailable
... |
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root
# for full license information.
# ==============================================================================
import numpy as np
import os
import sys
import signal
import subprocess
import re
... |
import demistomock as demisto
from CommonServerPython import *
from datetime import datetime, date
import boto3
from botocore.config import Config
from botocore.parsers import ResponseParserError
import urllib3.util
# Disable insecure warnings
urllib3.disable_warnings()
# Initiating params object for efficiency
param... |
class RecipOperations():
def __init__(self):
pass
@recip_logging
def send_recip_accept_response(self, string):
### <-------- Inbound from Server
print(string, end="")
choice = input("(Y/N)? ")
if choice.lower() == "y":
print("Send accepted.")
e... |
number = int(input())
sum = 0
for x in range(number):
number = int(input())
sum += number if (number % 2) == 0 else 0
print(sum,end="")
|
from omegaconf import OmegaConf
import pandas as pd
def flatten_configdict(
cfg: OmegaConf,
sep: str = ".",
):
cfgdict = OmegaConf.to_container(cfg)
cfgdict = pd.json_normalize(cfgdict, sep=sep)
return cfgdict.to_dict(orient="records")[0]
|
import unittest
import dataimports.livneh as livneh
class livnehtests(unittest.TestCase):
def test_livnehfilepaths(self, dir: str = 'C:/testexample/livneh/daily/', yr: list = ['1997'], var: list = ['prec']):
actual: list = livneh.inputfilepaths(dir, var, yr)
expected: list = [ 'C:/testexample/livn... |
### Examples of PS2 functions ###
### User guide at http://www.mindsensors.com/index.php?module=documents&JAS_DocumentManager_op=list
import nxt.locator, time
from nxt.sensor import *
b = nxt.locator.find_one_brick()#find brick and connect
s = MSPS2(b, PORT_1) #which sensor, brick and port
s.command(s... |
from netopsauto.juniper import Juniper
from pprint import pprint
switch = Juniper("host_name", "host_address", "user", "password")
# We can optionally call initialize_device() to directly utilize the PyEZ Device instance
dev = switch.initialize_device()
dev.open()
pprint(dev.facts)
dev.close()
# p... |
"""
Airbyte's implementation of this connector has been an important source of information
in the process of building this EWAH connector. Check out Airbyte for more info!
"""
from ewah.hooks.base import EWAHBaseHook
from datetime import datetime
import urllib.parse
import pendulum
import hashlib
import hmac
import b... |
'''
Um supermercado está fazendo uma promoção de venda de refrigerantes. Se um dia você comprar refrigerantes e levar os cascos vazios no dia seguinte, ela troca cada conjunto de K garrafas vazias por uma garrafa cheia. Um cliente quer aproveitar ao máximo essa oferta e por isso comprou várias garrafas no primeiro dia... |
'''OpenGL extension VERSION.GLES1_1_0
This module customises the behaviour of the
OpenGL.raw.GLES1.VERSION.GLES1_1_0 to provide a more
Python-friendly API
The official definition of this extension is available here:
http://www.opengl.org/registry/specs/VERSION/GLES1_1_0.txt
'''
from OpenGL import platform, constant... |
"""
Simple calendar using ttk Treeview together with calendar and datetime
classes.
"""
import calendar
import datetime
import tkinter as tk
import tkinter.font
from tkinter import ttk
from tkinter.messagebox import showwarning
def get_calendar(locale, fwday):
# instantiate proper calendar class
if locale is ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.cvalues import cvalues
def test_cvalues():
"""Test module cvalues.py by downloading
cvalues.csv and testing shape of
extracted data has 9 ... |
import aio_pika
from typing import Callable, Any, Optional, Union, Coroutine
from ._incoming_outgoing import Incoming, Outgoing
ProcessorType = Union[
Callable[[Incoming], Coroutine[Any, Any, None]],
Callable[[Incoming, Optional[Outgoing]], Coroutine[Any, Any, None]],
]
WrappedProcessorType = Callable[[aio_p... |
from .filter import Filter
from .simple import Simple
from .table import Table
from .free import Free
from .macros import Macros
from .widget import Widget |
expected_output = {
"instance":{
"default":{
"vrf":{
"EVPN-BGP-Table":{
"address_family":{
"l2vpn evpn":{
"prefixes":{
"[2][20.0.101.1:10][0][48][188B9D501231][0][*]/20":{
... |
# Imports the Google Cloud client library
from google.cloud import storage
# Instantiates a client
storage_client = storage.Client()
# The name for the new bucket
bucket_name = 'yamagiwa'
# Creates the new bucket
bucket = storage_client.create_bucket(bucket_name)
print('Bucket {} created.'.format(bucket.name))
|
from operator import itemgetter
import requests
from bs4 import BeautifulSoup
from classes import Cache
import re
class Cabmin:
__page_num = 0
__stop_num = "675"
__raw_article = True
__search_words = ['virus', 'yolux', 'covid', 'karantin', 'xəstə']
__cache_ttl = 240 * 60
__cache_file = 'cache... |
import os
import logging
import pytest
from optimus.setup_project import setup_project
from optimus.conf.loader import import_project_module
def test_dummy_valid(caplog, fixtures_settings, reset_syspath):
"""
Import valid module from sample dummy package
"""
basedir = os.path.join(fixtures_settings.... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: github.com/metaprov/modelaapi/services/data/v1/data.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import r... |
import math
import numpy as np
import random as random
import matplotlib.pyplot as plt
from matplotlib import colors
#The function below is to create the grid of our gas, the argument "n" is about number of particles we want inside our grid
#"dim" is an argument about the dimension of our grid, it's supposed ... |
import os
import pathlib
from urllib.parse import urljoin
from datetime import datetime
import fire
import requests
from bs4 import BeautifulSoup
from frictionless import Package
from collector.tools import content_updated
class Collect:
@staticmethod
def run():
base_dir = pathlib.Path(__file__).abs... |
# from https://github.com/joeybose/pytorch-normalizing-flows
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from src.utils import get_device
class MaskedLinear(nn.Linear):
""" same as Linear except has a configurable mask on the weights """
def __init__(self, in_featur... |
import discord
from discord import utils
from discord.ext import commands
class Emoji(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.on_message_send(bot)
async def getemote(self, arg):
emoji = utils.get(self.bot.emojis, name=arg.strip(":"))
if emoji is not None:
... |
import os
import json
import logging
def get_database_uri():
"""
Initialized DB2 database connection
This method will work in the following conditions:
1) With DATABASE_URI as an environment variable
2) In Bluemix with DB2 bound through VCAP_SERVICES
3) With PostgreSQL running on the loca... |
#!/usr/bin/env python
import rospy
import tf
from flexbe_core import EventState
from flexbe_core.proxy import ProxyPublisher, ProxySubscriberCached
from std_msgs.msg import Bool
from robotis_controller_msgs.msg import StatusMsg
from math import pi, radians
from enum import IntEnum
# from manipulator_h_base_module_msg... |
from sqlalchemy import Column, ForeignKey, Integer, String
from wedc.infrastructure.database import dbase, session_scope, load_session
from wedc.domain.core.common import hash_helper
from wedc.domain.core.data.seed.seed_vector import generate_vector
class LabelledData(dbase):
__tablename__ = 'labelled_data'
... |
_DF_ = "/"
_BINANCE_MODULE_DIR_NAME_ = "Binance"
_KEYS_FILE_NAME_ = ".keys"
_KEYS_FILE_PATH_ = _BINANCE_MODULE_DIR_NAME_ + _DF_ + _KEYS_FILE_NAME_
_CONFIG_FILE_NAME_ = "bm.conf"
_ENTRY_TYPE_ = 0
_LOSE_TYPE_ = 1
_PROFIT_TYPE_ = 2
_INIT_STATE_ = 0
_WAITING_STATE_ = 1
_OPEN_STATE_ = 2
_FILLED_STATE_ = 3
_CANCELED_STAT... |
from datetime import datetime
import pytz
from dateutil.relativedelta import relativedelta
from django.conf import settings
from django.core.management.base import BaseCommand
from django.db.models import Q
from django.utils import timezone
from notifications_python_client import NotificationsAPIClient
from sso.user.... |
import numpy
'''
Time taken by brute force: 256^L (L being key length)
Time taken to find key length: 256*L
Time take to find key bytes or key: (256^2)*L
Linear in L
'''
'''
Question:
F96DE8C227A259C87EE1DA2AED57C93FE5DA36ED4EC87EF2C63AAE5B9A7EFFD673BE4ACF7BE8923CAB1ECE7AF2DA3DA44FCF7AE29235A24C963FF0DF3CA3599A70E5DA3... |
import http.client
from os import getenv
# import dotenv
from flask import json
# dotenv.load_dotenv()
# api_key = getenv('API_KEY')
class MainWallet():
def __init__(self):
self.key = ""
def initialize_wallet(self):
wallet_data = create_wallet(self.key)
print("Wallet-data: ", wallet_... |
# coding: latin-1
import odbc
cx = odbc.odbc("mysqlperso")
cur = cx.cursor()
cur.execute ("SELECT * from ELEVE")
for row in cur.fetchall () :
print [ str (r) for r in row ] |
from drawing import Drawing
from util import logger
landscape = (11.0 * 96, 8.5 * 96)
portrait = (8.5 * 96, 11.0 * 96)
drawing = Drawing('svg/xkcd.svg', landscape, center=True, resize=True)
print(drawing.preview()) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Friday December 4 2020
"""
#pip install keras (x)
#pip install tensorflow (x)
#pip install numpy (x)
#pip install SimpleITK (x)
#pip install pydot
import os
import time
import pandas as pd
import numpy as np
import SimpleITK as sitk
from sklearn.m... |
# Copyright 2020 The Forte Authors. 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 ... |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.6.0
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + pycharm={"name": "#%%... |
# Generated file, please do not change!!!
import re
import typing
import marshmallow
import marshmallow_enum
from commercetools import helpers
from ... import models
from ..common import ReferenceTypeId
from ..customer import AnonymousCartSignInMode
from .common import BaseResourceSchema, ReferenceSchema, ResourceId... |
import os
import torch
import mlflow
from typing import Tuple, Dict, Any, Sequence
import logging as log
from mlflow.models import Model
from .utils import get_value
from .signature import Signature
from .logging import MyMLFlowLogger
from src import ROOT_FOLDER
def mlflow_setup(
experiment_name:str,
input_d... |
import json
from django.template import Library
from django.urls import NoReverseMatch, reverse
from django.utils.encoding import force_text
from django.utils.html import conditional_escape, format_html
from django.utils.safestring import mark_safe
register = Library()
_js_escapes = {
ord('>'): '\\u003E',
or... |
from tkinter import *
def cal_func():
gui=Tk()
gui.geometry("330x350")
gui.title("NoobNote Calculator")
gui.iconbitmap("icon.ico")
gui.resizable(False, False)
gui.configure(bg="#282923")
def calc1():
b = txt1.get()
txt1.delete(0, END)
b1 = b + btn1["text"]
tx... |
# Copyright 2018 The TensorFlow Constrained Optimization Authors. 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
#
#... |
"""
Initially, there is a Robot at position (0, 0). Given a sequence of its moves,
judge if this robot makes a circle, which means it moves back to the original place.
The move sequence is represented by a string. And each move is represent by a
character. The valid robot moves are R (Right), L (Left), U (Up) and D (d... |
#!/usr/bin/env python3
"""ngsutils.py: NGS-specific functions to read csv or vcf files."""
import os
import errno
import pathlib
import pandas as pd
from utils import osutils, pdutils
chromo_list = [
'chr1', 'chr2', 'chr3', 'chr4', 'chr5', 'chr6', 'chr7',
'chr8', 'chr9', 'chr10', 'chr11', 'chr12', 'chr13',
... |
import inspect
import re
import pyfixtures
from typing import Any
from docutils.parsers.rst import directives
from sphinx.domains.python import PyFunction, PyObject
from sphinx.ext.autodoc import FunctionDocumenter
from sphinx.util.typing import OptionSpec
class FixtureDirective(PyFunction):
option_spec: OptionS... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2018-09-06 11:36
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('experiments', '0096_experiment_release_notes'),
]
operations = [
migrations... |
#!/usr/bin/python
#-*- coding: utf-8 -*-
import torch
import numpy
import random
import pdb
import os
import threading
import time
from queue import Queue
import pdb
from dataLoader import *
class DatasetLoader(object):
def __init__(self, dataset_file_name, nPerEpoch, nBatchSize, maxFrames, nDataLoaderThread, maxQ... |
from sinling import SinhalaTokenizer
tokenizer = SinhalaTokenizer()
sentence = 'එච්.ආර්.ජෝතිපාල'
s = tokenizer.tokenize(sentence)
print(s)
from SinhalaStemming import sinhalaStemmer
from SinhalaStemming import sinhalaStemmer
testx = sinhalaStemmer.stemmer()
print(testx) |
#!/usr/bin/env python
import logging
import re
import time
from itertools import product
from os import getenv
from pathlib import Path
from typing import List, Set
import sentry_sdk
import spacy
from flask import Flask, request, jsonify
from spacy.tokens import Doc, Token
sentry_sdk.init(getenv("SENTRY_DSN"))
log... |
# @Author: Daniil Maslov (ComicSphinx)
import sqlite3
from datetime import datetime as dt
tableName = " records "
def main():
connection = sqlite3.connect('database.db')
cursor = connection.cursor()
cursor.execute(buildInsert("Demo", 60))
cursor.execute(buildInsert("Demonstration", 120))
connectio... |
from .engine import PlottingEngine, PlottingFigure, PlottingLayout
import plotly
from plotly.graph_objs import Scatter, Scatter3d, Layout, Data
import numpy as np
class PlotlyFigure(PlottingFigure):
def __init__(self, title=None, layout=PlottingLayout(), logx=False, logy=False, save_to_pdf=False):
self.ini... |
from django import forms
class AddDiscountForm(forms.Form):
_selected_action = forms.CharField(widget=forms.MultipleHiddenInput)
discount = forms.IntegerField(max_value=99, min_value=0) |
import logging
import time
from collections import deque
from datetime import datetime, timedelta
import numpy as np
import opendssdirect as dss
import pandas as pd
from PyDSS.common import DATE_FORMAT, TIME_FORMAT
from PyDSS.simulation_input_models import SimulationSettingsModel
logger = logging.getLogger(__name_... |
# https://www.codewars.com/kata/60a516d70759d1000d532029/train/python
def survivors(list_of_momentum, list_of_powerups):
output = []
i = 0
for momentum, powerups in zip(list_of_momentum, list_of_powerups):
if momentum <= 0:
i = i + 1
continue
isS... |
from MssqlContainer import MssqlContainer
from RedisContainers import RedisContainers, RedisContainer
|
#!/usr/bin/env python
"""
Publishes the joint state message for one arm from the simulation
computer to another computer (or series of computers).
Copyright 2018-2020 University of Cincinnati
All rights reserved. See LICENSE file at:
https://github.com/MatthewVerbryke/rse_dam
Additional copyright may be ... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy.integrate import odeint
import time as pctime
# load data
print('Loading data')
data = pd.read_csv('https://github.com/pcm-dpc/COVID-19/raw/master/dati-andamento-nazionale/dpc-covid19-ita-andamento-nazionale.csv')
xdata=pd.to_numeric... |
import global_variables as G
import chess
import time
times = []
def game_gui_string_list(game, offset=0, firstMoveOfVariation=False, firstMoveAfterVariation=False, indentationLevel=0):
strings = []
indentation_width = 4 # Set constant for now
# Form string
if game == game.root():
# Root node
... |
from django.urls import path
from django.conf import settings
from django.contrib.auth import views as auth_views
from .views import profile
urlpatterns = [
path('login/',
auth_views.LoginView.as_view(
extra_context={'next': settings.MAIN_PAGE}),
name='login',
),
path('... |
import os
import tempfile
import unittest
import pandas as pd
from smac.callbacks import IncorporateRunResultCallback
from smac.optimizer.smbo import SMBO
from smac.runhistory.runhistory import RunInfo, RunValue
from smac.tae.base import StatusType
import autosklearn.pipeline.util as putil
from autosklearn.classifica... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
from sklearn.model_selection import train_test_split
# In[2]:
import os
os.chdir('/Users/rushilnandandubey/Documents/Fall2020/CS-695(NLP)/Final/dumpp')
# In[3]:
os.listdir()
# In[4]:
file1 = open('sourcestring.txt', 'r')
Lines = file1.readlines()
# In[5]... |
"""Common get functions for version"""
# Python
import re
import time
import logging
# Genie
from genie.metaparser.util.exceptions import SchemaEmptyParserError
log = logging.getLogger(__name__)
def get_hostname(
device,
):
""" Get the hostname from 'show version'
Args:
device ('obj'): ... |
from flask_restful import reqparse, abort, Resource
from flask import jsonify
from data.__all_models import User
from data.db_session import create_session
parser = reqparse.RequestParser()
parser.add_argument('name', required=True)
parser.add_argument('surname', required=True)
parser.add_argument('age', required=Tru... |
import logging
import os
from datetime import datetime
from threading import Thread
import requests
from dotenv import load_dotenv
from app.config import ORDERS_CHANNEL
from app.config.basecontainer import BaseContainer
load_dotenv()
PUSHOVER_URL = os.getenv("PUSHOVER_URL")
PUSHOVER_TOKEN = os.getenv("PUSHOVER_TOKE... |
import pytest
import tempfile
from pathlib import Path
from .mock.cache import create_test_cachefile, get_cachefile_template
@pytest.fixture(scope="module")
def cachefile0():
"create a temporary cachefile0 different to, but fully consistent with cachefile1"
settings = get_cachefile_template()[0]
with temp... |
"""
Tests for the course indexer
"""
# pylint: disable=too-many-lines
import json
import uuid
from types import SimpleNamespace
from unittest.mock import patch
from django.conf import settings
from django.forms import ChoiceField, MultipleChoiceField
from django.http.request import QueryDict
from django.test import Te... |
from SimGeneral.TrackingAnalysis.trackingParticles_cfi import *
mergedtruth.HepMCDataLabels = ['hiSignal', 'generatorSmeared']
mergedtruth.useMultipleHepMCLabels = True
|
# -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from drf_yasg.utils import swagger_auto_schema
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.response import Response
from apps.keyboard import models
from apps.keyboard.handler import d... |
import math
from . import *
@speedo.on(Speedo_cmd(pattern="sin ?(.*)"))
@speedo.on(sudo_cmd(pattern="sin ?(.*)", allow_sudo=True))
async def findsin(event):
input_str = int(event.pattern_match.group(1))
output = math.sin(input_str)
await event.edit(f"**Value of Sin** `{input_str}`==\n`{output}`")
@speed... |
# "noqa" setting stops flake8 from flagging unused imports in __init__
from ._version import __version__ # noqa: F401
from ._start import start # noqa: F401
from ._name import SERVICE_NAME # noqa: F401
|
import requests
import json
import sys
import time
from datetime import date
from settings.app_config import AppConfig
from utilities.console_manager import ConsoleManager
class WebClient(object):
base_url = "n/a"
def __init__(self):
self.base_url = Config().get_integration_api_base_url()
def sh... |
# Before execute run
# pip install -U spacy
# python -m spacy download pt
__author__ = "Otacilio Maia"
__version__ = "1.0.0"
import spacy
nlp = spacy.load('pt')
my_doc = nlp('O S.E.C. é um evento incrível!')
for token in my_doc:
print(token, token.pos_)
# ADJ: adjective
# ADP: adposition
# ADV: adverb
# AUX: a... |
from __future__ import print_function
from subprocess import Popen, PIPE
import pytest
@pytest.mark.parametrize("cmd", [
'clean',
'clobber',
'build',
])
def test_projdir_not_detected(tmpdir, cmd):
with tmpdir.as_cwd():
p = Popen(['jmdwebsites', cmd], stdout=PIPE, stderr=PIPE)
out, err... |
# -*- coding: utf-8 -*-
"""
:time: 2021/2/23 16:16
:author: Harumonia
:url: http://harumonia.moe
:project: Christin
:file: ingredient.py
:copyright: © 2021 harumonia<zxjlm233@gmail.com>
:license: MIT, see LICENSE for more details.
"""
from wtforms import Form, StringField, FloatField
clas... |
# -*- coding: utf-8 -*-
from GUI.gui import event, w
from GUI.key import *
from GUI.change import change
from GUI.button import save, new, clear
import MyLib.sql as sql
def attr_event():
# list
if event['c'] == attr['list']:
get(sql.row_read_attr('attr', event['d'][attr['list']][0]))
# button
... |
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.conf import settings
from django.dispatch import receiver
from django.db.models.signals import post_save
from django.utils.translation import gettext_lazy as _
# Create your models here.
class User(AbstractUser) :
cla... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Alex
# @Date: 2015-11-16 19:14:39
# @Last Modified by: harmenta
# @Last Modified time: 2015-11-23 10:54:45
from django.db import models
from Inventationery.apps.DirParty.models import DirPartyModel
from Inventationery.core.models import TimeStampedModel
# C... |
#Jogo criado por Gabriel Chiarelli - 30/03/2022
from random import randint # importa a função 'randint' do módulo 'random'
from time import sleep # importa a função 'sleep' do módulo 'time'
opcao = 'S... |
from aws_lambda_decorators import cors, log, response_body_as_json
from src.common import hello_func
@cors()
@log(parameters=True, response=True)
@response_body_as_json
def handler(event, context): # pylint:disable=unused-argument
return {
"statusCode": 200,
"body": hello_func("a_lambda")
}
|
#!/usr/bin/env python
"""
This script starts a process locally, using <client-id> <hostfile> as inputs.
"""
import os
from os.path import dirname
from os.path import join
import time
import sys
if len(sys.argv) != 3:
print "usage: %s <client-id> <hostfile>" % sys.argv[0]
sys.exit(1)
# Please set the absolute pa... |
from datetime import datetime, timedelta
from celery.task import task
from django.dispatch import receiver
from django.test import override_settings
from freezegun import freeze_time
from freezegun.api import FakeDatetime
from tardis.signals import travel_started, travel_step_completed
class Tardis(object):
def... |
from veroviz._common import *
from veroviz._internal import loc2Dict
from veroviz.utilities import initDataframe
from veroviz._internal import replaceBackslashToSlash
def privAddStaticAssignment(initAssignments=None, odID=1, objectID=None, modelFile=None, modelScale=VRV_DEFAULT_CESIUMMODELSCALE, modelMinPxSize=VRV_DEF... |
from django.db import models
from genui.compounds.extensions.fileimports.model import FileCompounds
from genui.compounds.models import Molecule
class CSVCompounds(FileCompounds):
nameCol = models.CharField(max_length=256, null=True, default='NAME', blank=False)
smilesCol = models.CharField(max_length=256, nu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.