code
stringlengths
1
199k
n, m = map(int, input().split()) voices = [0 for i in range(n)] for i in range(m): b = input() if b.count('+') == 1: voices[b.index('+')] += 1 sum_voices = sum(voices) for i in range(n): if 100 * voices[i] >= 7 * sum_voices: print(i+1, end=' ') print()
from alvi.client.scenes.sort import Sort class InsertionSort(Sort): def sort(self, **kwargs): array = kwargs['container'] right_marker = array.create_marker("right", 0) left_marker = array.create_marker("left", 0) left1_marker = array.create_marker("left+1", 0) array.sync() ...
import requests import csv from bs4 import BeautifulSoup from time import strftime import re CH_url = "https://washingtondc.craigslist.org/search/apa?query=Columbia%20Heights&s=0" AM_url = "https://washingtondc.craigslist.org/search/apa?query=Adams%20Morgan&s=0" def scraper(url): #Retrieve and parse url r = req...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('climatemodels', '0093_auto_20190326_1338'), ] operations = [ migrations.AddField( model_name='forests', name='assimilation', ...
import RPi.GPIO as GPIO import time GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) ENP = 32 CWP = 37 CPP = 38 ENG = 40 GPIO.setup(ENP, GPIO.OUT) GPIO.setup(ENG, GPIO.OUT) GPIO.setup(CWP, GPIO.OUT) GPIO.setup(CPP, GPIO.OUT) def forward(delay): setStep(1, 0, 1, 0) time.sleep(delay) setStep(1, 1, 1, 0) time.slee...
import os import numpy as np from fairseq.data import FairseqDataset from . import data_utils from .collaters import Seq2SeqCollater class AsrDataset(FairseqDataset): """ A dataset representing speech and corresponding transcription. Args: aud_paths: (List[str]): A list of str with paths to audio fi...
""" Django settings for dcatcher project. Generated by 'django-admin startproject' using Django 1.10.6. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os BA...
import numpy as np MAX_FLOAT = np.finfo(0.0).max class Activation(object): def __init__(self): pass @staticmethod def get(name): nl = name.lower() if nl == "sigmoid": return Activation().sigmoid if nl == "linear": return Activation().linear if ...
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('crm', '0005_auto_20160729_1531'), ('registration', '0003_auto_20161104_0936'), ] operations = [ migrations.Remov...
from pyvisdk.thirdparty import Enum AffinityType = Enum( 'cpu', 'memory', )
def get_request_body_as_dict(request): """ Expects UTF-8 :param request: :return: """ import json as j try: b_e = request.body.decode('utf-8') b = j.loads(b_e) return b except Exception as e: return None
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('taskmanager', '0002_auto_20150708_1158'), ] operations = [ migrations.AlterField( model_name='project', name='user', ...
import weakref import asyncio import logging import sse from django.conf import settings from .exceptions import MethodNotAllowed logger = logging.getLogger(__name__) class Stream(sse.Handler): redis = None dispatcher = None http_method_names = ['get', ] @asyncio.coroutine def handle_request(self): ...
import os import unicodedata import re import itertools import csv import argparse global __showwarnings, __showinfo def loginfo(str): """Utility function to log information""" if __showinfo: print(str) def logwarning(str): """Utility function to log warnings""" if __showwarnings: print(...
from __future__ import unicode_literals import json import os from collections import namedtuple import six from packaging.requirements import Requirement from packaging.utils import canonicalize_name from tox import reporter from tox.config import DepConfig, get_py_project_toml from tox.constants import BUILD_ISOLATED...
import math import pygame import time screensize = (600,600) scale = 250 center = (-0.7,0) iterations = 30 colour = (0.2,0.6,1) #Sort of a sky-blue-ish colour---------------------------# screen = pygame.display.set_mode(screensize) def pixel_change(position,colour): screen.set_at(position,colour) def vector_square(i):...
import redis r = redis.StrictRedis(host='localhost', port=6379, db=0) def add_bind(wxid,stuid,cardpw,jwcpw): r.hdel(wxid,'stuid') r.hdel(wxid,'cardpw') r.hdel(wxid,'jwcpw') r.hset(wxid,'stuid',stuid) r.hset(wxid,'cardpw',cardpw) r.hset(wxid,'jwcpw',jwcpw) def get_info(wxid): return r.hgetall...
import _plotly_utils.basevalidators class Tick0Validator(_plotly_utils.basevalidators.AnyValidator): def __init__( self, plotly_name="tick0", parent_name="scattercarpet.marker.colorbar", **kwargs ): super(Tick0Validator, self).__init__( plotly_name=plotly_name, parent_nam...
import _plotly_utils.basevalidators class BgcolorValidator(_plotly_utils.basevalidators.ColorValidator): def __init__( self, plotly_name="bgcolor", parent_name="isosurface.hoverlabel", **kwargs ): super(BgcolorValidator, self).__init__( plotly_name=plotly_name, parent_nam...
"""1D and 2D Wavelet packet transform module.""" from __future__ import division, print_function, absolute_import __all__ = ["BaseNode", "Node", "WaveletPacket", "Node2D", "WaveletPacket2D"] import numpy as np from ._extensions._pywt import Wavelet from ._dwt import dwt, idwt, dwt_max_level from ._multidim import dwt2,...
import sys import time import math import random import util import numpy as np import theano import theano.tensor as T from nn_utils import sample_weights, relu from optimizers import sgd, ada_grad theano.config.floatX = 'float32' class Model(object): def __init__(self, x, y, n_words, batch_size, opt, lr, init_emb...
""" Support for HarpJS books @see http://harpjs.com/ @see http://odewahn.github.io/docker-jumpstart/ @see https://github.com/macbre/mobify/issues/10 """ import re from mobify.source import MultiChapterSource, MobifySource class HarpMainSource(MultiChapterSource): """ This will return a set of sources for each s...
""" Contains GUI forms for the Voronoi neighbours filter. """ from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals from . import base from ...filtering.filters import voronoiNeighboursFilter class VoronoiNeighboursSettingsDialog(base.GenericSettingsDialog)...
import glob import os import sys import urllib.request import django sys.path.append("/var/projects/museum/") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "z2.settings") django.setup() from z2_site.models import * from comic.models import * def main(): with open("shell.log", "w") as fh: command = input("...
import numpy as np from sklearn.svm import LinearSVC from logs import logger class SVMClassifier: def load(self, dataset): logger.info("[svm classifier start loading dataset]") dataset.create_tfidf_dataset() self.dataset = dataset def fit(self): logger.info("[svm classifier start...
import matplotlib.pyplot as plt import matplotlib.lines as mlines js = [5, 20, 100] d = 1 def storage(d, f): return d * f def bandwidth(j, d, f): return j * storage(d, f) * 8 #8bit = 1 byte x = [] s = [] for f in range(4, 240, 16): w = f*24*7 x.append(f) s.append(storage(d, w)) line = plt.plot(x, s)...
import os; link = "http://media.blizzard.com/heroes/images/battlegrounds/maps/infernal-shrines/main/6/" column = 0; rc_column = 0; while (rc_column == 0): row = 0; rc_column = os.system('wget ' + link + str(column) + '/' + str(row) + '.jpg -O ' + str(1000 + column) + '-' + str(1000 + row) + '.jpg') rc_row = rc_colum...
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: url(r'^$', 'alarms.views.index', name='home'), url(r'^clocks/', include('clocks.urls')), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(ad...
import os path = os.path.dirname(os.path.realpath(__file__)) sbmlFilePath = os.path.join(path, 'BIOMD0000000357.xml') with open(sbmlFilePath,'r') as f: sbmlString = f.read() def module_exists(module_name): try: __import__(module_name) except ImportError: return False else: return...
from setuptools import setup, find_packages setup(name='MODEL1208280001', version=20140916, description='MODEL1208280001 from BioModels', url='http://www.ebi.ac.uk/biomodels-main/MODEL1208280001', maintainer='Stanley Gu', maintainer_url='stanleygu@gmail.com', packages=find_packages()...
from dataactcore.models.baseInterface import BaseInterface from dataactcore.models.userModel import UserStatus class UserInterface(BaseInterface): """Manages all interaction with the user database.""" def __init__(self): super(UserInterface, self).__init__() def getUserStatusId(self, statusName): ...
import sqlalchemy as sa from uuid import uuid4 from sqlalchemy.dialects import postgresql from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine, MetaData from datetime import datetime from sqlalchemy.orm import sessionmaker Base = declarativ...
import hashmap states = hashmap.new() hashmap.set(states, 'Oregon', 'OR') hashmap.set(states, 'Florida', 'FL') hashmap.set(states, 'Califonia', 'CA') hashmap.set(states, 'New York', 'NY') hashmap.set(states, 'Michigan', 'MI') cities = hashmap.new() hashmap.set(cities, 'CA', 'San Francisco') hashmap.set(cities, 'MI', 'D...
""" Created on Mon May 11 16:57:58 2015 @author: Cristian """ def CorrMatFile(DsFile,CorrFile): import pandas as pd df=pd.read_csv(DsFile) # read CSV dataset df_corr= df.corr() # get correlation matrix for ds df_corr.to_csv(CorrFile) # print to file the corralation matrix return CorrMatFile(...
import os path = os.path.dirname(os.path.realpath(__file__)) sbmlFilePath = os.path.join(path, 'MODEL1310110021.xml') with open(sbmlFilePath,'r') as f: sbmlString = f.read() def module_exists(module_name): try: __import__(module_name) except ImportError: return False else: return...
class Solution: # @param root, a tree link node # @return nothing def connect(self, root): if root == None: return parent = root parent.next = None while parent != None: last, first = None, None while parent != None: for nod...
"""Webcrawler tests for reachability and HTML validation. The crawler attempts to retrieve any NAV web UI page that can be reached with parameterless GET requests, while logged in as an administrator. We want one test for each such URL, but since generating more tests while running existing tests isn't easily supported...
import robot import math import gui import random import sensFilters import controller def draw(screen,robot,pwmRatio): """ Called by the simulation to display the current state of the robot. """ #Get the robot state state = robot.getState() # Map robot angles to the screen coordinate system ...
def speedupFileStorageTxnLookup(): """Speed up lookup of start position when instantiating an iterator FileStorage does not index the file positions of transactions. With this patch, we use the existing {oid->file_pos} index to bisect the the closest file position to start iterating. """ from ar...
""" The Quick Insert panel widget. """ from __future__ import unicode_literals import weakref from PyQt4.QtGui import QVBoxLayout, QWidget class Tool(QWidget): """Base class for a tool in the quick insert panel toolbox. """ def __init__(self, panel): super(Tool, self).__init__(panel) self._p...
from src.tools.dialog import dialog from src.tools.addonSettings import string as st def confirmDialog(cSource, collection): HEADING = st(830) LINE1 = st(831) %(cSource.typeText(), cSource.title(), collection.title) return dialog.yesno(HEADING, LINE1) def successDialog(cSource, collection): HEADING ...
import sys import re import logging import time from datetime import datetime, timedelta import json import solr as solrpy from hdfs import InsecureClient import html2text SOLR_INDEX = 'http://144.76.155.175:5555/solr' PAGE_SIZE = 1000 MAX_RESULTS = 10000 SEARCH_FIELD = 'pageContent' DATE_FIELD = 'timeDownloaded' CRAWL...
"Communication with Bayer Contour USB meter" import usbcomm import re import time class FrameError(Exception): pass class BayerCOMM(object): "Framing for Bayer meters" framere = re.compile('\x02(?P<check>(?P<recno>[0-7])(?P<text>[^\x0d]*)' '\x0d(?P<end>[\x03\x17]))' ...
import logging from gettext import gettext as _ from httplib import NOT_FOUND, INTERNAL_SERVER_ERROR from urlparse import urlparse from mongoengine import DoesNotExist, NotUniqueError from nectar.listener import AggregatingEventListener from requests import Session from twisted.internet import reactor from twisted.web....
"""grid_search_vw.py Use grid search to find optimal parameters combinations: learning_rate, l1, l2, threshold ... For every combination, cross validation is used to calculate average score. Author: lifematrix <stevenliucx@gmail.com> """ from subprocess import check_call import logging from utils import initlog, getlog...
from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) exce...
import unittest <<<<<<< HEAD from meld.matchers import myers ======= from meld import matchers >>>>>>> c3a7c7d9b1b263e97a8640a8fe230e12e46f75cf class MatchersTests(unittest.TestCase): def testBasicMatcher(self): a = list('abcbdefgabcdefg') b = list('gfabcdefcd') r = [(0, 2, 3), (4, 5, 3), (1...
from skin import parseColor, parseFont from Components.config import config, ConfigClock, ConfigInteger, ConfigSubsection, ConfigYesNo, ConfigSelection, ConfigSelectionNumber from Components.Pixmap import Pixmap from Components.Button import Button from Components.ActionMap import HelpableActionMap from Components.GUIC...
from pyanaconda.installclass import BaseInstallClass from pyanaconda.constants import * from pyanaconda.product import * from pyanaconda.flags import flags from pyanaconda import iutil import os, types import gettext _ = lambda x: gettext.ldgettext("anaconda", x) from pyanaconda import installmethod from pyanaconda imp...
"""This module implements miscellaneous convenience functions.""" __author__ = 'Nathaniel Case, David Woods <dwoods@wcer.wisc.edu>' import string, sys # return mx.DateTime.DateTimeFrom(datestr) def dt_to_datestr(dt): """Return a localized date string for the given DateTime object.""" # FIXME: l10n: Does...
""" Flaskr ~~~~~~ flaskr sample """ from sqlite3 import dbapi2 as sqlite3 from flask import Flask, request, session, g, redirect, url_for, abort, \ render_template, flash app = Flask(__name__) app.config.update(dict( DATABASE='/tmp/mypyblog.db', DEBUG=True, SECRET_KEY='development key', USERNAME='a...
import os, re, sys if len(sys.argv) == 2: assert sys.argv[1] == '-f' delete = True else: assert len(sys.argv) == 1 delete = False hyps = {} hypre = re.compile("hypothesis.label-([A-Z]+).l1_penalty-([0-9\.e\+\-]+)$") for f in os.listdir("."): res = hypre.match(f) if res: lbl = res.group(1) dloss = float(res.gr...
Home Web Server <=r1.7.1 (build 147) "Gui Thread-Memory Corruption Exploit." By: Aodrulez. Homepage : http://downstairs.dnsalias.net/homewebserver.html Product Released : 22.4.2009/21:16:58 Description: This web server when fed with 1006 bytes of chr(0x0d),with the html "GET" parameter,the Server's Gui's Thr...
from __future__ import print_function, division, absolute_import import datetime import logging from rhsm import certificate from subscription_manager import certlib from subscription_manager import entcertlib from subscription_manager import injection as inj log = logging.getLogger(__name__) class HealingActionInvoker...
"""cairn.cmds.meta.Extract""" from cairn import Options from cairn.cmds.Command import Command class Extract(Command): def __init__(self, libname, fullCmdLine, parent): super(Extract, self).__init__(libname, fullCmdLine) self._parent = parent return def parent(self): return self._parent def getModuleString(s...
import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "libra.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
""" This class transforms an eXe node into a page on a self-contained website """ import logging import re from cgi import escape from urllib import quote from exe.webui.blockfactory import g_blockFactory from exe.engine.error import Error from exe.engine.path i...
"""Library for event testing. """ from cached_property import cached_property from contextlib import contextmanager from collections import Iterable from datetime import datetime from numbers import Number from sqlalchemy.sql.expression import func from time import sleep from threading import Thread, Event as ThreadEve...
from opentech.apply.funds.management.commands.migration_base import MigrateCommand class Command(MigrateCommand): CONTENT_TYPE = "fund" FUND_NAME = "Rapid Response (archive fund)" ROUND_NAME = "Rapid Response (archive round)" APPLICATION_TYPE = "request" STREAMFIELD_MAP = { "title": { ...
import os.path as path from SecuML.core.Data import labels_tools from SecuML.core.Tools.Plots.BarPlot import BarPlot from SecuML.core.Tools.Plots.PlotDataset import PlotDataset from SecuML.core.Tools import colors_tools class PredictionsBarplots(object): def __init__(self, has_ground_truth): self.ranges = [...
from edc_constants.choices import YES, NO from edc_constants.constants import CONTINUOUS, RESTARTED, OTHER, STOPPED, NOT_APPLICABLE, NEW from microbiome.apps.mb.constants import LIVE, STILL_BIRTH LIVE_STILL_BIRTH = ( (LIVE, 'live birth'), (STILL_BIRTH, 'still birth') ) YES_NO_DNT_DWTA = ( (YES, YES), (N...
import os import psycopg2 import sys file = open("/home/" + os.getlogin() + "/.pgpass", "r") pgpasses = [] for line in file: pgpasses.append(line.rstrip("\n").split(":")) file.close() for pgpass in pgpasses: #print str(pgpass) if pgpass[0] == "54.236.235.110" and pgpass[3] == "geonode": src_pgpass = pgpass ...
import urllib def get_exchange_rate(rate_type = "", title_initial = 0, rate_initial = 0, rate_offset = 0, url = "http://www.combanketh.et/More/CurrencyRate.aspx"): try: page = urllib.urlopen(url) text = page.read().decode("utf8", "ignore") except IOError: return False title_offset = ...
x = "There are %d types of people." % 10 binary = "binary" do_not = "don't" y = "Those who know %s and those who %s." % (binary, do_not) print x print y print "I said: %r." % x print "I also said: '%s'." % y hilarious = False joke_evaluation = "Isn't that joke so funny?! %r" print joke_evaluation % hilarious w = "This ...
""" /********************************************************** Organization :AsymptopiaSoftware | Software@theLimit Website :www.asymptopia.org Author :Charles B. Cosse Email :ccosse@asymptopia.org Copyright :(C) 2006-2011 Asymptopia Software License ...
import sys,os,re import grass.script as grass def main(): if not os.environ.has_key("GISBASE"): print "You must be in GRASS GIS to run this program." sys.exit(1) fluxes = options['fluxes'] land = options['land'] out_importLines = options['lIm'] out_pointImport = options['pIm'] out_exportLines = options['lEx']...
from django.conf.urls import patterns, include, url import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'blogdemo.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'...
''' form.py Copyright 2006 Andres Riancho This file is part of w3af, w3af.sourceforge.net . w3af 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 version 2 of the License. w3af is distributed in the hope that it wil...
import random import pandas as pd from portfolio.models import Loan from risk_management.models import Scenario def generate_adjusted_assumptions(portfolio_id, scenario_id): scenario = Scenario.objects.get(pk=scenario_id) assumptions = scenario.assumption_profile loan_df = pd.DataFrame(list(Loan.objects.fil...
from . import keyEditorPlugin, recipeEditorPlugin plugins = [keyEditorPlugin.KeyEditorPlugin, recipeEditorPlugin.IngredientKeyEditorPlugin, recipeEditorPlugin.KeyEditorIngredientControllerPlugin, ]
""" Utility functions Can be used via a class or as functions""" import sys from PyFoam.ThirdParty.six import print_ from PyFoam.Error import warning,error import subprocess import os,fnmatch if sys.version_info<(2,6): from popen2 import popen4 else: from subprocess import Popen,PIPE,STDOUT from os import listd...
import serial import time import cv2 import numpy as np from userfunctions import * device = '/dev/ttyACM0' baudrate = '57600' ser = serial.Serial(device, baudrate) # open serial port @ baudrate print(ser.name + device + " @ " + baudrate + "bps chosen") # check which port was really used cap = cv2.VideoCaptur...
""" Placeholder for rhs productions that are not implemented """ from pynestml.meta_model.ast_expression_node import ASTExpressionNode from pynestml.symbols.error_type_symbol import ErrorTypeSymbol from pynestml.utils.logger import Logger, LoggingLevel from pynestml.utils.messages import Messages, MessageCode from pyne...
from __future__ import unicode_literals import datetime import re from .common import InfoExtractor from ..utils import ( ExtractorError, str_to_int, unified_strdate, ) class MotherlessIE(InfoExtractor): _VALID_URL = r'http://(?:www\.)?motherless\.com/(?:g/[a-z0-9_]+/)?(?P<id>[A-Z0-9]+)' _TESTS = [{...
""" @summary: This module will be a wrapper that can be mounted as a WSGI application with CherryPy and query a locally running Solr instance @author: CJ Grady """ import cherrypy import urllib2 from lmSolr import searchArchive SERVER = 'http://localhost:8983/solr/' CORE = 'lmArchive' class SolrWrapper(obj...
from enigma import getPrevAsciiCode from Tools.NumericalTextInput import NumericalTextInput from Tools.Directories import resolveFilename, SCOPE_CONFIG, fileExists from Components.Harddisk import harddiskmanager from copy import copy as copy_copy from os import path as os_path from time import localtime, strftime class...
from PyQt5.QtWidgets import QLabel class WeightLabel(QLabel): def __init__(self, parent=None): super(WeightLabel, self).__init__(parent) def setText(self, weight): if isinstance(weight, str): text = weight else: text = "{:0.2f} lbs".format(weight) super(We...
"""Module for handling information about a DNS host, e.g. a hardware box. A host is connected to a DnsOnwer, and contains information like L{HINFO} and L{TTL}. HostInfo was previously referenced to as "mreg" at UiO. You should be aware of this looking in the documentation. """ from Cerebrum.Entity import Entity from Ce...
import os from progressbar import * from modules.androguard import * from modules.androguard.core.analysis import * from modules.androlyze import * def list_calls_apks_in_dir(dir, l): """ Return a list with all API calls found in first l APK files in dir """ calls = [] for f in os.listdir(dir): if f...
__version__ = "${API_ENV_VERSION}" __all__ = ["apswvfs"]
""" Plarform Service API. Provides search, and serialization services """ import logging import request_handler as rh import exception import jsonpickle logging.basicConfig(level=logging.INFO) log = logging.getLogger(__name__) log.setLevel(logging.INFO) def get_platform_by_id(url, args): """ Retrieve platform recor...
"""CAP Deposit permissions.""" from functools import partial from flask import request from invenio_access.permissions import ParameterizedActionNeed, Permission from invenio_files_rest.models import Bucket from invenio_jsonschemas.errors import JSONSchemaNotFound from invenio_records_files.models import RecordsBuckets...
from __future__ import unicode_literals import os import lxml.etree as ET from collections import defaultdict from django.core.management.base import BaseCommand, CommandError from tqdm import tqdm from neutron.models import Word from .import_sm import Command as ImportSM, to_console class Command(BaseCommand): hel...
""" Include this to load these fixtures. """ def import_fixtures(self): """ Create simple fixture entries...""" self.redis.zadd('mundaneitem_quality', '{"name":"excellent", "score":100 }', 100) self.redis.zadd('mundaneitem_repair', '{"name":"in pristine condition", "score":100 }', 100) self.redis.lp...
from .base import * DEBUG = True INTERNAL_IPS = INTERNAL_IPS + ("",) DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.postgresql_psycopg2', # 'NAME': 'app_hgl_dev', # 'USER': 'app_hgl', # 'PASSWORD': '', # 'HOST': '' # }, } INTERNAL_IPS = ...
import sys import os from os.path import expanduser import re import copy from makediary.DT import DT class DotCalendar: """Read and parse the pcal(1) .calendar file. Information about the .calendar file is returned in a dictionary. The keys are tuples of (year,month,day). The values are a list of events ...
from Plugins.Plugin import PluginDescriptor from Screens.PluginBrowser import * from Screens.Ipkg import Ipkg from Components.Console import Console from Components.SelectionList import SelectionList from Screens.NetworkSetup import * from enigma import * from Screens.Standby import * from Screens.LogManager import * f...
import threading import wx from os.path import abspath, dirname, join import eg from eg.WinApi.Dynamic import ( CreateEvent, SetEvent, SetWindowPos, SWP_FRAMECHANGED, SWP_HIDEWINDOW, SWP_NOACTIVATE, SWP_NOOWNERZORDER, SWP_SHOWWINDOW, ) from eg.WinApi.Utils import GetMonitorDimensions HWN...
""" The :mod:`wsr.data.district` handles reading and pre-processing the District Court dataset to extract opinion text. Author: Michael J Bommarito II <michael@bommaritollc.com> Date: 2014-05-24 """ from wsr.config import DISTRICT_FILE_NAME_LIST import dateutil.parser import lxml.etree import zipfile bad_element_list =...
""" Every db-related function of the bibcirculation module. The methods are positioned by grouping into logical categories ('Loans', 'Returns', 'Loan requests', 'ILLs', 'Libraries', 'Vendors' ...) This positioning should be maintained and when necessary, improved for readability, as and when additiona...
import unittest from .testutils import system, if_vagrant @unittest.skipUnless(if_vagrant(), "It's not a Vagrant image") class TestVagrantSwitchUser(unittest.TestCase): """Switch User Test for Vagrant based images""" def setUp(self): "Add a new user" system('sudo useradd testuser') def test_...
from collections import defaultdict d = defaultdict(list) d['a'].append(1) d['a'].append(2) d['b'].append(4) print(d.items()) d = {} d.setdefault('a', []).append(1) d.setdefault('a', []).append(2) d.setdefault('b', []).append(4) print(d.items())
from XMLBuilderDomain import XMLBuilderDomain, _xml_property from virtinst import _gettext as _ import logging class VirtualDevice(XMLBuilderDomain): """ Base class for all domain xml device objects. """ VIRTUAL_DEV_DISK = "disk" VIRTUAL_DEV_NET = "interface" VIRTUAL_DEV_I...
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np from sklearn.preprocessing import StandardScaler class LinearRegressionGD(object): def __init__(self, eta=0.001, n_iter = 20): self.eta = eta self.n_iter = n_iter def fit(self, X, y): self.w_ = n...
"""Functions which generate C/C++ code.""" import os import string import bldreg import umake_lib import types def WriteDLLTab(platform, project, plugin_list): """Write the dlltab.cpp file, and include it in the project source list. The dlltab.cpp file defines a global function table used by pnmisc/dllacces...
import sys sys.path.append( '..' ) from PyRTF import * def MergedCells( ) : # another test for the merging of cells in a document doc = Document() section = Section() doc.Sections.append( section ) # create the table that will get used for all of the "bordered" content col1 = 1000 col2 = 1000 col3 = 1000 col...
from .base import * DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'openid-staging', } } STATIC_ROOT = join(SITE_ROOT, '../webfiles-staging-ce/static/')
from struct import * from time import * from binascii import * import sys showmessage=0 strfile = "S60.NET" if len(sys.argv) > 0: strfile = sys.argv[1] strformat = "<HHHHHHHIIH" def readtest(f): s=f.tell() buffer = f.read(24) tosys,touser,fromsys,fromuser,main_type,minor_type,list_len,daten,length,method=unpack(...
import sys import gdb import os import os.path pythondir = '/opt/codesourcery/arm-none-eabi/share/gcc-4.7.2/python' libdir = '/opt/codesourcery/arm-none-eabi/lib/thumb2' if gdb.current_objfile () is not None: # Update module path. We want to find the relative path from libdir # to pythondir, and then we want t...
"""This module represents Persian language. For more information, see U{http://en.wikipedia.org/wiki/Persian_language} """ from translate.lang import common class fa(common.Common): """This class represents Persian.""" listseperator = u"، " puncdict = { u",": u"،", u";": u"؛", u"?": ...