content stringlengths 4 20k |
|---|
# -*- coding: utf-8 -*-
from __future__ import division
import game
import wx
from math import ceil
CELL = 15 # cell drawing size
class View(wx.Panel):
def __init__(self, parent, area):
self.area = area
# TODO: make board view flexibly resizable
super(View, self).__init__(parent)
... |
from django.db.models import Sum
from kolibri.auth.models import FacilityUser
from kolibri.content.models import ChannelMetadataCache, ContentNode, File
from rest_framework import serializers
from .content_db_router import default_database_is_attached, get_active_content_database
class ChannelMetadataCacheSerializer... |
class tensorflow(PipWig):
git_uri = 'https://github.com/tensorflow/tensorflow'
tarball_uri = 'https://github.com/tensorflow/tensorflow/archive/v{RELEASE_VERSION}.tar.gz'
last_release_version = '1.0.1'
dependencies = ['bazel', 'numpy']
config_access = ['PATH_TO_NVCC', 'PATH_TO_CUDNN_SO']
supported_features = ['cud... |
import os
from setuptools import setup, find_packages
ROOT = os.path.abspath(os.path.dirname(__file__))
setup(
name='django-nose',
version='1.4',
description='Makes your Django tests simple and snappy',
long_description=open(os.path.join(ROOT, 'README.rst')).read(),
author='Jeff Balogh',
auth... |
#!/usr/bin/python
import cStringIO, logging, os, sys, unittest
# direct imports; autotest has not been setup while testing this.
from shared.test_utils import mock
import setup_modules
class LoggingErrorStderrTests(unittest.TestCase):
def setUp(self):
autotest_dir = os.path.dirname(sys.modules[__name__]... |
from rest_framework import serializers
from .models import Payment
from sita.users.models import User
class PaymentSerializer(serializers.Serializer):
""""""
conekta_id = serializers.CharField()
card_last_four = serializers.CharField(
max_length=4
)
card_brand = serializers.CharField(
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @date 160212
"""
Upload and download file from S3
"""
import configparser
from boto3.session import Session
# Read configure
config = configparser.ConfigParser()
config.read('aws.ini')
if 'AWS-S3' in config:
conf = config['AWS-S3']
else:
conf = {
... |
from django.db import migrations, models
from django.conf import settings
from opaque_keys.edx.django.models import CourseKeyField
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
... |
import json
from collections import OrderedDict
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.http import Http404, HttpResponse
from django.http.response import HttpResponseBase
from django.views.decorators.csrf import csrf_exempt
from django.views.defaults import se... |
from django.conf import settings
from django.contrib import messages
from django.core.mail import EmailMessage
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from comics.help.forms import FeedbackForm
def about(request):
return render... |
from django.conf.urls import url, include
from django.conf import settings
from . import views
urlpatterns = [
url(r'^games/$', views.GameListView.as_view(), name='diplomacy_game_list'),
url(r'^games/(?P<slug>[-\w]+)/$', views.GameDetailView.as_view(),
name='diplomacy_game_detail'),
url(r'^games/... |
import datetime
import os
import shutil
import tempfile
import threading
import unittest
from webkitpy.common.system.executive import ScriptError
from webkitpy.common.system.outputcapture import OutputCapture
from webkitpy.tool.bot.queueengine import QueueEngine, QueueEngineDelegate, TerminateQueue
class LoggingDele... |
from rdkit import RDConfig
from rdkit import six
import sys,os,types
from rdkit import Chem
from rdkit.VLib.Filter import FilterNode
class SmartsFilter(FilterNode):
""" filter out molecules matching one or more SMARTS patterns
There is a count associated with each pattern. Molecules are
allowed to match the pat... |
"""SCons.Tool.m4
Tool-specific initialization for m4.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 The SCons Foundation
#
# Permission is h... |
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import PyQt4.QtCore as QtCore
from electrum.i18n import _
from electrum import mnemonic
from util import *
from qrtextedit import ShowQRTextEdit, ScanQRTextEdit
class SeedDialog(QDialog):
def __init__(self, parent, seed, imported_keys):
QDialog.__init__... |
from __future__ import absolute_import
from __future__ import print_function
import fnmatch
import re
from twisted.internet import defer
from twisted.web.error import Error
from zope.interface import implementer
from buildbot.interfaces import IConfigured
from buildbot.util import unicode2bytes
from buildbot.www.aut... |
{
'name': 'HR Services - Addsol',
'version': '1.0',
'author': 'Addition IT Solutions Pvt. Ltd.',
'category': 'Human Resources',
'summary': 'Attendance Requests & Leaves Management',
'website': 'https://www.aitspl.com',
'description': """
HR Services by Addition IT Solutions
=================... |
from itertools import groupby
import collections
def filter_empty_helper(keys=None):
""" Remove empty elements from a list."""
def _inner(elem):
if isinstance(elem, dict):
for k, v in elem.items():
if (keys is None or k in keys) and v:
return True
... |
"""
Unittests for the trial managers
"""
import datetime
import unittest
from mock import MagicMock, patch
from rm.trials import managers
from rm.trials.models import Trial
from rm.userprofiles.models import RMUser
class RmTrialManagerTestCase(unittest.TestCase):
def setUp(self):
super(RmTrialManagerTes... |
#!/usr/bin/env python
'''
see sample.json
'''
import sys
import json
from datetime import datetime
import time
import random
import httplib2
import argparse
# XXX lon,lat in payload_hex should be variable.
ns_fixed = {
"payload_hex" : "0000000058d4b41b420ea943430bbb24021d000000000000",
"Lrcid" : "00000201",
... |
import logging
import os
import shutil
import subprocess
import tempfile
import urlgrabber
from virtinst import Storage
from virtinst import support
from virtinst import util
from virtinst import Installer
from virtinst.VirtualDisk import VirtualDisk
from virtinst.User import User
from virtinst import OSDistro
def ... |
from nipype.pipeline.engine import Workflow, Node
import nipype.interfaces.utility as util
from nipype.interfaces.mipav.developer import JistIntensityMp2rageMasking, MedicAlgorithmSPECTRE2010
'''
Workflow to remove noisy background from MP2RAGE images
AND SKULLSTRIP unsing cbstools
==============================
ada... |
import re
import string
import os
import socket
# FCNTL is deprecated from Python 2.2, so only import it if we doesn't
# get the names we need. Furthermore, FD_CLOEXEC seems to be missing
# in Python 2.2.
import fcntl
if hasattr(fcntl, 'F_SETFD'):
F_SETFD = fcntl.F_SETFD
if hasattr(fcntl, 'FD_CLOEXEC'):
... |
"""
APIRequest class
"""
import datetime
import re
# TODO(termie): replace minidom with etree
from xml.dom import minidom
from nova import log as logging
LOG = logging.getLogger("nova.api.request")
_c2u = re.compile('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))')
def _camelcase_to_underscore(str):
return _c2u.sub(... |
# -*- coding: utf-8 -*-
from __future__ import division
from procedural_city_generation.roadmap.Vertex import Vertex
import numpy as np
from scipy.spatial import cKDTree
from procedural_city_generation.additional_stuff.Singleton import Singleton
singleton=Singleton("roadmap")
def check(suggested_vertex, neighbour, ne... |
# -*- coding: utf-8 -*-
'''
Phoenix Add-on
Copyright (C) 2015 Blazetamer
Copyright (C) 2015 lambda
This program 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 Lic... |
import numpy as np
from ..chesweet import *
from ..chesweet import _round_down_up, _nearest_chi
torsionals = [-10, 10., 180., -180., 60., 75., -185, 185]
ef_corr = 183.4
disaccharides_list = ['a-D-Glcp-1-1-a-D-Glcp', 'a-D-Galp-1-3-b-D-Galp', 'b-D-Galp-1-6-b-D-Galp']
disaccharides_red = CheSweet()
disaccharides_full... |
import asyncio
from unittest import mock
import pytest
from multidict import CIMultiDict
from aiohttp import WSMessage, WSMsgType, helpers, signals
from aiohttp.log import ws_logger
from aiohttp.test_utils import make_mocked_coro, make_mocked_request
from aiohttp.web import HTTPBadRequest, HTTPMethodNotAllowed, WebSo... |
#!/usr/bin/env python
import flask
import graphviz
import os
from contextlib import contextmanager
from functools import partial
from shutil import rmtree
from tempfile import mkdtemp
try:
# Python 3
from urllib.parse import urljoin
except ImportError:
# Python 2
from urlparse import urljoin
from ls... |
__author__ = "Brian O'Neill"
__version__ = '0.2.1'
import doctest
def main__record_history():
"""
# [The *record_history* decorator](id:record_history-decorator)
The `record_history` decorator is a stripped-down version of `log_calls` which
records calls to a decorated function but writes no messages. You can th... |
'''
Precise and fast Fermi-Dirac integrals of integer and half integer order.
[1] T. Fukushima, "Precise and fast computation of Fermi-Dirac integral of
integer and half integer order by piecewise minimax rational approximation,"
Applied Mathematics and Computation, vol. 259, pp. 708-729, May 2015.
DOI... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
r"""
flake8: noqa
script to help me figure out where things are used.
it is not named well
set PATH=%HOME%\code\utool\utool\util_scripts;%PATH%
classfuncs.py %HOME%/code/ibeis/ibeis/control/IBEISControl.py %HOME%/code/ibeis
classfuncs.py C:/Users/joncrall/code/ibeis/ibe... |
from __future__ import unicode_literals
import frappe
import urllib
from frappe.utils import nowdate, cint, cstr
from frappe.utils.nestedset import NestedSet
from frappe.website.website_generator import WebsiteGenerator
from frappe.website.render import clear_cache
from frappe.website.doctype.website_slideshow.website_... |
from __future__ import unicode_literals
from django.contrib.auth.models import Permission, User
from django.http import HttpRequest
from django.template import Context, Template
from djblets.testing.decorators import add_fixtures
from reviewboard.accounts.models import LocalSiteProfile
from reviewboard.site.context_p... |
from __future__ import division
import pytest
import numpy as np
import nnabla as nn
import nnabla.functions as F
import refs
from nbla_test_utils import list_context
ctxs = list_context('BinaryWeightConvolution')
def binarize_kernel(x, quantize_zero_to):
""" Performs binarization of one kernel """
y = np.si... |
from django.shortcuts import render
# Create your views here.
from django.http import *
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from users... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0003_auto_20151011_1724'),
]
operations = [
migrations.AddField(
model_name='draft',
name='d... |
from __future__ import absolute_import
from __future__ import unicode_literals
import logging
from docker.errors import NotFound
from docker.types import IPAMConfig
from docker.types import IPAMPool
from docker.utils import version_gte
from docker.utils import version_lt
from .config import ConfigurationError
from .... |
"""
Copyright (c) 2012-2020 RockStor, Inc. <http://rockstor.com>
This file is part of RockStor.
RockStor 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 2 of the License,
or (at your option) any la... |
import ipywidgets as widgets
from traitlets import Unicode, Any
# See js/lib/widgets.js for the frontend counterpart to this file.
@widgets.register
class DataTable(widgets.DOMWidget):
"""Progressivis DataTable widget."""
# Name of the widget view class in front-end
_view_name = Unicode('DataTableView')... |
"""
Views for user API
"""
from courseware.model_data import FieldDataCache
from courseware.module_render import get_module_for_descriptor
from django.shortcuts import redirect
from django.utils import dateparse
from rest_framework import generics, permissions, views
from rest_framework.authentication import OAuth2A... |
import pythonwifi
import time
import datetime
import socket
import random
import os
import json
import requests
from pythonwifi import iwlibs
from pythonwifi.iwlibs import Wireless
from subprocess import Popen, PIPE
user = 'ofer_linux'
count = 0
hostname = socket.gethostname()
while True:
process = Popen(["iwlist... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
int_or_none,
remove_end,
)
class GameStarIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?game(?P<site>pro|star)\.de/videos/.*,(?P<id>[0-9]+)\.html'
_TESTS = [{
'url': 'http://www.game... |
import re
from nova import exception
from nova.i18n import _
# Define the minimum and maximum version of the API across all of the
# REST API. The format of the version is:
# X.Y where:
#
# - X will only be changed if a significant backwards incompatible API
# change is made which affects the API as whole. That is, s... |
"""Support for Eufy devices."""
import logging
import lakeside
import voluptuous as vol
from homeassistant.const import (
CONF_ACCESS_TOKEN,
CONF_ADDRESS,
CONF_DEVICES,
CONF_NAME,
CONF_PASSWORD,
CONF_TYPE,
CONF_USERNAME,
)
from homeassistant.helpers import discovery
import homeassistant.he... |
"""Our workflows."""
from __future__ import absolute_import, division, print_function
from .article import Article # noqa: F401
from .author import Author # noqa: F401
from .manual_merge import ManualMerge # noqa: F401 |
#!/usr/bin/python3
"""Provides the ReverseDNS class for reverse DNS lookups
Performs IP address to domain name lookups from the systems DNS server
and stores the results in JSON format to allow for dictionary lookups.
If previous results are loaded in, it will perform the lookup
on the dictionary corresponding to the ... |
#!/usr/bin/python
import smbus
import struct
#import array
import math
#from ctypes import *
bus = smbus.SMBus(1)
class MPU6050Data:
def __init__(self):
self.Gx=0
self.Gy=0
self.Gz=0
self.Temperature=0
self.Gyrox=0
self.Gyroy=0
self.Gyroz=0
class MPU6050:
AccelerationFa... |
from plugin import FileChangeConditionPlugin, PLUGIN_CONST, plugin_name
# Gtk might be needed: uncomment if this is the case
# from gi.repository import Gtk
# setup localization for both plugin text and configuration pane
# locale.setlocale(locale.LC_ALL, locale.getlocale())
# locale.bindtextdomain(APP_NAME, APP_LOC... |
import flextls
import ssl
def convert_version2method(protocol_version):
"""
Convert internal protocol version ID to Python SSL method.
:param Integer protocol_version: Version ID
:return: OpenSSL method or None if not found
:rtype: OpenSSL method or None
"""
if protocol_version == flextls.... |
from __future__ import absolute_import
from builtins import map
from builtins import object
from ..util import get_base_app_name
from ..error import RestError
__all__ = [
'RestModel',
'RestEndpoint',
'SingleModel',
'MultipleModel',
'DataInputModel',
]
class RestModel(object):
def __init__(... |
"""Takes a generator of values, and accumulates them for a frontend."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import threading
from tensorflow.python.platform import gfile
from tensorflow.python.platform import logging
from tens... |
import os
import unittest
from cStringIO import StringIO
from pyptlib.config import EnvError, Config
class PluginCoreTestMixin(object):
"""
This class is not a TestCase but is meant to be mixed-into tests
for subclasses of TransportPlugin.
"""
pluginType = None
origEnv = os.environ
def s... |
import os
import shutil
import sys
import logging
from distutils.spawn import find_executable
from tools.wpt.utils import call
logger = logging.getLogger(__name__)
class Virtualenv(object):
def __init__(self, path):
self.path = path
self.virtualenv = find_executable("virtualenv")
if not s... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os;
import sys;
import datetime;
import string;
import shutil;
EPSILON = 1e-10;
Product_volume_dict = {};
START_TIME='09:20:00';
END_TIME='14:55:00';
if len(sys.argv) != 5:
print 'Usage: ./cmd src_md_dir dest_dir from_date(YYYYMMHH) to_date(YYYYMMHH)';
quit();
... |
from .arm_base_model_py3 import ARMBaseModel
class DataBoxEdgeDevice(ARMBaseModel):
"""The Data Box Edge/Gateway device.
Variables are only populated by the server, and will be ignored when
sending a request.
All required parameters must be populated in order to send to Azure.
:ivar id: The pat... |
from app.gloveSim import gloveSim
from app.utils import read_csv, lemmatize_an_idea
import random
import pickle
import cProfile
import timeit
TOPICS = {
'weddingTheme': 'topicWords/wedding_themes_collapsed_5.csv',
'weddingProp': 'topicWords/wedding_props_collapsed_5.csv'
}
with open('app/theme_dict_set.p')... |
from __future__ import unicode_literals
from moto.core.exceptions import JsonRESTError
class NotFoundException(JsonRESTError):
code = 400
def __init__(self, message):
super(NotFoundException, self).__init__("NotFoundException", message)
class ValidationException(JsonRESTError):
code = 400
... |
from tqdm import tqdm
import json
import numpy as np
from collections import defaultdict
import csv
import random
import os
class RelationEntityBatcher():
def __init__(self, input_dir, batch_size, entity_vocab, relation_vocab, mode = "train"):
self.input_dir = input_dir
self.input_file = input_dir... |
import errno
import logging
import os
import shlex
from webkitpy.layout_tests.breakpad.dump_reader import DumpReader
_log = logging.getLogger(__name__)
class DumpReaderWin(DumpReader):
"""DumpReader for windows breakpad."""
def __init__(self, host, build_dir):
super(DumpReaderWin, self).__init__(h... |
#
"""Sliver manager API.
This module exposes an XMLRPC interface that allows PlanetLab users to
create/destroy slivers with delegated instantiation, start and stop
slivers, make resource loans, and examine resource allocations. The
XMLRPC is provided on a localhost-only TCP port as well as via a Unix
domain socket th... |
import cle
import io
import logging
import os
import re
from .plugin import SimStatePlugin
from ..errors import SimConcreteRegisterError
from archinfo import ArchX86, ArchAMD64
l = logging.getLogger("state_plugin.concrete")
#l.setLevel(logging.DEBUG)
class Concrete(SimStatePlugin):
def __init__(self, segment_r... |
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this ... |
from __future__ import absolute_import
import copy
import mock
from sentry.models import (
ApiKey, AuditLogEntry, AuditLogEntryEvent, Commit, File, OrganizationMember,
OrganizationMemberTeam, OrganizationOption, Project, Release, ReleaseCommit,
ReleaseEnvironment, ReleaseFile, Team, TotpInterface, User,
)... |
"""
Basic admin screens to search and edit InstructorTasks.
This will mostly involve searching by course_id or task_id and manually failing
a task.
"""
from config_models.admin import ConfigurationModelAdmin
from django.contrib import admin
from .models import InstructorTask
from .config.models import GradeReportSett... |
#!/usr/bin/env python
"""
Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
from lib.core.exception import SqlmapUnsupportedFeatureException
from plugins.generic.takeover import Takeover as GenericTakeover
class Takeover(GenericTakeover):
def __i... |
"""Allow staff to add notes to nicks"""
""" Copyright 2013 ActiveState Software Inc. """
import re
from madcow.util import Module
from madcow.util.text import *
from madcow.conf import settings
from learn import Main as Learn
from staff import Main as Staff
from datetime import datetime
import os
try:
import dbm... |
import itertools
import re
import logging
log = logging.getLogger(__name__)
class InvocationPattern:
def __init__(self, insn, value, i=None):
self.insn = insn
self.value = value
self.i = i
class CodeFlows:
@staticmethod
def callers_of(store, method):
yield from store.query().callers_of(method)
... |
from buildbot.steps.source.git import Git
class Gerrit(Git):
def __init__(self, **kwargs):
Git.__init__(self, **kwargs)
def startVC(self, branch, revision, patch):
gerrit_branch = None
if self.build.hasProperty("event.patchSet.ref"):
gerrit_branch = self.build.getProperty... |
{
'name': "mrp_send_to_production",
'summary': """
Adds a state in a manufacturing order that says
we have sent to production floor
""",
'description': """
Adds a state in a manufacturing order that says
we have sent to production floor
""",
'author': "John... |
from __future__ import print_function
cube_corner_position_offsets = [
[0, 0, 0], #
[1, 0, 0],
[1, 1, 0],
[0, 1, 0],
[0, 0, 1],
[1, 0, 1],
[1, 1, 1],
[0, 1, 1]
]
cube_edge_index_to_corner_index_pair_table = [
[0, 1],
[1, 2],
[3, 2],
[0, 3],
[4, 5],
[5, 6],
... |
"""
Unit Tests for :py:class:`ironic.conductor.rpcapi.ConductorAPI`.
"""
import copy
import mock
from oslo.config import cfg
from ironic.common import boot_devices
from ironic.common import exception
from ironic.common import states
from ironic.conductor import manager as conductor_manager
from ironic.conductor impo... |
import numpy as np
from astropy.table import Table
from astropy.io import fits
import matplotlib.pyplot as plt
import matplotlib
import pickle
from os.path import isfile, join
from os import listdir
from astropy.time import Time
pkl_file = open('wl.pkl', 'rb')
wl = pickle.load(pkl_file)
pkl_file.close()
#Now ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import json
try:
from pymisp import MISPEncode
from pymisp.tools import make_binary_objects
except ImportError:
pass
def check():
missing_dependencies = {'pydeep': False, 'lief': False, 'magic': False, 'pymisp': False}
try:
i... |
import logging
from datetime import datetime
from dateutil.relativedelta import relativedelta
from odoo import api, models, fields
from odoo.addons.child_compassion.models.compassion_hold import HoldType
from odoo.addons.queue_job.job import job
from .sms_child_request import DEFAULT_MAX_AGE
# How many children are p... |
# This is an example of how to connect to and use the Bitmessage API.
# See https://bitmessage.org/wiki/API_Reference
import xmlrpclib
import json
api = xmlrpclib.ServerProxy("http://bradley:password@localhost:8442/")
print 'Let\'s test the API first.'
inputstr1 = "hello"
inputstr2 = "world"
print api.helloWorld(inp... |
from unittest import mock
import oslo_messaging
from oslo_utils import uuidutils
from neutron.api.rpc.callbacks import events
from neutron.api.rpc.callbacks import resources
from neutron.objects import trunk as trunk_obj
from neutron.services.trunk.drivers.openvswitch.agent import driver
from neutron.services.trunk.d... |
"""
Run a large scale benchmark.
We measure: {dataset, encoder, model, train and test accuracy measures, train and test runtimes, feature count}.
Note: A reasonably recent version of sklearn is required to run GradientBoostingClassifier and MLPClassifier.
"""
import os
import pandas as pd
import numpy as np
from skl... |
import GemRB
from GUIDefines import *
PartyFormationWindow = 0
ExitWindow = 0
ReviewWindow = 0
def OnLoad ():
global PartyFormationWindow
PartyFormationWindow = GemRB.LoadWindow (0, "GUISP")
ExitButton = PartyFormationWindow.GetControl (30)
ExitButton.SetText (13906)
ExitButton.SetEvent (IE_GUI_BUTTON_ON_PRESS,... |
'''
A script to check that the (Linux) executables produced by gitian only contain
allowed gcc, glibc and libstdc++ version symbols. This makes sure they are
still compatible with the minimum supported Linux distribution versions.
Example usage:
find ../gitian-builder/build -type f -executable | xargs python con... |
#! /usr/bin/env ipython
"""
GUI for the analysis of data from MRS experiments
-------------------------------------------------
This GUI (graphical user interface) will do the following:
- Load data from a p-file
- Display spectra (on, off and diff), while allowing dynamic changing of:
- Line-widening
- phase... |
from __future__ import annotations # isort:skip
import pytest ; pytest
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Bokeh imports
from bokeh._testing.util.api import verify_all
# Module under... |
import sys
import time
import unittest
from winlogbeat import WriteReadTest
if sys.platform.startswith("win"):
import win32security
"""
Contains tests for reading from the Event Logging API (pre MS Vista).
"""
@unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
class Test(WriteReadTest):
... |
__author__ = ['Salvador Aguinaga', 'Rodrigo Palacios', 'David Chaing', 'Tim Weninger']
import networkx as nx
import numpy as np
class Rule(object):
def __init__(self, id, lhs, rhs, prob, translate=True):
self.id = id
self.lhs = lhs
if translate:
self.rhs = rhs
self... |
from django.contrib.auth.models import AnonymousUser
from django.test.client import RequestFactory
from nose.tools import ok_
from mkt.site.tests import ESTestCase, TestCase, app_factory
from mkt.tags.models import Tag
from mkt.tvplace.serializers import (TVAppSerializer, TVESAppSerializer,
... |
#!/usr/bin/python2
import sys, os
# Check python version number
if sys.version_info[:2] != (2, 6) and sys.version_info[:2] != (2, 7):
raw_input("Error: Use Python version 2.6 or 2.7")
sys.exit(1)
# Check if PyQt4 is installed
try:
from PyQt4 import QtCore, QtGui
except ImportError, err:
print "Import... |
# ----------------------------------------------------------------------------------------------------------------------
class DefaultConfig(object):
DEBUG = False
TESTING = False
SQLALCHEMY_DATABASE_URI = 'sqlite:///babyshortener.db'
BLUEPRINTS_LOCATION = 'babyshortener.blueprints'
SQLALCHEMY_TRA... |
import conftest
from PathPlanning.GridBasedSweepCPP \
import grid_based_sweep_coverage_path_planner
grid_based_sweep_coverage_path_planner.do_animation = False
RIGHT = grid_based_sweep_coverage_path_planner. \
SweepSearcher.MovingDirection.RIGHT
LEFT = grid_based_sweep_coverage_path_planner. \
SweepSearche... |
#!/usr/bin/env python
""" Assignment 1, Exercise 1, INF1340, Fall, 2014. Grade to gpa conversion
This module prints the amount of money that Lakshmi has remaining
after the stock transactions
"""
__author__ = 'Susan Sim'
__email__ = "<EMAIL>"
__copyright__ = "2015 Susan Sim"
__license__ = "MIT License"
money = 10... |
import json
import time
from six.moves import http_client
from tests.api import controllers
class TestRun(controllers.APITest):
def _wait_for_run_complete(self, id):
counter = 0
while counter < self.counter:
res = self.app.get('/runs/{}'.format(id))
res_dict = json.loads... |
#!/usr/bin/env python
'''
Make predictions for the test data
{'C': [0.001, 0.01, 0.1, 1.0, 10., 100.]}
'''
import argparse, logging
import cPickle as pickle
import numpy as np
from common import *
from sklearn.linear_model import LogisticRegression
logging.basicConfig(level=logging.DEBUG)
def opts():
parser = a... |
"""
Provide a "ticket" interface with a request tracker.
Please see the help/hacking/bibcatalog-api page for details.
This is a base class that cannot be instantiated.
"""
from invenio.webuser import get_user_preferences
class BibCatalogSystem(object):
""" A template class for ticket support."""
TICKET_ATTRI... |
'''Manual Data Input - issue a single line of g-code to the running system
mdi.py may be specified on the commandline, e.g.,
bin/mdi configs/sim/emc.nml g0 x0
'''
import sys, os
import emc
if len(sys.argv) > 1:
emc.nmlfile = sys.argv[1]
del sys.argv[1]
c = emc.command()
s = emc.stat()
if len(sys.arg... |
# -*- coding: utf-8 -*-
"""
Multiple Linear regression in python - code example
- Considered mupltiple dependent variables
- Formula:
y = b0 + b1.x1 + b2.x2 + b3.x3 + ..... + bN.xN
y = dependent variable
x1, x2, ..., xN = Independent variables
b0 = offset/constant
b1, b2, ..., bN = coeffi... |
from cloudinit.config import cc_landscape
from cloudinit import (distros, helpers, cloud, util)
from cloudinit.sources import DataSourceNone
from cloudinit.tests.helpers import (FilesystemMockingTestCase, mock,
wrap_and_call)
from configobj import ConfigObj
import logging
LOG = l... |
from sys import argv
from os import system, getcwd, chdir
def setup_git_repo(repo, rev):
ori_dir = getcwd();
chdir(repo);
system("git checkout -f " + rev);
system("git clean -f -d");
chdir(ori_dir);
def build_repo(repo, build_cmd, deps_dir):
if deps_dir == "":
cmd = build_cmd + " " + r... |
from pyspark.sql import SparkSession
from pyspark.mllib.linalg import SparseVector, VectorUDT, Vectors
from pyspark.sql.types import *
import numpy as np
#initialize spark session
spark = SparkSession\
.builder\
.appName("Test")\
.config('spark.sql.warehouse.dir', 'file:///C:/')\
.getOr... |
r"""JSON (JavaScript Object Notation) <http://json.org> is a subset of
JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
interchange format.
:mod:`json` exposes an API familiar to users of the standard library
:mod:`marshal` and :mod:`pickle` modules. It is the externally maintained
version of the :m... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
'''Pychemqt, Chemical Engineering Process simulator
Copyright (C) 2009-2017, Juan José Gómez Romera <<EMAIL>>
This program 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 Foundatio... |
import json
import re
import xml.etree.ElementTree as ET
def lower_camel(string):
if not string or '_' not in string:
return string
result = "".join([x.title() for x in string.split('_')])
return result[0].lower() + result[1:]
def format_language(language):
"""
Attempt to format languag... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.