content stringlengths 4 20k |
|---|
"""Asyncronous tasks for MDN scraping."""
from json import dumps
from traceback import format_exc
from celery import shared_task
import requests
from .models import FeaturePage, TranslatedContent
from .scrape import scrape_feature_page
@shared_task(ignore_result=True)
def start_crawl(featurepage_id):
"""Start ... |
# -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["download"]
import os
import shutil
import logging
from tempfile import NamedTemporaryFile
from six.moves import urllib
try:
import pandas as pd
except ImportError:
pd = None
from .config import KPLR_ROOT
_URL = "https://z... |
def test_map_txes(chain):
tx0 = set()
for block in chain:
for tx in block:
tx0.add(tx.index)
tx1 = set(chain.blocks.txes.index)
tx2 = set(chain.blocks.map(lambda b: b.txes).index)
tx3 = set(chain.blocks.map(lambda b: b.txes.index))
tx4 = set(chain.blocks.map(lambda b: b.txes... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
hillshade.py
---------------------
Date : October 2013
Copyright : (C) 2013 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
***************... |
import os
import subprocess
import sublime
from ..SublimeCscope import DEBUG, PACKAGE_NAME
from . import settings
from .indexer import PRIMARY_DB, SECONDARY_DB
from .cscope_results import CscopeBuildDbResult, CscopeQueryResult, CscopeResultLimitException
CSCOPE_FILE_LIST_EXT = 'files'
CSCOPE_DB_EXT = 'out'
CSCOPE_O... |
"""
This file contains tools for (not only) Avocado developers.
"""
import logging
import time
import os
# Use this for debug logging
LOGGER = logging.getLogger("avocado.debug")
# measure_duration global storage
__MEASURE_DURATION = {}
def measure_duration(func):
"""
Use this as decorator to measure durati... |
__metaclass__ = type
__all__ = ['get_lock_id_for_branch_id', 'mirror']
import datetime
import pytz
from twisted.internet import defer
def get_lock_id_for_branch_id(branch_id):
"""Return the lock id that should be used for a branch with the passed id.
"""
return 'worker-for-branch-%s@supermirror' % (bra... |
"""engine.SCons.Platform.sunos
Platform-specific initialization for Sun systems.
There normally shouldn't be any need to import this module directly. It
will usually be imported through the generic SCons.Platform.Platform()
selection method.
"""
#
# Copyright (c) 2001 - 2016 The SCons Foundation
#
# Permission is h... |
import time
import pytest
class TestOsIntegration:
@pytest.mark.min_mender_version("2.2.1")
def test_syslogger(self, setup_board, connection):
"""Test that we log to syslog, and that we don't if we specify --no-syslog."""
def is_mender_in_syslog_messages():
now = time.time()
... |
"""
Demonstration of Polygon and subclasses
"""
import sys
import numpy as np
from vispy import app, gloo, visuals
from vispy.visuals import transforms
# vertex positions of polygon data to draw
pos = np.array([[0, 0, 0],
[0.25, 0.22, 0],
[0.25, 0.5, 0],
[0, 0.5, 0],
... |
import itertools
import re
from .logger import get_logger
from six import binary_type, text_type
any_method = object()
class RouteTokenizer(object):
def literal(self, scanner, token):
return ("literal", token)
def slash(self, scanner, token):
return ("slash", None)
def group(self, scann... |
import json
from collections import UserList
from django.conf import settings
from django.core.exceptions import ValidationError
from django.utils import timezone
from django.utils.html import escape, format_html, format_html_join, html_safe
from django.utils.translation import gettext_lazy as _
def pretty_name(name... |
"An arbitrary-precision, signed rational numeric type."
__all__ = [
'Fraction',
'FractionCompatible',
]
# ===----------------------------------------------------------------------===
# Python standard library, abstract base classes
from abc import ABCMeta
# The fractions package in the Python standard library p... |
"""
this is a place where we put datastructures used by legacy apis
we hope ot remove
"""
import attr
import keyword
from _pytest.config import UsageError
@attr.s
class MarkMapping(object):
"""Provides a local mapping for markers where item access
resolves to True if the marker is present. """
own_mark_... |
from __future__ import absolute_import, unicode_literals
import unittest
from build_swift.argparse import (
ArgumentParser, BoolType, Nargs, PathType, SUPPRESS, actions)
import six
from ... import utils
# -----------------------------------------------------------------------------
class TestAction(unittest.... |
# -*- coding: utf-8 -*-
"""
odict
~~~~~
This module is an example implementation of an ordered dict for the
collections module. It's not written for performance (it actually
performs pretty bad) but to show how the API works.
Questions and Answers
=====================
Why would any... |
"""State and behavior for operation termination."""
import abc
from grpc.framework.core import _constants
from grpc.framework.core import _interfaces
from grpc.framework.foundation import callable_util
from grpc.framework.interfaces.base import base
def _invocation_completion_predicate(
unused_emission_complete... |
__doc__ = """This is the event handler module for user notifications.
It can be bound to each event and can perform the action:
* sendmail: Send an email to the user/token owner
TODO:
* sendsms: We could also notify the user with an SMS.
The module is tested in tests/test_lib_events.py
"""
from privacyidea.lib.e... |
from collections import defaultdict
import mock
from searx.engines import qwant
from searx.testing import SearxTestCase
class TestQwantEngine(SearxTestCase):
def test_request(self):
query = 'test_query'
dicto = defaultdict(dict)
dicto['pageno'] = 0
dicto['language'] = 'fr_FR'
... |
# -*- coding: utf-8 -*-
# Responses from hook functions.
NF_DROP = 0
NF_ACCEPT = 1
NF_STOLEN = 2
NF_QUEUE = 3
NF_REPEAT = 4
NF_STOP = 5 # Deprecated, for userspace nf_queue compatibility.
NF_MAX_VERDICT = NF_STOP
# we overload the higher bits for encoding auxiliary data such as the queue
# number or errno values. ... |
"""Test that problems and problem submission works well."""
import time
from selenium.common.exceptions import StaleElementReferenceException
from workbench import scenarios
from workbench.test.selenium_test import SeleniumTest
class ProblemInteractionTest(SeleniumTest):
"""
A browser-based test of answerin... |
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
import function
import time
from common import EmailNotify
from common import GetConfigList
import threading
lst = GetConfigList('stock_number')
def get_ene(stock_number,mutex):
while True:
realtimePrice = function.GetRealTimePrice(stock_number)
... |
#!/usr/bin/python
from gibbs.conditions import AqueousParams
from .bounds import Bounds
from .concs import ConcentrationConverter
from util.SBtab import SBtabTools
import os
from equilibrator.settings import BASE_DIR
COFACTORS_FNAME = os.path.join(BASE_DIR, 'pathway/data/cofactors.csv')
def make_aq_params(form):
... |
from __future__ import (absolute_import, print_function, division)
import collections
import os
import re
from OpenSSL import SSL
from netlib import certutils, tcp
from netlib.http import authentication
from netlib.tcp import Address, sslversion_choices
from .. import utils, platform
CONF_BASENAME = "mitmproxy"
CA_D... |
from oauth2_provider.decorators import protected_resource
from django.views.decorators.http import require_POST
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from .create import create
from .update import update
from .delete import delete... |
# -*- coding: iso-8859-1 -*-
"""Configuration file management module.
Halberd uses configuration files to store relevant information needed for
certain protocols (SSL) or modes of operation (proxy, distributed
client/server, etc.).
This module takes care of reading and writing configuration files.
@var default_prox... |
import logging
from apache.aurora.client.cli.client import AuroraLogConfigurationPlugin
def test_log_plugin_enabled():
plugin = AuroraLogConfigurationPlugin()
plugin.before_dispatch(["aurora", "version", "--verbose"])
assert logging.getLogger().getEffectiveLevel() == logging.DEBUG
def test_log_plugin_disab... |
from __future__ import print_function
import sys
import json
import os
if __name__ == '__main__':
print("Input:")
print(sys.argv)
tmp_dir = sys.argv[1]
in_dir = sys.argv[2]
out_dir = sys.argv[3]
with open(os.path.join(in_dir, 'input.json'), 'r') as f:
params = json.load(f)
output... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import logging
import time
import re
import ssl
import requests
from distutils.version import StrictVersion
from threading import Thread, Event
from queue import Queue
from flask_cors import CORS
from flask_cache_bust import init_cache_busting
from ... |
import urllib.request
import json
url = "http://127.0.0.1:8081"
# check for free seats on the train "express_2000"
train_data = urllib.request.urlopen(url + "/data_for_train/express_2000")
print("original reservation situation: ", train_data.read().decode("utf-8"))
# book a seat
train_id = "express_2000"
seats = ["1... |
"""Gets all events from GCal."""
# General libraries
import json
import os
# Third-party libraries
# App specific libraries
from google_api_utils import InitService
from library import CALENDAR_ID
from models import Event
os.environ['HTTP_HOST'] = 'persistent-cal.appspot.com'
def main():
"""Main function. Ret... |
'''
Button
======
.. image:: images/button.jpg
:align: right
The :class:`Button` is a :class:`~kivy.uix.label.Label` with associated actions
that are triggered when the button is pressed (or released after a
click/touch). To configure the button, the same properties are used
as for the Label class::
button =... |
"""Unit test for Bigquery verifier"""
from __future__ import absolute_import
import logging
import unittest
import mock
from hamcrest import assert_that as hc_assert_that
from apache_beam.io.gcp.tests import bigquery_matcher as bq_verifier
from apache_beam.testing.test_utils import patch_retry
# Protect against en... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
import subprocess
def gather_lldp():
cmd = ['lldpctl', '-f', 'keyvalue']
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
(output, err) = proc.communicate()
... |
# -*- encoding: utf-8 -*-
from django.core.mail import EmailMultiAlternatives
from django.core.mail import get_connection
from django.db import models
from django.template import loader, Context
from django.utils.translation import ugettext as _
from emailtemplates.conf import settings
class EmailTemplat... |
import re
from livestreamer.compat import urlparse
from livestreamer.plugin import Plugin
from livestreamer.plugin.api import http, validate
from livestreamer.stream import HLSStream, HTTPStream
_url_re = re.compile("http(s)?://(\w+\.)?seemeplay.ru/")
_player_re = re.compile("""
SMP.(channel|video).player.init\({... |
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class Scope(object):
USERINFO_PROFILE = '/authenticate'
class OrcidAccount(ProviderAccount):
def get_profile_url(self):
return extract_from_dict(self.account.ex... |
from flask.ext import restful
from flask.ext.restful import marshal_with, reqparse
from route.base import api
from sqlalchemy import func, or_
from geoalchemy2.elements import WKTElement
from model.base import db
from model.station import Station
from model.poi import Poi, poi_marshaller
import json
import requests
... |
import os
from webassets.filter import Filter
from webassets.utils import common_path_prefix
__all__ = ('JST',)
class JSTemplateFilter(Filter):
"""Common base class for the JST and Handlebars filters, and
possibly other Javascript templating systems in the future.
"""
def concat(self, out, hunks, *... |
from django.conf.urls import url, include
from django.conf import settings
from docfish.apps.snacks import views as snack_views
urlpatterns = [
url(r'^snacks/$', snack_views.snacks_home, name="snacks"),
url(r'^snacks/my$', snack_views.view_snacks, name="my_snacks"),
url(r'^snacks/(?P<sid>\d+)/details$', s... |
# coding: utf-8
"""
ASN.1 type classes for certificate signing requests (CSR). Exports the
following items:
- CertificatationRequest()
Other type classes are defined that help compose the types listed above.
"""
from __future__ import unicode_literals, division, absolute_import, print_function
from .algos import ... |
import pytest
from eth_abi.decoding import (
ContextFramesBytesIO,
)
@pytest.fixture
def byte_string():
return bytes(range(100))
@pytest.fixture
def byte_stream(byte_string):
return ContextFramesBytesIO(byte_string)
def test_read_seek_tell_work_as_normal(byte_string, byte_stream):
assert byte_str... |
import os
import sys
import argparse
from xml.etree import ElementTree
from xml.dom import minidom
from s3_lifecycle_editor import S3LifecycleEditor
def get_bucket_from_file(filename):
bucket = os.path.basename(filename)
assert bucket.endswith('.xml'), "Expected a filename ending with .xml"
return bucket[... |
"""
Keeps track of scopes markings inside this node.
"""
# OAT - Obfuscation and Analysis Tool
# Copyright (C) 2011 Andy Gurden
#
# This file is part of OAT.
#
# OAT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the ... |
import logging
from django.core.urlresolvers import reverse
from django.utils.http import urlencode
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import tables
from openstack_dashboard import api
from openstack_dashboard.dashboards.admin.users.tables import User... |
"""Database setup and migration commands."""
from oslo.config import cfg
from stevedore import driver
_IMPL = None
def get_backend():
global _IMPL
if not _IMPL:
cfg.CONF.import_opt('backend', 'oslo.db.options', group='database')
_IMPL = driver.DriverManager("ironic.database.migration_backend... |
import random
from os import environ
try:
import asyncio
except ImportError:
# Trollius >= 0.3 was renamed
import trollius as asyncio
from autobahn.wamp.types import SubscribeOptions
from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner
class Component(ApplicationSession):
"""
... |
from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_3
from ryu.lib.packet import packet
from ryu.lib.packet import ethernet
class SimpleSwitch13(app_... |
"""
BitBake SFTP Fetch implementation
Class for fetching files via SFTP. It tries to adhere to the (now
expired) IETF Internet Draft for "Uniform Resource Identifier (URI)
Scheme for Secure File Transfer Protocol (SFTP) and Secure Shell
(SSH)" (SECSH URI).
It uses SFTP (as to adhere to the SECSH URI specification). I... |
import functools
import logbook
import math
import numpy as np
import numpy.linalg as la
from six import iteritems
from zipline.finance import trading
import pandas as pd
from . import risk
from . risk import (
alpha,
check_entry,
downside_risk,
information_ratio,
sharpe_ratio,
sortino_rati... |
"""Dst module
A module for reading, writing, and storing dst Data
Classes
-------------------------
dstRec a dst data record
-------------------------
Functions
---------------------------------------
readDst read dst data from database
readDstWeb read dst data from website
mapDstMongo store dst data to databa... |
from oslo_upgradecheck import upgradecheck
from neutron._i18n import _
from neutron.cmd.upgrade_checks import base
class CoreChecks(base.BaseChecks):
def get_checks(self):
return (
(_("Check nothing"), self.noop_check)
)
@staticmethod
def noop_check(checker):
# NOTE(... |
from __future__ import division
import numpy as np
import gaze_geometry
import image_utils
import anatomical_constants
from PIL import ImageGrab
from visual import *
import marker_manager
# VPYTHON : GAZETRACKER
# x, y, z : x, -y, z
cvt_pt = lambda x, y, z : (x, -y, z)
cvt_pts = lambda pts : [(x, -y, z) for (x, y, ... |
import json
class TweepyException(Exception):
"""Base exception for Tweepy"""
pass
class HTTPException(TweepyException):
"""Exception raised when an HTTP request fails"""
def __init__(self, response):
self.response = response
self.api_errors = []
self.api_codes = []
... |
class ModuleDocFragment(object):
DOCUMENTATION = """
options:
- See respective platform section for more details
requirements:
- See respective platform section for more details
notes:
- Ansible modules are available for the following NetApp Storage Platforms: E-Series, ONTAP, SolidFire
"""
# Documentat... |
# stdlib
import logging
import os
import sys
import unittest
# project
import modules
log = logging.getLogger('conmon.test')
TARGET_MODULE = 'tests.core.fixtures.target_module'
default_target = 'DEFAULT'
specified_target = 'SPECIFIED'
has_been_mutated = False
class TestModuleLoad(unittest.TestCase):
def setUp... |
from flask import Flask
from flask_restful import reqparse, abort, Api, Resource
app = Flask(__name__)
api = Api(app)
TODOS = {
'todo1': {'task': 'build an API'},
'todo2': {'task': '?????'},
'todo3': {'task': 'profit!'},
}
def abort_if_todo_doesnt_exist(todo_id):
if todo_id not in TODOS:
abor... |
from __future__ import division, print_function, absolute_import
import numpy as np
from numpy.testing import (assert_equal, assert_array_equal,
assert_array_almost_equal, assert_approx_equal, assert_allclose)
from pytest import raises as assert_raises
from scipy.special import xlogy
from scipy.stats.conting... |
from .fontstyle import FontStyle
#-------------------------------------------------------------------------
#
# set up logging
#
#-------------------------------------------------------------------------
import logging
log = logging.getLogger(".paragraphstyle")
#-------------------------------------------------------... |
"""
Tests for SplitTestTransformer.
"""
import ddt
import openedx.core.djangoapps.user_api.course_tag.api as course_tag_api
from openedx.core.djangoapps.user_api.partition_schemes import RandomUserPartitionScheme
from student.tests.factories import CourseEnrollmentFactory
from xmodule.partitions.partitions import Grou... |
import pandas as pd
from bokeh.sampledata.glucose import data
from bokeh.plotting import *
output_file("glucose.html", title="glucose.py example")
hold()
dates = data.index.to_series()
figure(x_axis_type="datetime", tools="pan,wheel_zoom,box_zoom,reset,previewsave")
line(dates, data['glucose'], color='red', legen... |
import sys
import numpy as np
import struct as strct
import string
class HydmodBinaryStatements:
'Class of methods for reading MODFLOW binary files'
# --byte definition
integer = np.int32
real = np.float32
double = np.float64
character = np.uint8
integerbyte = 4
realbyte ... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from kolibri.core.auth.test.helpers import create_dummy_facility_data
from kolibri.core.auth.test.helpers import... |
from __future__ import absolute_import
from oscar.core.loading import get_model
from ecommerce.extensions.fulfillment.status import ORDER
Option = get_model('catalogue', 'Option')
Refund = get_model('refund', 'Refund')
RefundLine = get_model('refund', 'RefundLine')
def find_orders_associated_with_course(user, cour... |
import urllib
from swift.common import bufferedhttp
from swift.common import exceptions
from swift.common import http
class Sender(object):
"""
Sends REPLICATION requests to the object server.
These requests are eventually handled by
:py:mod:`.ssync_receiver` and full documentation about the
proc... |
"""Test suite for pymongo, bson, and gridfs.
"""
import os
import socket
import sys
from pymongo.common import partition_node
if sys.version_info[:2] == (2, 6):
import unittest2 as unittest
from unittest2 import SkipTest
else:
import unittest
from unittest import SkipTest
import warnings
from functoo... |
# -*- coding: utf-8 -*-
"""
InaSAFE Disaster risk assessment tool developed by AusAid -
**metadata module.**
Contact : <EMAIL>
.. note:: 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; eit... |
import os,sys,string
import FCFileTools
import MakeAppTools
import re
FilFilter = ["^.*\\.o$",
"^.*\\Makefile$",
"^.*\\.la$",
"^.*\\.lo$",
"^.*\\.positions$",
"^.*\\.aux$",
"^.*\\.bsc$",
"^.*\\.exp$",
"^.*\\.ilg$",
... |
"""Tests for redis locks"""
from datetime import timedelta
from itertools import takewhile
import time
import uuid
import pytest
from micromasters.locks import (
Lock,
release_lock,
)
from micromasters.utils import now_in_utc
def _make_lock(seconds):
"""Helper to make a lock"""
lock_name = uuid.uuid... |
import json
import sys, traceback
from django.conf import settings
from django.db.models.base import ObjectDoesNotExist
from django.http import HttpResponse, Http404
from django.utils.translation import ugettext as _
from raven.contrib.django.models import client
class AjaxErrorMiddleware(object):
'''Return AJA... |
""" This module implements the feature in the hex editor which prints
out the structs in the current frame.
"""
import Hexeditor
import pyflag.Registry as Registry
import pyflag.format as format
urwid = Hexeditor.urwid
import pyflag.FlagFramework as FlagFramework
## The default DataType action is to print itself as a... |
import logging
import os
from sqlalchemy import create_engine, asc, desc, func, __version__, select
from sqlalchemy.sql import text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import create_session
from pycsw import util
LOGGER = logging.getLogger(__name__)
class Repository(object):
... |
from django.utils.translation import ugettext_lazy as _
class HealthCheckStatusType(object):
unavailable = 0
working = 1
unexpected_result = 2
HEALTH_CHECK_STATUS_TYPE_TRANSLATOR = {
0: _("unavailable"),
1: _("working"),
2: _("unexpected result"),
}
class HealthCheckException(Exception):
... |
"""
# Majic
# Copyright (C) 2014 CEH
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This pr... |
from pymongo import MongoClient
import pymongo
import os
import json
from emission.net.int_service.giles import archiver
_current_db = MongoClient('localhost').Stage_database
def _get_current_db():
return _current_db
def get_mode_db():
# #current_db = MongoClient().Stage_database
Modes= _get... |
# -*- coding: utf-8 -*-
import datetime
import json
import time
import dateutil
import pytest
import elastalert.create_index
import elastalert.elastalert
from elastalert import ElasticSearchClient
from elastalert.util import build_es_conn_config
from tests.conftest import ea # noqa: F401
test_index = 'test_index'
... |
from django.views.generic import ListView, View
from django.views.generic.detail import SingleObjectMixin
from django.views.generic.edit import CreateView, UpdateView, DeleteView, FormView
from tcs.shortcuts import PermissionDenied, login_required, get_object_or_404
from tcs.models import Problem ,Solution
from tcs.for... |
# vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""
Implementation of `igraph.Graph.Formula()`
You should use this module directly only if you have a very strong reason
to do so. In almost all cases, you are better off with calling
`igraph.Graph.Formula()`.
"""
from cStringIO import StringIO
from igraph.datatypes im... |
import collections
import mock
from neutron.agent import l2population_rpc
from neutron.plugins.ml2.drivers.l2pop import rpc as l2pop_rpc
from neutron.plugins.openvswitch.agent import ovs_neutron_agent
from neutron.tests import base
class FakeNeutronAgent(l2population_rpc.L2populationRpcCallBackTunnelMixin):
def... |
#!/usr/bin/env python
import sys
def name(i):
if i < 0x21:
return \
['NUL ', 'SOH ', 'STX ', 'ETX ', 'EOT ', 'ENQ ', 'ACK ', 'BEL ',
'BS ', 'HT ', 'LF ', 'VT ', 'FF ', 'CR ', 'SO ', 'SI ',
'DLE ', 'DC1 ', 'DC2 ', 'DC3 ', 'DC4 ', 'NAK ', 'SYN ', 'ETB ',
... |
#@PydevCodeAnalysisIgnore
# encoding: utf-8
from south.db import db
from south.v2 import SchemaMigration
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Decision'
db.create_table('publicweb_decision', (
('id', self.gf('django.db.models.fields.AutoFie... |
import os, sys, time
# usage: parse_log.py log-file [socket-index to focus on]
socket_filter = None
if len(sys.argv) >= 3:
socket_filter = sys.argv[2].strip()
if socket_filter == None:
print "scanning for socket with the most packets"
file = open(sys.argv[1], 'rb')
sockets = {}
for l in file:
if not 'our_d... |
import os
import operator
import functools
import warnings
import six
from six.moves import reduce
from . import xcbq
from .log_utils import logger
class QtileError(Exception):
pass
def lget(o, v):
try:
return o[v]
except (IndexError, TypeError):
return None
def translate_masks(modif... |
from django.contrib import admin
from django.conf import settings
from django.utils.module_loading import import_string
from django.utils.translation import ugettext_lazy as _
from polymorphic.admin import (
PolymorphicParentModelAdmin, PolymorphicChildModelAdmin
)
from cms.common import mixins
from .models impor... |
import chainer
import numpy
import pytest
import chainerx
from chainerx_tests import array_utils
def _create_batch_norm_ndarray_args(
xp, device, x_shape, gamma_shape, beta_shape, mean_shape, var_shape,
float_dtype):
x = array_utils.create_dummy_ndarray(xp, x_shape, float_dtype)
# Non-conti... |
import spur
class Local():
"""
Localhost shell class
"""
def run(self, cmd):
"""
:param cmd: Shell Command. list
Usage:
from psystem import shell
local_shell = shell.Local()
local_shell.run(['echo', '-n', 'hello'])
... |
import contextlib
import json
import uuid
import mock
import netaddr
from oslo.config import cfg
import redis
from quark.cache import redis_base
from quark import exceptions as q_exc
from quark.tests import test_base
CONF = cfg.CONF
class TestClientBase(test_base.TestBase):
def setUp(self):
super(Test... |
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from xmitgcm import open_mdsdataset
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
dir0 = '/homedata/bderembl/runmit/test_southatlgyre'
ds0 = open_mdsdataset(dir0,iters='all',prefix=['cheapAML'])
# Average of At... |
import io
import os
import tomlkit
# Fetch general information about the project from pyproject.toml.
toml_path = os.path.join(os.path.dirname(__file__), "..", "pyproject.toml")
with io.open(toml_path, "r") as toml_file:
toml_config = tomlkit.loads(toml_file.read())
# Redistribute pyproject.toml config to Sphinx... |
cwTooltips = {'Editor': 'Please enter the editor username as shown on the\n' + \
'.org, YouTube, etc. If this is a collaboration between\n' + \
'two editors, please enter both editors\' usernames,\n' + \
'and if this is an MEP with three or more... |
#!/usr/bin/python3
# coding: utf-8
#pré-processamento
lines = [line.rstrip().split(';')[0:3] for line in open('proximity.csv','r')][1:]
current_list = []
final_list = []
previous = None
current = lines.pop(0)
while len(lines) > 0:
previous = current
current = lines.pop(0)
current_list.append(previous[2]... |
from django.conf import settings
from django.utils.html import escape
from django.utils.translation import ugettext as _
def get_title():
return _(settings.TITLE)
def get_description():
return _(settings.DESCRIPTION)
def weblanguage(language):
"""Reformats the language code from locale style (pt_BR) to w... |
import platform
def get_os_metadata():
"""Retrieves the OS name and version for the host system.
Retrieves the OS name and OS version string for the host system. The OS name
can be "Windows", "OSX", the name of the Linux distribution, or, if the OS
is none of those, the name will be the OS platform n... |
from __future__ import absolute_import, division, print_function
INCLUDES = """
#include <openssl/dh.h>
"""
TYPES = """
typedef struct dh_st {
/* Prime number (shared) */
BIGNUM *p;
/* Generator of Z_p (shared) */
BIGNUM *g;
/* Private DH value x */
BIGNUM *priv_key;
/* Public DH value g^x... |
import traceback
from . import pylexotron, util
Hint = pylexotron.Hint
class CqlParsingRuleSet(pylexotron.ParsingRuleSet):
available_compression_classes = (
'DeflateCompressor',
'SnappyCompressor',
'LZ4Compressor',
)
available_compaction_classes = (
'LeveledCompactionStr... |
"""Tests for `tf.data.experimental.dense_to_ragged_batch`."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import numpy as np
from tensorflow.python.data.experimental.ops import batching
from tensorflow.python.data.... |
from __future__ import absolute_import, division, unicode_literals
from jx_base.expressions._utils import builtin_ops
from jx_base.expressions.and_op import AndOp
from jx_base.expressions.base_binary_op import BaseBinaryOp
from jx_base.expressions.eq_op import EqOp
from jx_base.expressions.literal import Literal, ZERO... |
import asyn
from micropython import kbd_intr
import uasyncio as asyncio
import utime
from machine import RTC, DEEPSLEEP, deepsleep, Pin, unique_id, UART
from umqtt.simple import MQTTClient
###### Configuration settings ######
PROJECT = "esp-botvac"
MQTT_SERVER = "1.1.1.1"
DO_DEEP_SLEEP = True
# Time (in seconds) to s... |
import operator
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.html import escape, format_html
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
@stringfilter
def trim(value, num):
return value[:num]
@register.fi... |
"""Execution rules for Aggregatons - mostly TODO
- ops.Aggregation
- ops.Any
- ops.NotAny
- ops.All
- ops.NotAll
"""
import functools
import operator
from typing import Optional
import dask.dataframe as dd
import dask.dataframe.groupby as ddgb
import ibis.expr.operations as ops
from ibis.backends.pandas.execution.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.