text stringlengths 1 927k |
|---|
"""
Author: Zahra Gharaee.
This code is written for the 3D-Human-Action-Recognition Project, started March 14 2014.
"""
import numpy as np
from numpy import linalg as LA
class SOM:
def __init__(self, learning, outputsize_x, outputsize_y, inputsize, sigma, softmax_exponent, max_epoch):
self.... |
# Cassini CAPS ELS data reader
# Modeled after Gary's MDIS reader
# Kiri Wagstaff, 11/28/18
import os
from datetime import datetime
from collections import defaultdict
import numpy as np
from pds.core.parser import Parser
from scipy.interpolate import interp1d
GEOMFILE = os.path.join(
os.path.dirname(os.path.real... |
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
## Created by: Donny You, RainbowSecret
## Microsoft Research
## yuyua@microsoft.com
## Copyright (c) 2019
##
## This source code is licensed under the MIT-style license found in the
## LICENSE file in the root directory of this source tree
##... |
# -*- coding: utf-8 -*-
# Copyright (c) Polyconseil SAS. All rights reserved.
from __future__ import unicode_literals
import json
import os
import os.path
from dokang import api
from . import compat
def get_harvester(fqn):
module_fqn, function_fqn = fqn.rsplit('.', 1)
# Hack around https://bugs.python.org/... |
# Generated by Django 2.1.2 on 2018-11-13 08:36
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('pywolf', '0044_placcount_dummy_user_flg'),
]
operations = [
migrations.RemoveField(
model_name='villageparticipant',
name='s... |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
from typing import Tuple, Dict, Any, Optional
from droidlet.dialog.dialogue_objects import DialogueObject
from ..interpreter import ReferenceObjectInterpreter, FilterInterpreter, interpret_reference_object
from ..condition_helper import ConditionInterpreter
fro... |
#--
# Copyright (c) 2012, Sebastian Tello, Alejandro Lozanoff
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# th... |
#!/usr/bin/env python3
# Copyright 2015-2021 Arm Limited
#
# 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 ... |
import gym
import numpy as np
from util import plot_running_average
# pylint: disable-msg=redefined-outer-name
def max_action(estimates, state):
values = np.array([estimates[state, i] for i in range(2)])
action = np.argmax(values)
return action
def get_state(observation):
cart_x, cart_x_dot, cart_thet... |
import os
from flask import Flask, escape, request, jsonify
from marshmallow import ValidationError
from flask_pymongo import PyMongo
from src.auth.auth_exception import UserExistsException, UserNotFoundException, AccessDeniedException
from src.auth.controllers.auth import auth_blueprint
import src.settings
from src.... |
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url as django_url
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin
from django.conf.urls.static import static
from django.views.generic.base import TemplateView,RedirectView
fro... |
import time
from typing import Dict, List, Optional, Tuple
import requests
import utility.args
class MadObj:
def __init__(self, api, obj_id: int):
assert obj_id >= 0
self.id = obj_id
self._data = {}
self._api = api # type:Api
def _update_data(self):
raise NotImpleme... |
"""2019 - Day 9 Part 1: Sensor Boost."""
from src.year2019.intcode import Computer
def solve(task: str) -> int:
"""Find BOOST key code."""
computer = Computer()
computer.load_program(task)
computer.stdin.append(1) # test mode
computer.execute()
return computer.stdout.pop() |
import os
import shutil
from cement.core.controller import CementBaseController, expose
from wo.cli.plugins.stack_pref import post_pref, pre_pref, pre_stack
from wo.core.aptget import WOAptGet
from wo.core.download import WODownload
from wo.core.extract import WOExtract
from wo.core.fileutils import WOFileUtils
from ... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: pi.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.protobuf import reflection as _reflection... |
# fake module that resides in my lib folder and
# imports the actual implementation
from pathlib import Path
here = Path(__file__).absolute().parent
name = here.stem
import sys
sys.path.insert(0, str(here))
del sys.modules[name]
module = __import__(name)
del sys.path[0]
del Path, here, name, sys
globals().update(m... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
from nintendo.nex import backend, authentication, ranking, datastore
from nintendo.games import MK8
from nintendo import account
import requests
import logging
logging.basicConfig(level=logging.INFO)
#Device id can be retrieved with a call to MCP_GetDeviceId on the Wii U
#Serial number can be found on the back of the... |
from urllib.parse import urlencode
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.views import SuccessURLAllowedHostsMixin
from django.shortcuts import redirect
from django.urls import reverse, reverse_lazy
from django.utils.http import is_safe_url
from django.utils.translation import get... |
# Copyright 2014 Mirantis.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 ... |
from bs4 import BeautifulSoup
from datetime import datetime
import requests
import time
def get_code(company_code):
url="https://finance.naver.com/item/main.nhn?code=" + company_code
result = requests.get(url)
bs_obj = BeautifulSoup(result.content, "html.parser")
return bs_obj
def get_price(company_co... |
from get_employees import PROVIDER
from get_employees.facade_factory import FacadeFactory
def main():
facade = FacadeFactory.create_facade(PROVIDER)
facade.get_employees()
if __name__ == '__main__':
main() |
MULTIMAP_PUT = 0x0201
MULTIMAP_GET = 0x0202
MULTIMAP_REMOVE = 0x0203
MULTIMAP_KEYSET = 0x0204
MULTIMAP_VALUES = 0x0205
MULTIMAP_ENTRYSET = 0x0206
MULTIMAP_CONTAINSKEY = 0x0207
MULTIMAP_CONTAINSVALUE = 0x0208
MULTIMAP_CONTAINSENTRY = 0x0209
MULTIMAP_SIZE = 0x020a
MULTIMAP_CLEAR = 0x020b
MULTIMAP_VALUECOUNT = 0x020c
MULT... |
# coding=utf-8
# Copyright 2019 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 agreed to ... |
# Copyright 2021 The NetKet Authors - 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 ... |
# Copyright 2016 Ananya Mishra (am747@cornell.edu)
#
# 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 ... |
#!/usr/bin/env python
import sys
from os.path import exists
from setuptools import setup
import versioneer
# NOTE: These are tested in `continuous_integration/test_imports.sh` If
# you modify these, make sure to change the corresponding line there.
extras_require = {
"array": ["numpy >= 1.18"],
"bag": [], ... |
"""Exceptions for ocean_utils """
# Copyright 2018 Ocean Protocol Foundation
# SPDX-License-Identifier: Apache-2.0
class OceanInvalidContractAddress(Exception):
"""Raised when an invalid address is passed to the contract loader."""
class OceanDIDUnknownValueType(Exception):
"""Raised when a requested DI... |
"""ThreatConnect TI Event"""
from ..group import Group
class Event(Group):
"""Unique API calls for Event API Endpoints
Valid status:
+ Escalated
+ False Positive
+ Needs Review
+ No Further Action
Args:
tcex (TcEx): An instantiated instance of TcEx object.
event_date (str... |
import torch.nn as nn
import torch
import math
# Embedding network used in Meta-learning with differentiable closed-form solvers
# (Bertinetto et al., in submission to NIPS 2018).
# They call the ridge rigressor version as "Ridge Regression Differentiable Discriminator (R2D2)."
# Note that they use a peculiar order... |
# 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 u... |
"""django_vali URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Clas... |
import graphene
from apps.movie.mutators import MovieType, CreateMovie, UpdateMovie, DeleteMovie
from .models import Movie
class MovieInput(graphene.InputObjectType):
name = graphene.String(required=True)
class MovieMutations(graphene.ObjectType):
create_movie = CreateMovie.Field()
update_movie = Updat... |
def create_sequence(count):
sequence = [0, 1, 1]
for n in range(3, count):
next_n = sequence[n - 1] + sequence[n - 2]
sequence.append(next_n)
print(' '.join([str(x) for x in sequence]))
def locate_number(number):
x, y = 0, 1
index = 0
while x < number:
x, y = y, x + y
... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
print '参数个数为:', len(sys.argv), '个参数。'
print '参数列表:', str(sys.argv) |
import copy
import itertools
import math
import os
import random
import sys
import tempfile
import time
from collections import namedtuple
from contextlib import contextmanager, suppress
from datetime import timedelta
from functools import reduce
from typing import Union, NamedTuple, Callable, Any
import torch
import ... |
# for http://blender.stackexchange.com/questions/32787/example-of-creating-and-setting-a-cycles-material-node-with-the-python-api
import bpy
# get the material
mat = bpy.data.materials['Material']
# get the nodes
nodes = mat.node_tree.nodes
# clear all nodes to start clean
for node in nodes:
nodes.remove(node)
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 30 17:44:42 2015
@author: junz
"""
import os
import numpy as np
import h5py
import tifffile as tf
#import allensdk_internal.brain_observatory.mask_set as mask_set
import corticalmapping.core.ImageAnalysis as ia
import corticalmapping.core.PlottingTools as pt
import scipy... |
# coding=utf-8
# Copyright 2020 The Google Research 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 applicab... |
"""Caching loader for the 20 newsgroups text classification dataset.
The description of the dataset is available on the official website at:
http://people.csail.mit.edu/jrennie/20Newsgroups/
Quoting the introduction:
The 20 Newsgroups data set is a collection of approximately 20,000
newsgroup documents... |
def most_frequent(s):
dic={}
for i in s:
if i in dic:
dic[i] += 1
else:
dic[i] = 1
z = sorted(dic.items(), key = lambda x: x[1], reverse = True)
for i in z:
print(i[0]+"="+str(i[1]))
most_frequent('mississippi') |
# -*- coding: utf-8 -*-
"""
Spectral Upsampling Coefficient Tables - Jakob and Hanika (2019)
================================================================
Defines the objects implementing support for *Jakob and Hanika (2019)*
*Spectral Upsampling Coefficient Tables* dataset loading:
- :class:`colour_datasets.loa... |
# Copyright 2018, The TensorFlow Federated 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... |
# coding: utf-8
# -----------------------------------------------------------------------------------
# <copyright company="Aspose Pty Ltd" file="JpegConvertOptions.py">
# Copyright (c) 2003-2021 Aspose Pty Ltd
# </copyright>
# <summary>
# Permission is hereby granted, free of charge, to any person obtaining a cop... |
# Copyright 2015 The Meson development team
# 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 ... |
from flask_socketio import emit
from flask_security import current_user
from sqlalchemy import update
from classes.shared import db, socketio
from classes import Channel
from classes import Stream
from classes import settings
from functions import system
from functions import webhookFunc
from functions import templa... |
import time
import socket
import yaml
import datetime
import base64
import difflib
import botocore.exceptions
import requests
import json
from copy import deepcopy
from ..helper import info, warning, error, ActionOnExit, substitute_template_vars
from ..helper.aws import filter_subnets, associate_address, get_tag
from .... |
# Implement int sqrt(int x).
# Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
# Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
# Example 1:
# Input: 4
# Output: 2
# Example 2:
# Input: 8
# Outp... |
# --------------------------------------------------------
# Fast/er R-CNN
# Licensed under The MIT License [see LICENSE for details]
# Written by Bharath Hariharan
# --------------------------------------------------------
import xml.etree.ElementTree as ET
import os
import pickle
import numpy as np
import pdb
def pa... |
from django import forms
from allauth.socialaccount.forms import SignupForm as SocialSignupForm
class SignupForm(SocialSignupForm):
first_name = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30) |
# -*- coding: utf-8 -*-
"""Analyzer for uwsgi log"""
import re
import copy
import datetime
from uwsgi_sloth.utils import total_seconds
from uwsgi_sloth.structures import ValuesAggregation
from uwsgi_sloth.settings import FILTER_METHODS, FILTER_STATUS, LIMIT_URL_GROUPS, \
LIMIT_PER_URL_G... |
#!/usr/bin/python3
#
# factors.py - Find the factors of a positive integer
#
# By Jim McClanahah, W4JBM (Dec 2020)
#
# Find the factors of a provided positive integer.
#
# The function is a modification of one originally
# provided by Harshit Agrawal to the geeksforgeeks.org
# website.
#
# It seems like things stop wor... |
import random
NUMBERS = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
def read_file():
WORDS = []
with open("./archivos/data.txt", "r", encoding="utf-8") as f:
for line in f:
WORDS.append(line.replace("\n", ""))
return WORDS
def random_word(words):
idx = random.randint(0, len(wor... |
def comp_surface_active(self):
"""Compute the active surface of the conductor
Parameters
----------
self : CondType13
A CondType13 object
Returns
-------
Sact: float
Surface without insulation [m**2]
"""
Sact = self.Wwire * self.Wwire * self.Nwppc_tan * self.Nwppc... |
# Import standard libraries.
import json
# Import external libraries.
import numpy as np
import pandas as pd
class dbSNP:
"""Store dbSNP data for a gene.
Parameters
----------
dbsnp_file : str
Path to a dbSNP file containing variant information.
Attributes
----------
df : pandas.... |
import itertools
import time
import warnings
import numpy as np
import matplotlib.colors
import matplotlib.pyplot as plt
import thalesians.tsa.checks as checks
import thalesians.tsa.numpyutils as npu
import thalesians.tsa.utils as utils
def _aggregate(aggregate_func, data, empty_aggregate):
if empty_aggregate !=... |
"""
Prime Developer Trial
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from fds.sdk.S... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
if __name__ == "__main__":
import sys
import json
import numpy as np
firstline = sys.stdin.readline()
obj = json.loads(firstline)
Np = obj['num_points']
dt = obj['dt']
L = obj['L']
Nt = obj['num_steps']
Nint = obj['step_chunk']
k = obj['k']
d = obj['d']
gifname = o... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
utils
~~~~~
Utility methods.
I'm including this file in the skeleton because it contains methods I've
found useful.
The goal is to keep this file as lean as possible.
:author: Jeff Kereakoglow
:date: 2014-11-14
:copyright: (c) 2014 ... |
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
import json
import logging
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from t... |
import os
import sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
import pglet
from pglet import Stack, Text
def main(page):
page.add(
Text('Squares', size='large'),
Stack(h... |
import os
import random
import itertools
import numpy as np
import torch
import torch.nn as nn
import torch.utils.data
import torchvision.transforms as transforms
from torchvision.utils import make_grid
from torch.autograd import Variable
from PIL import Image
import matplotlib.pyplot as plt
from tensorboardX import Su... |
# -*- coding: utf-8 -*-
# flake8: noqa
import os
from setuptools import find_packages, setup
from jaffle import __version__
long_description = '''
Jaffle is an automation tool for Python software development, which does:
- Instantiate Python applications in a Jupyter kernel and allows them to call
each other
- L... |
from ansiblelint import AnsibleLintRule
class LongStatement(AnsibleLintRule):
id = 'ANSIBLE0020'
descreiption = 'Keeping line in YAML file below 160 characters'
severity = 'medium'
tags = {'clarity'}
version_added = 'v1.0.0'
shortdesc = 'Keeping line in YAML file below 160 characters'
def... |
# Copyright 2000-2003 Jeff Chang.
# Copyright 2001-2008 Brad Chapman.
# Copyright 2005-2016 by Peter Cock.
# Copyright 2006-2009 Michiel de Hoon.
# All rights reserved.
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
#... |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import re, ast
with open('requirements.txt') as f:
install_requires = f.read().strip().split('\n')
# get version from __version__ variable in it_dept_library/__init__.py
_version_re = re.compile(r'__version__\s+=\s+(.*)')
with open('ssncoe/__init__... |
# Source and destination file names.
test_source = "data/math.txt"
test_destination = "math_output_mathml.html"
# Keyword parameters passed to publish_file.
reader_name = "standalone"
parser_name = "rst"
writer_name = "html5"
# Settings
settings_overrides['math_output'] = 'MathML'
# local copy of default stylesheet:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# (c) Copyright 2003-2015 HP Development Company, L.P.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at... |
from typing import Tuple, Union
import vapoursynth as vs
from lvsfunc.misc import source
from vardautomation import FileInfo, PresetAAC, PresetBD, VPath
from project_module import encoder as enc, flt
core = vs.core
core.num_threads = 4
# Sources
JP_NCED = FileInfo(r'BDMV/120926_JOSHIRAKU_VOL1/BDMV/STREAM/00002.m2t... |
# Generated by Django 3.1.3 on 2021-01-21 21:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('server', '0006_auto_20210120_2320'),
]
operations = [
migrations.AddField(
model_name='sensor',
name='lux_max',
... |
import sys
sys.path.append("../../")
import lib.gcn3d as gcn3d
import torch
import torch.nn as nn
import torch.nn.functional as F
class PriorEncoder(nn.Module):
def __init__(self, support_num: int, neighbor_num: int):
super(PriorEncoder, self).__init__()
self.neighbor_num = neighbor_num
... |
"""Tests for window_utils"""
import socket
import sys
import warnings
from trollius.test_utils import unittest
if sys.platform != 'win32':
raise unittest.SkipTest('Windows only')
from trollius import _overlapped
from trollius import py33_winapi as _winapi
from trollius import test_support as support
from trolliu... |
from collections import defaultdict, namedtuple
from django.contrib.gis import forms, gdal
from django.contrib.gis.db.models.proxy import SpatialProxy
from django.contrib.gis.gdal.error import GDALException
from django.contrib.gis.geos import (
GeometryCollection, GEOSException, GEOSGeometry, LineString,
Multi... |
# Copyright (c) OpenMMLab. All rights reserved.
import os
from collections import OrderedDict
import numpy as np
from mmpose.datasets.builder import DATASETS
from .hand_base_dataset import HandBaseDataset
@DATASETS.register_module()
class FreiHandDataset(HandBaseDataset):
"""FreiHand dataset for top-down hand p... |
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# 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... |
from .base_metric import BaseMetric
class ValueMetric(BaseMetric):
""" Base class for metrics that don't have state and just calculate a simple value """
def __init__(self, name):
super().__init__(name)
self._metric_value = None
def calculate(self, data_dict):
""" Calculate valu... |
# -*- coding: utf-8 -*-
import pya3rt
apikey = "{YOUR_API_KEY}"
client = pya3rt.TextSuggestClient(apikey)
print(client.text_suggest("馬"))
print(client.text_suggest("あき", style=1))
print(client.text_suggest("func", style=2)) |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-09-13 11:01
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import django_smalluuid.models
import mptt.fields
class Migration(migrations.Migration):
initial... |
"""
2019/12/08 15:16
142.【Python多任务编程】使用类的方式创建子进程(进程)
"""
"""
使用类的方式创建子进程:
有些时候,你想以类的形式定义子进程的代码。那么你可以自定义一个类,让他继承自`Process`,
然后在这个类中实现run方法,以后这个子进程在执行的时候就会调用run方法中的代码。
"""
from multiprocessing import Process
import os
class zhiliao(Process):
def run(self):
print('子进程ID: %s' % os.getpid())
print('... |
import logging
logging.getLogger('asyncio').setLevel(logging.ERROR)
logging.getLogger('asyncio.coroutines').setLevel(logging.ERROR)
logging.getLogger('websockets').setLevel(logging.ERROR)
logging.getLogger('urllib3').setLevel(logging.ERROR)
log_format = "[%(asctime)s][%(levelname)s] %(name)s - %(message)s"
logging.ba... |
# Shows the top tracks for a user
import sys
import spotipy
from spotipy.oauth2 import SpotifyOAuth
if len(sys.argv) > 1:
username = sys.argv[1]
else:
print("Usage: %s username" % (sys.argv[0],))
sys.exit()
scope = 'user-top-read'
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
ranges = ['... |
# -*- coding: utf-8 -*-
import re
import scrapy
from ics import Calendar
from city_scrapers.spider import Spider
class DetGreatLakesWaterAuthoritySpider(Spider):
name = 'det_great_lakes_water_authority'
agency_id = 'Great Lakes Water Authority'
timezone = 'America/Detroit'
allowed_domains = ['www.gl... |
"""
Python 3 Object-Oriented Programming
Chapter 13. Testing Object-Oriented Programs.
"""
import json
from pathlib import Path
import socketserver
from typing import TextIO
import pickle
import struct
import sys
class LogDataCatcher(socketserver.BaseRequestHandler):
log_file: TextIO
count: int = 0
size... |
# encoding: utf-8
import datetime
from south.db import db
from south.logger import get_logger
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'AttributeOption'
db.create_table('product_attributeoption', (
... |
#!/usr/bin/env python
"""
Renames (links) exam zip archives by consulting a lookup table.
This program looks up the proper name in a table that lists the original exam
archive name, and the target name.
Usage:
dm_link.py [options] <study>
dm_link.py [options] <study> <zipfile>
Arguments:
<study> ... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
"""
sentry.utils.manager
~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import datetime
import django
import logging
import warnings
from django.db import models
from django.db.models import signals, Sum, F
from sentry.con... |
"""
sentry.utils.auth
~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from sentry.models import ... |
from abc import ABCMeta, abstractmethod, abstractproperty
from collections import defaultdict
import six
from dagster import check
from dagster.core.errors import DagsterInvalidDefinitionError
from dagster.core.types.dagster_type import DagsterTypeKind
from .dependency import DependencyStructure, IDependencyDefinitio... |
class No:
def __init__(self, valor):
self.valor = valor
self.proximo = None
def mostra_no(self):
print(self.valor)
class ListaEncadeada:
def __init__(self):
self.primeiro = None
def insere_inicio(self, valor):
novo = No(valor)
novo.proximo = self.primeiro
self.primeiro = novo
d... |
from keras.applications.resnet_v2 import ResNet50V2
model=ResNet50V2(include_top=True, weights=None, input_tensor=None, input_shape=(100,100,3),classes=41)
model.summary()
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
print('Compiled!')
from keras.m... |
from bs4 import BeautifulSoup
import urllib.request as urllib2
import random
from random import choice
import pandas as pd
import copy, time, sys, shutil, os, yaml, json
import datetime as dt
from glob import glob
import regex
class scraper():
criteria = None
df = None
df_pre = None
__verbose = Fa... |
import os
import torch
import glob
import numpy as np
import scipy.sparse as sp
import yaml
from sklearn.preprocessing import StandardScaler
from shaDow.globals import git_rev, timestamp, Logger
from torch_scatter import scatter
from copy import deepcopy
from typing import List, Union
from shaDow import TRAIN, VALI... |
from collections import namedtuple
TestVector=namedtuple('TestVector', ['test_points', 'test_vectors']) |
import sys
sys.path.append('/export/zimmerman/khoidang/pyGSM')
SE_XING = True
SE_GSM = False
DE_GSM = False
ORCA=False
QCHEM=True
PYTC=False
nproc=8
if QCHEM: from qchem import *
elif ORCA: from orca import *
elif PYTC: from pytc import *
if SE_XING: from se_xing import *
if SE_GSM: from se_gsm import *
if DE_GSM: f... |
from flask_login import UserMixin
from __init__ import db
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True) # primary keys are required by SQLAlchemy
email = db.Column(db.String(100), unique=True)
password = db.Column(db.String(100))
name = db.Column(db.String(1000)) |
import os
mongodb_atlas = {
"connection_string": os.environ.get('MONGODB_CONNECTION_STRING'),
"database_name": "info-bot",
"news_collection_name": "wow-news",
"log_collections": {"commands": "user-commands-log", "updater": "push-updates-log"}
}
article_types = {
"HOTFIXES": "hotfixes",
"LATEST... |
# -*- coding: utf-8 -*-
"""
Created on Sam Aug 7 11:50:05 2020
@author: Dirk
This scripts applies a 10day low pass filter to the ERA5 gph daily means
"""
import scipy.signal as signal
import matplotlib.pyplot as plt
from pathlib import Path
import xarray as xr
#Define input and output data
data_folder = Path("..... |
from __future__ import unicode_literals, print_function, division
from io import open
import unicodedata
import string
import re
import random
from random import shuffle
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch import optim
import torch.nn.functional as F
import sys
import os
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.