repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
networks-lab/metaknowledge | metaknowledge/tests/test_recordcollection.py | Python | gpl-2.0 | 26,484 | 0.012538 | #Written by Reid McIlroy-Young for Dr. John McLevey, University of Waterloo 2015
import unittest
import metaknowledge
import metaknowledge.WOS
import os
import filecmp
import networkx as nx
disableJournChecking = True
class TestRecordCollection(unittest.TestCase):
@classmethod
def setUpClass(cls):
met... | self.assertEqual(self.RC, RC3)
RC4 = RC3 - self.RC
self.assertNotEqual(self.RC, RC4)
RC5 = RC4 ^ self.RC
| self.assertEqual(self.RC, RC5)
RC6 = RC5 & self.RCbad
self.assertNotEqual(self.RC, RC6)
def test_opErrors(self):
with self.assertRaises(TypeError):
self.RC <= 1
with self.assertRaises(TypeError):
self.RC >= 1
self.assertTrue(self.RC != 1)
wit... |
karulis/pybluez | osx/_bluetoothsockets.py | Python | gpl-2.0 | 35,262 | 0.002354 | # Copyright (c) 2009 Bea Lam. All rights reserved.
#
# This file is part of LightBlue.
#
# LightBlue 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 l... |
# Thanks to Simon Wittber for string queue recipe
# http://aspn.activestate.com/ASPN/Cookbook/ | Python/Recipe/426060
# (this is a modified version)
class _StringQueue(object):
def __init__(self):
self.l_buffer = []
self.s_buffer = ""
self.lock = threading.RLock()
self.bufempty = True
def empty(self):
return self.bufempty
def write(self, data):
# no typ... |
jay-lau/magnum | magnum/conductor/mesos_monitor.py | Python | apache-2.0 | 2,587 | 0 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# di... | ] == state['pid']
def pull_data(self):
self.data['mem_total'] = 0
self.data['mem_used'] = 0
self.data['cpu_total'] = 0
self.data['cpu_used'] = 0
for master_addr in self.bay.master_addresses:
mesos_master_url = self._build_url(master_addr, port='5050',
... | = jsonutils.loads(urlfetch.get(mesos_master_url))
if self._is_leader(master):
for slave in master['slaves']:
self.data['mem_total'] += slave['resources']['mem']
self.data['mem_used'] += slave['used_resources']['mem']
self.data['cpu... |
craws/OpenAtlas-Python | tests/test_search.py | Python | gpl-2.0 | 1,697 | 0 | from flask import url_for
from openatlas import app
from openatlas.models.entity import Entity
from tests.base import TestBaseCase
class SearchTest(TestBaseCase):
def test_search(self) -> None:
with app.test_request_context():
app.preprocess_request() # type: ignore
person = Ent... | assert b'Waldo' in rv.data
rv = self.app.post(
url_for('search_index'),
data={'term': 'wal', 'own': True})
assert b'Waldo' not in rv.data
data = {'term': 'do', 'classes': 'person'}
rv = self.app.post(url_for('search_index'), d | ata=data)
assert b'Waldo' in rv.data
rv = self.app.post(
url_for('search_index'),
follow_redirects=True,
data={'term': 'x', 'begin_year': 2, 'end_year': -1})
assert b'cannot start after' in rv.data
|
usta/radmyarchive-py | setup.py | Python | bsd-3-clause | 1,376 | 0.000728 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from codecs import open
from os import path
import re
import ast
here = path.abspath(path.dirname(__file__))
_version_re = re.compile(r'__version__\s+=\s+(.*)')
with open('radmyarchive/__init__.py', 'rb') as vf:
version = ... | om",
packages=find_packages(),
scripts=["scripts/RADMYARCHIVE.py"],
url="https://github.com/usta/radmyarchive-py",
license="BSD",
keywords="exif image photo rename metadata arrange rearrange catalogue",
description="A simple photo rearranger with help of | EXIF tags",
install_requires=['exifread', 'termcolor', 'colorama'],
long_description=readme_file,
classifiers=(
"Development Status :: 3 - Alpha",
"Environment :: Console",
"Intended Audience :: Developers",
"Intended Audience :: End Users/Desktop",
"License :: OSI A... |
marioluigiman/geekchicken | cafe/models.py | Python | mit | 960 | 0.015625 | from django.db import models
from django.utils import timezone
# Create your models here.
class Comment(models.Mode | l):
title = models.CharField(max_length=200)
comment_text = models.TextField()
rating = models.IntegerField()
created_date = models.DateTimeField(default = timezone.now)
published_date = models.DateTimeField(blank=True, null= True)
def publish(self):
self.published_date = timezone.now( | )
self.save()
def __str__(self):
return self.title
class Reservation(models.Model):
name = models.CharField(max_length=200)
people_amount = models.IntegerField(default = 1)
time = models.TimeField(default = timezone.now)
created_date = models.DateTimeField(default = timezone.now)
... |
tgracchus/spinnaker | pylib/spinnaker/reconfigure_spinnaker.py | Python | apache-2.0 | 891 | 0.003367 | #!/usr/bin/python
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | tor
if __name__ == '__main__':
try:
configurator = Configurator()
configurator.update | _deck_settings()
except (RuntimeError, IOError, ValueError) as e:
sys.stderr.write(str(e) + '\n')
sys.exit(-1)
|
simplegeo/sqlalchemy | test/aaa_profiling/test_zoomark_orm.py | Python | mit | 13,694 | 0.002629 | """Benchmark for SQLAlchemy.
An adaptation of Robert Brewers' ZooMark speed tests. """
import datetime
import sys
import time
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.test import *
ITERATIONS = 1
dbapi_session = engines.ReplayableSession()
metadata = None
class ZooMarkTest(TestBase):
... | 'Bai Yun', Legs=2)
session.add(bai_yun)
session.add(Animal(Species=u'Ape', Name=u'Hua Mei', Legs=2,
MotherID=bai_yun.ID))
session.flush()
sessio | n.commit()
def test_baseline_2_insert(self):
for x in xrange(ITERATIONS):
session.add(Animal(Species=u'Tick', Name=u'Tick %d' % x,
Legs=8))
session.flush()
def test_baseline_3_properties(self):
for x in xrange(ITERATIONS):
# Zoos
... |
kit-cel/gr-dab | python/channel_tests/ber.py | Python | gpl-3.0 | 427 | 0.04918 | def bits_set(x):
bits = 0
for i in range(0,8):
if (x & (1<<i))>0:
bits += 1
return bits
def find_ber(sent, received):
assert(len(received)<=len(sent))
if len(received) < len(sent)/2:
print "frame detection error, more than half of the frames were lost!"
return 0.5
er | rors = 0
for i in range(0,len(received)):
errors + | = bits_set(sent[i] ^ received[i]) # ^ is xor
return float(errors)/float(8*len(received))
|
DHI-GRAS/processing_SWAT | MDWF_Sensan_a.py | Python | gpl-3.0 | 7,579 | 0.006333 | """
***************************************************************************
MDWF_Sensan_a.py
-------------------------------------
Copyright (C) 2014 TIGER-NET (www.tiger-net.org)
***************************************************************************
* This plugin is part of the Water Observatio... | n 3 of the License, *
* or (at your option) any later version. *
* *
* WOIS is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTAB... | *
* *
* You should have received a copy of the GNU General Public License along *
* with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************... |
apple/swift-lldb | packages/Python/lldbsuite/test/functionalities/history/TestHistoryRecall.py | Python | apache-2.0 | 1,405 | 0.00427 | """
Make sure the !N and !-N commands work properly.
"""
from __future__ import print_function
import lldb
import lldbsuite.test.lldbutil as lldbutil
from lldbsuite.test.lldbtest import *
class TestHistoryRecall(TestBase):
mydir = TestBase.compute_mydir(__file__)
# If your test case doesn't stress debug ... | Command("command history", result, True)
interp.HandleCommand("platform list", result, True | )
interp.HandleCommand("!0", result, False)
self.assertTrue(result.Succeeded(), "!0 command did not work: %s"%(result.GetError()))
self.assertTrue("command history" in result.GetOutput(), "!0 didn't rerun command history")
interp.HandleCommand("!-1", result, False)
self.assertT... |
iandees/all-the-places | locations/spiders/hm.py | Python | mit | 3,295 | 0.003642 | import scrapy
from locations.items import GeojsonPointItem
import itertools
def chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
def partition(l, n):
return list(chunks(l, n))
def process_hours(opening_hours):
ret_hours = []
for hours_str in opening_hours:
split_hours =... | (*r)) for r in periods]
period_list = []
for start, start_period, end, end_period in periods:
start_hour, start_minutes = [int(x) for x in start.split(":")]
end_hour, end_minutes = [int(x) for x in end.split(":")]
if start_period == "PM":
start_hour... | append("%02d:%02d-%02d:%02d" % hours)
periods_str = ", ".join(period_list)
if range_start and range_end:
ret_hours.append("{}-{} {}".format(range_start[:2], range_end[:2], periods_str))
elif range_start:
ret_hours.append("{} {}".format(range_start[:2], periods_str))
r... |
wotaen/itunes_podcast_rss | extract.py | Python | mit | 1,768 | 0.005656 | import json
import re
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3 import Retry
URL_TEMPLATE = "https://itunes.apple.com/loo | kup?id=%s&entity=podcast"
def id_from_url(url):
"""
Extract ID from iTunes podcast URL
:param url (str)
:return: (str)
"""
matches = re.findall(r'\/id([0-9]+)',url)
if len(matches) == 0:
raise LookupError("No ID present in the given URL")
if len(matches) > 1:
raise Look... | lookup_id(id):
"""
Looks up podcast ID in Itunes lookup service
https://itunes.apple.com/lookup?id=<id>&entity=podcast
:param id (str):
:return: itunes response for the lookup as dict
"""
try:
retries = Retry(total=3,
backoff_factor=0.1,
status_forcel... |
TheBestHuman/DesktopSudokuGenerator | lib/gnome_sudoku.py | Python | gpl-3.0 | 38,776 | 0.013642 | import gtk, gobject, gtk.glade
import gnome, gnome.ui, pango
import os, os.path
from gtk_goodies import gconf_wrapper, Undo, dialog_extras, image_extras
import gsudoku, sudoku, saver, sudoku_maker, printing, sudoku_generator_gui
import game_selector
import time, threading
from gettext import gettext as _
from gettext i... | pen"/> | -->
<!--<toolitem action="Print"/>-->
<!--<toolitem action="Save"/>-->
<separator/>
<toolitem action="Clear"/>
<toolitem action="ClearNotes"/>
<!--<separator/>
<toolitem action="Undo"/>
<toolitem action="Redo"/>-->
<separator/>
<toolitem action="ShowPoss... |
nullpuppy/vgng | vgng.py | Python | mit | 2,102 | 0.00333 | #!/usr/bin/env python
#
# Translation of videogamena.me javascript to python
#
# http://videogamena.me/vgng.js
# http://videogamena.me/video_game_names.txt
#
# (C) 2014 Dustin Knie <dustin@nulldomain.com>
import argparse
import os
import random
from math import floor, trunc
_word_list_file = 'video_game_names.txt'
_... | rd)
return (words, bad_match_list)
def generate_game_name(allow_similar_matches=False):
words = []
bad_match_list = []
for word_list in _word_list:
(words, bad_match_list) = _get_word(word_list,
| words=words,
bad_match_list=bad_match_list,
allow_similar_matches=allow_similar_matches)
return ' '.join(words)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('count', type=int, nargs='?', help='Number of names to create')
parser.a... |
hahnicity/bamboo | bamboo/globals.py | Python | mit | 159 | 0 | """
bamboo.globals
~~~~~~~~~~~~~
"""
from peak.util.proxies i | mport CallbackProxy
from bamboo.context import context
db = CallbackProxy(lambda: context["db"])
| |
nwjs/chromium.src | tools/v8_context_snapshot/run.py | Python | bsd-3-clause | 552 | 0.003623 | # Copy | right 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style li | cense that can be
# found in the LICENSE file.
"""This program wraps an arbitrary command since gn currently can only execute
scripts."""
import os
import subprocess
import sys
from shutil import copy2
args = sys.argv[1:]
args[0] = os.path.abspath(args[0])
#if sys.platform == 'darwin':
# copy2(os.path.join(os.pa... |
rajpushkar83/cloudmesh | cloudmesh/management/read.py | Python | apache-2.0 | 752 | 0.00133 | import yaml
from mongoe | ngine import *
import datetime
import time
import hashlib
import uuid
from pprint import pprint
from user import User, Users
from cloudmesh_management.generate import random_user
from cloudmesh_management.user import read_user
FILENAME = "/tmp/user.yaml"
connect('user', port=27777)
users = Users()
# Reads user inf... | en(FILENAME, "w") as f:
# f.write(user.yaml())
print 70 * "="
user = User()
user = read_user(FILENAME)
print 70 * "="
pprint(user.json())
user.save()
user.update(**{"set__username": "Hallo"})
user.save()
print User.objects(username="Hallo")
if __name__ == "__main__":
... |
ESOedX/edx-platform | lms/djangoapps/dashboard/tests/test_sysadmin.py | Python | agpl-3.0 | 12,287 | 0.001139 | """
Provide tests for sysadmin dashboard feature in sysadmin.py
"""
from __future__ import absolute_import
import glob
import os
import re
import shutil
import unittest
from datetime import datetime
from uuid import uuid4
import mongoengine
from django.conf import settings
from django.test.client import Client
from d... | directories.
"""
for path in glob.glob(path):
shutil.rmtree(path)
def _mkdir(self, path):
"""
Create directory and add the cleanup for it.
"""
os.mkdir(path)
self.addCleanup(shutil.rmtree, path)
@override_settings(
MONGODB_LOG=TEST_MONGODB_... | "ENABLE_SYSADMIN_DASHBOARD not set")
class TestSysAdminMongoCourseImport(SysadminBaseTestCase):
"""
Check that importing into the mongo module store works
"""
@classmethod
def tearDownClass(cls):
"""Delete mongo log entries after test."""
super(TestSysAdminMongoCo... |
drcsturm/project-euler | p026.py | Python | mit | 1,084 | 0.021218 |
# A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:
# 1/2 = 0.5
# 1/3 = 0.(3)
# 1/4 = 0.25
# 1/5 = 0.2
# 1/6 = 0.1(6)
# 1/7 = 0.(142857)
# 1/8 = 0.125
# 1/9 = 0.(1)
# 1/10 = 0.1
# Where 0.1... | Decimal(n))[2:]
if len(num) <= max_len * 2:continue
for j in range(10):
breaker = False
for i in range(max_len, int(len(num)/2)-j):
# print(n, num[j:j+i], num[j+i:i*2+j])
if num[j:j+i] == num[j+i:i*2+j]:
if len(num[j:i]) | >= repeating:
repeating = len(num[j:i])
repeating_num = n
# print(n, num[j:i])
breaker = True
break
if breaker:break
print(repeating_num)
|
aws-quickstart/taskcat | tests/test_common_utils.py | Python | apache-2.0 | 4,514 | 0.001108 | import errno
import os
import unittest
import mock
from taskcat._common_utils import (
exit_with_code,
fetch_ssm_parameter_value,
get_s3_domain,
make_dir,
merge_dicts,
name_from_stack_id,
param_list_to_dict,
pascal_to_snake,
region_from_stack_id,
s3_bucket_name_from_url,
s3_... | mdir(path)
except FileNotFoundError:
pass
os.makedirs(path)
make_dir(path)
os.rmdir(path)
make_dir(path)
self.assertEqual(os.path.isdir(path), True)
with self.assertRaises(FileExistsError) as cm:
| make_dir(path, False)
self.assertEqual(cm.exception.errno, errno.EEXIST)
os.rmdir(path)
@mock.patch("taskcat._common_utils.sys.exit", autospec=True)
@mock.patch("taskcat._common_utils.LOG", autospec=True)
def test_exit_with_code(self, mock_log, mock_exit):
exit_with_code(1)
... |
starofrainnight/rabird.selenium | rabird/selenium/exceptions.py | Python | apache-2.0 | 118 | 0 | """
@date 2014-11-16
@author Hong-She Liang <starofrainnigh | t@gmai | l.com>
"""
from selenium.common.exceptions import *
|
PearsonIOKI/ioki-social | fabfile.py | Python | mit | 1,897 | 0.001054 | """
Script which define fabric's methods.
"""
from fabric.api import local, task, lcd
from utils import create_bundle_server as create_bs, create_bundle_client as create_bc
@task
def create_bundle_server(bundle_name=None):
"""
Creates bundle for server-side of the application.
"""
create_b | s(bundle_name)
@task
def create_bundle_client(bundle_name=None):
"""
Creates bundle for client-side of the application.
"""
create_bc(bundle_name)
@task
def create_bundle(bundle_name=None):
"""
Creates bundle for server and client.
"""
create_bundle_server(bundle_name)
create_bun... | bundle_list = local('find server/* -type d | grep tests', capture=True)
for catalog in bundle_list.split("\n"):
if is_ci:
xunit_file = catalog.replace('/', '_')
local("nosetests --with-xunit \
--xunit-file=../build/logs/xunit/" +
xunit_file + '... |
team-xue/xue | xue/cms/plugins/inherit/models.py | Python | bsd-3-clause | 673 | 0.005944 | from django.db import models
from django.utils.translation import ugettext_lazy as _
from cms.models import CMSPlugin, Page
from cms import settings
class InheritPagePlaceholder(CMSPlugin):
"""
Provides the ability to i | nherit plugins for a certain placeholder from an associated "parent" page instance
"""
from_page = models.ForeignKey(Page, null=True, blank=True, help_text=_("Choose a page to include its plugins into this placeholder, empty will choose current page"))
from_language = models.CharField(_("language"), max_len... | lugins you want"))
|
micahwood/linux-dotfiles | sublime/Packages/SublimeLinter/lint/highlight.py | Python | mit | 14,958 | 0.001738 | #
# highlight.py
# Part of SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ryan Hileman and Aparajita Fishman
#
# Project: https://github.com/SublimeLinter/SublimeLinter3
# License: MIT
#
"""
This module implements highlighting code with marks.
The following classes are exported:
Highligh... | ORMAT - format string for key used to mark gutter mark regions
MARK_SCOPE_FORMAT - format string used for color scheme scope names
"""
import re
import sublime
from . import persist
#
# Error types
#
WARNING = 'warning'
ERROR = 'error'
MARK_KEY_FORMAT = 'sublimelinter-{}-marks'
GUTTER_MARK_KEY_FORMAT = 'sub | limelinter-{}-gutter-marks'
MARK_SCOPE_FORMAT = 'sublimelinter.mark.{}'
UNDERLINE_FLAGS = sublime.DRAW_NO_FILL | sublime.DRAW_NO_OUTLINE | sublime.DRAW_EMPTY_AS_OVERWRITE
MARK_STYLES = {
'outline': sublime.DRAW_NO_FILL,
'fill': sublime.DRAW_NO_OUTLINE,
'solid underline': sublime.DRAW_SOLID_UNDERLINE | UND... |
prolifik/cakecoin | contrib/seeds/makeseeds.py | Python | mit | 709 | 0.015515 | #!/usr/bin/env python
#
# Generate pnSeed[] from Pieter's DNS seeder
#
NSEEDS=600
import re
import sys
from subprocess import check_output
def main():
lines = sys.stdin.readlines()
ips = []
pattern = re.compile(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}):17792")
for line in lines:
m = patt... | continue
ip = 0
for i in range(0,4):
ip = ip + (int(m.group(i+1)) << (8*(i)))
if ip == 0:
continue
ips.append(ip)
for row in range(0, min(NSEEDS,len(ips)), 8):
print " " + ", ".join([ "0x%08x"%i for i in ips[row:row+8] ]) + ","
if __name__ =... | n__':
main()
|
OpenMined/PySyft | packages/syft/src/syft/proto/lib/python/bool_pb2.py | Python | apache-2.0 | 1,474 | 0.002035 | # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: proto/lib/python/bool.proto
"""Generated protocol buffer code."""
# third party
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import m... | buf import symbol_database as _symbol_database
# @@pr | otoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
# syft absolute
from syft.proto.core.common import (
common_object_pb2 as proto_dot_core_dot_common_dot_common__object__pb2,
)
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(
b'\n\x1bproto/lib/python/bool.proto\x12\x0fsyft.lib.pyt... |
acsone/account-invoicing | account_invoice_rounding/tests/test_invoice_rounding.py | Python | agpl-3.0 | 7,217 | 0 | # -*- coding: utf-8 -*-
# Copyright 2016 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
import openerp.tests.common as test_common
# @test_common.post_install(True)
class TestSwedishRounding(test_common.TransactionCase):
def create_dummy_invoice(self):
invoice = self.env['ac... | nvoice3 = self.create_dummy_invoice_2()
invoice3.button_reset_taxes()
invoice3.signal_workflow('invoice_open')
self.assertEqual(invoice3.amount_total, 96.95)
self.assertEqual(invoice3.amount_untaxed, 90.02)
# test without pressing taxes reset button before validation
inv... | self.assertEqual(invoice3.amount_total, 96.95)
self.assertEqual(invoice3.amount_untaxed, 90.02)
|
cloudfoundry/python-buildpack | fixtures/setup_py/funniest/__init__.py | Python | apache-2.0 | 52 | 0 | d | ef joke():
return 'Knock Knock. | Who is there?'
|
shy21grams/GroundControl | Simulation/simulationCanvas.py | Python | gpl-3.0 | 3,902 | 0.022553 | from kivy.uix.floatlayout import FloatLayout
from kivy.properties import NumericProperty, ObjectProperty
from kivy.graphics import Color, Ellipse, Line
from kivy.graphics.transformation import Matrix
from kivy.core.window ... | angleB.initialize(self.chainB, self.lineT, 0)
self.angleP.initialize(self.chainA, self.chainB, 1)
def setupSled(self):
self.sled.initialize(self.chainA, self.chainB, 1, self.angleP)
def setInitialZoom(self):
mat = Matrix().scale(.4, .4, 1)
self.scatterInstance.apply_tra... |
mat = Matrix().translate(200, 100, 0)
self.scatterInstance.apply_transform(mat)
def startChains(self):
self.chainA.initialize()
self.chainB.initialize()
self.lineT.initialize()
self.lineT.color = (0,0,1)
self.chainA.setStart(-self.moto... |
log2timeline/plaso | plaso/preprocessors/generic.py | Python | apache-2.0 | 3,399 | 0.005001 | # -*- coding: utf-8 -*-
"""Operating system independent (generic) preprocessor plugins."""
from dfvfs.helpers import file_system_searcher
from plaso.lib import definitions
from plaso.preprocessors import interface
from plaso.preprocessors import manager
class DetermineOperatingSystemPlugin(
interface.FileSystem... | ss
the file system.
file_system (dfvfs.FileSystem): file system to be preprocessed.
Raises:
PreProcessFail: if the preprocessing fails.
"""
locations = []
for path_spec in searcher.Find(find_specs=self._ | find_specs):
relative_path = searcher.GetRelativePath(path_spec)
if relative_path:
locations.append(relative_path.lower())
operating_system = definitions.OPERATING_SYSTEM_FAMILY_UNKNOWN
if self._WINDOWS_LOCATIONS.intersection(set(locations)):
operating_system = definitions.OPERATING_S... |
aewallin/openvoronoi | python_examples/chain_1.py | Python | lgpl-2.1 | 3,292 | 0.001215 | import openvoronoi as ovd
import ovdvtk # helper library for visualization using vtk
import time
import vtk
import datetime
import math
import random
import os
import sys
import pickle
import gzip
if __name__ == "__main__":
# size of viewport in pixels
# w=2500
# h=1500
# w=1920
# h=1080
w =... | r = min(err)
maxerr = max(err)
print " min error= ", minerr
print " max error= ", maxerr
print " num vertices: ", vd.numVertices()
print " num SPLIT vertices: " | , vd.numSplitVertices()
calctime = t_after - t_before
vod.setAll()
print "PYTHON All DONE."
myscreen.render()
# w2if.Modified()
# lwr.SetFileName("{0}.png".format(Nmax))
# lwr.Write() # write screenshot to file
myscreen.iren.Start()
|
pferreir/indico-backup | indico/MaKaC/plugins/Collaboration/RecordingManager/fossils.py | Python | gpl-3.0 | 1,501 | 0.009993 | # -*- coding: utf-8 -*-
##
##
## This file is part of Indico.
## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
##
## Indico 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; eith... | mon.fossilize import addFossil
from MaKaC.conference import Contribution
class IContributionRMFossil(IContributionWithSpeakersFossil):
""" This fossil is ready f | or when we add subcontribution granularity to contributions
and to provide an example for a plugin-specific fossil
"""
def getSubContributionList(self):
pass
getSubContributionList.result = ISubContributionWithSpeakersFossil
# We cannot include this fossil in the Contribution class directl... |
suneeth51/neutron | neutron/tests/unit/plugins/ml2/drivers/openvswitch/agent/test_ovs_tunnel.py | Python | apache-2.0 | 25,812 | 0 | # Copyright 2012 VMware, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | _bridge.add_port.return_value = self.MAP_TUN_INT_OFPORT
self.mock_int_bridge.add_patch_ | port.side_effect = (
lambda tap, peer: self.ovs_int_ofports[tap])
self.mock_int_bridge.get_vif_ports.return_value = []
self.mock_int_bridge.get_ports_attributes.return_value = []
self.mock_int_bridge.db_get_val.return_value = {}
self.mock_map_tun_bridge = self.ovs_bridges[se... |
argentumproject/electrum-arg | plugins/hw_wallet/hw_wallet.py | Python | mit | 3,347 | 0.000299 | #!/usr/bin/env python2
# -*- mode: python -*-
#
# Electrum - lightweight Bi | tcoin client
# Copyright (C) 2016 The Electrum developers
#
# Permission is hereby granted, free of charge, to any person
# obt | aining 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, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is... |
1dot75cm/repo-checker | checker/backends/gnome.py | Python | mit | 803 | 0 | # -*- coding: utf-8 -*-
from checker.backends import BaseBackend
from checker import logger
log = logger.getLogger(__name__)
class GnomeBa | ckend(BaseBackend):
"""for projects hosted on gnome.org"""
name = 'Gnome'
domain = 'gnome.org'
example = 'https://download.gnome.org/sources/gnome-control-center'
def __init__(self, url):
super(GnomeBackend, self).__init__()
self._url = url
self._rule_type = "xpath"
de... | (self.name, self._url.split('/')[-1]))
return [("//tr/td[3][contains(text(), '-')]/text()", ""), ("", "")]
@classmethod
def isrelease(cls, url):
return True
|
ccxt/ccxt | examples/py/instantiate-all-at-once.py | Python | mit | 447 | 0.002237 | # -*- coding: utf-8 -*-
import os
import sys
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(root + '/python')
import ccxt # noqa: E402
exchanges = {} # a placeholder for your instances
for id in ccxt.exchanges:
exchange = getattr(ccxt, id)
exchanges[id... | tances...
exchanges['bitt | rex'].fetch_order_book('ETH/BTC')
|
ThunderShiviah/london-social-network-analysis | web_subscriptions/items.py | Python | mit | 330 | 0 | # -*- coding: utf-8 -*-
# Define here the models for your scrap | ed item | s
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class ListItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
name = scrapy.Field()
location = scrapy.Field()
|
rajaram1990/GetNSEStockPrice | GetNSEStockPrice/email_base.py | Python | mit | 1,041 | 0.011527 | import sys
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from config import config
def send_mail(message,receivers=config['smtp_receivers']):
"""
Module that sends emails.
Message should be a di | ctionary containing the following keys:
subject -> Subject of the email
text -> The plain text part of the email
uses options from config.py
"""
sender = config['smtp_sender']
print sender
print receivers
print message
try:
smtp | Obj = smtplib.SMTP_SSL(config['smtp_server'],config['smtp_port'])
smtpObj.login(config['smtp_login'],config['smtp_password'])
if not receivers:
return True
smtpObj.sendmail(sender, receivers, message)
smtpObj.quit()
return True
except Exception, exc:
pri... |
f0rki/cb-multios | original-challenges/Palindrome/poller/for-testing/machine.py | Python | mit | 1,305 | 0.011494 | from generator.actions import Actions
import random
import string
class Palindrome(Actions):
def start(self):
pass
def banner(self):
# Confirm the initial empty line
self.read(delim='\n', expect='\n')
# Confirm the actual banner
self.read(delim='\n', expect='Welcome to ... | drome!\n")
def not_palindrome(self):
word = self.random_string(random.randint(2, 32))
while self.is_palindrome(word):
word = self.random_string(random.randint(2, 32))
self.write(word + "\n")
self.read(delim='\n', expect="\t\tNope, that's not a palindrome\n")
def is_palindrome | (self, word):
for i in range(0, len(word) / 2):
if word[i] != word[-i - 1]:
return False
return True
def random_string(self, size):
chars = string.letters + string.digits
return ''.join(random.choice(chars) for _ in range(size))
|
kingsdigitallab/kdl-django | cms/migrations/0009_blogpost_date.py | Python | mit | 565 | 0.00177 | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-08-17 08:53
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migra | tion(migrations.Migration):
dependencies = [
('cms', '0008_blogindexpage_blogpost_blogposttag'),
]
operations = [
migrations.AddField(
| model_name='blogpost',
name='date',
field=models.DateField(default=django.utils.timezone.now, verbose_name='body'),
preserve_default=False,
),
]
|
aurex-linux/virt-manager | virtManager/createpool.py | Python | gpl-2.0 | 18,923 | 0.000951 | #
# Copyright (C) 2008, 2013 Red Hat, Inc.
# Copyright (C) 2008 Cole Robinson <crobinso@redhat.com>
#
# 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 2 of the License, or
# (at yo... | use_model = source_model
entry_list = []
if self._pool.type == StoragePool.TYPE_SCSI:
entry_list = self.list_scsi_adapters()
use_list | = source_list
use_model = source_model
elif self._pool.type == StoragePool.TYPE_LOGICAL:
pool_list = self.list_pool_sources()
entry_list = [[p.target_path, p.target_path, p]
for p in pool_list]
use_list = target_list
use_mode... |
flocca/flocca_dot_com | flocca_dot_com/settings.py | Python | gpl-3.0 | 5,929 | 0.001012 | # This Python file uses the following encoding: utf-8
"""
Copyright 2013 Giacomo Antolini <giacomo.antolini@gmail.com>.
This file is part of flocca_dot_com.
flocca_dot_com is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
... | s.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
... | }
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
|
bikash/h2o-dev | h2o-py/tests/testdir_algos/rf/pyunit_iris_ignoreRF.py | Python | apache-2.0 | 405 | 0.02716 | import sys
sys.path.insert(1, "../../../")
import h2o
def iris_ignore(ip,port):
# Connect to h2o
h2o.init(ip,port)
iris = h2o.import_frame(path=h2o.locate("smallda | ta/iris/iris2.csv"))
for maxx in range(4):
model = h2o.random_forest(y=iris[4], x=iris[range(maxx+1)], ntrees=50, max_depth=100)
model.show()
if __name__ == "__main__":
h2o.run_test(s | ys.argv, iris_ignore)
|
denny820909/builder | lib/python2.7/site-packages/buildbot_slave-0.8.8-py2.7.egg/buildslave/test/__init__.py | Python | mit | 2,076 | 0.003372 | # This file is part of Buildbot. Buildbot 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.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | ebug
failing tests.
"""
from twisted.application.service import Service
old_startService = Service.startService
old_stopService = Service.stopService
def startService(self):
assert not self.running
return old_startService(self)
def stopService(self):
assert self.runni... | tService
Service.stopService = stopService
# versions of Twisted before 9.0.0 did not have a UnitTest.patch that worked
# on Python-2.7
if twisted.version.major <= 9 and sys.version_info[:2] == (2,7):
def nopatch(self, *args):
raise unittest.SkipTest('unittest.TestCase.patch is not ... |
billiob/papyon | papyon/service/description/SingleSignOn/RequestMultipleSecurityTokens.py | Python | gpl-2.0 | 4,656 | 0.004296 | # -*- coding: utf-8 -*-
#
# papyon - a python client library for Msn
#
# Copyright (C) 2005-2006 Ali Sabil <ali.sabil@gmail.com>
#
# 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 ... | if isinstance(attr, tuple) and attr[0] == url:
return attr
return None
def transport_headers():
"""Returns a dictionary, containing transport (http) headers
to use for the request"""
return {}
def soap_action():
"""Returns the SOAPAction value to pass to the transport
or ... | <ps:AuthInfo xmlns:ps="http://schemas.microsoft.com/Passport/SoapServices/PPCRL" Id="PPAuthInfo">
<ps:HostingApp>{7108E71A-9926-4FCB-BCC9-9A9D3F32E423}</ps:HostingApp>
<ps:BinaryVersion>4</ps:BinaryVersion>
<ps:UIVersion>1</ps:UIVersion>
<ps:Cookies/>
<ps:RequestParams>AQAAAAI... |
grtfou/data-analytics-web | website/utils/data_exportor.py | Python | mit | 8,235 | 0 | # -*- coding: utf-8 -*-
# @date 161103 - Export excel with get_work_order_report function
"""
Data exportor (Excel, CSV...)
"""
import io
import math
from datetime import datetime
from xlsxwriter.workbook import Workbook
import tablib
from utils.tools import get_product_size
def get_customers(customer_list=None... | else '')
row += 3
workbook.close()
output.seek(0)
return output.read()
def get_order_report(report_data, file_format='csv'):
"""Generate csv file for download by machine loss rate detail."""
data = tablib.Dataset()
data.headers = ('製令編號', '客戶', '規格', '投入數', '需求數',
... | stomer'], get_product_size(r['part_no']),
r['input_count'], r['require_count'],
r['step1_prod_qty'], r['step2_prod_qty'],
r['step3_prod_qty'], r['step4_prod_qty'],
r['step5_prod_qty']]
data.append(record)
if file_format == 'csv':
... |
egbertbouman/tribler-g | Tribler/Core/DecentralizedTracking/pymdht/core/ptime.py | Python | lgpl-2.1 | 124 | 0.008065 | import sys
import time
sleep = time.sleep
if s | ys.platform == 'win32':
time = time.clock
else:
t | ime = time.time
|
publica-io/django-publica-modals | runtests.py | Python | bsd-3-clause | 1,244 | 0.000804 | import sys
try:
from django.conf impo | rt settings
settings.configure(
DEBUG=True,
USE_TZ=True,
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
ROOT_URLCONF="modals.urls",
INSTALLED_APPS=[
"django.contrib.auth",
"django.... |
],
SITE_ID=1,
NOSE_ARGS=['-s'],
)
try:
import django
setup = django.setup
except AttributeError:
pass
else:
setup()
from django_nose import NoseTestSuiteRunner
except ImportError:
import traceback
traceback.print_exc()
raise Impo... |
aonotas/chainer | chainer/initializers/orthogonal.py | Python | mit | 2,709 | 0 | import numpy
from chainer.backends import cuda
from chainer import initializer
# Original code forked from MIT licensed keras project
# https://github.com/fchollet/keras/blob/master/keras/initializations.py
class Orthogonal(initializer.Initializer):
"""Initializes array with an orthogonal system.
This init... | Error('Cannot make orthogonal system because'
' # of vectors ({}) is larger than'
' that of dimensions ({})'.format(
flat_shape[0], flat_sh | ape[1]))
a = numpy.random.normal(size=flat_shape)
# we do not have cupy.linalg.svd for now
u, _, v = numpy.linalg.svd(a, full_matrices=False)
# pick the one with the correct shape
q = u if u.shape == flat_shape else v
array[...] = xp.asarray(q.resh... |
Jumpscale/jumpscale6_core | apps/watchdogmanager/alerttypes/critical.py | Python | bsd-2-clause | 2,105 | 0.003325 |
from JumpScale import j
import JumpScale.baselib.watchdog.manager
import JumpScale.baselib.redis
import JumpScale.lib.rogerthat
descr = """
critical alert
"""
organization = "jumpscale"
enable = True
REDIS_PORT = 9999
# API_KEY = j.application.config.get('rogerthat.apikey')
redis_client = j.clients.credis.getRedis... | watchdogevent.escalationstate = 'L1'
# contact1 = redis_client.hget('contacts', '1')
message = str(watchdogevent)
# message_id = _send_message(message, [contact1,])
# watchdogevent.message_id = message_id
j.tools.watc | hdog.manager.setAlert(watchdogevent)
print "Escalate:%s"%message
def escalateL2(watchdogevent):
if watchdogevent.escalationstate == 'L1':
watchdogevent.escalationstate = 'L2'
contacts = redis_client.hgetall('contacts')
message = str(watchdogevent)
message_id = _send_message(... |
zxl200406/minos | owl/machine/management/commands/import_xman.py | Python | apache-2.0 | 2,543 | 0.012977 | import csv
import logging
import json
import sys
import urllib2
from django.conf import settings
from django.core.management.base import BaseCommand
from machine.models import Machine
logger = logging.getLogger(__name__)
XMAN_URL = "http://10.180.2.243/api/hostinfo.php?sql=hostname+=+'%s'"
IDC_ABBR = {
'shangdi... | : v['location'].lower(),
}
except Exception as e:
print 'Error on host: %s' % hostname
raise
if not xman:
# the machine doesn't exist in xm | an, delete it later.
changes.append((machine, xman, ))
else:
# check if any field changed.
# can't use iteritems as the dict might change.
for k, v in xman.items():
if getattr(machine, k) == v:
del xman[k]
if xman:
# some fields changed.
... |
Maethorin/concept2 | migrations/versions/6d8e9e4138bf_.py | Python | mit | 760 | 0.011842 | """empty message
Revision ID: 6d8e9e4138bf
Revises: 445667ce6268
Create Date: 2016-03-03 10:36:03.205829
"""
# revision identifiers, used by Alembic.
revision = '6d8e9e4138bf'
down_revision = '445667ce6268'
from alembic import op
import app
import sqlalchemy as sa
def upgrade():
### commands auto generated | by Alembic - please adjust! ###
op.add_column('provas', sa.Column('data_inicio', sa.DateTime(), nullable=True))
op.add_column('provas', sa.Column('tempo_execucao', sa.Integer(), nullable=True))
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
... | ta_inicio')
### end Alembic commands ###
|
Kent1/nxpy | nxpy/flow.py | Python | apache-2.0 | 4,735 | 0 | import re
from lxml import etree
from nxpy.util import tag_pattern, whitespace_pattern
class Flow(object):
def __init__(self):
self.routes = []
def export(self):
flow = etree.Element('flow')
if len(self.routes):
for route in self.routes:
flow.append(route.... | else:
etree.SubElement(then, key)
if then.getchildren():
ro.append(then)
if ro.getchildren():
return ro
else:
return False
def build(self, node):
for child in node:
nodeName_ = tag_pattern.match(child.tag).groups()... | ldren(self, child_, nodeName_, from_subclass=False):
if nodeName_ == 'name':
name_ = child_.text
name_ = re.sub(whitespace_pattern, " ", name_).strip()
self.name = name_
elif nodeName_ == 'match':
for grandChild_ in child_:
grandChildName_ ... |
willprice/weboob | weboob/applications/radioob/radioob.py | Python | agpl-3.0 | 15,978 | 0.001189 | # -*- coding: utf-8 -*-
# Copyright(C) 2010-2012 Romain Bignon
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your... | obj):
return obj.title
def get_description(self, obj):
result = ''
if hasattr(obj, 'description') and not empty(obj.description):
result += '%-30s' % obj.description
if hasattr(obj, 'current') and not empty(obj.current):
| if obj.current.who:
result += ' (Current: %s - %s)' % (obj.current.who, obj.current.what)
else:
result += ' (Current: %s)' % obj.current.what
return result
class SongListFormatter(PrettyFormatter):
MANDATORY_FIELDS = ('id', 'title')
def get_title(self, obj... |
claudep/pootle | tests/pootle_misc/templatetags.py | Python | gpl-3.0 | 1,836 | 0 | # -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from django.template import C... | = _render_str("{% load common_tags %}{% progress_b | ar 0 0 0 %}")
assert "<span class=\'value translated\'>0%</span>" in rendered
assert '<span class=\'value fuzzy\'>0%</span>' in rendered
assert '<span class=\'value untranslated\'>0%</span>' in rendered
rendered = _render_str(
"{% load common_tags %}{% progress_bar 123 23 73 %}")
assert "<sp... |
PetukhovVictor/compiler | src/Parser/AST/statements/skip.py | Python | mit | 152 | 0 | from ..base import AST
CLASS = "statements.skip"
class | SkipStatement(AST):
def __init__(self):
super().__init__(CLASS, "skip_s | tatement")
|
BillTheBest/MadeiraAgent | bin/madeira.py | Python | bsd-3-clause | 8,479 | 0.034202 | #!/usr/bin/env python -u
# -------------------------------------------------------------------------- #
# Copyright 2011, MadeiraCloud (support@madeiracloud.com) #
# -------------------------------------------------------------------------- #
"""MadeiraCloud Agent
"""
import os
import sys
import ... | parent
sys.exit(0)
except OSError, e:
logging.error("Cannot run MadeiraAgent in daemon mode: (%d) %s\n" % (e.errno, e.strerror))
raise | MadeiraAgentException
# Decouple from parent environment.
os.chdir(".")
os.umask(0)
os.setsid()
# Second fork
try:
pid = os.fork()
if pid > 0:
# Exit second parent.
sys.exit(0)
except OSError, e:
logging.error("Cannot run MadeiraAgent in daemon mode: (%d) %s\n" % (e.errn... |
MozillaSecurity/FuzzManager | server/crashmanager/tests/test_bugproviders_rest.py | Python | mpl-2.0 | 3,764 | 0.001063 | # coding: utf-8
from __future__ import unicode_literals
import logging
import pytest
import requests
LOG = logging.getLogger("fm.crashmanager.tests.bugproviders.rest")
@pytest.mark.parametrize("method", ["delete", "get", "patch", "post", "put"])
def test_rest_bugproviders_no_auth(db, api_client, method):
"""mus... |
("put", "/crashmanager/rest/bugproviders/1/", "restricted"),
], indirect=["user"])
def test_rest_bugproviders_methods_not_found(api_client, user, method, url):
"""must yield not-found for undeclared methods"""
assert get | attr(api_client, method)(url, {}).status_code == requests.codes['not_found']
def _compare_rest_result_to_bugprovider(result, provider):
expected_fields = {"id", "classname", "hostname", "urlTemplate"}
assert set(result) == expected_fields
for key, value in result.items():
assert value == getattr(p... |
slovelan/NRAODev | carta/html5/common/skel/source/class/skel/simulation/tLoadImage.py | Python | gpl-2.0 | 5,677 | 0.01603 | import Util
import time
import unittest
import selectBrowser
from selenium import webdriver
from flaky import flaky
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.su... | ete temporary files
self.driver.quit()
if __name__ | == "__main__":
unittest.main()
|
KaranToor/MA450 | google-cloud-sdk/lib/surface/source/__init__.py | Python | apache-2.0 | 1,960 | 0.00102 | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | oglecloudsdk.api_lib.source import source
from googlecloudsdk.api_lib.sourcerepo import sourcerepo
from googlecloudsdk.calliope import b | ase
from googlecloudsdk.core import properties
from googlecloudsdk.core import resolvers
from googlecloudsdk.core import resources
from googlecloudsdk.core.credentials import store as c_store
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Source(ba... |
vlas-sokolov/pyspeckit | pyspeckit/spectrum/headers.py | Python | mit | 1,312 | 0.005335 | from __future__ import print_function
try:
import astropy.io.fits as pyfits
except ImportError:
import pyfits
def intersection(header1, header2, if_conflict=None):
"""
Return a pyfits Header containing the inter | section of two pyfits Headers
*if_conflict* [ '1'/1/'Header1' | '2'/2/'Header2' | None ]
Defines behavior if a keyword conflict is found. Default is to remove the key
"""
newheader = pyfits.Header()
for key,value in header1.items():
if key in header2:
try:
... | elif if_conflict in ('1',1,'Header1'):
newheader[key] = value
elif if_conflict in ('2',2,'Header2'):
newheader[key] = Header2[key]
except KeyError:
""" Assume pyfits doesn't want you to have that keyword
(bec... |
jpzk/evopy | evopy/examples/problems/SchwefelsProblem26/ORIDSESAlignedSVC.py | Python | gpl-3.0 | 2,196 | 0.023679 | '''
This file is part of evopy.
Copyright 2012, Jendrik Poloczek
evopy 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.
evopy is distribut... | ORIDSESAlignedSVC
from evopy.problems.tr_problem import TRProblem
from evopy.problems.schwefels_problem_26 import SchwefelsProblem26
from evopy.simulators.simulator import Simulator
from evopy.metamodel.dses_svc_linear_meta_model import DSESSVCLinearMetaModel
from evopy.operators.scaling.scaling_standardscore import Sc... | t_method():
sklearn_cv = SVCCVSkGridLinear(\
C_range = [2 ** i for i in range(-1, 14, 2)],
cv_method = KFold(20, 5))
meta_model = DSESSVCLinearMetaModel(\
window_size = 10,
scaling = ScalingStandardscore(),
crossvalidation = sklearn_cv,
repair_mode = 'mirror')
... |
Azure/azure-sdk-for-python | sdk/appservice/azure-mgmt-web/azure/mgmt/web/v2021_01_01/aio/operations/_app_service_plans_operations.py | Python | mit | 83,276 | 0.004731 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Gene | rator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
import functools
from typing import Any, AsyncIterable, Ca | llable, Dict, Generic, List, Optional, TypeVar, Union
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 import PipelineResponse
from... |
renatahodovan/fuzzinator | fuzzinator/ui/tui/table.py | Python | bsd-3-clause | 18,857 | 0.000955 | # Copyright (c) 2016-2021 Renata Hodovan, Akos Kiss.
#
# Licensed under the BSD 3-Clause License
# <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>.
# This file may not be copied, modified, or distributed except
# according to those terms.
from functools import cmp_to_key
from urwid import *
from .decor... | self.body = self.listbox.body
self.ends_visible = self.listbox.ends_visible
super().__init__(self.listbox)
def keypress(self, size, key):
if key == 'home':
if self.body: # len(self.body) != 0
self.focus_position = 0
self._invalidate()
... | f.focus_position = len(self.body) - 1
self._invalidate()
return key
if key in ['page down', 'down'] and self.infinite and self.focus_position == len(self.body) - 1:
self.requery = True
self._invalidate()
return None
if key == 'enter':
... |
naresh21/synergetics-edx-platform | lms/djangoapps/branding/tests/test_models.py | Python | agpl-3.0 | 1,936 | 0.001033 | """
Tests for the Video Branding configuration.
"""
from django.test import TestCase
from django.core.exceptions import ValidationError
from nose.plugins.attrib import attr
from branding.models import BrandingInfoConfig
@attr(shard=1)
class BrandingInfoConfigTest(TestCase):
"""
Test the BrandingInfoConfig mo... | """
Tests get configuration from saved string.
"""
self.config.enabled = True
self.config.save()
expected_config = {
"CN": {
"url": "http://www.xuetangx.com",
"logo_src": "http://www.xuetangx.com/static/images/logo.png",
... | test_get_not_enabled(self):
"""
Tests get configuration that is not enabled.
"""
self.config.enabled = False
self.config.save()
self.assertEquals(self.config.get_config(), {})
|
UTC-Coding/Benji-s-Python | Rob/Odd or Even.py | Python | gpl-3.0 | 238 | 0.037815 | odd = [1,3,5,7,9]
even | = [2,4,6,8,10]
answer = input("Please enter your number! \n")
answer = int(answer)
if answer in odd:
print("That is quite odd!")
elif answer in even:
print("That's even")
else:
print("You are broken | !") |
wqferr/AniMathors | 01.py | Python | mit | 2,630 | 0.004563 | import numpy as np
import colorsys
from numpy import sin, cos, tan
import core
from core.anim import Animation
from core.obj import Point, Line, Vector, Curve
def update_p1(p1, t, tmax):
p1.x = np.cos(t)
def update_p2(p2, t, tmax):
p2.y = np.sin(t/3)
def update_p3(p3, t, tmax):
p3.pos = (p1.x, p2.y)
... | s(t)/2, np.sin(t)/2)
l.p2 = (-np.cos(t)/2, -np.sin(t)/2)
def update_v(v, t, tmax):
r2 = np.sqrt(2)/4
c = r2 * cos(2*t)
s = r2/3 * sin(2*t)
v.hx = s - c
v.hy = c + s
def update_c(c, t, tmax):
c.set_params(
tmin=min(v.hx, p3.x),
tmax=max(v.hx, p3.x)
)
def update_seg1(s,... | 1 = c.p2
s.p2 = (c.p2[0], 0)
def update_seg3(s, t, tmax):
s.p1 = seg1.p2
s.p2 = seg2.p2
def update_circumf(c, t, tmax):
c.set_params(
tmin=c.tmin+anim.dt,
tmax=c.tmax+anim.dt
)
col = colorsys.rgb_to_hsv(*c.color)
col = ((col[0]+anim.dt/(2*np.pi)) % 1, col[1], col[2])
c.... |
caio1982/capomastro | jenkins/management/commands/import_jenkinsserver.py | Python | mit | 960 | 0 | from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from jenkins.management.helpers import import_jenkinsserver
# TODO: implement optional field updating...
class Command(BaseCommand):
help ... | n_list = BaseCommand.option_list + (
make_option(
"--update", action="store_true", dest="update",
default=False, help="Update if server already exists."),
)
def handle(self, *args, **options): |
if len(args) != 4:
raise CommandError("must provide all parameters")
name, url, username, password = args
import_jenkinsserver(
name, url, username, password, update=options["update"],
stdout=self.stdout)
transaction.commit_unless_managed()
|
windskyer/weibo | weibo/test/sleep.py | Python | apache-2.0 | 300 | 0.003333 | #!/usr/bin/env pytho | n
# coding: utf-8
# Copyright (c) 2013
# Gmail:liuzheng712
#
import time
def task():
print "task ..."
def timer(n):
while True:
print time.strftime('%Y-%m-%d %X', time.localtime())
task()
time.sleep(n)
if __name__ == '__main_ | _':
timer(5)
|
chop-dbhi/ehb-service | ehb_service/apps/core/encryption/encryptionFields.py | Python | bsd-2-clause | 8,789 | 0.003186 | import datetime
import re
import binascii
import random
import string
import logging
from django import forms
from django.db import models
from django.forms import fields
from django.utils.encoding import force_text, smart_bytes
import sys
from core.encryption.Factories import FactoryEncryptionServices as efac
from c... | s odd, then it was
not encrypted because the encrypted values are all converted to ascii hex
before storing in db using the binascii.a2b_hex method which only operates
on even length values
'''
hexValues = True
# test to see if value is a hexadecimal
# get rid of ... | alue = value.strip()
try:
int(value, 16)
except ValueError:
hexValues = False
if hexValues == False or (len(value) % 2) != 0 :
return False
else:
# Have the encryption service verify if this is encrypted
return self.aes.is_encr... |
Mariaanisimova/pythonintask | PMIa/2015/Donkor_A_H/task_3_10.py | Python | apache-2.0 | 928 | 0.018018 | # Задача 3. Вариант 10.
# Напишите программу, которая выводит имя "Игорь Васильевич Лотарев", и запрашивает его псевдоним. Программа должна сцеплять две эти строки и выводить полученную строку, разделяя имя и псевдоним с помощью тире.
# Donkor A.H.
# 14.04.2016
print("Итак,гость нынешнего дня является русский по... | этого человека?")
input("\n\nВаш ответ: ")
print("\nВсе верно: Игорь Васильевич Лотарев - Северянин, Игорь Васильевич")
input("\n | Нажмите Enter для завершения") |
saberman888/Archiver | archive.py | Python | mit | 5,894 | 0.023583 | from __future__ import print_function
import sys, time
import requests, urllib
import demjson, shelve
import os.path
class Archi | ver:
def __init__(self):
"""
A class for archiving URLS into the wayback machine
"""
self._machine = "http://archive.org/wayback/available?url="
self._arch = "https://web.archive.org/save/"
self.archived | _urls = []
# load data
if os.path.isfile("archived_urls.dat"):
self.archived_urls = self.load_data()
def available(self, url, silent=False):
"""
:param: url
:param: silent=False
Checks if the given URL exists in the wayback machine.
... |
ExaScience/smurff | python/smurff/smurff.py | Python | mit | 3,868 | 0.009566 | from .trainsession import TrainSession
from .helper import FixedNoise
class SmurffSession(TrainSession):
def __init__(self, Ytrain, priors, is_scarce = True, Ytest=None, side_info=None, direct=True, *args, **kwargs):
TrainSession.__init__(self, priors=priors, *args, **kwargs)
self.addTrainAndTest(Y... | parse` matrix or :class: `SparseTensor`
Train matrix/tensor
Ytest : :mod:`scipy.sparse` matrix or :class: `SparseTensor`
Test matrix/tensor. Mainly used for calculating RMSE.
side_info : list of :class: `numpy.ndarray`, :mod:`scipy.sparse` matrix or None
... | Each side info should have as many rows as you have elemnts in corresponding dimension of `Ytrain`.
direct : bool
Use Cholesky instead of CG solver
univariate : bool
Use univariate or multivariate sampling.
\*\*args:
Extra arguments are pas... |
iti-luebeck/BEEP | Software/catkin_ws/src/beep_imu/ir_distance_zusmoro.py | Python | bsd-3-clause | 1,517 | 0.039552 | #!/usr/bin/env python
from __future__ import division
from std_msgs.msg import Int32
import roslib; roslib.load_manifest('beep_imu')
import rospy
import smbus
import time
bus = smbus.SMBus(1)
irAddress = 0x55
#pub_mag_xsens = rospy.Publisher('imu/mag', Vector3Stamped)
def decFrom2Compl(val, bitlen):
if val & (1... | and publishing Imu msg to topic Imu
def talker():
rospy.init_node('IRNode')
rospy.loginfo('starting IR_Node')
while not rospy.is_shutdown():
storeDistance()
rospy.sleep(0.05)
rospy.loginfo('IRNode shut down')
def storeDistance():
#read current linear accelerations
#msg = decFrom2Compl(msg,12)
#upd... | y.Publisher('topic/IR0', Int32)
msg = Int32()
msg.data = bus.read_byte_data(irAddress, 0x85)
msg.data += bus.read_byte_data(irAddress, 0x86) * 0x100
pub.publish(msg)
pub2.publish(msg)
print msg
if __name__ == '__main__':
init()
talker()
pass
|
ubaldino/pyloop | prueba3.py | Python | agpl-3.0 | 369 | 0.01897 | #encoding:utf-8
impo | rt Queue
import threading
import urllib2
# called by each thread
def get_url(q, url):
q.put(urllib2.urlopen(url).read())
theurls = '''http://google.com http://yahoo.com'''.split()
print theurls
q = Queue.Queue()
for u in theurls:
t = threading.Thread(target=get_url, args = (q,u))
t.daemon = True
t.... | s |
pepeportela/edx-platform | lms/djangoapps/instructor/features/common.py | Python | agpl-3.0 | 4,560 | 0.001316 | """
Define common steps for instructor dashboard acceptance tests.
"""
# pylint: disable=missing-docstring
# pylint: disable=redefined-outer-name
from __future__ import absolute_import
from lettuce import step, world
from mock import patch
from nose.tools import assert_in
from courseware.tests.factories import Inst... | dmin, data_download, analytics, send_email
tab_name_dict = {
'Course Info': 'course_info',
'Membership': 'membership',
'Student Admin': 'student_admin',
'Data Download': 'data_download',
| 'Analytics': 'analytics',
'Email': 'send_email',
}
go_to_section(tab_name_dict[tab_name])
|
Distrotech/scons | test/Script-import.py | Python | mit | 2,878 | 0.000695 | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# 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, merge, publish,
... | S OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Test that a module that we import into an SConscript file can itself
... | t the global SCons variables, and a handful of other variables
directly from SCons.Script modules.
"""
import TestSCons
test = TestSCons.TestSCons()
test.write('SConstruct', """\
import m1
""")
test.write("m1.py", """\
from SCons.Script import *
SConscript('SConscript')
""")
test.write('SConscript', """\
import m2... |
bozzzzo/quark | quarkc/test/emit/expected/py/defaulted-methods/defaulted_methods.py | Python | apache-2.0 | 87 | 0 | import defaulted_methods
if __name__ == "__main | __":
defaulted_methods | .call_main()
|
everyevery/programming_study | leetcode/404-SumOfLeftLeaves/sum_of_left_leaves.py | Python | mit | 719 | 0.002782 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def sumOfLeftLeavesRec(self, root, left) | :
if root is None:
return 0
elif root.left is None and root.right is None:
if left:
return root.val
else:
return 0
else:
return self.sumOfLeftLeavesRec(root.left, True) | + self.sumOfLeftLeavesRec(root.right, False)
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.sumOfLeftLeavesRec(root, False)
|
bharathramh92/easy-ecom | accounts/constants.py | Python | apache-2.0 | 102 | 0.009804 | __author__ = 'bharathramh'
EMAIL_VERIF | ICATION_EXPIRATION_DAYS = 1
FORGOT_PASSWORD_EXPIR | ATION_DAYS = 1 |
zitkino/backend | zitkino/spiders/praha_premierecinemas.py | Python | agpl-3.0 | 229 | 0 | # -*- coding: utf-8 -*-
from .base_premierecinemas | import BasePremierecinemasCinemaSpider
class Spider(BasePr | emierecinemasCinemaSpider):
name = 'praha-premierecinemas'
calendar_url = 'http://www.premierecinemas.cz/'
|
hainm/pythran | pythran/tests/openmp.legacy/omp_parallel_sections_reduction.py | Python | bsd-3-clause | 8,373 | 0.003583 | def omp_parallel_sections_reduction():
import math
dt = 0.5
rounding_error = 1.E-9
sum = 7
dsum = 0
dt = 1. / 3.
result = True
product = 1
logic_and = 1
logic_or = 0
bit_and = 1
bit_or = 0
i = 0
exclusiv_bit_or = 0
known_sum = (1000 * 999) / 2 + 7
if 'o... | :exclusiv_bit_or)':
if 'omp section':
for i in xrange(0, 300):
exclusiv_bit_or = (exclusiv_bit_or ^ logics[i])
if 'omp section':
for i in xrange(300, 700):
exclusiv_bit_or = (exclusiv_bit_or ^ logics[i])
if 'omp section':
for i ... | 0):
exclusiv_bit_or = (exclusiv_bit_or ^ logics[i])
if exclusiv_bit_or:
print "E: reduction(^:exclusiv_bit_or)"
result = False
exclusiv_bit_or = 0;
logics[1000/2]=1
if 'omp parallel sections private(i) reduction(^:exclusiv_bit_or)':
if 'omp section':
... |
SINGROUP/pycp2k | pycp2k/classes/_each126.py | Python | lgpl-3.0 | 1,114 | 0.001795 | from pycp2k.inputsection import InputSection
class _each126(InputSection):
def __init__(self):
InputSection.__init__(self)
self.Just_energy = None
self.Powell_o | pt = None
self.Qs_scf = None
self.Xas_scf = None
self.Md = None
self.Pint = None
self.Metadynamics = None
self.Geo_opt = None
self.Rot_opt = None
self.Cell_opt = None
self.Band = None
self.Ep_lin_solver = None
self.Spline_find_coeff... | lf.Tddft_scf = None
self._name = "EACH"
self._keywords = {'Bsse': 'BSSE', 'Cell_opt': 'CELL_OPT', 'Just_energy': 'JUST_ENERGY', 'Band': 'BAND', 'Xas_scf': 'XAS_SCF', 'Rot_opt': 'ROT_OPT', 'Replica_eval': 'REPLICA_EVAL', 'Tddft_scf': 'TDDFT_SCF', 'Shell_opt': 'SHELL_OPT', 'Md': 'MD', 'Pint': 'PINT', 'Met... |
osgcc/ryzom | nel/tools/build_gamedata/processes/pacs_prim_list/0_setup.py | Python | agpl-3.0 | 1,786 | 0.006719 | #!/usr/bin/python
#
# \file 0_setup.py
# \brief setup pacs_prim_list
# \date 2011-09-28 7:22GMT
# \author Jan Boon (Kaetemi)
# Python port of game data build pipeline.
# Setup pacs_prim_list
#
# NeL - MMORPG Framework <http://de | v.ryzom.com/projects/nel/>
# Copyright (C) 2010 Winch Gate Property Limited
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pu | blished by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Af... |
pixunil/Cinnamon | files/usr/share/cinnamon/cinnamon-settings/modules/cs_effects.py | Python | gpl-2.0 | 10,983 | 0.004826 | #!/usr/bin/env python2
from GSettingsWidgets import *
from ChooserButtonWidgets import TweenChooserButton, EffectChooserButton
EFFECT_SETS = {
"cinnamon": ("traditional", "traditional", "traditional", "none", "none", "none"),
"scale": ("scale", "scale", "scale", "scale", "scale", "scale... | schema] = Gio.Settings.new(schema)
self.settings = settings_objects[schema]
super(GSettingsEffectChooserButton, self).__i | nit__(options)
self.bind_settings()
class Module:
name = "effects"
category = "appear"
comment = _("Control Cinnamon visual effects.")
def __init__(self, content_box):
keywords = _("effects, fancy, window")
sidePage = SidePage(_("Effects"), "cs-desktop-effects", keywords, conte... |
lordamit/youtube-dl-gui | youtube-dl-gui.py | Python | gpl-3.0 | 3,654 | 0.001368 | #!/usr/bin/python
# Youtube-dl-GUI provides a front-end GUI to youtube-dl
# Copyright (C) 2013 Amit Seal Ami
#
# Th== program == 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 t... | check_url(self, url_tobe_checked):
"""
@param url_tobe_checked:
@return:
"""
try:
code = urlopen(url_tobe_checked).code
except ValueError:
return False
except HTTPError:
return False |
if (code / 100) >= 4:
return False
else:
return True
def return_youtube_dl_cmd(self):
from os.path import expanduser
home = expanduser("~")
cmd = "gnome-terminal -e "
cmd += '"youtube-dl -f{0} -c -o {1}/Downloads/%(title)s-%(id)s.%(ext)s {2}... |
technomaniac/trelliopg | trelliopg/__init__.py | Python | mit | 118 | 0.008475 | from .sql import *
__all__ = ['DBAdapter', 'get_db_adapter', 'async_a | tomic', 'async_atomic_func', 'get_db_settings']
| |
lambdal/envois | test/test_envois.py | Python | mit | 1,000 | 0.004 | #-*- coding: utf-8 -*-
"""
envois.test
~~~~~~ | ~~~~~ | ~
nosetests for the envois pkg
:copyright: (c) 2012 by Mek
:license: BSD, see LICENSE for more details.
"""
import os
import json
import unittest
from envois import invoice
jsn = {"seller": {"name": "Lambda Labs, Inc.", "address": {"street": "857 Clay St. Suite 206", "city": "San Francisco", "state": "CA... |
jasonwee/asus-rt-n14uhp-mrtg | src/lesson_text/re_fullmatch.py | Python | apache-2.0 | 247 | 0.004049 | import re
text = 'This is some text -- with punctuation.'
pattern = 'is'
print('Text :', text)
print('Pattern :', pattern)
m = re.search(pattern, text)
prin | t('Search :', m)
s = re.fullmatch( | pattern, text)
print('Full match :', s)
|
yland/coala | tests/parsing/StringProcessing/PositionIsEscapedTest.py | Python | agpl-3.0 | 2,282 | 0 |
from coalib.parsing.StringProcessing import position_is_escaped
from tests.parsing.StringProcessing.StringProcessingTestBase import (
StringProcessingTestBase)
class PositionIsEscapedTest(StringProcessingTestBase):
# Test the position_is_escaped() function.
def test_basic(self):
expected_results... | 31 * [False] + [True] + 6 * [False],
38 * [False],
6 * [Fals | e] + [True] + 31 * [False],
6 * [False] + [True, False, True] + 29 * [False],
6 * [False] + [True] + 31 * [False],
6 * [False] + [True, False, True] + 29 * [False],
14 * [False] + [True] + 23 * [False],
12 * [False] + [True, False, True] + 23 * [False],
... |
jeremiahyan/odoo | addons/l10n_cl/models/account_move.py | Python | gpl-3.0 | 9,118 | 0.005485 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.exceptions import ValidationError
from odoo import models, fields, api, _
from odoo.osv import expression
SII_VAT = '60805000-0'
class AccountMove(models.Model):
_inherit = "account.move"
partner_id_... | (l10n_latam_document_type_id)s AND ' \
'company_id = %(company_id)s AND move_type IN %(move_type)s'
param['company_id'] = self.company_id.id or False
param['l10n_latam_document_type_id'] = self.l10 | n_latam_document_type_id.id or 0
param['move_type'] = (('in_invoice', 'in_refund') if
self.l10n_latam_document_type_id._is_doc_type_vendor() else ('out_invoice', 'out_refund'))
return where_string, param
def _get_name_invoice_report(self):
self.ensure_one()
if ... |
hankcs/HanLP | plugins/hanlp_common/hanlp_common/visualization.py | Python | apache-2.0 | 10,303 | 0.000883 | # -*- coding:utf-8 -*-
# Modified from https://github.com/tylerneylon/explacy
import io
from collections import defaultdict
from pprint import pprint
from phrasetree.tree import Tree
def make_table(rows, insert_header=False):
col_widths = [max(len(s) for s in col) for col in zip(*rows[1:])]
rows[0] = [x[:l] ... | pec) is int:
return str(record[field_spec])
elif type(field_spec) is str:
return str(getattr(record, field_spec))
else:
return str(field_spec(record))
def markdown_table(headings, records, fields=None, alignment=None, file=None):
"""Ge | nerate a Doxygen-flavor Markdown table from records.
See https://stackoverflow.com/questions/13394140/generate-markdown-tables
file -- Any object with a 'write' method that takes a single string
parameter.
records -- Iterable. Rows will be generated from this.
fields -- List of fields for each... |
natj/bender | sweep.py | Python | mit | 8,380 | 0.024105 | import sys
sys.path.append('/Users/natj/projects/arcmancer/lib/')
import pyarcmancer as pyac
from img import Imgplane
from visualize_polar import Visualize
from lineprofile import *
import units
import numpy as np
import matplotlib as mpl
from pylab import *
import os
from matplotlib import cm
import scipy.interpol... | rofile
##################################################
#ax = subplot(gs[2,2])
#ax.set_xlim(0.8, 1.2)
visz.axs[6].plot(e | s, yy2, "b-")
pause(1.0)
fname = 'neutronstar_f{:03d}_bb_r{:02d}_m{:03.1f}_i{:02d}.png'.format(
np.int(freq),
np.int(R),
M,
np.int(incl),
)
savef... |
ganga-devs/ganga | ganga/GangaND280/Tasks/ND280Transform_CSVEvtList.py | Python | gpl-3.0 | 4,112 | 0.020185 | from GangaCore.GPIDev.Schema import *
from GangaCore.GPIDev.Lib.Tasks.common import *
from GangaCore.GPIDev.Lib.Tasks.ITransform import ITransform
from GangaCore.GPIDev.Lib.Job.Job import JobError
from GangaCore.GPIDev.Lib.Registry.JobRegistry import JobRegistrySlice, JobRegistrySliceProxy
from GangaCore.Core.exception... | oTRF( unit )
def createChainUnit( self, parent_units, use_copy_output = True ):
"""Create a chained unit using the output data from the given units"""
# check all parent units for copy_output
copy_output_ok = True
for parent in parent_units:
if not parent.copy_output:
... | ompleted so the outputfiles are filled correctly
for parent in parent_units:
if parent.status != "completed":
return None
if not use_copy_output or not copy_output_ok:
unit = ND280Unit_CSVEvtList()
unit.inputdata = ND280LocalDataset()
for parent in parent_... |
flgiordano/netcash | +/google-cloud-sdk/lib/googlecloudsdk/core/resource/resource_projection_spec.py | Python | bsd-3-clause | 10,147 | 0.00542 | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | .attribute.flag = self.DEFAULT
for node in projection.tree.values():
self._Defaults(node)
def _Print(self, projection, out, level):
"""Print() helper -- prints projection node p and its children.
Args:
projection: A _Tree node in the original projection.
out: The output stream.
l... | indent=' ' * level,
key=key,
attribute=projection.tree[key].attribute))
self._Print(projection.tree[key], out, level + 1)
def AddAttribute(self, name, value):
"""Adds name=value to the attributes.
Args:
name: The attribute name.
value: The attribute value
""... |
danrschlosser/eventum | tests/test_text.py | Python | mit | 790 | 0 | import pytest
from eventum.lib.text import clean_markdown
@pytest.mark.parametrize(["markdown", "output"], [
('**Bold** text is unbolded.', 'Bold text is unbolded.'),
('So is *underlined* text.', 'So is underlined text.'),
('An [](http://empty-link).', 'An.'),
('A [test](https://adicu.com)', 'A test ... | https://adicu.com)'),
('A [test](http://adicu.com)', 'A test (http://adicu.com)'),
('A [test](garbage) passes.', 'A test passes.'),
('An  gets removed.', 'An gets removed.'),
('An , [link](http://adicu.com), and an '
'[](http://adi... | assert clean_markdown(markdown) == output
|
jedie/pypyjs-standalone | website/js/pypy.js-0.3.0/lib/modules/distutils/sysconfig_pypy.py | Python | mit | 4,713 | 0.001485 | """Provide access to Python's configuration information.
This is actually PyPy's minimal configuration information.
The specific configuration variables available depend heavily on the
platform and configuration. The values may be retrieved using
get_config_var(name), and the list of variables is available via
get_co... | return a dictionary of all configuration
variables relevant for the current platform. Generally th | is includes
everything needed to build extensions and install both pure modules and
extensions. On Unix, this means every variable defined in Python's
installed Makefile; on Windows and Mac OS it's a much smaller set.
With arguments, return a list of values that result from looking up
each argumen... |
projectbuendia/server-status | libraries/Adafruit_Nokia_LCD/setup.py | Python | apache-2.0 | 591 | 0.099831 | from ez_setup import use | _setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(name = 'Adafruit_Nokia_LCD',
version = '0.1.0',
author = 'Tony DiCola',
author_email = 'tdicola@adafruit.com',
description = 'Library to display images on the Nokia 5110/3110 LCD.',
license = 'MIT',
url = '... | install_requires = ['Adafruit-GPIO>=0.1.0'],
packages = find_packages())
|
zmlabe/IceVarFigs | Scripts/SeaIce/JAXA_seaice_movinglines.py | Python | mit | 6,992 | 0.034611 | """
Plots Arctic sea ice extent from June 2002-present using JAXA metadata
Website : https://ads.nipr.ac.jp/vishop/vishop-extent.html
Author : Zachary M. Labe
Date : 4 August 2016
"""
### Import modules
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplo... | year
currentyear[59] = currentyear[58]
### Changes
weekchange = currentice - currentyear[lastday-7 | ]
daychange = currentice - currentyear[lastday-1]
### Make plot
matplotlib.rc('savefig', facecolor='black')
matplotlib.rc('axes', edgecolor='white')
matplotlib.rc('xtick', color='white')
matplotlib.rc('ytick', color='white')
matplotlib.rc('axes', labelcolor='white')
matplotlib.rc('axes', facecolor='black')
plt.rc('tex... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.