text stringlengths 2 999k |
|---|
# 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 ... |
from django_comment_migrate.backends.base import BaseCommentMigration
from django_comment_migrate.utils import get_field_comment
class CommentMigration(BaseCommentMigration):
sql_alter_column = "ALTER TABLE %(table)s %(changes)s"
sql_alter_column_comment_null = "MODIFY COLUMN %(column)s %(type)s NULL" \
... |
import collections
from typing import List
from test_framework import generic_test
PairedTasks = collections.namedtuple('PairedTasks', ('task_1', 'task_2'))
def optimum_task_assignment(task_durations: List[int]) -> List[PairedTasks]:
# TODO - you fill in here.
return []
if __name__ == '__main__':
exit... |
"""An observation wrapper that augments observations by pixel values."""
import numpy as np
from gym import spaces
from gym.spaces import Box
from gym import ObservationWrapper
import pdb
class PixelObservationWrapper(ObservationWrapper):
"""Augment observations by pixel values."""
def __init__(self, env):... |
from setuptools import setup
with open("README.rst", "r", encoding="utf-8") as fh:
long_description = fh.read()
setup(name='PySPARQL',
version='0.0.6',
description='Query a SPARQL endpoint and manage the result with Spark',
author='Emanuele Falzone',
author_email='emanuele.falzone@polimi.i... |
import re
from IzVerifier.izspecs.containers.izcontainer import IzContainer
from IzVerifier.izspecs.containers.constants import *
from os import walk
__author__ = 'fcanas'
class IzClasses(IzContainer):
"""
Container for parsing and storing custom classes used in izpack installers.
"""
properties = ... |
import FWCore.ParameterSet.Config as cms
negativeCombinedSecondaryVertexV2BJetTags = cms.EDProducer("JetTagProducer",
jetTagComputer = cms.string('negativeCombinedSecondaryVertexV2Computer'),
tagInfos = cms.VInputTag(cms.InputTag("impactParameterTagInfos"),
cms.InputTag("secondaryVertexNega... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import locale
import os
import re
import subprocess
import sys
from mathics.core.parser import MathicsFileLineFeeder, MathicsLineFeeder
from mathics.core.definitions import Definitions, Symbol
from mathics.core.expression import strip_context
from mathic... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# 歌曲投票
"""
Topic: 找出7号歌曲包揽5项大奖的投票组合
Desc :
云宏歌词比赛投票,总共166人参与投票
每人从1-13编号的歌曲中选5首不同的歌,依次放入1-5号大奖箱中,
最后分别将每个奖箱中得票数最多的那个号码提取出来。
请找出一个组合使得7号歌曲包揽5项大奖的投票组合
"""
__author__ = 'Xiong Neng'
def lucky_seven(rows=166, cols=5, choices=13, lucky=7, start=1):
... |
wins = np.array([0 for i in range(0, nb_cards+1)])
def compute_card_probability(card_value):
deck = [i for i in range(0, nb_cards+1)]
deck.remove(card_value)
# monte carlo loop: run many hands, the law of big
# numbers will do the rest
for _ in range(nb_iterations):
# play a hand, look for ... |
import ctypes
import os
import random, urllib.request, json
global drive, folder, image
drive = "C:\\"
folder = "images"
image = "test.jpg"
f = open("url.txt")
urls = []
# "https://www.reddit.com/r/MinimalWallpaper/.json"
subreddit = "http://pastebin.com/raw/DLNYEhNw"
def setImage(image):
image_path = os.path.jo... |
"""New enum value gasloline carType
Revision ID: f38c424891c2
Revises: 91dac376210b
Create Date: 2021-12-08 12:31:41.706156
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'f38c424891c2'
down_revision = '91dac376210b'
branch_labels = None
depends_on = None
de... |
# coding: utf-8
"""
OrderCloud
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 1.0
Contact: ordercloud@four51.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Ve... |
# Copyright 2017 Martin Olejar
#
# 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 writing... |
"""proyecto URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-base... |
from django.db.models.query import QuerySet
from rest_framework.filters import BaseFilterBackend
from rest_framework.request import Request
from rest_framework.views import APIView
class IsPublishedFilter(BaseFilterBackend):
def filter_queryset(
self,
request: Request,
queryset... |
import numpy as np
import pandas as pd
from time import sleep
from airbnb_pricer.utils.async_run import async_run
mile_per_degree__latitude = 111.32 * 0.621371
mile_per_degree__longitude = 84.35 * 0.621371
def get_dist_to_clusters(location_data, cluster_data):
location_data = location_data.copy()
cluster_dat... |
import data.fonts.character
class MetaFile:
def __init__(self, file, text_mesh_creator):
self.PAD_TOP = 0
self.PAD_LEFT = 1
self.PAD_BOTTOM = 2
self.PAD_RIGHT = 3
self.DESIRED_PADDING = 3
self.SPLITTER = " "
self.NUMBER_SEPARATOR = ","
... |
""" This example shows how to finite difference a single component."""
from __future__ import print_function
from openmdao.components.param_comp import ParamComp
from openmdao.core.component import Component
from openmdao.core.group import Group
from openmdao.core.problem import Problem
class SimpleComp(Component):... |
import app
import command
import config
import models
import operations
import exceptions
__version__ = app.__version__
|
#!/usr/bin/python
#
# Standard SoaT Sauce
#
# This file is ordered from most user-servicable to least.
# Don't be sad if you don't know how to change the stuff
# at the bottom. You probably shouldn't.
import sys
sys.path.append("../../")
try:
from TorCtl.PathSupport import *
except ImportError:
from os import... |
import re
with open('input.txt') as file:
CMDS = []
for line in file:
cmd, v = line.strip().split(' ')
CMDS.append((cmd, int(v)))
def go(cmds):
visited = []
acc = 0
index = 0
while True:
if index in visited:
return acc
visited.append(index)
... |
# Copyright 2017 NeuStar, 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 a... |
#!/usr/bin/env python
# coding=utf-8
import unittest
from ct.cert_analysis import tld_list
from ct.test import test_config
TLD_FILE = "test_tld_list"
class TLDListTest(unittest.TestCase):
def default_list(self):
return tld_list.TLDList(tld_dir=test_config.get_tld_directory(),
... |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# ThreadPool class
# ----------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# -------------------------------------------------------------... |
import cv2
from PIL import Image
import numpy as np
def stitch_sites(g, well_paths, multiplier):
panel_size = int(2048 - (2048 / 10))
height = int(g.y_sites * panel_size)
width = int(g.x_sites * panel_size)
new_im = Image.new('I', (height, width))
for site_path in well_paths:
site_image... |
import cv2
import os
import tensorflow as tf
import preprocessor
def main(author):
print('OpenCV version {} '.format(cv2.__version__))
current_dir = os.path.dirname(__file__)
training_folder = os.path.join(current_dir, 'data/training/', author)
test_folder = os.path.join(current_dir, 'data/test/', a... |
# qlearningAgents.py
# ------------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.be... |
from __future__ import unicode_literals
from utils import CanadianScraper, CanadianPerson as Person
import re
COUNCIL_PAGE = 'http://www.halifax.ca/councillors/index.php'
MAYOR_PAGE = 'http://www.halifax.ca/mayor/'
MAYOR_CONTACT_URL = 'http://www.halifax.ca/mayor/contact.php'
class HalifaxPersonScraper(CanadianScra... |
import errno
import logging
import os
import stat
from concurrent.futures import ThreadPoolExecutor
from functools import partial
from shortuuid import uuid
from dvc.config import Config
from dvc.exceptions import DownloadError
from dvc.exceptions import DvcException
from dvc.exceptions import UploadError
from dvc.pa... |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from swagger_server.models.base_model_ import Model
from swagger_server import util
class Person(Model):
"""NOTE: This class is auto generated by the swagger code... |
#!/usr/bin/env python3
"""Downloads latest player skin renders, and generates HTML for player cards."""
import argparse
import json
import pathlib
import sys
import urllib.request
import jinja2
REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent
RENDERS_DIR = REPO_ROOT / "images" / "players"
def parse_args()... |
from django.shortcuts import render_to_response
from django.template import RequestContext
def home(request, template='index.html'):
return render_to_response(
template,
{ },
context_instance=RequestContext(request))
|
class Foo:
pass
Foo.var = 1
def __main__():
print("in __main__")
try:
del Foo.var
except RuntimeError:
print("RuntimeError1")
print(Foo.var)
|
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse
from django.template.loader import render_to_string
from django.views.generic import TemplateView, RedirectView, CreateView
from django.contrib.auth import authenticate, login
from django.core.mail import EmailMessage
from dj... |
class LoginError(Exception):
"""Impossivel logar"""
pass
class NotXenforoPage(Exception):
"""Elementos de uma pagina xenforo nao encontrados"""
pass
class CookiesNotFound(Exception):
"""Cookies do navegador nao encontrados"""
pass
class DatabaseNotBeRead(Exception):
"""Database nao exi... |
# Copyright 2018 The TensorFlow Probability 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
import unittest
import random
from stanford_algoritms_part1.build_blocks import partioners
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.seq = range(10)
def test_shuffle(self):
# make sure the shuffled sequence does not lose any elements
random.shuffle(self.se... |
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout ,Activation
from keras.optimizers import RMSprop
from keras.regularizers import l2
import matplotlib.pyplot as plt
class Cvml:
def __init__(self):
self.plots_dir = "resulting_plots2"
... |
# Copyright 2021 Alibaba Group Holding Limited. All Rights Reserved.
import numpy as np
import torch
from .registry import TRANSFORMS
def to_tensor(data):
if isinstance(data, torch.Tensor):
return data
elif isinstance(data, np.ndarray):
return torch.from_numpy(data)
elif isinstance(data,... |
from mp_api.routes.elasticity.query_operators import (
BulkModulusQuery,
ShearModulusQuery,
PoissonQuery,
ChemsysQuery,
)
from monty.tempfile import ScratchDir
from monty.serialization import loadfn, dumpfn
def test_bulk_modulus_query():
op = BulkModulusQuery()
q = op.query(
k_voigt_... |
from .blackjack import *
__all__ = ["Blackjack"] |
# coding: utf-8
import sys
from automato import Automato
def init():
estados,inicial,aceita,transicoes,palavra,segundoArquivo = entrada()
automato = Automato(estados,inicial,aceita,transicoes)
if not "-" in palavra:
automato.execultar(palavra)
else:
if palavra == "-uniao":
... |
from django import forms
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from izi.apps.promotions.conf import PROMOTION_CLASSES
from izi.core.loading import get_class, get_classes
from izi.forms.fields import ExtendedURLField
HandPickedProductList, RawHTML, SingleProduct, PageP... |
{
'name': 'OpenERP Web Diagram',
'category': 'Hidden',
'description': """
Openerp Web Diagram view.
=========================
""",
'version': '2.0',
'depends': ['web'],
'data' : [
'views/web_diagram.xml',
],
'qweb': [
'static/src/xml/*.xml',
],
'auto_install': Tr... |
"""The Logitech Squeezebox integration."""
import logging
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from .const import DISCOVERY_TASK, DOMAIN, PLAYER_DISCOVERY_UNSUB
_LOGGER = logging.getLogger(__name__)
PLATFORMS = [P... |
import csv
from datetime import (
datetime,
time,
date,
)
from enum import (
auto,
Enum,
)
from functools import total_ordering
from io import StringIO
from itertools import groupby
from math import ceil
from typing import (
Any,
Callable,
Dict,
Iterable,
Optional,
Type,
... |
#!/usr/bin/python3
import sys
deliveries = 5;
dictionary = {}
lines=[]
for line in sys.stdin:
lines.append(line)
for line in lines:
mapf = map(str,line.split(","))
row=list(mapf)
if((row[0]!="ball")==False):
if (row[4],row[6]) not in dictionary:
dictionary[(row[4],row[6])]=1
elif(dictionary[(row[4],ro... |
'''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GL import _types as _cs
# End users want this...
from OpenGL.raw.GL._types import *
from OpenGL.raw.GL import _errors
from OpenGL.constant import Constant as _C
import ctypes
_... |
#!/usr/bin/env python3
import unittest
from nose.tools import eq_
import pandas as pd
import os
import decisiveml as dml
TEST_DIR = os.path.dirname(os.path.realpath(__file__))
class TestTradingHolidays(unittest.TestCase):
def setUp(self):
self.short_holiday = pd.read_csv(
os.path.join(
... |
#!/usr/bin/env python
#
# __COPYRIGHT__
#
# 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 rights to use, copy, modify, merge, publish,
... |
#!/usr/bin/python
#
# Copyright (c) 2016, Nest Labs, Inc.
# All rights reserved.
#
# 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, thi... |
from env_checker_error import EnvCheckerError
class ProcessRunningError(Exception):
def __init__(self, process_name):
self.process_name = process_name
def resolve(self):
raise EnvCheckerError(
"`%s` cannot be running while Ice is being run" %
self.process_name)
|
from conans.errors import ConanException
import yaml
from conans.model.values import Values
def bad_value_msg(name, value, value_range):
tip = ""
if "settings" in name:
tip = '\nRead "http://docs.conan.io/en/latest/faq/troubleshooting.html' \
'#error-invalid-setting"'
return ("Inval... |
# GENERATED BY KOMAND SDK - DO NOT EDIT
from setuptools import setup, find_packages
setup(name='tshark-rapid7-plugin',
version='1.0.1',
description='A tool for dumping and analyzing network traffic',
author='rapid7',
author_email='',
url='',
packages=find_packages(),
install_... |
from .lib import TestBase
class TestTutorial(TestBase):
def test_example(self):
# Memory Managers
##################
import smmap
# This instance should be globally available in your application
# It is configured to be well suitable for 32-bit or 64 bit applications.
... |
import typing as t
from django.conf import settings
from django.core import mail
from app import emails
from app.utils import reverse
from applications.models import Application
def create_invite_email(application, request):
c = {
'name': application.user.get_full_name,
'reimb': getattr(applicat... |
# coding: utf-8
"""
DocuSign Rooms API - v2
An API for an integrator to access the features of DocuSign Rooms # noqa: E501
OpenAPI spec version: v2
Contact: devcenter@docusign.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import... |
import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *
#Import Revit Nodes
clr.AddReference("RevitNodes")
import Revit
#Import Revit elements
from Revit.Elements import *
#Import Document Manager
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence ... |
# 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.
"""
Wrapper around various loggers and progress bars (e.g., tqdm).
"""
from collections import OrderedDict
from contextlib import contextmana... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2020-01-01 17:06
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('moderation', '0004_auto_20200101_1738'),
]
operations = [
migrations.RemoveField(
... |
"""
Copyright (c) 2018 Alex Forencich
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 rights
to use, copy, modify, merge, publish, distribute... |
import re
from io import BytesIO
from itertools import chain
from pathlib import Path
import shortuuid
from PIL import Image
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.db import models
from django.db.models import Q, OuterRef
from django.db.models.signals import pre_save
from django.di... |
import asyncio
import os
import requests
from gql import AIOHTTPTransport, Client, gql
from gql.transport.exceptions import TransportQueryError
from database import getDB, getPlayerData
from sportsdata import getTimeframe
# from flask import session
class SleeperGraphQLClient:
def __init__(self):
# TOD... |
# base16-qutebrowser (https://github.com/theova/base16-qutebrowser)
# Base16 qutebrowser template by theova
# Edge Dark scheme by cjayross (https://github.com/cjayross)
base00 = "#262729"
base01 = "#88909f"
base02 = "#b7bec9"
base03 = "#3e4249"
base04 = "#73b3e7"
base05 = "#b7bec9"
base06 = "#d390e7"
base07 = "#3e4249... |
import bisect
from typing import List
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
return bisect.bisect_left(nums, target)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import Counter
from datetime import datetime
import os
import re
import sys
import filesize
sys.path.insert(1, '../')
from model.config import *
from scripts.helpers import rm_blanks, str_to_bool
from scripts.process import has_metadata_initial_final, ... |
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
from dataclasses import dataclass
from typing import ClassVar, Tuple
from pants.engine.fs import (
EMPTY_DIRECTORY_DIGEST,
Digest,
FileContent,
FilesContent,
... |
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import os
import time
try:
from unittest import mock
except ImportError: # python < 3.3
import mock # type: ignore
from azure.core.credentials import AccessT... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from typing import List, Set, Mapping, Tuple, Sequence
import pytest
from fastapi import FastAPI
from pydantic import BaseModel, ValidationError
from starlette.testclient import TestClient
from fastapi_contrib.db.models import MongoDBTimeStampedModel
from fastapi_contrib... |
class TopologicalSorting:
def __init__(self, graph, vertices):
self.graph = graph
self.V = vertices
def addEdge(self, u, v):
self.graph[u].append(v)
def topologicalSortUtil(self, v, visited, stack):
visited[v] = True
for i in self.graph[v]:
if visited[i]... |
from pathlib import Path
import numpy as np
import torch
from torch.utils.data import Dataset
from torchvision.transforms import InterpolationMode, Resize
from .utils import downsample, bicubic_with_mask, random_crop, random_rotate, random_horizontal_flip
DIML_BASE_SIZE = (756, 1344)
class DIMLDataset(Dataset):
... |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import os
import unittest
from pathlib import Path
from typing import Callable, Optional, Union
import numpy as np
import torch
from PIL import Image
def get_tests_dir() -> Path:
"""
Returns Path for the directory containing this file.
... |
"""
Django settings for ecommerce project.
Generated by 'django-admin startproject' using Django 4.0.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from pathlib... |
from . import git
import os
from urllib.parse import quote_plus
from .utils import msg
_CACHE_FOLDER = os.path.expanduser('~/.glit/cache/git/')
_already_pulled = set()
class GitStoredFile(object):
def __init__(self, repository, filename):
self._repository = repository
self._relative_filename =... |
import os
"""
deletes labels without images to prevent errors
Parameters
----------
images_folder: str
images path
labels_folder: str
labels path
"""
def delete_images_with_no_labels(images_folder, labels_folder):
images = [image.split(".")[0] for image in os.listdir(images_folder)]
labels ... |
# -*- coding: utf-8 -*-
# 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 writing, software
# ... |
## Quantile regression
#
# This example page shows how to use ``statsmodels``' ``QuantReg`` class to replicate parts of the analysis published in
#
# * Koenker, Roger and Kevin F. Hallock. "Quantile Regressioin". Journal of Economic Perspectives, Volume 15, Number 4, Fall 2001, Pages 143–156
#
# We are interested... |
def prime_or_composite(number):
for i in range(2, int(number//2)):
if number % i == 0 and number > 1:
print("Composite")
break
else:
print ("Prime")
# Optional: If you want to test the efficency of your algorithm add this number to the... |
import torch
import torch.nn as nn
from torch.autograd import Variable
import collections
class strLabelConverterForAttention(object):
"""Convert between str and label.
NOTE:
Insert `EOS` to the alphabet for attention.
Args:
alphabet (str): set of the possible characters.
ignore_c... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-07-21 06:55
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pig', '0002_auto_20200714_1204'),
]
operations = [
migrations.AlterField(
... |
# 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 writing, software
# distributed under t... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.18
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import si... |
#importing dependencies:
import cv2
#importing trained and stored data from xml files::
car_tracker = cv2.CascadeClassifier('cars.xml') #trained data of cars
pedes_tracker = cv2.CascadeClassifier('body.xml') #trained data for human long figures
trained_faced_data = cv2.CascadeClassifier('df.xml') #train... |
from base import testlabel
from cqparts.utils.test import CatalogueTest
from cqparts.catalogue import JSONCatalogue
def add_catalogue(filename):
catalogue = JSONCatalogue(filename)
cls = testlabel('catalogue')(CatalogueTest.create_from(catalogue))
globals()[cls.__name__] = cls
# BoltDepot catalogues
ad... |
# GUM: GAMBIT Universal Model Machine
# ***********************************
# \file
#
# Routines for SPheno output from SARAH
#
# *************************************
#
# \author Sanjay Bloor
# (sanjay.bloor12@imperial.ac.uk)
# \date 2019 July
#
# \author Tomas Gonzalo
# (tomas.gonzalo@monash... |
from __future__ import division
import numpy as np
from scipy.ndimage import interpolation
def resize_n(old, new_shape):
new_f, new_t = new_shape
old_f, old_t = old.shape
scale_f = new_f/old_f
scale_t = new_t/old_t
#print(scale_f, 'scale_f-------------------')
#print(scale_t, 'scale_t---------... |
with open("maps.txt") as f:
lines = [l.rstrip("\n") for l in f]
maps = {}
for l in lines:
s = l.split()
maps[s[1]] = s[7]
nd = {}
prev = None
for k,v in maps.items():
if v != prev:
nd[k] = v
prev = v
print(nd)
with open("o.csv", "w") a... |
"""first_project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class... |
from flask import Blueprint, render_template, redirect, url_for, flash
from ..forms import ForumPostForm
from ..models.forum_posts import ForumPost
forum_bp = Blueprint('forum', __name__, url_prefix='/forum')
@forum_bp.route('/')
def forum_index():
"""Generates the index page of the forum."""
# TODO: Fix thi... |
from waldur_mastermind.marketplace import processors
from .utils import DockerExecutorMixin
"""
It is expected that offering plugin_options field is dict with following structure:
language: python
environ:
USERNAME: admin
PASSWORD: secret
create:
import os
print("Creating resource ", os.environ.ge... |
#Code written by Vinayak Nair for Using Python to Access Web Data coursera course
import re #invoking regular expression module
#Opening the file(s) in which we'll need to find the numbers
sample_file = open('regex_sum_42.txt') #This is to open the sample file
actual_file = open('regex_sum_1095114.txt') #This is to o... |
import os
import shutil
import sys
import tempfile
import unittest
from io import StringIO
from django.conf import settings
from django.contrib.staticfiles import finders, storage
from django.contrib.staticfiles.management.commands.collectstatic import (
Command as CollectstaticCommand,
)
from django.core.cache.ba... |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Matio(AutotoolsPackage):
"""matio is an C library for reading and writing Matlab MAT files... |
# -*- coding: utf-8 -*-
# @Author : ydf
# @Time : 2019/8/20 0008 12:12
import os
if os.name == 'nt':
"""
为了保险起见,这样做一下,设置一下path,否则anaconda安装的python可能出现 ImportError: DLL load failed while importing cimpl: 找不到指定的模块。
多设置没事,少设置了才麻烦。
"""
from pathlib import Path
import sys
# print(sys.execu... |
import pytest
import lib.cache
import lib.retriever
import lib.settings
import feedparser
import os
class TestRetriever:
@pytest.fixture(scope="class")
def chdir(self, request):
print(f"dirname: {request.fspath.dirname}")
print(f"invocation dir: {request.config.invocation_dir}")
os.chd... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from . import __version__ as app_version
app_name = "peruintercorp"
app_title = "Peruintercorp"
app_publisher = "Peru Intercorp"
app_description = "Peru Intercorp"
app_icon = "octicon octicon-globe"
app_color = "#220B5E"
app_email = "admin@peruintercorp.c... |
from typing import Tuple
from hypothesis import given
from robust.linear import (Segment,
SegmentsRelationship,
segments_relationship)
from tests.utils import (reflect_segment,
reverse_segment)
from . import strategies
@given(strategies.... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.template import loader
from dental_studio.models import *
# Create your views here.
def welcome... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import time
import calendar
import icalendar
import datetime
import sys
from PIL import Image, ImageFont
import inkyphat
print("""Inky pHAT: ICS Calendar Events List
Lists upcoming events from an ICS Calendar file.
""")
if len(sys.argv) < 2:
print... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.