content stringlengths 5 1.05M |
|---|
# this code is written by @SMSadegh19
from lib2to3.pgen2 import driver
import time
import json
from webdriver_manager.chrome import ChromeDriverManager
###### selenium imports
from selenium import webdriver
from selenium.webdriver import common
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.... |
from enum import Enum
import OperatingSystemClasses
import re
class OperatingSystemFamilies(Enum):
WINDOWS = ("WINDOWS", OperatingSystemClasses.OperatingSystemClasses.DESKTOP)
WINDOWSSERVER = ("WINDOWS SERVER", OperatingSystemClasses.OperatingSystemClasses.SERVER)
WINDOWSMOBILE = ("WINDOWS Mobile", OperatingSystem... |
# Generated by Django 2.1.3 on 2019-01-12 21:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('polygon', '0015_auto_20190112_1547'),
]
operations = [
migrations.AddField(
model_name='codeforcespackage',
name='si... |
#!/usr/bin/python3
import os
distribution_directory = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.chdir(distribution_directory + "/src/test/isabelle")
os.system("/opt/Isabelle2020/bin/isabelle jedit -l HOL Scratch.thy &")
|
# Released under the MIT License. See LICENSE for details.
#
"""
Provide top level UI related functionality.
"""
|
height = input("Enter Height of Rectangle : ")
width = input("Enter width of Rectangle : ")
area = int(height) * int(width)
print("Area is ",area)
|
from sgwsapi import *
import json
import os
import getpass
# SSO username and password with admin rights
api_url = ''
api_user = os.getenv('USER')
api_passwd= ""
api_passwd = getpass.getpass(api_user+" Enter your password:")
#Get auth token:
resp = get_auth_token(api_user,api_passwd)
if resp.status_code != 200... |
# --------------------------------------------------------
# Flow-Guided Feature Aggregation
# Copyright (c) 2017 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Xizhou Zhu
# --------------------------------------------------------
"""
given a imagenet vid imdb, compute mAP
"""
impor... |
phrase='British Library'
alpha=re.compile('[^a-zA-Z]')
def normalize_keep_case(word):
return re.sub(alpha,'',word)
def mapper(book):
def checker(first, second):
first_word=normalize_keep_case(first[1])
second_word=normalize_keep_case(second[1])
page=first[0]
if [first_wo... |
from .AST import AST
from .Operator import get_all_operator
from .Tokenizer import Tokenizer
def run(exp, env):
"""
执行断言
:param exp: 断言条件
:param env: api 返回
:return:
"""
ao = get_all_operator(env)
tokens = Tokenizer(ao).tokenizer(exp)
return AST(ao, tokens).eval(env)
def get_as... |
import logging
import random
import time
from datetime import datetime
from functools import partial
import numpy as np
import pandas as pd
from lagoon.dags import DAG
from lagoon.executors.local_executor import LocalExecutor
from simpleai.search.local import hill_climbing_weighted_stochastic, beam
from sklearn.covari... |
# from quiver_engine import server
# from keras.models import load_model
# model = load_model('model_log.h5')
# server.launch(
# model, # a Keras Model
# ['garbage'], # list of output classes from the model to present (if not specified 1000 ImageNet classes will be used)
# # where to store temporary fil... |
import logging
from dataclasses import dataclass
from datetime import datetime
@dataclass
class Transaction:
date: datetime.date = None
amount: int = 0
description: str = ""
account: str = ""
category: str = "unknown"
reference: str = ""
_income_expense: str = "E"
@property
def in... |
from typing import List, Dict
from CommonServerPython import *
def convert_mail_to_json(item, folder):
return {
'subject': item.get('subject', ''),
'textBody': item.get('textBody', ''),
'body': item.get('body', ''),
'folder': folder
}
def main():
folders_paths_str = demi... |
import sys
from decimal import Decimal, getcontext
input = lambda: sys.stdin.readline().rstrip()
def pi():
getcontext().prec += 2
three = Decimal(3)
lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
while s != lasts:
lasts = s
n, na = n + na, na + 8
d, da = d + da, da + 32
... |
import codecademylib3
# Import pandas with alias
import pandas as pd
# Import dataset as a Pandas dataframe
movies = pd.read_csv("movie_show.csv", index_col=0)
# View the first five rows of the dataframe
print(movies.head())
# Print the unique values in the country column
print(movies.country.unique())
# Set the c... |
# 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... |
import math
import torch
import random
import argparse
import datetime
import numpy as np
import torch.nn as nn
from copy import deepcopy
from datetime import timedelta
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
import matplotlib.patheffects as pe
from collections import OrderedDict
... |
# 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 "License"); you may not use ... |
class Solution:
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
return list(set(range(1, len(nums) + 1)) - set(nums)) |
from django.urls import path
from .views import (
AsteroidListView,
AsteroidDetailView,
#AsteroidTrackView
)
urlpatterns = (
path('', AsteroidListView.as_view(), name='asteroid-list'),
path('<slug:slug>', AsteroidDetailView.as_view(), name='asteroid-detail'),
#path('track/<slug:slug>', Asteroid... |
from copy import deepcopy
import re
import pytest
from marshmallow import ValidationError
from clean_code.compile_reading_list import (
ReadingListSchema,
format_review,
load_review_yml,
main,
)
valid_dict = {
"title": "title",
"author": "author",
"availability": ["list", "of", "string... |
import torch
import torch.nn as nn
from maskrcnn_benchmark.config import cfg
from predictor import COCODemo
class FasterRcnnVisionModel (nn.Module):
def __init__ (self):
super(FasterRcnnVisionModel, self).__init__()
config_file = '/home/jl25/research/maskrcnn-benchmark/configs/caffe2/e2e_faster_... |
import argparse
import os
import re
import binascii
import base64
import json
import copy
import requests
from Crypto.Cipher import AES
import requests
import osascript
import hashlib
import time
import math
import requests
from cachier import cachier
import datetime
from typing import *
import pinyin
from hanziconv i... |
import csv
import os
from django.core import management
from django.core.management.base import CommandError
from django.test import TestCase
from bmat_app.models import MusicalWork
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
def create_test_metadata():
"""
Creates a CSV with metadata to test and... |
from py2neo import Graph, Node, Relationship, NodeMatcher
# 疾病
dis_list = ["糖尿病", "高血压"]
# 临床表现
cli_list = ["肾脏损害", "心脏损害", "脑部损害", "大小动脉损害"]
# 药物
drug_list = ["利尿药", "钙拮抗药", "胰岛素", "胰高血糖素"]
# 诊断方法
zd_method_list = ["血脂", "血糖", "胆固醇", "超声心动图", "心电图", "肝功能", "肾功能"]
# 副作用
sdef_list = ["恶心", "呕吐", "头晕", "眼花", "血钾降低", "尿酸... |
# begin patch to set db_url for sqlite (only)
# since sqlite db is copied to created project, we can set db_url here
from pathlib import Path
import logging
running_at = Path(__file__)
project_abs_dir = running_at.parent.absolute()
project_abs_dir = project_abs_dir.parent.absolute()
project_abs_dir = project_abs_dir... |
"""
Provides an inteface to read seismic data written in binary files with a basic
structure of: File header, trace header0, trace0, trace header 1 , trace 1 etc..
All the boilerm plate functions are provided in the SegReader interface.
An open source implementation for a SEGY version 1 is provided, with a ctypes funct... |
from . import models
from .hooks import pre_init_hook
|
from blog.models import Post
from blog.serializers import PostProtoSerializer
from django_grpc_framework import mixins
from django_grpc_framework import generics
"""
class PostService(mixins.ListModelMixin,
mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixin... |
import cv2
from .naming_conventions import *
def photo_array(camera, amount, delay=3, name_convention=time_name_convention, path=None):
"""
Takes a series of images with a delay between shots and saves them, after every image,
press 'y' to save it and 'n' to pass
:param camera: the camera to take im... |
from xca.ml.tf_data_proc import dir2TFR
from xca.ml.tf_models import CNN_training as training
from xca.ml.tf_parameters import load_hyperparameters
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--params',
help='hyperparameters ... |
# Generated by Django 2.2 on 2019-04-23 23:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('draftcardposter', '0012_auto_20190412_1910'),
]
operations = [
migrations.AddField(
model_name='settings',
name='imgur... |
def test(nothing):
return nothing
def dupa(kasf):
pass
afasd
asfasdfasdf
fa
a
dfas
df
asdf
asfasdf
kolejny zamina
asfasf
asdf`
|
import re
issue_object_rg = None
def weather_change_readme(rest_repo, link_dict, labels):
# to see whether need change readme
contents = str(rest_repo.get_contents(link_dict['readme_path']).decoded_content)
pattern_tag = re.compile(r'tag: package-[\w+-.]+')
package_tag = pattern_tag.search(contents).... |
import Blender
from Blender.Window import EditMode, GetCursorPos, GetViewQuat
import bpy
import BPyMessages
def add_mesh_simple(name, verts, edges, faces):
'''
Adds a mesh from verts, edges and faces
name - new object/mesh name
verts - list of 3d vectors
edges - list of int pairs
faces - list of int triplets/... |
class TYPELIBATTR(object):
""" Use System.Runtime.InteropServices.ComTypes.TYPELIBATTR instead. """
guid = None
lcid = None
syskind = None
wLibFlags = None
wMajorVerNum = None
wMinorVerNum = None
|
import datetime
results = 0
num = 10
def callback(a):
global results
results = results + 1
print(results)
if __name__ == '__main__':
try:
file2 = open("colorsWritten.txt","r")
with open("colors.txt", "w") as file1:
for line in file.readlines:
if line not ... |
import os
from tkinter import *
import tkinter.messagebox
from tkinter import filedialog
from pygame import mixer
root = Tk()
mixer.init()
menubar = Menu(root, bg="white")
root.config(menu=menubar)
def browse_file():
global filename
filename = filedialog.askopenfilename()
subMenu = Menu(menubar, bg="white", ... |
from minpiler.std import M, memory_of, address_of, Processors, sync
x: sync.SharedFloat = 0
y: sync.SharedFloat = 0
@Processors.add
def f():
memory_of(y)[address_of(y)] = 10
M.print(memory_of(y)[address_of(y)])
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Utility functions to process data.
"""
import os
import pickle
import logging
from collections import Counter
import numpy as np
from util import read_conll, one_hot, window_iterator, ConfusionMatrix, load_word_vector_mapping
from defs import LBLS, NONE, LMAP, NUM, UN... |
from django.apps import AppConfig
class TinychainConfig(AppConfig):
name = 'tinychain'
|
# Generated by Django 2.0 on 2018-02-23 13:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('base', '0003_auto_20180223_0814'),
]
operations = [
migrations.AlterField(
model_name='socialmedia',
name='icon',
... |
import torch
from models.quantization import quan_Conv2d, quan_Linear
def int2bin(input, num_bits):
'''
convert the signed integer value into unsigned integer (2's complement equivalently).
'''
output = input.clone()
output[input.lt(0)] = 2**num_bits + output[input.lt(0)]
return output
def b... |
# Copyright 2017 David R. Bild
#
# 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 agree... |
from django.db import models
# Create your models here.
class Course(models.Model):
name = models.CharField(max_length=30)
cnt = models.IntegerField()
def __str__(self):
return f"{self.name} / {self.cnt}"
class AmyShop(models.Model):
# id = models.IntegerField(primary_key=True)
year = mod... |
import sys
#setup python path for RALI
sys.path.append('/opt/rocm/mivisionx/rali/python/')
from rali import *
from rali_image_iterator import *
from rali_common import *
#batch size = 64
raliList_mode1_64 = ['original', 'warpAffine', 'contrast', 'rain',
'brightness', 'colorTemp', 'exposure', 'vignette',
'blur'... |
# Add your FTP site credentials here
SITE = '' # eg ftp.foo.net
USER_NAME = ''
PASSWORD = ''
ROOT_DIR = '/public_html'
|
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.db.models import ImageField
import os
from django.db import models
from django.contrib.auth.models import User
from recipes.models import Recipe
from gallery.models import Gallery
from notifications.models import Notice
def comp_cat_up... |
# Copyright 2016 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 ag... |
#-----------------------------------------------------------------------------
# Copyright (c) 2013-2017, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt, distributed with this s... |
from flask import Flask, request, session
from flask_session import Session
import config
from utils import Logger, Returns, Telegram
import Routes
import shutil, os, requests
logger = Logger.logger
Logger.logging_start()
shutil.rmtree(os.getcwd()+"/flask_session")
app = Flask(__name__)
app.config["SESSION_PERMANENT... |
#!/usr/bin/env python
# --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""Train a plain ZF network for face attribute... |
class Plugin(object):
def __init__(self, context):
if context is None:
raise ValueError('Context must be set')
self._context = context
self._name = 'Name of your plugin'
self._console_msg = 'Console message to display when your plugin is used'
self._activated = ... |
"""In this module we define the ApplicationView
The ApplicationView contains the different subviews like main, sidebar, topbar, navigation etc
as well as other functionality like spinner, application_css, application_js, theme_css, theme_js,
..."""
import panel as pn
import param
class ApplicationView(pn.Te... |
# Django settings for widgets_sample_project project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
ALLOWED_HOSTS = []
TIME_ZONE = None
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = True
USE_L10N = True
USE_TZ =... |
#
# Copyright 2018 Joachim Lusiardi
#
# 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 wri... |
from .graph import Graph
__all__ = ["Graph"]
|
# coding: utf-8
"""
pyperclip モジュールについてのサンプルです。
"""
import pyperclip as clip
from trypython.common.commoncls import SampleBase
from trypython.common.commonfunc import pr
class Sample(SampleBase):
def exec(self):
# ---------------------------------------------------------------
# [link]
# ... |
#!/usr/bin/env python
"""The nearest neighbour algorithm was one of the first algorithms used
to solve the travelling salesman problem approximately. In that problem,
the salesman starts at a random city and repeatedly visits the nearest
city until all have been visited. The algorithm quickly yields a short
tour, but ... |
from events.game import Event, UserEvent
import hlib.api
# pylint: disable-msg=F0401
import hruntime # @UnresolvedImport
#
# Base classes
#
class ThiefEvent(Event):
def __init__(self, thief = None, victim = None, **kwargs):
Event.__init__(self, **kwargs)
self.thief = thief
self.victim = victim
d... |
import unittest
import urlparse
import url_decoder
class UrlDecoderTestCase(unittest.TestCase):
"""Base class for testing UrlDecoder instances."""
def _parse_url(self, url):
return urlparse.urlparse(url)
def _can_decode_url(self, decoder, url):
parsed_url = self._parse_url(url)
return decoder.can... |
# -*- coding: utf-8 -*-
from PIL import Image, ImageDraw, ImageFont
import os, time, sys
from math import ceil
class PlaceHoldMachine:
'''Author: Abraham Tugalov (aka Priler)'''
text = ""
prefix = ""
font_name = 'fonts/Ubuntu_Condensed/UbuntuCondensed-Regular.ttf'
font_size = '7%'
font = None
active_image = No... |
import panflute as pf
def add_one(e, doc):
if type(e)==pf.Table:
for row in e.items:
for cell in row:
if len(cell) == 1 and len(cell[0].items)==1:
text = cell[0].items[0].text
if text.isdigit():
cell[0].items[0].tex... |
"""Filter functions."""
import regex
from . import base
from .. import utils
class EmptyStringFilter(base.LoggedCallable):
"""Filter out the empty string."""
def apply(
self,
s: str
) -> bool:
"""Return ``True`` if ``s`` is the empty string.
Parameters
-... |
import sys
import pandas as pd
import scipy
import numpy as np
import random
co_df = pd.read_csv("conflicts-end.csv")
row_sums = co_df.sum(axis=1)
print("All sums:", co_df.sum(axis=1).sum(axis=0))
def insert_conflict(name, day, length):
co_df.loc[day:day + length, name] = 1
s = sys.argv[1]
intensity = int(sy... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from . import _unittest as unittest
import re
from datatest._predicate import (
_check_type,
_check_callable,
_check_wildcard,
_check_truthy,
_check_falsy,
_check_regex,
_check_set,
_get_matcher_parts,
get_matcher,
MatcherBase,
M... |
import uuid
import datetime
import builtins
import string
import copy
from jinja2 import Environment
from jinja2 import FileSystemLoader
def base_context():
defaults = [_ for _ in dir(builtins)
if _[0] in string.ascii_lowercase and
_ not in ['copyright', 'credits']
]
attrs = [getattr(bu... |
from bs4 import BeautifulSoup
from ..occurrences.occurrences import Occurrences
from ..occurrences.occurrence_interface import OccurrenceInterface
class Recommendation31:
"""
Recomendação 31: Nome da recomendação
- Dividir as áreas de informação
"""
def __init__(self, sourcecode):
self.r... |
# -*- coding: utf-8 -*-
import os
import pickle
from functools import lru_cache
import pytesseract
import numpy as np
from PIL import Image
import torch
from torchvision.transforms import ToTensor
PAD_TOKEN_BOX = [0, 0, 0, 0]
GRID_SIZE = 1000
def normalize_box(box, width, height, size=1000):
"""
Takes a boun... |
"""
.. module:: __init__.py
__init__.py
*************
:Description: __init__.py
:Authors: bejar
:Version:
:Created on: 22/01/2015 10:46
"""
__author__ = 'bejar'
from .SimpleConsensusClustering import SimpleConsensusClustering
from .MeanPartition import MeanPartitionClustering
__all__ = ['SimpleCon... |
import array
import math
import random
import secrets
import struct
import time
from Crypto.Random import get_random_bytes
from ..set1.challenge1_2 import xor_bytes
from ..set1.challenge8 import get_blocks
from .challenge5 import MersenneTwister
def mersenne_stream_cipher(seed, bytestring):
rng = MersenneTwist... |
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.utils.http import urlencode
def authorize(request):
pass
def refresh(request):
pass
def logout(request):
togo = request.GET.get('next', reverse('accounts:login'))
response = HttpResp... |
import cv2
import time
fitToEllipse = False
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
time.sleep(2)
fgbg = cv2.createBackgroundSubtractorMOG2()
j = 0
while(1):
ret, frame = cap.read()
#Convert each frame to gray scale and subtract the background
try:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2G... |
from django.db import models
class Post(models.Model):
id = models.BigAutoField(primary_key=True)
user = models.ForeignKey("authentication.User", on_delete=models.CASCADE)
text = models.TextField(max_length=280)
def __str__(self):
return self.id
|
#!/usr/bin/env python
import os.path
from getpass import getpass, getuser
import logging
from pathlib import Path
from typing import List, Union
from ltpylib import enums, inputs, procs
MAC_SOUND_DIRS = [
"/System/Library/Sounds",
"~/Library/Sounds",
]
class MacSoundsSystem(enums.EnumAutoName):
BASSO = "Bass... |
import random
from time import sleep
from datetime import datetime
class ClockControl(object):
shutdown = False
class Clock(object):
def __init__(self):
self.last = (0, 0, 0)
now = datetime.now()
self.now = (now.hour, now.minute, now.second)
self.confirmed = False
def _s... |
import random
def baseN(num,b,numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
return ((num == 0) and numerals[0]) or (baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b])
def jhash(arr):
h = reduce(
lambda sum, n:
((sum << 1 | sum >> 31) & 0xffffffff) ^ n,
arr,
8388617
)
return base... |
from decouple import config
from pysympla import Sympla
sympla = Sympla(token=config("TOKEN"))
print(sympla.events())
|
import requests
from project.server.main.utils.utils import os_get
def pushover(title, msg, priority, html):
url = "https://api.pushover.net/1/messages.json"
payload = {'token': os_get('PUSHOVER_TOKEN'),
'user': os_get('PUSHOVER_USER'),
'message': str(msg),
'titl... |
import json
import asyncio
import aiohttp
import mlrun
from storey.flow import _ConcurrentJobExecution
class BatchHttpRequests(_ConcurrentJobExecution):
"""class for calling remote endpoints in parallel
"""
def __init__(
self,
url: str = None,
subpath: str = None,
method: s... |
# Copyright (c) 2017, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
import unittest
from mixbox.vendor.six import u
from cybox.objects.win_hook_object import WinHook
from cybox.test.objects import ObjectTestCase
from cybox.test.objects.win_handle_test import TestWinHandle
class ... |
import logging
import time
import requests
import sys
import os
import errno
import json
from urllib.parse import urlparse
from raintale import package_directory
from raintale.storytellers.storytellers import storytellers, storytellers_without_templates
module_logger = logging.getLogger('raintale.utils')
def test_m... |
import pytest
import typing
from recap import URI
from chesscog.occupancy_classifier.download_model import ensure_model as ensure_occupancy_classifier
from chesscog.piece_classifier.download_model import ensure_model as ensure_piece_classifier
@pytest.mark.parametrize("ensure_model,name", [
(ensure_occupancy_cla... |
from SortStrategy import SortStrategy
class ShellSortStrategy(SortStrategy):
"""docstring for ShellSortStrategy"""
def sort(self, my_list = []):
return "Lista ordenada con Shell Sort!"
|
#!python3
"""
This program exhaustively searches for a negative example to the two-thirds conjecture.
See: https://arxiv.org/abs/1709.02564 Conjecture 3.12 for details.
"""
import fairness_criteria
from agents import BinaryAgent
from families import Family
import copy, itertools, utils
from partitions import powerse... |
# coding: utf-8
import datetime
import base64
import binascii
import sys
import types
import warnings
from collections.abc import Hashable, MutableSequence, MutableMapping
# fmt: off
from ruamel.yaml.error import (MarkedYAMLError, MarkedYAMLFutureWarning,
MantissaNoDotYAML1_1Warning)
fr... |
from collections import defaultdict
from csv import DictReader
import scipy.stats as st
import numpy as np
def load_params(file):
"""Custom param loading fn"""
table = defaultdict(list)
with open(file, 'r') as f:
reader = DictReader(f)
for row in reader:
for col, dat in row.ite... |
#
# PySNMP MIB module JUNIPER-CHASSIS-CLUSTER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/JUNIPER-CHASSIS-CLUSTER-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:47:57 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... |
import os
import argparse
import random
from statistics import mean
from collections import defaultdict
from operator import itemgetter
from itertools import groupby
import jsonlines
import re
import xml.etree.ElementTree as ET
random.seed(42)
#
# config
#
parser = argparse.ArgumentParser()
parser.ad... |
import arcpy
inTable = "C:/TmpWrkDirGIS/GEOG485/Lesson2/CityBoundaries.shp"
inField = "NAME"
rows = arcpy.SearchCursor(inTable)
#This loop goes through each row in the table
# and gets a requested field value
for row in rows:
currentCity = row.getValue(inField)
print (currentCity) |
from funcx.serialize.concretes import *
from funcx.serialize.base import METHODS_MAP_DATA, METHODS_MAP_CODE
import logging
logger = logging.getLogger(__name__)
class FuncXSerializer(object):
"""
Information that we want to be able to ship around:
* Function run information ->
* Function id <---> Con... |
import tensorflow as tf
print tf.__version__
import sys
sys.path.append("..")
# import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime
from graphnnSiamese import graphnn
from utils import *
import os
import argparse
import json
parser = argparse.ArgumentParser()
parser.add_arg... |
from drf_yasg.generators import OpenAPISchemaGenerator
from drf_yasg.inspectors import SwaggerAutoSchema
from drf_yasg.views import get_schema_view
class StandardizedSchemaGenerator(OpenAPISchemaGenerator):
pass
class StandardizedAutoSchema(SwaggerAutoSchema):
pass
def get_standardized_schema_view(api_url... |
import frappe
from typing import Dict, List
from digistore.api.billing import create_checkout_session
@frappe.whitelist(allow_guest=True)
def all_products() -> List:
return frappe.db.get_all(
"Digital Product",
filters={"available": True},
fields=["name", "image", "title", "description", "category", "short_de... |
# Generated by Django 2.2.5 on 2019-10-06 20:45
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Customer',
fields=[
... |
import urllib
import urllib.request
from colorama import *
try:
ns = input("Qual é o Nome do Site: ")
site = urllib.request.urlopen(input("Qual é a URL: "))
except:
print(f'O site não está acessivel no momento.')
else:
print(f'O site {ns} está acessivel no momento.')
|
import numpy as np
import time
import datetime
import os
import xarray as xr
from dataset import SpatialData, Bucket
from utils.parallel import parcall
'''
--------------------------------------------------------------------
Create data bucket.
First, make sure that the datasets are up to date, the files to
create t... |
# def is_divisible_by_2_or_5(n):
# # return True
# """
# >>> is_divisible_by_2_or_5(8)
# True
# """
# if __name__ == "__main__":
# import doctest
# doctest.testmod()
# # Unit testing with doctest from python standard library.
"""
This is the "example" module.
The example module supplies one function, factorial... |
import argparse
from collections import namedtuple
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler, S... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.