content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
ACTION_CLEAN = 'clean'
ACTION_CREATE_USERDEF = 'createuserdef'
ACTION_PREPARE = 'prepare'
ACTION_BUILD = 'build'
ACTION_BACKUP = 'backup'
ACTION_CREATE_NUGET = 'createnuget'
ACTION_PUBLISH_NUGET = 'publishnuget'
ACTION_UPDATE_SAMPLE = 'updatesample'
ACTION_RELEASE_NOTES = 'releasenotes'
ACTION_UPLOAD_BACKUP = 'uploadb... | python |
# AI_Javaher
# this is the first session of GDAL/OGR tutorial
# install GDAL video : https://www.youtube.com/watch?v=YsdHWT-hA4k&list=PLFhf3UaNX_xc8ivjt773rAjGNoAfz_ELm&index=2
# check the video of this code in youtube :https://www.youtube.com/watch?v=F1jaX9vmhIk
# you can find the list of videos about GDAL tutorial in... | python |
# Builtin
import os
import unittest
# Internal
from nxt import stage, nxt_layer
class TestReferences(unittest.TestCase):
def test_reference_by_path(self):
test_dir = os.path.dirname(__file__)
empty_path = os.path.join(test_dir, 'empty.nxt')
pre_test = stage.Stage.load_from_filepath(empty_... | python |
from Utilities import *
def convert_type(in_type: str) -> str:
if in_type == 'bit':
return 'boolean'
if in_type == 'datetime':
return 'Date'
if in_type == 'mediumtext':
return 'String'
if in_type == 'nonnegativeinteger':
return 'int'
if in_type == 'phone':
r... | python |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^(?P<pk>[0-9]+)$', views.DocumentDetailView.as_view(), name='document_detail'),
url(r'^create/$', views.DocumentCreate.as_view(), name='document_create'),
url(r'^update/(?P<pk>[0-9]+)$', views.DocumentUpdate.as_view(), name='docume... | python |
from django.db import models
class StatisticsMemory(models.Model):
value = models.FloatField()
| python |
""" AUTHTAB.DIR file parser. """
from pybycus.file import File
class AuthTab(File):
""" The Author List (with the filename AUTHTAB.DIR) contains
descriptive information for each text file on the disc. The
purpose of the Author Table is to allow the user to ask for
the author Plato, for example, withou... | python |
"""
Get an admin token for KeyCloak.
"""
import logging
from functools import partial
import requests
from rest_tools.server import from_environment
from rest_tools.client import RestClient
def get_token(url, client_id, client_secret, client_realm='master'):
url = f'{url}/auth/realms/{client_realm}/protocol/open... | python |
import scrapy
import codecs
import re
import json
from ..items import WebcrawlerItem
def unmangle_utf8(match):
escaped = match.group(0) # '\\u00e2\\u0082\\u00ac'
hexstr = escaped.replace(r'\u00', '') # 'e282ac'
buffer = codecs.decode(hexstr, "hex") # b'\xe2\x82\xac'
try:
... | python |
raise ValueError('character must be a single string')
raise ValueError('width must be greater than 2')
try
....
except ValueError as err:
print(str(err))
# if we want to log errors that are not crashers:
import traceback
now = datetime.datetime.now()
now = now.strftime('%Y-%m-%d %H:%M:%S')
except:
err... | python |
## predict iris dataset
## imports
import numpy as np
import pandas as pd
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
import neptune
import os
from dotenv import load_dotenv
load_dotenv()
## setup neptune account
NEPTUNE_API_KEY... | python |
# Generated by Django 3.2.12 on 2022-04-13 19:51
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('crypto', '0004_alert_user'),
]
operations = [
migrations.RenameField(
model_name='asset',
... | python |
# coding: utf-8
"""
ThingsBoard REST API
For instructions how to authorize requests please visit <a href='http://thingsboard.io/docs/reference/rest-api/'>REST API documentation page</a>. # noqa: E501
OpenAPI spec version: 2.0
Contact: info@thingsboard.io
Generated by: https://github.com/swagger-... | python |
import graphene
import pytest
from ....tests.utils import get_graphql_content
QUERY_GIFT_CARDS = """
query giftCards($filter: GiftCardFilterInput){
giftCards(first: 10, filter: $filter) {
edges {
node {
id
displayCode
}
... | python |
import sqlalchemy as sa
import aiopg.sa
meta = sa.MetaData()
question = sa.Table(
'question', meta,
sa.Column('id', sa.Integer, nullable=False),
sa.Column('question_text', sa.String(200), nullable=False),
sa.Column('pub_date', sa.Date, nullable=False),
# Indexes
sa.PrimaryKeyConstraint('id',... | python |
import json
import argparse
def main():
parser = argparse.ArgumentParser(description='Conversion IO')
parser.add_argument("--input_file", dest="input_file", type=argparse.FileType('r', encoding='UTF-8'), required=True)
parser.add_argument("--output_file", dest="output_file", type=argparse.FileType('w', enc... | python |
import xml.etree.ElementTree as ET
import sys
tree = ET.parse(sys.argv[1])
# the xml tree is of the form
# <expr><list> {all options, each an attrs} </list></expr>
options = list(tree.getroot().find('list'))
def sortKey(opt):
def order(s):
if s.startswith("enable"):
return 0
if s.start... | python |
from typing import Tuple, Union
import torch
def make_dense_volume(
ind: torch.Tensor,
voxel_res: Union[int, Tuple[int, int, int]]
) -> torch.Tensor:
if isinstance(voxel_res, int):
voxel_res = (voxel_res, voxel_res, voxel_res)
grid = torch.zeros(voxel_res, dtype=torch.bool)
grid[ind[:, ... | python |
import os
from django.http import FileResponse
from wsgiref.util import FileWrapper
from settings.static import MEDIA_URL
# from django.core.servers.basehttp import FileWrapper
from django.views.generic import TemplateView
from django.shortcuts import render_to_response, render, redirect, get_object_or_404
from django.... | python |
from functools import cached_property
from ..typing import TYPE_CHECKING, Any, Callable, Catchable
if TYPE_CHECKING:
from .fn import fn
def as_method(method, name):
method.__name__ = name
method.__qualname__ = f"fn.{name}"
method.__doc__ = "Auto generated, see :func:`sidekick.functions.{name}`"
... | python |
import requests
from typing import Dict, NamedTuple, NoReturn
from bs4 import BeautifulSoup
class WorkshopError(Exception):
def __init__(self, error: str):
self.error = error
def __str__(self) -> str:
return self.error
class Script(NamedTuple):
"""Encapsulate a numworks workshop pyth... | python |
import json
import os
import random
import bottle
from api import ping_response, start_response, move_response, end_response
@bottle.route('/')
def index():
return '''
Battlesnake documentation can be found at
<a href="https://docs.battlesnake.io">https://docs.battlesnake.io</a>.
'''
@bottle.route... | python |
import json
import itertools as it
from collections import defaultdict
import textwrap
from itertools import chain
COURSE_LIST_FILENAME = 'course_list.json'
REVERSE_KDAM_FILENAME = 'reverse_kdam.json'
REVERSE_ADJACENT_FILENAME = 'reverse_adjacent.json'
def read_json_to_dict(filename=COURSE_LIST_FILENAME):
with op... | python |
# -*- coding: utf-8 -*-
# created: 2021-06-22
# creator: liguopeng@liguopeng.net
import asyncio
from gcommon.aio.gasync import maybe_async
def sync_call():
print("sync")
return "1"
async def async_call():
await asyncio.sleep(1)
print("async")
return "2"
async def test():
r = await maybe_... | python |
# -*- coding: utf-8 -*-
from peewee import *
from telegram import User as TelegramUser
import util
from model.user import User
from model.basemodel import BaseModel
class APIAccess(BaseModel):
user = ForeignKeyField(User)
token = CharField(32)
webhook_url = CharField(null=True)
| python |
"""Module to test reset password"""
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from django.contrib.auth import get_user_model
from django.contrib.auth.tokens import default_token_generator
class ResetPassword(APITestCase):
def setUp(self):
... | python |
#!/usr/bin/env python3
import argparse
import logging
from pathlib import Path
import sys
from typing import Iterable
from typing import Union
import numpy as np
from espnet.utils.cli_utils import get_commandline_args
def aggregate_stats_dirs(
input_dir: Iterable[Union[str, Path]],
output_dir: Union[str, Pa... | python |
import argparse
import parmed as pmd
def merge_gro_files(prot_gro, lig_gro, cmplx_gro):
prot = pmd.load_file(prot_gro)
lig = pmd.load_file(lig_gro)
cmplx = prot + lig
cmplx.save(cmplx_gro)
def merge_top_files(prot_top, lig_top, cmplx_top):
with open(lig_top, 'r') as f:
lig_top_sections ... | python |
dictionary = {"name": "Shahjalal", "ref": "Python", "sys": "Mac"}
for key, value in dictionary.items():
print key, " = ", value
| python |
def get_sum_by_route(route_val, nums):
sum_val = nums[0][0]
j = 0
route=[sum_val]
for i in range(1, len(nums)):
if route_val % 2 > 0:
j+=1
sum_val += nums[i][j]
route.append(nums[i][j])
route_val >>= 1
return route, sum_val
s = """75
95 64
17... | python |
import numpy as np
from sort import algs
def test_bubblesort():
# 1) Test odd-sized vector + duplicate values
assert algs.bubblesort([1,2,4,0,1]) == [0,1,1,2,4]
# 2) Test even+duplicate values
assert algs.bubblesort([1,2,4,6,0,1]) == [0,1,1,2,4,6]
# 3) Test empty vector
assert algs.bubbleso... | python |
from service.resolver_base import ResolverBase
from service.rule_item_mutex import RuleItemMutex
# 6宫无马数独
# DB 互斥规则已写入
class Resolver1623(ResolverBase):
ANSWER_RANGE = ['1', '2', '3', '4', '5', '6']
def get_answer_range(self) -> []:
return Resolver1623.ANSWER_RANGE
def calculate_rules(self):
... | python |
from specusticc.data_preprocessing.preprocessed_data import PreprocessedData
from specusticc.model_testing.prediction_results import PredictionResults
class Tester:
def __init__(self, model, model_name: str, data: PreprocessedData):
self._model = model
self._data: PreprocessedData = data
s... | python |
from .encodeClass import encoderClass
from .decodeClass import decoderClass
| python |
import os
import uuid
from typing import Generator
from flask import current_app
from unittest import TestCase
from contextlib import contextmanager
from alembic import command
from sqlalchemy import create_engine
from {{ cookiecutter.app_name }} import app
from {{ cookiecutter.app_name }}.extensions import db
DATABA... | python |
# #https://docs.pytest.org/en/reorganize-docs/new-docs/user/assert_statements.html
# # Assertions are the condition or boolean expression which are always supposed to be true
# import pytest
# def vowels():
# return set('aeiou')
# @pytest.mark.skip
# def test_vowels():
# result = vowels()
# expected = se... | python |
#
# author: Jungtaek Kim (jtkim@postech.ac.kr)
# last updated: December 29, 2020
#
"""It is utilities for Gaussian process regression and
Student-:math:`t` process regression."""
import numpy as np
from bayeso.utils import utils_common
from bayeso import constants
@utils_common.validate_types
def get_prior_mu(prior... | python |
import rclpy,numpy,psutil
from rclpy.node import Node
from std_msgs.msg import Float32
class RpiMon(Node):
def __init__(self):
super().__init__('rpi_mon')
self.ramPublisher = self.create_publisher(Float32, 'freeram', 1)
timer_period = 2.0 # seconds
self.timer = self.create_timer(t... | python |
from libspn.inference.type import InferenceType
from libspn.graph.op.base_sum import BaseSum
import libspn.utils as utils
@utils.register_serializable
class Sum(BaseSum):
"""A node representing a single sum in an SPN.
Args:
*values (input_like): Inputs providing input values to this node.
... | python |
##############################################
##############################################
###### Predict the Bear ######################
# Flask app that uses a model trained with the Fast.ai v2 library
# following an example in the upcoming book "Deep Learning for Coders
# with fastai and PyTorch: AI Applications ... | python |
import numpy as np
from nexpy.gui.datadialogs import NXDialog, GridParameters
from nexpy.gui.utils import report_error
from nexusformat.nexus import NXfield, NXdata, NeXusError
from nexusformat.nexus.tree import centers
def show_dialog():
try:
dialog = ConvertDialog()
dialog.show()
except NeXu... | python |
from riemann.tx import tx_builder
from riemann import simple, script
from riemann import utils as rutils
from riemann.encoding import addresses
from workshop import crypto
from workshop.transactions import spend_utxo
from riemann import tx
'''
This is a hash timelock contract. It locks BTC until a timeout, or until ... | python |
#!/usr/bin/env python
# Part of sniffMyPackets framework.
# GeoIP Lookup modules to cut down on code changes.
import pygeoip
from canari.config import config
def lookup_geo(ip):
try:
# homelat = config['geoip/homelat'].strip('\'')
# homelng = config['geoip/homelng'].strip('\'')
db = conf... | python |
#python3 code
def count(i,s):
ans=0
for j in range(i,len(s)):
if(s[j]=="<"):
ans+=1
return ans
def higher(s):
res=0
for i in range(len(s)):
if(s[i]==">"):
b=count(i,s)
res=res+(b*2)
return res
def solution(s):
# Your code here
... | python |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... | python |
if x == 'none':
if False:
print('None')
elif x == None:
print('oh')
elif x == 12:
print('oh')
else:
print(123)
if foo:
foo()
elif bar:
bar()
else:
if baz:
baz()
elif garply:
garply()
else:
qux()
| python |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# 地址:http: //www.runoob.com/python/python-exercise-example70.html
if __name__ == "__main__":
# s = input("please input a string:\n")
s = "Hello World"
print("the string has %d characters." % len(s))
| python |
"""
Orchestrator module
"""
import logging
import os
import re
import shutil
import traceback
from functools import wraps
from glob import glob
from io import open
import six
from halo import Halo
from tabulate import tabulate
from toscaparser.common.exception import ValidationError
from yaml.scanner import ScannerErr... | python |
#############################################################################
#
# VFRAME
# MIT License
# Copyright (c) 2020 Adam Harvey and VFRAME
# https://vframe.io
#
#############################################################################
import click
from vframe.settings.app_cfg import VALID_PIPE_MEDIA_EXT... | python |
import os
import torch
import numpy as np
import warnings
try:
from typing import Protocol
except ImportError: # noqa
# Python < 3.8
class Protocol:
pass
from .dsp.overlap_add import LambdaOverlapAdd
from .utils import get_device
class Separatable(Protocol):
"""Things that are separatable.... | python |
import pickle
import brewer2mpl
import matplotlib
matplotlib.use("agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from absl import app, flags
from utils import *
FLAGS = flags.FLAGS
flags.DEFINE_string('base_dir', '', 'Path to the base dir where the logs are')
... | python |
# coding: utf-8
# # Table of Contents
# <p><div class="lev1 toc-item"><a href="#Blurring-a-part-of-an-image-in-Python" data-toc-modified-id="Blurring-a-part-of-an-image-in-Python-1"><span class="toc-item-num">1 </span>Blurring a part of an image in Python</a></div><div class="lev2 toc-item"><a href="#Blur... | python |
import json
import logging
import requests
from django.conf import settings
from django.contrib.auth.models import User
from rest_framework import status
class ExternalUmbrellaServiceAuthenticationBackend:
logger = logging.getLogger(__name__)
def get_user(self, user_id):
"""
Retrieve the use... | python |
# Copyright 2017,2018,2019,2020,2021 Sony Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | python |
from tclCommands.TclCommand import TclCommandSignaled
import collections
class TclCommandMirror(TclCommandSignaled):
"""
Tcl shell command to mirror an object.
"""
# array of all command aliases, to be able use
# old names for backward compatibility (add_poly, add_polygon)
aliases = ['mirror... | python |
import torch.nn as nn
from qanet.encoder_block import EncoderBlock
class ModelEncoder(nn.Module):
def __init__(self, n_blocks=7, n_conv=2, kernel_size=7, padding=3,
hidden_size=128, conv_type='depthwise_separable', n_heads=8, context_length=400):
super(ModelEncoder, self).__init_... | python |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def helper(self,root):
if not root:
return (0,0)
# get res from left
left=self.helper... | python |
#%load_ext autoreload
#%autoreload 2
from pathlib import Path
from pprint import pformat
from hloc import extract_features, match_features, localize_inloc, visualization
dataset = Path('datasets/inloc/') # change this if your dataset is somewhere else
pairs = Path('pairs/inloc/')
loc_pairs = pairs / 'pairs-query-n... | python |
from aws_cdk import (
aws_batch as _batch,
aws_ec2 as _ec2,
aws_iam as _iam,
core,
)
class BatchENV(core.Construct):
def getComputeQueue(self,queue_name):
return self.job_queue[queue_name]
def __init__(self, scope: core.Construct, id: str,CurrentVPC="default",TargetS3... | python |
from vyper import basebot
from vyper.web import interface
import os
class PluginBot(basebot.BaseBot):
def __init__(self, token, debug=False, start_loop=False, loop_time=.05, ping=True, list_plugins=False, web_app=None, name=None):
if not os.path.exists('plugins'):
os.mkdir('plugins')
with open('plugins/__init... | python |
import timeit
from copy import deepcopy
import time
import cProfile
import pstats
import numpy as np
from sympy import sin, symbols, Matrix, Symbol, exp, solve, Eq, pi, Piecewise, Function, ones
from CompartmentalSystems.moothmodel_run import SmoothModelRun
from CompartmentalSystems.smooth_reservoir_model import Smooth... | python |
from django.contrib import admin
from .models import User, Agent
class UserAdmin(admin.ModelAdmin):
list_display = ['username', 'is_agent', 'is_superuser']
admin.site.register(User, UserAdmin)
admin.site.register(Agent)
| python |
'''
'''
def main():
info('Pump Microbone After Jan diode analysis')
close(description="Jan Inlet")
close(description= 'Microbone to Minibone')
open(description= 'Microbone to Turbo')
open(description= 'Microbone to Getter NP-10H')
open(description= 'Microbone to Getter NP-10C')
o... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# script by Ruchir Chawdhry
# released under MIT License
# github.com/RuchirChawdhry/Python
# ruchirchawdhry.com
# linkedin.com/in/RuchirChawdhry
from subprocess import run
from prettytable import PrettyTable
# PS: This only works on macOS & Linux. It will not work on W... | python |
import os
import logging
from counterblock.lib import config
def set_up(verbose):
global MAX_LOG_SIZE
MAX_LOG_SIZE = config.LOG_SIZE_KB * 1024 #max log size of 20 MB before rotation (make configurable later)
global MAX_LOG_COUNT
MAX_LOG_COUNT = config.LOG_NUM_FILES
# Initialize logging (to file a... | python |
from getpass import getpass
from pprint import pprint
from datetime import datetime
from sqlalchemy import create_engine
from pydango import state
from pydango.switchlang import switch
from pydango import (
primary_func,
secondary_func
)
from pydango.primary_func import chunks
from pydango.primary_func imp... | python |
def _foo():
return "private" | python |
from collections import defaultdict
from itertools import islice
from typing import Dict, List, Optional, Sequence
import torch
from tango.common.dataset_dict import DatasetDictBase
from tango.common.exceptions import ConfigurationError
from tango.common.lazy import Lazy
from tango.common.tqdm import Tqdm
from tango.... | python |
import sproxel
from zipfile import ZipFile, ZIP_DEFLATED
import json
import os, sys
import imp
CUR_VERSION=1
def save_project(filename, proj):
# gather layers
layers=[]
for spr in proj.sprites:
for l in spr.layers:
if l not in layers: layers.append(l)
# prepare metadata
meta={... | python |
import uuid
from django.db import models
class Dice(models.Model):
sides = models.PositiveIntegerField()
class Roll(models.Model):
roll = models.PositiveIntegerField()
class DiceSequence(models.Model):
uuid = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=True, unique=True)
seq_n... | python |
class Solution(object):
def XXX(self, n):
"""
:type n: int
:rtype: str
"""
if not isinstance(n, int):
return ""
if n == 1:
return "1"
pre_value = self.XXX(n-1) # 递归
# 双指针解法
i = 0
res = ""
for ... | python |
# -*- coding: utf-8 -*-
from django.conf import settings
import requests
from sendsms.backends.base import BaseSmsBackend
TINIYO_API_URL = "https://api.tiniyo.com/v1/Account/SENDSMS_TINIYO_TOKEN_ID/Message"
TINIYO_TOKEN_ID = getattr(settings, "SENDSMS_TINIYO_TOKEN_ID", "")
TINIYO_TOKEN_SECRET = getattr(settings, "S... | python |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
import torch.nn as nn
from fairseq.models.transformer import TransformerEncoder
from .linformer_sentence_encoder_layer... | python |
# file arrange, remove, rename
import os
import astropy.io.fits as fits
def oswalkfunc():
f=open('oswalk.list','w')
#workDIr = os.path.abspath(b'.')
for root, dirs, files in os.walk('.'): # os.walk(".", topdown = False):
# all files with path names
for name in files:
#print(os.path.join(root, name))... | python |
from django.db import models
class TrackedModel(models.Model):
"""
a model which keeps track of creation and last updated time
"""
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
| python |
# -*- coding: utf-8 -*-
'''
Created by 15 cm on 11/22/15 3:20 PM
Copyright © 2015 15cm. All rights reserved.
'''
__author__ = '15cm'
import json
import urllib2
import multiprocessing
import numpy as np
from PIL import Image
import io
import os
CURPATH = os.path.split(os.path.realpath(__file__))[0]
DATAPATH = os.path.... | python |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from .pygame_component import Pygame
from .pygame_surface import PygameSurface
from .blit_surface import BlitSurface
from .blocking_pygame_event_pump import BlockingPygameEventPump
from .color_fill import ColorFill
from .draw_on_resi... | python |
#!/usr/bin/python
'''
(C) Copyright 2018-2019 Intel Corporation.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applic... | python |
from UE4Parse.BinaryReader import BinaryStream
class FPathHashIndexEntry:
FileName: str
Location: int
def __init__(self, reader: BinaryStream):
self.FileName = reader.readFString()
self.Location = reader.readInt32()
| python |
from typing import List
import cv2
from vision.domain.iCamera import ICamera
from vision.domain.iCameraFactory import ICameraFactory
from vision.infrastructure.cvCamera import CvCamera
from vision.infrastructure.cvVisionException import CameraDoesNotExistError
from vision.infrastructure.fileCamera import FileCamera
... | python |
import contextlib
import logging
import six
import py.test
_LOGGING_CONFIGURED_STREAM = None
@py.test.fixture(scope="session")
def streamconfig():
global _LOGGING_CONFIGURED_STREAM
if not _LOGGING_CONFIGURED_STREAM:
_LOGGING_CONFIGURED_STREAM = six.StringIO()
logging.basicConfig(
... | python |
import re
# Solution
def part1(data, multiplier = 1):
pattern = r'\d+'
(player_count, marble_count) = re.findall(pattern, data)
(player_count, marble_count) = (int(player_count), int(marble_count) * multiplier)
players = [0] * player_count
marbles = DoubleLinkedList(0)
k = 0
for i in range(... | python |
# -*- coding: utf-8 -*-
import hexchat
import re
__module_name__ = "DeadKeyFix"
__module_version__ = "2.2"
__module_description__ = "Fixes the Us-International deadkey issue"
prev = ''
def keypress_cb(word, word_eol, userdata):
global prev
specialChars = {
'65104': {
'a': u'à',
'o': u'ò',
'e': u'è',
... | python |
import FWCore.ParameterSet.Config as cms
process = cms.Process("TREESPLITTER")
process.source = cms.Source("EmptySource")
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(0)
)
process.TreeSplitterModule = cms.EDAnalyzer(
"TreeSplitter",
InputFileName = cms.string("/afs/cern.ch/user/d/... | python |
# This is an automatically generated file.
# DO NOT EDIT or your changes may be overwritten
import base64
from xdrlib import Packer, Unpacker
from .ledger_close_value_signature import LedgerCloseValueSignature
from .stellar_value_type import StellarValueType
from ..exceptions import ValueError
__all__ = ["StellarValu... | python |
import setuptools
def get_requires(filename):
requirements = []
with open(filename) as req_file:
for line in req_file.read().splitlines():
if not line.strip().startswith("#"):
requirements.append(line)
return requirements
with open("Readme.md", "r", encoding="utf8") a... | python |
REGISTRY = {}
from .sc_agent import SCAgent
from .rnn_agent import RNNAgent
from .latent_ce_dis_rnn_agent import LatentCEDisRNNAgent
REGISTRY["rnn"] = RNNAgent
REGISTRY["latent_ce_dis_rnn"] = LatentCEDisRNNAgent
REGISTRY["sc"] = SCAgent
| python |
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the Apache License Version 2.0.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied... | python |
# -*- coding: utf-8 -*-
#
# Copyright 2017 CPqD. 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 requi... | python |
#
# @lc app=leetcode id=160 lang=python3
#
# [160] Intersection of Two Linked Lists
#
# https://leetcode.com/problems/intersection-of-two-linked-lists/description/
#
# algorithms
# Easy (39.05%)
# Likes: 3257
# Dislikes: 372
# Total Accepted: 438K
# Total Submissions: 1.1M
# Testcase Example: '8\n[4,1,8,4,5]\n[5... | python |
def dividend(ticker_info):
for ticker, value in ticker_info.items():
value_dividends = value["dividends"].to_frame().reset_index()
dividend_groupped = value_dividends.groupby(value_dividends["Date"].dt.year)['Dividends'].agg(['sum'])
dividend_groupped = dividend_groupped.rename(c... | python |
import markdown
from flask import abort, flash, redirect, render_template, request
from flask_babel import gettext as _
from flask_login import current_user, login_required
from ..ext import db
from ..forms.base import DeleteForm
from ..models import Brew, TastingNote
from ..utils.pagination import get_page
from ..uti... | python |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
from collections import OrderedDict
from teach.dataset.actions import (
Action_Audio,
Action_Basic,
Action_Keyboard,
Action_MapGoal,
Action_Motion,
Action_ObjectInteraction,
Action_Progres... | python |
import collections
import pathlib
import sys
import os
import json
def as_dict(par):
if not par:
return None
if isinstance(par, dict):
return par
else:
return dict(par._asdict())
def from_dict(par_dict):
if not par_dict:
return None
# par = collections.namedtuple(... | python |
import unittest
import ServiceGame
from model.Platform import platform
from model.Publishers import publisher
class TestServiceGame(unittest.TestCase):
def test_games_Wii(self):
wiigames = ServiceGame.platz(platform('Wii'))
self.assertEqual(15, len(wiigames))
def test_games_PC(self):
... | python |
from robot_server.service.errors import RobotServerError, \
CommonErrorDef, ErrorDef
class SystemException(RobotServerError):
"""Base of all system exceptions"""
pass
class SystemTimeAlreadySynchronized(SystemException):
"""
Cannot update system time because i... | python |
from flask import Flask, redirect, render_template, url_for
from flask_pymongo import PyMongo
import scrape_mars
app = Flask(__name__)
mongo=PyMongo(app, uri="mongodb://localhost:27017/mars_app")
@app.route("/")
def index():
mars_info = mongo.db.mars_info.find_one()
return render_template("index.html", mar... | python |
import sys
with open(sys.argv[1]) as f:
data = f.read()
stack = []
for i in range(len(data)):
if i%1000000==0:
print("%.2f %%"%(i/len(data)*100))
stack += [data[i]]
if (len(stack)>=8 and
stack[-8] in "<" and
stack[-7] in "Ss" and
stack[-6] in "Cc" and
stack[-5] in "Rr" and
st... | python |
#!/usr/bin/env python
import numpy as np
import sys
from readFiles import *
thisfh = sys.argv[1]
linkerfh = "part_Im.xyz"
#Read the linker file
lAtomList, lAtomCord = readxyz(linkerfh)
sAtomList, sAtomCord = readxyz(thisfh)
a,b,c,alpha,beta,gamma = readcifFile(thisfh[:-4] + ".cif")
cell_params = [a, b, c... | python |
import copy
import os
import random
import kerastuner
import kerastuner.engine.hypermodel as hm_module
import tensorflow as tf
from autokeras.hypermodel import base
class AutoTuner(kerastuner.engine.multi_execution_tuner.MultiExecutionTuner):
"""A Tuner class based on KerasTuner for AutoKeras.
Different fr... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.