content stringlengths 5 1.05M |
|---|
"""Test problem submission against hard-coded replies with unittest.mock."""
from __future__ import division, absolute_import, print_function, unicode_literals
import time
import json
import unittest
import itertools
import threading
from datetime import datetime, timedelta
from dateutil.tz import UTC
from dateutil.p... |
from rest_framework import permissions
|
import numpy as np
from robosuite.environments.manipulation.causal import Causal
from robosuite.utils.observables import Observable, sensor
class CausalGoal(Causal):
def __init__(self, xy_range=[0.3, 0.4], z_range=0.2, **kwargs):
"""
:param table_coverage: x y workspace ranges as a coverage facto... |
import json
from collections import OrderedDict
from typing import Tuple, Optional, Union, Callable
from cached_property import cached_property
from django import template
from django.core.handlers.wsgi import WSGIRequest
from django.views import View
from django.http import HttpResponse, HttpResponseNotAllowed, JsonR... |
self.Item.insert(index, value)
self.numberOfItems = len(self.Item) |
# TC001 - User registration (with random data)
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options
import time
import random
import string
from selenium.webdriver.common.by import By
options = Options()
options.headless = True
d... |
import unittest
import time
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui impo... |
import contextlib
import json
from typing import Dict, List, Type
from urllib.parse import urlparse
import mongoengine
from bson.dbref import DBRef
from bson.objectid import ObjectId
from flask import has_request_context, request, url_for
try: # closeio/mongoengine
from mongoengine.base.proxy import DocumentProx... |
from keras.engine import Layer
from keras.engine import InputSpec
from keras import initializers
from keras import regularizers
from keras import constraints
from keras import backend as K
from keras.utils.generic_utils import get_custom_objects
class NALU(Layer):
def __init__(self, units,
use_g... |
""" File name: health_agents.py
Author: Jeff Yuanbo Han (u6617017)
Date: 8 March 2018
Description: This file contains agents which fight disease. It is used
in Exercise 4 of Assignment 0.
"""
import random
class HealthAgent:
""" A simple disease fighting agent. """
... |
def main():
if False:
print(1)
def while_unreachable():
while False:
print(1)
print(2)
print(3)
def while_unreachable2():
print("Hello")
while False:
print(1)
print(2)
print(3)
else:
print(1)
def if_unreachable_condition():
pr... |
import requests
import zipfile
import json
import io, os
import sys
import re
import socket
import pandas as pd
import reverse_geocoder as rg
import numpy as np
from glob import glob
import argparse
import boto3
import shutil
def get_args_from_command_line():
"""Parse the command line arguments."""
parser = a... |
import numpy as np
from integrals import S, T, V, two_electron
def nuc_repulsion(molecule):
"""
Calculate nuclear repulsion between atoms
"""
retval = 0.
for i in range(molecule.N):
for j in range(i+1, molecule.N):
if i == j: continue
atom_i, atom_j = molecule.atoms... |
__author__ = "Marc Wang"
__copyright__ = "Copyright (c) 2021 MSAM Lab - University of Waterloo"
__license__ = "BSD-3-Clause"
__maintainer__ = "Marc Wang"
__email__ = "marc.wang@uwaterloo.ca"
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QDialogButtonBox, QDialog, QAbstractButton, QInputDialog, QMessageBox, ... |
#!/usr/bin/python3
import unittest
import time
import json
from deployutils.testnet import *
import deployutils.eehelper as ee
techKey ='5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3'
class EETestCase(unittest.TestCase):
def setUp(self):
self.eeHelper = ee.EEHelper(self)
def tearDown(self):... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from hwtBuildsystem.vivado.executor import VivadoExecutor
from hwtBuildsystem.vivado.part import XilinxPart
def importSampleBdProject(v: VivadoExecutor, part: str, tmpDir: str):
p = v.project(tmpDir, "SampleBdProject")
if p._exists():
p._remove()
p.... |
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.core.config import settings
if os.environ.get("DEPLOY_ENV") == "TEST":
engine = create_engine("sqlite:///test.db", pool_pre_ping=True)
else:
engine = create_engine(settings.SQLALCHEMY_DATABASE_URI, pool_pre_ping=T... |
import subprocess
from mock import patch
from django.test import TestCase
from django.core.management.base import CommandError
from django.conf import settings
from django.utils import six
from dbbackup.management.commands.dbrestore import Command as DbrestoreCommand
from dbbackup.dbcommands import DBCommands
from dbba... |
from django.contrib import admin
from django.urls import path
from django.contrib.auth import views as auth_views
from django.urls import reverse_lazy
from . import views
app_name = "players"
urlpatterns = [
path('', views.home, name = 'home'),
path('users/', views.users_list, name = 'users'),
path('test/',... |
# from Utility import Utility as utility
import pandas as pd
class Imbalanced:
def __init__(self, data):
self.data = data
def DivideAndConquer(self, target, minority_class, majority_class, n=5000):
total = len(self.data)
minority = self.data[self.data[target] == minority_class]
... |
#################################################################
# test.py
# Author : %AUTHOR%
# Version : 1.0
# Date : %DATE%
# Description: Test Script
#################################################################
|
from .feature_params import FeatureParams
from .split_params import SplittingParams
from .train_params import TrainingParams
from .train_pipeline_params import (
read_training_pipeline_params,
TrainingPipelineParamsSchema,
TrainingPipelineParams,
)
from .model_params import (
read_model_logistic_regress... |
#
# Pybalone
#
# A Python implementation of the Abalone* board game
# Abalone is a registered trademark of Abalone S.A.
#
# github.com/marnovo
#
x = 9 # invalid spaces
b = 0 # empty board spaces
A = 1 # player 1/A/top
B = 2 # player 2/B/bottom
# Axial coordinates used as explained in:
# http://www.redblobgames.co... |
"""title
https://adventofcode.com/2021/day/19
"""
import numpy as np
import pandas as pd
import itertools
import re
SMALL_INPUT = open('small_input.txt').read()
ORIENTATIONS = """
x, y, z
x, z,-y
x,-y,-z
x,-z, y
y,-x, z
y, z, x
y, x,-z
y,-z,-x
z, y,-x
z,-x,-y
z,-y, x
z, x, y
-x, y,-z
-x, z, y
-x,-y, z
-... |
from setuptools import setup
setup(
name='genshinstats',
version='1.3.8.2',
author='thesadru',
packages=['genshinstats'],
description="A python library that can get the stats of your or others' Genshin Impact account using Mihoyo's API.",
keywords='wrapper-api genshin'.split(),
python_requi... |
from time import sleep
import utils.show as show
import utils.file as file
def list():
info = 'People Registered'
fileExists = file.exists()
if fileExists is True:
show.header(info)
file.read()
sleep(2)
def register(name: str, age: int):
file.write(f'{name},{age}')
sleep(2)
|
from .base_device import BaseDevice
import uuid
class Mower(BaseDevice):
def __init__(self, smart_system, device_map):
"""Constructor for the mower device."""
BaseDevice.__init__(self, smart_system, device_map["COMMON"][0]["id"])
self.type = "MOWER"
self.activity = "N/A"
s... |
import tkinter as tk
class app(tk.Frame):
def __init__(self, i, master=None):
super().__init__(master)
self.master = master
self.i = i
self.i_2 = i
self.i_3 = i
self.pack()
self.createWidgets()
def createWidgets(self):
self.btnFrame = tk.Frame(sel... |
import os
os.environ['FOR_DISABLE_CONSOLE_CTRL_HANDLER'] = 'T' # This is ot prevent to be called Fortran Ctrl+C crash in Windows.
import torch
import numpy as np
import logging, yaml, sys, argparse, math
from tqdm import tqdm
from collections import defaultdict
import matplotlib
matplotlib.use('agg')
import matplot... |
from datetime import time
from django.contrib.auth import get_user_model
from dlcf_anonymous_request.users.models import AnonymousMessage
from dlcf_anonymous_request.users.forms import RequestCreateForm
from django.shortcuts import render
# from django.urls import reverse
from django.forms.models import BaseModelForm... |
import argparse
import logging
import json
from .transport import CTSocketClient
from .event_trackers import testing, mpu6050
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--client-id', required=True)
subparsers = parser.add_subparsers()
mock_parser = subparsers.add_parser('tes... |
# Request Handle for Systems Management Ultra Thin Layer
#
# Copyright 2017 IBM Corp.
#
# 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/LICEN... |
import os
from sphinxcontrib.pylit.DataStore import DataStore
def test_default_rootdir():
ds = DataStore()
assert os.path.isdir('.pylit')
ds.delete()
def test__rootdir_specified():
ds = DataStore('test_repo')
assert os.path.isdir('test_repo')
ds.delete()
def test_delete_rootdir():
ds = ... |
import os, re, sys, logging
import numpy as np
import subprocess as sp
import cPickle as pickle
from pdb import set_trace
sys.path.insert(0, os.path.dirname(os.getcwd()))
from Core.CoreSystem import CoreHash, CoreGotoh
class clsParameter(object):
def __init__(self):
if len(sys.argv) > 1:
... |
from . import api, nav, data, stream
|
from gevent.pywsgi import Input
from gevent.wsgi import WSGIServer
from urlparse import urlparse
from netifaces import ifaddresses, interfaces
from socket import getnameinfo, gaierror, getservbyname, AF_INET, AF_INET6
from time import time
from socket import error as SocketError
from funcy import pluck
from geventhttp... |
#Aplicação simples em Python que faz a leitura de um banco de dados mysql
from flask import Flask
from typing import List, Dict
import json
import mysql.connector
app = Flask(__name__)
def cores() -> List[Dict]:
config = {
'user': 'root',
'password': 'root',
'host': 'db',
'port': '... |
from color_detection.histogram import hsv
import cv2 as cv
import numpy as np
class Threshold(hsv):
def __init__(self):
hsv.__init__(self)
def assign(self, img):
self.img = img
self.img_hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)
self._hsv__assign(self.img_hsv)
def read_mas... |
import QuantumSystem as qs
import unittest
class TestClasicoCuamtico(unittest.TestCase):
def test_transational_amplitude(self):
result = qs.Transitional_amplitude([[((2**0.5/2),0),(0,(2**0.5/2))]],[[(0,(2**0.5/2)),(-(2**0.5/2),0)]])
self.assertEqual(result,(0.0, -1.0))
def test_specific_posi... |
"""
Module with definitions for image transformations such as rotations and dilations
"""
import cv2
import numpy as np
def resize_to_target(img, width, height):
"""
Return resized img to given width and height dimensions
"""
dim = (width, height)
resized = cv2.resize(img, dim)
return resized... |
"""
Linear SVM with MapReduce
Algorithm builds a model with continuous features and predicts binary target label (-1, 1).
Reference
Algorithm is proposed by Glenn Fung, O. L. Mangasarian. Incremental Support Vector Machine Classification. Description of algorithm can be found at ftp://ftp.cs.wisc.edu/pub/dmi/tech-re... |
import numpy as np
import matplotlib.pyplot as plt
class Robot():
def __init__(self, time, x0, y0, tetta0, xf, yf, tettaf):
self.x_history = [x0]
self.y_history = [y0]
self.tetta_history = [tetta0]
self.time_history = [0.0]
self.control_history = [(0.0, 0.0)]
self.s... |
# ==== PHYSICS CONSTANTS ====
# BOLTZMAN
BOLTZMAN_CONSTANT = 5.6704 * (10 ** -8)
# KELVIN
DELTA_KELVIN = 273.15
# ==== SOFTWARE RELATED ====
SETTINGS_FILE_PATH = "settings.json"
SETTINGS_TEMPLATE_FILE_PATH = "settingsTemplate.json"
# ==== BASE SCI CONSTANTS ====
LAT_MARGINS = [-90, 90]
LON_MARGINS = [0, 360]
LON... |
class Tablet :
def __init__(self,tablet_proxy):
self._tablet = tablet_proxy
def set_background(self,color):
self._tablet.setBackgroundColor(color)
def set_image(self,url):
self._tablet.showImage(url)
def load_image(self,url):
return self._table.preLoadImage(url)
|
class Solution:
"""
@param nums: An array of integers
@return: An integer
"""
def maxProduct(self, nums):
n = len(nums)
if n == 0:
return 0
preMin = preMax = nums[0]
minProd = maxProd = nums[0]
largest = nums[0]
for i in range(1, n):
... |
###################################
# Overview
#
# Script to expose endpoints
###################################
import flask
from flask import request, jsonify
from scoring_functions import prediction_function
from joblib import load
clf = load('models/random_forest_model.joblib')
app = flask.Flask(__name__)
# app.... |
import tvm
def gemm(A, B, transposeA=False, transposeB=False):
"""Matrix multiplies matrix
Args:
-----------------------------
A: tvm.te.tensor.Tensor
shape [height, width]
B: tvm.te.tensor.Tensor
shape [width, length]
transposeA: (optional:False) bool
transposeB: (optiona... |
# Copyright 2011-2019, Damian Johnson and The Tor Project
# See LICENSE for licensing information
"""
Supports communication with sockets speaking Tor protocols. This
allows us to send messages as basic strings, and receive responses as
:class:`~stem.response.ControlMessage` instances.
**This module only consists of ... |
# -*- coding: utf-8 -*-
# Copyright 2012 Loris Corazza, Sakis Christakidis
#
# 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
#
# U... |
from fastapi import Request, Response
from fastapi.responses import RedirectResponse
from fps.hooks import register_exception_handler
from fps.logging import get_configured_logger
logger = get_configured_logger("helloworld")
class RedirectException(Exception):
def __init__(self, reason, redirect_to):
se... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# -*- mode: python3 -*-
# taken (with minor modifications) from pycoin
# https://github.com/richardkiss/pycoin/blob/01b1787ed902df23f99a55deb00d8cd076a906fe/pycoin/ecdsa/native/secp256k1.py
import os
import sys
import traceback
import ecdsa
from ctypes import (byref, c_s... |
from __future__ import annotations
from rich.console import RenderableType
from rich.padding import Padding, PaddingDimensions
from rich.style import StyleType
from rich.styled import Styled
from ..widget import Widget
class Static(Widget):
def __init__(
self,
renderable: RenderableType,
... |
import torch.utils.model_zoo as model_zoo
import torch
import numpy as np
from collections import OrderedDict
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet50': 'https://download.... |
import unittest
from scipy.stats import ttest_ind, pearsonr, ks_2samp
from utils import prepare_data
class TestExercise2_04(unittest.TestCase):
def setUp(self):
self.data = prepare_data()
self.data["Disease"] = self.data["Reason for absence"].apply(self.in_icd)
def in_icd(self, val):
... |
import pandas as pd
import numpy as np
import requests
import os
import json
import matplotlib.pyplot as plt
from time import sleep
# Need to load an api-key
api_key = '646928682c4b5d6f5f6c782a6b351b29'
def get_all_groups(location_str, radius=25, write_path=None, api_key=api_key):
'''Gets a list of all groups wi... |
#name: Fab Arm Exchange
#language: python
#tags: model, simulation
#meta.modality: Antibody
#meta.domain: Manufacturing
#input: double meaConcentration = 60 {category:FAE Reaction Parameters; units:mM; caption:2-MEA Concentration} [2-MEA Concentration]
#input: double phOfFaeReaction = 7.5 {category:FAE Reaction Paramet... |
from .tictactoe.tictactoe import env, raw_env
|
import glob
import os
import pandas as pd
from tensorflow.keras.models import load_model
from configs import config_roi
from utils.util import *
# Load model
model = load_model(config_roi.ROI_MODEL_PATH, compile=False)
# Load CSV with image files list
data = pd.read_csv(config_roi.IMAGES_CSV_PATH)
images_list = list(... |
# -*- coding: utf-8 -*-
from operator import add
from functools import partial
from collections import deque
from sys import float_info
from ..misc import call, callwith, raisef, pack, namelambda, timer, getattrrec, setattrrec, Popper, ulp
from ..fun import withself
def test():
# def as a code block (function ov... |
import context; context.set_context()
import os
import sys
import logging
import util
import gphoto
from gphoto.google_library import GoogleLibrary
from gphoto.imageutils import ImageUtils
# -----------------------------------------------------
# Main
# -----------------------------------------------------
def main... |
from openslides_backend.permissions.permissions import Permissions
from tests.system.action.base import BaseActionTestCase
class ProjectorAddToPreview(BaseActionTestCase):
def setUp(self) -> None:
super().setUp()
self.set_models(
{
"meeting/1": {"is_active_in_organizati... |
import sys
import numpy as np
import matplotlib.pyplot as plt
import sys
import os
import time
import argparse
from visual_utils import generate_listcol, generate_cmap
if __name__ == '__main__':
# Check for command line arguments
parser = argparse.ArgumentParser()
parser.add_argument('--basename', type=str... |
import numpy as np
import matplotlib.pyplot as plt
from time import sleep
from grid_map import StochOccupancyGrid2DLazy
from global_planners import AstarPlanner, NavFuncitonPlanner
from local_planners import DynamicWindowPlanner
from source.actors.simulated_human import SimulatedPathFollowingHuman
from source.actors.... |
class Solution:
def isValid(self, s: str) -> bool:
if s.count('(') == s.count(')') and s.count('[') == s.count(']') and s.count('{') == s.count('}'):
dic = {'}':'{',']':'[',')':'('}
a=[]
for x in s:
if x in [']',')','}'] and len(a)!=0 :
... |
from rest_framework import serializers
from django.http import Http404
from rest_framework import status
from rest_framework.response import Response
from ..projects import ProjectSerializer
from iaso.models import Project, FeatureFlag, Form
from hat.audit import models as audit_models
import logging
logger = logging.... |
"""
Let's start with the most simplest problem that can exist in Python.
Todo: Given three integers, return the largest integer.
"""
# solution one
def greatest_1(a, b, c):
return max(a, b, c)
# solution two
def greatest_2(a, b, c):
if a > b and a > c:
return a
elif b > a and b > c:
retu... |
import os,re, glob
import numpy as np
import pandas as pd
import logging
import tarfile
from distutils.version import StrictVersion
from ..config import ISOCHRONES
from ..grid import ModelGrid
class ParsecModelGrid(ModelGrid):
name = 'parsec'
common_columns = ('Zini', 'Age', 'Mini', 'Mass','logL', 'logTe', 'l... |
import os, yaml
from .exception import YamlErrorConfigFileParsing, NoConfigFileFound, YamlErrorConfigFileBadType
config_file_name = '.makaron.yml'
config_file_content = \
'''# {}
# more info at https://makaron.gitlab.io
setup.py: "__version__ = '[version]'"
'''.format(config_file_name)
def generate_config_file()... |
# Simple lineaer regression
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Salary_Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 1].values
# Splitting Data
# Splitting the dataset into the Training set an... |
# Copyright 2004 by Bob Bussell. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""NOEtools: For predicting NOE coordinates from assignment data.
The input and output are model... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 3 16:02:44 2019
@author: gptshubham595
"""
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import cv2
import matplotlib.pyplot as plot
def main():
#Various Colour spaces
#HSV-Hue Saturation Value
#GRAY
#CMY - Can Mar... |
"""
https://www.fifaindex.com/teams/?type=1
https://www.fifaindex.com/teams/fifa07_3/?league=78&type=1
https://www.fifaindex.com/teams/fifa06_2/?league=78&type=1
Attacks per game - average unknown
Number of attacks,
Goals per game
http://www.slate.com/articles/sports/sports_nut/2013/08/the_numbers_game_why_soccer_tea... |
r"""
Features for testing the presence of Singular
"""
from . import Executable
from sage.env import SINGULAR_BIN
class Singular(Executable):
r"""
A :class:`~sage.features.Feature` describing the presence of the Singular executable.
EXAMPLES::
sage: from sage.features.singular import Singular
... |
#!/usr/bin/env python
"""
Manage the LendingClub user session and all raw HTTP calls to the LendingClub site.
This will almost always be accessed through the API calls in
:class:`lendingclub.LendingClub` instead of directly.
"""
"""
The MIT License (MIT)
Copyright (c) 2013 Jeremy Gillick
Permission is hereby grante... |
from joblib import Parallel, delayed
from itertools import zip_longest
from collections import Counter
from github import Github
import os, sys, shutil, multiprocessing, json
class DevOracle:
def __init__(self, save_path : str):
self.save_path = save_path
if 'PAT' in os.environ:
self.... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
####################
import json
import time
import indigo
mqttPlugin = indigo.server.getPlugin("com.flyingdiver.indigoplugin.mqtt")
if mqttPlugin.isEnabled():
props = {
'message_type':"#Test#"
}
while True:
message_data = mqttPlugin.executeA... |
#!/usr/bin/env python
# Author: Costin Constantin <costin.c.constantin@intel.com>
# Copyright (c) 2015 Intel Corporation.
#
# Contributors: Alex Tereschenko <alext.mkrs@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the... |
"""Auto-generated file, do not edit by hand. FO metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_FO = PhoneMetadata(id='FO', country_code=298, international_prefix='00',
general_desc=PhoneNumberDesc(national_number_pattern='[2-9]\\d{5}', possible_number_pattern='\... |
import numpy as np
# using sklearn
from sklearn.neural_network import MLPClassifier
x = [[0., 0.], [1., 1.]]
y = [0, 1]
clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1)
clf.fit(x,y)
print(clf.predict([[2., 2.], [-1., -2.]])) |
from http import client as http_client
import json
from django.conf import settings
from django.contrib.messages import ERROR, INFO
from django.urls import reverse
from django.utils.http import urlencode
from django.utils.translation import gettext
from izi.core.loading import get_class, get_model
from izi.test.facto... |
"""
An interface to html5lib that mimics the lxml.html interface.
"""
import sys
import string
from html5lib import HTMLParser as _HTMLParser
from html5lib.treebuilders.etree_lxml import TreeBuilder
from lxml import etree
from lxml.html import Element, XHTML_NAMESPACE, _contains_block_level_tag
# python3 compatibilit... |
"""
Accuracy tester of Shaman
Usage:
shaman-tester <test_set.csv> [--model-path <model_path>]
python -m shamanld.tester <test_set.csv> [--model-path <model_path>]
:author: Prev(prevdev@gmail.com)
:license: MIT
"""
import sys
import os
import csv
import argparse
from . import shaman
def main():
aparser... |
#!/usr/bin/env python3
import os
import shutil
from . import settings
from aqt import mw
from anki.cards import Card
from anki.notes import Note
from anki.collection import Collection
from aqt.utils import showInfo
def importer(my_files_catalog):
for file in my_files_catalog:
importer_to_anki(file)
empty_trash()
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 24 10:34:28 2020
@author: bdobson
"""
import os
import geopandas as gpd
import pandas as pd
from shapely.geometry import Point
#Addresses
data_root = os.path.join("C:\\","Users","bdobson","Documents","data","population_data")
shape_fn = os.path.join("example_shape.shp")... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
# pylint: disable=no-member
#
# @Author: oesteban
# @Date: 2016-01-05 11:33:39
# @Email: code@oscaresteban.es
# @Last modified by: oesteban
""" Encapsulate... |
from django.conf import settings
from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
class BaseVerification(models.Model):
user = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name="%(app_label)s_%(class)s_related",
rela... |
#coding:utf-8
###################################################################
# File Name: setting.py
# Author: Meng Zhao
# mail: @
# Created Time: Wed 21 Mar 2018 04:50:40 PM CST
#=============================================================
import os
import logging
import logging.handlers
import tensorflow as tf
... |
from cStringIO import StringIO
from PIL import Image
from icrawler.builtin import GoogleImageCrawler
from Craft import CraftClient
import time
import sys
import os
import win32clipboard
import win32com.client
import shutil
PATH_TO_CRAFT_SDK_FILE = "./"
sys.path.insert(0, PATH_TO_CRAFT_SDK_FILE)
pre_recv_data =''
recv... |
from subprocess import check_output
loader_offset = int(check_output('nm -g payload/payload.dylib | grep "T _load"',
shell=True).split()[0], 16)
inp = open('shellcode.in.s').read()
outp = inp.replace('OFFSET_LOAD', hex(loader_offset))
with open('shellcode.s', 'w') as f:
f.write(outp)
|
from cloud.permission import Permission, NeedPermission
# Define the input output format of the function.
# This information is used when creating the *SDK*.
info = {
'input_format': {
'count_system_user': 'bool'
},
'output_format': {
'item': {
'count': 'int'
}
},
... |
import csv
import json
data = []
with open("data/commits.json") as f:
for line in f:
parsed = json.loads(line)
email = parsed["payload"]["commits"][0]["author"]["email"]
current = {}
current["id"] = parsed["id"]
current["repository_name"] = parsed["repo"]["name"]
... |
import json
from django.http import JsonResponse
from django.middleware.csrf import get_token
def get_csrf(request):
response = JsonResponse({'detail': 'CSRF cookie set'})
response['X-CSRFToken'] = get_token(request)
return response
|
#!/usr/bin/env python
# Copyright (c) 2018 Samsung Electronics Co., Ltd. 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... |
#!/usr/bin/env python
#coding = utf-8
import re,urllib,md5
def assign(service, arg):
if service == "phpcms":
return True, arg
def audit(arg):
url = arg
md5_check_value = 'cf00b069e36e756705c49b3a3bf20c40'
payload = urllib.unquote("statics/js/ckeditor/plugins/flashplayer/player/player.swf?skin=... |
import asyncio
import logging
from asyncio import CancelledError
import pytest
import lightbus
import lightbus.path
from lightbus import EventMessage
from lightbus.utilities.async_tools import cancel
pytestmark = pytest.mark.reliability
logger = logging.getLogger(__name__)
@pytest.mark.asyncio
async def test_rand... |
import os
import collections
import pandas
import matplotlib, seaborn, numpy
from matplotlib import pyplot
import sklearn
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.pipeline import Pipeline
from sklearn.linear_model import SGDClassifier, LogisticRegression
from sklearn.tree import Decisi... |
#!/usr/bin/env python
import os
import responses
import unittest
import shutil
from pydub import AudioSegment
from datetime import datetime
from typecaster import utils
import xml.etree.ElementTree as ET
class Object(object):
pass
def catch_requests():
# Catch synthesize requests and insert test .wav file... |
import numpy as np
import tensorflow as tf
def _to_int32(a):
return np.int32(np.ceil(a))
def extract_patches(detector: tf.keras.models.Model,
img: tf.TensorArray,
min_score: float = 0.4,
max_boxes: int = 10):
shape = tf.shape(img)
im_height, im... |
# 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 agree... |
from __future__ import absolute_import
import logging
import redis
import time
from contextlib import contextmanager
from random import random
from .container import Container
class UnableToGetLock(Exception):
pass
class _Redis(object):
def __init__(self, app, options):
self.app = app
se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.