content stringlengths 5 1.05M |
|---|
from datetime import datetime
import os
import platform
from setproctitle import setproctitle
import sys
import time
import traceback
from django.core.cache import cache
from django.core.management.base import BaseCommand, CommandError
from integlib.logbook_utils import configure_logging
from integlib.runtime import ... |
import collections
import json
import logging
import traceback
from urllib.parse import urlparse, parse_qs
import github as gh
from tornado.httpclient import AsyncHTTPClient
import tornado.gen
def parse_link(link_header):
l0, l1 = link_header.split(',')
next_url = l0.strip()[1:-len('>; rel="next"')]
last... |
#!/usr/bin/env python3
# Copyright 2014 Jason Heeris, jason.heeris@gmail.com
#
# This file is part of the gammatone toolkit, and is licensed under the 3-clause
# BSD license: https://github.com/detly/gammatone/blob/master/COPYING
import nose
import numpy as np
import scipy.io
from pkg_resources import resource_stream
... |
from django.conf.urls import url, include
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^$', views.shift_list, name='shift_list'),
]
|
# -*- coding:utf-8 -*-
from os import path
import os
import datetime
import sys
import requests
import config, log, util
import time
import hist_handler
import traceback
from threadpool import ThreadPool
from Queue import Queue
from mutagen.id3 import ID3,TRCK,TIT2,TALB,TPE1,APIC,TDRC,COMM,TPOS,USLT
from threading impo... |
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema
from flask_marshmallow.fields import AbsoluteUrlFor
from driftbase.models.db import FriendInvite
from marshmallow import pre_dump, fields, post_dump
class InviteSchema(SQLAlchemyAutoSchema):
class Meta:
model = FriendInvite
load_instance = Tr... |
# -*- encoding:utf-8 -*-
from datetime import datetime
import socket
import re
from twython import Twython
import os
import json
home = os.path.expanduser("~")
twitter_conf_file = os.path.join(home, '.ashioto', 'twitter.json')
tc = json.load(open(twitter_conf_file))
CONSUMER_KEY = tc["CONSUMER_KEY"]
CONSUMER_SECRET = ... |
from utils import lowercase, key_of_max
import string
#
# WordSet class
#
class WordSet:
"""
Set of unique words, all in lower case and of positive length.
"""
def __init__(self, text):
"""
Form a WordSet from a string of words or collection of words.
"""
# BEGIN Questi... |
#!/usr/bin/env python
from random import randrange as rand
import neopixel
import datetime
from PIL import Image
import time
import sys
import os
color_scheme = 'RGB'
class SingleAnimation:
active_id = 0
frame = 0
state = True
images = []
def __init__(self, strip, images_src, duration_s, *... |
import math
import numpy as np
def LinEx(y: int, est: int):
"""
A function that return the error for a given estimation of the number of calls
:param y: truth
:param est: estimation (ŷ in the folowing formula)
:return: LinEx(y, ŷ) = exp[α(y − ŷ)] − α(y − ŷ) − 1
"""
alpha = 0.1
prod = a... |
from dartcms.utils.config import DartCMSConfig
from dartcms.utils.loading import get_model
from django.forms import modelform_factory
app_name = 'feeds'
Feed = get_model('feeds', 'Feed')
config = DartCMSConfig({
'model': Feed,
'grid': {
'grid_columns': [
{'field': 'type', 'width': '10%'},... |
# make deterministic
from mingpt.utils import set_seed
set_seed(42)
import numpy as np
import torch
import torch.nn as nn
from torch.nn import functional as F
import math
from torch.utils.data import Dataset
from mingpt.model import GPT, GPTConfig,GPTForClassification
from mingpt.trainer import Trainer,... |
import argparse
import json
import logging
import subprocess
import sys
import hashlib
import coloredlogs
from wand.image import Image
from basset.exceptions import *
class Converter:
def __init__(self):
coloredlogs.install()
self.input_dir = ""
self.output_dir = ""
self.force_co... |
b2b_hotel_page_response = {
"debug": {
"b2b_request": {
"checkin": "2020-08-05",
"checkout": "2020-08-06",
"currency": None,
"residency": "ru",
"timeout": None,
"language": "ru",
"guests": [{"adults": 1, "children": []}],
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 17 10:37:19 2022
@author: kawta
"""
### Importing neccessary packages
import pandas as pd
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.linear_mo... |
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2019, Camptocamp SA
# 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, this
#... |
x = 40
y = 30
print('x + y =', x + y) # 70
print('x - y =', x - y) # 10
print('x * y =', x * y) # 1200
print('x / y =', x / y) # 1.333
print('x // y =', x // y) # 1 => Floor division (quotient)
print('x % y =', x % y) # 10
# 1152921504606846976000000000000000000000000000000 => x ^ y
print('x ** y =', x**y)
|
"""
[12/23/13] Challenge #130 [Hard] Coloring France's Departments
https://www.reddit.com/r/dailyprogrammer/comments/1tj0kl/122313_challenge_130_hard_coloring_frances/
# [](#HardIcon) *(Hard)*: Coloring France's Departments
The European country of [France](http://en.wikipedia.org/wiki/France) is segmented into many d... |
from errno import ENOENT
from os import path
import six
from .html_elements import InputCollection
from .input import Input
from ..meta_elements import MetaHTMLElement
@six.add_metaclass(MetaHTMLElement)
class FileField(Input):
def set(self, filepath):
"""
Set the file field to the given path
... |
from LinkedList import *
from collections import *
class Queue:
''' This class defines a queue data structure '''
def __init__(self):
''' __init__ method initializing the queue '''
self.queue = list()
def enqueue(self, item):
''' Method to perform the enqueue operatio... |
"""
This file reads the documents with specified values from the MongoDB, and readies them for insertion into the
Postgres schema. This is a separate class, since we want to avoid running it with every try/experimentation over
the 'regular' schema, which could potentially have several reworks. The stored documents, on ... |
#!/usr/bin/env python3
import json
import logging
import sys
import time
import click
import requests
from requests import Response
from bubuku.features.remote_exec import RemoteCommandExecutorCheck
from bubuku.utils import get_opt_broker_id, prepare_configs, is_cluster_healthy, get_max_bytes_in
from bubuku.zookeeper... |
#
# Copyright (c) 2016 Nutanix Inc. All rights reserved.
#
from curie.node_util import NodeUtil
class GenericVsphereNodeUtil(NodeUtil):
@classmethod
def _use_handler(cls, node):
"""Returns True if 'node' should use this class as its handler."""
software_info = node.cluster().metadata().cluster_software_... |
# -*- coding: utf-8 -*-
import datetime
import functools
import logging
from bleach import linkify
from bleach.callbacks import nofollow
import markdown
from markdown.extensions import codehilite, fenced_code, wikilinks
from modularodm import fields
from framework.forms.utils import sanitize
from framework.guid.mod... |
# Copyright 2019 Xanadu Quantum Technologies Inc.
# 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 agre... |
import ast
from types import FunctionType
from kanren import var
from tests.helpers import EvaloTestCase
class TestExpressions(EvaloTestCase):
def test_number_value_results_in_ast_number(self):
ret, _ = self.run_expr(var(), 1, eval_expr=True)
self.assertIsInstance(ret[0], ast.Num)
def test_n... |
# Copyright (C) 2010-2015 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# This signature was contributed by RedSocks - http://redsocks.nl
# See the file 'docs/LICENSE' for copying permission.
from lib.cuckoo.common.abstracts import Signature
class im_btb(Signature):
name ... |
# coding: utf8
import os, subprocess, datetime, fileinput
from flask import Flask, flash, request, redirect, url_for, send_from_directory
import common as kbd
KEYBOARDS = []
# import keyboard configurations and add them to app keyboard list
from keyboards.minivan import keyboard as minivan_rev1
KEYBOARDS.append(miniva... |
#!/usr/bin/python3
# coding:UTF8
#----library-----#
import os.path
import os
import sys
import vcf
import json
import time
import copy
import errno
import verification_vcf
#---------------#
class VcfModel(object):
# CONTANTE
SAMPLE_NAME = "SAMPLE_NAME"
CONTIGS = "CONTIGS"
FORMAT = "FORMAT"
IN... |
"""
Components/Transition
=====================
.. rubric::
A set of classes for implementing transitions between application screens.
.. versionadded:: 1.0.0
Changing transitions
--------------------
You have multiple transitions available by default, such as:
- :class:`MDFadeSlideTransition`
state one: t... |
from queue import Queue
class Node:
def __init__(self, char, count):
self.ch = char
self.ct = count
self.lt = None
self.rt = None
def __repr__(self):
return "{}=>[ct={},lt={},rt={}]".format(self.ch, self.ct, self.lt, self.rt)
def parse_queue_and_get_tree(nq):
if ... |
#!/usr/bin/env python
import os
import sys
os.chdir(sys._MEIPASS)
import data6
print os.getcwd()
|
# -*- coding: utf-8 -*-
from .queues import QueueInterruptable, is_main_alive
from .concurrent import Threaded
from .ilogging import logg
from time import sleep
class ActiveQ(QueueInterruptable):
def __init__(self, maxsize=256, jobq=None, resq=None):
self._run_thread = None
self._resq = resq # ... |
"""empty message
Revision ID: 0a1a1fcb6302
Revises:
Create Date: 2018-05-26 20:35:58.639216
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0a1a1fcb6302'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... |
#!/usr/bin/env python
import os
import time
#----------------------------------------------------------------
# Note:
# ds18b20's data pin must be connected to pin7(GPIO4).
#----------------------------------------------------------------
# Reads temperature from sensor and prints to stdout
# id is the id ... |
import numpy as np
import matplotlib.pyplot as plt
from distributionally_robust_portfolio import *
from SimSet2 import *
class SimSet3(DistributionallyRobustPortfolio):
m = 10
eps_range = np.concatenate([np.arange(1, 10)*10.0**(i)
for i in range(-3, 0)])
valids = normal_ret... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# java2python -> top-level package marker.
|
import os
import numpy as np
import matplotlib.pyplot as plt
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
ejemplo = plt.imread(THIS_FOLDER + "/img/vignetting.jpg")
def histograma(img):
"""Calcula y representa el histograma de una imagen RGB.
Args:
img (Numpy array 3d): Un imagen RGB
... |
# Create By : Yogesh Kothiya
# Uses : Manage Role
from flask import jsonify, request
import socket
import apis.utils.constants as CONST
from datetime import datetime, date, time, timedelta
import pymongo
from database import DB
import json
from bson import json_util, ObjectId
class crads:
def __init__(self,vendor... |
"""Command Line Parser realated functions.
One function creates the parser.
Another function allows hybird usage of:
- a yaml file with predefined parameters
and
- user inputted parameters through the command line.
"""
import argparse
import yaml
def create_parser():
"""Creates a parser with all the variables t... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from retrieval_rs.metric import rouge_score as rouge_score
import sys
import os
SR_DIR = os.path.abspath(os.path.join(__file__, os.pardir, os.pardir, os.pardir))
sys.path.insert(0, SR_DIR)
class Rouge:
DEFAULT_METRICS = ["rouge-1", "rouge-2", "rouge-3... |
import unittest
from pathlib import Path
from tempfile import TemporaryDirectory
from wrk2img import ImageGenerator
class TestImageGenerator(unittest.TestCase):
def setUp(self):
self.image_generator = ImageGenerator()
def test_generate_image(self):
data = {
'748868.53 req/s': {
... |
from project.card.card import Card
class CardRepository:
def __init__(self):
self.cards = list()
@property
def count(self):
return len(self.cards)
def add(self, card: Card):
if card.name in [c.name for c in self.cards]:
raise ValueError(f"Card {card.name} already ... |
#!/usr/bin/env python
###############################################################
# < next few lines under version control, D O N O T E D I T >
# $Date$
# $Revision$
# $Author$
# $Id$
###############################################################
###############################################################
... |
# in iPython:
# %run -i i2c.py
# the -i means use existing global variables; in particular: ser
# (otherwise, we end up with multiple open serial connections and it gets ugly)
import sys
import os
import re
import serial
import time
from math import ceil
from functools import reduce
from itertools import chain
if l... |
from alphaOps import AlphaOps
from extention import ExtentionOps
#Gloabal w value, bad practice but this easy for now
w = 2
class Ops():
"""Used the generate the correct fuzzy set operation for each node"""
def printStuff(self):
print(dir(self))
def getFunc(self,operator):
... |
# python
import lx, bling, os, lxu
CMD_NAME = "bling.matcapAdd"
class CommandClass(bling.CommanderClass):
_commander_default_values = []
_icon = None
_imageCache = bling.imageCache()
def commander_arguments(self):
return [
{
'name': 'matcap',
'data... |
# MIT License
# Copyright (c) 2018 Maximiliano Isi, Richard Brito
# 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... |
from nicos.devices.tango import BaseImageChannel as ImageChannel
|
# Generated by Django 3.1.1 on 2020-09-19 20:32
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('drinks', '0009_order_status'),
]
operations = [
migrations.RemoveField(
model_name='order',
name='status',
),
]
|
from dataclasses import dataclass, field
from typing import List, Optional, Tuple
from oogeso import dto
# Device types defined as part of "basic":
# DevicePowerSourceData
# DeviceSink_elData
# DeviceStorage_elData
@dataclass
class DeviceSourceElData(dto.DeviceData):
co2em: Optional[float] = None
op_cost: O... |
from processing_functions import color_stuff as mn
import cv2
import glob
from processing_functions import misc as msc
import os
# impath = "/home/kauevestena/data/extracted_images/2019-06-13-15-43-38/ngr/2419.jpg"
# outpath = "/home/kauevestena/data/extracted_images/transformed/teste_b.jpg"
# mn.save_one_band(impa... |
from __future__ import print_function
from onmt.translate.translator import Translator as _Translator
import onmt.model_builder
import onmt.translate.beam_search
from onmt.translate import TranslationBuilder as _TransBuilder
import onmt.inputters as inputters
import onmt.decoders.ensemble
from pangeamt_toolkit.pangeanm... |
from __future__ import (absolute_import, division, print_function)
import lmfit
import traitlets
import ipywidgets as ipyw
import weakref
from qef.io import log_qef
class ParameterWidget(ipyw.Box):
r"""One possible representation of a fitting parameter.
Inherits from `ipywidgets.widgets.widget_box.Box <https... |
import os
import sys
from PySide2 import QtWidgets
from sleap.gui.dialogs.filedialog import FileDialog
def test_non_native_dialog():
save_env_non_native = os.environ.get("USE_NON_NATIVE_FILE", None)
os.environ["USE_NON_NATIVE_FILE"] = ""
d = dict()
FileDialog._non_native_if_set(d)
is_linux = s... |
from PyQt5.QtWidgets import QWidget
from widgets import ImageButton
class SearchButton(ImageButton):
"""
Search and download image button with personalized style sheet
"""
def __init__(self, size: int = 28, parent: QWidget = None):
super().__init__('search-download', size, size, parent)
... |
import struct
def dq(v):
return struct.pack("Q", v)
with open("payload", "wb") as f:
f.write("A" * 1032)
f.write(dq(0x400616))
|
from bifrostlib import common
from bifrostlib.datahandling import Sample
from bifrostlib.datahandling import SampleComponentReference
from bifrostlib.datahandling import SampleComponent
from bifrostlib.datahandling import Category
from typing import Dict
import os
import json
import re
def extract_cgmlst(chewbbaca: Ca... |
import warnings
warnings.filterwarnings("ignore")
# basic package
import os
import sys
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import bisect
# feature selection package
from sklearn.model_selection import train_test_split
from sklearn.model_selection import learnin... |
from argparse import ArgumentParser
from asreview import ASReviewData
from asreview.analysis import Analysis
from asreview.entry_points.base import BaseEntryPoint
class DifficultEntryPoint(BaseEntryPoint):
description = "Show the most difficult records."
def __init__(self):
super(DifficultEntryPoint... |
import string
from Bio.Seq import Seq
from Bio import SeqIO
filepath = "/home/prokriti/HumanALDH2.fasta"
filepath1 = "/home/prokriti/MutatedHumanALDH2.fasta"
filepath2 = "/home/prokriti/mutatedgreenopsin.fasta"
filepath3 = "/home/prokriti/greenopsin.fasta"
def read(filepath: str):
reads = list(SeqIO.parse(file... |
import unittest
from pyspark.sql.tests import ReusedSQLTestCase
class TreeReduceTestCase(ReusedSQLTestCase):
def test_treereduce(self):
words = ["Settlements", "some", "centuries", "old", "and", "still", "no", "bigger", "than", "pinheads", "on",
"the", "untouched", "expanse", "of", "their... |
for i in range(1, int(input())+1):
print(i, i**2, i**3)
print(i, i**2+1, i**3+1)
|
from setuptools import setup
import os
import torch
import sysconfig
from torch.utils.cpp_extension import BuildExtension, CppExtension, CUDAExtension
_DEBUG = False
_DEBUG_LEVEL = 0
# extra_compile_args = []
# extra_compile_args = sysconfig.get_config_var('CFLAGS').split()
# extra_compile_args.remove('-DNDEBUG')
# ex... |
# ============================================================================
# FILE: deol.py
# AUTHOR: Shougo Matsushita <Shougo.Matsu at gmail.com>
# License: MIT license
# ============================================================================
from denite.source.base import Base
from denite.kind.base import B... |
from lib.autoclicker.logger import get_logger
from PyQt6.QtWidgets import QHBoxLayout, QPushButton, QRadioButton, QLineEdit, QGroupBox
from PyQt6.QtGui import QIntValidator
from PyQt6.QtCore import pyqtSignal
from pynput.mouse import Button, Listener as mouseListener
Logger = get_logger(__name__)
class cursor_loca... |
"""
.. module:: sampler
:synopsis: Generic sampler
.. moduleauthor:: Benjamin Audren <benjamin.audren@epfl.ch>
.. moduleauthor:: Surhudm More <>
This module defines one key function, :func:`run`, that distributes the work to
the desired actual sampler (Metropolis Hastings, or Nested Sampling so far).
It also defi... |
import pkg_resources, json
from word2lex.utils.custom_vader import SentimentIntensityAnalyzer
ROOT_PATH = pkg_resources.resource_filename('word2lex', 'data/')
AVAILABLE_MODELS = ['britain',
'usa',
'canada',
'politics_en',
'news_media',
... |
"""Users views."""
# Django REST Framework
from rest_framework import mixins, status, viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
# Permissions
from rest_framework.permissions import (
AllowAny,
IsAuthenticated
)
from pmanagement.users.permissions imp... |
from abc import ABC, abstractmethod
from typing import List, Union
import cvxpy as cp
class CvxpyProblem(ABC):
@abstractmethod
def problem(self) -> cp.Problem:
pass
@abstractmethod
def parameters(self) -> List[cp.Parameter]:
pass
@abstractmethod
def variables(self) -> List[c... |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
Tests for stringmatching.py
"""
# Standard library imports
import os
# Test library imports
import pytest
# Local imports
from spyder.utils.stringmatching import get_search_scores
TEST_FILE = os.... |
from bs4 import BeautifulSoup
def parseFile(filename):
with open(filename, 'r') as f:
html_text = f.read()
soup = BeautifulSoup(html_text, 'html.parser')
words = []
for s in soup.find_all("span", {"class": "collapseomatic"}):
korean = s.previous_sibling.previous_sibling.text
e... |
# Copyright 2015 Futurewei. 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 appl... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from dppd import dppd
import pandas as pd
import pandas.testing
from plotnine.data import mtcars
__author__ = "Florian Finkernagel"
__copyright__ = "Florian Finkernagel"
__license__ = "mit"
assert_series_equal = pandas.testing.assert_series_equal
assert_frame_equal = pa... |
import tensorflow as tf
from numpy import pi
from keras.backend import sigmoid
from keras.models import Sequential, load_model
from keras.layers import Layer, InputLayer, Dense, Flatten, Activation, Conv2D, MaxPooling2D, LeakyReLU
from keras.callbacks import ModelCheckpoint, TensorBoard
from keras.optimizers import Ada... |
# Copyright 2016, FBPIC contributors
# Authors: Remi Lehe, Manuel Kirchen, Kevin Peters, Soeren Jalas
# License: 3-Clause-BSD-LBNL
"""
Fourier-Bessel Particle-In-Cell (FB-PIC) main file
It defines a set of generic functions for printing simulation information.
"""
import sys, time
from fbpic import __version__
from fbp... |
import unittest.mock
from programy.clients.config import ClientConfigurationData
from programy.clients.events.client import EventBotClient
from programytest.clients.arguments import MockArgumentParser
class MockEventBotClient(EventBotClient):
def __init__(self, id, argument_parser=None):
EventBotClient.... |
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
## load the data
train = pd.read_csv('../temporal_data/train_id.csv')
test = pd.read_csv('../temporal_data/test_id.csv')
song = pd.read_csv('../temporal_data/songs_id_cnt.csv')
data = train[['msno', 'song_id']].append(test[['msno',... |
#绑定用户有效期
BIND_USER_ACCESS_TOKEN_EXPIRES = 10*60 |
#!/usr/bin/env python
"""
This file enables the python-fire based commandline interface.
"""
from .module import RModule
from .package import RPackage
def rcli(path_module_or_package):
"""Commandline interface to R packages and functions in a file.
Examples:
---------
# with a package
rcli utils ... |
# -*- coding: utf-8 -*-
from .configuration import (
cutoff_config,
cutoff_config_ecoinvent_row,
consequential_config,
)
from .filesystem import (
cache_data,
OutputDir,
save_intermediate_result,
save_specific_dataset,
)
from .io import extract_directory
from .logger import create_log, creat... |
import json
from time import time
import pulumi
import pulumi_aws
from pulumi_aws import apigateway, lambda_, s3
model_bucket = s3.Bucket("modelBucket")
model_object = s3.BucketObject("model",
bucket=model_bucket,
# The model comes from the pretrained model referenced in https://github.com/pytorch/vision/blob/... |
#!/usr/bin/python
import json
import logging
import os
import sys
import threading
from datetime import datetime
from decimal import Decimal
from time import sleep
import boto3
import pytz
from botocore.exceptions import ClientError
logger = logging.getLogger(__name__)
BOTO3_METERING_MARKETPLACE_CLIENT = 'metering... |
import json
import math
import time
from typing import Union
import coinbasepro
from cbpa.logger import logger
from cbpa.schemas.account import AddFundsResponse
from cbpa.schemas.config import Config
from cbpa.schemas.currency import CCC, FCC
from cbpa.services.discord import DiscordService
class AccountService:
... |
'''
Author : Shreyak Upadhyay
Email : shreyakupadhyay07@gmail.com
Subject : get verified for target website .
Description:
send a get request to get verified for the target website.
'''
import logging
import requests
import re
import os
import sys
import time
from bs4 import BeautifulSoup
import json
logging.basicConf... |
from datetime import datetime
import os
import config.constants as constants
def resolve_survey_id_from_file_name(name):
return parse_filename(name)['survey_id']
#return name.rsplit("/", 2)[1]
def parse_filename(filename):
"""
Parse filename into dictionary that reflects different properties... |
from synapse.tests.common import *
import synapse.axon as s_axon
import synapse.cortex as s_cortex
import synapse.daemon as s_daemon
import synapse.neuron as s_neuron
import synapse.tools.pushfile as s_pushfile
nullhash = hashlib.sha256(b'').digest()
visihash = hashlib.sha256(b'visi').digest()
class TestPushFile(Sy... |
# -*- coding: utf-8 -*-
import shutil
from pathlib import Path
import pytest
import tempfile
from casperlabs_client import CasperLabsClient, key_holders
from casperlabs_client.consts import (
SUPPORTED_KEY_ALGORITHMS,
PUBLIC_KEY_FILENAME,
PRIVATE_KEY_FILENAME,
PUBLIC_KEY_HEX_FILENAME,
)
@pytest.fixtu... |
# -*- coding: utf-8 -*-
from ....Classes.OutMag import OutMag
from ....Classes.Simulation import Simulation
from ....Methods.Simulation.Input import InputError
def gen_input(self):
"""Generate the input for the structural module (magnetic output)
Parameters
----------
self : InFlux
An InFlux... |
from bs4 import BeautifulSoup
from dedoc.readers.docx_reader.data_structures.base_props import BaseProperties
def check_if_true(value: str) -> bool:
if value == '1' or value == 'True' or value == 'true':
return True
return False
def change_paragraph_properties(old_properties: BaseProperties, tree: ... |
# Generated by Django 3.0.5 on 2021-01-27 14:35
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Visitor',
fields=[
('id', models.AutoField(... |
"""
Usage:
github-commit-status -c <commit-hash> -s <status> -u <github-username> -p <github-password> -r <github_repo> --url <URL> --context <context> -d "<description>"
github-commit-status -c <commit-hash> -s <status> -t <github-token> -r <github_repo> --url <URL> --context <context> -d "<description>"
Opti... |
import os
import joblib
import numpy as np
from rlkit.samplers.util import rollout
files = dict(
reach_left=(
'/home/vitchyr/git/rllab-rail/railrl/data/s3/09-14-pusher-3dof-reacher-naf-yolo-left/09-14_pusher-3dof-reacher-naf-yolo_left_2017_09_14_17_52_45_0010/params.pkl'
),
reach_right=(
... |
import numpy as np
from tensorflow.python.keras.models import Model
from tensorflow.python.keras.layers import Dense
from tensorflow.python.keras import backend as K
import tensorflow as tf
from keras.applications.mobilenet_v2 import MobileNetV2
#from keras.models import load_model
# target model
base_model = Mobil... |
"""Translation using local data given at initialization."""
from rics.translation.offline._format import Format
from rics.translation.offline._format_applier import DefaultFormatApplier, FormatApplier
from rics.translation.offline._magic_dict import MagicDict
from rics.translation.offline._placeholder_overrides import ... |
# -*- coding:utf-8 -*-
# author: Cone
# datetime: 2020-01-10 17:09
# software: PyCharm
def singleton(cls):
_instance = {}
def inner():
if cls not in _instance:
_instance[cls] = cls()
return _instance[cls]
return inner
class Singleton(object):
def __init__(self, cls):
... |
from distutils.core import setup
try:
from setuptools import setup
except:
pass
setup(
name = "kiss.py",
version = "1.0.0",
author = "Stanislav Feldman",
description = ("MVC web framework in Python with Gevent, Jinja2, Werkzeug"),
url = "http://stanislavfeldman.github.com/kiss.py/",
keywords ... |
__author__ = 'thorsteinn'
from dnv_exchange.input_files.dbDNV1 import db as db1
from dnv_exchange.input_files.dbDNV2 import db as db2
from dnv_exchange.input_files.dbDNV3 import db as db3
from dnv_exchange.input_files.dbDNV4 import db as db4
from dnv_exchange.input_files.dbDNV5 import db as db5
from dnv_exchange.input... |
# Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All contributing project au... |
# -*- coding: utf-8 -*-
from odoo import models, fields
class AccountMove(models.Model):
_inherit = 'account.move'
repair_ids = fields.One2many('repair.order', 'invoice_id', readonly=True, copy=False)
def unlink(self):
repairs = self.sudo().repair_ids.filtered(lambda repair: repair.state != 'ca... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.