content stringlengths 27 928k | path stringlengths 4 230 | size int64 27 928k | nl_text stringlengths 21 396k | nl_size int64 21 396k | nl_language stringlengths 2 3 | nl_language_score float64 0.04 1 |
|---|---|---|---|---|---|---|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from targets.firefox.fx_testcase import *
class Test(FirefoxTest):
@pytest.mark.details(
description='Bro... | tests/firefox/toolbars_window_controls/browser_controls_upper_corner.py | 3,530 | This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. | 192 | en | 0.934305 |
# Copyright (c) 2020, The InferLO authors. All rights reserved.
# Licensed under the Apache License, Version 2.0 - see LICENSE file.
from __future__ import annotations
import random
import time
from dataclasses import dataclass
from typing import TYPE_CHECKING, List, Callable, Dict
import numpy as np
from inferlo.ba... | inferlo/generic/libdai_bp.py | 20,194 | Belief propagation algorithm, equivalent to dai::BP.
This class is ported from libDAI's dai::BP class. It runs belief
propagation algorithm for graphical model with discrete variables with
arbitrary factor graph.
At the moment MAXPROD algorithm (for finding MAP state) is not supported.
Use BP.infer() to perform infe... | 3,966 | en | 0.82621 |
import os
import shutil
def setup_vscode():
def _get_vscode_cmd(port):
executable = "code-server"
if not shutil.which(executable):
raise FileNotFoundError("Can not find code-server in PATH")
# Start vscode in CODE_WORKINGDIR env variable if set
# If not, start ... | jupyter_vscode_proxy/__init__.py | 1,376 | Start vscode in CODE_WORKINGDIR env variable if set If not, start in 'current directory', which is $REPO_DIR in mybinder but /home/jovyan (or equivalent) in JupyterHubs | 168 | en | 0.774063 |
import time
import logging
import os
import openpathsampling as paths
from .path_simulator import PathSimulator, MCStep
from ..ops_logging import initialization_logging
logger = logging.getLogger(__name__)
init_log = logging.getLogger('openpathsampling.initialization')
class PathSampling(PathSimulator):
"""
... | openpathsampling/pathsimulators/path_sampling.py | 11,053 | General path sampling code.
Takes a single move_scheme and generates samples from that, keeping one
per replica after each move.
Parameters
----------
storage : :class:`openpathsampling.storage.Storage`
the storage where all results should be stored in
move_scheme : :class:`openpathsampling.MoveScheme`
the mov... | 3,055 | en | 0.772745 |
"""
WSGI config for rush00 project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTIN... | rush00/wsgi.py | 389 | WSGI config for rush00 project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ | 212 | en | 0.766387 |
"""
Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in... | agent/webdriver/recorder.py | 2,774 | Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wri... | 634 | en | 0.865276 |
import urllib.request
from urllib.parse import urlencode
import json
import pprint
import socket
import struct
#from src import etri2conll
def getETRI_rest(text):
url = "http://143.248.135.20:31235/etri_parser"
contents = {}
contents['text'] = text
contents = json.dumps(contents).encode('ut... | etri.py | 4,415 | from src import etri2conllclientSocket.sendall(text.encode('unicode-escape'))clientSocket.sendall(text.encode('utf-8'))def test():conll = getETRI_CoNLL2006(text)conll = getETRI_CoNLL2009(text)pprint.pprint(conll)test() | 218 | en | 0.107769 |
# (C) Datadog, Inc. 2018-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
__version__ = '4.7.3'
| gitlab/datadog_checks/gitlab/__about__.py | 138 | (C) Datadog, Inc. 2018-present All rights reserved Licensed under a 3-clause BSD style license (see LICENSE) | 108 | en | 0.821201 |
from django.contrib.auth import models as auth_models
from django.core.mail import send_mail
from django.db import models
from django.urls import reverse
from django.utils import timezone
from django.utils.crypto import get_random_string
from django.utils.translation import gettext_lazy as _
from oscar.core.compat imp... | src/oscar/apps/customer/abstract_models.py | 8,184 | An alert for when a product comes back in stock
An abstract base user suitable for use in Oscar projects.
This is basically a copy of the core AbstractUser model but without a
username field
Transfer any active alerts linked to a user's email address to the
newly registered user.
Creates and saves a User with the give... | 1,393 | en | 0.88757 |
"""A training script of TD3 on OpenAI Gym Mujoco environments.
This script follows the settings of http://arxiv.org/abs/1802.09477 as much
as possible.
"""
import argparse
import logging
import sys
import gym
import gym.wrappers
import numpy as np
import torch
from torch import nn
import pfrl
from pfrl import exper... | examples/mujoco/reproduction/td3/train_td3.py | 6,901 | Select random actions until model is updated one or more times.
A training script of TD3 on OpenAI Gym Mujoco environments.
This script follows the settings of http://arxiv.org/abs/1802.09477 as much
as possible.
Set a random seed used in PFRL Unwrap TimeLimit wrapper Use different random seeds for train and test en... | 478 | en | 0.806241 |
from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm
from artapp.models import Artist, Art
from django.template.defaultfilters import slugify
class RegistrationForm(ModelForm):
username = forms.CharField(label=(u'User Name'))
email = forms.EmailField(label=(u'Em... | artapp/forms.py | 2,407 | return self.cleaned_datanext_url = forms.CharField(label=(u'next url'), widget=forms.HiddenInput()) hiddenexclude = ('slug','created_at', 'likes',) | 147 | en | 0.205082 |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
OpenAPI spec version: release-1.16
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import... | kubernetes/test/test_discovery_v1alpha1_api.py | 2,027 | DiscoveryV1alpha1Api unit test stubs
Test case for create_namespaced_endpoint_slice
Test case for delete_collection_namespaced_endpoint_slice
Test case for delete_namespaced_endpoint_slice
Test case for get_api_resources
Test case for list_endpoint_slice_for_all_namespaces
... | 799 | en | 0.460375 |
# -*- coding:utf-8 -*-
"""
Sections organize movement between pages in an experiment.
.. moduleauthor:: Johannes Brachem <jbrachem@posteo.de>, Paul Wiemann <paulwiemann@gmail.com>
"""
import time
import typing as t
from ._core import ExpMember
from ._helper import inherit_kwargs
from .page import _PageCore, _DefaultF... | src/alfred3/section.py | 33,080 | A section that allows only a single step forward; no jumping and no
backwards steps.
Args:
{kwargs}
Examples:
Using an ForwardOnlySection and filling it with a page in instance
style::
import alfred3 as al
exp = al.Experiment()
exp += al.ForwardOnlySection(name="main")
e... | 14,981 | en | 0.845974 |
import bottle, logging, argparse, json, sys
from beaker.middleware import SessionMiddleware
from . import database, processing, routing
logger = logging.getLogger("snuggle.api.server")
def load_config(filename):
try:
f = open(filename)
return json.load(f)
except Exception as e:
raise Exception("Could not loa... | snuggle/api/server.py | 2,027 | configure dbconfigure processorsconstruct app30 minutes | 55 | en | 0.434382 |
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from registration.backends.simple.views import RegistrationView... | dhhd/dhhd/views.py | 2,295 | Query the database for a list of all the plans currently stored. Order the plans by the number of likes in descending order. Retrieve the top 5 only - or all if less than 5. Place the list in the context_dict dictionary which will be passed to the template engine.popular_plan_list = Plan.objects.order_by('-views')[:3] ... | 498 | en | 0.809724 |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | tests/st/control/inner/test_111_if_after_if_in_while.py | 3,096 | Copyright 2020 Huawei Technologies Co., Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, softw... | 688 | en | 0.805959 |
import re
from datetime import date, datetime, time, timedelta, timezone
ISO_8601_DATETIME_REGEX = re.compile(
r"^(\d{4})-?([0-1]\d)-?([0-3]\d)[t\s]?([0-2]\d:?[0-5]\d:?[0-5]\d|23:59:60|235960)(\.\d+)?(z|[+-]\d{2}:\d{2})?$",
re.I,
)
ISO_8601_DATE_REGEX = re.compile(r"^(\d{4})-?([0-1]\d)-?([0-3]\d)$", re.I)
ISO_... | chili/iso_datetime.py | 5,740 | Parses duration string according to ISO 8601 and returns timedelta representation (it excludes year and month)
http://www.datypic.com/sc/xsd/t-xsd_dayTimeDuration.html
:param str value:
:return dict:
type: ignore type: ignore type: ignore type: ignore type: ignore type: ignore type: ignore type: ignore type: ignore t... | 383 | en | 0.352859 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('report', '0003_auto_20151015_1921'),
]
operations = [
migrations.AlterField(
mo... | report/migrations/0004_auto_20151031_0721.py | 1,318 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
# 导入需要的包
import matplotlib.pyplot as plt
import numpy as np
import sklearn.datasets
import sklearn.linear_model
import matplotlib
# Display plots inline and change default figure size
matplotlib.rcParams['figure.figsize'] = (10.0, 8.0) # 生成数据集并绘制出来
np.random.seed(0)
X, y = sklearn.datasets.make_moons(200, noise=0.20)... | artificial_intelligence/experiment_7.py | 5,000 | 导入需要的包 Display plots inline and change default figure size 生成数据集并绘制出来 训练逻辑回归训练器 Helper function to plot a decision boundary. If you don't fully understand this function don't worry, it just generates the contour plot below. Set min and max values and give it some padding Generate a grid of points with distance h betwee... | 1,626 | en | 0.73604 |
# Distributed DL Client runs on the master node
# @author: Trung Phan
# @created date: 2021-06-28
# @last modified date:
# @note:
from ddlf.cluster import *
async def main():
cluster = Cluster()
await cluster.connect()
await cluster.show_data()
await cluster.clean()
await cluster.show_data()
aw... | examples/task-clean.py | 362 | Distributed DL Client runs on the master node @author: Trung Phan @created date: 2021-06-28 @last modified date: @note: | 119 | en | 0.727345 |
from django import forms
from django.db.models.loading import get_model
from django.utils.translation import ugettext_lazy as _
from oscar.forms import widgets
Voucher = get_model('voucher', 'Voucher')
Benefit = get_model('offer', 'Benefit')
Range = get_model('offer', 'Range')
class VoucherForm(forms.Form):
"""... | oscar/apps/dashboard/vouchers/forms.py | 3,089 | A specialised form for creating a voucher and offer
model. | 58 | en | 0.878028 |
import collections
import itertools
import string
import unittest
# noinspection PyUnusedLocal
# skus = unicode string
def getItemPrices():
itemPrices = {}
itemPrices['A'] = {1:50, 3:130, 5:200}
itemPrices['B'] = {1:30, 2:45}
itemPrices['C'] = {1:20}
itemPrices['D'] = {1:15}
itemPrices['E'] = {... | lib/solutions/CHK/checkout_solution.py | 8,606 | noinspection PyUnusedLocal skus = unicode string FIXME: Using 0 to denote saving from using group | 97 | en | 0.302203 |
import pdb
if __name__ == "__main__":
with open("21input.txt") as f:
data = f.read().split("\n")
data.pop(-1)
print(data)
all_food = []
for food in data:
allergens = False
ings = []
alle = []
for ingredient in food.split(" "):
if "(contain... | 2020/21day.py | 2,092 | for alg, val in alg_dico.items(): if (len(val) == 1): for valx in alg_dico.values(): if val in valx and valx != val: valx.remove(val) | 173 | en | 0.215319 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.db.models import Q
def update_upload_to_ia_field(apps, schema_editor):
Link = apps.get_model('perma', 'Link')
Link.objects.filter(uploaded_to_internet_archive=True).update(internet_archive_upl... | perma_web/perma/migrations/0006_add_internetarchive_status.py | 2,987 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
import os
import numpy
from numpy import *
import math
from scipy import integrate, linalg
from matplotlib import pyplot
from pylab import *
class Freestream:
"""
Freestream conditions.
"""
def __init__(self, u_inf=1.0, alpha=0.0):
"""
Sets the freestream speed and angle (in degrees).
... | steapy/freestream.py | 651 | Freestream conditions.
Sets the freestream speed and angle (in degrees).
Parameters
----------
u_inf: float, optional
Freestream speed;
default: 1.0.
alpha: float, optional
Angle of attack in degrees;
default 0.0.
degrees to radians | 251 | en | 0.487281 |
#!/usr/bin/python
"""
IO Module
"""
import sys
import logging
from time import time as _time
import threading
import cPickle
from bisect import bisect_left
from collections import deque
from bacpypes.debugging import bacpypes_debugging, DebugContents, ModuleLogger
from bacpypes.core import deferred
from bacpypes... | sandbox/io.py | 39,489 | Initialize a chained control block.
Initialize a group.
Initialize a controller.
Initialize a queue controller.
Create an IO client. It implements request_io like a controller, but
passes requests on to a local controller if it happens to be in the
same process, or the IOProxyServer instance to forward on for process... | 9,811 | en | 0.914152 |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from cli.output import CLIOutput
from cli.user_input import CLIUserInput
class CLIDay():
# constants
INTRO_TE... | cli/day.py | 11,932 | Answer cycle
Display 'definitions' task
Display intro text
Display 'matching' task
Display new words section
Display other new words section
Display 'sample sentences' task
Display title
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with ... | 970 | en | 0.555469 |
from __future__ import absolute_import
from desicos.abaqus.abaqus_functions import create_sketch_plane
from desicos.abaqus.utils import cyl2rec
class Imperfection(object):
"""Base class for all imperfections
This class should be sub-classed when a new imperfection is created.
"""
def __init__(self):... | desicos/abaqus/imperfections/imperfection.py | 874 | Base class for all imperfections
This class should be sub-classed when a new imperfection is created.
NOTE zs, rs and pts are the same | 136 | en | 0.907883 |
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
#
"""Code to interact with the primersearch program from EMBOSS."""
class InputRecord(object):
"""Represent the input file into the primersearch ... | Bio/Emboss/PrimerSearch.py | 2,311 | Represent a single amplification from a primer.
Represent the input file into the primersearch program.
This makes it easy to add primer information and write it out to the
simple primer file format.
Represent the information from a primersearch job.
amplifiers is a dictionary where the keys are the primer names and
... | 699 | en | 0.844436 |
# Copyright 2017 ProjectQ-Framework (www.projectq.ch)
#
# 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 app... | projectq/setups/decompositions/entangle.py | 1,282 | Decompose the entangle gate.
Registers a decomposition for the Entangle gate.
Applies a Hadamard gate to the first qubit and then, conditioned on this first
qubit, CNOT gates to all others.
Copyright 2017 ProjectQ-Framework (www.projectq.ch) Licensed under the Apache License, Version 2.0 (the "License"); you ... | 787 | en | 0.847002 |
import re
import json
from math import log, sqrt
from jinja2 import Markup
from sklearn import cluster
from sklearn.decomposition import PCA
from scipy import stats
from sklearn import metrics
import numpy
from db import export_sql
from werkzeug.wrappers import Response
# create higher order transformations
def x2fs... | modules/ml_kmeans.py | 7,963 | create higher order transformations fit_transform from sklearn doesn't return the loadings V. Here is a hacked version X_new = X * V / S * sqrt(n_samples) = U * sqrt(n_samples) X_new = X * V = U * S * V^T * V = U * S transposing component matrix such that PCA_1 is in row module independent user inputs start at 0 module... | 673 | en | 0.665402 |
# From http://rodp.me/2015/how-to-extract-data-from-the-web.html
import time
import sys
import uuid
import json
import markdown
from collections import Counter
from requests import get
from lxml import html
from unidecode import unidecode
import urllib
import lxml.html
from readability.readability import Document
de... | parseDoc.py | 7,033 | From http://rodp.me/2015/how-to-extract-data-from-the-web.html Possibly [1][0]print(tag)str_text = " ".join(str_text.split())print(len(newString))print('error')docStrings[i]['score']=1000*numLines / sum(1 for c in docString if c.isupper()) import urllib html = urllib.urlopen(url).read()print(getDoc('http://www.bbc.co.u... | 357 | en | 0.356288 |
# -*- coding: utf-8 -*-
"""Identity Services Engine deleteDeviceAdminLocalExceptionById data model.
Copyright (c) 2021 Cisco and/or its affiliates.
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... | tests/models/validators/v3_0_0/jsd_c7d6bb4abf53f6aa2f40b6986f58a9.py | 2,280 | deleteDeviceAdminLocalExceptionById request schema definition.
Identity Services Engine deleteDeviceAdminLocalExceptionById data model.
Copyright (c) 2021 Cisco and/or its affiliates.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the ... | 1,232 | en | 0.8704 |
# -*- coding: utf-8 -*-
u"""
Beta regression for modeling rates and proportions.
References
----------
Grün, Bettina, Ioannis Kosmidis, and Achim Zeileis. Extended beta regression
in R: Shaken, stirred, mixed, and partitioned. No. 2011-22. Working Papers in
Economics and Statistics, 2011.
Smithson, Michael, and Jay ... | statsmodels/othermod/betareg.py | 30,504 | Results class for Beta regression
This class inherits from GenericLikelihoodModelResults and not all
inherited methods might be appropriate in this case.
Derivative of the expected endog with respect to the parameters.
not verified yet
Parameters
----------
params : ndarray
parameter at which score is evaluated
... | 10,603 | en | 0.595582 |
import serial
import csv
import os
serialPort = serial.Serial("COM10", baudrate=115200)
try:
os.rename('output.csv', 'ALTERAR_MEU_NOME.csv')
except IOError:
print('')
finally:
while(True):
arduinoData = serialPort.readline().decode("ascii")
print(arduinoData)
#a... | receiveGeneratorData.py | 517 | add the data to the fileappend the data to the filewrite data with a newlineclose out the file | 94 | en | 0.71678 |
###############################################################################
#
# DONE:
#
# 1. READ the code below.
# 2. TRACE (by hand) the execution of the code,
# predicting what will get printed.
# 3. Run the code and compare your prediction to what actually was printed.
# 4. Decide whether you are... | src/m1r_functions.py | 1,354 | DONE: 1. READ the code below. 2. TRACE (by hand) the execution of the code, predicting what will get printed. 3. Run the code and compare your prediction to what actually was printed. 4. Decide whether you are 100% clear on the CONCEPTS and the NOTATIONS for: -- DEFINING a function that has PARAME... | 721 | en | 0.819633 |
"""
Django settings for YoutubeFun project.
Generated by 'django-admin startproject' using Django 1.8.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build p... | YoutubeFun/settings.py | 2,870 | Django settings for YoutubeFun project.
Generated by 'django-admin startproject' using Django 1.8.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
Build paths insi... | 895 | en | 0.653791 |
import urllib.request
import os
import random
import socket
def url_open(url):
#代理
iplist=['60.251.63.159:8080','118.180.15.152:8102','119.6.136.122:80','183.61.71.112:8888']
proxys= random.choice(iplist)
print (proxys)
proxy_support = urllib.request.ProxyHandler({'http': proxys})
opener = urllib.req... | mmParse.py | 2,181 | 代理头文件 for each in img_addrs: print(each)return img_addrs拿到所在页面查询页面中的图片保存图片 | 77 | zh | 0.623795 |
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2021, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... | bokeh/plotting/glyph_api.py | 24,868 | Examples:
.. code-block:: python
from bokeh.plotting import figure, output_file, show
plot = figure(width=300, height=300)
plot.annulus(x=[1, 2, 3], y=[1, 2, 3], color="#7FC97F",
inner_radius=0.2, outer_radius=0.5)
show(plot)
Examples:
.. code-block:: py... | 16,854 | en | 0.419175 |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown copyright. The Met Office.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are me... | improver/cli/__init__.py | 17,599 | Subclass to build Napoleon docstring from subject.
Subclass to add support for google style docstrings
Hide object under a string to pass it through Clize parser.
Dynamically discover CLIs.
Adds the updated docstring.
Decorator for creating CLI objects.
Converts comma separated string to list or returns passed obj... | 8,318 | en | 0.755215 |
"""
input: image
output: little squares with faces
"""
import face_recognition
image = face_recognition.load_image_file("people.png")
face_locations = face_recognition.face_locations(image)
print(face_locations) | Features/face_extraction.py | 213 | input: image
output: little squares with faces | 46 | en | 0.815414 |
# --------------------------------------------------------
# Deep Iterative Matching Network
# Licensed under The Apache-2.0 License [see LICENSE for details]
# Written by Yi Li
# --------------------------------------------------------
from __future__ import print_function, division
import numpy as np
class Symbol:
... | lib/utils/symbol.py | 2,420 | return a generated symbol, it also need to be assigned to self.sym
-------------------------------------------------------- Deep Iterative Matching Network Licensed under The Apache-2.0 License [see LICENSE for details] Written by Yi Li -------------------------------------------------------- infer shape | 307 | en | 0.617093 |
__author__ = 'Eugene'
class GroupHelper:
def __init__(self, app):
self.app = app
def open_groups_page(self):
wd = self.app.wd
if not (wd.current_url.endswith("/group.php") and len(wd.find_elements_by_name("new")) > 0):
wd.find_element_by_link_text("groups").click()
d... | fixture/group.py | 2,209 | init group creation submit group creation submit deletion delete init modify group fill group form submit modify group | 118 | en | 0.720088 |
import pandas as pd
import numpy as np
import os
import json
import requests
from dotenv import load_dotenv
from PIL import Image
from io import BytesIO
from IPython.core.display import display, HTML
def art_search(art):
'''
Function to retrieve the information about collections in the Art institute of Chicago... | src/aicapi_yw3760/aicapi_yw3760.py | 9,068 | Function to retrieve the information about collections in the Art institute of Chicago
Parameters:
-------------
The key word that users want to search,
for example: the artist's name, the title of the artwork.
Returns:
-------------
Status code: str
if the API request went through... | 3,220 | en | 0.740117 |
import argparse
import sys
from typing import List, Sequence
from exabel_data_sdk import ExabelClient
from exabel_data_sdk.scripts.base_script import BaseScript
class ListTimeSeries(BaseScript):
"""
Lists all time series.
"""
def __init__(self, argv: Sequence[str], description: str):
super()... | exabel_data_sdk/scripts/list_time_series.py | 1,933 | Lists all time series. | 22 | en | 0.839375 |
from typing import List, Dict
import os
import json
import argparse
import sys
from string import Template
from common import get_files, get_links_from_file, get_id_files_dict, get_id_title_dict
FORCE_GRAPH_TEMPLATE_NAME = "force_graph.html"
OUTPUT_FILE_NAME = "output.html"
def generate_force_graph(id_files_dict: ... | zettvis.py | 2,447 | Create nodes Dict(id, group) Create links Dict(source, target, value) Create Output and open it Handle the file Create title and files map | 138 | en | 0.491796 |
import os
import sys
import math
import copy
from binary_tree import BinaryTreeNode, BinaryTree, BinarySearchTree
from graph import GraphNode, Graph
# 4.6 find the next node (in-order) of a given node in a Binary Tree
# -> back to root and using in-order travelsal until meet the current node. get the next
def get_ne... | cracking-the-coding-interview/1-chapter4_1.py | 4,673 | 4.6 find the next node (in-order) of a given node in a Binary Tree -> back to root and using in-order travelsal until meet the current node. get the next Test array = [1,2,3,4,5,6] tree = BinaryTree() for v in array: tree.append(v) node = tree.root.left.right next_node = get_next_node(node) if next_node != None: pr... | 1,199 | en | 0.538308 |
# (C) Datadog, Inc. 2020-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
"""
Built-in value transformers.
"""
import datetime as dt
from typing import Any, Sequence
from datadog_checks.base import AgentCheck
from datadog_checks.base.types import ServiceCheckStatus
from datadog... | rethinkdb/datadog_checks/rethinkdb/document_db/transformers.py | 775 | Built-in value transformers.
(C) Datadog, Inc. 2020-present All rights reserved Licensed under a 3-clause BSD style license (see LICENSE) type: (Sequence) -> int type: (dt.datetime) -> float type: (Any) -> ServiceCheckStatus | 226 | en | 0.661962 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | benchmark/opperf/nd_operations/unary_operators.py | 2,635 | Runs benchmarks with the given context and precision (dtype)for all the unary
operators in MXNet.
Parameters
----------
ctx: mx.ctx
Context to run benchmarks
dtype: str, default 'float32'
Precision to use for benchmarks
warmup: int, default 25
Number of times to run for warmup
runs: int, default 100
Nu... | 2,071 | en | 0.555549 |
from utils.compute import get_landmark_3d, get_vector_intersection
from utils.visualize import HumanPoseVisualizer
from utils.OakRunner import OakRunner
from utils.pose import getKeypoints
from utils.draw import displayFPS
from pathlib import Path
import depthai as dai
import numpy as np
import cv2
fps_limit = 3
fra... | _examples/pose_estimation.py | 4,859 | draw keypoint insert empty array if the keypoint is not detected with enough confidence Determined depth to accuratly locate landmarks in space Switch to BGR (but still grayscaled) link transformed video stream to neural network entry | 234 | en | 0.847457 |
import sys
import numpy as np
import pandas as pd
from pandas.api.types import is_list_like, is_scalar
from dask.dataframe import methods
from dask.dataframe.core import DataFrame, Series, apply_concat_apply, map_partitions
from dask.dataframe.utils import has_known_categories
from dask.utils import M
##############... | dask/dataframe/reshape.py | 11,467 | Convert categorical variable into dummy/indicator variables.
Data must have category dtype to infer result's ``columns``.
Parameters
----------
data : Series, or DataFrame
For Series, the dtype must be categorical.
For DataFrame, at least one column must be categorical.
prefix : string, list of strings, or di... | 4,300 | en | 0.416317 |
import json
from sqlalchemy.orm import subqueryload
from werkzeug.exceptions import BadRequest, NotFound, PreconditionFailed
from rdr_service import clock
from rdr_service.code_constants import PPI_EXTRA_SYSTEM
from rdr_service.dao.base_dao import BaseDao, UpdatableDao
from rdr_service.lib_fhir.fhirclient_1_0_6.model... | rdr_service/dao/questionnaire_dao.py | 13,444 | Maintains version history for questionnaires.
All previous versions of a questionnaire are maintained (with the same questionnaireId value and
a new version value for each update.)
Old versions of questionnaires and their questions can still be referenced by questionnaire
responses, and are used when generating metri... | 2,120 | en | 0.86518 |
import json
import os
from urllib import request
from flask import current_app
from elastichq.model import ClusterDTO
from elastichq.vendor.elasticsearch.exceptions import NotFoundError
from .ConnectionService import ConnectionService
from ..globals import CACHE_REGION, LOG
class HQService:
def get_status(self... | elastichq/service/HQService.py | 5,017 | alter cache alter cache | 23 | de | 0.261264 |
# -*- coding: utf-8 -*-
import scrapy
import json
from locations.items import GeojsonPointItem
class NoodlesAndCompanySpider(scrapy.Spider):
name = "noodles_and_company"
item_attributes = { 'brand': "Noodles and Company" }
allowed_domains = ["locations.noodles.com"]
start_urls = (
'https://lo... | locations/spiders/noodles_and_company.py | 5,371 | -*- coding: utf-8 -*- For counties that have multiple locations, go to a county page listing, and go to each individual location from there. For counties that have only one location, go directly to that location page. | 217 | en | 0.964171 |
#!/usr/bin/env python
from __future__ import print_function
import numpy as np
import scipy as sp
from PIL import Image
import six
import networkx
for m in (np, sp, Image, six, networkx):
if not m is None:
if m is Image:
# Pillow 6.0.0 and above have removed the 'VERSION' attribute
... | tools/build_versions.py | 662 | !/usr/bin/env python Pillow 6.0.0 and above have removed the 'VERSION' attribute https://bitbucket.org/rptlab/reportlab/issues/176/incompatibility-with-pillow-600 | 162 | en | 0.669261 |
from .base import SimIRExpr
from ... import s_options as o
from ...s_action import SimActionData
class SimIRExpr_RdTmp(SimIRExpr):
def _execute(self):
if (o.SUPER_FASTPATH in self.state.options
and self._expr.tmp not in self.state.scratch.temps):
self.expr = self.state.se.BVV(0,... | simuvex/vex/expressions/rdtmp.py | 727 | finish it and save the tmp reference | 36 | en | 0.732176 |
# coding: utf-8
# # Load and preprocess 2012 data
#
# We will, over time, look over other years. Our current goal is to explore the features of a single year.
#
# ---
# In[1]:
get_ipython().magic('pylab --no-import-all inline')
import pandas as pd
# ## Load the data.
#
# ---
#
# If this fails, be sure that yo... | notebooks/as_script/1.0-adm-load-data-2012-Copy1.py | 3,705 | Turn ANES data entry into an integer.
>>> convert_to_int("1. Govt should provide many fewer services")
1
>>> convert_to_int("2")
2
Eliminate negative numbers and {95. Other}
Rearrange questions where 3 is neutral.
Reorder questions where the liberal response is low.
Convert negative values to missing.
ANES codes vari... | 1,233 | en | 0.799784 |
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | google-cloud-sdk/.install/.backup/lib/surface/compute/machine_types/__init__.py | 871 | Read Google Compute Engine virtual machine types.
Commands for reading machine types.
Copyright 2014 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.a... | 656 | en | 0.859282 |
"""
WSGI config for rara_api project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETT... | rara_api/wsgi.py | 393 | WSGI config for rara_api project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ | 214 | en | 0.781004 |
#!/usr/bin/env python
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# ---------------------------------------------... | src/azure-cli-core/setup.py | 3,095 | !/usr/bin/env python -------------------------------------------------------------------------------------------- Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. -------------------------------------------------------... | 524 | en | 0.57808 |
# -*- coding: utf-8 -*-
#
import re
from collections import OrderedDict
from copy import deepcopy
from ._http import HTTPStatus
#copied from sanic router
REGEX_TYPES = {
'string': (str, r'[^/]+'),
'int': (int, r'\d+'),
'number': (float, r'[0-9\\.]+'),
'alpha': (str, r'[A-Za-z]+'),
}
FIRST_CAP_RE = re.... | sanic_restplus/utils.py | 5,739 | Transform a CamelCase string into a low_dashed one
:param str value: a CamelCase string to transform
:return: the low_dashed string
:rtype: str
Default operation ID generator
Recursively merges two dictionaries.
Second dictionary values will take precedence over those from the first one.
Nested dictionaries are merge... | 2,151 | en | 0.702361 |
import asyncio
import io
import userbot.plugins.sql_helper.pmpermit_sql as pmpermit_sql
from telethon.tl.functions.users import GetFullUserRequest
from telethon import events, errors, functions, types
from userbot import ALIVE_NAME, LESS_SPAMMY
from userbot.utils import admin_cmd
PM_WARNS = {}
PREV_REPLY_MESSAGE = {}
... | userbot/plugins/pmpermit.py | 7,096 | userbot's should not reply to other userbot's https://core.telegram.org/bots/faqwhy-doesn-39t-my-bot-see-messages-from-other-bots don't log Saved Messages don't log bots don't log verified accounts pm permit the_message += f"Media: {message_media}" reply_to=, parse_mode="html", file=message_media, | 298 | en | 0.706465 |
''' Frsutum PointNets v1 Model.
'''
from __future__ import print_function
import sys
import os
import tensorflow as tf
import numpy as np
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(BASE_DIR)
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(ROOT_DIR, 'utils'))
import tf_util
... | models/frustum_pointnets_v1.py | 9,914 | 3D Box Estimation PointNet v1 network.
Input:
object_point_cloud: TF tensor in shape (B,M,C)
point clouds in object coordinate
one_hot_vec: TF tensor in shape (B,3)
length-3 vectors indicating predicted object type
Output:
output: TF tensor in shape (B,3+NUM_HEADING_BIN*2+NUM_SIZE_CLUSTER*4)... | 2,685 | en | 0.561355 |
import asyncio
import discord
from discord import Member, Role, TextChannel, DMChannel
from discord.ext import commands
from typing import Union
from profanity_check import predict
class ProfanityFilter:
"""
A simple filter that checks for profanity in a message and
then deletes it. Many profanity detec... | profanity-filter/profanity-filter.py | 3,360 | A simple filter that checks for profanity in a message and
then deletes it. Many profanity detection libraries use a hard-coded
list of bad words to detect and filter profanity, however this
plugin utilises a library that uses a linear support vector machine
(SVM) model trained on 200k human-labeled samples of clea... | 537 | en | 0.832786 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Author: vs@webdirect.md
Description: Very simple reminder
'''
from core.people.person import Profile, Session
from core.utils.utils import text2int
import re
from crontab import CronTab
from getpass import getuser
from core.config.settings import logger, ROBOT_DIR
c... | core/brain/remind/me/every/reaction.py | 17,836 | remind me every ... reaction
original request string
default method
Author: vs@webdirect.md
Description: Very simple reminder
!/usr/bin/env python -*- coding: utf-8 -*-get request objectrequest word sequencerequest received from (julius, jabber any other resources)exctract sender emailfind user profile by primary em... | 1,973 | en | 0.757046 |
import cv2
class SimplePreprocessor:
def __init__(self, width, height, inter=cv2.INTER_AREA):
# store the target image width, height, and interpolation
# method used when resizing
self.width = width
self.height = height
self.inter = inter
def preprocess(self, image):
... | 22. Neural Networks from Scratch/preprocessing/simplepreprocessor.py | 483 | store the target image width, height, and interpolation method used when resizing resize the image to a fixed size, ignoring the aspect ratio | 141 | en | 0.775208 |
"""Define endpoints related to user reports."""
import logging
from typing import Any, Dict
from .helpers.report import Report
_LOGGER: logging.Logger = logging.getLogger(__name__)
class UserReport(Report):
"""Define a user report object."""
async def status_by_coordinates(
self, latitude: float, l... | pyflunearyou/user.py | 954 | Define a user report object.
Define endpoints related to user reports. | 70 | en | 0.881593 |
import re
from .reports import BaseReport
from .utils import get_pacer_doc_id_from_doc1_url, reverse_goDLS_function
from ..lib.log_tools import make_default_logger
from ..lib.string_utils import force_unicode
logger = make_default_logger()
class AttachmentPage(BaseReport):
"""An object for querying and parsing ... | juriscraper/pacer/attachment_page.py | 7,089 | An object for querying and parsing the attachment page report.
Return the attachment number for an item.
In district courts, this can be easily extracted. In bankruptcy courts,
you must extract it, then subtract 1 from the value since these are
tallied and include the main document.
Get the description from the row
R... | 2,363 | en | 0.851504 |
# System
import json
# SBaaS
from .stage02_physiology_pairWiseTest_query import stage02_physiology_pairWiseTest_query
from SBaaS_base.sbaas_template_io import sbaas_template_io
# Resources
from io_utilities.base_importData import base_importData
from io_utilities.base_exportData import base_exportData
from ddt_python.d... | SBaaS_COBRA/stage02_physiology_pairWiseTest_io.py | 11,805 | Export data for a volcano plot
Visuals:
1. volcano plot
2. sample vs. sample (FC)
3. sample vs. sample (concentration)
4. sample vs. sample (p-value)
Export data for a volcano plot
Visuals:
1. volcano plot
2. sample vs. sample (FC)
3. sample vs. sample (concentration)
4. sample vs. sample (p-value)
Export data for a vo... | 893 | en | 0.563043 |
"""Euler explicit time advancement routine"""
from .projection import predictor, corrector, divergence
from .stats import stats
def advance_euler(gridc, gridx, gridy, scalars, grid_var_list, predcorr):
"""
Subroutine for the fractional step euler explicit time advancement of Navier Stokes equations
Arg... | flowx/ins/euler.py | 1,797 | Subroutine for the fractional step euler explicit time advancement of Navier Stokes equations
Arguments
---------
gridc : object
Grid object for cell centered variables
gridx : object
Grid object for x-face variables
gridy : object
Grid object for y-face variables
scalars: object
Scalars ob... | 892 | en | 0.596948 |
"""
Stacked area plot for 1D arrays inspired by Douglas Y'barbo's stackoverflow
answer:
http://stackoverflow.com/questions/2225995/how-can-i-create-stacked-line-graph-with-matplotlib
(http://stackoverflow.com/users/66549/doug)
"""
from __future__ import (absolute_import, division, print_function,
... | lib/matplotlib/stackplot.py | 4,198 | Draws a stacked area plot.
*x* : 1d array of dimension N
*y* : 2d array of dimension MxN, OR any number 1d arrays each of dimension
1xN. The data is assumed to be unstacked. Each of the following
calls is legal::
stackplot(x, y) # where y is MxN
stackplot(x, y1, y2, y3, y4) ... | 1,741 | en | 0.786461 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.FileItem import FileItem
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.AlipayOpenMiniInnerversionOnlinePublishModel import AlipayOpenMiniInnerversionOnlinePublishModel
class AlipayOpenMiniI... | alipay/aop/api/request/AlipayOpenMiniInnerversionOnlinePublishRequest.py | 4,084 | !/usr/bin/env python -*- coding: utf-8 -*- | 42 | en | 0.34282 |
# Copyright 2018-2019 The glTF-Blender-IO authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | addons/io_scene_gltf2/blender/imp/gltf2_blender_mesh.py | 5,752 | Blender Mesh.
Mesh creation.
Copyright 2018-2019 The glTF-Blender-IO authors. 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 appli... | 1,302 | en | 0.861917 |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: v1.10.6
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import u... | test/test_v1beta1_custom_resource_subresources.py | 1,086 | V1beta1CustomResourceSubresources unit test stubs
Test V1beta1CustomResourceSubresources
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: v1.10.6
Generated by: https://github.com/swagger-api/swagger-codegen.git
codi... | 525 | en | 0.40557 |
# QAP Gemini
#
# adcclib.py
# ------------------------------------------------------------------------------
import os
import sys
import signal
import time
from copy import copy
from ... | recipe_system/adcc/adcclib.py | 4,661 | Write racefile and ADCC Startup Report
QAP Gemini adcclib.py ------------------------------------------------------------------------------ ------------------------------------------... | 408 | en | 0.296922 |
from datetime import datetime
from dagster import Out, job, op
from dagster.utils import script_relative_path
from dagster_pandas import PandasColumn, create_dagster_pandas_dataframe_type
from dagster_pandas.constraints import (
ColumnConstraint,
ColumnConstraintViolationException,
ColumnDTypeInSetConstrai... | examples/docs_snippets/docs_snippets/legacy/dagster_pandas_guide/custom_column_constraint.py | 1,808 | start_custom_col end_custom_col | 31 | en | 0.395284 |
# coding: utf-8
"""
jinja2schema.config
~~~~~~~~~~~~~~~~~~~
"""
from .order_number import OrderNumber
class Config(object):
"""Configuration."""
TYPE_OF_VARIABLE_INDEXED_WITH_VARIABLE_TYPE = 'dictionary'
"""Possible values: ``"dictionary"`` or ``"list""``.
For example, in the expression ``xs[a]`` va... | jinja2schema/config.py | 4,031 | Configuration.
jinja2schema.config
~~~~~~~~~~~~~~~~~~~
coding: utf-8 | 70 | en | 0.204889 |
from typing import Any, List, Literal, TypedDict
from .FHIR_CodeableConcept import FHIR_CodeableConcept
from .FHIR_Element import FHIR_Element
from .FHIR_Reference import FHIR_Reference
from .FHIR_string import FHIR_string
# A record of a clinical assessment performed to determine what problem(s) may affect the patie... | src/fhir_types/FHIR_ClinicalImpression_Finding.py | 2,766 | A record of a clinical assessment performed to determine what problem(s) may affect the patient and before planning the treatments or management strategies that are best to manage a patient's condition. Assessments are often 1:1 with a clinical consultation / encounter, but this varies greatly depending on the clinica... | 2,097 | en | 0.920554 |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import time
'''
ComputeCost computes the cost function
'''
def computeCost(X, y, theta):
#computeCost Compute cost for linear regression
# J = computeCost(X, y, theta) computes the cost of using theta as the
# parameter for linear regressio... | Linear_Regression/ex1.py | 4,537 | computeCost Compute cost for linear regression J = computeCost(X, y, theta) computes the cost of using theta as the parameter for linear regression to fit the data points in X and y Initialize some useful values number of training examples You need to return the following variables correctly ======================... | 1,984 | en | 0.647776 |
# Mobile Verification Toolkit (MVT)
# Copyright (c) 2021-2022 The MVT Project Authors.
# Use of this software is governed by the MVT License 1.1 that can be found at
# https://license.mvt.re/1.1/
import logging
import os
import click
from rich.logging import RichHandler
from mvt.common.help import (HELP_MSG_FAST, ... | mvt/android/cli.py | 10,563 | Mobile Verification Toolkit (MVT) Copyright (c) 2021-2022 The MVT Project Authors. Use of this software is governed by the MVT License 1.1 that can be found at https://license.mvt.re/1.1/ Setup logging using Rich.============================================================================== Main======================... | 1,601 | en | 0.460461 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2006 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.com/license.html.
#
# This software consi... | files/spam-filter/tracspamfilter/filters/tests/__init__.py | 1,004 | -*- coding: utf-8 -*- Copyright (C) 2006 Edgewall Software All rights reserved. This software is licensed as described in the file COPYING, which you should have received as part of this distribution. The terms are also available at http://trac.edgewall.com/license.html. This software consists of voluntary contribution... | 467 | en | 0.966947 |
#!/usr/bin/python
import re, random, sys, difflib
random.seed(123)
for i, line in enumerate(sys.stdin.readlines()):
if i % 1000 == 0: print >>sys.stderr, i, "..."
if i>0 and re.search(r'^id\tsentiment', line): continue # combined files, ignore multiple header rows
line = re.sub(r'\n$', '', line) # stri... | augment-c_and_cpp.py | 3,270 | !/usr/bin/python combined files, ignore multiple header rows strip trailing newlines "0003b8d" <tab>1<tab> }\n \n u32 cik_gfx_get_wptr(struct radeon_device *rdev,\n \t\t struct radeon_ri corruption due to empty commits, i.e. no applicable code... keep <=25 lines cleanup non-ASCII augment x% of the time, i.e. don't go... | 1,016 | en | 0.670901 |
# Copyright 2019 The Magenta Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | magenta/models/shared/events_rnn_model.py | 23,210 | Stores a configuration for an event sequence RNN.
Only one of `steps_per_quarter` or `steps_per_second` will be applicable for
any particular model.
Attributes:
details: The GeneratorDetails message describing the config.
encoder_decoder: The EventSequenceEncoderDecoder or
ConditionalEventSequenceEncoderDec... | 10,193 | en | 0.87389 |
# Functions for visualization
import numpy as np
import networkx as nx
import multinetx as mx
from jinja2 import Environment, FileSystemLoader, Template
import json
from networkx.readwrite import json_graph
def write_mx_to_json(filename, mg, nNodes, pos, nLayers, nodes_to_remove = []):
# filename the complet... | mx_viz.py | 6,665 | Functions for visualization filename the complete name of the output file (data/slide_x.json) mx the multilayer network as a multinetx object nNodes the number of nodes in the first layer pos a dictionary of node coordinates nLayers the number of layers in the second aspect. nodes_to_remove is a list of nodes that shou... | 1,302 | en | 0.656255 |
#!/usr/bin/python
import logging
class NullHandler(logging.Handler):
def emit(self, record):
pass
log = logging.getLogger('MirrorEngine')
log.setLevel(logging.ERROR)
log.addHandler(NullHandler())
import re
import threading
import copy
from pydispatch import dispatcher
fr... | DataConnector/MirrorEngine.py | 10,422 | !/usr/bin/python store params log initialize parent class connect extra applications add stats local variables======================== public ================================================================== private ========================================= disconnect extra applications format the data to publish temp... | 634 | en | 0.568382 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2017 New Vector Ltd
#
# 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 req... | scripts/move_remote_media_to_new_store.py | 3,800 | Move the given file, and any thumbnails, to the dest repo
Args:
origin_server (str):
file_id (str):
src_paths (MediaFilePaths):
dest_paths (MediaFilePaths):
Moves a list of remote media from one media store to another.
The input should be a list of media files to be moved, one per line. Each line
shou... | 1,299 | en | 0.743094 |
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import Client
# Find your credentials at twilio.com/console
api_key_sid = 'SKXXXX'
api_key_secret = 'your_api_key_secret'
client = Client(api_key_sid, api_key_secret)
compositionHook = client.video.compositionHooks('KHXXXX').upd... | video/rest/compositionhooks/update-hook/update-hook.6.x.py | 717 | Download the Python helper library from twilio.com/docs/python/install Find your credentials at twilio.com/console | 114 | en | 0.817787 |
import sqlite3;
import csv;
import sys;
from ordery.db import get_db
from flask import current_app
def order_csv(filename):
## Connect to the database
try:
conn = sqlite3.connect(
current_app.config['DATABASE'],
detect_types=sqlite3.PARSE_DECLTYPES); # Get a connection... | ordery/order_csv.py | 3,078 | Connect to the database Get a connection object for the database Turn on foreign key constraints Get a cursor object for the connection Print error message Fatal Error Open the orders csv file Open the file – default for reading Return a dictionary reader iterator for the file Print error message Fatal Error ----------... | 909 | en | 0.622446 |
_base_ = [
'../common/mstrain-poly_3x_coco_instance.py',
'../_base_/models/mask_rcnn_r50_fpn.py'
]
model = dict(
pretrained='open-mmlab://detectron2/resnext101_32x8d',
backbone=dict(
type='ResNeXt',
depth=101,
groups=32,
base_width=8,
num_stages=4,
out_in... | configs/mask_rcnn/mask_rcnn_x101_32x8d_fpn_mstrain-poly_3x_coco.py | 2,474 | In mstrain 3x config, img_scale=[(1333, 640), (1333, 800)], multiscale_mode='range' Use RepeatDataset to speed up training | 122 | en | 0.606389 |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | vision_transformer.py | 12,421 | Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
Image to Patch Embedding
Vision Transformer
Mostly copy-paste from timm library.
https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
Copyright (c) Facebook, Inc. and its aff... | 1,291 | en | 0.813687 |
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | src/oci/devops/models/compute_instance_group_selector_collection.py | 2,558 | A collection of selectors. The combination of instances matching the selectors are included in the instance group.
Initializes a new ComputeInstanceGroupSelectorCollection object with values from keyword arguments.
The following keyword arguments are supported (corresponding to the getters/setters of this class):
:par... | 1,487 | en | 0.787627 |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Update the location of a adrespositie and and add a terrein koppeling using a shapeFile
import os, sys, codecs, datetime, argparse
import osgeo.ogr as ogr
from pyspatialite import dbapi2 as sqlite3 #import sqlite3
def updateTerrein(cur, TERREINOBJECTID , HUISNUMMERID):
... | update_terrein_adrespositie.py | 3,955 | herkomst: 2= perceel, 3= gebouw
!/usr/bin/env python -*- coding: UTF-8 -*- Update the location of a adrespositie and and add a terrein koppeling using a shapeFileimport sqlite3joined twice or morejoined to a adres with an enddate | 230 | en | 0.37787 |
import sqlite3
import datetime
from collections import Counter
import calendar
def return_unique_ID():
conn = sqlite3.connect("ORDERM8.db")
c = conn.cursor()
c.execute('SELECT * FROM rolodex')
IDs = []
for item in c:
ID = int(item[0])
IDs.append(ID)
IDs = sorted(IDs, key=int, re... | SQL_functions.py | 16,437 | def drop_rolodex_table(): conn = sqlite3.connect("ORDERM8.db") c = conn.cursor() c.execute('DROP table rolodex') for item in c: orderlist = item[2].split() print item[0], item[1], orderlist, item[3] Day Duties Stuff. Examples new_day_duty(datetime.datetime.now(), "Wednesday", "Condense Recycli... | 882 | en | 0.575305 |
"""
MIT License
Copyright (c) 2020-2021 phenom4n4n
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, publis... | roleutils/roleutils.py | 3,033 | This allows the metaclass used for proper type detection to
coexist with discord.py's metaclass
Useful role commands.
Includes massroling, role targeting, and reaction roles.
MIT License
Copyright (c) 2020-2021 phenom4n4n
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software a... | 1,373 | en | 0.859512 |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 24 17:59:20 2017
@author: amirbitran
Various functions that serve to compute the contacts matrix for a series of PDB snapshots
"""
import numpy as np
from matplotlib import pyplot as plt
import sklearn
from sklearn import metrics
from dbfold.utils import loopCluster
im... | dbfold/analyze_structures.py | 22,219 | Input PDB file, plots contacts matrix
Radius of gyration...
much faster computation
min_seq_separation is minimum distnce the two residues must be apart in sequence for them to be counted
You can specify either of two modes:
1. 'binary': Returns 1 at positions where distance is less than or equal to thresh
2. 'distan... | 9,260 | en | 0.887723 |
from django.http import HttpResponse
from django.shortcuts import render, reverse
from django.views.decorators.csrf import csrf_exempt
import os
from twilio.rest import Client
from conversations.models import Conversation, Message
from .models import TwilioConfig, PhoneOwnership
# @validate_twilio_request
@csrf_exempt... | twilioconfig/views.py | 4,382 | @validate_twilio_request store message Set the webhook for the phone number if some items are found in the database incoming_phone_number = client.incoming_phone_numbers.create( sms_url='https://hackaway.software/twilio/receive', phone_number='+447700153842' ) Obtain informatio... | 594 | en | 0.707313 |
#
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
import urllib.parse
from abc import ABC
from typing import Any, Iterable, Mapping, MutableMapping, Optional
import requests
from airbyte_cdk.sources.streams.http import HttpStream
class CartStream(HttpStream, ABC):
primary_key = "id"
def __init__... | airbyte-integrations/connectors/source-cart/source_cart/streams.py | 4,787 | Docs: https://developers.cart.com/docs/rest-api/b3A6MjMzMTc3Njc-get-addresses
Docs: https://developers.cart.com/docs/rest-api/restapi.json/paths/~1customers/get
Docs: https://developers.cart.com/docs/rest-api/restapi.json/paths/~1order_items/get
Docs: https://developers.cart.com/docs/rest-api/restapi.json/paths/~1order... | 1,034 | en | 0.670341 |
# coding:utf-8
# usr/bin/python3
# python src/chapter28/chapter28note.py
# python3 src/chapter28/chapter28note.py
"""
Class Chapter28_1
Class Chapter28_2
Class Chapter28_3
Class Chapter28_4
Class Chapter28_5
"""
from __future__ import absolute_import, division, print_function
import numpy as np
class Chapter28_... | src/chapter28/chapter28note.py | 20,506 | chapter28.1 note and function
chapter28.2 note and function
chapter28.3 note and function
chapter28.4 note and function
chapter28.5 note and function
Summary
====
Print chapter28.1 note
Example
====
```python
Chapter28_1().note()
```
Summary
====
Print chapter28.2 note
Example
====
```python
Chapter28_2().note()
```
... | 1,288 | en | 0.295707 |
#Python 3.X? Could be compatitible with small tweaks.
from re import findall
#Tatatat0 2016
#Documentation:
#Virtual Memory Classes:
# Virtual_Memory(max_memory)
# maxmemory: maximum address memory can be allocated to
# chunks: list of virtual memory chunks.
# format: ((chunk1, chunk1.start_address,... | VirtualMemory.py | 15,475 | Python 3.X? Could be compatitible with small tweaks.Tatatat0 2016Documentation:Virtual Memory Classes: Virtual_Memory(max_memory) maxmemory: maximum address memory can be allocated to chunks: list of virtual memory chunks. format: ((chunk1, chunk1.start_address, chunk1.allocated_memory),(chunk2,...,...)) F... | 4,913 | en | 0.738116 |
import asyncio, sys, os
from onvif import ONVIFCamera
import time
IP="192.168.1.64" # Camera IP address
PORT=80 # Port
USER="admin" # Username
PASS="intflow3121" # Password
XMAX = 1
XMIN = -1
XNOW = 0.5
YMAX = 1
YMIN = -1
YNOW = 0.5
Move = 0.1
Velocity = 1
Zoom = 0
positionrequest = None
p... | examples/AbsoluteMove.py | 8,309 | Reading from stdin and displaying menu
Camera IP address Port Username Password Create media service object Create ptz service object Get target profile Get range of pan and tilt Test Define def move(ptz, request): request.Position.PanTilt.y = -1 request.Position.PanTilt.x = 0 do_move(ptz,request) ... | 401 | en | 0.483882 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.