code stringlengths 1 199k |
|---|
import RPi.GPIO as gp
gp.setwarnings(False)
gp.setmode(gp.BOARD)
gp.setup(7, gp.OUT)
gp.setup(11, gp.OUT)
gp.setup(12, gp.OUT)
gp.output(7, False)
gp.output(11, False)
gp.output(12, True)
c = ''
while c != 'q':
c = raw_input("Enter Selection (q for quit):")
if c == '1':
gp.output(7, False)
gp.ou... |
"""
req v3.1
Copyright (c) 2016, 2017, 2018 Eugene Y. Q. Shen.
req is free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation, either version
3 of the License, or (at your option) any later version.
req is distributed in the ... |
if "bpy" in locals():
import imp
if "anim_utils" in locals():
imp.reload(anim_utils)
import bpy
from bpy.types import Operator
from bpy.props import (IntProperty,
BoolProperty,
EnumProperty,
StringProperty,
)
cla... |
'''
Some plot functions
Copyright (c) 2016 Peng Zhang <zhpn1024@163.com>
'''
import matplotlib
matplotlib.use('pdf')
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42
matplotlib.rcParams['svg.fonttype'] = 'none'
from matplotlib.pylab import *
def plotTrans(t, ypos = 0, intv = None, r = [0... |
__author__ = 'rdk'
from flask_wtf import Form
from wtforms import StringField, SelectField
from wtforms.validators import DataRequired
class UploadForm(Form):
filetype = SelectField('File type', coerce=int, validators=[DataRequired()])
customer = SelectField('Customer', coerce=str, validators=[DataRequired()])
... |
"""Test classes for Bookmark tests"""
from fauxfactory import gen_string
from nailgun import entities
from random import choice
from robottelo.constants import BOOKMARK_ENTITIES, STRING_TYPES
from robottelo.decorators import (
bz_bug_is_open,
skip_if_bug_open,
stubbed,
tier1,
tier2,
)
from robottelo... |
"""
"""
import time
import sys
DEFINITION_TEMPLATE = "sans_Definition_template.txt"
PARAMETERS_TEMPLATE = "sans_Parameters_template.txt"
class Generator(object):
## Pixel size in X [mm]
pixel_size_x = 5.15/1000.0
## Pixel size in Y [mm]
pixel_size_y = 5.15/1000.0
## Instrument name
name = "GPSAN... |
from __future__ import division, unicode_literals
import os
import csv
from collections import OrderedDict
from PyQt5.QtCore import pyqtSignal as QSignal
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QWidget, QPushButton, QGridLayout, QLabel,
QToolButton, QColorDialog, QApplicati... |
"""Triggered cog
`triggered from spoopy.
"""
import os
import urllib.request
import discord
from discord.ext import commands
from PIL import Image, ImageChops, ImageOps
SAVE_FOLDER = "data/lui-cogs/triggered/" # Path to save folder.
SAVE_FILE = "settings.json"
AVATAR_URL = "https://cdn.discordapp.com/avatars/{0.id}/{0.... |
"""Excitation Data."""
import numpy as _np
from .. import clientweb as _web
from . import util as _util
class ExcitationData:
"""ExcitationData Class.
This class implements access to excitation data paremeters and
current - integrated field conversions.
"""
def __init__(self, filename_web=None, file... |
import requests
import json
r = requests.get("https://graph.facebook.com/v2.3/186957608173966/comments?limit=25&__paging_token=enc_AdDROMkcRsTE08ZAeZAZC0goPHEgAdSiS2XuClMPBqiHdYXGUtILUCkwkTvST10QkWWtGejwZAgmKg2zZBvgVwpeuo2UZA&since=1483568411&__previous=1&access_token=EAACEdEose0cBAEocbeN4HW1NwQAqKiq3ci9wFZCSZB5oxg68tj... |
"""
APM automatic test suite
Andrew Tridgell, October 2011
"""
from __future__ import print_function
import atexit
import fnmatch
import glob
import optparse
import os
import re
import shutil
import signal
import subprocess
import sys
import time
import traceback
import apmrover2
import arducopter
import arduplane
im... |
import pytest
import os
from . import make_dsn, run
from .conditions import has_http
pytestmark = pytest.mark.skipif(not has_http, reason="tests need http")
def test_retry_after(cmake, httpserver):
tmp_path = cmake(["sentry_example"], {"SENTRY_BACKEND": "none"})
env = dict(os.environ, SENTRY_DSN=make_dsn(httpse... |
from __future__ import print_function
import pickle, os, sys, glob, hashlib
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
import fastdupes
test_files = set(pd.read_csv('./data/sampleSubmission_v2.csv').file.values)
train = pd.read_csv('./data/train_v2.csv')
df_full = pickle.load(open( "df_full... |
def f(a):
return a*a
list1=[1,2,3,4,5,6]
print(list1)
list2=map(f,list1)
print(list2)
list3=list(list2)
print(list3)
list4=list(map(lambda x: x * x, list3))
print(list4) |
from django.utils.translation import gettext_lazy as _
from django.contrib import admin
from .models import pictures,themes
class picturesAdmin(admin.ModelAdmin):
list_display = ('reference','name','sold','theme')
admin.site.register(pictures,picturesAdmin)
class themesAdmin(admin.ModelAdmin):
list_display = ('... |
__version__ = "0.14"
from . import sentinel
from .exceptions import (
SentinelAPIError,
SentinelAPILTAError,
ServerError,
InvalidKeyError,
QueryLengthError,
QuerySyntaxError,
UnauthorizedError,
InvalidChecksumError,
)
from .sentinel import (
SentinelAPI,
format_query_date,
ge... |
import sys
import glob
sys.path.append('gen-py')
sys.path.append('/html/NginxServer/py-fixbugs-tools/test/rpc/')
from task7698 import Task
from task7698.ttypes import Auth
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
t... |
from operator import itemgetter
from django.db.models import Count, Sum
from django_countries.fields import Country as DjangoCountry
from mi.models import Target, Sector
from mi.utils import percentage_formatted, percentage
from mi.views.base_view import BaseWinMIView, BaseExportMIView
from wins.models import HVC
GLOBA... |
import os
from urllib.error import HTTPError
from tempfile import gettempdir
import hashlib
from urllib.request import urlopen
def download_file(url, used_cached=True, temp_dir=None):
if not temp_dir:
temp_dir = gettempdir()
file_name = url.split("/")[-1]
suffix = file_name.split(".")[-1] # TODO suffix: if no endi... |
import copy
from flask_babel import lazy_gettext
from mycodo.inputs.base_input import AbstractInput
from mycodo.utils.atlas_calibration import setup_atlas_device
from mycodo.utils.system_pi import str_is_float
measurements_dict = {
0: {
'measurement': 'temperature',
'unit': 'C'
}
}
INPUT_INFORMA... |
import os
from pysollib.mygettext import _
from pysollib.settings import TITLE
from pysollib.ui.tktile.tkcanvas import MfxCanvas, MfxCanvasGroup
from pysollib.ui.tktile.tkcanvas import MfxCanvasImage, MfxCanvasRectangle
from pysollib.ui.tktile.tkutil import after, after_cancel
from pysollib.ui.tktile.tkutil import bind... |
"""driver that reads from serial port sent by arduino in json
and sends data on zmq pub socket"""
from threading import Thread
import serial
import zmq
import json
import logging
import time
from deware.core import settings as setg
from deware.core.utilis import OutOfRangeError
from deware.core.utilis import get_ra... |
import sys
import os
extensions = ['rst2pdf.pdfbuilder']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = 'itucsdb'
copyright = '2016, ShakeSpace'
version = '1.0'
release = '1.0'
exclude_patterns = ['_build']
pygments_style = 'sphinx'
html_theme = 'default'
html_static_path = ['_sta... |
from bottle_utils.html import urlquote, urlunquote
def safepath_filter(config):
regexp = r'.*?'
def to_python(match):
return urlunquote(match)
def to_url(path):
# return urlquote(path)
# at the moment bottle-utils performs quoting as well
# until a flag is implemented there t... |
import pandas as pd
import sys
sys.path.insert(0,'../')
import icr
import dedoose_utils as du
print('Loading data files...')
d1 = pd.read_csv('../data/ben_all.tsv', sep='\t')
d2 = pd.read_csv('../data/gabi_all.tsv', sep='\t')
d3 = pd.read_csv('../data/lizzie_all.tsv', sep='\t')
code_cols = ['culture_problem',
... |
import copy
__author__ = 'Serge Poltavski'
class LayoutItem(object):
def __init__(self, x=0, y=0, width=0, height=0):
self._x = x
self._y = y
self._w = width
self._h = height
def x(self):
return self._x
def y(self):
return self._y
def width(self):
... |
from pixel_math import is_any, q_same_rounded_floats
class MarkType(int):
none = 0
Legal = 1
Illegal = 2
Action = 3
Blocked = 4
def __new__(cls, value):
if MarkType._is_valid(value):
return super(MarkType, cls).__new__(cls, value)
else:
raise ValueError("N... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
"""
Creating a colormap from a list of colors
-----------------------------------------
Creating a colormap from a list of colors can be done with the `from_list`
method of `LinearSegmentedColormap`. You must pass a... |
"""InaSAFE Disaster risk assessment tool developed by AusAid -
**IS Safe Interface.**
The purpose of the module is to centralise interactions between the gui
package and the underlying InaSAFE packages. This should be the only place
where SAFE modules are imported directly.
Contact : ole.moller.nielsen@gmail.com
.. not... |
import os
import time
import json
import errno
from ansible import constants as C
from ansible import utils
from ansible.cache.base import BaseCacheModule
class CacheModule(BaseCacheModule):
"""
A caching module backed by json files.
"""
def __init__(self, *args, **kwargs):
self._timeout = float... |
import sys
import subprocess
import getopt
VERBOSITY=1
filename = ""
def call_undertaker(filename):
""" Generates the presence conditions for `filename' in one line """
cpppc = subprocess.Popen(['undertaker', '-q', '-j', 'cpppc', filename],
stdin=subprocess.PIPE,
... |
"""Utilities for computing the gradient and Hessian of functionals."""
from __future__ import print_function, division, absolute_import
from future import standard_library
standard_library.install_aliases()
import numpy as np
from odl.solvers.functional.functional import Functional
from odl.operator import Operator
fro... |
import unittest
import six
from simplicial import *
class FiltrationTests(unittest.TestCase):
def testSimple(self):
'''Test basic behaviour.'''
f = Filtration()
f.addSimplex(id = 1)
f.addSimplex(id = 2)
six.assertCountEqual(self, f.simplices(), [ 1, 2 ])
f.setIndex(0.... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('statisticscore', '0025_auto_20160202_1742'),
]
operations = [
migrations.AddField(
model_name='session',
name='gender_number_female',
field=models.IntegerFie... |
""" Class for handling downloading and installing a rice"""
import json
import os
from . import error, util, gitrice
TMPEXTENSION = "-tmp.zip"
INSTALL = "install.json"
class Installer(object):
"""
Handles downloading and installing rices for a specific package
Deals with all functionality concerning configu... |
import os,subprocess,re,json,hashlib
def extract_defines(filepath):
f = open(filepath, encoding="utf8").read().split("\n")
a = []
for line in f:
sline = line.strip(" \t\n\r")
if sline[:7] == "#define":
# Extract the key here (we don't care about the value)
kv = sline[8:].strip().split(' ')
a.append(kv[0... |
import copy
from tests.test_utils import post_collection
from treeherder.client.thclient import client
from treeherder.perf.models import (PerformanceDatum,
PerformanceFramework,
PerformanceSignature)
def test_post_perf_artifact(test_repository, fa... |
import json
import logging
import platform
from os.path import abspath
from django.utils.functional import lazy
import dj_database_url
from decouple import Csv, config
from pathlib2 import Path
from .static_media import PIPELINE_CSS, PIPELINE_JS # noqa
ROOT_PATH = Path(__file__).resolve().parents[2]
ROOT = str(ROOT_PA... |
"""Fibonacci Sequence Generator"""
def xfibo(count):
"""Fibonacci Sequence Generator
Args:
iterator (int) = Placeholder for count of sequence iteration attempts.
lasnum (int) = Last number in the sequence.
currnum (int) = Current number in the sequence
count (int) = The number of... |
import os
ABS_WORK_DIR = os.path.join(os.getcwd(), "build")
config = {
"log_name": "central_to_aurora",
"version_files": [
{"file": "browser/config/version.txt", "suffix": ""},
{"file": "browser/config/version_display.txt", "suffix": ""},
{"file": "config/milestone.txt", "suffix": ""},
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import os
import flask
from flask import Flask, Response
from mo_dots import listwrap, coalesce, unwraplist
from mo_json import value2json, json2value
from mo_logs import Log, constants, startup, Except
from m... |
from django.contrib.auth.models import User
from django.db import models
class BaseModel(models.Model):
"""
Base class for models which adds utility methods.
"""
class Meta:
abstract = True
@classmethod
def choice_display_extra_expression(self, field):
exp = 'CASE %s ' % field
... |
from importer import DocImporter
from collections import OrderedDict
import sys
import time
import subprocess, shlex
import ConfigParser
import pprint
class Scraper():
def __init__(self, _docset, config_file):
self.config = ConfigParser.ConfigParser()
config_file = 'importer.cfg'
self.config... |
import os
import sys
import tempfile
import shutil
import pickle as pkl
import types
import time
from seqtools import SerializableFunc
if sys.version_info >= (3, 4):
from importlib import reload
def test_SerializableFunc():
tmpdir = tempfile.mkdtemp()
try:
sys.path.insert(0, tmpdir)
pkgdir =... |
import re
f = open("downloaded.rules", "r")
f2 = open("disablesid.conf", "r")
r = re.compile('^#|^alert')
r2 = re.compile('^\ sid:')
r3 = re.compile('^1:[0-9]+$')
desc2sid = dict()
for l in f.readlines():
if r.search(l):
sigtable = l.split(';')
for i in sigtable:
if r2.search(i):
... |
from bedrock.base.urlresolvers import reverse
from bedrock.mozorg.util import page
class PageNode(object):
"""
A utility for representing a hierarchical page structure.
A PageNode is associated with a static page and can have several child nodes
that themselves have pages and children, forming a tree st... |
from nipype.interfaces.base import CommandLineInputSpec, Directory, File, TraitedSpec, OutputMultiPath, traits, isdefined
from nipype.interfaces.fsl.base import FSLCommand, FSLCommandInputSpec, Info
from nipype import LooseVersion
from nibabel import load
import os
from os import path
class MCFLIRTInputSpec(FSLCommandI... |
import json
import mock
from nose.tools import eq_, assert_raises
from socorro.lib.util import SilentFakeLogger, DotDict
from socorro.external.crashstorage_base import (
Redactor,
MemoryDumpsMapping
)
from socorro.external.hb.crashstorage import HBaseCrashStorage, CrashIDNotFound
from socorro.database.transacti... |
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import itertools
from collections import Mapping
from numbers import Number
from mo_future import text_type
from jx_base.expressions import jx_expression
from mo_collections.unique_index import UniqueIndex
fro... |
from setuptools import setup
VERSION = 0.1
DEPS = []
setup(
name='mozlint',
description='Framework for registering and running micro lints',
license='MPL 2.0',
author='Andrew Halberstadt',
author_email='ahalberstadt@mozilla.com',
url='',
packages=['mozlint'],
version=VERSION,
classif... |
import sys
import os
import copy
import json
import gzip
import math
import re
from pprint import pprint
from libmozdata import bugzilla
def __download_bugs(name, query):
bugs = []
i = 0
while True:
try:
with open(name + '/' + name + str(i) + '.json', 'r') as f:
bugs += j... |
"""!
-----------------------------------------------------------------------------
File Name : loop_script.py
Purpose:
Created: 23-Jun-2016 07:55:30 AEST
-----------------------------------------------------------------------------
Revision History
-----------------------------------------------------------------------... |
"""Sound-related functions."""
import logging
import application
import db
from threading import Thread
from math import pow
from datetime import datetime
from random import choice
from time import time, sleep
from .util import do_login, do_error
from .network import download_track
from showing import SHOWING_QUEUE
fro... |
config = {
"nightly_build": True,
"branch": "mozilla-beta",
"en_us_binary_url": "http://ftp.mozilla.org/pub/mozilla.org/firefox/nightly/latest-mozilla-beta/",
"update_channel": "beta",
"latest_mar_dir": '/pub/mozilla.org/firefox/nightly/latest-mozilla-beta-l10n',
# l10n
"hg_l10n_base": "http... |
import os
config = {
"default_actions": [
'clobber',
'checkout-sources',
'get-blobs',
'update-source-manifest',
'build',
'build-symbols',
'make-updates',
'prep-upload',
'upload',
'make-update-xml',
'upload-updates',
'mak... |
from __future__ import unicode_literals
from frappe import _
app_name = "erpnext"
app_title = "ERPNext"
app_publisher = "Frappe Technologies Pvt. Ltd."
app_description = """ERP made simple"""
app_icon = "icon-th"
app_color = "#e74c3c"
app_version = "6.12.11"
app_email = "info@erpnext.com"
app_license = "GNU General Pub... |
from __future__ import absolute_import, unicode_literals
from django.conf import settings
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.db import models
from django.utils import timezone
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
fr... |
"""
Signals declaration for the user accounts app.
"""
from django.dispatch import Signal
user_profile_updated = Signal(providing_args=['user_profile']) |
from . import test_purchase_manual_currency |
from unittest.mock import patch
import flask
import pytest
import main
from flask import json
@pytest.fixture(scope='class')
def app():
return flask.Flask(__name__)
def mock_response_for(misspelled):
class MockResponse:
def __init__(self, json_data, status_code):
self.json_data = json_data
... |
"""
This script manages an Orka server image.
@author: e-science Dev-team
"""
from sys import argv
from datetime import datetime
import os
import yaml
import sys
import random, string
import base64
from time import sleep
import logging
import subprocess
from base64 import b64encode
from os.path import abspath, join, ex... |
"""
Tests for django admin command `update_expiration_date` in the verify_student module
"""
from datetime import timedelta
from unittest.mock import patch
from django.conf import settings
from django.core.management import call_command
from django.test import TestCase
from django.utils.timezone import now
from testfix... |
from django.core.management.base import BaseCommand
from django.db import transaction
from cronotacografo.models import Registro
import json
import os
import requests
import datetime
import warnings
class Command(BaseCommand):
help = 'Recebe dados geográficos de ônibus da API Olho Vivo da SPTrans'
url = 'http:/... |
from django.core.urlresolvers import reverse, resolve
from models import MP
from core.models import Person
def process(request):
rs = resolve(request.path_info)
if rs.url_name is 'person':
slug = rs.kwargs['slug']
try:
person = Person.objects.get(slug=slug)
return dict(mp... |
"""
This is a util methods to work with flask-cache.
how-to:
variable = fromcache('<cachekey>') or tocache('<cachekey>', <live-object> )
print variable
"""
from flask.ext.cache import Cache
cache = Cache()
cache.CACHE_DEFAULT_TIMEOUT = 600 #10 minutos
def fromcache(name):
o = cache.get(name)
if o:
return o
else:
... |
import masterdirac.models.systemdefaults as sys_def
from tcdiracweb.utils.common import json_prep
import boto.sqs
import json
class Console:
"""
Gets messages for the console from master
"""
def __init__(self, current_app):
self.app = current_app
self.logger = current_app.logger
... |
'''
Created on 17 avr. 2015
@author: Bertrand Verdu
'''
import logging
from twisted.application import service
from utils import load_yaml
from util.main import get_subservices
logging.basicConfig(level=logging.INFO)
def makeService(args):
'''
Create and launch main service
'''
mainService = service.Mul... |
def find_common_kmers(dna, k, threshold):
"""Return a list of all `k`-mers in `dna` which occur more than `threshold` times
"""
result = []
for start in range(len(dna)-k):
kmer = dna[start:start+k]
if dna.count(kmer) >= threshold:
result.append(kmer)
return result |
from odoo import api, models
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
@api.onchange("product_id")
def _onchange_product_id(self):
res = super()._onchange_product_id()
if self.product_id and self.user_has_groups(
"account_invoice_line_description."
... |
import connector
import consumer
import backend
import company
import icops_model |
"""User interface definitions for this plugin.
"""
from lino.api import dd, _
from lino.utils import AttrDict
from lino.modlib.users.mixins import My
from .roles import CBSSUser, SecurityAdvisor
from .mixins import RequestStates
from .utils import (nodetext, cbss2gender, cbss2date, cbss2address,
cbs... |
import argparse
import os
from datetime import date
default_extensions = [ "scala" ]
year = date.today().year
copyright = "/*\n" + " * Copyright (c) " + str(year) +" Oracle and/or its affiliates. All rights reserved.\n" + """ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This program is free sof... |
# -*- coding: utf-8 -*-
from osv import fields, osv
from ..taobao_top import TOP
from ..taobao_top import TOPException
from openerp.loglevels import ustr
import logging
_logger = logging.getLogger(__name__)
class taobao_delivery_update_line(osv.osv_memory):
_name = "taobao.delivery.update.line"
_description = ... |
from tastypie_nonrel.resources import MongoResource
from tastypie_nonrel.fields import ForeignKeysListField
from tastypie.constants import ALL
from tastypie import fields
from models import (Deputy, Document, Commission, WrittenQuestion,
CommissionMembership, AnnualReport, Party)
class AnnualReportR... |
from argparse import Namespace
from datetime import (
datetime,
)
from mock import (
Mock,
patch,
)
try:
# Import none-unicode first because it means unicode is not default.
from StringIO import StringIO
except ImportError:
from io import StringIO
from tests import TestCase
import gce
GCE_ENVIRO... |
{
"name" : "oerp.at Commission",
"description":"""
Commission Base Module
======================
Basic module for commission management
""",
"version" : "1.2",
"author" : "oerp.at",
"category" : "Commission",
"depends" : ["at_base",
"at_account",
"at_sale",
... |
from . import account_hierarchy_label
from . import account |
from django.http import HttpResponse, HttpResponseBadRequest
from django.shortcuts import get_object_or_404
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from squad.http import auth_submit, read_file_upload
from squad.ci.tasks import submit
from squad... |
from flask import Blueprint, request, url_for, flash, redirect
from flask.ext.login import login_user, current_user
from pybossa.core import db, twitter
from pybossa.model.user import User
from pybossa.util import get_user_signup_method
blueprint = Blueprint('twitter', __name__)
@blueprint.route('/', methods=['GET', 'P... |
{
'name': 'HR (Extra) Hours Management',
'summary': 'Compute extra hours based on attendances',
'category': 'Human Resources',
'author': "Compassion Switzerland, "
"Odoo Community Association (OCA)",
'depends': [
'hr_attendance',
'hr_public_holidays',
'hr_contra... |
ECS_DESCOMP = 'Descomposición'
ECS_MRTLD = 'Mortalidad' |
import sys, os
import errno
def getAppDataDir(appname):
# http://stackoverflow.com/questions/1084697/how-do-i-store-desktop-application-data-in-a-cross-platform-way-for-python
if sys.platform == 'darwin':
from AppKit import NSSearchPathForDirectoriesInDomains
# http://developer.apple.com/DOCUMEN... |
from . import test_purchase_cancel_reason |
import pytest
from conftest import PLUGIN_CLASS, PLUGIN_NAME
def test_bigchain_class_file_initialization(plugin_config):
from bigchaindb.core import Bigchain
bigchain = Bigchain()
assert bigchain.consensus == PLUGIN_CLASS
def test_bigchain_class_initialization_with_parameters(default_config):
from bigch... |
class NoCurrentEntry(Exception):
pass |
import requests
import re
import os
base = os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../')
import rethinkdb as r
conn = r.connect( "localhost", 28015).repl()
db = r.db('public')
organization_id = list(db.table('organizations').filter({'name': 'Seattle Police Department'}).run(conn))[0]['id']
def par... |
import sark
import idautils
def in_segment(address, segment):
return address >= segment.startEA and address <= segment.endEA
codeseg = sark.Segment(name='seg004')
names = [i for i in idautils.Names() if in_segment(i[0], codeseg)]
names = [(i[0] - codeseg.startEA, i[1]) for i in names]
with open('c:/Users/Joe/datase... |
import shutil
from urllib.request import urlopen
from sqlalchemy.types import LargeBinary
from cherrypy.lib.static import serve_file
from uber.common import *
from mivs._version import __version__
from mivs.config import *
from mivs.models import *
import mivs.tasks
import mivs.model_checks
import mivs.automated_emails... |
def _quote(to_quote):
if '"' not in to_quote:
return '"%s"' % to_quote
return to_quote
class Query(object):
"""
Dumb implementation of a Query object, using 3 string lists so far
for backwards compatibility with the (table, where_clause, where_params) previously used.
TODO: To be impr... |
import xml.sax
import urllib2
import glob
import re
import sys
ASSOCIATED = "http://www.w3.org/ns/prov#wasAssociatedWith"
ATTRIBUTED = "http://www.w3.org/ns/prov#wasAttributedTo"
ACTIVITY = "http://www.w3.org/ns/prov#Activity"
ENTITY = "http://www.w3.org/ns/prov#Entity"
AGENT = "http://www.w3.org/ns/prov#Agent"
ORGANIZ... |
"""
Content Type Gating service.
"""
import crum
from lms.djangoapps.courseware.access import has_access
from lms.djangoapps.courseware.masquerade import (
is_masquerading_as_limited_access, is_masquerading_as_audit_enrollment,
)
from openedx.core.lib.graph_traversals import get_children, leaf_filter, traverse_pre_... |
import json
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.client import RequestFactory
from courseware.access import has_access
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
from student.mod... |
from __future__ import print_function
from __future__ import absolute_import
import code
import os
import sys
try:
from usi.usage import *
except ImportError:
help_text = help
credits_text = ""
copyright_text = ""
license_text = ""
from .console import Console
CONSOLE = None
def start(*k, **kw):
global CO... |
from openbase.openbase_core import OpenbaseCore
from osv import fields,osv
class openstc_equipement(OpenbaseCore):
_inherit = "openstc.equipment"
_columns = {
'patrimoine_contract_ids':fields.one2many('openstc.patrimoine.contract', 'equipment_id', 'Contracts linked'),
#'occurrences_contr... |
import random
from django.test import TestCase
from recipes.models import Recipe, RecipeTag
from recipes.views import *
from tests.recipes.model_tests import TestRecipe, TestRecipeTag
class HomeTests(TestCase):
def test_get_context_data(self):
Recipe.objects.all().delete()
RecipeTag.objects.all().de... |
"""
Automated tests for checking similarity server.
"""
from __future__ import with_statement
import logging
import sys
import unittest
from copy import deepcopy
import numpy
import Pyro4
import gensim
import simserver
logger = logging.getLogger('test_simserver')
def mock_documents(language, category):
"""Create a ... |
"""
An API for retrieving user account information.
For additional information and historical context, see:
https://openedx.atlassian.net/wiki/display/TNL/User+API
"""
import datetime
import logging
import uuid
from functools import wraps
import pytz
from consent.models import DataSharingConsent
from django.apps import... |
from django.conf import settings
BRAND_MODEL = getattr(settings, 'SHOPKIT_BRAND_MODEL')
""" Model class used brands. """
BRAND_REQUIRED = getattr(settings, 'SHOPKIT_BRAND_REQUIRED', True)
""" Whether or not brand is a required property for products. """ |
"""
MIT License
Copyright (c) 2019 Claude SIMON (https://q37.info/s/rmnmqd49)
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, co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.