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 |
|---|---|---|---|---|---|---|---|---|
obi-two/Rebelion | data/scripts/templates/object/building/poi/shared_anywhere_rebel_camp_small_2.py | Python | mit | 458 | 0.045852 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Building()
result.template = "object/building/poi/sha | red_anywhere_rebel_camp_small_2.iff"
result.attribute_template_id = -1
result.stfName("poi_n","base_poi_building")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return res | ult |
wndias/bc.repository | script.module.urlresolver/lib/urlresolver/plugins/usersfiles.py | Python | gpl-2.0 | 2,201 | 0.003635 | # -*- coding: UTF-8 -*-
"""
Copyright (C) 2015 tknorris
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
... | cense for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import re
from lib import jsunpack
f | rom urlresolver import common
from urlresolver.resolver import UrlResolver, ResolverError
class UsersFilesResolver(UrlResolver):
name = "UsersFiles"
domains = ["usersfiles.com"]
pattern = '(?://|\.)(usersfiles\.com)/(?:embed-)?([0-9a-zA-Z/]+)'
def __init__(self):
self.net = common.Net()
... |
yamaguchiyuto/icwsm15 | indegree_distribution.py | Python | mit | 510 | 0.009804 | import sys
filepath = sys | .argv[1]
delim = '\t'
if len(sys.argv) > 2:
delim = sys.argv[2]
indegrees = {}
for line in open(filepath):
entry = line.rstrip().split(delim)
src = entry[0]
dst = entry[1]
tag = entry[2]
if not dst in | indegrees: indegrees[dst] = 0
indegrees[dst] += 1
distribution = {}
for nid in indegrees:
d = indegrees[nid]
if not d in distribution: distribution[d] = 0
distribution[d] += 1
for d, count in sorted(distribution.items()):
print d,count
|
setrar/INF1069 | C.PYTHON/mysql.py | Python | mit | 475 | 0.008421 | #!/usr/bin/python
# Script pour telecharger City
import MySQLdb
file_ = open('city.csv', 'w')
file_.write ('city_id,city,country_id\n')
db = MySQLdb.connect( user='etudiants',
| passwd='etudiants_1',
host='192.168.99.100',
db='sakila')
cur = db.cursor()
cur.execute("SELECT * FROM city")
|
for row in cur.fetchall():
file_.write(str(row[0])+','+ row[1]+','+ str(row[2])+'\n')
db.close()
file_.close()
|
damaggu/SAMRI | samri/examples/2017-09_aic-pom.py | Python | gpl-3.0 | 774 | 0.040052 | from os import path
import matplotlib.pyplot as plt
from samri.plotting.aggregate import registration_qc
from samri.typesetting import inline_anova
this_path = path.dirname(path.realpath(__file__))
data_dir = path.join(this_path,"../../example_data/")
df_path = path.join(data_dir,"f_reg_quality.csv")
plt.style.use(p... | ={"similarity":"Similarity"},
group={"subject":"Subject"},
repeat={"session":"Session"},
extra={"acquisition":"Type"},
save_as="2017-09_aic-pom.pdf",
show=False,
samri_style=False,
extra_cmap=["#FFFFFF","#000000"],
cmap=["#EE1111","#11DD11","#1111FF","#CCCC22","#AA11AA"],
values_rename={
"sub":"Subject",
"... | },
)
|
XiangYz/webscraper | test10.py | Python | lgpl-2.1 | 368 | 0.019022 | import requests
params = {'username':'Ryan', 'password':'password'}
r = requests.post("http://pythonscraping.com/pages/cookies/welcome.php", params)
print("Cookie is set to:")
print(r.cookies.get_dict())
print("-------------")
print("Going to profile page...")
r = requests.get("http://pythonscraping.c | om/pages/cookies/p | rofile.php", cookies = r.cookies)
print(r.text) |
Ralev93/Clan-site | clan_site/battles/forms.py | Python | gpl-3.0 | 1,375 | 0.022545 | from django import forms
from django.contrib.admin.widgets import AdminDateWidget
from django.forms import ModelForm
from basic.models import *
from battles.models import *
from itertools import chain
def getMemberAsOptions():
members = Member.objects.all()
return [(member.id, member.get_username()) for member in m... | itoriesAsOptions())
class ClanWarForm(Battle):
clan_war_type | = forms.ChoiceField(ClanWar.CLAN_WAR_TYPES)
result = forms.ChoiceField(ClanWar.RESULT_CHOICES)
enemy_clans=forms.CharField(max_length=50)
class HypothesisForm(forms.Form):
def __init__(self, *args, **kwargs):
super(HypothesisForm, self).__init__(*args, **kwargs)
for i in Hypothesis.OPPONENTS:
... |
anhstudios/swganh | data/scripts/templates/object/building/poi/shared_corellia_solitude_medium3.py | Python | mit | 456 | 0.046053 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Building()
result.template = "object/building/poi/sha | red_corellia_solitude_medium3.iff"
result.attribute_template_id = -1
result.stfName("poi_n","base_poi_building")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS | ####
return result |
pashinin-com/pashinin.com | src/core/tests/__init__.py | Python | gpl-3.0 | 1,556 | 0 | import requests
import gzip
from io import BytesIO
def validate_html(html, content_type):
# 'node_modules/vnu-jar/build/dist/vnu.jar'
vnu_url = 'http://vnu:8888'
with BytesIO() as buf:
with gzip.GzipFile(fileobj=buf, mode='wb') as gzipper:
gzipper.write(html)
gzippeddata = buf.... | 'Content-Encoding': 'gzip',
'Content-Length': str(len(gzippeddata)),
},
data=gzippeddata
)
return r.text.strip()
def validate_process(res, html):
# t = validate_html(html, ct)
if res == '':
return
# print(t)
print('- - - - -')
res = ''
erro... | msg = error_string[len(rng+cls)+2:].strip()
# for skip in skips:
# if skip in msg:
# continue
print(rng, msg)
linePos1, linePos2 = rng.split('-')
line1, pos1 = map(int, linePos1.split('.'))
line2, pos2 = map(int, linePos2.split('.'))
# for li... |
joelfiddes/toposubv2 | topoMAPP/getERA/era_prep.py | Python | gpl-3.0 | 1,384 | 0.013006 | #!/usr/bin/env python
""" This module preprocesses ERA-Interim data, units, accumulated to instantaneous values and timestep interpolation for 6 h to 3 h va | lues.
Example:
as import:
from getERA import era_prep as prep
prep.main(wd, config['main']['startDate'], config['main']['endDate'])
Attributes:
wd = "/home/joel/sim/topomap_test/"
plotshp = TRUE
Todo:
"""
path2script = "./rsrc/toposcale_pre2.R"
# main
def main(wd, startDate, ... | , startDate, endDate])
# functions
def run_rscript_stdout(path2script , args):
""" Function to define comands to run an Rscript. Returns an object. """
import subprocess
command = 'Rscript'
cmd = [command, path2script] + args
print("Running:" + str(cmd))
x = subprocess.check_output(cmd,... |
antoinecarme/pyaf | tests/model_control/detailed/transf_RelativeDifference/model_control_one_enabled_RelativeDifference_MovingMedian_BestCycle_AR.py | Python | bsd-3-clause | 163 | 0.04908 | import tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['RelativeDiff | erence'] , ['MovingMedian'] , ['BestCycle'] , ['AR'] | ); |
Rambatino/CHAID | CHAID/__init__.py | Python | apache-2.0 | 239 | 0 | from .split import Split
from .tree import Tree
from .node import Node
from .column import NominalColumn, OrdinalColumn, ContinuousColumn
from .stats import Stats
from .invali | d_split | _reason import InvalidSplitReason
__version__ = "5.3.0"
|
icatproject/python-icat | tests/test_06_ingest.py | Python | apache-2.0 | 11,631 | 0.006276 | """Test icatdump and icatingest.
"""
from subprocess import CalledProcessError
import pytest
import icat
import icat.config
from icat.query import Query
from conftest import DummyDatafile, gettestdata, getConfig, callscript
# Test input
ds_params = str(gettestdata("ingest-ds-params.xml"))
datafiles = str(gettestdata... | set_params(client, dataset, {
("Magnetic field", 5.3, "T"),
("Reactor power", 5.0, "MW")
})
def test_ingest_duplicate_ignore(client, dataset, | cmdargs):
"""Ingest with a collision of a duplicate object.
Same test as above, but now ignore the duplicate.
"""
dataset.create()
ptype = client.assertedSearch("ParameterType [name='Reactor power']")[0]
p = client.new("datasetParameter", numericValue=5.0,
dataset=dataset, ... |
rajalokan/nova | nova/tests/unit/test_identity.py | Python | apache-2.0 | 3,137 | 0 | # Copyright 2017 IBM Corp.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file ex | cept in compliance with the License. You may obtain
# a copy of the Li | cense at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the spe... |
dennybaa/st2 | st2api/st2api/signal_handlers.py | Python | apache-2.0 | 941 | 0 | # Licensed | to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file exc... | e 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
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or ... |
mou4e/zirconium | tools/perf/page_sets/key_hit_test_cases.py | Python | bsd-3-clause | 1,778 | 0.004499 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import page as page_module
from telemetry.page import page_set as page_set_module
class KeyHitTestCasesPage(page_module.Page):
def _... | type = 'mobile'
def RunNavigateSteps(self, action_runner):
super(KeyHitTestCasesPage, self).RunNavigateSteps(action_runner)
action_runner.Wait(2)
def RunPageInteractions(self, action_runner):
action_runner.Wait(2)
for _ in xrange(100):
self.TapButton(action_runner)
class PaperCalculatorH... | github.com/zqureshi/paper-calculator
# vulcanize --inline --strip paper-calculator/demo.html
url='file://key_hit_test_cases/paper-calculator-no-rendering.html',
page_set=page_set)
def TapButton(self, action_runner):
interaction = action_runner.BeginInteraction(
'Action_TapAction')
a... |
AKSW/LODStats | test/test_lodstats.py | Python | gpl-3.0 | 1,647 | 0.001821 | import unittest
from requests.exceptions import HTTPError
import lodstats
from lodstats import RDFStats
from requests import HTTPError
from . import helpers
http_base = he | lpers.webserver(helpers.resources_path)
testfile_path = helpers.resources_path
class LodstatsTest(unittest.TestCase):
d | ef setUp(self):
lodstats.stats.stats_to_do = []
lodstats.stats.results = {}
def test_remote_bz2(self):
uri = http_base + 'heb.rdf.bz2'
rdfstats = RDFStats(uri)
#rdfstats.set_callback_function_download(test_callback_download)
#rdfstats.set_callback_function_extraction... |
tgalal/inception | inception/argparsers/makers/submakers/submaker_supersu.py | Python | gpl-3.0 | 4,484 | 0.006467 | from .submaker import Submaker
import zipfile
import os
import shutil
import logging
logger = logging.getLogger(__name__ )
class SuperSuSubmaker(Submaker):
def make(self, workDir):
supersuZipProp = self.getTargetConfigProperty("root.methods.supersu.path")
assert supersuZipProp.getValue(), "Must s... | eArchs) else archs
newSuperSuZip = zipfile.ZipFile(newSuperSuZipPath, "w")
| for arch in targetArchs:
self.__addDirToZip(newSuperSuZip, os.path.join(tmpDir, arch), arch)
if not includeApk:
os.remove(os.path.join(tmpDir, superuserApkPath))
self.__addDirToZip(newSuperSuZip, os.path.join(tmpDir, "common"), "comm... |
zacharyvoase/relations | test/test_joins.py | Python | unlicense | 867 | 0 | import relations
employees = relations.Relation('name', 'emp_id', 'dept_name')
employees.add(name='Harry', emp_id=3415, dept_name='Finance')
employees.add(name='Sally', emp_id=2241, dept_name='Sales')
employees.add(name='George', emp_id=3401, dept_name='Finance')
employees.add(name='Harriet', emp_id=2202, dept_name='... | departments.add(dept_name='Sales', manager='Harriet')
departments.add(dept_name='Production', manager='Charles')
def test_natural_join():
joined = employees.natural_join(departments)
assert len(joined) == 4
def test_natural_join_on_disjoint_relations_is_cartesian_product():
joined = employees.project('... | al_join(departments)
assert len(joined) == (len(employees) * len(departments))
|
jorisvanzundert/sfsf | sfsf/sfsf_config.py | Python | mit | 717 | 0.033473 | import os
PRODUCTION = 'merged-corpus'
DEVELOPMENT = 'test'
ENVIRONMENT = PRODUCTION
EPUB = 'epub'
EPUB_DIRNAME = EPUB
TXT = 'txt'
TXT_DIRNAME = TXT
def set_env( env=PRODUCTION ):
global ENVIRONMENT
| ENVIRONMENT = env
def get_data_dir():
path_to_here = os.path.dirname( os.path.abspath( __file__ ) )
if ENVIRONMENT == DEVELOPMENT:
data_dir = os.path.join( path_to_here, '../data/{t}'.format( t=DEVELOPMENT ) )
else:
data_dir = os.path.join( path_to_here, '../../docker_volume/{p}'.format(... | data_dir(), TXT_DIRNAME )
|
Chandra-MARX/marx-test | tests/source.py | Python | gpl-2.0 | 10,336 | 0.002032 | '''
|marx| offers several different source shapes. Tests in this module exercise
those sources (except ``SAOSAC``, which is heavily used in
:ref:`sect-tests.PSF` already).
'''
import shutil
import subprocess
import os
from collections import OrderedDict
from marxtest import base
title = 'Sources in |marx|'
tests = ... | geometric sources'
figures = OrderedDict([('ds9', {'alternative': 'Six PSFs.',
| 'caption': '`ds9`_ image of the simulated PSFs in alphabetical order (beta distribution, disk, disk with hole, Gauss, line, and point).'})
])
@base.Marx
def step_10(self):
return [{'OutputDir': 'point'},
{'SourceType': 'GAUSS', 'S-GaussSigma': 20,
... |
chemreac/chemreac | chemreac/chemistry.py | Python | bsd-2-clause | 1,640 | 0 | # -*- coding: utf-8 -*-
"""
chemreac.chemistry
==================
This module collects classes useful for describing substances,
reactions and reaction systems. The classes have methods to help
with consistent low-level conversion to numerical parameters of
the model. The classes are from the
`chempy <https | ://pypi.python. | org/pypi/chempy>`_ package.
"""
from __future__ import print_function, division, absolute_import
from collections import OrderedDict
from chempy import Substance, Reaction, ReactionSystem
def mk_sn_dict_from_names(names, **kwargs):
"""
Convenience function to generate a OrderedDict of Substance
instance... |
bolkedebruin/airflow | airflow/jobs/scheduler_job.py | Python | apache-2.0 | 57,604 | 0.003368 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | rs.executor_loader import UNPICKLEABLE_EXECUTORS
from airflow.jobs.base_job import BaseJob
from airflow.jobs.local_task_job import LocalTaskJob
from airflow.models import DAG
from airflow.models.dag import DagModel
from airflow.models.dagbag import DagBag
from airflow.models.dagrun import DagRun
from airflow.models.ser... | ts import Stats
from airflow.ti_deps.dependencies_states import EXECUTION_STATES
from airflow.utils import timezone
from airflow.utils.docs import get_docs_url
from airflow.utils.event_scheduler import EventScheduler
from airflow.utils.retries import MAX_DB_RETRIES, retry_db_transaction, run_with_db_retries
from airflo... |
tadgh/ArgoRevisit | third_party/nltk/parse/nonprojectivedependencyparser.py | Python | apache-2.0 | 27,018 | 0.00533 | # Natural Language Toolkit: Dependency Grammars
#
# Copyright (C) 2001-2011 NLTK Project
# Author: Jason Narad <jason.narad@gmail.com>
#
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
#
import math
from nltk.grammar import parse_dependency_grammar
from dependencygraph import *
############... | row.append([math.log(pdist.prob("T"))])
count += 1
if count == len(graph.nodelist):
edge_scores.append(row)
row = []
count = 0
return edge_scores
#################################################################
# A ... | #########
# A short class necessary to show parsing example from paper
class DemoScorer:
def train(self, graphs):
print 'Training...'
def score(self, graph):
# scores for Keith Hall 'K-best Spanning Tree Parsing' paper
return [[[], [5], [1], [1]],
[[], [], [11], [4]... |
jonasprobst/wandering-pillar-cli | firebase-test.py | Python | mit | 292 | 0.003425 | from firebase import | firebase
firebase = firebase.FirebaseApplication('https://wapi.firebaseio.com', None)
new_user = 'Ozgur Vatansever'
result = firebase.post('/users', new_user, name=None, connection=None, params={'print': 'pretty'}, headers={'X_FANCY_HEADER': 'VERY FANC | Y'})
print result
|
liboyin/algo-prac | arrays/longest_increasing_subsequence.py | Python | gpl-3.0 | 3,290 | 0.006079 | from bisect import bisect_left
from lib import argmax, bin_search_left, yield_while
from math import inf
def search(arr): # binary search, length only. O(n\log n) time
st = [arr[0]] # st[i]: smallest tail of LIS of length i + 1. naturally sorted, and all elements are distinct
for x in arr:
if x > st[... | for _ in range(100):
rnd_test = list(range(50 | )) * 4
shuffle(rnd_test)
n = search(rnd_test)
bs = search2(rnd_test)
dp = search3(rnd_test)
assert n == len(bs) == len(dp)
for i in range(n - 1):
assert rnd_test[bs[i]] < rnd_test[bs[i + 1]]
assert rnd_test[dp[i]] < rnd_test[dp[i + 1]]
|
tommyip/zulip | zerver/tests/test_push_notifications.py | Python | apache-2.0 | 82,169 | 0.002312 | from contextlib import contextmanager
import datetime
import itertools
import requests
import mock
from mock import call
from typing import Any, Dict, List, Optional
import base64
import os
import ujson
import uuid
from django.test import override_settings
from django.conf import settings
from django.http import Http... | otifications import (
absolute_avatar_url,
b64_to_hex,
datetime_to_timestamp,
DeviceToken,
get_apns_client,
get_display_recipient,
get_message_payload_apns,
get_message_payload_gcm,
get_mobile_push_content,
handle_push_notification,
handle_remove_push_notification,
hex_to... | _notification,
send_notifications_to_bouncer,
send_to_push_bouncer,
)
from zerver.lib.remote_server import send_analytics_to_remote_server, \
build_analytics_data, PushNotificationBouncerException
from zerver.lib.request import JsonableError
from zerver.lib.test_classes import (
TestCase, ZulipTestCase,... |
zoowii/pia-cloud | cloudweb/app/db.py | Python | mit | 85 | 0.011765 | from core import db
fro | m auth import models
from admin import models
db.create_al | l() |
plang85/rough_surfaces | examples/example_contact.py | Python | mit | 1,319 | 0.001516 | import numpy as np
import rough_surfaces.params as rp
import rough_surfaces.generate as rg
import rough_surfaces.analyse as ra
import rough_surfaces.surface as rs
import rough_surfaces.contact as rc
import matplotlib.pyplot as plt
from matplotlib import rcParams
import rough_surfaces.plot as rplt
# TODO dont do this
rc... | , seed=0)
E, nu = 1.0E+9, 0.3
dxy = 1.0E-3
nominal_stress = 1.0E7
contact = rc.contact_FFT(surface, nominal_stress, E, nu, verbose=2, err_lim=1.0E-8)
if 1:
fig, ax = plt.subplots()
rplt.traces(ax, surface, [contact.u], 128)
unit_den = '(m)'
ax.set_xlabel('x ' + unit_den)
ax.set_ylabel('y ' + unit_... | , x)
pressure_plot = ax.pcolor(XX, YY, contact.p)
ax.axis('equal')
unit_den = '(m)'
ax.set_xlabel('x ' + unit_den)
ax.set_ylabel('y ' + unit_den)
cbar = plt.colorbar(pressure_plot)
cbar.set_label('Pressure (Pa)', rotation=270)
plt.show()
|
Jacobious52/PythonLab | osxpasscrack.py | Python | gpl-2.0 | 886 | 0.029345 | import itertools
import subprocess
import sys
#http://pastebin.com/zj72xk4N
#run when system password box is showing eg. keychain password dialog
#apple script for automating dialog box input
sys_script = '''
tell application "System Events" to tell process "SecurityAgent"
set value of text field 1 of window 1 to $... | login():
for l in xrange(0, len(keys)+1):
for subset in itertools.permutations(keys, l):
guess = ''.join(subset)
tmp = sys_script.replace('$(PASS)', '"%s"' % guess)
try:
subprocess.check_output('osascript -e \'%s\'' % tmp, shell=True)
sys.stdout.write('\rtrying %s ' % guess)
sys.stdout.flush()
... | n
automate_login() |
noironetworks/group-based-policy | gbpservice/nfp/core/sequencer.py | Python | apache-2.0 | 4,161 | 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
# d... | uencerBusy(Exception):
pass
"""Sequences the events. """
class EventSequencer(object):
class Sequencer(object):
def __init__(self):
# Events not scheduled are queued
self._waitq = deque()
# Currently scheduled event
self._scheduled = None
de... | cerBusy
def _is_empty(self):
if not len(self._waitq):
raise SequencerEmpty
def sequence(self, event):
self._waitq.append(event)
def run(self):
"""Run to get event to be scheduled.
If sequencer is busy - i.e, an event is alre... |
mo-g/iris | lib/iris/tests/unit/fileformats/pp_rules/test__reshape_vector_args.py | Python | gpl-3.0 | 5,242 | 0 | # (C) British Crown Copyright 2014 - 2015, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any l... | xpected = [np.array(points)]
self._check(result, expected)
def test_transpose(self):
points = np.array([[1, 2, 3], [4, 5, 6]])
result = _reshape_vector_args([(points, (1, 0))])
expected = [points.T]
self._check(result, expected)
def test_extend(self):
points = n... | result = _reshape_vector_args([(points, (1, 3))])
expected = [points.reshape(1, 3, 1, 4)]
self._check(result, expected)
class TestMultipleArgs(tests.IrisTest):
def _check(self, result, expected):
self.assertEqual(len(result), len(expected))
for result_arr, expected_arr in zip(re... |
jgoodell/chess-algebra | tests.py | Python | apache-2.0 | 1,483 | 0.002697 | from unittest import TestCase
from chess import get_potential_moves
class ChessTestCase(TestCase):
def setup(self):
pass
def teardown(self):
pass
def test_knight(self):
response = get_potential_moves('knight', 'd2')
response = [each.strip() for each in response.split(',')... | ponse), len(possible_moves))
for each in possible_moves:
self.assertTrue(each in response)
def test_queen(self):
response = get_potential_moves | ('queen', 'd4')
response = [each.strip() for each in response.split(',')]
possible_moves = ['a4', 'b4', 'c4', 'e4', 'f4', 'g4', 'h4',
'd1', 'd2', 'd3', 'd5', 'd6', 'd7', 'd8',
'a7', 'b6', 'c5', 'e3', 'f2', 'g1',
'a1', 'b2', 'c... |
lol/BCI-BO-old | plot_iv2a.py | Python | gpl-3.0 | 4,270 | 0.016862 | import numpy as np
import matplotlib.pyplot as plt
import math
from pylab import figure
from my_plotter import *
import os
import sys
sys.path.append('./BCI_Framework')
import Main
import Single_Job_runner as SJR
import os
import re
if __name__ == '__main__':
bciciv1 | = Main.Main('BCI_Framework','BCICIV2a','RANDOM_FOREST', 'BP', 'ALL', -1, 'python')
res_path = bciciv1.config.configuration['resu | lts_opt_path_str']
classifiers_dict = {'Boosting':0, 'LogisticRegression_l1':1, 'LogisticRegression_l2':2, 'RANDOM_FOREST':3,'SVM_linear':4, 'SVM_rbf':5 }
features_dict = {'BP':0, 'logbp':1, 'wackerman':2,'BPCSP':3, 'logbpCSP':4, 'wackermanCSP':5}
results = np.zeros((len(classifiers_dict),len(features_dict)... |
fredwulei/fredsneverland | fredsneverland/timeline/urls.py | Python | mit | 130 | 0.007692 | from django.conf.urls import url
from timeline import views
urlpatterns = [
url(r'^$', views.timelines, name='timelines'), |
] | |
naveensan1/nuage-openstack-neutron | nuage_neutron/plugins/nuage_ml2/securitygroup.py | Python | apache-2.0 | 12,033 | 0 | # Copyright 2016 NOKIA
#
# 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... | OUPS]))
self.vsdclient.check_unused_policygroups(deleted_sg_ids)
@TimeTracker.tracked
def post_port_delete(self, resource, event, trigger, **kwargs):
port = kwargs['port']
subnet_mapping = kwargs['subnet_mapping | ']
if subnet_mapping['nuage_managed_subnet']:
return
securitygroups = port.get(ext_sg.SECURITYGROUPS, [])
successful = False
attempt = 1
while not successful:
try:
self.vsdclient.check_unused_policygroups(securitygroups)
su... |
Phy-David-Zhang/UnivMathSys | Technology/TopModuleInit/__init__.py | Python | gpl-3.0 | 329 | 0.009119 | # Initialization of All Modules of UnivMathSys
# Copyright (C) | 2016 Zhang Chang-kai #
# Contact via: phy.zhangck@gmail.com #
# General Public License ver | sion 3.0 #
'''Initialization of All Modules'''
from Foundation import *
from Elementary import *
from Structure import *
# End of Initialization of All Modules
|
elbeardmorez/quodlibet | quodlibet/gdist/__init__.py | Python | gpl-2.0 | 7,360 | 0 | # -*- coding: utf-8 -*-
# Copyright 2007 Joe Wreschnig
# 2012-2016 Christoph Reiter
#
# 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 limita... | ss.setdefault("install_shortcuts", install_shortcuts)
self.cmdclass.setdefault("install_dbus_services",
install_dbus_services)
self.cmdclass.setdefault("install_man", install_man)
self.cmdclass.setdefault("install_mo", install_mo)
self.cmdclass.setdefault... | earch_provider)
self.cmdclass.setdefault("install_appdata", install_appdata)
self.cmdclass.setdefault(
"install_zsh_completions", install_zsh_completions)
self.cmdclass.setdefault("build", build)
self.cmdclass.setdefault("install", install)
self.cmdclass.setdefault("p... |
AlphaLambdaMuPi/CamDrone | camera3.py | Python | mit | 937 | 0.002134 | #! /u | sr/bin/env python3
import asyncio
import subprocess
import numpy as np
import time
c | omm = None
class Camera:
def __init__(self, notify):
self._process = None
self._now_pos = np.array([0., 0., 0.])
self._running = False
self._notify = notify
@asyncio.coroutine
def connect(self):
self._process = yield from asyncio.create_subprocess_exec(
... |
itarozzi/classerman | src/ui/mainwindow_ui.py | Python | gpl-3.0 | 16,000 | 0.003313 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'src/ui/mainwindow.ui'
#
# Created: Fri Feb 15 16:08:54 2013
# by: PyQt4 UI code generator 4.9.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
exce... | _2"))
self.label_2 = QtGui.QLabel(self.centralwidget)
font = QtGui.QFont()
font.setPointSize(20)
self.label_2.setFont(font)
| self.label_2.setAlignment(QtCore.Qt.AlignCenter)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.verticalLayout_2.addWidget(self.label_2)
self.labelServerId = QtGui.QLabel(self.centralwidget)
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 255))
... |
huangciyin/youtube-dl | youtube_dl/downloader/f4m.py | Python | unlicense | 10,503 | 0.001238 | from __future__ import unicode_literals
import base64
import io
import itertools
import os
import time
import xml.etree.ElementTree as etree
from .common import FileDownloader
from .http import HttpFD
from ..utils import (
struct_pack,
struct_unpack,
compat_urlparse,
format_bytes,
encodeFilename,
... | gress': True,
'test': self.params.get('test', False),
})
doc = etree.fromstring(manifest)
formats = [(int(f.attrib.get('bitrate', -1)), f) for f in doc.findall(_add_ns('media'))]
formats | = sorted(formats, key=lambda f: f[0])
rate, media = formats[-1]
base_url = compat_urlparse.urljoin(man_url, media.attrib['url'])
bootstrap = base64.b64decode(doc.find(_add_ns('bootstrapInfo')).text)
metadata = base64.b64decode(media.find(_add_ns('metadata')).text)
boot_info = re... |
rohitranjan1991/home-assistant | tests/components/tplink/test_diagnostics.py | Python | mit | 1,931 | 0.001554 | """Tests for the diagnostics data provided by the TP-Link integration."""
import json
from aiohttp import ClientSession
from kasa import SmartDevice
import pytest
from homeassistant.core import HomeAssistant
from . import _mocked_bulb, _mocked_plug, initializ | e_config_entry_for_device
from tests.common import load_fixture
from tests.components.diagnostics import get_diagnostics_for_config_entry
@pytest.mark.parametrize(
"mocked_dev,fixture_file,sysinfo_vars",
[
(
_mocked_bulb(),
"tplink-diagnostics-data-bulb-kl130.json",
... | iceId", "oemId", "hwId", "alias"],
),
(
_mocked_plug(),
"tplink-diagnostics-data-plug-hs110.json",
["mac", "deviceId", "oemId", "hwId", "alias", "longitude_i", "latitude_i"],
),
],
)
async def test_diagnostics(
hass: HomeAssistant,
hass_client: Cli... |
RedXBeard/gitwatcher-ui | shortcuts.py | Python | mit | 4,040 | 0.000248 | import os
import re
from subprocess import Popen, PIPE
from kivy.uix.popup import Popup
def run_syscall(cmd):
"""
run_syscall; handle sys calls this function used as shortcut.
::cmd: String, shell command is expected.
"""
p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
out, err = p.commu... | line_end = text[tmp_location + 2:].find("\n")
if line_end > 0:
result_text += "\n[color=%s]%s[/color]" % \
(color,
text[tmp_location + 1:tmp_location + 2 + line_end])
else:
... | t_text += "\n[color=%s]%s[/color]" % \
(color, text[tmp_location + 1:])
text = ""
location = tmp_location + 2 + line_end
text = text[location:]
else:
result_text += text
location = -1
... |
kubevirt/client-python | test/test_v1_virtual_machine_instance_replica_set_status.py | Python | apache-2.0 | 1,109 | 0.002705 | # coding: utf-8
"""
KubeVirt API
This is KubeVirt API an add-on for Kubernetes.
OpenAPI spec version: 1.0.0
Contact: kubevirt-dev@googlegroups.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absol | ute_import
import os
import sys
import unittest
import kubevirt
from kubevirt.rest import ApiException
from kubevirt.models.v1_virtual_machine_instance_replica_set_status import V1VirtualMachineInstanceReplicaSetStatus
class TestV1VirtualMachineInstanceReplicaSetStatus(unittest.TestCase):
""" V1VirtualMachineIn... |
def setUp(self):
pass
def tearDown(self):
pass
def testV1VirtualMachineInstanceReplicaSetStatus(self):
"""
Test V1VirtualMachineInstanceReplicaSetStatus
"""
# FIXME: construct object with mandatory attributes with example values
#model = kubevirt.m... |
kerel-fs/skylines | skylines/lib/geo.py | Python | agpl-3.0 | 737 | 0 | # -*- coding: utf-8 -*-
import math
EARTH_RADIUS = 6367009
METERS_PER_DEGREE = 111319.0
FEET_PER_METER = 3.2808399
def geographic_distance(loc1, loc2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
... | dlon = lon2 - lon1
dlat = lat2 - lat1
a = math.sin(dlat / 2) ** 2 + math.cos(lat1) * \
math.cos(lat2) * math.sin(dlon / 2) ** 2
| c = 2 * math.asin(math.sqrt(a))
return EARTH_RADIUS * c
|
graphite-project/ceres | ceres.py | Python | apache-2.0 | 31,634 | 0.010084 | # Copyright 2011 Chris Davis
#
# 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, so... | :param behavior: See :func:`getNode` for valid behavior values
"""
behavior = behavior.lower()
if | behavior not in ('none', 'all'):
raise ValueError("invalid caching behavior '%s'" % behavior)
self.nodeCachingBehavior = behavior
self.nodeCache = {}
def getNode(self, nodePath):
"""Returns a Ceres node given a metric name. Because nodes are looked up in
every read and write, a caching mechan... |
repotvsupertuga/tvsupertuga.repository | script.module.streamlink.base/resources/lib/streamlink/plugins/telefe.py | Python | gpl-2.0 | 1,939 | 0.004126 | import re
from streamlink.plugin import Plugin
from streamlink.plugin.api import useragents
from streamlink.stream import HLSStream, HTTPStream
from streamlink.utils import parse_json
class Telefe(Plugin):
_url_re = re.compile(r'https?://telefe.com/.+')
@classmethod
def can_handle_url(cls, url):
... | tent available")
self.session.http.headers = {
'Referer': self.url, 'User-Agent': useragents.CHROME, 'X-Requested-With': 'ShockwaveFlash/25.0.0.148'
}
if video_url_found_hls:
hls_streams = HLSStream.parse_variant_playlist(self.session, video_url_found_hls)
f... | e
|
VladimirFilonov/moscowdjango | moscowdjango/settings_production.py | Python | bsd-3-clause | 780 | 0 | # Django settings for moscowdjango project.
from .settings import *
DEBUG = False
EMBEDLY_KEY = os.environ.get('EMBEDLY_KEY')
SECRET_KEY = os.environ.get('SECRET_KEY')
# Amazon credentials
AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS | _KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = 'moscowdjango'
AWS_QUERYSTRING_AUTH = False
AWS_CALLING_FORMAT = 2 # SUBDOMAIN
AWS_S3_SECURE_URLS = True
# Media & static
DEFAULT_FILE_STORAGE = 'moscowdjango.ama | zon.DefaultStorage'
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
DEFAULT_S3_PATH = "media"
MEDIA_ROOT = '/%s/' % DEFAULT_S3_PATH
MEDIA_URL = 'https://%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME
# Django compressor
COMPRESS_ENABLED = False
|
earthquakesan/pyrdf2nt | pyrdf2nt/converter.py | Python | mit | 1,329 | 0.006772 | from __future__ import print_function
import os
import subprocess
class PyRDF2Ntriples(object):
def __init__(self):
pass
def convertTTL2NT(self, filepath):
#Save to the same folder with .nt extension
(outputDir, outputFile) = os.path.split(os.path.abspath(filepath))
outputFil... | serdiCommand = "serdi -i turtle -o ntriples -b -q %s" % | (inpath)
p = self.execute(serdiCommand)
f = open(outpath, "wb+")
for line in p.stdout.readlines():
print(line, file=f, end="")
f.close()
def executeRapper(self, inpath, outpath, serialization):
pass
def execute(self, command):
p = subprocess.Popen(c... |
punalpatel/st2 | contrib/examples/actions/pythonactions/yaml_string_to_object.py | Python | apache-2.0 | 168 | 0 | import yaml
from st2common.runners.base_action import Act | ion
class YamlStringToObject(Action):
def run(self, yaml_st | r):
return yaml.safe_load(yaml_str)
|
coddingtonbear/django-neighborhoods | neighborhoods/importer.py | Python | mit | 3,743 | 0.000534 | import logging
import os.path
import shutil
import tempfile
import urllib2
import zipfile
from django.contrib.gis.gdal import DataSource, OGRGeometry, OGRGeomType
from django.db import transaction
from django.db.utils import IntegrityError
logger = logging.getLogger('neighborhoods.importer')
class NeighborhoodShapef... | elf._get_multipolygon_geometry_from_row(row)
geom = self.transform_geometry(geom)
if not geom:
logger.warning(
"Unable to convert row %s %s into MultiPolygon" % (
row.fid,
repr(row)
... | )
continue
place = self.get_neighborhood(row, geom)
sid = transaction.savepoint()
try:
place.save()
transaction.savepoint_commit(sid)
logger.info(
"(%s) %s, %s, %s Imported Successfully"... |
kawamon/hue | desktop/core/ext-py/nose-1.3.7/functional_tests/support/issue771/test.py | Python | apache-2.0 | 272 | 0.011029 | from nose.plugins.attrib import attr
from unittest import TestCase
@attr("b")
def test_b():
assert 1 == 1
class TestBas | e(TestCase):
def test_a(self):
assert 1 == 1
class TestDerived(TestBas | e):
@attr("a")
def test_a(self):
assert 1 == 1
|
corumcorp/redsentir | redsentir/foro/migrations/0003_comentario_fecha.py | Python | gpl-3.0 | 453 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-1 | 0-02 22:23
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('foro', '0002_comentario_usuario'),
]
operations = [
migrations.AddField(
model_name='comentario',
name='fecha',
... | ),
]
|
ScholarTools/pypub | tests/nrg_test.py | Python | mit | 3,751 | 0.000267 | # Standard imports
import os
import sys
import pickle
# Third party imports
import nose
# Local imports
from pypub.scrapers import nature_nrg as nrg
from pypub.paper_info import PaperInfo
class TestNature(object):
def __init__(self):
self.curpath = str(os.path.dirname(os.path.abspath(__file__)))
... | = saved_authors[z[0]]
if live.__dict__ != saved.__dict__:
print('\nDifference found.')
print('Key: authors')
print('Saved value: ' + str(saved))
print('Live value: ' + str(live))
assert False
assert True
def test_n... | ure_saved_refs(self):
for y in range(len(self.pi.references)):
saved_ref_dict = self.saved_pi.references[y].__dict__
live_ref_dict = self.pi.references[y].__dict__
for x in live_ref_dict.keys():
if saved_ref_dict[x] != saved_ref_dict[x]:
pr... |
jameslkey/CERM-Morse-Code-Exhibit | tests/test_config.py | Python | lgpl-3.0 | 2,346 | 0.007673 | # coding=utf-8
"""
CERMMorse : test_config
5/7/2017 : 11:32 PM
Author : James L. Key
"""
from unittest import TestCase
from readconfig import Config
__author__ = 'James L. Key'
__project__ = 'CERMMorse'
class TestConfig(TestCase):
def setUp(self):
self.conf = Config(configpath='../data/config.json')
... | if (r not in range(0, 2)) | (g not in range(0, 2)) | (b not in range(0, 2)):
return False
else:
return True
def test_getconfig(self):
self.assertIsInstance(self. | conf.LCDPin1, int, 'Config LCDPin1 is not an Integer!!')
self.assertIn(self.conf.LCDPin1, range(0, 4), 'Config LCDPin1 is not in I2C Range!!')
self.assertIsInstance(self.conf.LCDPin2, int, 'Config LCDPin2 is not an Integer!!')
self.assertIn(self.conf.LCDPin2, range(0, 4), 'Config LCDPin1 is not ... |
alandmoore/pystump | includes/lookups.py | Python | gpl-3.0 | 856 | 0 | bg_image_modes = ('stretch', 'tile', 'center', 'right', 'left')
transitions_jquery_ui = (
'blind', 'bounce', 'clip', 'drop', ' | explode', 'fade', 'fold',
'highlight', 'puff', 'pulsate', 'scale', 'shake', 'size', 'slide'
)
transitions_animatecss = (
'bounceIn',
'bounceInDown',
'bounceInLeft',
'bounceInRight',
'bounceInUp',
'fadeIn',
'fadeInDown',
'fadeInDownBig',
'fadeInLeft',
'fadeInLeftBig',
'fa... | 'flipInX',
'flipInY',
'lightSpeedIn',
'rotateIn',
'rotateInDownLeft',
'rotateInDownRight',
'rotateInUpLeft',
'rotateInUpRight',
'rollIn',
'zoomIn',
'zoomInDown',
'zoomInLeft',
'zoomInRight',
'zoomInUp',
'slideInDown',
'slideInLeft',
'slideInRight',
's... |
saelo/willie-modules | asm.py | Python | mit | 4,715 | 0.009334 | # coding=utf8
"""
asm.py - (dis)assembly features.
(c) 2014 Samuel Groß
"""
from willie import web
from willie.module import commands, nickname_commands, example
from random import choice
from binascii import hexlify, unhexlify
import string
import re
import os
from subprocess import Popen, PIPE
@commands('disas', ... | return bot.reply('Nothing to disassemble')
try:
arg = trigger.group(2)
# remove all 0x
while "0x | " in arg:
arg = arg.replace("0x","")
# remove everything except hex
arg = re.sub(r"[^a-fA-F0-9]", r"", arg)
code = unhexlify(arg)
except Exception:
return bot.say('Invalid hex sequence')
bits = 64 if '64' in trigger.group(1) else 32
filename = '/tmp/' + ''.join(... |
spulec/moto | moto/kms/responses.py | Python | apache-2.0 | 19,277 | 0.002905 | import base64
import json
import os
import re
from moto.core import ACCOUNT_ID
from moto.core.responses import BaseResponse
from moto.kms.utils import RESERVED_ALIASES
from .models import kms_backends
from .exceptions import (
NotFoundException,
ValidationException,
AlreadyExistsException,
NotAuthorize... | """
is_alias_arn = key_id.startswith("arn:") and ":alias/" in key_id
is_alias_name = key_id.startswith("alias/")
if is_al | ias_arn or is_alias_name:
self._validate_alias(key_id)
return
self._validate_cmk_id(key_id)
def create_key(self):
"""https://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html"""
policy = self.parameters.get("Policy")
key_usage = self.parameters.... |
schriftgestalt/robofab | Tools/buildRoboFabDistroFromSVN.py | Python | bsd-3-clause | 5,807 | 0.008783 | """
Build the zipped robofab + dependency distros for RoboFab.
Check out fresh copies of the code from SVN.
Compile into zips.
Write optional html page.
"""
import os, glob, time
def getRevision(url):
""" Ask svn for the revision."""
cmd = "svn info \"%s\""%url
d = os.popen(cmd... | ame)
newZips.sort()
oldZips.sort()
oldZips.reverse()
oldZips = oldZips[:200]
newLinks = "\n\t".join(["<li><a href=\"%s\">%s</a></li>"%(n,n) for n in newZips])
oldLinks = "\n\t".join(["<li><a href=\"%s\">%s</a></li>"%(n,n) for n in oldZips])
html = downloadPageTemplate%(changeSet, changeSet, ... | robofabProducts = {
'RoboFab_%s_plusAllDependencies':[
("http://svn.robofab.com/trunk", "RoboFab"),
("http://svn.typesupply.com/packages/vanilla/trunk", "Vanilla"),
("http://svn.typesupply.com/packages/dialogKit/trunk", "DialogKit"),
("https://fonttools.svn.sour... |
acmaheri/sms-tools | lectures/7-Sinusoidal-plus-residual-model/plots-code/hpsModel-sax-phrase.py | Python | agpl-3.0 | 1,834 | 0.008179 | import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import hamming, hanning, triang, blackmanharris, resample
import math
import sys, os, time
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../../software/models/'))
import utilFunctions as UF
import hpsModel as HPS
(fs,... | mFrames)/float(fs)
plt.plot(frmTime, harms, color='k', ms=3, alpha=1)
plt.autoscale(tight=True)
plt.title('harmonics + stochastic')
plt.subplot(313)
plt.plot(np.arange(y.size)/float(fs), y, 'b')
plt.autoscale(tight=True)
plt.title('y')
plt.tight_layout()
plt.savefig('hpsModel-sax-phrase.png')
UF.wavwrite(y, fs, 'sax... | -synthesis.wav')
UF.wavwrite(yh, fs, 'sax-phrase-harmonic.wav')
UF.wavwrite(yst, fs, 'sax-phrase-stochastic.wav')
plt.show()
|
kenorb/BitTorrent | auto-update/sign_file.py | Python | gpl-3.0 | 1,204 | 0.001661 | #!/usr/bin/env python
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that ... |
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from common import sig_ext, pri_key_path
import sys
import time
import pickle
from sha import sha
from Crypto.Util import randp | ool
r = randpool.KeyboardRandomPool()
r.randomize()
private_key_file = open(pri_key_path, 'rb')
key = pickle.load(private_key_file)
for f in sys.argv[1:]:
c = open(f, 'rb').read()
h = sha(c).digest()
r.add_event()
signature = key.sign(h, r.get_bytes(2**4))
if key.verify(h, signature):
si... |
atodorov/anaconda | pyanaconda/modules/storage/storage.py | Python | gpl-2.0 | 13,962 | 0.000573 | #
# Kickstart module for the storage.
#
# Copyright (C) 2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is di... | if self.applied_partitioning:
self.applied_partitioning.setup_kickstart(data)
@property
def storage(self):
"""The storage model.
:return: an | instance of Blivet
"""
if self._storage_playground:
return self._storage_playground
if not self._current_storage:
self._set_storage(create_storage())
return self._current_storage
def _set_storage(self, storage):
"""Set the current storage model.
... |
dezelin/scons | scons-local/SCons/Tool/packaging/msi.py | Python | mit | 20,208 | 0.013856 | """SCons.Tool.packaging.msi
The msi packager.
"""
#
# Copyright (c) 2001 - 2014 The SCons Foundation
#
# 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
# with... | name(file):
return file
# strip forbidden characters.
forbidden = '."/[]:;=, '
fname = [c for c in fname if c not in forbidden]
# check if we already generated a filename with the same number:
# thisis1.txt, th | isis2.txt etc.
duplicate, num = not None, 1
while duplicate:
shortname = "%s%s" % (fname[:8-len(str(num))].upper(),\
str(num))
if len(ext) >= 2:
shortname = "%s%s" % (shortname, ext[:4].upper())
duplicate, num = shortname in filename_set, num+1
... |
sysadminmatmoz/pmis | change_management/__init__.py | Python | agpl-3.0 | 173 | 0 | # -*- coding: utf-8 -*-
# Copyrigh | t 2017 Matmoz d.o.o. (<http://www.matmoz.si>).
# License AGPL-3.0 or later (https://www. | gnu.org/licenses/agpl.html).
from . import models
|
avehtari/GPy | GPy/plotting/plotly_dep/plot_definitions.py | Python | bsd-3-clause | 15,302 | 0.004901 | #===============================================================================
# Copyright (c) 2015, Max Zwiessele
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source... | lottingLibrary
from .. import Tango
from . import defaults
from plotly import tools
from plotly i | mport plotly as py
from plotly.graph_objs import Scatter, Scatter3d, Line,\
Marker, ErrorX, ErrorY, Bar, Heatmap, Trace,\
Annotations, Annotation, Contour, Font, Surface
from plotly.exceptions import PlotlyDictKeyError
SYMBOL_MAP = {
'o': 'dot',
'v': 'triangle-down',
'^': 'triangle-up',
'<': 't... |
namco1992/voicetools | voicetools/api.py | Python | apache-2.0 | 4,729 | 0.001269 | # coding: utf-8
import wolframalpha
from .exceptions import APIError
from .clients import turingclient, baiduclient
from .utils import get_mac_address, get_audio_info
class Wolfram(object):
"""A client for request Wolfram.
Attributes:
key: The key string got from https://www.wolframalpha.com.
"""... | =1, lan='zh'):
"""Constructs and sends an Automatic Speech Recognition request.
Args:
file_: the open file with methods write(), close(), tell(), seek()
set through the __init__() metho | d.
format_:(optional) the audio format, default is 'wav'
cuid:(optional) Unique identification of user, default is MAC address.
ptc:(optional) nbest results, the number of results.
lan:(optional) language, default is 'zh'.
Returns:
A list of recognitio... |
chenkianwee/pyliburo | py4design/pyoptimise/nsga2.py | Python | gpl-3.0 | 35,056 | 0.008814 | # ==================================================================================================
#
# Copyright (c) 2016, Chen Kian Wee (chenkianwee@gmail.com)
#
# This file is part of py4design
#
# py4design is free software: you can redistribute it and/or modify
# it under the terms of the GNU General ... | ange":
self.values[c] = random.randrange(value_range[0], value_range[1], value_range[2])
if gene_type == "int_choice":
self.values[c] = random.choice(value_ | range)
def read_str( |
sanguinariojoe/sonsilentsea | scripts/showMouse.py | Python | gpl-3.0 | 38 | 0 | import | Rasterizer | as r
r.showMouse(1)
|
lewisodriscoll/sasview | src/sas/sascalc/data_util/ordereddict.py | Python | bsd-3-clause | 3,441 | 0.002906 | #!/usr/bin/env python
"""Backport from python2.7 to python <= 2.6."""
from itertools import repeat as _repeat, chain as _chain, starmap as _starmap
try:
from itertools import izip_longest as _zip_longest
except ImportError:
from itertools import izip
def _zip_longest(*args, **kwds):
# izip_longe... | urn list(self)
def values(self):
return [self[key] for key in self]
def items(self):
return [ | (key, self[key]) for key in self]
def __repr__(self):
if not self:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, list(self.items()))
def copy(self):
return self.__class__(self)
@classmethod
def fromkeys(cls, iterable, value=... |
gateway4labs/labmanager | alembic/versions/105c1c44ff70_login_is_not_nullabl.py | Python | bsd-2-clause | 832 | 0.014423 | """login is not nullable
Revision ID: 105c1c44ff70
Revises: 2003c675a267
Create Date: 201 | 3-12-09 10:52:50.646000
"""
# revisi | on identifiers, used by Alembic.
revision = '105c1c44ff70'
down_revision = '2003c675a267'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.alter_column('labmanager_users', 'login',
... |
tvaddonsco/tva-release-repo | matrix/plugin.video.realizerx/resources/lib/modules/pyperclip/clipboards.py | Python | gpl-3.0 | 3,970 | 0 | import sys
import subprocess
from .exceptions import PyperclipException
EXCEPT_MSG = """
Pyperclip could not find a copy/paste mechanism for your system.
For more information, please visit https://pyperclip.readthedocs.org """
PY2 = sys.version_info[0] == 2
text_type = str if PY2 else str
def init... | p', '-selection', 'c'],
stdin=subprocess.PIPE, close_fds=True)
p.communicate(input=text)
def paste_xclip():
p = subprocess.Popen(['x | clip', '-selection', 'c', '-o'],
stdout=subprocess.PIPE, close_fds=True)
stdout, stderr = p.communicate()
return stdout
return copy_xclip, paste_xclip
def init_xsel_clipboard():
def copy_xsel(text):
p = subprocess.Popen(['xsel', '-b', '-i'],
... |
projectatomic/atomic-reactor | tests/plugins/test_bump_release.py | Python | bsd-3-clause | 24,769 | 0.002059 | """
Copyright (c) 2015, 2019 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from __future__ import unicode_literals, absolute_import
import koji
import os
from copy import deepcopy
from textwrap import dedent
... | tmpdir, add_timestamp=None):
self.dockerfile_path = str(tmpdir.join('Dockerfile'))
self.path = str(tmpdir)
self.commit_id = None
if add_timestamp is not None:
self.config = flexmock(autorebuild=dict(add_timestamp_to_release=add_timestamp))
else:
self.conf... | tmpdir,
labels=None,
include_target=True,
certs=False,
append=False,
reserve_build=False,
is_auto=False,
add_timestamp=None,
fetch_source=False,
scratch=None):
... |
unintended/Cohen | tests/test_dbus.py | Python | mit | 3,086 | 0.000648 | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008, Frank Scholz <coherence@beebits.net>
"""
Test cases for L{dbus_service}
"""
import os
from twisted.trial import unittest
from twisted.internet import reactor
from twisted.internet.defer impor... | back(version)
self.coherence_service.version(dbus_interf | ace=BUS_NAME,
reply_handler=handle_version_reply,
error_handler=d.errback)
return d
def test_dbus_plugin_add_and_remove(self):
""" tests creation and removal of a backend via dbus
"""
d = Deferred()
... |
sahat/wagtail | wagtail/wagtaildocs/wagtail_hooks.py | Python | bsd-3-clause | 282 | 0.003546 | from django.conf.urls import inclu | de, url
from wagtail.wagtailadmin import hooks
from wagtail.wagtaildocs import admin_urls
de | f register_admin_urls():
return [
url(r'^documents/', include(admin_urls)),
]
hooks.register('register_admin_urls', register_admin_urls)
|
myarjunar/QGIS | python/plugins/processing/algs/qgis/JoinAttributes.py | Python | gpl-2.0 | 4,402 | 0.000454 | # -*- coding: utf-8 -*-
"""
***************************************************************************
JoinAttributes.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
************************... | e2] = attrs
feedback.setProgress(int(current * total))
# Create output vector layer with additional attribute
outFeat = QgsFeature()
features = vector.features(layer)
total = 100.0 / len(features)
for current, feat in enumerate(features): |
outFeat.setGeometry(feat.geometry())
attrs = feat.attributes()
joinValue1 = str(attrs[joinField1Index])
attrs.extend(cache.get(joinValue1, []))
outFeat.setAttributes(attrs)
writer.addFeature(outFeat)
feedback.setProgress(int(current * ... |
rossplt/ross-django-utils | ross/settings.py | Python | mit | 3,090 | 0.001294 | """
Django settings for ross 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
#... | .messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware' | ,
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'ross.urls'
TEMP... |
dhhxu/LBNL-ion7350-interface | setup.py | Python | gpl-2.0 | 3,243 | 0.002158 | """
Setup script
The ION 7350 interface requires several directories and files to work. If the
interface is to be run on a different machine, run this script to set up the
requisite directories and files.
"""
import os
from getpass import getpass
from LbnlIon7350Interface.utils import defaults
from LbnlIon7350Interf... | n IOError and no file is created.
root is the root directory of the interface program. It is needed so that
the credentials file is saved in the correct location.
The file contains two lines. The first is username. The second is password.
Params:
root string
"""
path = defaults.creds(... | t to overwrite (Y/N)? ')
if answer.lower() == 'y':
os.remove(path)
break
elif answer.lower() == 'n':
return
else:
print('Unknown input. Please try again.')
try:
user = get_username()
pwd = get_passwo... |
nicholasserra/sentry | src/sentry/web/frontend/auth_logout.py | Python | bsd-3-clause | 457 | 0 | from __future__ import absolute_import
from django.contrib.auth import logout
from django.contrib.auth.models import AnonymousUser
from sentry.web.frontend.base import BaseView
from sentry.utils.auth import get_login_redirect
class AuthLogoutView(BaseView):
auth_requi | red = False
def handle(self, request):
rv = get_login_redi | rect(request)
logout(request)
request.user = AnonymousUser()
return self.redirect(rv)
|
Mandrilux/GOC_2017 | api/polydevs/parking/migrations/0008_auto_20170311_2109.py | Python | agpl-3.0 | 1,364 | 0.002199 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2017-03-11 21:09
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('parking', '0007_auto_20170311_2028'),
]
operations = [
migrations.AlterFiel... | '), ('Electric', 'Electric')], default='Default', max_length=8),
),
migrations.AlterField(
model_name='parking',
nam | e='is_free',
field=models.BooleanField(default=True),
),
migrations.AlterField(
model_name='parking',
name='is_paying',
field=models.BooleanField(default=False),
),
migrations.AlterField(
model_name='parking',
name='... |
esthermm/odoo-addons | sale_service_recurrence_configurator/models/sale.py | Python | agpl-3.0 | 7,124 | 0 | # -*- coding: utf-8 -*-
# (c) 2016 Alfredo de la Fuente - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from openerp import models, fields, api
class SaleOrder(models.Model):
_inherit = 'sale.order'
@api.multi
def onchange_template_id(self, template_id, partner=False,
... | ring_service')
january = fields.Boolean('January')
february = fields.Boolean('February')
march | = fields.Boolean('March')
april = fields.Boolean('April')
may = fields.Boolean('May')
june = fields.Boolean('June')
july = fields.Boolean('July')
august = fields.Boolean('August')
september = fields.Boolean('September')
october = fields.Boolean('October')
november = fields.Boolean('Novem... |
python-bonobo/bonobo | bonobo/nodes/basics.py | Python | apache-2.0 | 10,187 | 0.00265 | import functools
import html
import itertools
import pprint
from mondrian import term
from bonobo import settings
from bonobo.config import Configurable, Method, Option, use_context, use_no_input, use_raw_input
from bonobo.config.functools import transformation_factory
from bonobo.config.processors import ContextProc... | self.print_quiet(context, *args, **kwargs)
return NOT_MODIFIED
def print_quiet(self, context, *args, **kwargs):
for index, (key, value) in enumerate(itertools.chain(enumerate(args), kwargs.items())):
if self.filter(index, key, value):
print(self.format_quiet(index, k | ey, value, fields=context.get_input_fields()))
def format_quiet(self, index, key, value, *, fields=None):
# XXX should we implement argnames here ?
return " ".join(((" " if index else "-"), str(key), ":", str(value).strip()))
def print_console(self, context, *args, **kwargs):
print("\u... |
LarsDu/DeepPixelMonster | dpixelmonster/kim_utils.py | Python | apache-2.0 | 7,612 | 0.015108 | """
Some codes from https://github.com/Newmu/dcgan_code
"""
from __future__ import division
import math
import json
import random
import pprint
import scipy.misc
import numpy as np
from time import gmtime, strftime
pp = pprint.PrettyPrinter()
get_stddev = lambda x, k_h, k_w: 1/math.sqrt(k_w*k_h*x.get_shape()[-1])
de... | (100):
print(" [*] %d" % idx)
z_sample = np.zeros([config.batch_size, dcgan.z_dim])
for kdx, z in enumerate(z_sample):
z[idx] = values[kdx]
samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample})
make_gif(samples, './samples/test_gif_%s.gif' % (idx))
elif option == 4:
... | 1, 1./config.batch_size)
for idx in xrange(100):
print(" [*] %d" % idx)
z_sample = np.zeros([config.batch_size, dcgan.z_dim])
for kdx, z in enumerate(z_sample): z[idx] = values[kdx]
image_set.append(sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample}))
make_gif(image_set[-1], './sa... |
yanheven/console | horizon/middleware.py | Python | apache-2.0 | 8,472 | 0.000118 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# no... | a
from django.contrib import messages as django_messages
from django import http
from django.http import HttpResponseRedirect # noqa
from django import shortcuts
from django.utils.encoding import iri_to_uri # noqa
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _ |
from horizon import exceptions
from horizon.utils import functions as utils
LOG = logging.getLogger(__name__)
class HorizonMiddleware(object):
"""The main Horizon middleware class. Required for use of Horizon."""
logout_reason = None
def process_request(self, request):
"""Adds data necessary ... |
GaelVaroquaux/scikits.image | scikits/image/morphology/__init__.py | Python | bsd-3-clause | 63 | 0 | f | rom grey import *
from selem import *
from ccomp import label
| |
maxdl/Synapse.py | synapse/main.py | Python | mit | 24,280 | 0.002059 | import itertools
import os.path
import sys
import time
from . import core
from . import file_io
from . import geometry
from . import stringconv
from . import version
#
# Functions
#
def save_output(profileli, opt):
""" Save a summary of results of evaluated profiles
"""
def m(x, pixelwidth):
retu... | )
f.writerow(["Metric unit:", eval_proli[0].metric_unit])
f.writerow(["Spatial resolution:", opt.spatial_resolution, eval_proli[0].metric_unit])
f.writerow(["Shell width:", opt.shell_width, eval_proli[0].metric_unit])
f.writerow(["Interpoint distances calculated:",
... | terpoint_dists)])
if opt.determine_interpoint_dists:
f.writerow(["Interpoint distance mode:", opt.interpoint_dist_mode])
f.writerow(["Shortest interpoint distances:",
stringconv.yes_or_no(opt.interpoint_shortest_dist)])
f.writerow([... |
Inboxen/Inboxen | inboxen/views/manifest.py | Python | agpl-3.0 | 1,459 | 0 | ##
# Copyright (C) 2018 Jessica Tallon & Matthew Molyneaux
#
# This program 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 option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied wa... | LAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
##
from django.conf import settings
from django.http import JsonResponse
from django.... |
NaPs/Docbucket | setup.py | Python | mit | 796 | 0 | from setuptools import setup, find_packages
import os
version = '1.0~dev'
base = os.path.dirname(__file__)
readme = open(os.path.join(base, 'README.rst')).read()
changelog = open(os.path.join(base, 'CHANGELOG.rst')).read()
setup(name='docbucket',
version=version,
desc | ription='',
long_description=readme + '\n' + changelog,
classifiers=[],
keywords='dms django',
author='Antoine Millet',
author_email='antoine@inaps.org',
| url='https://github.com/NaPs/Docbucket',
license='MIT',
data_files=(
('/etc/', ('etc/docbucket.conf',)),
),
scripts=['docbucketadm'],
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=True,
install_requires... |
vaidap/zulip | zerver/tests/test_urls.py | Python | apache-2.0 | 6,615 | 0.001209 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
import importlib
import os
import six
import ujson
import django.core.urlresolvers
from django.test import TestCase
from typing import List, Optional
from zerver.lib.test_classes import ZulipTestCase
from zerver.mode... | n't do so because this Django test mechanism doesn't go
| # through Tornado.
denmark_stream_id = Stream.objects.get(name='Denmark').id
get_urls = {200: ["/accounts/home/", "/accounts/login/"
"/en/accounts/home/", "/ru/accounts/home/",
"/en/accounts/login/", "/ru/accounts/login/",
... |
umitproject/openmonitor-desktop-agent | umit/icm/agent/gui/dashboard/timeline/TimeLineConnector.py | Python | gpl-2.0 | 3,540 | 0.013842 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 S2S Network Consultoria e Tecnologia da Informacao LTDA
#
# Authors: Guilherme Polo <ggpolo@gmail.com>
# Tianwei Liu <liutainweidlut@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of ... | 'graph_show': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (bool, )),
#Lin | e Filter updates. Timeline handles this signals and updates Timeline Graph accordingly
'filter_update':(gobject.SIGNAL_RUN_FIRST,gobject.TYPE_NONE,(object, )),
#Timeline Graph emits this signal when a new selection is done, TimelineBase grabs it,
#handles it and stores selected timera... |
optiv-labs/talus_client | talus_client/cmds/images.py | Python | mit | 11,313 | 0.034827 | #!/usr/bin/env python
# encoding: utf-8
import argparse
import cmd
import os
import shlex
import sys
from tabulate import tabulate
import time
from talus_client.cmds import TalusCmdBase
import talus_client.api
import talus_client.errors as errors
from talus_client.models import Image,Field
class ImageCmd(TalusCmdBas... | mport
-o,--os ID or name of the operating system model
| -n,--name The name of the resulting image (default: basename(FILE))
-d,--desc A description of the image (default: "")
-t,--tags Tags associated with the image (default: [])
-f,--file-id The id of an already-uploaded file (NOT A NORMAL USE CASE)
-u,--username The username to be use... |
buzz/flicks | flicksapp/management/commands/scan_files.py | Python | gpl-2.0 | 7,514 | 0.00173 | from django.core.management.base import BaseCommand
import os
import re
import subprocess
from pymediainfo import MediaInfo
from flicksapp.models import Movie, File, Track
from flicksapp.choices import FILE_TYPES, PICTURE_TYPE, VIDEO_TYPE, NFO_TYPE, \
SUBTITLES_TYPE, OTHER_TYPE, AUDIO_TYPE
IGNORES = (
'^\..+... | found = True
else:
for pat in patterns:
pattern = '.+\.%s$' % pat
| if re.search(pattern, f, flags=re.IGNORECASE):
file_obj.file_type = file_type
found = True
break
if found:
break
... |
justephens/ArduMusic | ArduMusic.py | Python | mit | 3,240 | 0.01142 | import MuseScoreHelper as MuseScore
import SerialHelper
while True:
# Print a menu of available operations
print ("AVAILABLE OPERATIONS:")
print (" 1. Connect Device\n")
print (" 2. Load Music File\n")
print (" 3. Exit Program\n")
# Loop until valid input is provided
while True:... | if type(device) != None:
Arduino = SerialHelper.device_begin(device)
else:
print("No device found")
print("\n...\n")
# LOAD MUSIC FILE
elif operation_code == 2:
# Asks the user for a file to load music from, and
# loads it into a list of tup... | sic_Raw = MuseScore.read_file()
# Loop through the music tracks that were returned
# (one track will be played on one buzzer)
for i in range(0, len(Music_Raw)):
print("BUZZER " + str(i) + ":")
for i in Music_Raw[i]:
print (" " + st... |
kevinlee12/oppia | core/controllers/android_e2e_config.py | Python | apache-2.0 | 13,766 | 0.000218 | # Copyright 2021 The Oppia Authors. 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 ... | xp_domain
from core.domain import exp_services
from core.domain import fs_domain
from core.domain import fs_services
from | core.domain import opportunity_services
from core.domain import question_domain
from core.domain import question_services
from core.domain import rights_manager
from core.domain import skill_domain
from core.domain import skill_services
from core.domain import state_domain
from core.domain import story_domain
from cor... |
MicroPyramid/Django-CRM | leads/views.py | Python | mit | 30,110 | 0.000731 | from django.db.models import Q
from django.shortcuts import get_object_or_404
from accounts.models import Account, Tags
from contacts.models import Contact
from leads import swagger_params
from common.models import Attachments, Comment, APISettings, Profile
from common.utils import COUNTRIES, LEAD_SOURCE, LEAD_STATUS, ... | cation,)
permission_classes = (IsAuthenticated,)
def get_context_data(self, **kwargs):
params | = (
self.request.query_params
if len(self.request.data) == 0
else self.request.data
)
queryset = (
self.model.objects.filter(org=self.request.org)
.exclude(status="converted")
.select_related("created_by")
.prefetch_rel... |
rhyolight/nupic.son | app/soc/mapreduce/publish_gci_tasks.py | Python | apache-2.0 | 1,249 | 0.005604 | # Copyright 2011 the Melange authors.
#
# Licensed under the Apache License, Ver | sion 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
# distributed under the License is distributed on an "AS IS" BAS... | guage governing permissions and
# limitations under the License.
"""Surveys model updating MapReduce."""
from mapreduce import context
from mapreduce import operation
from soc.modules.gci.models import task as task_model
from soc.modules.gci.models.program import GCIProgram
def process(task):
ctx = context.get()... |
oemof/reegis-hp | reegis_hp/berlin_hp/create_objects.py | Python | gpl-3.0 | 4,813 | 0 | # -*- coding: utf-8 -*-
# Demandlib
import logging
import oemof.solph as solph
import reegis_hp.berlin_hp.electricity as electricity
import pandas as pd
import demandlib.bdew as bdew
import demandlib.particular_profiles as pprofiles
import reegis_hp.berlin_hp.prepare_data as prepare_data
def heating_systems(esyst... | m, dfull, add_elec, p):
power_plants = prepare_data.chp_berlin(p)
time_index = esystem.time_idx
temperature_path = '/home/uwe/rli-lokal/git_home/demandlib/examples'
temperature_file = temperature_path + '/example_data.csv'
temperature = pd.read_csv(temperature_file)['temperature']
sli = pd.Seri... | x=list(range(8760, 8784)))
temperature = temperature.append(sli)
temperature = temperature.iloc[0:len(time_index)]
heatbus = dict()
hd = dict()
auxiliary_energy = 0
print(dfull)
for h in dfull.keys():
hd.setdefault(h, 0)
lsink = 'demand_{0}'.format(h)
lbus = 'bus_{0}... |
taigaio/taiga-back | taiga/events/management/commands/emit_notification_message.py | Python | agpl-3.0 | 1,345 | 0.001487 | # -*- coding: utf-8 -*-
# Copyright (C) 2014-present Taiga Agile LLC
#
# This program 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 option) any later ver... | f, parser):
parser.add_argument("titl | e", help="The title of the message.")
parser.add_argument("description", help="The description of the message.")
def handle(self, **options):
data = {
"title": options["title"],
"desc": options["description"],
}
routing_key = "notifications"
emit_ev... |
janrygl/gensim | gensim/test/test_count_minimal_sketch_counter.py | Python | gpl-3.0 | 3,092 | 0.004204 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
Automated tests for checking transformation algorithms (the models package).
"""
import logging
import unittest
import os
import sys
import random
import itertools
from gensim.models.phrase... | al_token = 'non_present_token'
phrases = Phrases(None, min_count=1)
current = iter([])
for i in range(100):
current = itertools.chain(current, iter([[special_token]]), TestPhrasesModel.get_sentence(i))
phrases.add_vocab(current)
freq = phrases.vocab[special_token]
... | for i in range(100):
current = itertools.chain(current, iter([[special_token]]), TestPhrasesModel.get_sentence(i))
phrases.add_vocab(current)
freq = phrases.vocab[special_token]
self.assertTrue(freq >= 200)
#endclass TestPhrasesModel
if __name__ == '__main__':
loggin... |
xuhdev/nikola | tests/test_utils.py | Python | mit | 15,927 | 0.000753 | # -*- coding: utf-8 -*-
import unittest
import mock
import os
import lxml.html
from nikola import metadata_extractors
from nikola.post import get_meta
from nikola.utils import (
demote_headers, TranslatableSetting, get_crumbs, TemplateHookRegistry,
get_asset_path, get_theme_chain, get_translation_candidate, wri... |
def __init__(self):
metadata_extractors.load_defaults(s | elf, self.metadata_extractors_by)
class GetMetaTest(unittest.TestCase):
def test_getting_metadata_from_content(self):
file_metadata = ".. title: Nikola needs more tests!\n"\
".. slug: write-tests-now\n"\
".. date: 2012/09/15 19:52:05\n"\
... |
SteffenDE/monitornjus-classic | admin/index.py | Python | mit | 15,077 | 0.022087 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# Copyright (c) 2015 Steffen Deusch
# Licensed under the MIT license
# Beilage zu MonitorNjus, 14.09.2015 (Version 0.9.3)
import os
workingdir = os.path.dirname(os.path.realpath(__file__))
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import cgi
import imp
modul... | REFRESH-Links-"""+unicode(x)+"""\">Refresh Links</label>
</div>
</div>
<div>
<input type="checkbox" n | ame="AKTIV-Links-"""+unicode(x)+"""\" id="AKTIV-Links-"""+unicode(x)+"""\" """+common.aktiv("AKTIV", "Links", x)+"""/>
<label for="AKTIV-Links-"""+unicode(x)+"""\">Links aktiviert</label>
<input type="hidden" value="0" name="HIDDEN.AKTIV-Links-"""+unicode(x)+"""\">
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.