content stringlengths 5 1.05M |
|---|
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
import json
from pa... |
#from .geometry import Scope
class ContextSimple():
def getStartObj(self):
return 0
def split(self, obj):
print("hello")
print(obj)
return (obj, obj+1)
def colour(self, obj, colour):
print("yo")
print(obj)
print(colour)
|
from rob.cli import cli
from rob.console import print_
# Entry point for application
cli() # pylint: disable=no-value-for-parameter
# TODO: should we try to clean up library and filesystem if left in an inconsistent state?
print_("")
|
# -*- coding: utf-8 -*-
"""
This module contains the flask view functions for the
web application.
:Authors: Balwinder Sodhi
"""
from flask import current_app as app
from flask import (Flask, jsonify, request, session)
from flask.blueprints import Blueprint
from werkzeug.utils import secure_filename
from passlib.hash ... |
# License: MIT
import time
import sys
import traceback
from openbox.utils.constants import MAXINT, SUCCESS, FAILED, TIMEOUT
from openbox.utils.limit import time_limit, TimeoutException
from openbox.core.message_queue.worker_messager import WorkerMessager
class mqmfWorker(object):
"""
message queue worker for... |
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from main.models import User
from main.defaults import get_default_username
from sms.lib import format_number
class UserSerializer(serializers.ModelSerializer):
id = serializers.ReadOnlyField()
username = seriali... |
from zeit.cms.browser.resources import Resource, Library
lib = Library('zeit.campus', 'resources')
Resource('editor.css')
|
# Joshua Nelson Gomes (Joshua)
# CIS 41A Spring 2020
# Take Home Assignment G
def main():
# Part Three – – Dictionary Keys and Sets
states = {}
file = open('USPresidents.txt', 'rt')
for line in file:
x = line.split()
if x[0] in states:
states[x[0]] += 1
else:
states[x[0]] = 1
for state in states:... |
"""VCD pattern matcher."""
from typing import Dict
from hdltools.patterns.matcher import PatternMatcher
from hdltools.vcd.parser import BaseVCDParser, VAR_PARSER
from hdltools.vcd.variable import VCDVariable
# TODO: extract pattern matching logic and abstract to generic data source
class VCDPatternMatcher(BaseVCDPar... |
#!/usr/bin/env python
from argparse import ArgumentParser
import sys
from fsspec.implementations.local import LocalFileSystem
from transformer.transform import Transform
sys.path.append('..')
from disemvowel import disemvowel # noqa
'''
Sample usage:
./main.py banana.txt bnn.txt [-w]
'''
if __name__ == '__main__':... |
# Generated by Django 2.2.13 on 2020-06-25 14:05
from django.contrib.auth.models import User
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('cms', '0054_blog_author'),
]
def add_blog_authors(apps, schema_editor):
BlogAuthor = apps.get_model('cms... |
#!/usr/bin/env python3
#
# Solve a crackme using instruction counting. Works if the flag is
# checked byte for byte.
#
# Requires pin and the pintools from the ManualExamples folder.
#
import sys
import os
def run(data):
with open('input', 'wb') as f:
f.write(bytes(data))
os.system("../../../../pin -t... |
import xml.dom.minidom
import type_mapper
class adiosConfig:
def __init__ (self, config_file_name):
self.config_file_name = config_file_name
#This would be a good time to parse the file...
doc = xml.dom.minidom.parse (config_file_name)
nodes = doc.childNodes
if (nodes.len... |
# Copyright (c) <2011>, Steven Caron <steven@steven-caron.com>
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice,... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib2
from StringIO import StringIO
from lxml import etree
def download_image(image_url, local_folder, folder_index):
ufile = urllib2.urlopen(image_url)
root = etree.parse(ufile, etree.HTMLParser())
dwnld = root.xpath('//div[@class="wallpaper_big"]//div[@class="w... |
from enum import IntEnum, auto
class Dir(IntEnum):
East = 0
South = 1
West = 2
North = 3
ACTIONS = []
with open('input.txt') as f:
for fl in f:
ACTIONS.append(fl.strip())
ship_x, ship_y, ship_dir = 0, 0, Dir.East
def turn_ship(param, direction):
d = ship_dir
while param > 0:
... |
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# 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.... |
# -*- coding: utf-8 -*-
#
# Author: Tomi Jylhä-Ollila, Finland 2017
#
# This file is part of Kunquat.
#
# CC0 1.0 Universal, http://creativecommons.org/publicdomain/zero/1.0/
#
# To the extent possible under law, Kunquat Affirmers have waived all
# copyright and related or neighboring rights to Kunquat.
#
from .procp... |
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 9 16:47:14 2021
@author: Mike
"""
import algoritmosSumas
import random as rn
import copy
from time import time
def crear_lista(longitud):
lista = []
for i in range(0,longitud):
lista.append(rn.randint(-150, 150))
return lista
if __name__=="__main__... |
import asyncio
import websockets
from socket import AddressFamily
from EventWriter import EventWriter
from events.PleaseRestartEvent import PleaseRestartEvent
class WSBroadcastEventWriter(EventWriter):
def __init__(self, ws_gap_closer_callback):
super().__init__()
self.__clients = set()
s... |
import os
from django.db import migrations
def store_filename(apps, schema_editor):
Example = apps.get_model("examples", "Example")
for example in Example.objects.all():
example.upload_name = os.path.basename(example.filename.name)
example.save()
class Migration(migrations.Migration):
... |
import json
import torch
import numpy as np
import time
import os
import sys
import copy
from copy import deepcopy
import cloudvolume as cv
from pdb import set_trace as st
from helpers import normalize, create_model, get_np
from taskqueue import RegisteredTask, MockTaskQueue, TaskQueue
class NCCTask(RegisteredTask)... |
from cloudr.config import REDIS_URL
broker_url = REDIS_URL
result_backend = REDIS_URL
task_serializer = 'json'
result_serializer = 'json'
accept_content = ['json']
beat_schedule = {
'refresh': {
'task': 'task.download.refresh',
'schedule': 10.0
}
}
|
import json
import os, sys
import jsonschema
from jsonschema import validate
# local imports
from src.log import rootLogger
logger = rootLogger.getChild('CONFIG')
cfg = None
schema = """
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"threads": {
"type": "s... |
from .models import UserPoints, PointSetting
from ..payments.models import Payment
from ..users.services import FCMService
class PointsService(object):
def __init__(self):
self.settings = PointSetting.objects.first()
def book_approval_award(self, user, book_id):
if self.settings and self.sett... |
from pathlib import Path
from diot import Diot
from bioprocs.utils import shell2 as shell, logger
from bioprocs.utils.parallel import Parallel, distributeList
{%from os import path%}
{%from pyppl.utils import always_list%}
infile = {{i.infile | quote}}
afile = {{i.afile | ?path.isfile | =readlines | !always_lis... |
from collections import defaultdict
def get_short_names(names):
'''
Given an iterable names, return the shortest prefix for each element
so that all prefixes are different. All elements in names must be unique.
>>> get_short_names(['cat', 'castor', 'could', 'fire', 'first'])
['cat', 'cas', 'co', ... |
from functools import wraps
def check_instrument_attributes(func):
@wraps(func)
def wrapper(*args, **kwargs):
inst = args[0]
if not hasattr(inst, "accuracy"):
raise NotImplementedError("Please add instrument attributes")
return func(*args, **kwargs)
return wrapper
|
# Write a program that keeps all the unique chemical elements.
# On the first line you will be given a number n - the count of input lines that you are going to receive.
# On the next n lines, you will be receiving chemical compounds, separated by a single space.
# Your task is to print all the unique ones on separa... |
# Copyright 2021 Andreas Steck (steck.andi@gmail.com)
#
# 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 ... |
# Link: https://github.com/AI-secure/Meta-Nerual-Trojan-Detection
# Author: @xiaojunxu
# License: MIT
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import librosa
class Model(nn.Module):
def __init__(self, gpu=False):
super(Model, self).__init__()
self.gpu =... |
from django.conf.urls import url
from . import views
app_name = "nominations"
urlpatterns = [
url(r"^elections/$", views.ElectionsList.as_view(), name="elections_list"),
url(r"^election/(?P<election>[-\w]+)/$", views.ElectionDetail.as_view(), name="election_detail"),
url(
r"^elections/(?P<election... |
from dice import *
from pool import *
import sys, re
def get_all_eote_dice():
"""Returns a dict of all the dice in the Edge of the Empire game."""
ddict = {
'Boost': Dice('Boost', ['', '', 'Success', ['Success', 'Advantage'], ['Advantage', 'Advantage'], 'Advantage']),
'Setback': Dice('Setback',... |
from .dqn import DQN
from .dueling import DuelingDQN
from .double import DoubleDQN
|
from timeit import default_timer as timer
start_time = timer()
arr = list(range(1, 1001))
ans = -1
for a in arr:
flag = False
for b in arr:
c = math.sqrt(a**2 + b**2)
if math.floor(c) == c and a+b+c == 1000:
flag = True
ans = c
break
if flag:
... |
# -*- coding: utf-8 -*-
# __author__ = 'elkan1788@gmail.com'
from ppytools.compresshelper import zipFile, tarFile
import unittest
import logging
import os
logger = logging.getLogger(__name__)
class TestCompressHelperCase(unittest.TestCase):
"""TestCompressHelperCase
"""
@classmethod
def setUpClass... |
"""Analyzer
Analyzer module for setting menu bar setup for OSX
"""
__author__ = "ales lerch"
import os
import cv2
import numpy
from PIL import Image
def check_image_color(image):
"""Returns string containing 'ligh' or 'dark' that tells if image is for day or night,
Y -- converting to gray to detect if it's ... |
index = 0
while index < 10:
print("Szoveg")
index = index + 1
|
# Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
# Example 1:
# Input: a = 1, b = 2
# Output: 3
# Example 2:
# Input: a = -2, b = 3
# Output: 1
class Solution:
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
... |
import json
from difflib import get_close_matches
data = json.load(open("data.json"))
def english_word(w):
w=w.lower()
if w in data:
return data[w]
elif w.title() in data: #if user entered "delhi" this will check for "Delhi" as well.
return data[w.title()]
elif w.upper() in da... |
import numpy as np
import math
def factorial(n):
fact = 1
for i in range(1,n+1):
fact *= i
return fact
summation = 1
for i in range(1,7):
val = (-1)**i * (math.pi/3)**(2*i) / factorial(2*i)
summation += val
print "val: ", val
print "summation: ", summation
print "Final summation: ", summation |
"""
Write a function that takes string characters as input and returns each characters hexadecimal value.
The output should be in the form of a string.
input_string = 'Python'
Expected output = '50 79 74 68 6f 6e'
"""
def convert_to_hex(input_string):
new = input_string.encode('utf-8')
final = new.hex()
... |
from setuptools import setup
setup(
name='UniqueBotsKR',
version='1.2',
packages=['UniqueBotsKR'],
url='https://github.com/gunyu1019/UniqueBotsKR',
license='MIT',
author='gunyu1019',
author_email='gunyu1019@yhs.kr',
description='UniqueBots를 위한 비공식 파이썬 API 레퍼입니다.',
python_requires='>... |
import numpy as np
import sys
def PYN(approx, real):
app = set(list(map(tuple, approx)))
rea = set(list(map(tuple, real)))
return len(app & rea)/len(real)
def DM(approx, real):
nadir = np.array([real[:, 0].min(), real[:, 1].min()])
ideal = np.array([real[:, 0].max(), real[:, 1].max()])
p = np.empty(2,... |
from unittest import TestCase
from salesforce.dbapi.subselect import (
find_closing_parenthesis, split_subquery, transform_except_subquery,
mark_quoted_strings, subst_quoted_strings, simplify_expression,
)
class TestSubSelectSearch(TestCase):
def test_parenthesis(self):
self.assertEqual(find_closi... |
import json
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from products.models import Product
from home.models import User
# Create your views here.
def get_products_list(request):
if request.method == 'GET':
products_list = Product.objects.all()
all_produ... |
# Generated by Django 3.2.5 on 2021-08-25 19:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("public_data", "0008_artifcommune"),
("project", "0005_auto_20210825_1559"),
]
operations = [
migrations.AlterField(
mode... |
#!/usr/bin/env python3
# @generated AUTOGENERATED file. Do not Change!
from enum import Enum
class UserStatus(Enum):
ACTIVE = "ACTIVE"
DEACTIVATED = "DEACTIVATED"
MISSING_ENUM = ""
@classmethod
def _missing_(cls, value: object) -> "UserStatus":
return cls.MISSING_ENUM
|
PE_LOGIN_URL = "http://58.192.114.239/student/studentFrame.jsp"
PE_PC_URL = "http://58.192.114.239/student/queryCheckInfo.jsp"
CONNECT_TIME_OUT = 3
API_SERVER_HOST = ''
API_SERVER_PORT = ''
API_SERVER_KEY = ''
SECRET_KEY1 = 0
SECRET_KEY2 = 0
A = hex(SECRET_KEY1^SECRET_KEY2)[2:-1] + API_SERVER_KEY + hex(SECRET_KEY1)[... |
# -*- coding: utf-8 -*-
"""A Simple Flask App main.py
process request and response
"""
import os
import sys
import inspect
from flask import Flask, request
from werkzeug import secure_filename
def insert_path():
"""insert parentdir"""
currentdir = os.path.dirname(os.path.abspath(
inspect.getfile(ins... |
"""Search a 2D Matrix
https://www.lintcode.com/problem/search-a-2d-matrix/description
"""
class Solution:
"""
@param matrix: matrix, a list of lists of integers
@param target: An integer
@return: a boolean, indicate whether matrix contains target
"""
def searchMatrix(self, matrix, target):
... |
# Copyright (C) 2010-2015 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# This signature was contributed by RedSocks - http://redsocks.nl
# See the file 'docs/LICENSE' for copying permission.
from lib.cuckoo.common.abstracts import Signature
class Suspicious_TLD(Signature):
... |
import rdkit.Chem as Chem
import networkx as nx
class molecule():
def __init__(self,mol):
self.mol_name = mol
self.mol = Chem.MolFromMolFile(mol,removeHs=False)
self.atoms = self.mol.GetAtoms()
self.atoms_idx = [i.GetIdx() for i in self.atoms]
self.charge=[atom.GetFormalChar... |
# coding: utf-8
import smtplib
import ssl
from email.mime.text import MIMEText
from email.utils import formataddr
from email.mime.multipart import MIMEMultipart # New line
from email.mime.base import MIMEBase # New line
from email import encoders # New line
import pandas as pd
grado = input("GRADO: ")
File = pd.rea... |
from direct.actor.Actor import Actor
from direct.directnotify import DirectNotifyGlobal
from direct.distributed import DistributedObject
from direct.interval.IntervalGlobal import *
from panda3d.core import *
from toontown.toonbase import ToontownGlobals
class DistributedTTCHQEventMgr(DistributedObject.DistributedObje... |
import pytest
import brownie
from brownie import ZERO_ADDRESS
yDaiV2Address = "0x16de59092dAE5CcF4A1E6439D611fd0653f0Bd01"
ethZapAddress = "0x5A0bade607eaca65A0FE6d1437E0e3EC2144d540"
@pytest.fixture
def earnGenerator(AddressesGeneratorEarn, oracle, helper, management):
registryAddress = "0x62a4e0E7574E5407656A6... |
import json
def convert_json_to_dict(text: str):
"""Function that converts JSON to dictionary
Args:
text (str): text to be processed
Returns:
str: processed text
"""
return json.loads(text)
class JSONString:
"""Class that handles conversion of JSON strings
Args:
... |
import pandas as pd
import csv
import glob
import os
from pathlib import Path
import xlrd
from money import Money
def get_path():
return str(Path().absolute()) + "/"
def convert_to_csv(output_file_name,my_file, my_sheet_name="Sheet1",my_index=False):
wb = xlrd.open_workbook(str(my_file), logfile=open(os.dev... |
handshake = {
'key': 'API_KEY_HERE'
},
fishbowl = {
'host': 'HOST_ADDRESS_OF_FISHBOWL_SERVER',
'user': 'USER_NAME_OF_FISHBOWL_ADMIN',
'password': 'PASSWORD_FOR_FISHBOWL_ADMIN'
},
# handbowl_settings = {
# 'sync_products': True,
# 'sync_inventory': False,
# 'sync_customers': True,
# 'sy... |
# Copyright 2022 Sony Semiconductors Israel, 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 b... |
from os_ios_prepare_ipa_file import ipa_preparer as ip
ip.prepare_ipa_file(ipa_file_path="path/to/ipa_file.ipa",
ipa_file_path_in_server= "www.my_website.com/storage/ipa_file.ipa",
html_file_path_in_server="www.my_website.com/pages/download_latest_version/download.html",
... |
from __future__ import absolute_import, unicode_literals
import os
import tornado.web
from mopidy import config, ext
__version__ = '0.3.1'
class PartyRequestHandler(tornado.web.RequestHandler):
def initialize(self, core, data, config):
self.core = core
self.data = data
self.requiredVo... |
from experiment_helper_logo import *
from shape import *
import dsl
from DSL import logo
def print_clown():
eye1 = Polygon(5,3)
eye1.move(-2,-2)
eye2 = Polygon(5,3)
eye2.move(2,-2)
s4 = Circle(4)
smile1 = Rectangle(10, 3)
smile1.move(-1, 2)
smile2 = Rectangle(10, 3)
smile2.move(1, 2... |
# https://leetcode.com/problems/sum-of-two-integers/
class Solution:
def getSum(self, a: int, b: int) -> int:
x = 0xffffffff
# python default int size is not 32bit, it is very large number, so to prevent overflow and stop running into infinite loop, we use 32bit mask to limit int size to 32bit
... |
{
"targets": [
{
"target_name": "EspressoLogicMinimizer",
"cflags": ["-std=c99", "-Wno-misleading-indentation", "-Wno-unused-result", "-Wno-format-overflow", "-Wno-implicit-fallthrough"],
"sources": [
"bridge/addon.cc",
"bridge/bridge.c",
... |
# This code is written at BigVision LLC. It is based on the OpenCV project. It is subject to the license terms in the LICENSE file found in this distribution and at http://opencv.org/license.html
# Usage example: python3 object_detection_yolo.py --image=gBanana1.jepg
import cv2 as cv
import argparse
import sys
impor... |
from lib import action
class ColorTempMiredAction(action.BaseAction):
def run(self, light_id, temperature, transition_time):
light = self.hue.lights.get(light_id)
light.ct(temperature, transition_time)
|
from __future__ import absolute_import
import numpy as np
import os
from . import shocktube
"Runs the shocktube test problem with the Python HLLC solver."
claw = shocktube.setup(kernel_language='Python')
claw.run()
test_solution = claw.solution.state.get_q_global()
if test_solution is not None:
thisdir = os.path... |
from pyvdp.visadirect import VisaDirectDispatcher
def send(data):
"""Submits a WatchlistInquiry request.
:param WatchListInquiryModel data: **Required**.
Instance of :func:`~pyvdp.visadirect.watchlist.WatchListInquiryModel`.
:return: Dictionary with VDP API response.
**Usage:*... |
"""CLI for the Data Delivery System."""
####################################################################################################
# IMPORTS ################################################################################ IMPORTS #
#############################################################################... |
from typing import List, Literal
import blessed
from blessed.keyboard import Keystroke
import time
import tictactoe
import os
from utils import Vec
from draw_circle import draw_circle, draw_cross
import logging
if "logs" not in os.listdir():
os.mkdir("logs")
logging.basicConfig(filename="logs/debug.log", level=lo... |
# Copyright 2021 The Pigweed 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
import os
import boto3
from datetime import datetime
def lambda_handler(event, context):
print('Helper triggered...')
# Environment Variables
replication_function_name = os.environ['ONGOING_REPLICATION_FUNCTION_NAME']
ssm_event_source_mapping_uuid = os.environ['SSM_EVENT_SOURCE_MAPPING_UUID']
ssm_... |
from setuptools import setup
setup(
name='postdoc',
version='0.4.0',
description='A helper for Postgres + Docker that works for free',
long_description=open('README.rst').read(),
author='Chris Chang',
author_email='c@crccheck.com',
url='https://github.com/crccheck/postdoc',
py_modules=... |
################################################################################
#
# Copyright (c) 2019, the Perspective Authors.
#
# This file is part of the Perspective library, distributed under the terms of
# the Apache License 2.0. The full license can be found in the LICENSE file.
#
from logging import critical
... |
import os
import shutil
folders = os.listdir()
for folder in folders:
if not os.path.isdir(folder):
continue
files = os.listdir(folder)
for file in files:
if file.split('.')[-1] == 'txt':
continue
src = os.path.join(folder,file)
batch = file.split('_')[0]
dir = os.path.join('..','packed',batch)
if no... |
from data_maker import DataDescriptor, DataMaker, TruncatedNormalParameters
from utils import SolutionVisualizer
from greedy_planner import Planner
if __name__ == '__main__':
size = [60, 120, 180]
covid = [0.5]
anesthesia = [0.8]
anesthetists = [1, 2]
for s in size:
for c in covid:
... |
import copy
import numpy as np
import os
import glob
import pdb
import subprocess
import yaml
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
from sdss import yanny
from apogee.speclib import atmos
from apogee.utils import spectra
from apogee.plan ... |
# coding: utf-8
import socketserver
from pathlib import Path # for checking if files exist
# Copyright 2013 Abram Hindle, Eddie Antonio Santos, Peter Weckend
#
# 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 cop... |
"""Docstring de uma linha"""
variavel = 'valor'
def um():
return 1
|
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import pathlib
import sqlite3
import json
class DyntaxaDbCache:
""" """
def __init__(self, db_file="data_in/dyntaxa_db_cache_2.db"):
""" """
self.db_file = db_file
self.db_path = pathlib.Path(self.db_file)
def create_db(self):
... |
import h5py
def save_file(data, filename, dataset_name="data"):
"""Save a np.array in hdf5 format.
Args:
data (np.array): An array.
filename (str): Name of the file.
Examples:
>>> a = np.array([[1,2,3],[4,5,6]])
>>> save_file(a, 'file.hdf5')
>>> os.path.is... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
try:
with open("manifesto.txt") as f:
manifesto = f.readlines()
manifesto = [word.strip() for word in manifesto]
except Exception as e:
print(e)
activated_commands = [
'!help',
'!bug',
'!femops',
'!eightball',
'!roulette',
'!export',
'!di... |
import numpy as np
from scipy.spatial import distance_matrix
def distance2(A, B):
M = A.shape[0]
N = B.shape[0]
A_dots = (A*A).sum(axis=1).reshape((M, 1))*np.ones(shape=(1, N))
B_dots = (B*B).sum(axis=1)*np.ones(shape=(M, 1))
D_squared = A_dots + B_dots - 2*A.dot(B.T)
zero_mask = np.less(D_... |
import torch
import logging
from torch import Tensor
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models.utils import load_state_dict_from_url
from typing import Type, Any, Callable, Union, List, Optional
from ..builder import BACKBONES
from mmcv.runner import load_checkpoint
from mmcv.utils.p... |
def get_y(event, context):
return dict(oh="yaaaaa!")
function_mapping = {
"GET:/api/Y": get_y
}
def route_request(event, context):
if "route" not in event:
raise ValueError("must have 'route' in event dictionary")
if event["route"] not in function_mapping:
raise ValueError("cannot f... |
# Time complexity: O(n*n)
# Approach: Storing words in Trie and applying dfs.
class TrieNode:
def __init__(self):
self.child = defaultdict(TrieNode)
self.isWord = False
def addWord(self, word):
curr = self
for c in word:
curr = curr.child[c]
curr.isWord = Tr... |
def funk(a, b = 5, c = 10):
print("a je ", a, ", a b je ", b, " i c je ", c)
funk(3,7)
funk(25, c=24)
funk(c=50, a=100)
|
from dataclasses import dataclass
from typing import Any, Callable
from avilla.core.service import ExportInterface
from avilla.core.service.entity import BehaviourDescription
from avilla.core.service.session import BehaviourSession
from avilla.core.stream import Stream
@dataclass
class PostConnected(BehaviourDescrip... |
from flask import Flask,render_template, request,redirect
from instamojo_wrapper import Instamojo
API_KEY ="test_4b6c991d2d6f02dc9b4aa45127e"
AUTH_TOKEN = "test_fe8287ed5f08248dc08558dd8b8"
app = Flask(__name__,template_folder='template')
api = Instamojo(api_key=API_KEY,auth_token=AUTH_TOKEN,endpoint='https://te... |
from rest_framework import viewsets
from admirer_app.models import Secret_Messages
from admirer_app.serializers import SecretMessagesSerializer
from django_filters.rest_framework import DjangoFilterBackend
# Create your views here.
class SecretMessageViewSet(viewsets.ModelViewSet):
queryset = Secret_Messages.obje... |
import os
from colorama import Fore, Style
from instascrape.commands import COOKIES_DIR, OBJECT_FILE, error_print, warn_print, load_obj, error_catcher
def logout_handler(**args):
real = args.get("real")
insta = load_obj()
if insta is None:
error_print("No session is logged in currently.", exit=1... |
from logging import getLogger
from django.core.management.base import BaseCommand
from django.core.management.base import CommandError
from django.utils.functional import cached_property
from hornet.client import Client
from hornet.models import Account
logger = getLogger(__name__)
class ClientCommand(BaseCommand)... |
# Get the desired future value.
future_value = float(input('Enter the desired future value: '))
# Get the annual interest rate.
rate = float(input('Enter the annual interest rate: '))
# Get the number of years that the money will appreciate.
years = int(input('Enter the number of years the money will grow: '))
# Cal... |
# SPDX-License-Identifier: Apache-2.0
# coding: utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np # type: ignore
import onnx
from ..base import Base
from . import expect
from typing import Se... |
import petl as etl
from fhir_petl.util import preprocess, resolve, mkdirp
mkdirp(resolve('work'))
preprocess(
etl.io.csv.fromcsv(resolve('Table_1_Demographics_New_Cohorts.csv'))
).tocsv(resolve('work/Patient.csv'))
preprocess(
etl.io.csv.fromcsv(resolve('Diagnoses.csv'))
).tocsv(resolve('work/Condition.csv')... |
## ----- Uzdevums-2 -----
"""
Uzrakstiet funkciju is_palindrome(text)
kas atgriež bool True vai False atkarībā vai vārds vai teikums ir lasāms vienādi no abām pusēm.
PS no sākuma varat sākt ar viena vārda risinājumu, bet pilns risinājums ignorēs atstarpes(whitespace) un lielos/mazos burtus
is_palindrome("Alus ari ira ... |
"""The shogoth reader."""
import re
from typing import Any
from lark import (
Lark,
Token,
Transformer,
Tree,
v_args,
)
from shogoth.parser import parse
from shogoth.types import Keyword, Symbol
# Monkeypatching for py3.10 matching
Tree.__match_args__ = ("data", "children")
Token.__match_args__... |
from modules.ranking.models.ranking import Ranking
from modules.ranking.query.base import MISSION_PACKAGE_RANKING_BASE_QUERY
class MissionPackagesRanking(Ranking):
BASE_QUERY = MISSION_PACKAGE_RANKING_BASE_QUERY
def __init__(self, mission_package):
self.mission_package = mission_package
def get_... |
import json
import math
import os
import random
import tempfile
from typing import Optional, Union, List, Dict
from datasets import load_dataset
from torch.utils.data import DataLoader
from lm_eval.pl_models import (
LitGPT2,
LitT5, VAL_LOSS, VAL_ACC
)
from transformers import set_seed
import pytorch_lightni... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.