content stringlengths 5 1.05M |
|---|
# 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 ... |
from piComm.transmitter import transmitter_main
from piComm.receiver import receiver_main
if __name__ == '__main__':
option = input("1 - Transmitter | 2 - Receiver | 0 - Exit")
while option != 0:
if option == 1:
transmitter_main()
elif option == 2:
receiver_ma... |
#!/usr/bin/env python3
# Note that installing `puccini` will also install `ard`
import sys, puccini.tosca, ard
if len(sys.argv) <= 1:
sys.stderr.write('no URL provided\n')
sys.exit(1)
url = sys.argv[1]
try:
clout = puccini.tosca.compile(url)
ard.write(clout, sys.stdout)
except puccini.tosca.Proble... |
""" Lexer for pascal. """
import re
from ..common import SourceLocation, Token
from ..tools.baselex import SimpleLexer, on
class Lexer(SimpleLexer):
""" Generates a sequence of token from an input stream """
keywords = ['program',
'type', 'const', 'var',
'begin', 'end',
... |
from dataclasses import dataclass
from bindings.csw.triangle_type import TriangleType
__NAMESPACE__ = "http://www.opengis.net/gml"
@dataclass
class Triangle(TriangleType):
class Meta:
namespace = "http://www.opengis.net/gml"
|
#!/usr/bin/python
from pymongo import MongoClient
client = MongoClient()
db = client.sherlock_database
stocks = [
{
"resource": {
"classname": "Quote",
"fields": {
"name": "ZICOM ELECTRONIC S INR10",
"price": "47.299999",
"symbol": "... |
import numpy as np
import matplotlib.pyplot as plt
import time
import sys
sys.path.append('../')
from FollyHighLevelControllerV1 import FollyHighLevelControllerV1
# Initialize Molly position
molly_position = np.array([-4, -8])
# Initialize Folly position
folly_position = np.array([-2, -7.5, 0])
# object length
obje... |
#! /usr/bin/env python3
# vim:ts=4:sw=4:ai:et:si:sts=4
import argparse
import logging
import json
from flask_jsonrpc.proxy import ServiceProxy
import os
import sys
import re
import time
import configparser
FORMAT = "%(asctime)s: %(name)s:%(lineno)d (%(threadName)s) - %(levelname)s - %(message)s"
logging.basicConfig(f... |
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import math
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
from sklearn.model_selection import train_test_split
dataset = pd.DataFrame()
model = {}
def load_dataset(filename):
#Load Dataset
global dataset
... |
import os
from tqdm import tqdm
import numpy as np
from ..dataloaders.custom_path import Path
def calculate_weigths_labels(dataset, dataloader, num_classes, server='039614'):
# Create an instance from the data loader
z = np.zeros((num_classes,))
# Initialize tqdm
tqdm_batch = tqdm(dataloader)
print... |
#written by ruth
from os import listdir
from string import punctuation
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk import pos_tag
from json import loads,dumps
from random import seed
seed(1000)
class preProcessor(object):
def __init__(self, inputdir, stops, negtags):
... |
import pso
import os
particles = [5, 10, 20, 30, 40, 50, 70, 75, 100, 150, 200, 500]
for n in particles:
os.system('mkdir results/p%d_i50 && python main.py --infile "data/scg_gawad/pat1.txt" --mutations 20 --mutfile "data/scg_gawad/pat1_mut.txt" --particles %d --iterations 50 >> results/p%d_i50/result.txt && mv r... |
from flask_restful import current_app
from common.database import db
import datetime
import string
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey, Sequence, exc
def create_db():
db.create_all()
def run():
create_db()
|
"""
Simple script generate the static HTML for the Bokeh climate zone map
Requirements:
- python >= 3.7
- bokeh
- ???
"""
import json
from pathlib import Path
from bokeh.embed import autoload_static
from bokeh.models import GeoJSONDataSource, WMTSTileSource
from bokeh.plotting import figure
from bokeh.resources ... |
# Copyright 2020 DeepMind Technologies 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... |
from bll import GameControl
class GameView:
def __init__(self):
self.controller = GameControl()
def show_menu(self):
print("按下w上滑")
print("按下s下滑")
print("按下a左滑")
print("按下d右滑")
def select_menu(self, map):
result = input("请输入你的选项")
if result == "w":... |
#from .symbol_vgg import *
from .symbol_ssh import *
|
inp = input('European floor? ')
usf = int(inp) + 1
print('US floor number is:', usf) |
from django.contrib import admin
from .models import *
class EventAdmin(admin.ModelAdmin):
model = Event
list_display = ['event_cod', 'event_nom', 'event_date_init', 'even_date_end', 'event_site', 'event_url']
class MagazineAdmin(admin.ModelAdmin):
model = Magazine
list_display = ['magazine_code', 'ma... |
import time
import random
import logging
logger = logging.getLogger(__name__)
from bs4 import BeautifulSoup
import zlib
from fbscraper.settings import (
DEFAULT_MAX_TRY_TIMES,
DEFAULT_SHOULD_USE_ORIGINAL_URL,
STATUS_SUCCESS,
)
import fbscraper.facebook as fb
class DiscoverCrawler:
def __init__(
... |
# import library zeroMQ dan time
import zmq
import time
# membuat context zeroMQ
context = zmq.Context()
# membuat socket publisher dan binding dengan IP server
sock = context.socket(zmq.PUB)
sock.bind("tcp://192.168.1.18:5680")
id = 0
while True:
# sleep selama 1 detik
time.sleep(1)
# mengupdate nilai ... |
"""This file and its contents are licensed under the Apache License 2.0. Please see the included NOTICE for copyright information and LICENSE for a copy of the license.
"""
import os
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from io_storages.serializers import ImportSt... |
#
# @lc app=leetcode id=237 lang=python3
#
# [237] Delete Node in a Linked List
#
# https://leetcode.com/problems/delete-node-in-a-linked-list/description/
#
# algorithms
# Easy (68.67%)
# Likes: 2914
# Dislikes: 9579
# Total Accepted: 641.1K
# Total Submissions: 932.4K
# Testcase Example: '[4,5,1,9]\n5'
#
# Wri... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import bpy
class MHC_OT_MarkAsClothesOperator(bpy.types.Operator):
"""Mark this object to be used as clothes"""
bl_idname = "makeclothes.mark_as_clothes"
bl_label = "Mark selected object as clothes"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def p... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from basic_class.basic_class import basic_class
class realtime_inspector(basic_class):
def __init__(self):
super().__init__()
def log_this(self, *message, new_line=True):
for sub_mesg in message:
print(sub_mesg, end='')
if new_li... |
from ._BoxBoundsCoercionISPSpecifier import BoxBoundsCoercionISPSpecifier
from ._MaskBoundsCoercionISPSpecifier import MaskBoundsCoercionISPSpecifier
|
from django.apps import AppConfig
class ScenicConfig(AppConfig):
name = 'scenic'
|
import threading
import time
import socket, subprocess,sys
from datetime import datetime
import thread
import shelve
'''section 1 '''
subprocess.call('clear',shell=True)
shelf = shelve.open("mohit.raj")
data=(shelf['desc'])
#shelf.sync()
'''section 2 '''
class myThread (threading.Thread):
def __init__(self, threadN... |
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 30 02:37:25 2013
@author: roel
"""
import unittest
import pandas as pd
import opengrid as og
from opengrid.library import weather
from opengrid.library.exceptions import *
dfw = og.datasets.get('weather_2016_hour')
class WeatherTest(unittest.TestCase):
def test_... |
import json
import requests
import time
import auth
import util
from instance import Instance
from exceptions import AlaudaServerError
MAX_RETRY_NUM = 10
INSTANCE_SIZES = ['XXS', 'XS', 'S', 'M', 'L', 'XL']
class Service(object):
def __init__(self, name, image_name, image_tag, target_num_instances=1, instance_s... |
from mlhub.pkg import azkey, azrequest, mlask, mlcat
mlcat("Text Classification of MultiNLI Sentences Using BERT", """\
To run through the demo quickly the QUICK_RUN flag
is set to True and so uses a small subset of the data and
a smaller number of epochs.
The table below provides some reference running times on two ... |
from functools import cmp_to_key
class Player:
def __init__(self, name, score):
self.name=name
self.score=score
def __repr__(self):
return {'name':self.name,'score':self.score}
@staticmethod
def comparator(a, b):
if a.score>b.score:
return -1
... |
#!/usr/bin/env python3
# Copyright 2021 Open Source Robotics Foundation, 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 re... |
#MenuTitle: Transfer Hints to First Master
# -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
from builtins import str
__doc__="""
Moves PostScript (stem and ghost) hints from the current layer to the first master layer, provided the paths are compatible.
"""
from GlyphsApp impor... |
"""
This module is the test suite of leggedsnake.
It uses unit test.
""" |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
## Project:
## Author: Oliver Watts - owatts@staffmail.ed.ac.uk
import sys
import os
import glob
import math
import tempfile
import struct
import re
import copy
import h5py
from argparse import ArgumentParser
import numpy
import numpy as np
# import pylab
import num... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2018 all rights reserved
#
"""
Verify various configuration methods
"""
# externals
import pyre
# the protocols
class functor(pyre.protocol, family="quad.functors"):
@pyre.provides
def eval(self, z):
"""... |
# Copyright 2019 Verily Life Sciences LLC
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
'''An implementation of the Google BigQuery Standard SQL syntax.
https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax
Differences from this grammar o... |
import csv
# TODO
# Below are measurements for failing transparent http proxies:
# https://explorer.ooni.org/measurement/20170509T041918Z_AS5384_fSeP50M6LS3lUhIarj2WhbQNIQS8mKtvhuxEhwJOhgheEL7EsZ?input=http:%2F%2Fanonym.to
# https://explorer.ooni.org/measurement/20180914T010619Z_AS11427_d3lligD9zAEneBLYeI8Mt2JUpVBC2y5... |
import sys
import time
import machine
import st7789
import uos
import random
import ftext
def pick_item(sequence):
div = 0x3fffffff // len(sequence)
return sequence[random.getrandbits(30) // div]
bl = machine.Pin(4, machine.Pin.OUT)
bl.value(1)
spi = machine.SPI(
2,
baudrate=30000000,
polarity=1... |
DATABASE_ENGINE = 'sqlite3'
ROOT_URLCONF = 'database_files.urls'
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'database_files',
'database_files.tests',
]
DEFAULT_FILE_STORAGE = 'database_files.storage.DatabaseStorage'... |
import configparser
import logging
import pandas as pd
try:
from sklearn.model_selection import KFold, GridSearchCV
except ImportError: # sklearn 0.17
from sklearn.cross_validation import KFold
from sklearn.grid_search import GridSearchCV
from . import utils as eutils
log = logging.getLogger(name=__nam... |
class Movie:
filename = 'films/{title} ({year})'
def __init__(self, title, year):
self.title = title
self.year = year
@property
def path(self):
return self.filename.format_map(self.__dict__)
|
"""aque rm - Remove tasks from the queue.
Removes given tasks, or tasks matching given statuses. By default only removes
tasks submitted by the current user, but may operate on all tasks via `-x`.
"""
import os
import sys
from aque.commands.main import command, argument
from aque.queue import Queue
@command(
... |
#Import the necessary methods from tweepy library
from tweepy.streaming import StreamListener
import tweepy
import webbrowser
import json
#Variables that contains the user credentials to access Twitter API
access_token = ""
access_token_secret = ""
consumer_key = ""
consumer_secret = ""
#This is a basic listener th... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import os
def get_package_data():
paths = [os.path.join('js', '*.js'), os.path.join('css', '*.css')]
return {'astropy.extern': paths}
|
import pandas as pd
import datetime as dt
import numpy as np
import matplotlib.pyplot as plt
# age = 1
# jobStr = 2
# maritalStr = 3
# educationStr = 4
# default = 5
# balance = 6
# carloan = 7
# communicationStr = 8
# lastContactDay = 9
# lastContactMonthStr = 10
# noOfContacts = 11
# prevAttempts = 12
# OutoComeStr ... |
import math
import cv2
import matplotlib.cm
import numpy as np
from scipy.ndimage.filters import gaussian_filter, maximum_filter
from scipy.ndimage.morphology import generate_binary_structure
# It is better to use 0.1 as threshold when evaluation, but 0.3 for demo
# purpose.
cmap = matplotlib.cm.get_cmap('hsv')
# He... |
"""
Code for optimizers
"""
from typing import Union, Optional
import torch
import torch.nn as nn
from torch.optim.optimizer import Optimizer
from torch.optim.lr_scheduler import _LRScheduler
# -- tests
def one_test():
pass
if __name__ == '__main__':
print('Done, success!\a')
|
# Minimum and Maximum
playerOneScore = 10
playerTwoScore = 4
print(min(playerOneScore, playerTwoScore))
print(max(1, 35, 1, 34))
print(min("Kathryn", "Katie"))
print(min("Angela", "Bob"))
print(max(playerOneScore, playerTwoScore))
|
# ------------------------------------------------------------------------------
#
class Callback (object) :
# FIXME: sigs
pass
# ------------------------------------------------------------------------------
#
|
import os
from .exception import *
from .linux import ShortCutterLinux
from tempfile import NamedTemporaryFile
import subprocess
class ShortCutterMacOS(ShortCutterLinux):
def _get_menu_folder(self):
return os.path.join('/', 'Applications')
def _create_shortcut_file(self, target_n... |
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright Blaze 2021.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
https://www.boost.org/LICENSE_1_0.txt)
"""
from typing import Callable, Dict, cast, List, TypeVar, Union
from da... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
2D linear elasticity example
Solve the equilibrium equation -\nabla \cdot \sigma(x) = f(x) for x\in\Omega
with the strain-displacement equation:
\epsilon = 1/2(\nabla u + \nabla u^T)
and the constitutive law:
\sigma = 2*\mu*\epsilon + \lambda*(\nabla\cdot u)I,... |
# H
class Product:
def __init__(self, id, name, cost):
self.__id = id
self.__name = name
self.__cost = cost
self.__quantity = 1
self.__stock = 0
def add_quantity(self):
self.__quantity += 1
def remove_quantity(self):
self.__quantity -= 1
def get... |
import ctypes
from vector2 import Vector2
class float4(ctypes.Structure):
_fields_ = [
('m', ctypes.c_float * 4)
]
class m4(ctypes.Structure):
_fields_ = [
('m00', ctypes.c_float), ('m01', ctypes.c_float),
('m10', ctypes.c_float), ('m11', ctypes.c_float)
]
class columns(ctypes.Structure):
_f... |
#!/usr/bin/python3
"""
输入圆的半径计算计算周长和面积
version: 0.1
author: icro
"""
import math
r = float(input('圆的半径 = '))
p = 2 * math.pi * r
a = math.pi * r * r
print('周长: %.2f' % p)
print('面积: %.2f' % a) |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 17 13:27:49 2021
@author: Hatlab-RRK
"""
import numpy as np
import matplotlib.pyplot as plt
#visualizing phase offest in a mixer
I_0 = lambda t: np.cos(t)
Q_0 = lambda t: np.sin(t)
delay = np.pi/6
I_delayed = lambda t: np.cos(t+delay)
t = np.linspace(0, 2*np.pi-np.pi/3... |
"""Unit tests for _properties/compatibility.py."""
# pylint: disable=protected-access
# pylint: disable=invalid-name,missing-docstring
import unittest
from unittest import mock
import keras
import hmmlearn
from pyhumour._properties.language_models import HMMHelper
class TestHMM(unittest.TestCase):
def setUp(se... |
from typing import Union, Tuple, Optional, List
import torch
from ....torchio import DATA
from ....utils import is_image_dict, to_tuple
from .. import RandomTransform
class RandomFlip(RandomTransform):
"""Reverse the order of elements in an image along the given axes.
Args:
axes: Axis or tuple of axe... |
# Copyright 2012 NagiosQL-API authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
#encoding: utf-8
from django.db import models
class TblCommand(models.Model):
command_name = models.CharField(unique=True, max_length=255)
command_l... |
from django.conf.urls import url
from .import views
urlpatterns = [
url(r'^index1',views.Dname.as_view()),
] |
import csv
# import os
def convert_tsv_to_csv(input, out):
# if os.path.exists(out):
# raise ValueError("Output file already exists")
reader = csv.reader(open(input, 'rU'), dialect=csv.excel_tab)
writer = csv.writer(open(out, "w+"), dialect="excel")
for row in reader:
writer.writerow(ro... |
# tests grabbed from:
# https://github.com/tidyverse/dplyr/blob/master/tests/testthat/test-slice.r
from pandas.testing import assert_frame_equal
from pipda.context import ContextError
import pytest
from datar.core.grouped import DataFrameRowwise
from datar.all import *
from datar.datasets import mtcars
from datar.dplyr... |
def format_out(out):
# TODO: Why do I need to do this?
maybe_newline = '\n' if out.endswith('\n') else ''
return '\n'.join(
map(lambda line: ';; {}'.format(line), out.splitlines())
) + maybe_newline
def format(message):
if 'value' in message:
return message['value']
if 'nrepl.... |
#
# Copyright 2013 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... |
# coding: utf-8
# # Joblib for Daniel:
#
# Trying to implement parallelism into Daniels problem.
#
# ## Some Tests with random values
# I don't know if these quite match your data types
# In[135]:
import time
import tempfile
import shutil
import os
import numpy as np
from joblib import Parallel, delayed
from jobl... |
"""C6T Assembler First Pass
"""
from sys import stderr
import util
def pass1(parsed: list, program_counter: int = 0) -> int:
"""Handle the first pass, building the symbol table and macros.
Starts at the given program counter value. Returns the new program counter.
"""
util.macros.clear()
util.re... |
def fitting(data):
n = len(data)
if n <= 2:
print('Error! Not enough data!')
# Declare all variables (x and y components)
s_x = 0
s_y = 0
s_xx = 0
s_xy = 0
for i in range(0,n):
entry = data[i]
s_x += entry[0]
s_y += entry[1]
s_xx += entry[0]**2
... |
#! /usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "... |
from .backend import InteractiveBackend
import numpy as np
import matplotlib.pyplot as plt
import plotly.graph_objs as go
class InteractiveBackendPlotly(InteractiveBackend):
"""
Implementation of the interactive plotting backend for Plotly.
"""
@classmethod
def make_scattergl_map(cls, xs, ... |
'''
simple if/else
'''
def main():
a = 'x'
if a == 'x':
print('ok')
|
#!/usr/bin/python
#-*- coding: utf-8 -*-
# =========================================================================
# Program: S1Processor
#
# Copyright (c) CESBIO. All rights reserved.
#
# See LICENSE for details.
#
# This software is distributed WITHOUT ANY WARRANTY; without even
# the implied warranty o... |
import uuid
from datetime import datetime
from app import db
from sqlalchemy.ext.hybrid import hybrid_property
class Project(db.Model):
__tablename__ = "projects"
id = db.Column(db.Integer, primary_key=True)
public_id = db.Column(db.String, unique=True, default=uuid.uuid4)
name = db.Column(db.String(... |
import unittest
import BasePage
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
caps=DesiredCapabilities.FIREFOX
caps['wires']=True
class LoginTestCase(unittest.TestCase):
def setUp(self):
self.driver= webdriver.Firefox(capabilities=caps)
... |
from setuptools import setup
setup(use_scm_version=True)
|
# -*- coding: utf-8 -*-
import unittest
import mock
from docktors.core import DecWrapper, decorated
class TestDecWrapper(unittest.TestCase):
def test__check_inputs_mandatory_arg_missing(self):
# GIVEN
props = dict(str_prop=dict(argtype=[str], mandatory=True))
inputs = dict(other_prop='va... |
import boto3
import argparse, os, sys
sys.path.insert(1, os.path.join(sys.path[0], '../..'))
from settings import settings
parser = argparse.ArgumentParser(description='Create a trigger when a file is uploaded to an specific S3 bucket.')
parser.add_argument('--bucket', type=str,
help='Bucket name.'... |
__author__ = 'HaoBin'
from XGraph2 import *
import copy, cProfile
def generate(m,n):
# recursively generates a list of values according to m, n parameter
# where m is the size of the alphabet set
# and n is the length of each string
# Complexity: O(M^N)
dict = []
for i in range(m):
dic... |
import sys
from pyspark.sql import SparkSession
import pyspark.sql.functions as f
spark = SparkSession \
.builder \
.appName("geocode") \
.config("spark.some.config.option", "some-value") \
.getOrCreate()
metadataPath = sys.argv[1]
metadataDF = spark.read.json(metadataPath, multiLine =... |
"""Registry Script Snippets
Parsing registry hives is a common task for Windows host analysis.
The ``yarp`` library is a robust library for parsing registry
hives and this section will show examples of how to use it.
"""
|
from .wheel import main
def main_p():
main(type='pad')
if __name__ == '__main__':
main_p() |
"""Print Dialog for Grail Browser.
This displays a dialog allowing the user to control printing of the current
document. The following printing characteristics can be controlled from the
dialog:
- the print command (which should take PostScript from stdin
or a %s can be placed on the command line w... |
# coding: utf-8
# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department
# Distributed under the terms of "New BSD License", see the LICENSE file.
import os
import shutil
import subprocess
from pyiron.base.settings.install import command_line
import unittest
class ... |
def preprocess(input_file, output_file):
all_queries = []
with open(input_file, 'r', errors='ignore') as infile:
for line in infile.readlines():
e1, r, e2 = line.strip().split('\t')
r_num = len(r.split('.'))
if r_num == 1:
all_queries.append([e1, r, e2... |
from unittest import TestCase
class Test(TestCase):
"""
The test will be done in User class because it extends Credentials
"""
def test_credentials(self):
self.fail()
|
# detect cycle in directed graph
# https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/CycleInDirectedGraph.java
from graph import *
GRAY = "gray"
BLACK = "black"
WHITE = "white"
def has_cycle(graph):
visited = set()
current_stack = set()
for vertex in graph.all_vertex.values()... |
import nomad.api.exceptions
from nomad.api.base import Requester
class Status(object):
"""
By default, the agent's local region is used
https://www.nomadproject.io/docs/http/status.html
"""
def __init__(self, **kwargs):
self.leader = Leader(**kwargs)
self.peers = Peers(**kwargs... |
from social_auth.backends.facebook import FacebookBackend
from social_auth.backends import google
def social_extra_values(sender, user, response, details, **kwargs):
result = False
if "id" in response:
from apps.photo.models import Photo
from urllib2 import urlopen, HTTPError
from ... |
# coding=utf-8
from .parsed_date import ParsedDate # noqa
|
from django import forms
from utils.fields import SlugField
from utils.forms import BootstrapMixin, SmallTextarea, StaticSelect, add_blank_choice
from .enums import PasswordAlgorithm
from .models import Platform
class PlatformForm(BootstrapMixin, forms.ModelForm):
slug = SlugField(max_length=255)
password_a... |
import json
import time
from typing import List, Tuple, cast, Callable
import polyline
import requests
from .joblib import memory
class _QueryTopo:
_last_query: float = 0
def __call__(self) -> Callable[[List[Tuple[float, float]]], List[float]]:
@memory.cache
def impl(data: List[Tuple[float,... |
from pathlib import Path
import os
import sys
source_path = str(Path(os.path.abspath(__file__)).parent.parent)
if source_path not in sys.path:
sys.path.insert(0, source_path)
import pandas as pd
from sqlalchemy import create_engine
import os
import yaml
from os.path import expanduser
from pathlib import Path
from ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
TIPO = 'selectable' # 'basic' or 'selectable'. 'basic': necesario para el funcionamiento del programa
# 'selectable': No necesario. Añade nuevas funcionalidades al programa
# Por ejemplo autenticar es 'basic', pero actas es pre... |
#!/usr/bin/env python3
# encoding: utf-8
# cook_datasets.py
import numpy as np
import pandas as pd
import pickle
from sklearn.preprocessing import StandardScaler
USPS_DIM = 256
LEU_DIM = 7129
def unpickle(file):
with open(file, 'rb') as fo:
dict = pickle.load(fo, encoding='bytes')
return dict
... |
#! /usr/bin/env python
import os
import numpy as np
import astropy.io.fits as fits
from . import noise_simulation as ng
def add_dark_current(ramp, seed, gain, darksignal):
"""
Adds dark current to the input signal
Parameters
----------
ramp: sequence
The array of ramp images
seed: i... |
'''!
Декларация класса Depth_calculator и запуск ноды данного класса в main()
'''
import rclpy
import cv2 as cv
from rclpy.node import Node
from sensor_msgs.msg import Image
from std_msgs.msg import Float32
from cv_bridge import CvBridge
import sys
import time
import numpy as np
class Depth_calculator(Node):
'''!... |
from unittest import TestCase
from kaggle_runner.logs import NBatchProgBarLogger
class TestLogs(TestCase):
@classmethod
def setup_class(cls):
"prepare a dummy model for logger to show"
# TODO set up a dummy model / or just use imagenette
cls.model = None
@classmethod
def tear... |
"""
Description
===========
A Ducci sequence is a sequence of n-tuples of integers, sometimes known as "the
Diffy game", because it is based on sequences. Given an n-tuple of integers
(a_1, a_2, ... a_n) the next n-tuple in the sequence is formed by taking the
absolute differences of neighboring integers. Ducci sequen... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.