code stringlengths 1 199k |
|---|
import gdb
import pwndbg.abi
import pwndbg.arch
import pwndbg.events
import pwndbg.memory
import pwndbg.regs
argc = None
argv = None
envp = None
envc = None
@pwndbg.events.start
@pwndbg.abi.LinuxOnly()
def update():
global argc
global argv
global envp
global envc
pwndbg.arch.update() # :-(
sp = ... |
from datetime import datetime
from django.core.exceptions import ObjectDoesNotExist
from functools import update_wrapper
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib import admin
from django.db import models
import reversion
from django.core.urlresolvers import reverse
from .models imp... |
from django.apps import AppConfig
class LoginappConfig(AppConfig):
name = 'loginapp' |
import array
import os
import struct
from fcntl import ioctl
from typing import NoReturn
print('Available devices:')
for fn in os.listdir('/dev/input'):
if fn.startswith('js'):
print(f' /dev/input/{fn}')
axis_states = {}
button_states = {}
axis_names = {
0x00 : 'x',
0x01 : 'y',
0x02 : 'z',
... |
from . import fast_ffts
import numpy as np
from . import scale
from matplotlib import docstring
def zoom1d(inp, usfac=1, outsize=None, offset=0, nthreads=1,
use_numpy_fft=False, return_xouts=False, return_real=True):
"""
Zoom in to the center of a 1D array using Fourier upsampling
Parameters
---... |
import os
import subprocess
import sys
fullname = sys.argv[1]
path, name = os.path.split(fullname)
subprocess.check_call(["exec/gonex/gonex", fullname + "x"] + sys.argv[2:]) |
import unittest
from declarativeunittest import raises, atmostone, alldifferent
from construct.lib.py3compat import *
class TestPy3compat(unittest.TestCase):
def test_version(self):
assert atmostone(PY2, PY3)
assert atmostone(PY27, PY32, PY33, PY34, PY35, PY36)
def test_int_byte(self):
a... |
from nose.tools import ok_
from nose.tools import eq_
import os
from py_utilities.context_managers import cd
import tempfile
import unittest
class TestContextManagers(unittest.TestCase):
def setUp(self):
self.temp_dir = tempfile.gettempdir()
def test_cd(self):
curr = os.getcwd()
path = o... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.manager
class Migration(migrations.Migration):
dependencies = [
('health', '0001_initial'),
]
operations = [
migrations.AlterModelManagers(
name='directory',
manag... |
"""
基础配置文件
"""
DEBUG = False
CONNECT_TIMEOUT = 10
REQUEST_TIMEOUT = 10 |
from functools import reduce
def arrayPacking(a):
return reduce(lambda x, y: x << 8 | y, a[::-1], 0) |
from wepay.calls.base import Call
class App(Call):
""" The /app API calls """
call_name = 'app'
def __call__(self, client_id, client_secret, **kwargs):
"""Call documentation: `/app
<https://www.wepay.com/developer/reference/app#lookup>`_, plus extra
keyword parameter:
:keywor... |
import urllib.request as request
from urllib.error import URLError
from datetime import datetime, timezone, timedelta
from bs4 import BeautifulSoup
from .base_scraper import Scraper
class TrendAz(Scraper):
def __init__(self):
super().__init__(__name__)
self.url = 'http://georgiatoday.ge/en/news'
... |
import scrapy
from existentialcomics.items import ExistentialcomicsItem
from datetime import datetime
from base import BaseSpider
class DilbertSpider(BaseSpider):
name = "dilbert"
allowed_domains = ["dilbert.com"]
start_urls = [
"http://dilbert.com"
]
def parse(self, response):
url =... |
from bot_app.messages import *
from bot_app.value_types import *
import bot_app.data as data
import bot_app.settings as settings
from telegram.ext.dispatcher import run_async
class Setting:
def __init__(self, name, valid_values, help_message):
self.name = name
self.value = str(settings.settings_defa... |
from django.db import migrations, models
import multiselectfield.db.fields
class Migration(migrations.Migration):
dependencies = [
('proposals', '0001_initial_squashed_0003_remove_under_represented_questions'),
]
operations = [
migrations.AddField(
model_name='proposal',
... |
"""Model and Property classes and associated stuff.
A model class represents the structure of entities stored in the
datastore. Applications define model classes to indicate the
structure of their entities, then instantiate those model classes
to create entities.
All model classes must inherit (directly or indirectly)... |
from django import forms
from konfera.models import Speaker, Talk, Ticket, Receipt
class ReceiptForm(forms.ModelForm):
required_css_class = 'required'
class Meta:
model = Receipt
exclude = ['order', 'amount']
class SpeakerForm(forms.ModelForm):
required_css_class = 'required'
class Meta:... |
DOCUMENTATION = '''
---
module: kolla_container_facts
short_description: Module for collecting Docker container facts
description:
- A module targeting at collecting Docker container facts. It is used for
detecting whether the container is running on host in Kolla.
options:
api_version:
description:
-... |
from __future__ import print_function
from PIL import Image
import argparse
def process_arguments():
parser = argparse.ArgumentParser(description="Outlier Detection Utility",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("-i", "--infile", type=argpars... |
from dumbyaml.exceptions import InvalidYAMLTypeConversion
from dumbyaml.exceptions import InvalidYAMLTypeComparison
import re
FLOAT_REGEXP = re.compile(r"^(\-|\+)?[0-9]+(\.[0-9]*)?$")
INT_REGEXP = re.compile("^(\-|\+)?[0-9]+$")
class YAMLNode(object):
"""Representation of a YAML node."""
def __init__(self, item... |
"""
Swaggy Jenkins
Jenkins API clients generated from Swagger / Open API specification # noqa: E501
The version of the OpenAPI document: 1.1.2-pre.0
Contact: blah@cliffano.com
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
import typing # noqa: F4... |
from tests.commands.execution.utils import get_execution_data_mock
from tests.fixture_data import EXECUTION_DATA, PROJECT_DATA
from valohai_cli.commands.execution.info import info
def test_execution_info(runner, logged_in_and_linked):
with get_execution_data_mock():
output = runner.invoke(info, [str(EXECUTI... |
import itertools
def erat2():
D = {}
yield 2
for q in itertools.islice(itertools.count(3), 0, None, 2):
p = D.pop(q, None)
if p is None:
D[q * q] = q
yield q
else:
x = p + q
while x in D or not (x & 1):
x += p
... |
menu = {}
menu['1']="Shells"
menu['2']="Exploits"
menu['3']="Scanners"
menu['4']="Payloads"
menu['5']="Scripts"
menu['6']="Utilities"
while True:
print ""
print "==============Offensive Cyber Tools================="
print ""
options=menu.keys()
... |
import pyglet
from pyglet.window import key
from vecrec import Vector
from math import pi
from branch import Branch
def print_instructions():
def print_key_pair(increase_key, decrease_key, value):
print(increase_key, ": Increase ", value, ".", sep="")
print(decrease_key, ": Decrease ", value, ".", s... |
from pylab import axis, draw, close, gcf, gca
def zoom(event):
ax = gca()
cur_xlim = ax.get_xlim()
cur_ylim = ax.get_ylim()
# edit the scale if needed
base_scale = 1.1
xdata = event.xdata # get event x location
ydata = event.ydata # get event y location
# performs a prior check i... |
import urllib2
import re
import leancloud
import time
leancloud.init('xSKEPbolbbf8kzTyPwh0k8IN-gzGzoHsz', 'yfsU1LM3UsB2UPQPURS9zvew')
from leancloud import Object
class LoveQ(Object):
def is_cheated(self):
# 可以像正常 Python 类一样定义方法
return self.get('cheatMode')
@property
def score(self):
... |
import argparse
from datetime import datetime, timedelta
import logging
import os
from typing import Tuple, Optional
import gitlab
from slack import WebClient as SlackClient
from Tests.Marketplace.marketplace_services import get_upload_data
from Tests.Marketplace.marketplace_constants import BucketUploadFlow
from Tests... |
import os
VERSION = os.getenv('VERSION', '113')
if VERSION == '113':
from gadgets_113 import *
elif VERSION == '116':
from gadgets_116 import *
else:
raise ImportError('Unknown firmware version %s' % VERSION)
from lc87_regs import *
fosc = 12e6
adr_y = [
0x0168, # Y00
0x0268, # Y01
0x006... |
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
import torch
from itertools import product
from torch.nn import functional as F
def laplace():
return np.array([[0,-1, 0], [-1, 4, -1], [0, -1, 0]]).astype(np.float32)[None, None, ...]
def laplace3d():
l = np.zeros((3, 3, 3))
l[1, ... |
"""
Django settings for test_project project.
Generated by 'django-admin startproject' using Django 1.11.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
from __f... |
import numpy as np
from sklearn.base import BaseEstimator
class FeatureMapper:
def __init__(self, features):
self.features = features
def fit(self, X, y=None):
for feature_name, column_name, extractor in self.features:
extractor.fit(X[column_name], y)
def transform(self, X):
... |
import warnings
from typing import Optional
from selenium.webdriver.remote.webdriver import WebDriver
from selene.common.helpers import on_error_return_false
class Help: # todo: should we make it private? like call it _Help (or think on better name)
# what about this style for example: ExtendedWebdriver(driver).is... |
"""
Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly
twice. Find the two elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].
Note:
The order of the result is not important. So in the above example, [5, 3] i... |
def number_to_token(number):
return token_object(number).as_token()
def number_to_prev_token(number):
t = token_object(number)
t.is_prev_token(True)
return t.as_token()
def token_to_number(token):
return token_object(token, True).as_number()
class token_object:
b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrs... |
total=0
for i in range(100,150,2):
total=total+i
print("The addition of the even numbers between 100-150 is:",total)
lastNumber=eval(input("\nHow far do you want to add the numbers? "))
total=0
for i in range(1,lastNumber+1):
total=total+i
print('The total for the sequence is:',total)
lastNumber= eval(input('\n... |
from distantio import DistantIO
from distantio import distantio_protocol
from distantio import crc16
from struct import pack
from time import time
import logging
import cProfile, pstats, io
def encode_test_frame(variable_id, group_id, extraid_1,extraid_2, value, fmt, fmtlookup):
# formatting
data_ID = (variable... |
import json
import pytest
from jirareports import api
CHANGELOG_SAMPLE = [
{
u'items': [
{
u'field': u'description', u'fieldtype': u'jira',
u'from': None, u'fromString': u'test-from',
u'to': None, u'toString': u'test-to'
}
],
... |
from collections import defaultdict
import argparse
import os
import traceback
from tqdm import tqdm
from tools.lib.logreader import LogReader
from tools.lib.route import Route
from selfdrive.car.car_helpers import interface_names
from selfdrive.car.fw_versions import match_fw_to_car_exact, match_fw_to_car_fuzzy, build... |
"""pybooru.moebooru
This module contains Moebooru class for access to API calls,
authentication, build url and return JSON response.
Classes:
Moebooru -- Moebooru classs.
"""
from __future__ import absolute_import
import hashlib
from .pybooru import _Pybooru
from .api_moebooru import MoebooruApi_Mixin
from .exceptio... |
'''
Created on 30 Jan 2013
@author: chris
'''
from azi_deriv import max_n_minimas as azi_maximas_n_minimas |
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import UserMixin, AnonymousUserMixin
from werkzeug.security import generate_password_hash, check_password_hash
db = SQLAlchemy()
class User(db.Model, UserMixin):
id = db.Column(db.Integer(), primary_key=True)
username = db.Column(db.String())
... |
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django import forms
from invoice import models
class ProfileCreationForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = models.Profile
class ProfileChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta):
... |
"""
pygments.lexers.nimrod
~~~~~~~~~~~~~~~~~~~~~~
Lexer for the Nim language (formerly known as Nimrod).
:copyright: Copyright 2006-2020 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, include, default
from pygments.toke... |
import os
SECRET_KEY = "very secret"
DEBUG = True
SQLALCHEMY_ECHO = False
if os.environ.get('DATABASE_URL'):
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
else:
SQLALCHEMY_DATABASE_URI = 'postgresql://postgres:postgres@localhost/webvita-heroku' |
'''
Created on Aug 18, 2014
This file contains all views associated with the "user" controller.
@author: Dean4Devil
'''
import random
from pycore.Base import ViewBase
class Login(ViewBase):
'Login View'
failed_list = ["Even MySQL thinks you are stupid!",
"Wrong Username or Password you moron!... |
"""
None
"""
class Solution:
def numberOfPatterns(self, m: int, n: int) -> int:
skip = {}
skip[(1,7)] = 4
skip[(1,3)] = 2
skip[(1,9)] = 5
skip[(2,8)] = 5
skip[(3,7)] = 5
skip[(3,9)] = 6
skip[(4,6)] = 5
skip[(7,9)] = 8
self.res = 0
... |
source = 'pictures'
theme = 'galleria'
img_size = (800, 600)
thumb_size = (280, 210)
ignore_directories = []
ignore_files = [] |
from datetime import datetime, timedelta
import pytest
from tests.conftest import twilio_vcr
from apostello import models, tasks
@pytest.mark.slow
@pytest.mark.django_db
class TestSendingSmsForm:
"""Test the sending of SMS."""
@twilio_vcr
def test_send_adhoc_now(self, recipients, users):
"""Test sen... |
class ConfigurationError(Exception):
"""
Raised when there is an error while setting up
the checkup class.
"""
pass |
"""
Flails
------------
Flask application factory.
Flails provides some basics for generating a flask application from a specific
configuration & file structure
Links
`````
* `documentation <http://packages.python.org/>`_
* `development version
<http://github.com/thrisp/flails>`_
"""
from setuptools import setup
setu... |
import sys
import numpy as np
import matplotlib.pyplot as plt
from PyQt4 import QtGui
from PyQt4.uic import loadUiType
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import (
FigureCanvasQTAgg as FigureCanvas,
NavigationToolbar2QT as NavigationToolbar)
Ui_MainWindow, QMainWindow = ... |
import re
import os.path
from io import open
from setuptools import find_packages, setup
PACKAGE_NAME = "azure-mgmt-azurestackhci"
PACKAGE_PPRINT_NAME = "Azure Stack HCI Management"
package_folder_path = PACKAGE_NAME.replace('-', '/')
namespace_name = PACKAGE_NAME.replace('-', '.')
with open(os.path.join(package_folder... |
from ._synapse_management_client import SynapseManagementClient
__all__ = ['SynapseManagementClient']
from ._patch import patch_sdk
patch_sdk() |
import errno
import os
from socket import socket as _original_socket
import socket
import sys
import time
import warnings
from eventlet.support import get_errno, six
from eventlet.hubs import trampoline, notify_close, notify_opened, IOClosed
__all__ = ['GreenSocket', 'GreenPipe', 'shutdown_safe']
BUFFER_SIZE = 4096
CON... |
import csv
import os.path
from tasks import sentiment
from celery import group
from collections import (
defaultdict,
Counter
)
from itertools import groupby
from numpy import (
std,
mean,
log
)
from prettytable import from_csv
import matplotlib.pyplot as plt
def polarity_to_class(polarity):
if ... |
from __future__ import absolute_import, division, print_function, unicode_literals
import os.path
def has_extension(f):
return f.endswith('.yml') or f.endswith('.json')
def data_filename(name):
if os.path.exists(name):
return name
if not has_extension(name):
n = name + '.yml'
if os.p... |
from setuptools import setup, find_packages
import SCFpy
import os
def extra_dependencies():
import sys
ret = []
if sys.version_info < (2, 7):
ret.append('argparse')
return ret
def read(*names):
values = dict()
extensions = ['.txt', '.rst']
for name in names:
value = ''
... |
import pandas as pd
import re
def _screen(self,include=True,**kwargs):
"""
Filters a DataFrame for columns that contain the given strings.
Parameters:
-----------
include : bool
If False then it will exclude items that match
the given filters.
This is the same as passing a regex ^keyword
kwargs :
Ke... |
from django.apps import AppConfig
class UsersConfig(AppConfig):
name = 'Internet_store.users'
verbose_name = "Users"
def ready(self):
"""Override this to put in:
Users system checks
Users signal registration
"""
pass |
"""
Qc API
Qc API # noqa: E501
The version of the OpenAPI document: 3.0.0
Contact: cloudsupport@telestream.net
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import datetime
import telestream_cloud_qc
from telestream_cloud_qc.models.audio_cli... |
import matplotlib
import pylab as pl
import networkx as nx
import random as rnd
import pickle
import math
from scipy.stats import norm
def euclidean_dist(i,j):
x1,y1=REDS.node[i]['pos']
x2,y2=REDS.node[j]['pos']
return math.sqrt((x1-x2)**2+(y1-y2)**2)
def pick_nodes():
node_name=[]
degree_set=[]
for i in REDS.nod... |
"""
Download EPG data from Horizon and output XMLTV stuff
"""
import logging
import time
import json
import http.client
def debug(msg):
logging.debug(msg)
def debug_json(data):
debug(json.dumps(data, sort_keys=True, indent=4))
class HorizonRequest(object):
hosts = ['web-api-salt.horizon.tv', 'web-api-pepper... |
from django.conf.urls import url
from apps.frontpage.views import PackageProfileView
from .views import HomepageView, LoginView, SignupView, LogoutView
urlpatterns = [
url(r'^$', HomepageView.as_view(), name="homepage"),
url(r'^auth/login', LoginView.as_view(), name='login'),
url(r'^auth/signup', SignupView... |
import re
import os
import maya.cmds as cmds
import maya.mel as mel
def get_meshes():
'''Gets all the transform meshes node names from a scene
Returns:
list: all meshes in scene
'''
objects = cmds.ls('*', type='mesh')
meshes = cmds.listRelatives(objects, parent=True)
meshes = list(se... |
"""Pyramid 3rd party plugin adding routes to config."""
from tzf.pyramid_routing import routes_from_package
def includeme(config):
"""Full includeme."""
routes_from_package(config,
'tests.routes_definitions.routing_to_include_1') |
import unittest
from types import *
from engine import *
class characterTestCase(unittest.TestCase):
def setUp(self):
self.root = Tk()
self.testCharacter = Character("Tom")
self.hack_1 = Hack('habit', 'Read More', 'Read more books', 50, 10)
self.hack_2 = Hack('habit', 'Veggies', 'E... |
from csv_utils import CsvUtils
from excel_utils import ExcelUtils
__all__ = ["CsvUtils",
"ExcelUtils"] |
__revision__ = "test/runtest/xml/output.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog"
"""
Test writing XML output to a file.
"""
import os
import re
import TestCmd
import TestRuntest
test = TestRuntest.TestRuntest(match = TestCmd.match_re,
diff = TestCmd.diff_re)
pythonstri... |
"""
WSGI config for jedi_academy project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
from whitenoise.django import Djan... |
"""Test keepercommander.subfolder."""
from unittest.mock import Mock
import pytest
import keepercommander.subfolder as subfolder
def BFN(*, type, uid, parent_uid, name, subfolders):
"""Build a mock BaseFolderNode."""
result = Mock(name=name)
result.type = type
result.uid = uid
result.parent_uid = pa... |
"""
Worm Algorithm for 2D Ising model.
By Christopher Wilson.
Written in Python 2.7.
Algorithm adapted from: http://www.sciencedirect.com/science/article/pii/S0550321308005609
Original Paper: http://journals.aps.org/prl/pdf/10.1103/PhysRevLett.87.160601
Other references:
Slides - http://pitp.physics.ubc.ca/confs/sh... |
import json
from datetime import datetime
import re
from amwatcher_spider.spiders.base import BaseSpider, KeywordEscape
from scrapy import Spider, Request
import logging
logger = logging.getLogger(__name__)
PROXY_KEY = 'amwatcher:spider:login_proxy:%s'
class AcfunSpider(BaseSpider):
name = 'acfun'
updrama_patte... |
from distutils.core import setup
setup(name='gitreformat',
version='0.1',
description='Reformat code without destroying git history (blame)',
long_description=open('README.md').read(),
author='Glenn Tarbox, PhD',
author_email='<glenn@tarbox.org>',
maintainer='Glenn Tarbox',
mai... |
from __future__ import absolute_import
from __future__ import unicode_literals
import testing.testing_package.package_a
import testing.testing_package.package_b
from git_code_debt.util.discovery import discover
from testing.testing_package.package_a.base import Base
def test_discover_classes():
# Note: package_a ba... |
__author__ = 'Jayin Ton'
from flask import Flask, render_template
from controller.UserController import user_controller
app = Flask(__name__)
host = '127.0.0.1'
port = 8000
app.register_blueprint(user_controller)
@app.route('/')
def index():
return render_template('index.html', title='Home Page')
if __name__ == '__... |
import argparse
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
default_ports = [5,8,20,21,22,23,25,53,67,68,69,79,80,88,110,123,135,137,138,139,143,161,162,179,360,389,427,443,445,464,515,546,593,631,636,989,990,1022,1023,1025,1026,1039,1070,1234,2222,3268,3389,8000,80... |
import logging
import re
from datetime import datetime, timedelta
from google.appengine.ext import ndb
from google.appengine.api import mail
from protorpc import messages
from webapp2_extras import security
from webapp2_extras.appengine.auth.models import UserToken as BaseUserToken
from webapp2_extras.appengine.auth.mo... |
class Square():
def __init__(self):
self.mset = set([1])
self.mk = 1
self.mv = 1
def __contains__(self,n):
if n < self.mv:
return n in self.mset
else:
from math import sqrt
mk = int(sqrt(n)) + 2
for i in xrange(self.mk, mk, ... |
from .. import models
from .generic import Manager, AllMixin, GetByIdMixin, SyncMixin
class RemindersManager(Manager, AllMixin, GetByIdMixin, SyncMixin):
state_name = 'Reminders'
object_type = 'reminder'
resource_type = 'reminders'
def add(self, item_id, **kwargs):
"""
Creates a local re... |
import logging
try:
import numpy as np
import numpy.random as rand
from astropy import units as u
from astropy.coordinates import SkyCoord,Angle
from astropy.units.quantity import Quantity
from astropy import constants as const
MSUN = const.M_sun.cgs.value
AU = const.au.cgs.value
DAY... |
def _int2char(int_):
int2char = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "."]
return int2char[int_]
def intlist2str(intlist):
return "".join([_int2char(int_) for int_ in intlist]) |
import luigi
import sciluigi as sl
class WriteFooFile(sl.SciTask):
def output(self):
return { 'out' : luigi.LocalTarget('foo.txt') }
def run(self):
with self.output()['out'].open('w') as outfile:
outfile.write('foo')
class FooToBar(sl.SciTask):
def output(self):
return { ... |
"""Various MySQL constants and character sets
"""
from .errors import ProgrammingError
MAX_PACKET_LENGTH = 16777215
def flag_is_set(flag, flags):
"""Checks if the flag is set
Returns boolean"""
if (flags & flag) > 0:
return True
return False
class _constants(object):
prefix = ''
desc = {... |
"""
.. codeauthor:: Cédric Dumay <cedric.dumay@gmail.com>
"""
import logging
from kser.entry import Entrypoint
from kser.schemas import Message
logger = logging.getLogger(__name__)
class Task(Entrypoint):
"""Mother class for tasks"""
@classmethod
def init_by_id(cls, _id):
"""Load task by its ID"""
... |
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
def remove_recursively(head, node, prev_node=None):
# No more elements in the list, return the original pointer.
if node is None:
re... |
import pysec.campic as campic
def parser_test():
campic.get_parser() |
from . import all, py2, py3, py27, py35, py36, py37, py38, py39 |
"""
The 'grouping' widget for Morse Trainer.
grouping = Groups()
group = grouping.get_grouping()
Return None or a value in [2..8] inclusive.
Raises the '.change' signal when changed.
"""
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import (QApplication, QWidget, QComboBox, QLabel,
... |
import random
from urllib import urlopen
from sys import argv
WORD_URL = "http://learncodethehardway.org/words.txt"
words=[]
if argv[1]=="english":
PHRASE_FIRST = True
else:
PHRASE_FIRST = False
for line in urlopen(WORD_URL).readlines():
words.append(line)
print(words) |
"""
WSGI config for myblock project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` s... |
import datetime
from bottle import Bottle, request, response, HTTPResponse
from bottle.ext import sqlalchemy
from bottle import static_file
from gisela.model import engine, Base, Tag, Timelog, Timer
from gisela.response import Response
app = Bottle()
plugin = sqlalchemy.Plugin(
engine,
Base.metadata,
... |
import spotipy
import spotipy.oauth2 as oauth2
import sys
import auth_data
try:
credentials = oauth2.SpotifyClientCredentials(
client_id=auth_data.client_id,
client_secret=auth_data.client_secret)
except oauth2.SpotifyOauthError:
print(
"Invalid client_id or secrept provided, make sure t... |
"""
Usage: python get_status.py [<serial>]
Gets the status of all APT controllers, or of the one specified
"""
import pyAPT
from runner import runner_serial
@runner_serial
def status(serial):
with pyAPT.MTS50(serial_number=serial) as con:
status = con.status()
print('\tController status:')
print('\t\tPosi... |
from jsonrpc import ServiceProxy
access = ServiceProxy("http://127.0.0.1:9248")
pwd = raw_input("Enter old wallet passphrase: ")
pwd2 = raw_input("Enter new wallet passphrase: ")
access.walletpassphrasechange(pwd, pwd2) |
import argparse
import bz2
import data_processing as dp
import emcee
import numpy as np
import os
import os.path as op
import plotutils.autocorr as ac
import posterior
import uuid
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--candidates', required=True, help='candidate fil... |
def DivisorSum(num):
res = 0
tmp = 1
while True:
if tmp * tmp > num:
break
if num % tmp == 0:
if int(num / tmp) == tmp:
res += tmp
else:
res += tmp + num / tmp
tmp += 1
return int(res - num)
abu_list = []
for i i... |
"""Module for POET application.""" |
import hashlib
import hmac
import six
def validate_hub_signature(app_secret, request_payload, hub_signature_header):
"""
@inputs:
app_secret: Secret Key for application
request_payload: request body
hub_signature_header: X-Hub-Signature header sent with request
@o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.