code stringlengths 1 199k |
|---|
import re
from wsgiref.util import request_uri
from wack.http.errors import HttpMethodNotAllowed, HttpNotFound
from wack.http.request import Request
from wack.http.response import Response
class Controllers(object):
"""
WSGI application that maps URLs and HTTP methods to functions wack that have
been mounte... |
import json
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.common.abstract_client import AbstractClient
from tencentcloud.tms.v20201229 import models
class TmsClient(AbstractClient):
_apiVersion = '2020-12-29'
_endpoint = 'tms.tencentcloudapi.com... |
from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import Async... |
from twilio.rest import Client
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)
map_item = client.sync \
.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.sync_maps("Players") \
.sync_map_items("steph_curry") \
.fetch()
print(map... |
"""
Note: This does not sort the output.
For sorting simply run:
$ sort md5sums.txt > md5sums_sorted.txt
"""
import sys
import glob
import csv
import hashlib
from multiprocessing import Pool
def md5_file(filename):
with open(filename) as f:
return (hashlib.md5(f.read()).hexdigest(),filename)... |
Test.expect(find_multiples(5, 25) == [5, 10, 15, 20, 25], f'{str(find_multiples(5, 25))} should equal [5, 10, 15, 20, 25]')
Test.expect(find_multiples(1, 2) == [1, 2], f'{str(find_multiples(1, 2))} should equal [1, 2]') |
'''
Get satellite data according to input file.
'''
from random import shuffle,random
import os,json
from utils.mapbox_static import MapboxStatic
from utils.coordinate_converter import CoordConvert
from modules.getFeatures import latLon,getBBox
from libs.foldernames import satDataFolder,testDataFolder
def get_satellite... |
import numpy as np
import cv2
from collections import deque
from obstacle_detector.distance_calculator import spline_dist
from obstacle_detector.perspective import inv_persp_new
from obstacle_detector.perspective import regress_perspecive
from obstacle_detector.depth_mapper import calculate_depth_map
from obstacle_dete... |
"""WavPack reading and writing.
WavPack is a lossless format that uses APEv2 tags. Read
http://www.wavpack.com/ for more information.
"""
__all__ = ["WavPack", "Open", "delete"]
from mutagen.apev2 import APEv2File, error, delete
from mutagen._util import cdata
class WavPackHeaderError(error): pass
RATES = [6000, 8000, ... |
import sys
from traceback import format_exception
import colorama
def color(color_, settings):
"""Utility for ability to disabling colored output."""
if settings.no_colors:
return ''
else:
return color_
def exception(title, exc_info, settings):
sys.stderr.write(
u'{warn}[WARN] {t... |
"""
Object
"""
import sys
from copy import copy as _copy
from collections import defaultdict
from .errors import ConfigurationError, ExecutionError, \
InvalidParameterDatatype
from .debugging import bacpypes_debugging, ModuleLogger
from .primitivedata import Atomic, BitString, Boolean, CharacterString, Date, \
... |
import miscClin
import tsvIO
import sys
remapDict = {}
DAYS_PER_YEAR = 365.2425
remapDict["anatomic_organ_subdivision"] = {}
if (1):
remapDict["anatomic_organ_subdivision"]["na"] = "NA"
remapDict["anatomic_organ_subdivision"]["rectum"] = 0
remapDict["anatomic_organ_subdivision"]["rectosigmoid_junction"] = 1... |
from __future__ import (absolute_import, print_function, division)
import itertools
import time
import hyperframe.frame
from hpack.hpack import Encoder, Decoder
from netlib import utils
from netlib.http import url
import netlib.http.headers
import netlib.http.response
import netlib.http.request
from netlib.http.http2 i... |
from discord import Embed
from bot import Command, categories
class GuildList(Command):
def __init__(self, bot):
super().__init__(bot)
self.name = 'guildlist'
self.aliases = ['guilds']
self.category = categories.SETTINGS
self.bot_owner_only = True
async def handle(self, c... |
import cgi
import logging
import os
import uuid
from collections import namedtuple
import requests
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.runtime.client_request import ClientRequest
from office365.runtime.utilities.http_method import HttpMethod
from office365.runt... |
from __future__ import unicode_literals
from django.db import migrations, models
import contents.models
class Migration(migrations.Migration):
dependencies = [
('contents', '0017_auto_20170329_1504'),
]
operations = [
migrations.AlterField(
model_name='frontpageimage',
... |
"""
WSGI config for jt_portfolio 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
os.environ.setdefault("DJANGO_SETT... |
from tempfile import TemporaryFile
import pytest
from imgpy import Img
@pytest.mark.parametrize('image', ({
'sub': 'anima/bordered.gif',
'convert': 'L',
'mode': 'P'
}, {
'sub': 'anima/clear.gif',
'convert': 'L',
'mode': 'P'
}, {
'sub': 'fixed/bordered.jpg',
'convert': 'L',
'mode': 'L... |
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRe... |
import unittest
from tests import testfunctions
from dftintegrate.fourier import vaspdata
class TestExtractingVASPDataToDatFiles(unittest.TestCase,
testfunctions.TestFunctions):
def setUp(self):
print('Testing extracting VASP data to .dat files...')
self.cases ... |
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline i... |
def capitalize(string):
for s in string.split(" "):
string = string.replace(s, s.capitalize())
return string
if __name__ == '__main__':
string = input()
capitalized_string = capitalize(string)
print(capitalized_string) |
import json
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.utils.datastructures import SortedDict
from django.db.models.signals import post_save
from django.db import models
from gamification.badges.models import ProjectBadge, ProjectBadgeToUser
from jsonfield impor... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
(r'^login/$', 'django.contrib.auth.views.login'),
(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page' : '/login'}),
... |
"""
__init__.py
The MIT License (MIT)
Copyright (c) 2013 Matt Ryan
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,... |
import pytest # noqa
import python_jsonschema_objects as pjo
def test_regression_156(markdown_examples):
builder = pjo.ObjectBuilder(
markdown_examples["MultipleObjects"], resolved=markdown_examples
)
classes = builder.build_classes(named_only=True)
er = classes.ErrorResponse(message="Danger!",... |
"""
virtstrap.project
-----------------
This module contains all the abstractions for dealing with a Project.
Using this object simplifies creating commands that are used to manage
the project.
"""
import os
import sys
from virtstrap import constants
from virtstrap.config import VirtstrapConfig
from virtstrap.utils imp... |
"""Module containing kernel related classes"""
__author__ = 'wittawat'
from abc import ABCMeta, abstractmethod
import numpy as np
import scipy.signal as sig
class Kernel(object):
"""Abstract class for kernels"""
__metaclass__ = ABCMeta
@abstractmethod
def eval(self, X1, X2):
"""Evalute the kerne... |
from core.himesis import Himesis, HimesisPreConditionPatternLHS
import uuid
class HSS2_then_IsolatedLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HSS2_then_IsolatedLHS.
"""
# Flag this instance a... |
import sys, re
output = open(sys.argv[1])
output = output.read()
output = re.split('thisisalinebreak =',output)
f = open(sys.argv[2])
i = 1
matlab = False
for line in f:
if line == "<?ml\n":
matlab = True
j = 0
for oline in output[i].split('\n'):
if (j > 2) & (re.match('^(\s+[^\s... |
import argparse
import logging
import struct
import sys
import socket
from contextlib import contextmanager
from random import randint
from typing import Generator
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.WARNING)
MC_QUERY_MAGIC = b'\xFE\xFD'
MC_QUERY_HANDSHAKE = b'\x09'
MC_QUERY_STATISTIC... |
from converters.circle import circle
from converters.currency import currency
from converters.electric import electric
from converters.force import force
from converters.pressure import pressure
from converters.speed import speed
from converters.temperature import temperature
class UnitsManager(object):
'''
Cla... |
""" Various global variables """
import os
PROG_NAME = "gBuilder"
PROG_VERSION = "2.0.0"
environ = {"os":"Windows",
"path":os.environ["GINI_HOME"]+"/",
"remotepath":"./",
"images":os.environ["GINI_HOME"]+"/share/gbuilder/images/",
"config":os.environ["GINI_HOME"]+"/etc/",
... |
from satori.client.common import want_import
want_import(globals(), '*')
from satori.web.utils.decorators import contest_view
from django import forms
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from satori.web.utils.forms imp... |
"""create_table
Revision ID: 42f4a0f4afd9
Revises: None
Create Date: 2014-11-15 16:53:22.716676
"""
revision = '42f4a0f4afd9'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table(u'board',
sa.Column('id', sa.Integer(), nullable=False, primary_key=True),
... |
import argparse
import os
import re
import subprocess
import sys
import traceback
import json
def main():
parser = argparse.ArgumentParser(description='Test discovery for Zabbix',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--discovery", dest="discovery", action='store_t... |
from sqlalchemy.testing import eq_, assert_raises, assert_raises_message
from sqlalchemy import testing
from sqlalchemy.testing import engines
from sqlalchemy.testing.schema import Table, Column
from test.orm import _fixtures
from sqlalchemy import exc
from sqlalchemy.testing import fixtures
from sqlalchemy import Inte... |
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from az... |
import re
from contextlib import contextmanager
from tempfile import NamedTemporaryFile
from plumbum.commands import CommandNotFound, ConcreteCommand, shquote
from plumbum.lib import ProcInfo
from plumbum.machines.base import BaseMachine
from plumbum.machines.env import BaseEnv
from plumbum.machines.local import LocalP... |
import os, shutil, glob
from functools import wraps
def print_warning(message, *args, **kwargs):
from . import colortext
if args or kwargs: message = message.format(*args, **kwargs)
colortext.write(message + '\n', color='red')
def print_error_and_die(message, *args, **kwargs):
aborting = "Aborting..."
... |
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import json
china = json.loads(open('china.json', 'r').read()) # slow
new_provs = []
new_citys = []
for prov in china['children']:
new_provs.append(prov['name'])
for city in prov['children']:
if city['name'] not in [u'市辖区', u'县', u'省直辖县级行政区划']:
... |
from time import sleep
TEMP_LOW = -20.0
TEMP_HIGH = 10.0
UNLOAD_TIME = 0.75
LOAD_TIME = 0.75
LABEL_APPLICATION_TIME = 0.1
class _BaseContainer:
"""The parent class for which all containers are inherited."""
def __init__(self, id, info, destination):
"""
Initialises the class. id is the id tag on... |
"""
Test for the bandicoot.helper.group module.
"""
import bandicoot as bc
from bandicoot.core import Record, Position
import unittest
import datetime
from bandicoot.tests.generate_user import random_burst
from bandicoot.helper.group import group_records
from bandicoot.helper.tools import std, mean
from datetime import... |
"""tcprocd client."""
from __future__ import unicode_literals, print_function, absolute_import
from tcprocd.protocol import Protocol
import socket
import select
import sys
if sys.version_info[0] < 3:
str_types = (str, unicode) # noqa
else:
str_types = (str, bytes) # noqa
class SocketShell(object):
"""
... |
major = 0
minor = 37
patch = 0 |
"""
Custom management command to rebuild thumbnail images
- May be required after importing a new dataset, for example
"""
import os
import logging
from PIL import UnidentifiedImageError
from django.core.management.base import BaseCommand
from django.conf import settings
from django.db.utils import OperationalError, Pr... |
import json
import struct
import re
import base64
import httplib
import sys
ERR_SLEEP = 15
MAX_NONCE = 1000000L
settings = {}
class UmaroRPC:
OBJID = 1
def __init__(self, host, port, username, password):
authpair = "%s:%s" % (username, password)
self.authhdr = "Basic %s" % (base64.b64encode(authpair))
self.conn... |
import json
from urllib import urlencode
from scrapy import log
from scrapy.http import Request
from scrapy.selector import Selector
from scrapy.contrib.loader import ItemLoader
from scrapy.contrib.loader.processor import Identity, TakeFirst
from torabot.spy.spiders.redis import RedisSpider
from torabot.spy.items impor... |
from django.contrib import admin
from books.models import *
class BookInfoAdmin(admin.ModelAdmin):
list_display=('title','isbn','price')
class GoodInfoAdmin(admin.ModelAdmin):
list_display=('seller','book','price')
admin.site.register(UserInfo)
admin.site.register(BookInfo,BookInfoAdmin)
admin.site.register(GoodsIn... |
"""Test RPCs related to blockchainstate.
Test the following RPCs:
- getblockchaininfo
- gettxoutsetinfo
- getdifficulty
- getbestblockhash
- getblockhash
- getblockheader
- getchaintxstats
- getnetworkhashps
- verifychain
Tests correspond to code in rpc/blockchain.cpp.
"""
from decim... |
from lob.resource import (
Address,
BankAccount,
BillingGroup,
BulkUSVerification,
BulkIntlVerification,
Card,
CardOrder,
Check,
Letter,
Postcard,
SelfMailer,
USAutocompletion,
USReverseGeocodeLookup,
USVerification,
USZipLookup,
IntlVerification
)
from lo... |
import datetime
from xml.etree import ElementTree
try:
from urllib.parse import urlparse, parse_qs
except ImportError:
# Python 2
from urlparse import urlparse, parse_qs
import html5lib
import requests
from .models import (
Category, SearchSortKey, SearchOrderKey, SearchResultPage, TorrentPage,
Torr... |
import csv
def model_name(table_name):
if table_name in [
'vtm',
'vpi',
'vmp',
'vmpp',
'amp',
'ampp',
'gtin',
]:
return table_name.upper()
else:
return ''.join(tok.title() for tok in table_name.split('_'))
def quote(s):
assert '"' n... |
import csv
import json
import requests
def main():
# We'll use a local version of this file from now on to save on
# bandwith.
with open('bills.json', 'r') as f:
data = json.load(f)
objects = data['objects']
# Create a csv file to output
with open('bills.csv', 'w') as o:
... |
STATUSCODES = {
200 : "success",
201 : "created",
202 : "accepted",
204 : "no_content",
302 : "redirect",
304 : "not_modified",
400 : "bad_request",
401 : "unauthorized",
403 : "forbidden",
4... |
import json
import unittest
from pyowm.airpollutionapi30 import airpollution_client, airpollution_manager, coindex, so2index, ozone, no2index, airstatus
from pyowm.config import DEFAULT_CONFIG
from pyowm.constants import AIRPOLLUTION_API_VERSION
from pyowm.utils import timestamps
from tests.unit.airpollutionapi30.test_... |
import clusters
blognames,words,data=clusters.readfile( './../data/feed_list.csv' )
for k in range( 1, 10 ) :
kclust = None
kclust = clusters.kcluster(data, blognames, clusters.pearson, k)
for k_id in range( len( kclust ) ):
print [blognames[r] for r in kclust[k_id]] |
import logging
import rlp
from utils import big_endian_to_int as idec
from utils import int_to_big_endian4 as ienc4
from utils import int_to_big_endian as ienc
from utils import recursive_int_to_big_endian
import dispatch
import sys
import signals
logger = logging.getLogger(__name__)
def lrlp_decode(data):
"always ... |
from RPi import GPIO as gpio
from robotics.actors.redbot_motor_actor import RedbotMotorActor
from robotics.interfaces.spi.mcp3008_spi_interface import MCP3008SpiInterface
from robotics.robots.aizek_robot import AizekRobot
from robotics.sensors.redbot_wheel_encoder_sensor import RedbotWheelEncoderSensor
from robotics.se... |
"""Simple tools to query github.com and gather stats about issues.
"""
from __future__ import print_function
import json
import re
import sys
from datetime import datetime, timedelta
from subprocess import check_output
from urllib2 import urlopen
ISO8601 = "%Y-%m-%dT%H:%M:%SZ"
PER_PAGE = 100
element_pat = re.compile(r'... |
import termcolor
import sys
class StrUtils:
def __init__(self):
pass
@staticmethod
def print_log_row(op_code, url, status_code, documented_reason, body, curlcommand):
if type(curlcommand) == str:
curlstr = curlcommand
else:
curlstr = curlcommand.get()
... |
import unittest
from probe import SearchApi, CompanyApi
class TestProbeAPI(unittest.TestCase):
def test_search_company_loanzen(self):
api = SearchApi()
companies = api.companies_get('1.1', filters='{"nameStartsWith": "loanzen"}')
#print type(companies.data), companies.data.companies
... |
import pytest
from path import Path
import yaml
from uuid import uuid4
from formica import cli
from tests.unit.constants import (REGION, PROFILE, STACK,
CHANGE_SET_PARAMETERS, CHANGE_SET_STACK_TAGS,
FULL_CONFIG_FILE, CHANGE_SET_CAPABILITIES,
... |
"""
Helper module for Python version 2.6 and below
- Ordered dictionaries
- Encoding/decoding urls
- Unicode
- Exception handling (except Exception, e)
"""
import base64
from urllib import unquote, quote
try:
from ordereddict import OrderedDict
except:
pass
def modulename():
return 'Helper module for Python... |
"""
Google AJAX Search Module
http://code.google.com/apis/ajaxsearch/documentation/reference.html
Needs Python 2.6 or later
"""
try:
import json
except ImportError as e:
import simplejson as json
except ImportError as e:
print(e)
exit()
import sys
import urllib.request, urllib.parse, urllib.error
import... |
import PyQt5 # this force pyqtgraph to deal with Qt5
import matplotlib
import warnings
with warnings.catch_warnings():
try:
warnings.simplefilter("ignore")
matplotlib.use('Qt5Agg')
except:
# on server without screen this is not possible.
pass
from .myqt import QT,mkQApp
from .cat... |
from pysimplesoap.client import SoapClient
def inspect(wsdl_url):
client = SoapClient(wsdl=wsdl_url,trace=False)
print("Target Namespace", client.namespace)
for service in list(client.services.values()):
for port in list(service['ports'].values()):
print(port['location'])
for... |
from PyQt4.QtCore import *
from PyQt4 import QtGui
class RadioManagement ():
def __init__ (self, radioCol, gridLayout):
self.radioGroup = QtGui.QButtonGroup() # To store radio buttons.
self.radioCol = radioCol
self.gridLayout = gridLayout
def initDelAndMovButtons (self, vLayout):
# Add hbox for edit buttons.
... |
from types import MethodType
def implant_method(obj, func, func_name):
base_class = obj.__class__
event = MethodType(func, obj, base_class)
setattr(obj, func_name, event)
if __name__ == "__main__":
pass |
import sys
import os.path
import lzma
import time
import os
import subprocess
if "APPVEYOR_REPO_TAG" not in os.environ or os.environ["APPVEYOR_REPO_TAG"] != "true":
print("Not uploading symbols since build is not tagged")
sys.exit()
symbol_filename = sys.argv[1]
with open(symbol_filename, "rt") as fh:
first... |
import os
import pickle
from parsers_backend import get_tree
from directories import dirs
def get_cached_sentence_image(argv, output_path, img_path):
"""Returns if the image is already generated or not, and avoids generating if yes.
Args:
argv: The command line arguments.
output_path: The path f... |
import os, sys, argparse
from os import listdir
from os.path import isfile, join
from os import walk
from dd_client import DD
from annoy import AnnoyIndex
import shelve
import cv2
parser = argparse.ArgumentParser()
parser.add_argument("--index",help="repository of images to be indexed")
parser.add_argument("--index-bat... |
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "formalarg",
version = "0.0.1",
author = "Emmanuel Hadoux",
author_email = "emmanuel.hadoux@gmail.com",
description = ("Library for formal argumentation system... |
from sris import db, models
from messenger import Messenger
from service import SMSService
from datetime import datetime
class Manager:
"""
The middle-man of interaction between messenger and the SMS service.
"""
def __init__(self):
self.config = self.__load_config_file()
self.messenger ... |
import sys
import os
from setuptools import setup, find_packages
import amqpy
if sys.version_info < (3, 2):
raise Exception('amqpy requires Python 3.2 or higher')
name = 'amqpy'
description = 'an AMQP 0.9.1 client library for Python >= 3.2.0'
keywords = ['amqp', 'rabbitmq', 'qpid']
classifiers = [
'Development ... |
import sys
import argparse
from itertools import izip
import math
def parseArgument():
# Parse the input
parser = argparse.ArgumentParser(description = "Make regions with 0 signal the average of their surrounding regions")
parser.add_argument("--signalsFileName", required=True, help='Signals file')
parser.add_argum... |
import sys
import os.path
import subprocess
import configparser
import argparse
import web.service.github.api.v3.AuthenticationsCreator
import web.service.github.api.v3.Client
import database.src.Database
import cui.uploader.Main
import web.log.Log
import database.src.contributions.Main
import setting.Setting
class Mai... |
'''
NPR Puzzle 2018-10-28
https://www.npr.org/2018/10/28/660936138/sunday-puzzle-row-row-row
Think of a famous Broadway musical in two words.
Change one letter in it to the preceding letter of the alphabet —
so B would become A, C would become B, etc.
Remove the space so you have a solid word.
The result will name some... |
import OOMP
newPart = OOMP.oompItem(8826)
newPart.addTag("oompType", "CAPC")
newPart.addTag("oompSize", "0603")
newPart.addTag("oompColor", "X")
newPart.addTag("oompDesc", "PF100")
newPart.addTag("oompIndex", "V50")
OOMP.parts.append(newPart) |
import pygame
import environment
from models import Projectile
class Laser(Projectile):
def __init__(self, laser_x, laser_y, sign=None, speed=20):
self.laser_height = 20
self.laser_width = environment.WINDOW_WIDTH - laser_x
self.laser_rect = pygame.Rect(laser_x, laser_y, self.laser_width, se... |
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import sys
try:
import seaborn
except:
pass
sigma=5.67e-8
def find_tau(tot_trans,num_layers):
"""
# -TD- document using
"""
trans_layer=tot_trans**(1./num_layers)
tau_layer= -1.*np.log(trans_layer)
tau_lay... |
import simplejson as json
import urllib
import urllib2
import time
server = ""
def GET(uri, params):
params = urllib.urlencode(params)
req = urllib2.Request(server + uri + "?" + params , headers={'Accept': 'application/json'})
return json.loads(urllib2.urlopen(req).read())
def POST(uri, params):
params ... |
import requests
import sys
import base64
import DeepsearchModule
from functools import wraps
from flask import Response,request
import config_settings
from flask import render_template
import os
import subprocess
import datetime
import time
import logging
import SearchModule
import urlparse
import urllib
import datetim... |
""" Marcos Moyano - marcos@anue.biz
Logout users of a specified period of idle time.
Copyright (c) 2006 Marcos Moyano
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
"""
__revision__ =... |
import fileinput
import sys
import argparse
from operator import attrgetter
class TraceItem(object):
def __init__(self, reftype, pg, tstamp):
self.reftype = reftype
self.pg = pg
self.tstamp = tstamp
self.marked = False
def __eq__(self, other):
return self.pg == other.pg
def __repr__(self)... |
import xbmc
import xbmcaddon
import xbmcgui
import os
import re
import sfile
def GetXBMCVersion():
#xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method": "Application.GetProperties", "params": {"properties": ["version", "name"]}, "id": 1 }')
version = xbmcaddon.Addon('xbmc.addon').getAddonInfo('version')
versi... |
import argparse
import os
import re
import shutil
import signal
import subprocess
import sys
import time
import unittest
from shutil import copytree
network_unit_file_path='/run/systemd/network'
networkd_runtime_directory='/run/systemd/netif'
networkd_ci_path='/run/networkd-ci'
network_sysctl_ipv6_path='/proc/sys/net/i... |
import cx_Oracle
def getCurrentOrNextSemesterCX (self):
file = open('/opt/Plone-2.5.5/zeocluster/client1/Extensions/Oracle_Database_Connection_NGUYEN_PRD.txt', 'r')
for line in file.readlines():
if line <> "" and not line.startswith('#'):
connString = line
file.close()
connection = c... |
from PyPedal import pyp_demog
from PyPedal import pyp_graphics
from PyPedal import pyp_jbc
from PyPedal import pyp_newclasses
from PyPedal import pyp_nrm
from PyPedal import pyp_metrics
from PyPedal.pyp_utils import pyp_nice_time
if __name__ == '__main__':
print 'Starting pypedal.py at %s' % (pyp_nice_time())
e... |
__all__ = ['keywords_header']
from portage import settings as ports
from portage.output import colorize
from display_pretty import colorize_string
from display_pretty import align_string
class keywords_header:
__IMPARCHS = [ 'arm', 'amd64', 'x86' ]
__ADDITIONAL_FIELDS = [ 'unused', 'slot' ]
__EXTRA_FIELDS = [ 'repo'... |
"""Invenio Access Control FireRole."""
__revision__ = "$Id$"
__lastupdated__ = """$Date$"""
"""These functions are for realizing a firewall like role definition for extending
webaccess to connect user to roles using every infos about users.
"""
import re
import cPickle
from zlib import compress, decompress
import sys
i... |
import sys
import math
name = input().strip() + ".txt"
lines = ''
with open(name, 'r') as r:
for line in r:
lines += line.strip() + " "
string = [i.lower() for i in lines.split()]
from collections import Counter
result = Counter(string).most_common(1)[0]
output = "output_2.txt"
with open(output, 'w') as out... |
import time as t
infinity = 1000
def getObjectInList(nodes, id):
return nodes[id-1]
def getChildOfNode(data, node):
ret = []
for dic in data:
if dic['start'] == node:
ret.append(dic['end'])
return ret
def getDist(data, node1, node2):
for dic in data:
if (dic['start'] == n... |
from webkom_constants import VERSION
template = open("webkom.spec.template")
new = open("webkom.spec", "w")
while 1:
line = template.readline()
if not line:
break
if line.find("Version:") != -1:
line = "Version: " + VERSION + "\n"
new.write(line) |
import string
import random
from sbnc.proxy import Proxy
from sbnc.plugin import Plugin, ServiceRegistry
from plugins.ui import UIPlugin, UIAccessCheck
proxy_svc = ServiceRegistry.get(Proxy.package)
ui_svc = ServiceRegistry.get(UIPlugin.package)
class AdminCommandPlugin(Plugin):
"""Implements basic admin commands."... |
import os
from AhsayTools import XmlConf, env_true, env_false
server_conf = XmlConf("/rdr/conf/server.xml")
server_conf.set_attrib("Service/Connector", "port", "RDR_HTTP_PORT")
server_conf.set_attrib("Service/Connector[@scheme='https']", "port",
"RDR_HTTPS_PORT")
server_conf.set_attrib("Service/Connector[@schem... |
"Fully test this module's functionality through the use of fixtures."
from megacosm.generators import Gem
import unittest2 as unittest
import fakeredis
from config import TestConfiguration
import fixtures
class TestGem(unittest.TestCase):
def setUp(self):
""" """
self.redis = fakeredis.FakeRedis()
... |
'''
Created on Jul 13, 2014
@author: cilia
'''
import os.path
import os
import time
import sys
import tempfile
from utils.path import loadModule
import utils
conf = utils.get_conf()
def run_task(task_conf):
print 'run task:', task_conf['task name']
task_func = loadModule(task_conf['task method'])
task_param... |
'''
Multicore 3D streamplot Python library for MDAnalysis --- :mod:`MDAnalysis.visualization.streamlines_3D`
=========================================================================================================
:Authors: Tyler Reddy and Matthieu Chavent
:Year: 2014
:Copyright: GNU Public License v3
:Citation: [Chav... |
"""
Created on Fri Dec 23 15:22:48 2011
@author: moritz
"""
__all__ = ["bslip"] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.