content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
import json
def save_json(file_path, data):
"""
Load data to json file.
>>> save_json("./JsonAccessorDoctest.json", "{"Fuji": {"Id": 30, "server": ["JP", "CN"]}}") # doctest: +SKIP
"""
with open(file_path, 'w', encoding='utf8') as outfile:
json.dump(data, outfile, ... |
"""
This lambda compares new batches to previous batches to detect
which records are missing from the new one. These indicate that
a membership has lapsed.
"""
import datetime
import json
import os
import boto3
from actionnetwork_activist_sync.actionnetwork import ActionNetwork
from actionnetwork_activist_sync.loggi... |
"""
vp_overlap.py
Do calculations for overlap type functionals
"""
import numpy as np
from scipy.special import erf
def vp_overlap(self):
const = 2
#Calculate overlap
self.E.S = self.grid.integrate((np.sum(self.na_frac, axis=1) * np.sum(self.nb_frac, axis=1))**(0.5))
self.E.F = erf( const * self.E.S... |
from datetime import datetime
def voto(ano):
global idade
idade = datetime.now().year - ano
if idade < 16:
return 'NEGADO'
elif idade < 18:
return 'OPCIONAL'
else:
return 'OBRIGATORIO'
idade = 0
tip = voto(int(input('Em que ano vc nasceu?: ')))
print(f'com {idade} anos, O seu... |
# -*- coding: utf-8 -*-
import base64
import urlparse
import urllib
import hashlib
import re
from resources.lib.modules import client
from resources.lib.modules import directstream
from resources.lib.modules import trakt
from resources.lib.modules import pyaes
RES_4K = ['4k', 'hd4k', 'hd4k ', '4khd', '4khd ', 'uhd... |
# -*- coding: utf-8 -*-
from collections import OrderedDict
from copy import deepcopy
import errno
import fnmatch
import logging
import os
import random
import shutil
import string
import subprocess
import yaml
import sys
from ansible_vault import Vault
def _is_py3():
return True if sys.version_info >= (3, 0) el... |
def a(z):
print(z + z)
a(0)
a('e')
a([0])
|
# Generated by Django 2.2.5 on 2019-10-26 18:45
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Cat... |
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
RESOLUTION = ["Performance Tuning of Cortex XSOAR Server: https://docs.paloaltonetworks.com/cortex/cortex-xsoar/6-0/"
"cortex-xsoar-admin/cortex-xsoar-overview/performance-tuning-of-cortex-xsoar-server"]
def ana... |
class DSN:
def __init__(self,
user,
password,
database="test", host="localhost", port: int = 3306, charset="utf8"):
self.user = user
self.password = password
self.host = host
self.port = port
self.database = database
... |
from vart.sampler.walkers import Walkers
class SamplerBase(object):
def __init__(self,nwalkers=1000, nstep=1000, nelec=1, ndim=3,
step_size = 3, domain = {'min':-2,'max':2},
move='all'):
self.nwalkers = nwalkers
self.nstep = nstep
self.step_size = step_s... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2021 Johns Hopkins University (Jiatong Shi)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import argparse
import codecs
import sys
def get_parser():
parser = argparse.ArgumentParser(description="language identification scoring")
parser... |
# -*- coding: utf-8 -*-
import pytest
import csv
import sys
import os
from filecmp import cmp
from feature_extractor.feature_extractor import FeatureExtractor
__author__ = "Harvey Bastidas"
__copyright__ = "Harvey Bastidas"
__license__ = "mit"
class Conf:
""" This method initialize the configuration variables f... |
# coding:utf-8
from . import api
from ..models import User,Bucketlist
from flask import request, jsonify, abort, make_response
@api.route('/bucketlists/', methods=['POST', 'GET'])
def bucketlists():
# get the access token
access_token = request.headers.get('Authorization')
if access_token:
user_id... |
# Standard Library
import asyncio
import json
import logging
import os
import time
from datetime import datetime
# Third Party
import kubernetes.client
from elasticsearch import AsyncElasticsearch, exceptions
from elasticsearch.helpers import async_streaming_bulk
from kubernetes import client, config
from kubernetes.c... |
from django import template
from django.contrib.auth.models import User
from ..forms import UserCreateForm
register = template.Library()
@register.inclusion_tag('registration/_signup.html')
def signup_form():
return {'form': UserCreateForm(instance=User())}
|
coordinates_E0E1E1 = ((128, 86),
(129, 81), (129, 84), (129, 86), (130, 82), (130, 86), (130, 97), (130, 116), (130, 119), (131, 69), (131, 82), (131, 84), (131, 86), (131, 96), (131, 97), (131, 112), (131, 114), (131, 116), (131, 117), (131, 119), (132, 70), (132, 71), (132, 83), (132, 85), (132, 87), (132, 96), (13... |
# =============================================================================
#
# Jade Tree Personal Budgeting Application | jadetree.io
# Copyright (c) 2020 Asymworks, LLC. All Rights Reserved.
#
# =============================================================================
from flask.views import MethodView
from... |
from setuptools import setup
import codecs
from fns import __version__
with codecs.open('README.md', 'r', 'utf-8') as readme:
long_description = readme.read()
setup(
name='fns',
version=__version__,
description='Revise receipt client',
author='Sergey Popov',
author_email='poserg@gmail.com',
... |
from pyconvcli import PyConvCli
import os
def main():
cli = PyConvCli('pyconvcli_internal_cli',os.path.dirname(os.path.realpath(__file__)),'pyconvcli')
cli.run()
def visualize():
cli= PyConvCli('pyconvcli_internal_cli',os.path.dirname(os.path.realpath(__file__)),'pyconvcli')
args,parsers = cli.parse_a... |
class VectorUtils:
def __init__(self):
pass
@staticmethod
def norm_2(vec):
return vec[0]**2 + vec[1]**2 + vec[2]**2
@staticmethod
def norm(vec):
return VectorUtils.norm_2(vec)**(1./2)
|
import time # so we can use "sleep" to wait between actions
import RPi.GPIO as io # import the GPIO library we just installed but call it "io"
from ISStreamer.Streamer import Streamer # import the ISStreamer
## name the bucket and individual access_key
#streamer = Streamer(bucket_name="Locker Protector", bucket_key="l... |
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from django.utils.translation import ugettext_lazy as _
title = _("Reporters and Groups")
tab_link = "/reporters"
|
# persistence.py
"""
Wrapper to edit the persistent settings
"""
import os
import sys
import pathlib
import argparse
import configparser
import thinkpad_tools_assets.classes
from thinkpad_tools_assets.cmd import commandline_parser
from thinkpad_tools_assets.utils import NotSudo
try:
if os.getuid() != 0:
... |
from .interval import Interval, str_to_iv
from dataclasses import dataclass
from itertools import product
from math import prod
@dataclass(frozen=True)
class Cuboid:
points: list[Interval]
value: any = None
def volume(self) -> int:
return prod((x.get_length() for x in self.points))
def di... |
import argparse
from .display import LINE_SIZE
class Args:
def __init__(self, * args, mutex: list = [], group: list = [], **kargs):
self.args = args
self.kargs = kargs
self.group = group
self.mutex = mutex
self.arguments = None
def build(self, parser=None):
i... |
from datetime import datetime as dt
import requests, re
import pandas as pd
import numpy as np
import json
import time
import os
import tushare as ts
import logging
from bs4 import BeautifulSoup
logger = logging.getLogger('main.fetch')
def fetch_index(index_name):
path = os.path.dirname(os.path.abspath(__file__))... |
import os.path
from nbt.nbt import NBTFile
from PIL import Image
from config import *
def main():
# Read map files to sort by scale
print("Reading map files...")
mapfiles = []
for i in range(0,5):
mapfiles.append([])
i = 0
while os.path.isfile(inputDir + "map_" + str(i) + ".dat"):
# read file
nbt = NBTFil... |
from queue import Queue
import threading
class Synchonizer:
def __init__(self):
return
|
nome = str(input('Digite o seu nome completo: ')).strip().title()
fatiar = nome.split()
fatiar2 = nome.split()
print(f'Primeiro nome: {fatiar[0]};')
print(f'Último nome: {fatiar2[-1]}.')
|
#!/usr/bin/env python3
import os
import numpy as np
from shutil import copyfile
import glob
import argparse
import h5py
import datetime
from dateutil.parser import isoparse
import time
import decimal
import shutil
from scipy.interpolate import interp2d
import pybind_isce3 as isce3
from shapely import wkt
from alos_t... |
from django.conf.urls import url
from django.urls import include, path
from django.contrib.auth import views as auth_views
from django.urls import reverse_lazy
from envelope.views import ContactView
from . import views
from .forms import MyContactForm
urlpatterns = [
# path('change-password/', auth_views.Passwo... |
"""
Finds all possible combinations of integers below value to generate value
Author: Juan Rios
"""
import math
"""
Calculate the possible number of partitions
"""
def find_partitions_dict(limit_value):
p = {(1,1):0}
for i in range(2,limit_value+1):
tmp = 1
index = 1
while index<=(i-ind... |
""" This script generates google search queries and uses requests to go get
the HTML from the google search page. This was the most time-consuming
step in the process.
Certain lines are commented out as evidence of debugging and
to help me remember what I had already done.
Anyways, this script ma... |
from django import forms
from django.core.exceptions import ValidationError
import re
def validar_exclucion_numeros(value):
if value != 'None':
numeros = re.sub("[^0-9]", "", value)
if numeros:
raise ValidationError("No permite numeros")
else:
return value
retur... |
class Solution:
def maxNumber(self, nums1, nums2, k):
"""
:type nums1: List[int]
:type nums2: List[int]
:type k: int
:rtype: List[int]
"""
def prep(nums, k):
dr = len(nums) - k # 要删除的数目
stay = [] # 保留的list
for num in ... |
from BeautifulSoup import BeautifulSoup
from urllib2 import urlopen
import re
print("Searching... please wait")
emails=[]
url="http://www.bbe.caltech.edu/people-public/all/all"
data=urlopen(url)
parse=BeautifulSoup(data).findAll('a')
b=[parse[k]['href'][7:] for k in range(len(parse)) if "@" in parse[k]['hre... |
from __future__ import absolute_import
from .base import ViewTest, TemplateViewTest, RedirectViewTest
from .dates import (ArchiveIndexViewTests, YearArchiveViewTests,
MonthArchiveViewTests, WeekArchiveViewTests, DayArchiveViewTests,
DateDetailViewTests)
from .detail import DetailViewTest
from .edit import (Mod... |
#!/usr/bin/env python
"""
Insert blank notes at the top of every set of cards.
Useful for creating new cards in bulk with an editor.
This is undone by running the normalization code, `sort.py`.
"""
import glob
from collections import OrderedDict
from library import DynamicInlineTableDict
from library import NoteLi... |
from math import sqrt
class cone():
def __init__(self,radius,height):
self.radius = radius
self.height = height
def volume(self):
r = 3.14*self.radius**2*(self.height/3)
print("Volume of Cone a is : ",r)
def surfaceArea(self):
import math
c = 3.1... |
# Copyright 2018 by Paolo Inglese, National Phenome Centre, Imperial College
# London
# All rights reserved.
# This file is part of DESI-MSI recalibration, and is released under the
# "MIT License Agreement".
# Please see the LICENSE file that should have been included as part of this
# package.
import t... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
vi $HOME/.LoginAccount.txt
[mailClient]
host = smtp.qq.com
port = 25
user = ***
pass = ***
fr = xxxxxx@qq.com
to = xxxxxx@gmail.com
debuglevel = True
login = False
starttls = False
'''
__all__ = ['get_smtp_client', 'sendmail']
import os, sys
from ConfigParser import ... |
from django.urls import path
from . import views
urlpatterns = [
path("", views.profil, name="profil"),
path('sport_profil/', views.create_sport_profil, name="createSportProfil"),
]
|
from __future__ import division, absolute_import
__copyright__ = """
Copyright (C) 2013 Andreas Kloeckner
Copyright (C) 2018 Matt Wala
Copyright (C) 2018 Hao Gao
"""
__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the ... |
"""
Render shortest/fastest paths for intervals as HTML.
"""
from typing import Any, List, Optional, Tuple
import attr
import osmnx as ox
from jinja2 import Template
from .routing import RestrictedGraph
from .calculation import IntervalCalculation
@attr.define
class Page:
"""
A full HTML page of interval calc... |
# -*- coding: utf-8 -*-
from .Cardstack import *
from .Exception import *
from copy import deepcopy
playPreds = ("PLAY", "PLAY COIN", "THRONE", "THRONE GENERIC", "THRONE COIN", "KING")
# -- Standard Exceptions -- #
def persistent(exc):
newExc = deepcopy(exc)
newExc.persistent = True
return newExc
def... |
import unittest
import numpy as np
import mesostat.utils.iterators.sweep as sweep
class TestUtilIterSweep(unittest.TestCase):
pass
# TODO: Implement me
unittest.main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#######################################################
# Script that runs all regression tests.
#
#
# MWetter@lbl.gov 2011-02-23
#######################################################
#
from collections import defaultdict
from contextlib import ... |
#! /usr/bin/env python3
# coding: utf-8
from __future__ import annotations
import logging
from logging import StreamHandler
import os
log = logging.getLogger()
formatter = logging.Formatter("%(filename)s %(levelname)s - %(message)s")
handler = StreamHandler()
handler.setFormatter(formatter)
log.addHandler(handler)
l... |
#!/usr/bin/env python3
from argparse import ArgumentParser, Namespace
from datetime import date, datetime
from lxml import etree
from geopy.distance import vincenty
def main(arguments: Namespace):
aggregated_total_distance = sum(
track_distance(gpx_file)
for gpx_file in arguments.gpx_files)
... |
from django.contrib import admin
from .models import Tutorial, Complemento
admin.site.register(Tutorial)
admin.site.register(Complemento) |
# Generated by Django 2.1.3 on 2019-06-23 15:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pdfmerge', '0013_auto_20190623_1536'),
]
operations = [
migrations.AlterField(
model_name='pdfformfield',
name='fiel... |
# (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
try:
# Agent5 compatibility layer
from checks.libs.win.pdhbasecheck import PDHBaseCheck
from checks.libs.win.winpdh import WinPDHCounter
except ImportError:
from .winpdh_base import PDHBaseCheck
... |
from __future__ import print_function
from __future__ import absolute_import
import cv2
from .tesisfunctions import Plotim,overlay,padVH
import numpy as np
from RRtoolbox.lib.plotter import Imtester
# http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_imgproc/py_morphological_ops/py_morphological... |
"""Bank module message types."""
from __future__ import annotations
import copy
from typing import List
from secret_sdk.core import AccAddress, Coins
from secret_sdk.core.msg import Msg
from secret_sdk.util.json import JSONSerializable, dict_to_data
__all__ = ["MsgSend", "MsgMultiSend", "MultiSendIO"]
import attr
... |
from datetime import datetime
import numpy as np
from pixiu.api.defines import (OrderCommand)
from pixiu.api.utils import (parse_datetime_string)
class Order(object):
def __init__(self, params={'volume': 0}):
self.order_dict = params.copy()
open_time = self.order_dict.get("open_time", None)
... |
import numpy as np
def eval_q2m(scores, q2m_gts):
'''
Image -> Text / Text -> Image
Args:
scores: (n_query, n_memory) matrix of similarity scores
q2m_gts: list, each item is the positive memory ids of the query id
Returns:
scores: (recall@1, 5, 10, median rank, mean rank)
gt_ranks: the best ran... |
import traceback
import uuid
import socket
import logging
import os
import base64
import zlib
import gzip
import time
import datetime
from http import cookies
from http.server import BaseHTTPRequestHandler
from http.server import HTTPServer
from threading import Thread
import WebRequest
def capture_expected_headers... |
import json
from concurrent.futures import ThreadPoolExecutor
import psutil
from notebook.base.handlers import IPythonHandler
from tornado import web
from tornado.concurrent import run_on_executor
try:
# Traitlets >= 4.3.3
from traitlets import Callable
except ImportError:
from .utils import Callable
cl... |
NOT_CONTINUATION = -1
CONTINUATION_START = 0
CONTINUATION = 1
CONTINUATION_END = 2
CONTINUATION_EXPLICIT = 3
#A function that returns the correct set of language regex expressions for functions
#and function like objects.
class languageSwitcher(object):
def __init__(self, ext):
self.lang = ""
sel... |
import logging
from typing import Any
from typing import List
from typing import Optional
from matchms.utils import filter_none
from matchms.utils import get_common_keys
from ..typing import SpectrumType
logger = logging.getLogger("matchms")
_retention_time_keys = ["retention_time", "retentiontime", "rt... |
#!/usr/bin/env python3
# Copyright 2020 Google LLC
#
# 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 ... |
#
# cortexm.py
#
#
# Copyright (c) 2013-2017 Western Digital Corporation or its affiliates.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
... |
# Advent of Code - Day 5 - Part One
from collections import defaultdict
def result(data):
points = defaultdict(int)
for line in data:
a, b = line.split(' -> ')
x1, y1 = a.split(',')
x2, y2 = b.split(',')
x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
min_x, max_... |
# -*- coding: utf-8 -*-
"""Split Definition dataclass"""
from dataclasses import dataclass
from typing import Optional, List
from .rule import Rule
from .treatment import Treatment
from .environment import Environment
from .default_rule import DefaultRule
from .traffic_type import TrafficType
@dataclass
class Split... |
#!/usr/bin/env python
# Copyright (c) 2006-2010 Tampere University of Technology
#
# 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 rig... |
import serial
import struct
s = serial.Serial('/dev/cu.usbserial-A600e0ti', baudrate=19200)
def receive_msg():
print 'Receiving messages'
message = []
c = s.read()
while c != '\n':
message.append(c)
message = ''.join(message)
print 'Msg:', message
|
from django.conf.urls import url
from app05plus.views import index, register, mylogin
from app05plus.views import mylogout
urlpatterns = [
url(r"^newindex01$",index),
url(r"^register01$",register,name="register"),
url(r"^mylogin01$",mylogin,name="mylogin"),
url(r"^logout$",mylogout),
] |
import astropy.units as u
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
from einsteinpy.metric import Schwarzschild
class ScatterGeodesicPlotter:
"""
Class for plotting static matplotlib plots.
"""
def __init__(
self, mass, time=0 * u.s, at... |
import os, sys
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import scipy.signal
from classy import Class
from helper import cache_grendel, cropsave, grendel_dir
"""
For just one of the boxes, plot the absolute CONCEPT
and GADGET spectra over time, including a = a_begin.
"""
textwidth = 504... |
import sys
import errno
from contextlib import contextmanager
from lemoncheesecake.cli.command import Command
from lemoncheesecake.cli.utils import auto_detect_reporting_backends, add_report_path_cli_arg, get_report_path
from lemoncheesecake.reporting import load_report
from lemoncheesecake.reporting.backends.console ... |
import torch
from torch.utils.data import Dataset
class GenericDataSet(Dataset):
def __init__(self,
x_inputs: torch.Tensor,
y_targets: torch.Tensor):
if x_inputs.size()[0] != y_targets.size()[0]:
raise Exception("row count of input does not match targets")
... |
from abc import ABC, abstractmethod
from typing import Iterable, Mapping, Optional
from bankroll.model import AccountBalance, Activity, Position
from .configuration import Settings
# Offers data about one or more brokerage accounts, initialized with data
# (e.g., exported files) or a mechanism to get the data (e.g.... |
"""Integration platform for recorder."""
from __future__ import annotations
from homeassistant.core import HomeAssistant, callback
from . import ATTR_AVAILABLE_MODES, ATTR_MAX_HUMIDITY, ATTR_MIN_HUMIDITY
@callback
def exclude_attributes(hass: HomeAssistant) -> set[str]:
"""Exclude static attributes from being r... |
from django.shortcuts import render
from .models import Image, Video
from .serializers import ImageSerializer, VideoSerializer
from accounts.permissions import isAdminOrReadOnly
from rest_framework.response import Response
from rest_framework import status
from rest_framework.viewsets import ModelViewSet
# Create you... |
# Copyright (c) 2014, Oracle and/or its affiliates. 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
#
# ... |
"""This module provides a mock callable class."""
from __future__ import annotations
import queue
import unittest.mock
from typing import Any, Dict, NamedTuple, Optional, Tuple
from .consumer import ConsumerAsserter, MockConsumerGroup
class MockCallableGroup:
"""This class implements a group of callables."""
... |
# Is Prime
# determine whether the number is prime or not
class isPrime:
def isPrime(self, n):
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
ip = isPrime()
print(ip.isPrime(5)) |
#!/bin/env python
import platform, socket, random, time
_appname_="slowloris"
_version_="0.1"
_description_="fastly take down the web"
_author_="blackc8"
ncol ="\033[0m"
bold ="\033[1m"
dim ="\033[2m"
uline ="\033[4m"
reverse="\033[7m"
red ="\033[31m"
green ="\033[32m"
yellow ="\033[33m"
blue ="\033[34m"... |
import sys, os
import allel
import random
import numpy as np
from diploshic.msTools import *
from diploshic.fvTools import *
import time
(
trainingDataFileName,
totalPhysLen,
numSubWins,
maskFileName,
vcfForMaskFileName,
popForMask,
sampleToPopFileName,
unmaskedGenoFracCutoff,
chrAr... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: second/protos/train.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.... |
'''
Created on Nov 9, 2011
@author: ppa
'''
from analyzer.lib.errors import Errors, UfException
class DAMFactory(object):
''' DAM factory '''
@staticmethod
def createDAM(dam_name, config):
''' create DAM '''
if 'yahoo' == dam_name:
from analyzerdam.yahooDAM imp... |
from pydantic import BaseModel
class ProfileStats(BaseModel):
visits: int = 0
views: int = 0
counters: dict = {}
|
import pyautogui
import time
import cv2
import numpy as np
import imutils
def ImageDetection(temp_img,threshold,img_type):
image = pyautogui.screenshot()
img_bgr = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
img_gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)
# 0 is for grayscale
template = cv2.imread(tem... |
"""
Finds the dictionary for the measurement specification based on the name of the measurement.
"""
def find_measurement_spec(monitoring_system_specs, measurement_type):
"""
Scans the list of specs and returns dictionary of specifications for the named measurement type
Parameters
----------
... |
# HeadPhoneJacks Cause Vaccines
# Softdev2 pd8
# K#06: Yummy Mango Py
#2019-02-28
import pymongo
SERVER_ADDR=""
connection =pymongo.MongoClient(SERVER_ADDR)
db = connection.test
collection = db.restaurants
def boro_find(borough):
'''
finds restaurants by borough and returns them in a list.
'''
restua... |
'''
Function:
AI玩俄罗斯方块
Author:
Charles
公众号:
Charles的皮卡丘
'''
import copy
import math
from modules.utils import *
'''AI玩俄罗斯方块'''
class TetrisAI():
def __init__(self, inner_board):
self.inner_board = inner_board
'''获得下一步的行动'''
def getNextAction(self):
if self.inner_board.current_tetris == tetrisShape().shape_e... |
import requests
import urllib.request
import time
from bs4 import BeautifulSoup
import json
import csv
filecsv = open('SouqDataapple.csv', 'w',encoding='utf8')
# Set the URL you want to webscrape from
url = 'https://saudi.souq.com/sa-ar/apple/new/a-c/s/?section=2&page='
file = open('SouqDataapple.json','w',encoding='ut... |
#!/usr/bin/python
#
# Scraper for libraries hosted at jcenter and custom maven repos
# Retrieves jar|aar files along with some meta data
# @author erik derr [derr@cs.uni-saarland.de]
#
import sys
import json
import urllib2
import datetime
import os
import errno
import zipfile
import traceback
import xml.etree.ElementT... |
#!/usr/bin/env python
#
# Copyright (c) 2018 Intel Labs.
#
# authors: Bernd Gassmann (bernd.gassmann@intel.com)
#
"""
Actor registry class for carla-id mapping
"""
class ActorIdRegistry(object):
"""
Registry class to map carla-ids (potentially 64 bit)
to increasing numbers (usually not exceeding 32 bit)... |
##
# This software was developed and / or modified by Raytheon Company,
# pursuant to Contract DG133W-05-CQ-1067 with the US Government.
#
# U.S. EXPORT CONTROLLED TECHNICAL DATA
# This software product contains export-restricted data whose
# export/transfer/disclosure is restricted by U.S. law. Dissemination
# to ... |
from typing import Optional, Union
from torch_sparse import SparseTensor
from torch_geometric.data import Data, HeteroData
from torch_geometric.transforms import BaseTransform
from torch_geometric.utils import sort_edge_index
class ToSparseTensor(BaseTransform):
r"""Converts the :obj:`edge_index` attributes of ... |
from __future__ import print_function
import re
import time
from ...version import __version__
HEADER_FMT = '''\
/**
* The MIT License (MIT)
*
* Copyright (c) 2018 Erik Moqvist
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* fi... |
from traffic.imports.builtins import SequenceType, sub
def concat(strings: SequenceType[str], separator: str) -> str:
return "".join(s if i == 0 else separator + s for i, s in enumerate(strings))
def to_func_name(name: str):
return sub(r"\W", "_", name).lower()
|
try:
import urllib.parse as urlparse
except ImportError:
import urlparse
from aws_xray_sdk.core.models import http
from aws_xray_sdk.ext.flask.middleware import XRayMiddleware as OrigMiddleware
from flask import request
__all__ = 'XRayMiddleware',
class XRayMiddleware(OrigMiddleware):
def _before_reques... |
# Exercício Python 069: Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa cadastrada,
# o programa deverá perguntar se o usuário quer ou não continuar. No final, mostre:
# A) quantas pessoas tem mais de 18 anos.
# B) quantos homens foram cadastrados.
# C) quantas mulheres tem menos de 20 anos.... |
#!/usr/bin/env python3
# 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.
from __future__ import annotations
import typing # noqa F401
import torch
from torch import Tensor
def _flip_sub_u... |
from numpy import *
class Nematic:
def __init__(self, xx=0, xy=0):
self.xx=xx
self.xy=xy
def angle(self):
return 0.5*arctan2(self.xy, self.xx)
def norm(self):
return sqrt(self.xx**2 + self.xy**2)
def __str__(self):
return "Nematic(%g, %g)"%(self.xx, self.xy) |
# this file serves as both a test suite and an illustration of how tracing
# responds to various AST node types
import re
from tracelib import macros, kite_trace, get_all_traced_ast_reprs
with kite_trace:
for i in range(5):
print i
print len([1, 2, 3, 1 + 1])
x = {1: 2}
# AugAssign
a = 0... |
import numpy as np
import mmap
import os
import glob
import re
class Uio:
"""A simple uio class"""
@staticmethod
def find_device_file(device_name):
device_file = None
r = re.compile("/sys/class/uio/(.*)/name")
for uio_device_name_file in glob.glob("/sys/class/uio/uio*/name"):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.