content stringlengths 5 1.05M |
|---|
import os
from datetime import datetime as dt
from datetime import timedelta as td
from typing import Any, List, Set, Tuple
import shutil
import pandas as pd
from formsite_util.core import FormsiteCredentials, FormsiteInterface, FormsiteParams
from formsite_util.downloader import _FormsiteDownloader
def init... |
"""Contains code for training model"""
import pickle
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import transforms
from torch.nn.utils.rnn import pack_padded_sequence
from .models import EncoderCNN, DecoderRNN
from .dataset import get_loader
BATCH_SIZE = 32
EMBEDDING_DIM = 300
HID... |
"""Add requires_validator_role in project table
Revision ID: 5581aa8a3cd
Revises: 11695ee852ff
Create Date: 2017-01-10 11:18:46.081801
"""
# revision identifiers, used by Alembic.
revision = '5581aa8a3cd'
down_revision = '11695ee852ff'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_colum... |
from itertools import cycle
from typing import List
import numpy as np
from pyNastran.utils.numpy_utils import integer_types
from pyNastran.op2.tables.oes_stressStrain.real.oes_objects import (
StressObject, StrainObject, OES_Object)
from pyNastran.f06.f06_formatting import write_floats_13e, write_floats_8p1e
c... |
import themata
project = 'Exotic Libraries'
copyright = '2021, Exotic Libraries - MIT License'
author = 'Exotic Libraries Contributors'
html_theme_path = [themata.get_html_theme_path()]
html_theme = 'water'
master_doc = 'index'
html_favicon = 'assets/images/libcester/exoticlibs.png'
html_static_path = ['_st... |
def max_sequence(listeners, price):
"""
Compute the maximum earnings for a sequence of length 'length'.
An instance of the maximum subarray problem.
:param listeners: list of listeners for each break slot
:param price: price per break
:return: maximum profit
"""
best = 0
cur_... |
"""Module containing tests for two-repo mode of the Chlorine algorithm."""
from . import test_repo1_dir, test_repo2_dir
from engine.preprocessing.module_parser import get_modules_from_dir
from engine.algorithms.chlorine.chlorine import chlorine_two_repos
def test_chlorine_two_not_none():
"""Check if two-repo mod... |
# Copyright 2017-present Michael Hall
#
# 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... |
import json
from http.server import BaseHTTPRequestHandler
from flair.models import SequenceTagger
from REL.mention_detection import MentionDetection
from REL.utils import process_results
API_DOC = "API_DOC"
"""
Class/function combination that is used to setup an API that can be used for e.g. GERBIL evaluation.
"""... |
# MIT License
#
# Copyright (c) 2020 Archis Joglekar
#
# 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, mer... |
# coding: utf-8
"""
SCORM Cloud Rest API
REST API used for SCORM Cloud integrations.
OpenAPI spec version: 2.0
Contact: systems@rusticisoftware.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import sys
import os
import re
# pyth... |
import depthai #core packages
import logging # Logger
import cv2 # computer vision package
import json #json lib
from time import time, sleep, monotonic
from pathlib import Path #Path lib
from config import model, calib
# Object Tracker
from tracker import Tracker
from collision_avoidance import CrashAvoidance... |
from cranlock import main, lock
|
from django.urls import path
from . import views
urlpatterns = [
path('', views.bundle_list, name='bundles'),
path('<int:bundle_id>/', views.bundle_view, name='bundle'),
path('search/', views.bundle_search, name='search_bundles'),
]
|
class Encapsulada:
atributo_visible = 'soy visible'
_atributo_protegido = 'soy protegido'
__atributo_privado = 'soy un atributo privado'
def get_atributo_privado(self):
return self.__atributo_privado
def set_atributo_privado(self, cambio):
self.__atributo_privado = cambio
|
# SPDX-License-Identifier: Apache-2.0
#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
import os
import subprocess
import yaml
from git.git_repository import GitRepository
from manifests.bundle_manifest import Bu... |
from __future__ import print_function, division
#
import sys,os
os.environ['KMP_DUPLICATE_LIB_OK']='True' # uncomment this line if omp error occurs on OSX for python 3
os.environ['OMP_NUM_THREADS']='1' # set number of OpenMP threads to run in parallel
os.environ['MKL_NUM_THREADS']='1' # set number of MKL threads to run... |
from django.forms import SelectMultiple, HiddenInput
from django_filters import MultipleChoiceFilter
from service_catalog.models import Instance, Service
from service_catalog.models.instance import InstanceState
from Squest.utils.squest_filter import SquestFilter
class InstanceFilter(SquestFilter):
class Meta:
... |
#Import basic modules
import os, re
#Import local .py modules
from . import Utils
echo = Utils.echo
#Class to build a conditional tree to compare notes
class Node:
def __init__(self, string, depth = 0, removeBrackets = True):
self.children = []
if removeBrackets:
self.setString(strin... |
arquivo = open("dados.txt", "rt") #para ler oarquivo
arquivo = open("dados.txt", "wt+") #para escrver o aquivo, caso ele n exista criar
frase = []
frase.append('Olá \n')
frase.append('eu quero \n')
frase.append('cagarrr \n')
arquivo.writelines(frase)
print(arquivo.readline())
|
# This code sample uses the 'requests' library:
# http://docs.python-requests.org
import requests
import os
url = "https://api.trello.com/1/lists"
board_pos = int(os.environ.get("DAYS_OUT")) + 2
query = {
'key': os.environ.get("TRELLO_KEY"),
'token': os.environ.get("TRELLO_TOKEN"),
'name': os.environ.get("FO... |
"""Unit tests for cira_satellite_io.py."""
import unittest
from ml4tc.io import cira_satellite_io
TOLERANCE = 1e-6
TOP_DIRECTORY_NAME = 'foo'
CYCLONE_ID_STRING = '1998AL05'
VALID_TIME_UNIX_SEC = 907411500
SATELLITE_FILE_NAME = 'foo/1998/1998AL05/AL0598_19982761045M.nc'
class CiraSatelliteIoTests(unittest.TestCase)... |
'''
Submitted by: Ansh Gupta(@ansh422)
Date: 18/10/2021
'''
def isSafe(x,y,val,grid):
for i in range(9):
if grid[x][i] == val or grid[i][y] == val:
return False
for i in range(3):
for j in range(3):
if grid[i+(x-x%3)][j+(y-y%3)] == val:
return Fa... |
class Solution(object):
def isSubsequence(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
i=j=0
while i<len(s) and j<len(t):
if s[i]==t[j]:
i+=1
j+=1
else:
j+=1
return True if i==len(s) else False |
# Copyright 2020-2021 Exactpro (Exactpro Systems 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... |
import numpy as np
from scipy.stats import dirichlet
from scipy.special import psi, polygamma, gammaln
eps = 1e-100
max_iter = 10
converge_criteria = 0.001
def parameter_estimation(theta, old_alpha):
"""Estimating a dirichlet parameter given a set of multinomial parameters.
Parameters
----------
... |
# Copyright 2018 The TensorFlow 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 b... |
from google.appengine.ext import ndb
# Keep the details of articles
class Article(ndb.Model):
# The parent of an Entry is Account
dateCreated = ndb.DateProperty()
lastEdited = ndb.DateProperty(indexed = True) # indexed = True is only useful for changing previous indexed = False
content = ndb.TextProperty()
titl... |
# module binary
import sys
sys.path.append('..')
from astropy import units as u
from astropy import constants as const
import astropy
import numpy
import numpy as np
import math
import timeit
import zams
import argparse
import System
from scipy.integrate import trapz
def parse_commandline():
parser = argparse.A... |
import pandas as pd
import numpy as np
#Returns number of cells in dataframe that are missing in percent
def calc_missing_values(df: pd.Series) -> float:
missing_per_column: pd.Series = df.isnull().sum()
total_missing: int = missing_per_column.sum()
total_number_cells = np.product(df.shape)
return total_missin... |
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
nums.sort()
i=0
j=1
while i<=len(nums)-2:
if nums[i]==nums[j]:
return nums[j]
i+=1
j+=1
|
"""Cascade Mask RCNN with ResNet50-FPN, 3x schedule."""
_base_ = [
"../_base_/models/cascade_mask_rcnn_r50_fpn.py",
"../_base_/datasets/bdd100k.py",
"../_base_/schedules/schedule_3x.py",
"../_base_/default_runtime.py",
]
load_from = "https://dl.cv.ethz.ch/bdd100k/ins_seg/models/cascade_mask_rcnn_r50_fp... |
from gym.envs.registration import register
register(
id='HybridHammerEnv-v1',
entry_point='environments.metaworld.constructors:HybridHammerEnvV1',
max_episode_steps=200,
kwargs={'mode': 'train'}
)
register(
id='HybridDcEnv-v1',
entry_point='environments.metaworld.constructors:HybridDrawerClose... |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
from datetime import datetime, timedelta
from .common.base import BaseResource
from ..libs.respository import create_repo
from ..models.models import PipelineRPS
from ..schemas.pipeline_rps import (
PipelineRPSPostSchema,
PipelineRPSGetSchema,
PipelineRPSSchema
)
from flask import request, jsonify
from fl... |
'''
SAT Solver based on Davis–Putnam–Logemann–Loveland (DPLL) algorithm
Uses Jersolow-Wang 2-sided method (consider only positive literals)
Returns -
* SATISFIABLE followed by the model if the formula is satisfiable
* UNSATISFIABLE if the formula is unsatisfiable
'''
# Import necessary libraries
import argp... |
# coding=utf-8
from django.contrib import admin
from django.utils.html import format_html_join, format_html
from .models import NewsItem
@admin.register(NewsItem)
class NewsItemAdmin(admin.ModelAdmin):
readonly_fields = ('formatted_text',)
list_display = ('publish_date', 'get_title', 'source')
list_displ... |
from __future__ import absolute_import
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django_rq import queues
from redis import RedisError
from rq import Worker
from ..constants import OK, WARNING, ERROR
from ..decorators import timed
from . import Resource
class Djang... |
from .odeConstructs import *
from .EditorPanel import *
from direct.directtools.DirectCameraControl import *
from direct.tkpanels import Placer
from .PinballElements import *
import shutil
class PinballEditor:
__module__ = __name__
def __init__(self, bw, dfn):
self.defaultFilename = dfn
self.b... |
#==========================================================================
#===============================
a = int(input("Enter first number: "))
b= int(input("Enter second number: "))
c= int(input("Enter third number: "))
if (a > b) and (a > c):
largest = a
elif (b > a) and (b > c):
largest =b
... |
# Copyright (C) 2011 Victor Semionov
# 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, this
# list of conditions and t... |
import os
HOSTNAME = '127.0.0.1'
PORT = '3306'
DATABASE = 'project_demo'
USERNAME = 'root'
PASSWORD = 'zxcvBnm123'
DB_URI = 'mysql+pymysql://%s:%s@%s:%s/%s?charset=utf8' % (USERNAME,PASSWORD,HOSTNAME,PORT,DATABASE)
SQLALCHEMY_DATABASE_URI = DB_URI
SQLALCHEMY_TRACK_MODIFICATIONS = False
DEBUG = True
SECRET_KEY = o... |
#!/usr/bin/env python3
import argparse
import os
import serial
import struct
import sys
import time
from esp8266 import ESP8266, CLOSED
def expect(a, b):
if a == b:
return
print(f'Mismatch: {a} versus {b}', file=sys.stderr)
assert(0)
def sanity_check(ser):
'''Check sanity of current rate'''
... |
class CalculadorImposto:
def calcula(self, orcamento, imposto):
return imposto.calcula(orcamento)
|
#!/usr/bin/python
#
#./transformer.py input.csv transformations.csv > output.csv
##
#
# A Python program to read a csv file extract from a cell the content and replace
# elements with the tranformations rules.
# Program name - transformer.py
# Written by - Catalin Stanciu (catacsdev@gmail.com)
#
# Example:
# transfo... |
import time
EXIT_WIN_DELAY = 5 # [EXIT_WIN_DELAY] = s
class TicTacToe(object):
def __init__(self):
self.fields = []
self.reset()
def reset(self):
self.fields = [['' for _ in range(3)] for _ in range(3)]
def set_field(self, x, y, player):
self.fields[y][x] = player
... |
import datetime
import os
try:
from .ignore2 import AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY
except:
AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID", "AKIAV2BJVZP6UY2H44NZ")
AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_SECRET_ACCESS_KEY", "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")
AWS_GROUP_NAME = ... |
from setuptools import setup
from pypaystack import version
setup(name='pypaystack',
version=version.__version__,
description='Python wrapper for Paystack API',
url='https://github.com/edwardpopoola/pypaystack',
author=version.__author__,
author_email='edwardpopoola@gmail.com',
license=version.... |
import FWCore.ParameterSet.Config as cms
from SimFastTiming.FastTimingCommon.fastTimeDigitizer_cfi import *
from SimFastTiming.FastTimingCommon.mtdDigitizer_cfi import *
from SimFastTiming.FastTimingCommon.mtdDigitizer_cfi import _barrel_bar_MTDDigitizer
from Configuration.Eras.Modifier_phase2_timing_layer_bar_cff i... |
from algo.dqn.train import * |
"""
Kalman filter implementation was based on paper "Implementation of Kalman Filter with Python Language"
Mohamed LAARAIEDH
IETR Labs, University of Rennes 1
Mohamed.laaraiedh@univ-rennes1.fr
Code was adapted to follow the notation of the course assignment
"""
from numpy.linalg import inv
import matplotlib.pyplot a... |
from pathlib import Path
from jinja2 import Environment, FileSystemLoader
from .config import config, root
SQL_DIR: str = "sql"
SCHEMA_FILE: str = "schema.sql"
def schema() -> None:
path: Path = (root / SQL_DIR).resolve(strict=True)
env = Environment(loader=FileSystemLoader(path))
template = env.get_te... |
import pygame
import os
import random
import time
from enemy.scorpion import Scorpion
from towers.archerTower import ArcherTower
from towers.archerTower import ArcherTowerShort
from enemy.Club import Club
from enemy.tmall import TMall
from towers.supportTower import DamageTower
from towers.supportTower import RangeTowe... |
import os
import numpy as np
import pandas as pd
df = pd.read_csv(os.getcwd() + "/city/output/list_of_countries.csv")
df.set_index("country", inplace=True)
print("Enter the name of a country : ", end=" ")
country_to_be_searched = input().title()
for i in df:
if not np.isnan(df.loc[country_to_be_searched][str(i)]... |
from typing import List, Dict, Any, Optional, Union
from relevanceai.operations_new.run import OperationRun
from relevanceai.operations_new.dr.models.base import DimReductionModelBase
class DimReductionBase(OperationRun):
model: DimReductionModelBase
fields: List[str]
alias: str
def __init__(
... |
from optparse import OptionParser
from ztf_util import make_dict_from_config, make_dict_from_optparse
from ztf_simu import Simul_lc
from ztf_hdf5 import Write_LightCurve
from ztf_util import multiproc, dump_in_yaml, checkDir
from astropy.table import Table, vstack
def simu(index, params, j=0, output_q=None):
par... |
import sys
import pytest
if sys.version_info >= (3, 8):
from importlib.metadata import version
else:
from importlib_metadata import version
python_3_6_plus = pytest.mark.skipif(sys.version_info < (3, 6), reason="Python 3.6+")
def test_version(flake8dir):
result = flake8dir.run_flake8(["--version"])
... |
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from Employees.models import Person, Employee, Project
# Create your views here.
# Display Persons
def index_persons(request):
persons = Person.objects.all()
return render(request,
'employees/index_per... |
# Copyright (c) 2016 EMC Corporation.
# 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 requ... |
from PySide2 import QtCore, QtGui, QtWidgets
import sys
class FilterEdit(QtWidgets.QLineEdit):
def __init__(self):
super(FilterEdit, self).__init__()
self.setPlaceholderText("Filter")
class SectionView(QtWidgets.QListView):
doubleClicked = QtCore.Signal(object)
def __init__(self, parent... |
# Iterate over string using list comprehension
list = ['Hello World', "JAVA", "C++", "MySQL"]
x = [str.lower() for str in list]
print(x) |
from unittest import TestCase
from gdacs.api import GDACSAPIReader, GDACSAPIError
class TestGDACSAPI(TestCase):
def setUp(self):
self.client = GDACSAPIReader()
def tearDown(self):
self.client = None
# delete all the files
def test_latest_events_no_args(self):
'''Test la... |
import unittest
from soap.datatype import int_type, FloatArrayType
from soap.expression import Variable
from soap.parser import parse
from soap.semantics.schedule.extract import ForLoopNestExtractor
from soap.semantics.state import flow_to_meta_state
def _extract_from_program(program):
flow = parse(program)
... |
import pyttsx3
import datetime
import time as t
import smtplib
import wikipedia
import webbrowser as wb
import os
import string
import wolframalpha
import pyautogui
import psutil
import pyjokes
import random
from colored import fg, attr
import speech_recognition as sr
print(f"""{fg(226)}{attr(1)}
... |
"""
https://leetcode.com/problems/fair-candy-swap/
https://leetcode.com/submissions/detail/186770998/
"""
class Solution:
def fairCandySwap(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: List[int]
"""
diff = (sum(A) - sum(B)) / 2
setB = set(... |
class DiscipleClass:
def displayAllDisciples(self,language):
import json
if (language == "EN"):
try:
with open('../data/data.txt') as json_file:
data = json.load(json_file)
for i in data['disciples']:
print('... |
# Created by Artem Manchenkov
# artyom@manchenkoff.me
#
# Copyright © 2019
#
# Сервер для обработки сообщений от клиентов
#
from twisted.internet import reactor
from twisted.protocols.basic import LineOnlyReceiver
from twisted.internet.protocol import ServerFactory, connectionDone
class Client(LineOnlyReceiver):
... |
__author__ = "Nghia Doan"
__company__ = "Agiga Quanta Inc."
__copyright__ = "Copyright 2018"
__version__ = "1.0.0"
__maintainer__ = "Nghia Doan"
__email__ = "nghia71@gmail.com"
__status__ = "Production"
from ast import literal_eval
from configparser import ConfigParser, ExtendedInterpolation
class ConfigHandler(obj... |
import typer
from pyfiglet import Figlet
from rich.console import Console
from triggercmd_cli import __version__
from triggercmd_cli.command.command import command_app as app
# app = typer.Typer(help=__doc__)
console = Console()
app.help = __doc__
# app.add_typer(command_app, name="command")
def get_version(version... |
#!/usr/bin/env python
from distutils.core import setup
setup(name='widlparser',
version='0.999',
description='WebIDL Parser',
author='Peter Linss',
author_email='peter.linss@hp.com',
url='http://github.com/plinss/widlparser/',
packages = ['widlparser']
)
|
import asyncio
import logging
import socket
import fstrm
import dnstap_pb
from dnstap_receiver.outputs import transform
clogger = logging.getLogger("dnstap_receiver.console")
def checking_conf(cfg):
"""validate the config"""
clogger.debug("Output handler: dnstap")
valid_conf = True
if cfg["... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 6 13:12:12 2021
@author: z
"""
import pprint
import numpy as np
import torch
import logging
import transformers
import datasets
from dataclasses import dataclass, field
from typing import Optional
from custom_data_collator import DataCollatorForTo... |
"""
Find most common first names in a list of people.
This can be used after cleaning your data.
Example of cleaned data used: ./example/names.txt
Author: Christian M. Fulton
Date: 05.Aug.2021
"""
def main():
"""
Exec
"""
first_names()
#impl opt exp data
#ex = input("Would you like to expo... |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... |
from django.urls import path
from . import views
app_name = "inventory"
urlpatterns = [
path("objekt/", views.ObjektListView.as_view(), name="objekt-list"),
path("objekt/add/", views.ObjektCreateView.as_view(), name="objekt-create"),
path("objekt/<int:pk>/", views.ObjektDetailView.as_view(), name="objekt-... |
import sys
import os
sys.path.insert(0, os.path.realpath('.'))
import mimetypes
from create_movie import generate_movie
def test_generate_movie(tmpdir):
images_dir = os.path.realpath(
os.path.join(
os.path.dirname(__file__),
'fixtures'))
output_filename = tmpdir.jo... |
"""
It is always Calm before a Tornado!
Calm is a Tornado extension providing tools and decorators to easily develop
RESTful APIs based on Tornado.
The core of Calm is the Calm Application. The users should initialize an
(or more) instance of `calm.Application` and all the rest is done using that
instance.
The whole... |
import discord
import datetime as dt
from fuzzywuzzy import fuzz
from dateutil.relativedelta import relativedelta
from data import data
DEFAULT_BIRHDAY_RANGE_IN_DAYS = 45
A_EMOJI = 127462
SKIP_EMOJI = 9197
YES_NO_SHOW = {'👍': 1, '👎': 0, '🔎': 2}
MAPS = ['Haven', 'Split', 'Ascent', 'Bind', 'Icebox']
def emoji_list(... |
from flask import Flask
from flask_opentracing import FlaskTracer
import lightstep.tracer
import opentracing
import urllib2
app = Flask(__name__)
# one-time tracer initialization code
ls_tracer = lightstep.tracer.init_tracer(group_name="example client", access_token="{your_lightstep_token}")
# this tracer does not tr... |
#!/usr/bin/env python
values = [4, 10, 3, 8, -6]
print(values)
for i in range(len(values)):
values[i] = values[i] * 2
print(values)
|
import random
import json
def index():
return dict(message=T('Welcome to our Crowd Sourcing Platform!'))
#@auth.requires_login()
def get_sentence():
return "bla"
#@auth.requires_login()
def tutorial():
return dict()
def getAnnotation(data):
session.data = data
ret = "<p>"
words = data['sent... |
from RePoE.parser.util import call_with_default_args, write_json
from RePoE.parser import Parser_Module
class quest_rewards(Parser_Module):
@staticmethod
def write(ggpk, data_path, relational_reader, translation_file_cache, ot_file_cache):
root = {}
all_classes = ["Duelist", "Marauder", "Range... |
from __future__ import absolute_import, division, print_function
def info(filename):
'''Generate information from EXIF headers.'''
import exifread
import datetime
import calendar
ts = 'EXIF DateTimeOriginal'
result = {}
with open(filename) as f:
tags = exifread.process_file(f, ... |
import spam
@spam.eggs
def eggs_and_sausage(*args):
return "spam"
|
###########################################################################
# Created by: Dan Xu
# Email: danxu@robots.ox.ac.uk
# Copyright (c) 2019
###########################################################################
import os
import os.path as osp
import numpy as np
import random
import collections
import tor... |
# Generated with SMOP 0.41-beta
try:
from smop.libsmop import *
except ImportError:
raise ImportError('File compiled with `smop3`, please install `smop3` to run it.') from None
# Get_VarthsPSI_swing.m
@function
def Get_VarthsPSI_swing(zetaj=None,ntilj=None,PSIdj=None,PSIdjm1=None,*args,**kwargs)... |
from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
from flask_httpauth import HTTPBasicAuth
import utils
app = Flask(__name__, static_folder="react-dashboard/build", static_url_path="/")
CORS(app, resources={r"/*": {"origins": "*"}})
app.config["CORS_HEADERS"] = "Content-Type"
... |
B_15_01_10 = {0: {'A': -0.054, 'C': 0.0, 'E': 0.52, 'D': 0.0, 'G': 0.183, 'F': -0.158, 'I': -0.377, 'H': -0.009, 'K': 0.207, 'M': -0.074, 'L': -0.365, 'N': 0.062, 'Q': 0.054, 'P': 0.164, 'S': -0.081, 'R': -0.242, 'T': 0.141, 'W': -0.11, 'V': 0.136, 'Y': 0.002}, 1: {'A': 0.094, 'C': 0.0, 'E': -0.305, 'D': 0.0, 'G': 0.20... |
from collections import deque
import random
import numpy as np
import tensorflow as tf
class flappydqn:
# parameters
ACTION = 2
FRAME_PER_ACTION = 1
GAMMA = 0.99 # decay rate of past observations
OBSERVE = 10000 # timesteps to observe before training
EXPLORE = 300000 # frames over which to anneal epsilon
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2012 The Plaso Project Authors.
# Please see the AUTHORS file for details on individual 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 L... |
# Imports
from pysal.lib import examples
import geopandas as gpd
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
from pysal.viz.splot.mapping import vba_legend, mapclassify_bin
# Load Example Data
link_to_data = examples.get_path('columbus.shp')
gdf = gpd.read_file(link_to_data)
x = gdf['HOVAL']... |
# coding=utf-8
from config import *
from dependency import *
from downloader import *
|
CLIENT_ID = None
CLIENT_SECRET = None
API_BASE_URL = 'https://api.figshare.com/v2/'
MAX_RENDER_SIZE = 1000
FIGSHARE_OAUTH_TOKEN_ENDPOINT = '{}{}'.format(API_BASE_URL, 'token')
FIGSHARE_OAUTH_AUTH_ENDPOINT = 'https://figshare.com/account/applications/authorize'
FIGSHARE_DEFINED_TYPE_NUM_MAP = {
'figure': 1,
... |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class TypeFileSearchResultEnum(object):
"""Implementation of the 'Type_FileSearchResult' enum.
Specifies the type of the file document such as KDirectory, kFile, etc.
Attributes:
KDIRECTORY: TODO: type description here.
KFILE: TODO: ... |
import json
from cardbuilder.common import Language, Fieldname
from cardbuilder.exceptions import WordLookupException
from cardbuilder.input.word import Word
from cardbuilder.lookup.data_source import WebApiDataSource
from cardbuilder.lookup.lookup_data import LookupData, outputs
from wiktionaryparser import Wiktiona... |
import tvm
from ..hw_abs_base import (
HardwareAbstraction,
register_abstraction,
MemoryAbstraction,
ComputeAbstraction,
ElementwiseComputeAbstraction,
ElementwiseMemoryAbstraction,
)
@register_abstraction("tenet axpy", "tenet::axpy::store_vector")
class TenetAxpyStoreVector(MemoryAbstraction)... |
# import os
from pathlib import Path
import pandas as pd
class QC(object):
def __init__(self, folder_path = '/Users/htelg/data/baseline/scaled/brw/2018/',
folder_path_raw='/Volumes/grad/gradobs/raw/ber/2018/',
num_files_to_be_opened = 3,
verbose = False,
... |
"""
Copyright 2017 NREL
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
un... |
"""Module for converting sysopt expression graphs into casadi functions."""
from typing import List, Union
from sysopt.symbolic import Algebraic, scalar_shape, is_op, is_matrix
import casadi as _casadi
def lambdify(graph,
arguments: List[Union[Algebraic, List[Algebraic]]],
name: str = 'f')... |
from django.conf import settings
from django.db.models import F
from django.utils.translation import activate
from geotrek.api.v2 import serializers as api_serializers, \
filters as api_filters, viewsets as api_viewsets
from geotrek.api.v2.functions import Transform
from geotrek.outdoor import models as outdoor_mo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.