content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
# -*- coding: utf-8 -*-
""" Helper for uploading file, takes care of chunking file, create the file schema. """
__author__ = 'Thomas Sileo (thomas@trucsdedev.com)'
import logging
import os
from concurrent import futures
import camlipy
from camlipy.rollsum import Rollsum
from camlipy.schema import Bytes, File
MAX... | python |
# Generated by Django 2.0 on 2017-12-30 16:08
from django.conf import settings
from django.db import migrations, models
import apps.web.validators
class Migration(migrations.Migration):
dependencies = [
('web', '0001_initial'),
]
operations = [
migrations.RemoveField(
model... | python |
"""Generate masks from sum of flurophore channels"""
import os
import pandas as pd
import micro_dl.utils.aux_utils as aux_utils
from micro_dl.utils.mp_utils import mp_create_save_mask
from skimage.filters import threshold_otsu
class MaskProcessor:
"""Generate masks from channels"""
def __init__(self,
... | python |
# Testing
from django.test import TestCase, Client
from django.test.utils import override_settings
# APP Models
from seshdash.models import Sesh_Alert, Alert_Rule, Sesh_Site,VRM_Account, BoM_Data_Point as Data_Point, Daily_Data_Point, Sesh_User
# django Time related
from django.utils import timezone
from time import ... | python |
# Created by Gorkem Polat at 10.02.2021
# contact: polatgorkem@gmail.com
import os
import glob
import json
import shutil
import cv2
import numpy as np
import random
import matplotlib.pyplot as plt
from tqdm import tqdm
def show_image(image):
plt.imshow(image)
plt.show()
def show_image_opencv(image):
if... | python |
import importlib
import imp
import sys
class SettingsWrapper(object):
'''
Wrapper for loading settings files and merging them with overrides
'''
my_settings = {}
ignore = [
'__builtins__',
'__file__',
'__package__',
'__doc__',
'__name__',
]
def _in... | python |
"""
Frame assertion setting.
"""
class Ac:
"""
Set assertion constant.
Const:
eq: Assertion is equal.
nq: Assert inequality.
at: Assertion is True.
af: Assertion is False.
als: Assert a is b.
alst: Assert a is not b.
an: Assertion is None.
an... | python |
from pwn import *
sh = ssh(user='ctf', host='node3.buuoj.cn', port=25102, password='guest', level='debug')
sh.interactive() | python |
# Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hp.com>
#
# 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/L... | python |
import unittest
from elasticsearch import ElasticsearchException
from elasticbatch.exceptions import ElasticBufferFlushError
class TestElasticBufferFlushError(unittest.TestCase):
def test_str(self):
class TestCase:
def __init__(self, msg, err, verbose, expected_str):
self.m... | python |
from domain import Material
from collections import namedtuple
from random import randint
_State = namedtuple('_State', 'player_spawn, world_map, links, players')
def initial_state(player_spawn, world_map, links):
return _State(player_spawn, world_map, links, {})
def handle_command(state, command_name, input_data... | python |
# EXPERIMENTAL: all may be removed soon
from gym.benchmarks import scoring
from gym.benchmarks.registration import benchmark_spec, register_benchmark, registry, register_benchmark_view # imports used elsewhere
register_benchmark(
id='Atari200M',
scorer=scoring.TotalReward(),
name='Atari200M',
view_gr... | python |
#coding: utf-8
from __future__ import division, absolute_import, print_function, unicode_literals
from kasaya.core import exceptions
import msgpack
#
# Warning, msgpack is broken and can't differentiate strings from binary data.
# Under python 3 message pack is unusable to transport data.
#
# More details and useles... | python |
from RPIO import PWM
from sys import stdin,stdout
pin=18
PWM.setup()
PWM.init_channel(13)
PWM.add_channel_pulse(13, pin ,0,0)
while True:
userinput = stdin.readline().rstrip('\n')
if userinput == 'quit':
break
else:
stdout.write("LightValue: " + userinput)
PWM.clear_channel_gpio(13, pin)
PWM.add_channel_p... | python |
import flask
import pickle
import praw
import nltk
nltk.download("stopwords")
nltk.download("punkt")
from nltk.corpus import stopwords
import contractions
import inflect
import pandas as pd
import json
def clean(t):
en_stops = set(stopwords.words('english'))
t_old = str(t)
t_old = t_old.translate({ord(... | python |
"""
Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же, но с прописной
первой буквой. Например, print(int_func(‘text’)) -> Text.
Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом. Каждое слово состоит
из латинских букв в ниж... | python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Distributed under terms of the MIT license.
import os
import datetime
import json
import numpy as np
from numpy.linalg import norm
import math
import argparse
from platt import *
from sklearn.metrics import f1_score
import time
import scipy.stats
from ... | python |
import pandas as pd
import time
import json
from collections import OrderedDict
class RunManager():
def __init__(self):
""" Class constructor """
self.epoch_count = 0
self.epoch_loss = 0
self.epoch_num_correct = 0
self.epoch_start_time = None
self.run_params = None... | python |
__author__ = 'David Moser <david.moser@bitmovin.net>'
from unittest import TestSuite
from .testcase_create_delete_live_stream import CreateLiveStreamTestCase
def get_test_suite():
test_suite = TestSuite()
test_suite.addTest(CreateLiveStreamTestCase())
return test_suite
| python |
#
# PySNMP MIB module Dlink-IMPB-MNG (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Dlink-IMPB-MNG
# Produced by pysmi-0.3.4 at Wed May 1 12:58:21 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | python |
#GAE modules
import webapp2
from google.appengine.ext.webapp import template
from google.appengine.ext import ndb
#Application specific Modules
from ExtraModules.gettemplate import gettemplate
from ExtraModules import phonenumbers
from model import Messages
def checkPhoneNumber(number, country_code):
try:
... | python |
from mcpi.minecraft import Minecraft
mc = Minecraft.create()
mc.postToChat("Hello, Minecraft World") | python |
"""
You should not make an instance of the Client class yourself, rather you should listen for new connections with
:meth:`~websocket.server.WebSocketServer.connection`
>>> @socket.connection
>>> async def on_connection(client: Client):
... # Here you can use the client, register callbacks on it or send it messag... | python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui_log_viewer.ui'
#
# Created by: PyQt5 UI code generator 5.7
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObj... | python |
import requests
import json
import re
ig_url = 'https://instagram.com'
ig_username = 'thephotoadventure'
query_url = f'{ig_url}/graphql/query'
all_user_posts = []
r = requests.get(f'{ig_url}/{ig_username}/?__a=1')
all_data = r.json()
user_data = all_data['graphql']['user']
user_posts = user_data['edge_owner_to_timel... | python |
#!/usr/bin/env python3
import os
import sys
if __name__ == '__main__':
section, foil, cap = None, None, 9999999
if len(sys.argv) == 3:
section, foil = sys.argv[2], sys.argv[1]
elif len(sys.argv) == 4:
section, foil, cap = sys.argv[2], sys.argv[1], int(sys.argv[3])
else: # len(sys.argv... | python |
import sys
if len(sys.argv) != 3:
sys.exit("Wrong argument. getSeq.py <.fasta> <seqID>")
targetid = str(sys.argv[2])
# Flag
seq2print = False
with open(sys.argv[1], "r") as f:
for line in f:
if not seq2print:
if line.startswith(">"):
#print(line.lstrip(">"))
if line.rstrip().lstrip(">") == targetid:
... | python |
# uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: type_Params.py
from types import *
import mcl.object.MclTime
PARAMS_QUERY_TYPE_ALL = 0
PARAMS_QUERY_TYPE_IP_ONLY = 1
PARAMS_QUERY_TYPE_TCP_ONLY = 2
P... | python |
from typing import Any, Dict
from . import State
from app import app
from models import User
class AssetState(State[User]):
def __init__(self) -> None:
super().__init__()
self.pending_file_upload_cache: Dict[str, Any] = {}
def get_user(self, sid: str) -> User:
return self._sid_map[si... | python |
from .dijkstras_algorithm import DijkstraNode, DijkstraEdge, DijkstraGraph
from .a_star import AStarNode, AStarEdge, AStarGraph
from .custom_dijkstras_algorithm import CDijkstraNode, CDijkstraEdge, CDijkstraGraph | python |
from .test_case import TestCase
from infi.unittest.parameters import iterate
class IsolatedPythonVersion(TestCase):
def test(self):
with self.temporary_directory_context():
self.projector("repository init a.b.c none short long")
self.projector("isolated-python python-version get")
... | python |
import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import xml
from xml.dom.minidom import parse, parseString
def send_email(to, server, subj, body, attachments... | python |
#!/usr/bin/python
import time,serial,math,sys,numpy as np,matplotlib.pyplot as plt
print '*** Graf periode pulzarja - 11.05.2017 ***'
povpstolp=20 #stevilo povprecenj stolpcev (integer)
perioda=7145.117 #perioda pulzarja v stevilu vzorcev (float)
odmik=1000 #odmik zacetka (integer) 0<odmik=<perioda
zacetek=8000 #za... | python |
from django.contrib import admin
from .models import *
from django import forms
from ckeditor_uploader.widgets import CKEditorUploadingWidget
class ServiceAdmin(admin.ModelAdmin):
list_display = ['title','status']
class CategoryAdmin(admin.ModelAdmin):
list_display = ['title','parent','slug']
class BrandAdmi... | python |
"""
FIFO
Queue = []
Queue = [1,2,3,4] push
[2,3,4] pop
[3,4] pop
[4] pop
[] pop
empty stack
"""
class Queue(object):
def __init__(self):
self.queue = []
self.length = 0
def enque(self, data):
self.queue.append(data)
self.length += 1
def deque(self):
if self.lengt... | python |
def test_canary():
assert True
| python |
import numpy as np
import random
import sys
from scipy.stats import f
from scipy.stats import norm
param= int(sys.argv[1])
np.random.seed(param)
n=500 # mediciones efectuadas
p=100 # variables medidas
mu=0.0
sigma=1.0
X=np.random.normal(mu,sigma,size=(n,p))
Y=np.random.normal(mu,sigma,size=(n,1))
XT=X.T
YT=Y.T
Inv=np... | python |
# Permission mixins to override default django-guardian behaviour
from guardian.mixins import PermissionRequiredMixin
class SetChildPermissionObjectMixin:
"""
Sets child object as the focus of the permission check in the view.
"""
def get_permission_object(self):
return self.child
class Perm... | python |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... | python |
import pandas as pd
import numpy as np
from ttk.corpus.CategorizedDatedCorpusReader import CategorizedDatedCorpusReader
class CategorizedDatedCorpusReporter(object):
""" Reporting utility for CategorizedDatedCorpusReporter corpora. """
def __init__(self):
self._output_formats = ['list', 'str', 'datafr... | python |
import os
import math
import sys
import datetime
import re
import numpy as np
import traceback
import pprint
import json
from rafiki.model import BaseModel, InvalidModelParamsException, test_model_class
from rafiki.constants import TaskType
# Min numeric value
MIN_VALUE = -9999999999
class BigramHmm(BaseModel):
... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 26 09:03:17 2022
@author: apauron
"""
import os
import get_files_cluster
import pandas as pd
from numpy import genfromtxt
### Get the parent folder of the working directory. Change it if you modify the name of the folders
path_parent = os.path.dirn... | python |
# Exercice 3.3 : Nombres premiers
## Question 1
def divise(n : int, p : int) -> bool:
"""Précondition : n > 0 et p >= 0
Renvoie True si et seulement si n divise p.
"""
return p % n == 0
# Jeu de tests
assert divise(1, 4) == True
assert divise(2, 4) == True
assert divise(3, 4) == False
assert di... | python |
import os
import re
import subprocess
import time
import urllib
import glanceclient
import keystoneauth1
import keystoneauth1.identity.v2 as keystoneauth1_v2
import keystoneauth1.session as keystoneauth1_session
import keystoneclient.v2_0.client as keystoneclient_v2
import keystoneclient.v3.client as keystoneclient_v3... | python |
# -*- coding: utf-8 -*-
from flask import Flask, abort
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from config import basedir, UPLOAD_FOLDER
#from flask.ext.mail import Mail
theapp = Flask(__name__)
theapp.config.from_object('config')
#mail = Mail(theapp)
bootstrap = Bootstrap(theapp... | python |
import Sofa
import SofaPython.Tools
import SofaTest
def createScene(node):
node.createObject('PythonScriptController', filename=__file__, classname='VerifController')
class VerifController(SofaTest.Controller):
def initGraph(self, node):
Sofa.msg_info("initGraph ENTER")
child = node.crea... | python |
"""
This application demonstrates how to create a Tag Template in Data Catalog,
loading its information from Google Sheets.
"""
import argparse
import logging
import re
import stringcase
import unicodedata
from google.api_core import exceptions
from google.cloud import datacatalog
from googleapiclient import discovery... | python |
import cloudpassage
import sys
import os
import pytest
import datetime
import time
import platform
sys.path.append(os.path.join(os.path.dirname(__file__), '../../', ''))
import lib.validate as validate
class TestUnitValidate:
def test_validate_valid_time(self):
accepted = True
try:
val... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Evolve life in a landscape.
Life evolves alongside landscapes by biotic and abiotic processes under complex
dynamics at Earth's surface. Researchers who wish to explore these dynamics can
use this component as a tool for them to build landscape-life evolution models.
La... | python |
import math
import timeit
import random
import sympy
import warnings
from random import randint, seed
import sys
from ecpy.curves import Curve,Point
from Crypto.Hash import SHA3_256, SHA256, HMAC
import requests
from Crypto.Cipher import AES
from Crypto import Random
from Crypto.Util.Padding import pad
from Crypto.Util... | python |
from singly_linked_lists.remove_nth_node_from_list import remove_nth_from_end
from data_structures.singly_linked_list_node import SinglyLinkedListNode
def test_remove_nth_from_end():
head = SinglyLinkedListNode(1)
assert remove_nth_from_end(head, 1) is None
head = SinglyLinkedListNode(1)
head.next = ... | python |
# Copyright (c) 2009 Alexandre Quessy, Arjan Scherpenisse
# See LICENSE for details.
"""
Tests for txosc/osc.py
Maintainer: Arjan Scherpenisse
"""
from twisted.trial import unittest
from twisted.internet import reactor, defer, task
from txosc import osc
from txosc import async
from txosc import dispatch
class TestG... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2017 jem@seethis.link
# Licensed under the MIT license (http://opensource.org/licenses/MIT)
from __future__ import absolute_import, division, print_function, unicode_literals
import yaml
import struct
import hexdump
import math
import re
import time
import os
... | python |
# This file adds code completion to the auto-generated pressuresense_pb2 file.
from .pressuresense_pb2 import PressureQuanta, PressureLog
from .common_proto import _TimeStamp
from typing import List, Callable, Union
class _PressureProfile( object ):
mpa = 0
class _PressureQuanta( object ):
profiles = _Press... | python |
import sys
import logging
import argparse
from pprint import pprint
from . import *
def dumpSubject(cert):
info = getSubjectFromCertFile(cert)
pprint(info, indent=2)
def main():
services = ",".join(LOGIN_SERVICE.keys())
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDe... | python |
'''
knowyourmeme.com image crawler:
-------------------------------------------
Script designed to specifically crawl meme templates to be used in ml(and self enjoyment).
url: https://knowyourmeme.com/photos/templates/page/<page_number>
So, as you can see, we are lucky enough that knowyoumeme has pagination here
IMP... | python |
# Generated by Django 2.2.1 on 2019-06-03 04:58
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('Profesor', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Estu... | python |
import sys
sys.path.append(".")
import numpy as np
from DDPG import *
from main import *
import os.path
import argparse
from Environment import Environment
from shield import Shield
def carplatoon(learning_method, number_of_rollouts, simulation_steps, learning_eposides, actor_structure, critic_structure, train_dir,... | python |
#!/usr/bin/python3
#
# Scratchpad for working with raw U2F messages, useful for creating raw messages as test data.
# Example keys from secion 8.2 of
# https://fidoalliance.org/specs/fido-u2f-v1.0-nfc-bt-amendment-20150514/fido-u2f-raw-message-formats.html#authentication-response-message-success
from binascii import h... | python |
# encoding: utf-8
from workflow import web, Workflow, PasswordNotFound
def get_saved_searches(api_key, url):
"""
Parse all pages of projects
:return: list
"""
return get_saved_searches_page(api_key, url, 1, [])
def get_dashboards(api_key, url):
"""
Parse all pages of projects
:return:... | python |
##############################################################################
# Written by: Cachen Chen <cachen@novell.com>
# Date: 08/05/2008
# Description: hscrollbar.py wrapper script
# Used by the hscrollbar-*.py tests
##########################################################################... | python |
from dotenv import load_dotenv
import os
load_dotenv(verbose=True)
DISCORD_BOT_TOKEN = os.getenv('DISCORD_BOT_TOKEN') | python |
# Time: O(log n)
# Space: O(n) Call stack size
class Solution:
def searchRange(self, nums, target):
first = self.binarySearch(nums, 0, len(nums) - 1, target, True)
last = self.binarySearch(nums, 0, len(nums) - 1, target, False)
return [first, last]
def binarySearch(self, nu... | python |
# -*- coding: utf-8 -*-
# import model interface
from . import models
# import constraints
from . import constraints
# import tasks
from . import tasks
# import solvers
from . import solvers
| python |
import csv
from django.db import models
import reversion
from django.core.exceptions import ObjectDoesNotExist
@reversion.register()
class FileTemplate(models.Model):
FILE_FOR_CHOICES = (
('input', 'Input'),
('equip', 'Equipment'),
('output', 'Output'),
)
name = models.CharField(... | python |
import daisy
import unittest
class TestMetaCollection(unittest.TestCase):
def get_mongo_graph_provider(self, mode, directed, total_roi):
return daisy.persistence.MongoDbGraphProvider(
'test_daisy_graph',
directed=directed,
total_roi=total_roi,
mode=mode)
... | python |
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 29 08:40:49 2018
@author: user
"""
import numpy as np
np.random.seed(1)
from matplotlib import pyplot as plt
import skimage.data
from skimage.color import rgb2gray
from skimage.filters import threshold_mean
from skimage.transform import resize
import network
# Utils
def... | python |
def main() -> None:
N, K = map(int, input().split())
assert 1 <= K <= N <= 100
for _ in range(N):
P_i = tuple(map(int, input().split()))
assert len(P_i) == 3
assert all(0 <= P_ij <= 300 for P_ij in P_i)
if __name__ == '__main__':
main()
| python |
# -*- coding: UTF-8 -*-
import sys,io,os
from mitie import *
from collections import defaultdict
reload(sys)
sys.setdefaultencoding('utf-8')
#此代码参考:https://nlu.rasa.com/python.html
#这个代码是为了测试,直接通过python api去获取rasa nlu的意图和实体识别接口
sys.path.append('../MITIE/mitielib')
from rasa_nlu.model import Metadata, Interpreter
... | python |
from tir import Webapp
import unittest
class GTPA107(unittest.TestCase):
@classmethod
def setUpClass(inst):
inst.oHelper = Webapp()
inst.oHelper.Setup("SIGAGTP", "20/04/2020", "T1", "D MG 01 ")
inst.oHelper.Program('GTPA107')
def test_GTPA107_CT001(self):
self.oHelper.SearchBrowse("D MG 000033", "Filia... | python |
#!/usr/bin/env python
import unittest
import os
import time
from bones.utils import *
class TestUtils(unittest.TestCase):
def test_temp_filename_collision(self):
fn1 = temp_filename()
fn2 = temp_filename()
self.assertNotEqual(fn1, fn2)
def test_temp_filename_kwargs(self):
fn =... | python |
from django.http import HttpRequest
from django.test import Client
from django.test import TestCase
from django.urls import reverse
from project_core.tests import database_population
class CallListTest(TestCase):
def setUp(self):
self._user = database_population.create_management_user()
self._fun... | python |
from .base import Base
class Ls(Base):
"""Show List"""
def run(self):
if self.options['<ctgr>'] == "done":
self.show(None, 1)
elif self.options['<ctgr>'] == "all":
self.show(None, None)
else:
self.show(self.options['<ctgr>'],1 if self.options['<done... | python |
import io
import os
import sys
from setuptools import setup
if sys.version_info < (3, 6):
sys.exit('Sorry, Python < 3.6.0 is not supported')
DESCRIPTION = 'Images Generator for bouncing objects movie'
here = os.path.abspath(os.path.dirname(__file__))
try:
with io.open(os.path.join(here, 'README.md'), encodin... | python |
import os
from tqdm import tqdm
from PIL import Image, UnidentifiedImageError
if __name__ == '__main__':
jpg_path = '../shufa_pic/shufa'
broken_jpg_path = '../shufa_pic/broken_img'
for jpg_file in tqdm(os.listdir(jpg_path)):
src = os.path.join(jpg_path, jpg_file)
try:
image = Im... | python |
#!/usr/bin/env python
# this just calculates the roots, it doesn't generate the heat map
# see https://thoughtstreams.io/jtauber/littlewood-fractals/
import itertools
import sys
import time
import numpy
DEGREE = 16
INNER_ONLY = False
print "generating roots for degree={}".format(DEGREE,)
start = time.time()
c... | python |
from aiohttp.test_utils import TestClient
from server.serializer import JSendSchema, JSendStatus
from server.serializer.fields import Many
from server.serializer.models import RentalSchema
class TestRentalsView:
async def test_get_rentals(self, client: TestClient, random_admin, random_bike):
"""Assert t... | python |
# 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.
"""Timer."""
import time
class Timer(object):
"""A simple timer (adapted from Detectron)."""
def __init__(self):
self.tota... | python |
#!/usr/bin/env python
import optparse
import os,sys
#from optparse import OptionParser
import glob
import subprocess
import linecache
import struct
import shutil
def setupParserOptions():
parser = optparse.OptionParser()
parser.set_usage("%prog -f <stack> -p <parameter> -c <ctf> -s")
parser.add_option("-f",dest="s... | python |
from itertools import cycle
from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.cache import cache
from django.http import Http404
from django.shortcuts import render
from django.views.generic import TemplateView
from django.views.generic.base import View
import... | python |
node = S(input, "application/json")
object = {
"name": "test",
"comment": "42!"
}
node.prop("comment", object)
propertyNode = node.prop("comment")
value = propertyNode.prop("comment").stringValue() | python |
# -*- coding: utf-8 -*-
"""Example Google style docstrings.
This module demonstrates documentation as specified by the `Google Python
Style Guide`_. Docstrings may extend over multiple lines. Sections are created
with a section header and a colon followed by a block of indented text.
Example:
Examples can be give... | python |
__author__ = "Nathan Ward"
import logging
from datetime import date, datetime
from pytz import timezone, utc
_LOGGER = logging.getLogger()
_LOGGER.setLevel(logging.INFO)
def get_market_open_close() -> dict:
"""
Grab the market open and close settings. Convert timezone.
Lambdas run in UTC. Settings are s... | python |
# -*- coding: utf-8 -*-
#---------------------------------------
# Import Libraries
#---------------------------------------
import sys
import io
import json
from os.path import isfile
import clr
clr.AddReference("IronPython.SQLite.dll")
clr.AddReference("IronPython.Modules.dll")
from datetime import datetime
#-------... | python |
import unittest
import sys
module = sys.argv[-1].split(".py")[0]
class PublicTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
global top_3
undertest = __import__(module)
top_3 = getattr(undertest, 'top_3', None)
def test_exemplo(self):
l = [1,2,3,4,8,22,-3,5]
... | python |
import datetime
from .wordpress import WordPress
class CclawTranslations(WordPress):
base_urls = [
"https://cclawtranslations.home.blog/",
]
last_updated = datetime.date(2021, 11, 3)
def init(self):
self.blacklist_patterns += ["CONTENIDO | SIGUIENTE"]
def parse_content(self, el... | python |
from discord.ext import commands
class Echo(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def echo(self, ctx):
await ctx.send(ctx.message.content[6:])
def setup(bot):
bot.add_cog(Echo(bot))
| python |
import json
import logging
from . import BASE
from .oauth import Tokens
logger = logging.getLogger(__name__)
def store(client_id: str, tokens: Tokens) -> None:
cache = BASE / f"{client_id}_cache.json"
# Store tokens
cache.touch(0o600, exist_ok=True)
with cache.open("w") as fh:
temp = {k: v ... | python |
from .model import TreeNode
"""
BFS Solution
Space : O(n)
Time : O(n)
"""
class Solution:
def pseudoPalindromicPaths(self, root: TreeNode) -> int:
if not root:
return 0
stack = [(root, [])]
res = []
ans = 0
while stack:
node, mem = stack.pop()... | python |
import sys, os
from MySQLdb import Error as Error
from connect_db import read_connection
class ReaderBase(object):
def __init__(self):
self._password_file = "/n/home00/cadams/mysqldb"
def connect(self):
return read_connection(self._password_file) | python |
"""Geometric Brownian motion."""
import numpy as np
from stochastic.processes.base import BaseTimeProcess
from stochastic.processes.continuous.brownian_motion import BrownianMotion
from stochastic.utils import generate_times
from stochastic.utils.validation import check_numeric
from stochastic.utils.validation import ... | python |
#-----------------------------------------------------
# Make plots from matplotlib using data exported by
# DNSS.jl
# Soham M 05/2022
#-----------------------------------------------------
import numpy as np
import glob
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator... | python |
import os
import torch
from torchinfo import summary
from torch.utils.data import DataLoader
import source.utils as utils
import source.arguments as arguments
from source.model import FusionNet, UNet
from source.dataset.dataset import NucleiCellDataset
def main(m_args):
# For reproducibility
torch.manual_see... | python |
"""Objects representing regions in space."""
import math
import random
import itertools
import numpy
import scipy.spatial
import shapely.geometry
import shapely.ops
from scenic.core.distributions import Samplable, RejectionException, needsSampling
from scenic.core.lazy_eval import valueInContext
from scenic.core.vec... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Tests for C++ module twiss.
"""
import os
import IBSLib as ibslib
import numpy as np
import pandas as pd
import pytest
constants = [
(ibslib.clight, 299792458.0),
(ibslib.hbarGeV, 6.582119569e-25),
(ibslib.electron_mass, 0.51099895000e-3),
(ibslib.pr... | python |
import attr
from typing import Any, List, Optional
from tokopedia import TokopediaResponse
@attr.dataclass(slots=True)
class ActiveProductsShop:
id: int
name: str
uri: str
location: str
@attr.dataclass(slots=True)
class ActiveProductShop:
id: int
name: str
url: str
is_gold: bool
... | python |
"""Tests for the models of the ``media_library`` app."""
from django.test import TestCase
from user_media.models import UserMediaImage
from user_media.tests.factories import UserMediaImageFactory
from . import factories
class MediaLibraryTestCase(TestCase):
"""Tests for the ``MediaLibrary`` model class."""
... | python |
from slack import WebClient
class SlackApiWrapper(WebClient):
def __init__(self, api_token):
super().__init__(api_token)
def post_message(self, channel, message):
response = self.chat_postMessage(
channel=channel,
text=message)
assert response["ok"]
def po... | python |
from sys import stdin, stdout
num_cases = int(stdin.readline())
stdin.readline()
for case in range(num_cases):
n = int(stdin.readline().strip()) # num_candidates
candidates = []
for i in range(n):
candidates.append(stdin.readline().strip())
votes = []
line = stdin.readline().strip()
while line... | python |
from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CppExtension
setup(
name='syncbn_cpu',
ext_modules=[
CppExtension('syncbn_cpu', [
'operator.cpp',
'syncbn_cpu.cpp',
]),
],
cmdclass={
'build_ext': BuildExtension
})... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.