content stringlengths 5 1.05M |
|---|
from typing import List
class StrLt(str):
def __lt__(x, y):
return x+y > y+x
class Solution:
def largestNumber(self, nums: List[int]) -> str:
strn = [str(n) for n in nums]
strn.sort(key=StrLt)
return ''.join(strn) if strn[0] != '0' else '0'
nums = [10, 2]
res = Solution().larg... |
# Author: Nate K
# Date of Creation: 01/09/2020
# Date of Last Edit: 01/09/2020
# Monte Carlo Simulation
# SOURCES:
# REFLECTION:
# 22 walks is the best average
# On my honor, I have neither given nor received unauthorized aid.
# Signed: NK 01/08/2020
# *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+... |
# *******************************************************************************
# Copyright 2016-2017 Dell 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/licen... |
print('-#-'*20)
print('Conversor de sistemas númericos!')
print('-#-'*20)
inteiro = int(input('Digite o número inteiro em Decimal: '))
print('\nQual será a base de conversão? ')
print('1 para binário')
print('2 para octal')
print('3 para hexadecimal')
base = int(input())
print('Valor em decimal: {}'.format(inteiro))
if... |
#!/usr/bin/env python3
# Copyright (c) 2016 Fabian Schuiki
#
# This script generates the nodeset for a memory macro.
import sys, argparse
from potstill import nodeset
# Parse the command line arguments.
parser = argparse.ArgumentParser(prog="potstill make-nodeset", description="Generate the nodeset for a memory macr... |
import time
import urllib2
import sys
import json
from lib.client import Client, get_api_path
client = Client(access_key='ZURvhizTAkcw2aYcnYQ9Jn3CYKNREeDcNdl1HXlp', secret_key='TYJeyNkXH1y7CD3xW64u6NbNsfgdIwJmlPfzsx58')
#client = Client(access_key='E4xWabtFKMWrj2YAwIyg3LHIml0ACLP2Cr1', secret_key='3p33k2yF22lE0nHJxwr... |
from .planner_abs import Planner
from .planner_doors import DoorPlanner, CellPlanner
|
from .anchor_head import AnchorHead
#from .atss_head import ATSSHead
#from .fcos_head import FCOSHead
#from .fovea_head import FoveaHead
#from .free_anchor_retina_head import FreeAnchorRetinaHead
#from .ga_retina_head import GARetinaHead
#from .ga_rpn_head import GARPNHead
#from .guided_anchor_head import FeatureAdapti... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models import vgg16
import gc
class AdversialLoss(nn.Module):
def __init__(self, cartoon_labels, fake_labels):
super(AdversialLoss, self).__init__()
self.cartoon_labels = cartoon_labels
self.fake_labels = fa... |
from gevent import monkey; monkey.patch_socket()
import gevent
from gevent import http
import greentest
import os
import socket
import errno
from test__pywsgi import read_http
# add test for "chunked POST input -> chunked output"
class BoundTestCase(greentest.TestCase):
address = ('127.0.0.1', 0)
def setUp... |
from indigox.exception import IndigoSearchError
class _Element(object):
def __init__(self, name, symbol, group, period, number, mass, atomic_radii,
covalent_radii, vdw_radii, chi, hyper=None):
self.name = name
self.symbol = symbol
self.group = group
self.period = pe... |
from __future__ import absolute_import
from django.db import models
from django.utils.translation import ugettext_lazy as _
from mptt.models import MPTTModel
from ..product.models import Product
__all__ = ('Category', )
class Category(MPTTModel):
name = models.CharField(_('name'), max_length=128)
descriptio... |
foods = ["apples", "bread", "milk", "cheese", "bananas", "beer", "onion"]
count = 0
#FOR loop
for food in foods:
if food == "beer":
print(f"You have to buy {food}.")
break
elif food == "bread":
continue
print(food)
for number in range(0, 3):
print(f"{number}*2 = {number*2}")
f... |
import json
import os
from .misc import resolve_import
class FuncChainer(object):
def __init__(self, funcs):
self.funcs = funcs
def __call__(self, inputs):
result = inputs
for f in self.funcs:
result = f(result)
return result
class Fixer(object):
FIX_DIR =... |
import json
import tarfile
import tempfile
from pathlib import Path
import adios2
from app.schemas.format import PlotFormat
from fastapi import APIRouter
from fastapi import Header
from fastapi import HTTPException
from .colormap import generate_colormap_response
from .mesh import generate_mesh_data
from .mesh impor... |
#!/usr/bin/env python
import os
import sys
base_dir = sys.argv[1]
base_dir = os.path.abspath(base_dir)
if base_dir.endswith('/') or base_dir.endswith('\\'):
base_dir = base_dir[0:-1]
def build(ls, prefix, base):
base += '/'
files = os.listdir(base)
files.sort()
has_java = False
for f in files... |
# NLP written by GAMS Convert at 04/21/18 13:53:09
#
# Equation counts
# Total E G L N X C B
# 105 0 0 105 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc ... |
'''
MapReduce word counting example
'''
class doc(object):
def __init__(self,name,content):
self.name = name
self.content = content
def getName(self):
return self.name
def getContent(self):
return self.content
doc1 = doc("doc1", "Hello world Bye w... |
from mock import call
from hypernode_vagrant_runner.settings import REQUIRED_VAGRANT_PLUGINS
from hypernode_vagrant_runner.vagrant.set_up import ensure_required_plugins_are_installed
from tests.testcase import TestCase
class TestEnsureRequiredPluginsAreInstalled(TestCase):
def setUp(self):
self.run_local... |
import numpy as np
import gmpy2 as gm
import tqdm
from recursions import alpha, beta, gamma, eta, zeros_gm, eye_gm
from innerprods import inner0_j1k1, symmetrize, lis2str
from Polynomial import Polynomial
# This file contains functions that generate coefficients for the
# symmetric orthogonal polynomials with resp... |
# Name: main.py
# Author: Duy Nguyen Ngoc
# Date: 2020/10/10
# Description:
# A back end basic with cors using flask
############################ Import ###########################################
from flask import (
Flask
)
import logging
from flask_cors import CORS
from database.db import (
db_session
)
... |
from flask import Flask
from flask_cors import CORS
def create_app():
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
app.config['RESTX_ERROR_404_HELP'] = False
return app
|
##################################################
# Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2020 #
###################################################################
# BOHB: Robust and Efficient Hyperparameter Optimization at Scale #
# required to install hpbandster ##################################
# pip install ... |
# coding=utf-8
# Transcript Downloader
# Downloads from a specified list of URLs
# Then saves them all to disk
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
import json
import os
class MySpider(BaseSpider):
root_directory = os.path.dirname(os.path.abspath(os.curdir))
# ... |
from tests.test_helper import *
from braintree.test.nonces import Nonces
from braintree.exceptions.not_found_error import NotFoundError
from braintree.error_codes import ErrorCodes
class TestCoinbase(unittest.TestCase):
def test_customer(self):
result = Customer.create({"payment_method_nonce": Nonces.Coi... |
from __future__ import absolute_import
import logging
import urllib
import urllib.request
import zipfile
from io import BytesIO
from tqdm.auto import tqdm, trange
from api import beam__common, fileio
def download(url, local_fname, block_sz=8192, display=True, nested_tqdm_pb=None):
http_file = urllib.request.urlo... |
# -*- coding: utf-8 -*-
# @Time : 2020/8/3 22:30
# @Author : CC
# @Desc : memery_queue.py
from queue import Queue
from pypattyrn.structural.flyweight import FlyweightMeta
class MemoryQueue(metaclass=FlyweightMeta):
def __init__(self, queue_name, fliter_rep=False, namespace='', **kwargs):
self.que... |
import telebot
from telebot import types
from datetime import datetime, date, time
from fuzzywuzzy import process
print("Bot is running")
bot = telebot.TeleBot('')
admin = "0"
ausername = "0"
#admin---------------------------------------------------------------------
@bot.message_handler(commands=['admin'])
def admi... |
import os
import pytest
# from kivy.clock import Clock
# Clock._maxfps = 0
KIVY_EVENTLOOP = os.environ['KIVY_EVENTLOOP']
try:
from kivy.tests.fixtures import kivy_app
except SyntaxError:
# async app tests would be skipped due to async_run forcing it to skip so
# it's ok to fail here as it won't be used a... |
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
def test_test():
print("Yeah")
|
# -*- coding: utf-8 -*-
# coding=utf-8
# Copyright 2019 The SGNMT 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 requir... |
import logging
import time
import os
import sys
import shutil
LOG_FORMAT = "[%(asctime)s]: %(message)s" # \" %(levelname)-8s ▶ %(message)s"
class Log(object):
_instance = None
# def __new__(cls, *args, **kwargs):
# if cls._instance is None:
# cls._instance = super().__new__(cls)
# ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# common
import os
import os.path as op
import sys
# pip
import numpy as np
import xarray as xr
# DEV: override installed teslakit
import sys
sys.path.insert(0, op.join(op.dirname(__file__), '..', '..', '..'))
# teslakit
from teslakit.database import Database
from tesla... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Abstract interface for parallel execution of multiple jobs.
The main class is `ScatterGather`, which can submit many instances
of a job with different configurations.
"""
from __future__ import absolute_import, division, print_function
import sys
imp... |
#!/usr/bin/env python
#
# Copyright 2007 Google 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 o... |
import re
import numpy as np
def is_entity(id):
return True if type(id) == str and re.match("^Q[0-9]+", id, re.IGNORECASE) else False
def is_prop(id):
return True if type(id) == str and re.match("^P[0-9]+", id, re.IGNORECASE) else False
def is_char(id):
return type(id) == str and len(id) == 1
def r... |
import db.stud_networkdb as db
import secrets
def generate_token(vk_id):
unique_flag = False
token = None
while not unique_flag:
token = secrets.token_hex()
unique_flag = db.is_unique_token(token)
return token
|
# stdlib
from copy import deepcopy
import csv
from io import StringIO
import tarfile
from typing import Iterable
from typing import Optional
# third party
from nacl.encoding import HexEncoder
from nacl.signing import SigningKey
import numpy as np
import pandas as pd
from pandas import DataFrame
from syft.core.common.g... |
import functools
import inspect
import numpy as np
import random
from abc import ABC, abstractmethod
from box import Box
class Param(ABC):
def __init__(self, capsule, key, default):
self._capsule = capsule
self._key = key
self.default = default
@abstractmethod
def get_next_value(... |
# May require:
# $ pip3 install --proxy http://...:80 requests
# $ pip3 install json
#
# Good requests 101-tutorial at https://realpython.com/api-integration-in-python/
#
# This is a REST Client.
#
from typing import Any
import sys
import requests
import json
import traceback
AUDIO_FILE: str = "foo.wav"
TENANT_ID: st... |
# Web08.py
# naver.com 에서 '네이버를 시작페이지로'를 가져와서 출력
from urllib.request import urlopen
from bs4 import BeautifulSoup
url = 'https://www.naver.com/'
html = urlopen(url)
bs_obj = BeautifulSoup(html,'html.parser')
# <div class="area_links">
#bs1 = bs_obj.html.body.find('div',{"class":"area_links"})
#print(bs1)
# <a class... |
#!/usr/bin/env python3
import sys,re
import getopt
from glob import glob
import sqlite3
import os
import time
from datasketch import MinHash, LeanMinHash
import itertools
import ssdeep
from pysimhash import SimHash
import tlsh
import statistics
VERBOSE = False # can be turned off via flags
ALGO = "minhash"
THRESH... |
import numpy as np
import scipy.sparse as sp
import networkx as nx
def Eigen(adj, d, adj_normalize, feature_abs):
"""
Calculate the top-d eigenvectors of the adjacency matrix
Input:
adj: adjacency matrix in scipy sparse format, could be replaced by other symmetric matrices, e.g., the Laplacian mat... |
from rest_framework import serializers
from ..models.transaction import Transaction
class BaseTransactionSerializer(serializers.ModelSerializer):
"""
Base serializer for Transaction model.
Other transaction serializers must be inherited from it.
"""
class Meta:
model = Transaction
... |
import unittest
import os
from shapely.geometry import shape
from shapely.strtree import STRtree
from rastervision2.pipeline import rv_config
from rastervision2.pipeline.file_system import json_to_file
from rastervision2.core.box import Box
from rastervision2.core.data import (
ClassConfig, infer_cell, ChipClassi... |
import numpy as np
#other constants will be added soon
m, x, y, vx, vy = np.loadtxt("system.txt", skiprows=0, unpack=True)
G = 6.67408e-11
cons_m = 1
|
from sklearn.metrics import accuracy_score, f1_score, recall_score, precision_score, roc_auc_score
class ResultMetric:
accuracy = None
f1 = None
recall = None
precision = None
auc = None
def __init__(self, pred_classes: [], real_classes: []):
self.predicted = pred_classes
self... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class InsSumInsured(object):
def __init__(self):
self._default_value = None
self._max_value = None
self._min_value = None
self._sum_insured_type = None
self._sum... |
from collections.abc import Sequence
from dataclasses import dataclass
from typing import NewType
from reviewlogic.value_objects import ProposalId
Title = NewType("Title", str)
Description = NewType("Description", str)
@dataclass
class Proposal:
id: ProposalId
title: Title
description: Description
... |
# -*- coding: utf-8 -*-
"""
File yolov3_detector.py
@author:ZhengYuwei
"""
import logging
from tensorflow import keras
from backbone.resnet18 import ResNet18
from backbone.resnet18_v2 import ResNet18_v2
from backbone.resnext import ResNeXt18
from backbone.mixnet18 import MixNet18
from backbone.mobilenet_v2 import Mobil... |
from ..utils.filemanager import FileManager
from ..storage_managing.storage import Storage
from .exceptions.passworderror import PasswordError
from .exceptions.roleerror import RoleError
from .exceptions.alreadyloggederror import AlreadyLoggedError
class RoleAuth:
'''
A class made for simplifiying users' ro... |
import json
from typing import List
from util import listToJson
if __name__ == '__main__':
sections: List[dict] = json.load(open('_pawsSection.raw.json', 'r'))
titles = set()
for section in sections:
titles.add(section['title'][0])
titles = list(titles)
listToJson(titles, 'title')
|
# This script deletes all messages in a queue
#
# Author - Paul Doyle Sept 2013
#
#
import sys
import Queue
import boto.sqs
import argparse
import socket
datasource = '/data/compressed/'
parser = argparse.ArgumentParser()
parser.add_argument('queuearg',help='name of the sqs queue to use',metavar="myQueueName")
args =... |
import datetime as datetime
from sqlite3 import Timestamp
import sqlalchemy as _sql
import sqlalchemy.orm as _orm
import passlib.hash as _hash
from sqlalchemy.schema import Column
from sqlalchemy.types import String, Integer, Enum, DateTime, Boolean, ARRAY, Text
from sqlalchemy import ForeignKey
from uuid import UUID,... |
"""
reaction_coord.py
"""
import os
from pydantic import BaseModel
from typing import List, Any
from .output_parser import read_embed_output, read_matrop_matrix
class EvenHandedInfo(BaseModel):
lmo_mat: Any = None
s_mat: Any = None
nocc: int = None
nao: int = None
nocc_a: int = None
nocc_b: ... |
""" Helper class and functions for loading KITTI objects
Author: Charles R. Qi
Date: September 2017
"""
from __future__ import print_function
import os
import sys
import numpy as np
import cv2
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(BASE_DIR)
sys.path.append(os.path.join(ROOT... |
# Created by MechAviv
# ID :: [865020001]
# Commerci Republic : Canal 1
sm.curNodeEventEnd(True)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(True, True, False, False)
sm.setStandAloneMode(True)
sm.forcedInput(2)
sm.curNodeEventEnd(True) |
"""
Implements Bayesian Hyperparameter optimization
"""
from typing import List, Any
import logging
import numpy as np
from ml_tooling.data import Dataset
from ml_tooling.result import ResultGroup, Result
from ml_tooling.search.base import Searcher
from ml_tooling.utils import Estimator
import sklearn.utils.fixes
f... |
colors = {
"white": (255, 255, 255),
"black": (0, 0, 0),
"red": (255, 0, 0),
"blur_red": (255, 135, 133),
"green": (0, 255, 0),
"gray": (133, 133, 133),
"blue": (0, 0, 255),
"blur_blue": (133, 135, 255),
"yellow": (255, 255, 0),
}
directions = [
{"x": -1, "y": -1},
{"x": -1,... |
import logging
import os.path
import sys
import unittest
import urllib
from django.core.files import File
from project_settings.settings.base import PROJECT_ROOT
from parsers.improvteams.parser import BaseItParser
from parsers.improvteams.parser import ItPerformerParser
from parsers.improvteams.parser import ItTeamPa... |
# Load pretrained weights
pretrained_dict = torch.load(pretrained_path)
# Get model state dicts
model_dict = model.state_dict()
# Filter out unnecessary keys
pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}
# Overwrite entries in the existing state dict
model_dict.update(pretrained_dict) ... |
__test__ = False
if __name__ == '__main__':
from eventlet import tpool
def do():
print("should not get here")
try:
tpool.execute(do)
except AssertionError:
print('pass')
|
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
import torchvision
import cv2
import numpy as np
import random
from PIL import Image
from maskrcnn_benchmark.structures.rotation_box import RBoxList
from maskrcnn_benchmark.structures.segmentation_mask import SegmentationMask
from mas... |
import torch
import numpy as np
import pandas as pd
from training.model import SeqLSTM
from training.data_utils import get_data_loader_chr
from training.data_utils import get_samples_sparse, get_cumpos, contactProbabilities
import time
from torch.utils.tensorboard import SummaryWriter
import torch.nn.functional as F
fr... |
from copy import copy
import re
#------------------------------------------------------------------------------#
u8neg = u"\u00AC"
u8and = u"\u2227"
u8or = u"\u2228"
class Expression:
def __init__(self, clauses, var2desc = {}, meta = {}):
self.meta = meta
self.clauses = clauses
self.v... |
from os.path import join
from bids.analysis.auto_model import auto_model
from bids.analysis import Analysis
from bids.layout import BIDSLayout
from bids.tests import get_test_data_path
import pytest
@pytest.fixture
def model():
layout_path = join(get_test_data_path(), 'ds005')
layout = BIDSLayout(layout_path)... |
import turtle as hail
import math
hail.ht()
hail.delay(50)
hail.color("#008080")
hail.width(5)
hail.bgcolor("lavender")
size=200
hail.setheading(90) #towards the top
for i in range(0,6):
hail.forward(size)
hail.penup()
hail.forward(-size)
hail.left(60)
hail.pendown()
hail.setheading(90) #towards the top
hai... |
# quoting.py
"""Various helpers for string quoting/unquoting."""
import re
__all__ = [
# _pyqoting / _cquoting
"quote_literal", "quote_copy", "quote_bytea_raw",
"db_urlencode", "db_urldecode", "unescape",
"unquote_literal",
# local
"quote_bytea_literal", "quote_bytea_copy", "quote_statement",... |
def potential(element_symbol,functional):
"""
:param element_symbol: string, symbol of the element
:param functional: string, functional name
:return: string, GTH potential name to be used in the simulation
"""
return "GTH-"+functional
|
from flask import Flask
from src.main.admin_api.main import admin_api
from src.main.query_api.main import query_api
from src.main.config import active_config
app = Flask(__name__)
app.config["DEBUG"] = active_config.debug
app.register_blueprint(admin_api, url_prefix="/admin")
app.register_blueprint(query_api, ... |
import os
import sys
def dataset(x, datatype):
'''
the datatype determine the surface of the search space
'''
y = [ ]
if datatype == "linear":
for i in range(1000):
y.append(1000 - i)
else:
y.append(random.uniform(1, 1000))
return y[x]
def dump_result(qor):
filename = 'qor.txt'
f =... |
def golomb(n):
'''
Checks if secuence meets Golomb's 3 postulates:
1. Number of 0s and number of 1s is as near as possible to n/2, where n is secuence's length.
2. The number of runs of given length should halve when the length is increased by one.
3. The out-of-phase cor... |
# webui.py -
# main web ui controller for spiro
#
# - Jonas Ohlsson <jonas.ohlsson .a. slu.se>
#
from flask import Flask, render_template, Response, request, redirect, url_for, session, flash, abort
from waitress import serve
import io
import time
import os
import hashlib
import shutil
from spiro.config import Confi... |
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2015-present Dolfies
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 ... |
import numpy as np
import pandas as pd
import matplotlib.ticker as tick
from matplotlib import pyplot as plot
numbers_count = 1000
macd = np.zeros(numbers_count)
signal = np.zeros(numbers_count)
ema = np.zeros(numbers_count)
dema = np.zeros(numbers_count)
strength = np.zeros(numbers_count)
buy_ids = []
sell_ids = []
... |
private_key = b'0\x82\x04\xa3\x02\x01\x00\x02\x82\x01\x01\x00\xd29\xdf\xec-"\xcd{\xdf\xd4^3\xc7Ik\xac\x8c&\xa5\xa6\x07I\x00\x18\xd41\x921%N\x02-\xb0=d\x9eT\x97\xc9\xbc{\xe6\xeb\xe9\x98\x8b\x0cW\x8a\xba2\x8b>\xc1\xbc\x98\x19\xdb\xe7\x96u\xa8\xdei\xd5%F\x12\xacaa\x009\xa1\xfd|\xc3\xf2\xfc\xd9\xb3f\x96\x81_J\xb0\xac%`A\x8... |
import argparse
import os
from argparse import ArgumentParser
parser = ArgumentParser(description="Read file form Command line.")
parser.add_argument("-i", "--input", dest="filename", required=True,
help="input file", metavar="FILE")
parser.add_argument("-o", "--output", dest="outputname",
... |
from .. import db
from faker import Faker
import random
class ChecklistItem(db.Model):
id = db.Column(db.Integer, primary_key=True)
assignee_id = db.Column(
db.Integer,
db.ForeignKey('student_profile.id'),
index=True)
deadline = db.Column(db.Date, index=True)
text = db.Column(d... |
#Embedded file name: www_auth.py
import sys
import urlparse
if 0:
i11iIiiIii
OO0o = None
Oo0Ooo = None
if 0:
OOO0O0O0ooooo % IIii1I.II1 - O00ooooo00
def I1IiiI(arg):
global OO0o
global Oo0Ooo
IIi1IiiiI1Ii, I11i11Ii, oO00oOo, OOOo0 = arg
try:
Oooo000o = 0
IiIi11iIIi1Ii = curl.new... |
import sqlite3
db_connect = sqlite3.connect('test.sqlite')
cursor = db_connect.cursor()
cursor.execute('''
CREATE TABLE `following` (`id` INTEGER NOT NULL UNIQUE, `name` TEXT NOT NULL, `screen_name` TEXT NOT NULL, PRIMARY KEY(`id`))
''') |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os, sys, time, subprocess, string
from collections import deque
from threading import Thread
from utils.printing import *
from utils.mylogging import get_logger
logger = get_logger(__name__)
class LocalRunner(Thread):
def __init__(self, nam... |
#! /usr/bin/env python
from .default import *
'''
--------------------------------------------------------------------------------------------------------
DEBUGGING
--------------------------------------------------------------------------------------------------------
'''
DEBUG = True
... |
# Utility functions for a Python SSL certificate conversion tool.
# These functions are in this file so the can also be used in
# A web API implementing this tool.
# Author: Tony DiCola, Modified by Noah Koontz
#
# Dependencies:
# click - Install with 'sudo pip install click' (omit sudo on windows)
# PyOpenSSL - S... |
"""
Find the largest number from the given three integers.
Example
For a = 3, b = 2 and c = 4, the output should be
myMaxOfThree(a, b, c) = 4.
"""
def myMaxOfThree(a, b, c):
return max(a, b, c)
|
import pytest
from dependency_injector import Container
@pytest.fixture
def ioc():
return Container()
|
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 4 16:23:07 2017
@author: mojod
"""
import random
import tweepy
import time
consumer_key='L3MsyCOoqgSPc4jzZV8wero0d'
consumer_secret='ZCOI3x1f8GZ9c2cJ8kPYyyBW4gRX4MJBbyHijGE1UObnAow6ka'
access_token='3789452353-dmM75KVaDGqIPz6ZtzP8b5Q6VkvzQQo9Sn34ZOZ'
ac... |
#
# General-purpose Photovoltaic Device Model - a drift diffusion base/Shockley-Read-Hall
# model for 1st, 2nd and 3rd generation solar cells.
# Copyright (C) 2008-2022 Roderick C. I. MacKenzie r.c.i.mackenzie at googlemail.com
#
# https://www.gpvdm.com
#
# This program is free software; you can redist... |
"""
Module to generate Lebedev grids and quadrature weights for degrees 6, 14, 26,
38, 50, 74, 86, 110, 146, 170, 194:
`genGrid(n)`
Generate Lebedev grid geometry of degree `n`.
Adapted from Richard P. Mullers Python version,
https://github.com/gabrielelanaro/pyquante/blob/master/Data/lebedev_write.py
C version: ... |
import csv
import sys
import pandas as pd
import os.path
import numpy as np
# Created functions
import dtwParallel
from .error_control import possible_distances
from .utils import *
from .dtw_functions import dtw, dtw_tensor_3d
def input_File(input_obj):
args, input_obj = parse_args(True)
data = read_data(... |
# Copyright 2013 Donald Stufft
#
# 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, so... |
import inspect
import os
import os.path as op
import logging
from glob import glob
from os import path as op
from ..utils import create_file_if_missing
lgr = logging.getLogger(__name__)
MIN_VERSION = '0.7'
def prepare_datalad(studydir, outdir, sid, session, seqinfo, dicoms, bids):
""" Prepare data for datalad... |
# Copyright (C) 2014 Google 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 a... |
#!/usr/bin/env python
# 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
#
# Authors:
# - Shuwei Ye, yesw@bnl.gov, 2021
# - Paul Nilsson, paul.nilsson@... |
import unittest
import shutil
from pathlib import Path
import pytest
from spikeinterface import extract_waveforms, WaveformExtractor
from spikeinterface.extractors import toy_example
from spikeinterface.toolkit.postprocessing import calculate_template_metrics, get_template_channel_sparsity
if hasattr(pytest, "globa... |
#
# File : 04-10.py
# Author : Kazune Takahashi
# Created : 11/14/2019, 11:50:58 AM
# Powered by Visual Studio Code
#
def start_end(func):
def new_func(*args, **kwargs):
print("start")
res = func(*args, **kwargs)
print("end")
return res
return new_func
@start_end
def sum_... |
# Copyright 2017 Insurance Australia Group Limited
#
# 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... |
#!/usr/bin/env python3
import sys
with open(sys.argv[1], 'r') as f:
for l in f:
if l.strip():
print(l, end='')
|
from models import SAFA
from dataloader import DataLoader
import tensorflow as tf
import numpy as np
import os
import time
# -------------------------------------------------------- #
def validate(grd_descriptor, sat_descriptor):
accuracy = 0.0
data_amount = 0.0
dist_array = 2 - 2 * np.matmul(sat_descript... |
#!/usr/bin/env python3
import os
import sys
import time
import json
import argparse
import subprocess
import threading
import queue
import logging
logger = logging.getLogger(__name__)
GRIT_DIRECTORY = ".grit"
LOG_FILE_NAME = "_commands.log"
ACTIVE_MANIFEST_FILE = "_active_manifest" # .json is added automatically
GR... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.