code stringlengths 1 199k |
|---|
APP_DISC_PATH = "C:/www/Django-Projects/"
DISC_PATH = "C:/WWW/"
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'meem_dev',
'USER': 'root',
'PASSWORD': 'root',
'HOST': '',
'PORT': '',
'OPTIONS': {'init_command': 'SET storage_engine=INN... |
from distutils.core import setup
setup(name='splice',
version='0.1',
description='Plot Multiple Slices of Data in Plotly (More Easily)',
author='Connor Sempek',
author_email='cpsempek@gmail.com',
license='MIT',
packages=['splice'],
package_data={'': ['flat_ui_colors.json']}
... |
import pyglet
import settings
import entity
import utils
from utils import Vec2d, Point, Rect
class Ruby(entity.Entity):
IMAGE = settings.RUBY_IMAGE |
from redis import Redis
from rq import Queue
q = Queue(connection=Redis())
def output_result(results):
job = q.enqueue() |
from builtins import range, next, zip, map
from future.utils import viewvalues
import sys
if sys.version < '3':
text_type = unicode
binary_type = str
shelve_key = lambda x: x.encode()
int_type = long
else:
text_type = str
binary_type = bytes
unicode = str
shelve_key = lambda x: x
int... |
'''
run the CCR scorer on all the groups, including no restriction to a single group
'''
import os
import sys
import json
import subprocess
import multiprocessing
from collections import defaultdict
targets = json.load(open('../../trec-kba-ccr-and-ssf-query-topics-2013-07-16.json'))['targets']
groups = set()
for targ i... |
from selenium import webdriver
from selene import config
from selene.common.none_object import NoneObject
from selene.driver import SeleneDriver
from tests.acceptance.helpers.helper import get_test_driver
from tests.integration.helpers.givenpage import GivenPage
__author__ = 'yashaka'
driver = NoneObject('driver') # t... |
<removed> |
from PySide import QtGui, QtCore
from view.playerModule.Player import Player
class SessionViewItem(QtGui.QWidget):
"""
This class define the item contained in the SessionView that stands for videos. An item is composed by a thumbnail of the video,
the name of the video and the duration of the video. it has ... |
from django import template
from django.conf import settings
from kishore import settings as kishore_settings
try:
from less.templatetags.less import less as less_tag
except ImportError:
pass
register = template.Library()
@register.simple_tag
def kishore_admin_js():
output = ""
for path in kishore_setti... |
"""Find examples where classifiers are wrong.
Matthew Alger <matthew.alger@anu.edu.au>
Research School of Astronomy and Astrophysics
The Australian National University
2017
"""
import collections
import astropy.io.ascii
import numpy
import pipeline
def get_examples():
titlemap = {
'RGZ & Norris & compact': ... |
from .read import read |
'''
Copyright (c) 2014 Tilman Ginzel
This code is licensed under MIT license (see LICENSE.txt for details).
Created on 11.04.2014
'''
from math import sqrt
from general.HomVectorException import HomVectorException
class HomVector(object):
"""
This class describes vectors and points with homogeneous coordinates.... |
class Solution(object):
def merge(self, intervals):
if len(intervals) == 0:
return []
intervals.sort(key=lambda item:item.start)
answer = [intervals[0]]
for item in intervals[1:]:
if item.start > answer[-1].end:
answer.append(item)
... |
"""
Created on Mon Jul 27 10:26:00 2015
@author: danb0b
"""
import PySide.QtGui as qg
import PySide.QtCore as qc
class CommonTableWidget(qg.QTableWidget):
pass
def calc_table_width2(self):
width = 0
width += self.verticalHeader().width()
width += sum([self.columnWidth(ii)
... |
"""
Models and database for wcycle application
"""
import os
from playhouse.db_url import connect
from peewee import Model as _Model, CharField, DateField, IntegerField
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
DB_NAME = 'db.sqlite3'
DB_PATH = os.path.abspath(os.path.join(PROJECT_ROOT, DB_NAME))
DB_URL ... |
from distutils.core import setup
setup(
name = 'vireo',
version = '0.15.1',
description = 'A library and framework for event-driven application development',
license = 'MIT',
author = 'Juti Noppornpitak',
author_email = 'juti_n@yahoo.co.jp',
# url = 'http://... |
'''
ogm_pallet.py
A module that contains a forklift pallet definition for this project.
It updates these feature classes in SGID from the OGM database:
SGID10.ENERGY.DNROilGasWells
SGID10.ENERGY.DNROilGasWells_HDBottom
SGID10.ENERGY.DNROilGasWells_HDPath
as well as the associated ftp packages.
It also updates data in f... |
import json, urllib2, weka, os
from bs4 import BeautifulSoup
def ensurePathForFile(filename):
directory = os.path.dirname(filename)
if not os.path.isdir(directory):
print "*Note* Folder '%s' doesn't exist. Creating for file '%s'" %(directory,filename)
os.makedirs(directory)
def writeJsonToFile(jsonObj, filename, ... |
import requests
from bs4 import BeautifulSoup
from apps.base import respond
def youtube(query):
url = "https://www.youtube.com/results?search_query={}".format(query)
res = requests.get(url)
if res.status_code != 200:
logging.error(res)
return "cannot find video"
bs = BeautifulSoup(res.co... |
import json
from src.controllers import\
Base<%= endpoint %>Controller
from src.models.authentication_model import\
requires_auth,\
check_all_request_limit
_parse_class_name = Base<%= endpoint %>Controller.model._parse_class_name
class <%= endpoint %>Controller(BaseUserController):
pass |
def sanitize(time_string):
if '-' in time_string:
splitter = '-'
elif ':' in time_string:
splitter = ':'
else:
return(time_string)
(mins, secs) = time_string.split(splitter)
return (mins + '.' + secs)
def get_coach_data(fileName):
try:
with open(fileName) as myfil... |
"""Hello
"""
import sys
import json
def main():
assert sys.argv[1] == 'update'
print json.dumps({
'name': 'moe',
'sex': 0
}, indent=4)
if __name__ == '__main__':
main() |
from mamba import description, context, it, before
from expects import expect, equal, contain, raise_error
from doublex_expects import have_been_called, have_been_called_with
from doublex import Spy, when
from simpledatamigrate import migrator, repositories
with description('Test Migrator') as self:
with before.eac... |
from __future__ import unicode_literals
from django.core.exceptions import ImproperlyConfigured
from django.core.paginator import InvalidPage, Paginator
from django.db.models.query import QuerySet
from django.http import Http404
from django.utils import six
from django.utils.translation import ugettext as _
from django... |
import sys
import json
import click
import logging
import requests
log = logging.getLogger(__name__)
from snfilter import parse_nameslist, filter_feed, output_json, output_truvu, output_gr
@click.group()
def cli():
pass
@cli.command()
@click.option("--url", default="http://www.spotternetwork.org/feeds/gr.txt", help... |
import sys,os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ms2ldaviz.settings")
import django
django.setup()
from basicviz.models import *
import csv
if __name__ == '__main__':
experiment_name = sys.argv[1]
output_name = sys.argv[2]
experiment = Experiment.objects.get(name = experiment_name)
motifs = Mass2Motif... |
from django.conf.urls import include, url
from rest_framework import routers
from rest_framework_jwt.views import refresh_jwt_token
from rockit.core import views
router = routers.SimpleRouter()
urlpatterns = router.urls
urlpatterns.append(url(r'^$', views.RockitView.as_view(), name="root"))
urlpatterns.append(url(r'^to... |
from mongorpc import MongoRPC
rpc = MongoRPC()
@rpc.register()
def hello(msg):
print("hello {}".format(msg))
rpc.start() |
import os
import sys
import optparse
import re
import time
def GetOptions():
parser = optparse.OptionParser()
parser.add_option('-o', '--output',
dest="output",
help="output path for new files",
)
parser.add_option('-l', '--list',
... |
from elvis.peanuts import Peanut
from elvis.peanuts import PeanutManager
__all__ = ['Peanut', 'PeanutManager'] |
from LambdaQuery.expr import *
from LambdaQuery.do_notation import *
class Query(Table, Monad):
alias = 'query'
def __init__(self, columns, joincond=AndExpr(), groupbys=L(), leftjoin=False):
self.columns = columns
self.joincond = joincond
self.groupbys = groupbys
self.leftjoin = ... |
import collections
import json
from enum import Enum
from typing import Iterable, Optional, List, Dict, Union
from TM1py.Objects.TM1Object import TM1Object
from TM1py.Utils.Utils import CaseAndSpaceInsensitiveSet, format_url
class UserType(Enum):
User = 0
SecurityAdmin = 1
DataAdmin = 2
Admin = 3
Op... |
import select
from .lib import *
from .sock import *
from future.moves.urllib.request import urlopen, Request
import platform
import subprocess
from threading import Thread
"""
This is a modified version of "UPnP-Exploiter." It's been
changed to work with Python 3.3, the code has been
restructured to make it modular, c... |
BOARD_HEIGHT = 10
BOARD_WIDTH = 10
DEFAULT_SHIPS = [
('Carrier', 5),
('Battleship', 4),
('Destroyer', 3),
('Submarine', 3),
('Patrol Boat', 2),
]
TIMEOUT_LENGTH = 1000000 # 1000000 microseconds = 1 second |
"""Wrappers to TensorFlow Session.run().
"""
from collections import OrderedDict
class Runner(object):
"""
Wrap TensorFlow Session.run() by adding preprocessing and postprocessing
steps.
"""
def __init__(self, inputs, outputs, sess=None):
self.sess = sess
self.inputs = inputs
... |
from jasy.asset.sprite.BlockNode import BlockNode
class BlockPacker():
def __init__(self, w = 0, h = 0):
self.nodes = []
self.autogrow = False
if w > 0 and h > 0:
self.root = BlockNode(self, 0, 0, w, h)
else:
self.autogrow = True
self.root = None
... |
class Solution(object):
def numberToWords(self, num):
"""
:type num: int
:rtype: str
"""
if num==0:
return 'Zero'
mapping=["","Thousand","Million", "Billion"]
resstr=''
for i in range(len(mapping)):
if num%1000 != 0:
... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'traces.tests.south_settings')
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.views import defaults as default_views
from rest_framework import route... |
"""
A quick example of uploading instances to a job with a multi-page document.
You will have to update the following constants for this to work on your box:
API_TOKEN
ENDPOINT
IMAGE_PATH
TARGET_JOB_ID
"""
from client import Client
API_TOKEN = "1569df5c3d624054b8f3ba6b513f0bc3"
ENDPOINT = "http://localh... |
from distutils.core import setup
setup(
name='osmapping',
version='0.1.7',
packages=[''],
url='https://github.com/astyler/osmapping',
download_url='https://github.com/astyler/osmapping/tarball/0.1.6',
license='MIT',
author='Alex Styler',
author_email='astyler@gmail.com',
description=... |
NAME="Generic Attribute"
UUID=0x1801 |
import functools
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline impo... |
my_seq = [0, 1, 2]
print my_seq[3] |
from annotator import es
TYPE = 'document'
MAPPING = {
'annotator_schema_version': {'type': 'string'},
'created': {'type': 'date'},
'updated': {'type': 'date'},
'title': {'type': 'string'},
'link': {
'type': 'nested',
'properties': {
'type': {'type': 'string', 'index': 'n... |
from django.db import migrations
import sandbox.apps.user.models
class Migration(migrations.Migration):
dependencies = [
('user', '0001_initial'),
]
operations = [
migrations.AlterModelManagers(
name='user',
managers=[
('objects', sandbox.apps.user.mod... |
'''
Created on Jun 15, 2012
@author: rogelio
'''
from django.db.models.query import QuerySet
class CaseInsensitiveQuerySet(QuerySet):
'''This QuerySet is not used by default in the ExtendedBaseModel, but is another utility
query set which provides case insensitive searches.
This Query set is used to replace... |
"""
pyannote.audio relies on torchaudio for reading and resampling.
"""
import math
import warnings
from io import IOBase
from pathlib import Path
from typing import Mapping, Optional, Text, Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
import torchaudio
from torch import Tensor
from pyan... |
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class Mapping(Document):
pass |
import _plotly_utils.basevalidators
class ZautoValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(self, plotly_name="zauto", parent_name="heatmapgl", **kwargs):
super(ZautoValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edi... |
import sys
import threading
import subprocess
import os
from flask import Flask
import glob
import argparse
app = Flask(__name__)
engines = ["google", "linkedin", "bing", "yahoo", "github"]
class EngineThread (threading.Thread):
"""Thread used to call EmailHarvester for a specific engine (google, github, bing, etc.... |
from preggy import expect
from tornado.testing import gen_test
import thumbor.filters
from tests.base import FilterTestCase
from thumbor.config import Config
from thumbor.context import Context, RequestParameters
from thumbor.filters.rotate import Filter
from thumbor.importer import Importer
class RotateFilterTestCase(... |
from rwslib.extras.audit_event import parser
import unittest
import os
class MockEventer:
"""
Mock Event Sink instance for the purposes of testing (capturing all ASC)
"""
def __init__(self):
self.__events = {}
def default(self, event):
self.__events.setdefault(event.subcategory, []).... |
import string
original = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
print string.translate(original,string.maketrans("abcdefghijklmnopqrstuvwxyz","cdefghijkl... |
'''This will have the class that will execute the commands
It will be a container, but will also have a method for
executing and logging.'''
import time, subprocess
class Command(object):
'''inputs:
title as str
description as str
command as str
named_opts as dictionary
positional_opts as arr... |
"""
A converter of python values to TOML Token instances.
"""
import codecs
import datetime
import six
import strict_rfc3339
import timestamp
from prettytoml import tokens
import re
from prettytoml.elements.metadata import NewlineElement
from prettytoml.errors import TOMLError
from prettytoml.tokens import Token
from p... |
from __future__ import division, print_function
import re
import string
import tarfile
import fnmatch
import requests
import feedparser
import numpy as np
import os
URL = "http://arxiv.org/rss/astro-ph"
COMMENT_RE = re.compile(r"(?<!\\)%")
AMP_RE = re.compile(r"(?<!\\)&")
DATA_DIR = os.environ.get("ARXIV_DATA_DIR", "da... |
import user
from institutions import institutions
user.questions = {'age': 'How old are you?', 'name': 'Hey! Whats your name'}
class TestClass:
def test_user_create(self):
new_user = user.User('123')
assert new_user.chat_id =='123'
def test_answer_name_question(self):
new_user = user.Use... |
from __future__ import print_function, unicode_literals
import random
import requests
import click
from characteristic import attributes
from constants import USER_AGENTS, URLs
from utils import string_to_datetime
def get_headers():
return {
'User-Agent': random.choice(USER_AGENTS),
}
@click.command()
@... |
from keras.models import Sequential
from keras.layers import Dense
import numpy
seed = 7
numpy.random.seed(seed)
dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",")
print dataset[:,0:8]
X = dataset[:,0:8]
Y = dataset[:,8] |
import os
import sys
import logging
import logging.config
import time
dir_cur = os.path.normpath(os.path.dirname(os.path.abspath(__file__)).split('bin')[0])
if dir_cur not in sys.path:
sys.path.insert(0, dir_cur)
log_dir = os.path.normpath(dir_cur + os.path.sep + 'logs' + os.path.sep + 'sync_snmp_logs')
if not os.p... |
from sodapy import Socrata
from NASA_accounts import apps
app = apps["pyNASA"]
client = Socrata("data.nasa.gov", app["token"])
metadata = client.get_metadata("b67r-rgxc")
data = client.get("b67r-rgxc") |
"""
PyCydia
by switchpwn
Copyright (c) 2014 Mustafa Gezen
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... |
from peewee import IntegerField
from playhouse.kv import KeyValue
from .base import DatabaseTestCase
from .base import db
class TestKeyValue(DatabaseTestCase):
def setUp(self):
super(TestKeyValue, self).setUp()
self._kvs = []
def tearDown(self):
if self._kvs:
self.database.dr... |
"""
Local settings
- Run in Debug mode
- Use mailhog for emails
- Add Django Debug Toolbar
- Add django-extensions as app
"""
from .base import *
import environ
env = environ.Env()
DEBUG = env.bool('DJANGO_DEBUG', default=True)
TEMPLATES[0]['OPTIONS']['debug'] = DEBUG
SECRET_KEY = env('DJANGO_SECRET_KEY', default='|ad(... |
from django.contrib import admin
from trips.models import Post
admin.site.register(Post) |
'''
usage: python git.py clone [options] [--] <repo> [<dir>]
options:
-v, --verbose be more verbose
-q, --quiet be more quiet
--progress force progress reporting
-n, --no-checkout don't create a checkout
--bare create a bare repository
--mirror ... |
from django import forms
from static.models import ipv6_static, ipv4_static
class IPv6StaticForm(forms.ModelForm):
class Meta:
model = ipv6_static
fields = ('__all__')
class IPv4StaticForm(forms.ModelForm):
class Meta:
model = ipv4_static
fields = ('__all__') |
from google.appengine.ext import ndb
import collections
from ndbx import utils, Lock
class TestTasklets:
def testA(self):
future = ndb.Future()
lock = Lock()
messages = collections.deque()
@utils.tasklet(ff=True)
def work(i):
messages.append('init %s' % i)
... |
"""Flask plugin
Heavily copied from apispec
"""
from collections.abc import Mapping
import re
import werkzeug.routing
from apispec import BasePlugin
RE_URL = re.compile(r'<(?:[^:<>]+:)?([^<>]+)>')
DEFAULT_CONVERTER_MAPPING = {
werkzeug.routing.UnicodeConverter: ('string', None),
werkzeug.routing.IntegerConverte... |
__author__ = 'JoeJoe'
from enum import IntEnum
class Direction(IntEnum):
North = 0
East = 1
South = 2
West = 3
def next(self):
return Direction((self + 1) % 4)
def prev(self):
return Direction((self - 1) % 4)
def oppos(self):
return Direction(self.next().next())
d... |
import scipy
import numpy
import pyfits
import VLTTools
import SPARTATools
import os
import glob
import time
i = 0
datadir = "/diska/data/SPARTA/2015-04-09/Derotator_20/"
ciao = VLTTools.VLTConnection(simulate=False, datapath=datadir)
offsetFile = '/diska/data/SPARTA/2015-04-09/Derotator_19/FieldLensModel.txt'
offsetX ... |
import csv
import matplotlib.pyplot as plt
import numpy as np
import functions as fxn
ps = fxn.pseasons
reg = fxn.gp_plotting_regions
reg_lab = fxn.gp_regions
mild = fxn.gp_mild # mild season numbers
mod = fxn.gp_mod # moderate season numbers
sev = fxn.gp_sev # severe seasons numbers
sevvec = fxn.gp_severitylabels # m... |
"""
Author(s): Matthew Loper
See LICENCE.txt for licensing and contact information.
"""
__all__ = ['ColoredRenderer', 'TexturedRenderer', 'DepthRenderer']
import numpy as np
from cvwrap import cv2
import time
import platform
import scipy.sparse as sp
from copy import deepcopy
import common
from common import draw_visib... |
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/usr/local/include".split(';') if "/usr/local/include" != "" else []
PROJECT_CATKIN_DEPENDS = "".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else []
PROJECT_NAME = "csv_annotation_proc"
PROJECT_SPACE_DIR = "/usr/local"
PROJ... |
from functools import partial
from pytest import raises
from ..scalars import String
from ..structures import List, NonNull
from .utils import MyLazyType
def test_list():
_list = List(String)
assert _list.of_type == String
assert str(_list) == "[String]"
def test_list_with_unmounted_type():
with raises(... |
""" vxhr.py
Interface
"""
__author__ = 'Scott Burns <scott.s.burns@vanderbilt.edu>'
__copyright__ = 'Copyright 2014 Vanderbilt University. All Rights Reserved'
import os
from app import app
import data
if __name__ == '__main__':
app.debug = True
port = int(os.environ.get('VXHR_PORT', 9000))
host = os.enviro... |
import sys
import os
sys.path.insert(0, os.path.abspath('../humo/'))
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.mathjax',
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'HUMO'
copyright = u'2015, Kim G. L. Pedersen'
version = '0.1'
release = '0.1'
exclude_patterns... |
"""This module represents an optimized variant of the module genetic2.py.
It uses the multiprocessing module instead of the threading module to take
advantage of systems with multiple cores.
"""
import random
import multiprocessing
import benchbuild.experiments.sequences.polly_stats as polly_stats
__author__ = "Christo... |
def permutations(data, string, tracker):
if len(string) == len(data):
print(string)
return
for i in range(len(data)):
if i in tracker:
continue
tracker[i] = True
permutations(data, string + str(data[i]), tracker)
del tracker[i]
permutations(['A', 'B', ... |
import os
import sys
import dotenv
if __name__ == "__main__":
dotenv.read_dotenv()
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "buildservice.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
from django.test import TestCase |
from django.apps import AppConfig
class BlogConfig(AppConfig):
name = 'blog'
varbose_name = 'Blog Application'
def ready(self):
from . import signals |
from django.conf.urls import patterns, url, include
from rest_framework import routers
from commoncore import views
router = routers.SimpleRouter()
router.register(r'strandtypes', views.StrandTypeViewSet)
router.register(r'strands', views.StrandViewSet)
router.register(r'gradelevels', views.GradeLevelViewSet)
router.re... |
"""
Shane Bussmann
2014 August 20
Plot dN/dA as a function of angular separation from the center of light. dN =
number of objects between radius 1 and radius 2. dA = area between radius 1
and radius 2.
"""
from astropy.table import Table
from astropy.io import ascii
import matplotlib
import matplotlib.pyplot as plt
f... |
from optparse import make_option
import django
from evostream.default import api
from evostream.management.base import BaseEvoStreamCommand
class Command(BaseEvoStreamCommand):
help = 'Push a local stream to an external destination.'
requires_system_checks = False
silent_keys = ('localStreamName',)
if d... |
import re
import inspect
def convert_to_int(x):
try:
return int(x)
except:
return x
class PatternRegister(object):
"""
This objects is a register for mapping keystrokes into functions. A
keystroke is added using the register method and the function is
retrieved using get_function... |
import _plotly_utils.basevalidators
class AlignValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self, plotly_name="align", parent_name="scattergeo.hoverlabel", **kwargs
):
super(AlignValidator, self).__init__(
plotly_name=plotly_name,
parent_name... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import tempfile
import warnings
from cleverhans import dataset
utils_mnist_warning = "cleverhans.utils_mnist is deprecrated and will be " \
... |
"""
Remove Duplicates from Sorted List II
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
"""
class ListNode(object):
def __init__(self, x):
... |
import isilon
import argparse
import json
import logging
from os.path import expanduser
import getpass
import os
import sys
fqdn = "192.168.167.101"
username = "root"
password = "a"
def main():
parser = argparse.ArgumentParser(description='Report on user quotas')
parser.add_argument('--file', action='append', ... |
import os
import re
from datetime import datetime
from google.appengine.api import users
from google.appengine.api import urlfetch
import webapp2
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp import util
import json as simplejson
from model import get_current_youtify_user_model
from ... |
from django.conf import settings
from django.test import TestCase
from django_test_tools.generators.model_generator import FactoryBoyGenerator
class TestFactoryBoyGenerator(TestCase):
def test_create_template_data_servers(self):
generator = FactoryBoyGenerator()
server_template_data = generator.crea... |
from django import test
from django.http import HttpRequest
from tastypie.http import HttpUnauthorized
from libs.auth import MethodAuthentication
class MethodAuthenticationTest(test.TestCase):
def setUp(self):
self.auth = MethodAuthentication()
self.request = HttpRequest()
def test_is_authentica... |
import praw
import random
reddit = praw.Reddit(user_agent='Facility_AI Reborn by /u/Reckasta', client_id='GORfUXQGjNIveA', client_secret='SzPFXaqgVbRxm_V9-IfGL05npPE', username='Facility_AI', password='UncloakIsADick')
subreddit = bot.subreddit('SecretSubreddit')
comments = subreddit.stream.comments()
for comment in co... |
import numpy as np
from time import time
from eft_calculator import EFT_calculator
import tools
def load_coordinates(name):
lines = open('random/'+name).readlines()[-7:-1]
coors = [[float(item) for item in line.split()[2:5]] for line in lines]
return np.array(coors)
def test_random_set():
ener = []
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import unittest
import numpy as np
from vectormath import Vector2, Vector2Array, Vector3, Vector3Array
class TestVMathVector2(unittest.TestCase):
def test_init_excepti... |
import unittest
from katas.kyu_7.count_consonants import consonant_count
class ConsonantCountTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(consonant_count(''), 0)
def test_equals_2(self):
self.assertEqual(consonant_count('aaaaa'), 0)
def test_equals_3(self):
se... |
from setuptools import setup, find_packages
from os.path import dirname, realpath, join
def read_long_description():
current_dir = dirname(realpath(__file__))
with open(join(current_dir, "README.rst")) as long_description_file:
return long_description_file.read()
setup(
name="Flask-Navigation",
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.