commit stringlengths 40 40 | subject stringlengths 1 1.49k | old_file stringlengths 4 311 | new_file stringlengths 4 311 | new_contents stringlengths 1 29.8k | old_contents stringlengths 0 9.9k | lang stringclasses 3
values | proba float64 0 1 |
|---|---|---|---|---|---|---|---|
68206c67739abf4f9f4d1ab8aa647a28649b5f5f | add figure one comparison between IME and random | analysis/figure_1_ime_vs_random.py | analysis/figure_1_ime_vs_random.py | #!/usr/bin/env python3
import os
import click
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
# from matplotlib import cm
import pandas as pd
font = {'family':'sans-serif',
'sans-serif':['Helvetica'],
'weight' : 'normal',
'size' : 8}
rc('font', **font)
@click... | Python | 0 | |
e3aa781fe60e3ce293e34767c78e947ffc169cbc | Allow module contributions to return dict | src/ggrc/extensions.py | src/ggrc/extensions.py | # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: david@reciprocitylabs.com
# Maintained By: david@reciprocitylabs.com
import sys
from ggrc import settings
import ggrc
def get_extension_name(exte... | # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: david@reciprocitylabs.com
# Maintained By: david@reciprocitylabs.com
import sys
from ggrc import settings
import ggrc
def get_extension_name(exte... | Python | 0.000001 |
13f495ddabd1997b7dfdc9e2933b82fd25ecd664 | Create LevelOrderTraversal.py from LeetCode | LevelOrderTraversal.py | LevelOrderTraversal.py |
#https://leetcode.com/problems/binary-tree-level-order-traversal/#/description
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Node(object):
def __init__(self,node,level):
self... | Python | 0 | |
66c00d10ddc1f137deaf9208572a287bbad33de7 | Add migration script | migrations/versions/d756b34061ff_.py | migrations/versions/d756b34061ff_.py | """Store privacyIDEA node in eventcounter table
Revision ID: d756b34061ff
Revises: 3d7f8b29cbb1
Create Date: 2019-09-02 13:59:24.244529
"""
# revision identifiers, used by Alembic.
from sqlalchemy import orm
from sqlalchemy.sql.ddl import CreateSequence
from privacyidea.lib.config import get_privacyidea_node
revisi... | Python | 0.000001 | |
891dc05f36ae9084d8511bf3e26e0631eadecef7 | add medications urls | medications/urls.py | medications/urls.py |
from django.conf.urls import url
from medications.views import MedicationsView
urlpatterns = [
url(r'^$', MedicationsView.as_view()),
url(r'^([0-9]+)/$', MedicationsView.as_view()),
]
| Python | 0.000009 | |
aa4f1df448c6d01875ed667e37afe68c114892ed | Add initial verification endpoint. Add all balance endpoint | api/mastercoin_verify.py | api/mastercoin_verify.py | import os
import glob
from flask import Flask, request, jsonify, abort, json
data_dir_root = os.environ.get('DATADIR')
app = Flask(__name__)
app.debug = True
@app.route('/addresses')
def addresses():
currency_id = request.args.get('currency_id')
print currency_id
response = []
addr_glob = glob.glob(data_dir... | Python | 0.000001 | |
23799c4a33b9d2da82ec0770f15e840459a940c6 | Add api comtrade | app/apis/comtrade_api.py | app/apis/comtrade_api.py | from flask import Blueprint, jsonify, request
from sqlalchemy import func, distinct
from inflection import singularize
from app.models.comtrade import Comtrade as Model
from app import cache
from app.helpers.cache_helper import api_cache_key
blueprint = Blueprint('comtrade_api', __name__, url_prefix='/comtrade')
@blu... | Python | 0 | |
670e5d017adb24c5adffb38fa59059fec5175c3c | Create hello.py | hello.py | hello.py | print('hello, world!')
| Python | 0.999503 | |
1692161ad43fdc6a0e2ce9eba0bacefc04c46b5c | Add form generator module. | src/epiweb/apps/survey/utils.py | src/epiweb/apps/survey/utils.py | from django import forms
from epiweb.apps.survey.data import Survey, Section, Question
_ = lambda x: x
def create_field(question):
if question.type == 'yes-no':
field = forms.ChoiceField(widget=forms.RadioSelect,
choices=[('yes', _('Yes')), ('no', _('No'))])
elif que... | Python | 0 | |
72a5f0d301b2169367c8bcbc42bb53b71c1d635c | Create utils.py | utils.py | utils.py | from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.api import memcache
import jinja2
import logging
import json
import os
class BaseHandler(webapp.RequestHandler):
context = {}
def initialize(self, req... | Python | 0.000001 | |
26bc11340590b0b863527fa12da03cea528feb46 | Add initial stub of GerritClient class | pygerrit/client.py | pygerrit/client.py | """ Gerrit client interface. """
from Queue import Queue, Empty, Full
from pygerrit.error import GerritError
from pygerrit.events import GerritEventFactory
class GerritClient(object):
""" Gerrit client interface. """
def __init__(self, host):
self._factory = GerritEventFactory()
self._host... | Python | 0.000006 | |
10f99acc11051b37595751b9b9b84e11dd133a64 | Add functions for getting available checksums for a channel from remote and disk. | kolibri/core/content/utils/file_availability.py | kolibri/core/content/utils/file_availability.py | import json
import os
import re
import requests
from django.core.cache import cache
from kolibri.core.content.models import LocalFile
from kolibri.core.content.utils.paths import get_content_storage_dir_path
from kolibri.core.content.utils.paths import get_file_checksums_url
checksum_regex = re.compile("^([a-f0-9]{... | Python | 0 | |
61ec190ca29187cbf9ad7b721fbf1936d665e4f6 | Revert "rm client.py" | orchestration/containerAPI/client.py | orchestration/containerAPI/client.py | from docker import Client as docker_client
class Client(object):
'''
Docker engine client
'''
def __init__(self, hostURL, version):
self.client = docker_client(base_url=hostURL, version=version)
self.url = hostURL
self.version = version
def get_url():
return self.ur... | Python | 0 | |
dcc08986d4e2f0e7940f485d0ece465b1325a711 | Add barebones FileBlob class | python/fileblob.py | python/fileblob.py | #!/usr/bin/env python
import os
MEGABYTE = 1024 * 1024
class FileBlob:
def __init__(self, path):
self.path = path
def data(self):
return open(self.path).read()
def size(self):
try:
return os.path.getsize(self.path)
except os.error:
return 0
d... | Python | 0.000009 | |
5c1e1744fa19bf900981d6a40c69195419861357 | Add snactor sanity-check command (#564) | leapp/snactor/commands/workflow/sanity_check.py | leapp/snactor/commands/workflow/sanity_check.py | from __future__ import print_function
import sys
from leapp.exceptions import LeappError, CommandError
from leapp.logger import configure_logger
from leapp.repository.scan import find_and_scan_repositories
from leapp.snactor.commands.workflow import workflow
from leapp.utils.clicmd import command_arg
from leapp.utils.... | Python | 0 | |
489004c5f81b8a5a2a639bc67f3ed5008f18960a | fix the naming error of the plotting script | doc/source/report/plots/plot_hc_dendrogram.py | doc/source/report/plots/plot_hc_dendrogram.py | from mousestyles import data
from mousestyles.classification import clustering
from mousestyles.visualization import plot_clustering
# load data
mouse_data = data.load_all_features()
# mouse inidividual
mouse_dayavgstd_rsl = clustering.prep_data(mouse_data, melted=False, std = True, rescale = True)
# optimal parame... | Python | 0.000004 | |
e47f61f22a568a69e74cbf8d0b70c4858879b9b5 | Temporary workaround for an apprtc bug. | chrome/test/functional/webrtc_apprtc_call.py | chrome/test/functional/webrtc_apprtc_call.py | #!/usr/bin/env python
# Copyright (c) 2012 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.
import random
import time
# Note: pyauto_functional must come before pyauto.
import pyauto_functional
import pyauto
import webrtc_... | #!/usr/bin/env python
# Copyright (c) 2012 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.
import random
# Note: pyauto_functional must come before pyauto.
import pyauto_functional
import pyauto
import webrtc_test_base
... | Python | 0.998543 |
37d851bb34552edfc3b1abd4d1034d4fdf46408f | Implement --remote | nvim-remote.py | nvim-remote.py | #!/usr/bin/env python3
"""
Copyright (c) 2015 Marco Hinz
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, ... | Python | 0.000097 | |
49424b855f043ae2bbb3562481493b1fa83f5090 | add random selection wip code | af_scripts/tmp/randSelect.py | af_scripts/tmp/randSelect.py | import random as rd
list = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
randList = list
#print randList
div=3
listSize=len(list)
#print listSize
numForOnePart=listSize/div
#print numForOnePart
rd.shuffle(randList)
#print randList
print [randList[i::3... | Python | 0 | |
7d4281574a9ee2a8e7642f14402a452f82a807db | Create smarthome.py | demos/smarthome/smarthome.py | demos/smarthome/smarthome.py | import logging
from pabiana import area
from pabiana.area import autoloop, load_interfaces, pulse, register, scheduling, subscribe
from pabiana.node import create_publisher, run
NAME = 'smarthome'
publisher = None
# Triggers
@register
def increase_temp():
area.context['temperature'] += 0.25
autoloop(increase_temp... | Python | 0 | |
a0493ff48b96056709880804f61e794621886c61 | Add CoNLL reader tests | compattern/dependency/tests/test_conll.py | compattern/dependency/tests/test_conll.py | # encoding: utf8
from compattern.dependency import conll
def test_read_french():
"""Test that conll.read understands French Bonsai output"""
line = (u"6\tchauffé\tchauffer\tV\tVPP\tg=m|m=part|n=s|t=past\t"
u"1100011\t5\tdep_coord\t_\t_")
sentence = conll.read([line, '\n'])[0]
assert len(s... | Python | 0 | |
4b696c2a54f7afd95013763c098aec30b08409d6 | Create bulb-switcher-ii.py | Python/bulb-switcher-ii.py | Python/bulb-switcher-ii.py | # Time: O(1)
# Space: O(1)
class Solution(object):
def flipLights(self, n, m):
"""
:type n: int
:type m: int
:rtype: int
"""
if m == 0: return 1
if n == 1: return 2
if m == 1 and n == 2: return 3
if m == 1 or n == 2 re... | Python | 0.000001 | |
0621b935558b6805d2b45fee49bc2e959201fd7a | add number-of-digit-one | vol5/number-of-digit-one/number-of-digit-one.py | vol5/number-of-digit-one/number-of-digit-one.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Zeyuan Shang
# @Date: 2015-11-03 15:21:00
# @Last Modified by: Zeyuan Shang
# @Last Modified time: 2015-11-03 15:21:14
import itertools
class Solution(object):
def countDigitOne(self, n):
"""
:type n: int
:rtype: int
"""
... | Python | 0.999993 | |
27d37833663842405f159127f30c6351958fcb10 | Add draft of example using the new @bench | bench_examples/bench_dec_insert.py | bench_examples/bench_dec_insert.py | from csv import DictWriter
from ktbs_bench.utils.decorators import bench
@bench
def batch_insert(graph, file):
"""Insert triples in batch."""
print(graph, file)
if __name__ == '__main__':
# Define some graph/store to use
graph_list = ['g1', 'g2']
# Define some files to get the triples from
... | Python | 0 | |
70cf735e7bee9c320229432400c775f6da8f0a5d | Add astro/osm-randomize-coord.py | astro/oskar/osm-randomize-coord.py | astro/oskar/osm-randomize-coord.py | #!/usr/bin/env python3
#
# Copyright (c) 2017 Weitian LI <weitian@aaronly.me>
# MIT License
#
"""
Create new randomized coordinates by adding random offset to the existing
OSKAR sky model (i.e., osm), and replace original coordinates with the
specified new ones.
"""
import os
import argparse
import numpy as np
cla... | Python | 0 | |
7c0a37e2ad123dfeb409c682a1cab37630678642 | Improve preprocessing text docs | tensorflow/python/keras/preprocessing/text.py | tensorflow/python/keras/preprocessing/text.py | # Copyright 2015 The TensorFlow 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 applica... | # Copyright 2015 The TensorFlow 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 applica... | Python | 0.000116 |
8b9c06d4cf29c546c97957a1cb381196e87eb25f | Update j2ee roles for 5.5 | ibmcnx/config/j2ee/RoleAllRestricted55.py | ibmcnx/config/j2ee/RoleAllRestricted55.py | '''
Set all Roles to Restricted - no anonymous access possible
Description:
Script is tested with IBM Connections 5.0
You have to edit the variables and set them to your administrative Accounts
Author: Klaus Bild
Blog: http://www.kbild.ch
E-Mail:
Documentation: http://scripting101.stoeps.de
Version: 5.0.1
Date... | Python | 0 | |
175470eea9716f587a2339932c1cfb6c5240c4df | add tools.testing module for asserts (numpy, pandas compat wrapper) | statsmodels/tools/testing.py | statsmodels/tools/testing.py | """assert functions from numpy and pandas testing
"""
import re
from distutils.version import StrictVersion
import numpy as np
import numpy.testing as npt
import pandas
import pandas.util.testing as pdt
# for pandas version check
def strip_rc(version):
return re.sub(r"rc\d+$", "", version)
def is_pandas_min_ve... | Python | 0 | |
68cd37c1c1bf279bc67e3d6391c8f4b88e0eb7a0 | add buggy profiler, not ready each instanciation add 2sec to exec time | syntaxnet_wrapper/test/profile_execution.py | syntaxnet_wrapper/test/profile_execution.py | from syntaxnet_wrapper.wrapper import SyntaxNetWrapper
from time import time
from prettytable import PrettyTable
def profile_exec(niter, action, keep_wrapper):
t = time()
sentence = 'une phrase de test'
for i in range(niter):
if keep_wrapper == False or i == 0:
sn_wrapper = SyntaxNetWrapper('French... | Python | 0 | |
c76c7b19afdf364ade2b7d0793cbdb14cb315131 | add smalltalk like object model | smalltalk_like/obj_model.py | smalltalk_like/obj_model.py | class Base(object):
def __init__(self, cls, fields):
self.cls = cls
self.fields = fields
def read_attribute(self, field_name):
return self.fields.get(field_name)
def write_attribute(self, field_name, value):
self.fields[field_name] = value
def call_method(self, method... | Python | 0.000002 | |
5bcd31440322d19262b694a5df299f43af577e5e | Create app.py | app.py | app.py | from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
| Python | 0.000003 | |
f6624531e47c599af42e75d84708359eaa982569 | Solve AoC 2020-12-25/1 | adventofcode2020/25.py | adventofcode2020/25.py |
def loop_size_finder(inp, subject_number=7):
i = 1
c = 0
while i != inp:
i *= subject_number
i %= 20201227
c += 1
return c
def transformer(iterations, subject_number=7):
i = 1
for _ in range(0, iterations):
i *= subject_number
i %= 20201227
retu... | Python | 0.999999 | |
b5433672a4e27db4e8f8698c311d05055462ac00 | Create main file | annotate_clin_virus.py | annotate_clin_virus.py | import timeit
import subprocess
import glob
import sys
import argparse
start = timeit.default_timer()
# This program runs some shit and does some shit about clinical virus samples
# Gonna write more as I need too
# parser = argparse.ArgumentParser(description= 'Annotate a set of UW clinical viral samples, pulling vi... | Python | 0.000001 | |
92aaff39dbd670f65dcbdeb34a2a506e0fcdf58b | add basic show_urls test | tests/management/commands/test_show_urls.py | tests/management/commands/test_show_urls.py | # -*- coding: utf-8 -*-
from django.core.management import call_command
from django.utils.six import StringIO
def test_show_urls_format_dense():
out = StringIO()
call_command('show_urls', stdout=out)
output = out.getvalue()
assert "/admin/\tdjango.contrib.admin.sites.index\tadmin:index\n" in output
... | Python | 0 | |
74a4f56d28497de89415f29ca3e1d6298c2fdd23 | Create drivers.py | chips/sensor/simulation/drivers.py | chips/sensor/simulation/drivers.py | # This code has to be added to the corresponding __init__.py
DRIVERS["simulatedsensors"] = ["PRESSURE", "TEMPERATURE", "LUMINOSITY", "DISTANCE", "HUMIDITY",
"COLOR", "CURRENT", "VOLTAGE", "POWER",
"LINEARACCELERATION", "ANGULARACCELERATION", "ACCELERATION", "LINEARVE... | Python | 0.000001 | |
0d77fe363b6e6e8b1a0424cec7631cf13b669968 | add linear simulation | epistasis/simulate/linear.py | epistasis/simulate/linear.py | __doc__ = """Submodule with various classes for generating/simulating genotype-phenotype maps."""
# ------------------------------------------------------------
# Imports
# ------------------------------------------------------------
import numpy as np
from gpmap.gpm import GenotypePhenotypeMap
# local imports
from ... | Python | 0.000012 | |
14e637720d6c80ed88232130b00385ceb4d451da | Create manual/__init__.py | app/tests/manual/__init__.py | app/tests/manual/__init__.py | """
Manual test module.
Note that while `TEST_MODE` should be set an environment variable for the
unit and integration tests, we want that off here so we can test against
local config data.
"""
| Python | 0.000294 | |
5bd4534b375efed2ce5026a64228a45a9acc1d64 | add parallel runner | microscopes/kernels/parallel.py | microscopes/kernels/parallel.py | """Contains a parallel runner implementation, with support
for various backends
"""
from microscopes.common import validator
import multiprocessing as mp
def _mp_work(args):
runner, niters = args
runner.run(niters)
return runner.get_latent()
class runner(object):
def __init__(self, runners, backen... | Python | 0.001425 | |
0cdc87edc4d5e4c967e7bc5bd35c5b30151d5a6e | Create admin_pages.py | evewspace/API/admin_pages.py | evewspace/API/admin_pages.py | from core.admin_page_registry import registry
registry.register('SSO', 'sso_admin.html', 'API.change_ssoaccesslist')
| Python | 0.000001 | |
48190b463bcbafc0b1d3af6c41677a295237e3ba | Add missing file | 3rdParty/V8/V8-5.0.71.39/build/has_valgrind.py | 3rdParty/V8/V8-5.0.71.39/build/has_valgrind.py | #!/usr/bin/env python
# Copyright 2016 the V8 project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
VALGRIND_DIR = os.path.join(BASE_DIR, 'third_party'... | Python | 0.000006 | |
82860a07e361aa5322b7d055c60c7178e40296bd | Create search_accepted_nodes_for_queries.py | SearchTools/search_accepted_nodes_for_queries.py | SearchTools/search_accepted_nodes_for_queries.py | # Search and accept, looks for each accept what the previously entered search text
# and the node that was accepted
import gzip
import json
import base64
import sys # Library of system calls
import traceback
import time
import os
from os.path import isfile, join
# Check that the script has been given the right arg... | Python | 0.000008 | |
ccce1108e1deab466fd72c022949fa05fa807a3a | add initial files for launch | synth.py | synth.py | # 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 specific language governing pe... | Python | 0.000001 | |
f480a0a8d51c5c059a05165f30f64bb310299ee3 | Add 'rescore' command | project/apps/api/management/commands/rescore.py | project/apps/api/management/commands/rescore.py | from django.core.management.base import (
BaseCommand,
)
from apps.api.models import (
Contestant,
Appearance,
Performance,
)
class Command(BaseCommand):
help = "Command to denormailze data."
def handle(self, *args, **options):
ps = Performance.objects.all()
for p in ps:
... | Python | 0.999783 | |
d4a7bbe27b285e455a3beafefd22fc493edeb161 | Add unittest for eventlogger config validation. | test/test_config_eventlogger.py | test/test_config_eventlogger.py | #!/usr/bin/env python2
import unittest
import subprocess
import threading
import tempfile
import os
from testdc import *
DAEMON_PATH = './astrond'
TERMINATED = -15
EXITED = 1
class ConfigTest(object):
def __init__(self, config):
self.config = config
self.process = None
def run(self, timeout)... | Python | 0 | |
1578c4328542dd1b1c7ccd1f08dd2b2455055190 | Add integration test covering all cql types | tests/integration/test_types.py | tests/integration/test_types.py | from decimal import Decimal
from datetime import datetime
from uuid import uuid1, uuid4
import unittest
from cassandra.cluster import Cluster
from cassandra.query import ColumnCollection
class TypeTests(unittest.TestCase):
def test_basic_types(self):
c = Cluster()
s = c.connect()
s.execut... | Python | 0 | |
78c9f392a02c0fdb72294e08a3d5ce78262443f5 | Create 1.py | 1.py | 1.py | u=1
| Python | 0.000001 | |
d596bfbbfa725111fb4c0f6d4abf6789669f06de | Create sets.py | sets.py | sets.py | #!/usr/bin/env python2
'''
Generates automatically one array, a.
Prints an ordered list with only unique elems
'''
import random
SIZE_LIST_A = 10
a = []
def populate_arrays():
for i in range(0, SIZE_LIST_A):
a.append(random.randint(1, 100))
if __name__ == "__main__":
populate_arrays()
print "a: {:s}".f... | Python | 0.000001 | |
563b9e1f826433179a5e3c5e611d40efc8736c4a | Create Hexbin Example | altair/examples/hexbins.py | altair/examples/hexbins.py | """
Hexbin Chart
-----------------
This example shows a hexbin chart.
"""
import altair as alt
from vega_datasets import data
source = data.seattle_weather()
# Size of the hexbins
size = 15
# Count of distinct x features
xFeaturesCount = 12
# Count of distinct y features
yFeaturesCount = 7
# Name of the x field
xFiel... | Python | 0 | |
ec85dbe3937781f188b9e8d5ae1f8dc7a58c1d0c | Add tests for message_processing module | tests/messenger/message_processing_test.py | tests/messenger/message_processing_test.py | import unittest
from app.messenger import message_processing
class MessageProcessingTestCase(unittest.TestCase):
def test_extract_all_messaging_events_valid_input(self):
known_input = [
{
'id': 1,
'messaging': [
{
... | Python | 0.000001 | |
8118dc283eececdd074bac675c57975ceeba3739 | Create gateway.py | Gateway/gateway.py | Gateway/gateway.py | \\ This will be the Gateway.py file for the RPi Gateway
| Python | 0.000001 | |
d9dcf34a73b4168885a02c495fb9b808a55b5c9e | Add spu debugger printer module | corepy/lib/printer/spu_debugger.py | corepy/lib/printer/spu_debugger.py | # Copyright (c) 2006-2009 The Trustees of Indiana University.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without ... | Python | 0 | |
2c0ce3c64720122bf2fdd80aeb2ff8359873ac83 | Test that noindex flag will only show robots metatag when set | municipal_finance/tests/test_analytics.py | municipal_finance/tests/test_analytics.py | from django.test import TestCase
from django.conf import settings
class TestAnalytics(TestCase):
def test_noindex_flag(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
self.assertTrue('<meta name="robots" content="noindex">' not in str(response.content))
... | Python | 0 | |
11dd2daf7dd125e0be6a604dd22ae25efed16226 | Update at 2017-07-20 14-05-11 | test.py | test.py | import json
from pathlib import Path
import numpy as np
import pandas as pd
import tensorflow as tf
from keras.backend.tensorflow_backend import set_session
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
set_session(tf.Session(config=config))
from keras.models import Sequential, Model
from keras.pr... | Python | 0 | |
5383c884257eda3977b32c29874da8402c6a6380 | Add test cases for Link, missed this file in previous commits. | coil/test/test_link.py | coil/test/test_link.py | """Tests for coil.struct.Link"""
import unittest
from coil import errors
from coil.struct import Node, Link
class BasicTestCase(unittest.TestCase):
def setUp(self):
self.r = Node()
self.a = Node(self.r, "a")
self.b = Node(self.a, "b")
def assertRelative(self, link, expect):
r... | Python | 0 | |
0c76fa59e77786c577f0750c65f97d24eb3c4157 | Test script | test.py | test.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
import os
import time
import datetime
import tables
from sklearn.metrics import f1_score,confusion_matrix
# ===================== Preparation des données =============================
# Load data
print("Loading data...")
... | Python | 0.000001 | |
77effff7ece070eabb3853ba918d40b7eb1c3de5 | Create sc.py | sc.py | sc.py | #!/usr/bin/env python
import soundcloud
from clize import clize, run
from subprocess import call
@clize
def sc_load(tracks='', likes='', tags='', group=''):
opts = {}
if likes:
method = 'favorites'
elif tracks or group:
method = 'tracks'
elif tags:
method = 'tracks'
o... | Python | 0.000005 | |
2055fc1eda896103931eaba5fb01238506aaac1a | Add signup in urls | urls.py | urls.py | from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from okupy.login.views import *
from okupy.user.views import *
from okupy.signup.views import *
admin.autodiscover()
urlpatterns = patterns('',
url(r'^login/$', mylogin),
url(r'^$', user),
url(r'^signup/', signup... | from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from okupy.login.views import *
from okupy.user.views import *
admin.autodiscover()
urlpatterns = patterns('',
url(r'^login/$', mylogin),
url(r'^$', user),
url(r'^admin/', include(admin.site.urls)),
)
| Python | 0 |
d5b6299b802810748584b06242f614550155a283 | Create app.py | app.py | app.py | from flask import Flask, request
import requests
import json
import traceback
import random
import os
from urllib.parse import urlencode
from urllib.request import Request, urlopen
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def main():
# if request.method == 'POST':
# try:
# ... | Python | 0.000003 | |
4ff22a24a7d681a3c62f7d7e4fe56c0032a83370 | Improve logging | app.py | app.py | import bottle
from bottle import get, post, static_file, request, route, template
from bottle import SimpleTemplate
from configparser import ConfigParser
from ldap3 import Connection, LDAPBindError, LDAPInvalidCredentialsResult, Server
from ldap3 import AUTH_SIMPLE, SUBTREE
from os import path
@get('/')
def get_index... | import bottle
from bottle import get, post, static_file, request, route, template
from bottle import SimpleTemplate
from configparser import ConfigParser
from ldap3 import Connection, LDAPBindError, LDAPInvalidCredentialsResult, Server
from ldap3 import AUTH_SIMPLE, SUBTREE
from os import path
@get('/')
def get_index... | Python | 0.00001 |
b720ecf75634718a122c97bcff29129e321aa9b2 | Add cat.py. | cat.py | cat.py | """
Usage: cat.py [FILE]...
Concatenate FILE(s), or standard input, to standard output.
"""
import sys
def iter_files(paths):
for path in paths:
try:
yield open(path, 'rb')
except (IOError, OSError) as e:
print("error: {}".format(e), file=sys.stderr)
def main(argv=None):... | Python | 0.000007 | |
3b58283f613fc827e024c8d971d89c24fc2b3ed0 | Create knn.py | knn.py | knn.py | import numpy as np
import pandas as pd
from sklearn import metrics
from sklearn.cross_validation import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.decomposition import PCA
#Read training data and split into train and test data
data=pd.read_csv('train.csv')
data1=data.values
X=data... | Python | 0.00005 | |
1faa3c76d1c752de02149af34954ed538fe10fa1 | Add test | app/tests/test_data.py | app/tests/test_data.py | import unittest
from app import data
class TestProjects(unittest.TestCase):
def test_load(self) -> None:
projects = data.Projects.load()
self.assertNotEqual(projects.data, {})
self.assertIn('Python', projects.data)
self.assertIn('Git Browse', projects.data['Python'])
self.... | Python | 0.000005 | |
5813474651299998fb27c64c6d179a0a59bbe28c | Create otc.py | otc.py | otc.py | def tick(a,b,c):
if a == 'help':
msg = '^otc {currency}, specify a 2nd currency for rates, add --last/high/low etc for that alone.'
return msg
import urllib2,json,StringIO
a = a.lower()
b = b.lower()
c = c.lower()
if b.startswith('-'):
c = b
b = 'usd'
if b =... | Python | 0.000002 | |
bf678628cf98b1c18a75f09fa15d26526ea0e3ac | Add gender choices fields | accelerator/migrations/0028_add_gender_fields.py | accelerator/migrations/0028_add_gender_fields.py | from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0027_add_gender_choices_object'),
]
operations = [
migrations.AddField(
model_name='entr... | Python | 0.000001 | |
bac06acb1e6255040f371232776f3da75fb9247a | Add data migration to populate preprint_doi_created field on existing published preprints where DOI identifier exists. Set to preprint date_published field. | osf/migrations/0069_auto_20171127_1119.py | osf/migrations/0069_auto_20171127_1119.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-11-27 17:19
from __future__ import unicode_literals
import logging
from django.db import migrations
from osf.models import PreprintService
logger = logging.getLogger(__name__)
def add_preprint_doi_created(apps, schema_editor):
"""
Data migration tha... | Python | 0 | |
167a6497d79a4a18badd5ea85a87e7eefcd02696 | Add init file to the root acceptance tests folder | test/acceptance/__init__.py | test/acceptance/__init__.py | # -*- coding: utf-8 -*-
"""
Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U
This file is part of fiware-orion-pep
fiware-orion-pep 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 versio... | Python | 0 | |
d290b3b2cc15a3bab907ed3847da709ab31edace | disable unpredictable tests | tests/acceptance/test_api.py | tests/acceptance/test_api.py | from __future__ import absolute_import
from sentry.testutils import AcceptanceTestCase
class ApiTokensTest(AcceptanceTestCase):
def setUp(self):
super(ApiTokensTest, self).setUp()
self.user = self.create_user('foo@example.com')
self.login_as(self.user)
self.path = '/api/'
def... | from __future__ import absolute_import
from sentry.testutils import AcceptanceTestCase
class ApiTokensTest(AcceptanceTestCase):
def setUp(self):
super(ApiTokensTest, self).setUp()
self.user = self.create_user('foo@example.com')
self.login_as(self.user)
self.path = '/api/'
def... | Python | 0 |
8fa776fd2fa63a44cb048a39fe7359ee9366c5e8 | Add basic Processor tests | tests/003-test-processor.py | tests/003-test-processor.py | import time
import random
import multiprocessing
from functools import wraps
try:
import queue
except ImportError:
import Queue as queue
import t
import bucky.processor
import bucky.cfg as cfg
cfg.debug = True
def processor(func):
@wraps(func)
def run():
inq = multiprocessing.Queue()
... | Python | 0.000001 | |
0b185bb6a30cb7c9b02c80051a8426dc736da3d6 | Add sample WSGI app | examples/wsgi.py | examples/wsgi.py |
import cgi
import json
from wsgiref import simple_server
import falcon
from mclib import mc_info
class MCInfo(object):
def on_get(self, req, resp):
host = req.get_param('host', required=True)
port = req.get_param_as_int('port', min=1024,
max=65565)
... | Python | 0 | |
b097075f7606563fc8ae80274e73b74dedd8129f | prepare a new folder "resources" for json files to replace python dynamic_resources | src/alfanous/Data.py | src/alfanous/Data.py | '''
Created on Jun 15, 2012
@author: assem
'''
class Configs:
pass
class Indexes:
pass
class Ressources:
pass
| Python | 0.000014 | |
708f1b009b9b23971d73bfc7bc09163969ab6e00 | Add integration tests for MEDIA_ALLOW_REDIRECTS | tests/test_pipeline_crawl.py | tests/test_pipeline_crawl.py | # -*- coding: utf-8 -*-
import os
import shutil
from testfixtures import LogCapture
from twisted.internet import defer
from twisted.trial.unittest import TestCase
from w3lib.url import add_or_replace_parameter
from scrapy.crawler import CrawlerRunner
from scrapy import signals
from tests.mockserver import MockServer
... | Python | 0.000001 | |
b171eb0c77f2d68051b48145f4e49275ed6860b9 | Add tests for signup code exists method | account/tests/test_models.py | account/tests/test_models.py | from django.conf import settings
from django.core import mail
from django.core.urlresolvers import reverse
from django.test import TestCase, override_settings
from django.contrib.auth.models import User
from account.models import SignupCode
class SignupCodeModelTestCase(TestCase):
def test_exists_no_match(self)... | Python | 0 | |
6c55d840ed22ec584c6adad15d89d9888b408d88 | [128. Longest Consecutive Sequence][Accepted]committed by Victor | 128-Longest-Consecutive-Sequence/solution.py | 128-Longest-Consecutive-Sequence/solution.py | class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# idea something like bucket sort,
# put the element n at the (start,end) bucket, everytime
# check n-1 or n+1 in the bucket, if so combine them
... | Python | 0.999951 | |
f5140f87e0e4326fe189b2f5f3ff3ac90f8db5c8 | Add new heroku_worker.py to run as a Heroku worker process | blockbuster/heroku_worker.py | blockbuster/heroku_worker.py | import redis
from rq import Worker, Queue, Connection
import os
REDIS_URL = os.environ.get('REDIS_URL', 'redis://localhost:32769/1')
print(REDIS_URL)
listen = ['default']
conn = redis.from_url(REDIS_URL)
if __name__ == '__main__':
with Connection(conn):
worker = Worker(map(Queue, listen))
worker... | Python | 0.000001 | |
0722624244d107b19a006f07fd884d47597e4eb1 | Add utility class to filter text through external program | lib/filter.py | lib/filter.py | from subprocess import Popen
from subprocess import PIPE
from subprocess import TimeoutExpired
import threading
from Dart import PluginLogger
from Dart.lib.plat import supress_window
_logger = PluginLogger(__name__)
class TextFilter(object):
'''Filters text through an external program (sync).
'''
def _... | Python | 0 | |
c7da0ed13838150f0276c4c9f425390822b5b43b | Add serializers for API models. | vinotes/apps/api/serializers.py | vinotes/apps/api/serializers.py | from django.contrib.auth.models import User
from rest_framework import serializers
from .models import Note, Trait, Wine, Winery
class WinerySerializer(serializers.ModelSerializer):
class Meta:
model = Winery
fields = ('id', 'name')
class WineSerializer(serializers.ModelSerializer):
class Me... | Python | 0 | |
383c67da4729886602227b715f65390427ccd8bc | Create w3_1.py | w3_1.py | w3_1.py | print ("Hello World!")
| Python | 0.000482 | |
66afbaab9abe51a83d6ea9765b7b8b70d045115e | Create question2.py | dingshubo/question2.py | dingshubo/question2.py | #_*_ coding:utf-8 _*_
#!/user/bin/python
import random
number_random = random.randint(1,100)
for chance in range(5): #玩家有5次机会
number_player=input('请输入一个1-100之间的整数:')
if(number_player>number_random):
print('这个数字偏大')
elif (number_player<number_random):
print('这个数字偏小')
print('你还有%... | Python | 0.999772 | |
3189cd139b868d74caf35aa5b7a80f748f21c231 | add tool to process brian's files | scripts/import/import_brian_files.py | scripts/import/import_brian_files.py | import glob
import os
os.chdir("c")
for filename in glob.glob("*"):
tokens = filename.split("_")
huc12 = tokens[1]
typ = tokens[2].split(".")[1]
newfn = "/i/%s/%s/%s" % (typ, huc12, filename)
os.rename(filename, newfn) | Python | 0 | |
e73b5fadbcff141fab2478954345ebaac22d8e63 | add K-means | K-means/K-means.py | K-means/K-means.py | '''
Created on Apr 30, 2017
@author: Leo Zhong
'''
import numpy as np
# Function: K Means
# -------------
# K-Means is an algorithm that takes in a dataset and a constant
# k and returns k centroids (which define clusters of data in the
# dataset which are similar to one another).
def kmeans(X, k, maxIt):
... | Python | 0.999987 | |
7e17363eaf8d17f0d595ca5199e59a51c7b1df65 | Add the core social_pipeline. | oneflow/core/social_pipeline.py | oneflow/core/social_pipeline.py | # -*- coding: utf-8 -*-
u"""
Copyright 2013-2014 Olivier Cortès <oc@1flow.io>.
This file is part of the 1flow project.
It provides {python,django}-social-auth pipeline helpers.
1flow is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by th... | Python | 0 | |
ee533a5e2a4eff99641383741e1cbe8e57c43e1f | add typing stub/compat package | gosubl/typing.py | gosubl/typing.py | try:
# ST builds >= 4000
from mypy_extensions import TypedDict
from typing import Any
from typing import Callable
from typing import Dict
from typing import Generator
from typing import IO
from typing import Iterable
from typing import Iterator
from typing import List
from ... | Python | 0 | |
2761e3bfd8d2c8281db565e54f6e3ea687bd5663 | add backfill problem_id script | private/scripts/extras/backfill_problem_id.py | private/scripts/extras/backfill_problem_id.py | """
Copyright (c) 2015-2019 Raj Patel(raj454raj@gmail.com), StopStalk
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
... | Python | 0.000001 | |
a3de0337f6e3511cc3381f92f7bbc384d7667dfd | Create xmas.py | xmas.py | xmas.py | gifts=['A Partridge in a Pear Tree', 'Two Turtle Doves, and', 'Three French Hens', 'Four Calling Birds', 'Five Golden Rings', 'Six Geese-a-Laying', 'Seven Swans-a-Swimming', 'Eight Maids-a-Milking', 'Nine Ladies Dancing', 'Ten Lords-a-Leaping', 'Eleven Pipers Piping', 'Twelve Drummers Drumming']
ordinal=['st', 'nd', 'r... | Python | 0.999876 | |
8fa4888dbf82d225f52b6df347372a0381c08237 | Add __main__.py for running python -m grip. | grip/__main__.py | grip/__main__.py | """\
Grip
----
Render local readme files before sending off to Github.
:copyright: (c) 2014 by Joe Esposito.
:license: MIT, see LICENSE for more details.
"""
from command import main
if __name__ == '__main__':
main()
| Python | 0.000006 | |
95874a5e06ff70d1cbea49321549beee5cc5abba | Create an example of storing units in HDF5 | examples/store_and_retrieve_units_example.py | examples/store_and_retrieve_units_example.py | """
Author: Daniel Berke, berke.daniel@gmail.com
Date: October 27, 2019
Requirements: h5py>=2.10.0, unyt>=v2.4.0
Notes: This short example script shows how to save unit information attached
to a `unyt_array` using `attrs` in HDF5, and recover it upon reading the file.
It uses the Unyt package (https://github.com/yt-pro... | Python | 0.000001 | |
406d038232a44c2640d334015ef3485ac115074d | Create PyAPT.py | PyAPT.py | PyAPT.py | # -*- coding: utf-8 -*-
"""
APT Motor Controller for Thorlabs
Adopted from
https://github.com/HaeffnerLab/Haeffner-Lab-LabRAD-Tools/blob/master/cdllservers/APTMotor/APTMotorServer.py
With thanks to SeanTanner@ThorLabs for providing APT.dll ad APT.lib
V1.0
20141125 V1.0 First working version
Michael Leung
mcleun... | Python | 0.000001 | |
4fe50fda289be7db3fb96450e713eb8f1a815026 | Add weighted linear algorithm | autoscaler/server/scaling/algorithms/weighted.py | autoscaler/server/scaling/algorithms/weighted.py | import math
from autoscaler.server.request_history import RequestHistory
from autoscaler.server.scaling.utils import parse_interval
class WeightedScalingAlgorithm:
def __init__(self, algorithm_config):
self.interval_seconds = parse_interval(
algorithm_config['interval']
)
self... | Python | 0.000596 | |
ca43479fc10505b04ec8861de074f25c80c6f5e1 | add rhythm description module | rhythm_features.py | rhythm_features.py |
from __future__ import division, print_function
import os
import numpy as np
import utils
onsets_dir = ''
beats_dir = ''
def compute_and_write(data_dir, track_list=None, features=None):
"""Compute frame-based features for all audio files in a folder.
Args:
data_dir (str): where to write features... | Python | 0.000001 | |
a726625e13ac08d0b6c2c686de476b6e78bc0f48 | Add unit test for _skeleton | dlstats/fetchers/test__skeleton.py | dlstats/fetchers/test__skeleton.py | import unittest
from datetime import datetime
from _skeleton import Dataset
class DatasetTestCase(unittest.TestCase):
def test_full_example(self):
self.assertIsInstance(Dataset(provider='Test provider',name='GDP',dataset_code='nama_gdp_fr',dimension_list=[{'name':'COUNTRY','values':[('FR','France'),('DE','... | Python | 0.000001 | |
e54c82c336827c1fc835837006885c245a05e5cb | Add html stripper for announcements | html_stripper.py | html_stripper.py | from html.parser import HTMLParser
class HTMLStripper(HTMLParser):
def __init__(self):
super().__init__()
self.reset()
self.strict = False
self.convert_charrefs= True
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
retur... | Python | 0 | |
20830e9fb2785eda94bf9e7c0dab70d476bc82b4 | Add `sample_settings.py` | sample_settings.py | sample_settings.py | # Rename this file to `settings.py` in deployment
# supported_subreddits = 'india'
supported_subreddits = 'india+indianbooks'
user_agent = ('Goodreads, v0.1. Gives info of the book whenever goodreads'
'link to a book is posted. (by /u/avinassh)')
scopes = ['identity', 'submit', 'privatemessages', 'read']... | Python | 0 | |
638c6383acf4431c95327fd0cbdb535e115e027d | Create admin util for user management. | flow-admin.py | flow-admin.py | #!/usr/bin/env python
#
# To ensure you can import rhizo-server modules set PYTHONPATH
# to point to rhize-server base dir.
# E.g.
# export PYTHONPATH=/home/user/rhizo-server/
#
from optparse import OptionParser
from main.users.auth import create_user
from main.users.models ... | Python | 0 | |
7af1a75b26ecdf1c7932169f2904a74db50c5b5d | Add release.py, updated to use Darcs. | sandbox/release.py | sandbox/release.py | #!/usr/bin/env python
import os
import re
import sys
import ftplib
import shutil
def firstLines(filename, n):
fd = file(filename)
lines = []
while n:
n -= 1
lines.append(fd.readline().rstrip('\r\n'))
return lines
def firstLine(filename):
return firstLines(filename, 1)[0]
def erro... | Python | 0 | |
0da1d2edc0f2a01d90cfc7cbf2bb4d37d1cc58d9 | Add examples from JModelica User's Manual (1.17.0) | src/ast_example.py | src/ast_example.py | # Import library for path manipulations
import os.path
# Import the JModelica.org Python packages
import pymodelica
from pymodelica.compiler_wrappers import ModelicaCompiler
# Import numerical libraries
import numpy as N
import ctypes as ct
import matplotlib.pyplot as plt
# Import JPype
import jpype
... | Python | 0 | |
55dd21610a2ed1befed6b4560528e8a6bf3602e2 | Define function to retrieve imgur credentials | imgur_cli/cli.py | imgur_cli/cli.py | import argparse
import logging
import os
import imgurpython
from collections import namedtuple
logger = logging.getLogger(__name__)
def imgur_credentials():
ImgurCredentials = namedtuple('ImgurCredentials', ['client_id', 'client_secret', 'access_token', 'refresh_token', 'mashape_key'])
try:
from con... | Python | 0.000006 | |
d3ebb800c88be18861608f8b174cc652223ac67c | Add utils.py with get_options function | apps/ivrs/utils.py | apps/ivrs/utils.py | def get_options(question_number):
if question_number == 2:
return " Press 4 or 5 "
else:
return " Press 1 for Yes or 2 for No"
| Python | 0.000001 | |
2c8752cd586f6d02ce8da4bc3a79660889ed7f3f | Add some minimal testing for BandRCModel to the test suite. | climlab/tests/test_bandrc.py | climlab/tests/test_bandrc.py | import numpy as np
import climlab
import pytest
# The fixtures are reusable pieces of code to set up the input to the tests.
# Without fixtures, we would have to do a lot of cutting and pasting
# I inferred which fixtures to use from the notebook
# Latitude-dependent grey radiation.ipynb
@pytest.fixture()
def model():... | Python | 0 | |
c1ea660b72ac10fd0a2dea1416b45c6796ca5adb | add pascal voc ingest | ingest/pascal.py | ingest/pascal.py | #!/usr/bin/python
import json
import glob
import sys
import getopt
import collections
import os
from os.path import isfile, join
import xml.etree.ElementTree as et
from collections import defaultdict
# http://stackoverflow.com/questions/7684333/converting-xml-to-dictionary-using-elementtree
def etree_to_dict(t):
... | Python | 0.999984 | |
59fd062a65e83bc95e9864e4cfb057ba7ffbe475 | Add files via upload | apriori_temp.py | apriori_temp.py | """
Description : Simple Python implementation of the Apriori Algorithm
Usage:
$python apriori.py -f DATASET.csv -s minSupport -c minConfidence
$python apriori.py -f DATASET.csv -s 0.15 -c 0.6
"""
import sys
from itertools import chain, combinations
from collections import defaultdict
from optparse imp... | Python | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.