max_stars_repo_path stringlengths 4 286 | max_stars_repo_name stringlengths 5 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.03M | content_cleaned stringlengths 6 1.03M | language stringclasses 111
values | language_score float64 0.03 1 | comments stringlengths 0 556k | edu_score float64 0.32 5.03 | edu_int_score int64 0 5 |
|---|---|---|---|---|---|---|---|---|---|---|
tests/test_formatter.py | hbraux/kafkacli | 0 | 3700 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import pytest
import json
from kafkacli.formatter import Formatter
sampleJson = json.loads('{"a":"s", "b":1}')
def test_print_default(capsys):
Formatter().print(sampleJson)
captured = capsys.readouterr()
assert captured.out == '{"a": "s", "b": 1}\n... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import pytest
import json
from kafkacli.formatter import Formatter
sampleJson = json.loads('{"a":"s", "b":1}')
def test_print_default(capsys):
Formatter().print(sampleJson)
captured = capsys.readouterr()
assert captured.out == '{"a": "s", "b": 1}\n... | en | 0.352855 | #!/usr/bin/env python # -*- coding: utf-8 -*- | 2.398014 | 2 |
src/jobs/forms.py | arc198/DJANGO-JOB-SITE | 20 | 3701 | from django import forms
from .models import Application
class ApplicationForm(forms.ModelForm):
class Meta:
model = Application
fields = ('resume', 'cover_letter',) | from django import forms
from .models import Application
class ApplicationForm(forms.ModelForm):
class Meta:
model = Application
fields = ('resume', 'cover_letter',) | none | 1 | 1.820574 | 2 | |
src/test/tests/unit/protocol.py | ylee88/visit | 1 | 3702 | # ----------------------------------------------------------------------------
# CLASSES: nightly
#
# Test Case: protocolo.py
#
# Tests: vistprotocol unit test
#
# <NAME>, Tue Jan 11 10:19:23 PST 2011
# ----------------------------------------------------------------------------
tapp = visit_bin_path("visitpr... | # ----------------------------------------------------------------------------
# CLASSES: nightly
#
# Test Case: protocolo.py
#
# Tests: vistprotocol unit test
#
# <NAME>, Tue Jan 11 10:19:23 PST 2011
# ----------------------------------------------------------------------------
tapp = visit_bin_path("visitpr... | en | 0.282431 | # ---------------------------------------------------------------------------- # CLASSES: nightly # # Test Case: protocolo.py # # Tests: vistprotocol unit test # # <NAME>, Tue Jan 11 10:19:23 PST 2011 # ---------------------------------------------------------------------------- | 2.097165 | 2 |
pyMazeBacktrack.py | Dozed12/pyMazeBacktrack | 2 | 3703 | import libtcodpy as libtcod
from random import randint
nSquares = 30
nTiles = nSquares * 2 + 1
SCREEN_WIDTH = nTiles
SCREEN_HEIGHT = nTiles
libtcod.console_set_custom_font("cp437_12x12.png", libtcod.FONT_LAYOUT_ASCII_INROW)
libtcod.console_init_root(SCREEN_WIDTH, SCREEN_HEIGHT, 'pyMazeBacktrack', False, li... | import libtcodpy as libtcod
from random import randint
nSquares = 30
nTiles = nSquares * 2 + 1
SCREEN_WIDTH = nTiles
SCREEN_HEIGHT = nTiles
libtcod.console_set_custom_font("cp437_12x12.png", libtcod.FONT_LAYOUT_ASCII_INROW)
libtcod.console_init_root(SCREEN_WIDTH, SCREEN_HEIGHT, 'pyMazeBacktrack', False, li... | ru | 0.43976 | #print #print | 2.552217 | 3 |
source/tests/test_resources.py | aws-solutions/maintaining-personalized-experiences-with-machine-learning | 6 | 3704 | <gh_stars>1-10
# ######################################################################################################################
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# ... | # ######################################################################################################################
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# ... | en | 0.496922 | # ###################################################################################################################### # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # # ... | 1.500758 | 2 |
gradefiles-send.py | lapets/bu-gsubmit-grading | 3 | 3705 | #####################################################################
##
## gradefiles-send.py
##
## Script to send grade files by email to enrolled students; the
## input grade file names should correspond to the user names of
## the students.
##
##
from email.mime.text import MIMEText # For creating a message... | #####################################################################
##
## gradefiles-send.py
##
## Script to send grade files by email to enrolled students; the
## input grade file names should correspond to the user names of
## the students.
##
##
from email.mime.text import MIMEText # For creating a message... | de | 0.352615 | ##################################################################### ## ## gradefiles-send.py ## ## Script to send grade files by email to enrolled students; the ## input grade file names should correspond to the user names of ## the students. ## ## # For creating a message string. # For sending email on linux. ... | 3.323006 | 3 |
Publisher/PGGAN-1024 trained on CelebaHQ/2-exporter.py | GalAster/16 | 3 | 3706 | <filename>Publisher/PGGAN-1024 trained on CelebaHQ/2-exporter.py<gh_stars>1-10
import os
import pickle
import tensorflow as tf
import wolframclient.serializers as wxf
name = 'karras2018iclr-celebahq-1024x1024'
file = open(name + '.pkl', 'rb')
sess = tf.InteractiveSession()
G, D, Gs = pickle.load(file)
saver = tf.train... | <filename>Publisher/PGGAN-1024 trained on CelebaHQ/2-exporter.py<gh_stars>1-10
import os
import pickle
import tensorflow as tf
import wolframclient.serializers as wxf
name = 'karras2018iclr-celebahq-1024x1024'
file = open(name + '.pkl', 'rb')
sess = tf.InteractiveSession()
G, D, Gs = pickle.load(file)
saver = tf.train... | en | 0.387881 | # Save as protobuf # output_node_names=['G_paper_1/images_out'] # 保存模型 # 序列化输出 | 2.047986 | 2 |
src/moveGoogle.py | Quanta-Robotics/Robot-Blueberry | 25 | 3707 | #!/usr/bin/env python
import os
import os.path
import yaml
import time
import random
import multiprocessing
import RPi.GPIO as GPIO
from talk import say
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
from adafruit_servokit import ServoKit
Motor1 = {'EN': 27, 'input1': 19, 'input2': 16}
Motor2 = {'EN': 22, 'input1': 2... | #!/usr/bin/env python
import os
import os.path
import yaml
import time
import random
import multiprocessing
import RPi.GPIO as GPIO
from talk import say
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
from adafruit_servokit import ServoKit
Motor1 = {'EN': 27, 'input1': 19, 'input2': 16}
Motor2 = {'EN': 22, 'input1': 2... | ru | 0.26433 | #!/usr/bin/env python | 2.28471 | 2 |
src/onegov/translator_directory/models/language.py | politbuero-kampagnen/onegov-cloud | 0 | 3708 | from uuid import uuid4
from sqlalchemy import Index, Column, Text, Table, ForeignKey
from sqlalchemy.orm import object_session
from onegov.core.orm import Base
from onegov.core.orm.types import UUID
spoken_association_table = Table(
'spoken_lang_association',
Base.metadata,
Column(
'translator_i... | from uuid import uuid4
from sqlalchemy import Index, Column, Text, Table, ForeignKey
from sqlalchemy.orm import object_session
from onegov.core.orm import Base
from onegov.core.orm.types import UUID
spoken_association_table = Table(
'spoken_lang_association',
Base.metadata,
Column(
'translator_i... | en | 0.982358 | Having it as mother tongue... | 2.512358 | 3 |
tfjs-converter/python/tensorflowjs/converters/graph_rewrite_util.py | djemeljanovs/tfjs | 0 | 3709 | <gh_stars>0
# Copyright 2019 Google LLC
#
# 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 i... | # Copyright 2019 Google LLC
#
# 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, s... | en | 0.844687 | # Copyright 2019 Google LLC # # 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, s... | 2.074047 | 2 |
loss_fn/classification_loss_fns/binary_cross_entropy.py | apple/ml-cvnets | 209 | 3710 | <filename>loss_fn/classification_loss_fns/binary_cross_entropy.py
#
# For licensing see accompanying LICENSE file.
# Copyright (C) 2022 Apple Inc. All Rights Reserved.
#
from torch.nn import functional as F
from torch import Tensor
import argparse
from . import register_classification_loss_fn
from .. import BaseCrite... | <filename>loss_fn/classification_loss_fns/binary_cross_entropy.py
#
# For licensing see accompanying LICENSE file.
# Copyright (C) 2022 Apple Inc. All Rights Reserved.
#
from torch.nn import functional as F
from torch import Tensor
import argparse
from . import register_classification_loss_fn
from .. import BaseCrite... | en | 0.785312 | # # For licensing see accompanying LICENSE file. # Copyright (C) 2022 Apple Inc. All Rights Reserved. # Binary CE for classification tasks | 2.304171 | 2 |
Sorting/insertion_sort.py | lakshyarawal/pythonPractice | 0 | 3711 | <filename>Sorting/insertion_sort.py
""" Insertion Sort Algorithm:"""
"""Implementation"""
def insertion_sort(arr) -> list:
n = len(arr)
for i in range(1, n):
swap_index = i
for j in range(i-1, -1, -1):
if arr[swap_index] < arr[j]:
arr[swap_index], arr[j] = arr[j],... | <filename>Sorting/insertion_sort.py
""" Insertion Sort Algorithm:"""
"""Implementation"""
def insertion_sort(arr) -> list:
n = len(arr)
for i in range(1, n):
swap_index = i
for j in range(i-1, -1, -1):
if arr[swap_index] < arr[j]:
arr[swap_index], arr[j] = arr[j],... | en | 0.416752 | Insertion Sort Algorithm: Implementation # Using the special variable # __name__ | 4.245015 | 4 |
nipype/interfaces/spm/__init__.py | felixsc1/nipype | 8 | 3712 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Top-level namespace for spm."""
from .base import (Info, SPMCommand, logger, no_spm, scans_for_fname,
scans_for_fnames)
from .preprocess import ... | # -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Top-level namespace for spm."""
from .base import (Info, SPMCommand, logger, no_spm, scans_for_fname,
scans_for_fnames)
from .preprocess import (FieldMap, Slic... | en | 0.37214 | # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: Top-level namespace for spm. | 1.552201 | 2 |
network.py | tobloef/neural-network | 3 | 3713 | <reponame>tobloef/neural-network<filename>network.py
import numpy as np
from mathUtils import *
class Network(object):
"""
Model for a feedforward Neural Network that use backpropagation with stochastic gradient decent.
"""
def __init__(self, layerSizes, biasVectors, weightMatrices):
"""
... | import numpy as np
from mathUtils import *
class Network(object):
"""
Model for a feedforward Neural Network that use backpropagation with stochastic gradient decent.
"""
def __init__(self, layerSizes, biasVectors, weightMatrices):
"""
Initialise the network with a list of layer sizes ... | en | 0.869302 | Model for a feedforward Neural Network that use backpropagation with stochastic gradient decent. Initialise the network with a list of layer sizes and lists for biases and weights for the neurons in the network. The first layer is the input layer and the last layer is the output layer. Initialise a new network with ran... | 3.609519 | 4 |
examples/airflow/dags/etl_orders_7_days.py | phixMe/marquez | 0 | 3714 | <reponame>phixMe/marquez
from datetime import datetime
from marquez_airflow import DAG
from airflow.operators.postgres_operator import PostgresOperator
from airflow.utils.dates import days_ago
default_args = {
'owner': 'datascience',
'depends_on_past': False,
'start_date': days_ago(1),
'email_on_failur... | from datetime import datetime
from marquez_airflow import DAG
from airflow.operators.postgres_operator import PostgresOperator
from airflow.utils.dates import days_ago
default_args = {
'owner': 'datascience',
'depends_on_past': False,
'start_date': days_ago(1),
'email_on_failure': False,
'email_on_... | en | 0.201982 | CREATE TABLE IF NOT EXISTS orders_7_days ( order_id INTEGER REFERENCES orders(id), placed_on TIMESTAMP NOT NULL, discount_id INTEGER REFERENCES discounts(id), menu_id INTEGER REFERENCES menus(id), restaurant_id INTEGER REFERENCES restaurants(id), menu_item_id INTEGE... | 2.299031 | 2 |
sample/pizza.py | marianarmorgado/python-starter | 0 | 3715 | <filename>sample/pizza.py
# store information about a pizza being ordered
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra vegan cheese']
}
# summarize the order
print("You ordered a " + pizza['crust'] + "-crust pizza" +
"with the following toppings:")
for topping in pizza['toppings']:
pr... | <filename>sample/pizza.py
# store information about a pizza being ordered
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra vegan cheese']
}
# summarize the order
print("You ordered a " + pizza['crust'] + "-crust pizza" +
"with the following toppings:")
for topping in pizza['toppings']:
pr... | en | 0.841785 | # store information about a pizza being ordered # summarize the order | 4.01064 | 4 |
YouTube/CursoEmVideo/python/ex012.py | Fh-Shadow/Progamando | 0 | 3716 | <filename>YouTube/CursoEmVideo/python/ex012.py<gh_stars>0
a = float(input('Qual é o preço do produto? R$'))
d = a - (a * 23 / 100)
print('O produto que custava R${:.2f}, na promoção de 23% de desconto vai custar: R${:.2f}' .format(a, d))
| <filename>YouTube/CursoEmVideo/python/ex012.py<gh_stars>0
a = float(input('Qual é o preço do produto? R$'))
d = a - (a * 23 / 100)
print('O produto que custava R${:.2f}, na promoção de 23% de desconto vai custar: R${:.2f}' .format(a, d))
| none | 1 | 3.498558 | 3 | |
dnnlib/submission/submit.py | gperdrizet/gansformer | 1,172 | 3717 | <reponame>gperdrizet/gansformer
# Submit a function to be run either locally or in a computing cluster.
# Compared to original StyleGAN implementation, we extend the support for automatic training resumption,
# and network recompilation.
import copy
import inspect
import os
import pathlib
import pickle
import platform
... | # Submit a function to be run either locally or in a computing cluster.
# Compared to original StyleGAN implementation, we extend the support for automatic training resumption,
# and network recompilation.
import copy
import inspect
import os
import pathlib
import pickle
import platform
import pprint
import re
import s... | en | 0.779862 | # Submit a function to be run either locally or in a computing cluster. # Compared to original StyleGAN implementation, we extend the support for automatic training resumption, # and network recompilation. # The target where the function should be run # LOCAL: Run it locally # Determines in which format should a path b... | 2.17816 | 2 |
pyecharts/custom/grid.py | zilong305/pycharts | 0 | 3718 | <gh_stars>0
#!/usr/bin/env python
# coding=utf-8
from pyecharts.option import grid
class Grid(object):
def __init__(self):
self._chart = None
self._js_dependencies = set()
def add(self, chart,
grid_width=None,
grid_height=None,
grid_top=None,
... | #!/usr/bin/env python
# coding=utf-8
from pyecharts.option import grid
class Grid(object):
def __init__(self):
self._chart = None
self._js_dependencies = set()
def add(self, chart,
grid_width=None,
grid_height=None,
grid_top=None,
grid_bottom=... | en | 0.840053 | #!/usr/bin/env python # coding=utf-8 :param chart: chart instance :param grid_width: Width of grid component. Adaptive by default. :param grid_height: Height of grid component. Adaptive by default. :param grid_top: Distance between grid component a... | 2.482295 | 2 |
smooch/conversations.py | devinmcgloin/smooch | 3 | 3719 | import logging
from .endpoint import ask
def send_message(user_id, message, sent_by_maker=True):
if not valid_args(user_id, message):
logging.warning("send message called with invalid args user_id={} message={}".format(user_id, message))
return
logging.debug("Sending message: user_id={0} mes... | import logging
from .endpoint import ask
def send_message(user_id, message, sent_by_maker=True):
if not valid_args(user_id, message):
logging.warning("send message called with invalid args user_id={} message={}".format(user_id, message))
return
logging.debug("Sending message: user_id={0} mes... | en | 0.87548 | Note that amount is a integer which specifies the amount of cents in the transaction Smooch will default to the currency specified in your account settings. Sends a series of links. The options field is a dictionary in which the keys are descriptions and values uris Sends a series of options that you can listen... | 2.48759 | 2 |
cifar/evalit.py | Sharkbyteprojects/IRIS-ML_and_Deep-Learning | 0 | 3720 | <reponame>Sharkbyteprojects/IRIS-ML_and_Deep-Learning<gh_stars>0
import keras
from keras.models import load_model
from PIL import Image
import matplotlib.pylab as plt
import numpy as np
import zipfile
print("Extract")
zip_ref = zipfile.ZipFile("./asset.zip", 'r')
zip_ref.extractall(".")
zip_ref.close()
print("Load Mode... | import keras
from keras.models import load_model
from PIL import Image
import matplotlib.pylab as plt
import numpy as np
import zipfile
print("Extract")
zip_ref = zipfile.ZipFile("./asset.zip", 'r')
zip_ref.extractall(".")
zip_ref.close()
print("Load Model")
model=load_model("cifar-model.h5")
CIFAR_10_CLASSES=["Plane",... | none | 1 | 3.115216 | 3 | |
tt/urls.py | samiksha-patil/Knowledge-Sharing-Platform | 1 | 3721 | """
tt URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based vi... | """
tt URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based vi... | en | 0.591946 | tt URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views ... | 2.58342 | 3 |
src/git/cmd.py | danihodovic/dht | 2 | 3722 | import os
import click
os.environ["GIT_PYTHON_REFRESH"] = "quiet"
@click.group()
def git():
pass
| import os
import click
os.environ["GIT_PYTHON_REFRESH"] = "quiet"
@click.group()
def git():
pass
| none | 1 | 1.443269 | 1 | |
TwitterImage2JPG.py | Tymec/Playground | 0 | 3723 | import glob
import os
def main():
os.chdir("F:/Downloads")
extensions = ["*.jpg_large", "*.png_large", "*.jpg_orig"]
file_list = list()
for extension in extensions:
file_list = file_list + glob.glob(extension)
for file in file_list:
for extension in extensions:
new_ex... | import glob
import os
def main():
os.chdir("F:/Downloads")
extensions = ["*.jpg_large", "*.png_large", "*.jpg_orig"]
file_list = list()
for extension in extensions:
file_list = file_list + glob.glob(extension)
for file in file_list:
for extension in extensions:
new_ex... | none | 1 | 3.546578 | 4 | |
Data Analysis/classification.py | Riccardo95Facchini/DIL-2019 | 0 | 3724 | <filename>Data Analysis/classification.py
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.metrics import classification_report
#EVERY TIME THE DATASET IS RETRIEVED FROM GITHUB
input_file = 'https://raw.githubusercontent.com/lcphy/Digital-Innovation-Lab/master/... | <filename>Data Analysis/classification.py
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.metrics import classification_report
#EVERY TIME THE DATASET IS RETRIEVED FROM GITHUB
input_file = 'https://raw.githubusercontent.com/lcphy/Digital-Innovation-Lab/master/... | en | 0.402452 | #EVERY TIME THE DATASET IS RETRIEVED FROM GITHUB #DELETE NEXT CALLS DATA #FEATURE ENGINEERING #COLLERATION MATRIX #CLASSIFIFICATION #DECISION TREE #RANDOM FOREST # K-NEAREST NEIGHBOURS # TRAINING - TEST # SCALING # FITTING # PREDICTION # CONFUSION MATRIX #UNDERSAMPLING #SPLIT FEATURE AND TARGET #TRAIN TEST #SELECTING T... | 3.393854 | 3 |
tools/c7n_azure/tests/test_route_table.py | anastasiia-zolochevska/cloud-custodian | 2 | 3725 | # Copyright 2015-2018 Capital One Services, LLC
#
# 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 ... | # Copyright 2015-2018 Capital One Services, LLC
#
# 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 ... | en | 0.84552 | # Copyright 2015-2018 Capital One Services, LLC # # 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 ... | 1.781326 | 2 |
proto/tp_artifact_1.0/build/lib/sawtooth_artifact/processor/handler.py | pkthein/sparts_all_fam | 1 | 3726 | # Copyright 2016 Intel Corporation
# Copyright 2017 Wind River
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2016 Intel Corporation
# Copyright 2017 Wind River
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | en | 0.591231 | # Copyright 2016 Intel Corporation # Copyright 2017 Wind River # 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 applicab... | 1.47826 | 1 |
ReviewsCollector.py | fsandx/moodybooks | 0 | 3727 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
STEP 2
Takes the list of urls in the json files and downloads the html files to local drive
Start with: scrapy runspider ReviewsCollector.py
"""
import scrapy
import json
class ReviewsCollector(scrapy.Spider):
def start_requests(self):
with open("data/b... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
STEP 2
Takes the list of urls in the json files and downloads the html files to local drive
Start with: scrapy runspider ReviewsCollector.py
"""
import scrapy
import json
class ReviewsCollector(scrapy.Spider):
def start_requests(self):
with open("data/b... | en | 0.671089 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- STEP 2 Takes the list of urls in the json files and downloads the html files to local drive Start with: scrapy runspider ReviewsCollector.py | 3.403952 | 3 |
firelight/interfaces/light.py | roshie548/firelight | 16 | 3728 | <gh_stars>10-100
from abc import ABC, abstractmethod
from .color import Color
class LightSystem(ABC):
@classmethod
def __subclasshook__(cls, subclass):
return (hasattr(subclass, 'set_transition_time')
and callable(subclass.set_transition_time)
and hasattr(subclass, 'dis... | from abc import ABC, abstractmethod
from .color import Color
class LightSystem(ABC):
@classmethod
def __subclasshook__(cls, subclass):
return (hasattr(subclass, 'set_transition_time')
and callable(subclass.set_transition_time)
and hasattr(subclass, 'discover_lights')
... | en | 0.858203 | Discover the lights and groups in this LightSystem. Set how long it takes in milliseconds for colors to transition. Set the color of all the lights in the LightSystem. Turn on the lights in this group. Turn off the lights in this group. Set how long it takes in milliseconds for colors to transition. Set the color of th... | 3.339895 | 3 |
PolymorphismPYTHON/Polypy.py | cadeng23/oop-cjgustafson | 0 | 3729 | <reponame>cadeng23/oop-cjgustafson
import random
class Family:
def __init__(self,first, last, hair):
self.first = first
self.last = last
self.hair = hair
def fullname(self):
return '{} {}'.format(self.first,self.last)
def eyefind(self):
temp = random.choice([1,2... | import random
class Family:
def __init__(self,first, last, hair):
self.first = first
self.last = last
self.hair = hair
def fullname(self):
return '{} {}'.format(self.first,self.last)
def eyefind(self):
temp = random.choice([1,2])
#using the punnet square... | en | 0.94725 | #using the punnet square in genetics we know thatt a donor #with blue eyes and one with brown makes it 50/50 odds #that the childs eyes will be brown or blue #with the kids being born it will define what color hair and eyes # they may randomly get through inheritance #Eyes are marked as Grey because they are unknown fo... | 3.964492 | 4 |
homeassistant/components/device_tracker/owntracks.py | evancohen/home-assistant | 14 | 3730 | """
homeassistant.components.device_tracker.owntracks
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
OwnTracks platform for the device tracker.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.owntracks/
"""
import json
import logging
im... | """
homeassistant.components.device_tracker.owntracks
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
OwnTracks platform for the device tracker.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.owntracks/
"""
import json
import logging
im... | en | 0.56365 | homeassistant.components.device_tracker.owntracks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ OwnTracks platform for the device tracker. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/device_tracker.owntracks/ Set up a OwnTracksks tracker. MQTT mes... | 2.276761 | 2 |
src/models/end_to_end_event_coreference.py | luyaojie/E3C | 2 | 3731 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Created by Roger on 2019-09-10
# Mostly by AllenNLP
import logging
import math
from typing import Any, Dict, List, Optional, Tuple
import torch
import torch.nn.functional as F
from allennlp.data import Vocabulary
from allennlp.models.model import Model
from allennlp.mod... | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Created by Roger on 2019-09-10
# Mostly by AllenNLP
import logging
import math
from typing import Any, Dict, List, Optional, Tuple
import torch
import torch.nn.functional as F
from allennlp.data import Vocabulary
from allennlp.models.model import Model
from allennlp.mod... | en | 0.773761 | #!/usr/bin/env python # -*- coding:utf-8 -*- # Created by Roger on 2019-09-10 # Mostly by AllenNLP # pylint: disable=invalid-name This ``Model`` implements the coreference resolution model described "End-to-end Neural Coreference Resolution" <https://www.semanticscholar.org/paper/End-to-end-Neural-Coreference-R... | 2.000504 | 2 |
week2/7litersProblem.py | vietanhtran2710/ArtificialIntelligenceHomework | 3 | 3732 | <filename>week2/7litersProblem.py
"""
Given 3 bottles of capacities 3, 5, and 9 liters,
count number of all possible solutions to get 7 liters
"""
current_path = [[0, 0, 0]]
CAPACITIES = (3, 5, 9)
solutions_count = 0
def move_to_new_state(current_state):
global solutions_count, current_path
if 7 in c... | <filename>week2/7litersProblem.py
"""
Given 3 bottles of capacities 3, 5, and 9 liters,
count number of all possible solutions to get 7 liters
"""
current_path = [[0, 0, 0]]
CAPACITIES = (3, 5, 9)
solutions_count = 0
def move_to_new_state(current_state):
global solutions_count, current_path
if 7 in c... | en | 0.830138 | Given 3 bottles of capacities 3, 5, and 9 liters, count number of all possible solutions to get 7 liters # Empty bottle # Fill bottle # Pour from one bottle to another # Result: at least 44900799 solution | 3.536289 | 4 |
st2common/st2common/bootstrap/rulesregistrar.py | avezraj/st2 | 0 | 3733 | <gh_stars>0
# Copyright 2019 Extreme Networks, Inc.
#
# 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... | # Copyright 2019 Extreme Networks, Inc.
#
# 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 i... | en | 0.907341 | # Copyright 2019 Extreme Networks, Inc. # # 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 i... | 1.699767 | 2 |
sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_models_py3.py | aiven/azure-sdk-for-python | 1 | 3734 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | en | 0.691641 | # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ... | 1.904907 | 2 |
test/test_simple_compression.py | jayvdb/brotlipy | 0 | 3735 | <reponame>jayvdb/brotlipy
# -*- coding: utf-8 -*-
"""
test_simple_compression
~~~~~~~~~~~~~~~~~~~~~~~~~
Tests for compression of single chunks.
"""
import brotli
import pytest
from hypothesis import given
from hypothesis.strategies import binary, integers, sampled_from, one_of
def test_roundtrip_compression_with_f... | # -*- coding: utf-8 -*-
"""
test_simple_compression
~~~~~~~~~~~~~~~~~~~~~~~~~
Tests for compression of single chunks.
"""
import brotli
import pytest
from hypothesis import given
from hypothesis.strategies import binary, integers, sampled_from, one_of
def test_roundtrip_compression_with_files(simple_compressed_fil... | en | 0.884026 | # -*- coding: utf-8 -*- test_simple_compression ~~~~~~~~~~~~~~~~~~~~~~~~~ Tests for compression of single chunks. Roundtripping data through the compressor works correctly. Confirm that the streaming compressor works as expected. Confirm that the streaming compressor works as expected, including flushes after each... | 2.312375 | 2 |
wexapi/models/ticker.py | madmis/wexapi | 3 | 3736 | <filename>wexapi/models/ticker.py
from decimal import Decimal
class Ticker(object):
def __init__(
self,
high: float,
low: float,
avg: float,
vol: float,
vol_cur: int,
last: float,
buy: float,
sell: float,
... | <filename>wexapi/models/ticker.py
from decimal import Decimal
class Ticker(object):
def __init__(
self,
high: float,
low: float,
avg: float,
vol: float,
vol_cur: int,
last: float,
buy: float,
sell: float,
... | none | 1 | 2.887198 | 3 | |
hard-gists/98bb452dc14e8c40e403/snippet.py | jjhenkel/dockerizeme | 21 | 3737 | <filename>hard-gists/98bb452dc14e8c40e403/snippet.py
from scryptos import *
p1 = 32581479300404876772405716877547
p2 = 27038194053540661979045656526063
p3 = 26440615366395242196516853423447
n = p1*p2*p3
e = 3
c = int(open("flag.enc", "rb").read().encode("hex"), 16)
# from User's Guide to PARI/GP, nth_root function
s... | <filename>hard-gists/98bb452dc14e8c40e403/snippet.py
from scryptos import *
p1 = 32581479300404876772405716877547
p2 = 27038194053540661979045656526063
p3 = 26440615366395242196516853423447
n = p1*p2*p3
e = 3
c = int(open("flag.enc", "rb").read().encode("hex"), 16)
# from User's Guide to PARI/GP, nth_root function
s... | en | 0.339273 | # from User's Guide to PARI/GP, nth_root function c1 = [6149264605288583791069539134541, 13404203109409336045283549715377, 13028011585706956936052628027629] c2 = [19616973567618515464515107624812] c3 = [13374868592866626517389128266735, 7379361747422713811654086477766, 5686385026105901867473638678946] | 1.980532 | 2 |
musa/migrations/0001_initial.py | ccsreenidhin/Music-Web-Django | 0 | 3738 | <gh_stars>0
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-03-29 06:43
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import musa.models
class Migration(migrations.Migration):
initial = True
depe... | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-03-29 06:43
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import musa.models
class Migration(migrations.Migration):
initial = True
dependencies = [... | en | 0.742467 | # -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-03-29 06:43 | 1.665557 | 2 |
nuitka/codegen/LoopCodes.py | RESP3CT88/Nuitka | 1 | 3739 | # Copyright 2021, <NAME>, mailto:<EMAIL>
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Lice... | # Copyright 2021, <NAME>, mailto:<EMAIL>
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Lice... | en | 0.900701 | # Copyright 2021, <NAME>, mailto:<EMAIL> # # Part of "Nuitka", an optimizing Python compiler that is compatible and # integrates with CPython, but also works on its own. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Lice... | 2.009417 | 2 |
3_module/C_BloomFilter.py | L4mborg1n1-D14610/Algoritms_and_DataStructure | 0 | 3740 | import math
from sys import exit
# итак, n - приблизительное число элементов в массиве, P - вероятность ложноположительного ответа, тогда размер
# структуры m = -(nlog2P) / ln2 (2 - основание), количество хеш-функций будет равно -log2P
# хеш-функции используются вида: (((i + 1)*x + p(i+1)) mod M) mod m,где - x - ключ,... | import math
from sys import exit
# итак, n - приблизительное число элементов в массиве, P - вероятность ложноположительного ответа, тогда размер
# структуры m = -(nlog2P) / ln2 (2 - основание), количество хеш-функций будет равно -log2P
# хеш-функции используются вида: (((i + 1)*x + p(i+1)) mod M) mod m,где - x - ключ,... | ru | 0.993644 | # итак, n - приблизительное число элементов в массиве, P - вероятность ложноположительного ответа, тогда размер # структуры m = -(nlog2P) / ln2 (2 - основание), количество хеш-функций будет равно -log2P # хеш-функции используются вида: (((i + 1)*x + p(i+1)) mod M) mod m,где - x - ключ, i - номер хэш-функции, # pi - i-т... | 2.412048 | 2 |
pyzmq/examples/pubsub/subscriber.py | Surfndez/source-publish | 0 | 3741 | """A test that subscribes to NumPy arrays.
Uses REQ/REP (on PUB/SUB socket + 1) to synchronize
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2010 <NAME>
#
# Distributed under the terms of the New BSD License. The full license is in
# the file COPYING.BSD, distr... | """A test that subscribes to NumPy arrays.
Uses REQ/REP (on PUB/SUB socket + 1) to synchronize
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2010 <NAME>
#
# Distributed under the terms of the New BSD License. The full license is in
# the file COPYING.BSD, distr... | en | 0.589059 | A test that subscribes to NumPy arrays. Uses REQ/REP (on PUB/SUB socket + 1) to synchronize #----------------------------------------------------------------------------- # Copyright (c) 2010 <NAME> # # Distributed under the terms of the New BSD License. The full license is in # the file COPYING.BSD, distributed a... | 2.606975 | 3 |
Doc/includes/sqlite3/load_extension.py | livioso/cpython | 36 | 3742 | import sqlite3
con = sqlite3.connect(":memory:")
# enable extension loading
con.enable_load_extension(True)
# Load the fulltext search extension
con.execute("select load_extension('./fts3.so')")
# alternatively you can load the extension using an API call:
# con.load_extension("./fts3.so")
# disable extension load... | import sqlite3
con = sqlite3.connect(":memory:")
# enable extension loading
con.enable_load_extension(True)
# Load the fulltext search extension
con.execute("select load_extension('./fts3.so')")
# alternatively you can load the extension using an API call:
# con.load_extension("./fts3.so")
# disable extension load... | en | 0.417381 | # enable extension loading # Load the fulltext search extension # alternatively you can load the extension using an API call: # con.load_extension("./fts3.so") # disable extension loading again # example from SQLite wiki insert into recipe (name, ingredients) values ('broccoli stew', 'broccoli peppers cheese tomatoes')... | 2.99697 | 3 |
lingvo/core/inference_graph_exporter.py | RunzheYang/lingvo | 1 | 3743 | # Lint as: python3
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | # Lint as: python3
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | en | 0.806363 | # Lint as: python3 # Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless ... | 1.612568 | 2 |
src/preprocessing/annual_hc_by_crime_loc.py | VijayKalmath/USCrimeAnalysis | 0 | 3744 | <filename>src/preprocessing/annual_hc_by_crime_loc.py
#! usr/env/bin python
import glob
import numpy as np
import pandas as pd
from tqdm import tqdm
def main():
# Fetch File Paths
file_paths = glob.glob(r'./data/raw/ucr/hc_count_by_place/*.xls')
# Sort them according to year
file_paths.sort(key = lam... | <filename>src/preprocessing/annual_hc_by_crime_loc.py
#! usr/env/bin python
import glob
import numpy as np
import pandas as pd
from tqdm import tqdm
def main():
# Fetch File Paths
file_paths = glob.glob(r'./data/raw/ucr/hc_count_by_place/*.xls')
# Sort them according to year
file_paths.sort(key = lam... | en | 0.709622 | #! usr/env/bin python # Fetch File Paths # Sort them according to year # Create a result dataframe to store the data # Iterate over the rest of the files # Save the result to disk Function to return # Extracting the table name from and year from the given file path # Read the Excel spreadsheet # Get the start and end i... | 3.084925 | 3 |
allennlp/tests/modules/token_embedders/bag_of_word_counts_token_embedder_test.py | ethanjperez/allennlp | 24 | 3745 | # pylint: disable=no-self-use,invalid-name
import numpy as np
from numpy.testing import assert_almost_equal
import torch
from allennlp.common import Params
from allennlp.data import Vocabulary
from allennlp.modules.token_embedders import BagOfWordCountsTokenEmbedder
from allennlp.common.testing import AllenNlpTestCase
... | # pylint: disable=no-self-use,invalid-name
import numpy as np
from numpy.testing import assert_almost_equal
import torch
from allennlp.common import Params
from allennlp.data import Vocabulary
from allennlp.modules.token_embedders import BagOfWordCountsTokenEmbedder
from allennlp.common.testing import AllenNlpTestCase
... | en | 0.639922 | # pylint: disable=no-self-use,invalid-name | 2.18463 | 2 |
demo/demo_shapenet.py | hengkaiz/meshrcnn | 0 | 3746 | import argparse
import logging
import multiprocessing as mp
import logging
import os
from detectron2.evaluation import inference_context
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from detectron2.utils.collect_env import collect_env_info
from detectron2.utils.logger import setup_lo... | import argparse
import logging
import multiprocessing as mp
import logging
import os
from detectron2.evaluation import inference_context
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from detectron2.utils.collect_env import collect_env_info
from detectron2.utils.logger import setup_lo... | en | 0.474575 | # parser.add_argument("--output", help="A directory to save output visualizations") # logger.info('Original mesh:') # print(pv_mesh) # remesh # verts = remesh.points # faces = remesh.faces.reshape((-1, 4))[:, 1:] # load checkpoing and build model # load image # Save voxel_score # Save image features # Save P # Save cub... | 1.811098 | 2 |
proglearn/voters.py | jshin13/progressive-learning | 0 | 3747 | <gh_stars>0
import numpy as np
# from sklearn.ensemble import BaggingClassifier
# from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.utils.validation import (
check_X_y,
check_array,
NotFittedError,
)
from sklearn.utils.multiclass import check_... | import numpy as np
# from sklearn.ensemble import BaggingClassifier
# from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.utils.validation import (
check_X_y,
check_array,
NotFittedError,
)
from sklearn.utils.multiclass import check_classificati... | en | 0.819578 | # from sklearn.ensemble import BaggingClassifier # from sklearn.tree import DecisionTreeClassifier Doc strings here. Doc strings here. # Fit multilabel binary task. # Each posterior is now a num_labels size vector or binary probabilities. # TODO: multilabel finite sample correction. Doc strings here. Doc strings here. ... | 2.603147 | 3 |
config.py | jhattat/photoBooth | 0 | 3748 | <filename>config.py
# Tumblr Setup
# Replace the values with your information
# OAuth keys can be generated from https://api.tumblr.com/console/calls/user/info
consumer_key='<KEY>' #replace with your key
consumer_secret='<KEY>' #replace with your secret code
oath_token='<KEY>' #replace with your oath token
oath_secret=... | <filename>config.py
# Tumblr Setup
# Replace the values with your information
# OAuth keys can be generated from https://api.tumblr.com/console/calls/user/info
consumer_key='<KEY>' #replace with your key
consumer_secret='<KEY>' #replace with your secret code
oath_token='<KEY>' #replace with your oath token
oath_secret=... | en | 0.843413 | # Tumblr Setup # Replace the values with your information # OAuth keys can be generated from https://api.tumblr.com/console/calls/user/info #replace with your key #replace with your secret code #replace with your oath token #replace with your oath secret code # replace with your tumblr account name without .tumblr.com ... | 2.358834 | 2 |
accounts/admin.py | GuilhemN/site-interludes | 0 | 3749 | from django.contrib import admin
from django.contrib.auth.models import Group
from accounts.models import EmailUser
from shared.admin import ExportCsvMixin
# no need for groups - we only have regular users and superusers
admin.site.unregister(Group)
@admin.register(EmailUser)
class EmailUserAdmin(ExportCsvMixin, adm... | from django.contrib import admin
from django.contrib.auth.models import Group
from accounts.models import EmailUser
from shared.admin import ExportCsvMixin
# no need for groups - we only have regular users and superusers
admin.site.unregister(Group)
@admin.register(EmailUser)
class EmailUserAdmin(ExportCsvMixin, adm... | fr | 0.548014 | # no need for groups - we only have regular users and superusers option d'affichage des activités dans la vue django admin | 2.004182 | 2 |
rotkehlchen/exchanges/coinbase.py | vnavascues/rotki | 0 | 3750 | <reponame>vnavascues/rotki
import hashlib
import hmac
import logging
import time
from json.decoder import JSONDecodeError
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
from urllib.parse import urlencode
import requests
from rotkehlchen.assets.asset import Asset
from rotkehlchen.assets.converters ... | import hashlib
import hmac
import logging
import time
from json.decoder import JSONDecodeError
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
from urllib.parse import urlencode
import requests
from rotkehlchen.assets.asset import Asset
from rotkehlchen.assets.converters import asset_from_coinbase
... | en | 0.882554 | Turns a coinbase transaction into a rotkehlchen Trade. https://developers.coinbase.com/api/v2?python#buys If the coinbase transaction is not a trade related transaction returns None Throws: - UnknownAsset due to Asset instantiation - DeserializationError due to unexpected format of dict en... | 2.157565 | 2 |
lib/python3.7/site-packages/ldap/controls/deref.py | aonrobot/MSC-thug-auth-provider | 1 | 3751 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""
ldap.controls.deref - classes for
(see https://tools.ietf.org/html/draft-masarati-ldap-deref)
See https://www.python-ldap.org/ for project details.
"""
__all__ = [
'DEREF_CONTROL_OID',
'DereferenceControl',
]
import ldap.controls
from ldap.controls import LDAPControl,KN... | # -*- coding: utf-8 -*-
"""
ldap.controls.deref - classes for
(see https://tools.ietf.org/html/draft-masarati-ldap-deref)
See https://www.python-ldap.org/ for project details.
"""
__all__ = [
'DEREF_CONTROL_OID',
'DereferenceControl',
]
import ldap.controls
from ldap.controls import LDAPControl,KNOWN_RESPONSE_CO... | en | 0.40598 | # -*- coding: utf-8 -*- ldap.controls.deref - classes for (see https://tools.ietf.org/html/draft-masarati-ldap-deref) See https://www.python-ldap.org/ for project details. # Request types #--------------------------------------------------------------------------- # For compatibility with ASN.1 declaration in I-D # Re... | 1.865134 | 2 |
emoji.py | notagoat/Deepmoji | 1 | 3752 | import requests
import urllib.request
import os.path
import shutil
import csv
def main():
with open("data.csv") as i: #Open the data.csv file
instances = i.readlines() #Write them into memory
instances = [x.strip() for x in instances] #Strip any weird issues from writing
instances.sort() #Sort t... | import requests
import urllib.request
import os.path
import shutil
import csv
def main():
with open("data.csv") as i: #Open the data.csv file
instances = i.readlines() #Write them into memory
instances = [x.strip() for x in instances] #Strip any weird issues from writing
instances.sort() #Sort t... | en | 0.84833 | #Open the data.csv file #Write them into memory #Strip any weird issues from writing #Sort them alphabetically #Run setup to create all the necessary files and subfolders #Get the count just for fun #Run the fetching code #Print the error. We catch errors here for pleroma instances, weirdly encoded urls, etc #Don't sto... | 3.356761 | 3 |
String/640.One Edit Distance/Solution_DP.py | Zhenye-Na/LxxxCode | 12 | 3753 | class Solution:
"""
@param s: a string
@param t: a string
@return: true if they are both one edit distance apart or false
"""
def isOneEditDistance(self, s, t):
# write your code here
if s == t:
return False
if abs(len(s) - len(t)) > 1:
return Fal... | class Solution:
"""
@param s: a string
@param t: a string
@return: true if they are both one edit distance apart or false
"""
def isOneEditDistance(self, s, t):
# write your code here
if s == t:
return False
if abs(len(s) - len(t)) > 1:
return Fal... | en | 0.435747 | @param s: a string @param t: a string @return: true if they are both one edit distance apart or false # write your code here | 3.532505 | 4 |
nsq/__init__.py | jehiah/pynsq | 1 | 3754 | <gh_stars>1-10
from __future__ import absolute_import
import signal
import tornado.ioloop
import logging
from .protocol import (
Error,
unpack_response,
decode_message,
valid_topic_name,
valid_channel_name,
identify,
subscribe,
ready,
finish,
touch,
requeue,
nop,
pu... | from __future__ import absolute_import
import signal
import tornado.ioloop
import logging
from .protocol import (
Error,
unpack_response,
decode_message,
valid_topic_name,
valid_channel_name,
identify,
subscribe,
ready,
finish,
touch,
requeue,
nop,
pub,
mpub,
... | en | 0.440225 | # NOQA Starts any instantiated :class:`nsq.Reader` or :class:`nsq.Writer` | 2.032438 | 2 |
scripts/summaryPlot.py | Hespian/ParFastKer | 3 | 3755 | import get_data_ours
import get_data_akiba
import get_data_NearLinear
import get_data_LinearTime
import os
import matplotlib.pyplot as plt
# graphs = ["uk-2002", "arabic-2005", "gsh-2015-tpd", "uk-2005", "it-2004", "sk-2005", "uk-2007-05", "webbase-2001", "asia.osm", "road_usa", "europe.osm", "rgg_n26_s0", "RHG-10000... | import get_data_ours
import get_data_akiba
import get_data_NearLinear
import get_data_LinearTime
import os
import matplotlib.pyplot as plt
# graphs = ["uk-2002", "arabic-2005", "gsh-2015-tpd", "uk-2005", "it-2004", "sk-2005", "uk-2007-05", "webbase-2001", "asia.osm", "road_usa", "europe.osm", "rgg_n26_s0", "RHG-10000... | en | 0.472178 | # graphs = ["uk-2002", "arabic-2005", "gsh-2015-tpd", "uk-2005", "it-2004", "sk-2005", "uk-2007-05", "webbase-2001", "asia.osm", "road_usa", "europe.osm", "rgg_n26_s0", "RHG-100000000-nodes-2000000000-edges", "delaunay_n24", "del26"] # data = [oursequential, ourparallel, akiba, nearLinear] # print(graph + "(sequential... | 1.944531 | 2 |
bouncer/cli/base.py | lrnt/git-bouncer | 0 | 3756 | <gh_stars>0
import configparser
import sys
import inspect
from argparse import ArgumentParser, RawDescriptionHelpFormatter
def opt(*args, **kwargs):
def decorator(method):
if not hasattr(method, 'options'):
method.options = []
method.options.append((args, kwargs))
return metho... | import configparser
import sys
import inspect
from argparse import ArgumentParser, RawDescriptionHelpFormatter
def opt(*args, **kwargs):
def decorator(method):
if not hasattr(method, 'options'):
method.options = []
method.options.append((args, kwargs))
return method
return... | en | 0.638911 | # Find out which arguments the method expects # Get the expected method arguments, ignore rest # Put rest of the arguments in self | 2.794766 | 3 |
Examples/ExampleCodes_ssccoorriinngg.py | MahdadJafarzadeh/ssccoorriinngg | 2 | 3757 | <filename>Examples/ExampleCodes_ssccoorriinngg.py
#%% Import libs
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_validate
from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score
import h5py
import time
from ssccoo... | <filename>Examples/ExampleCodes_ssccoorriinngg.py
#%% Import libs
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_validate
from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score
import h5py
import time
from ssccoo... | en | 0.601383 | #%% Import libs #%% Picking featureset of interest and apply classification # Train set # Test set # Define the scoring criteria: # Cross-validation using logistic Random Forests # Cross-validation using XGBoost #%% Outcome measures # Defien required metrics here: #RF # xgb # SVM # LR #%% Applying Randomized grid searc... | 2.495492 | 2 |
igibson/examples/behavior/behavior_demo_collection.py | suresh-guttikonda/iGibson | 0 | 3758 | <reponame>suresh-guttikonda/iGibson
"""
Main BEHAVIOR demo collection entrypoint
"""
import argparse
import copy
import datetime
import os
import bddl
import numpy as np
import igibson
from igibson.activity.activity_base import iGBEHAVIORActivityInstance
from igibson.render.mesh_renderer.mesh_renderer_cpu import Mes... | """
Main BEHAVIOR demo collection entrypoint
"""
import argparse
import copy
import datetime
import os
import bddl
import numpy as np
import igibson
from igibson.activity.activity_base import iGBEHAVIORActivityInstance
from igibson.render.mesh_renderer.mesh_renderer_cpu import MeshRendererSettings
from igibson.rende... | en | 0.493283 | Main BEHAVIOR demo collection entrypoint # HDR files for PBR rendering # VR rendering settings # VR system settings | 2.028284 | 2 |
wagtail/wagtailadmin/menu.py | digitalmarmalade/wagtail | 1 | 3759 | <gh_stars>1-10
from django.utils.text import slugify
from django.utils.html import format_html
class MenuItem(object):
def __init__(self, label, url, name=None, classnames='', order=1000):
self.label = label
self.url = url
self.classnames = classnames
self.name = (name or slugify(u... | from django.utils.text import slugify
from django.utils.html import format_html
class MenuItem(object):
def __init__(self, label, url, name=None, classnames='', order=1000):
self.label = label
self.url = url
self.classnames = classnames
self.name = (name or slugify(unicode(label)))... | fa | 0.075113 | <li class="menu-{0}"><a href="{1}" class="{2}">{3}</a></li> | 2.334137 | 2 |
django_mfa/migrations/0001_initial.py | timgates42/django-mfa | 0 | 3760 | # Generated by Django 2.1.5 on 2019-03-26 11:35
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... | # Generated by Django 2.1.5 on 2019-03-26 11:35
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... | en | 0.77162 | # Generated by Django 2.1.5 on 2019-03-26 11:35 | 1.846363 | 2 |
app/logger_example/main.py | khanh-nguyen-code/my-collection | 0 | 3761 | from my_collection import logger
if __name__ == "__main__":
logger.now().debug("debug1")
logger.now().debug("debug2")
logger.now().info("hello1")
logger.now().info("hello2")
logger.now().with_field("key", "val").error("with field1")
logger.now().with_field("key", "val").error("with field2")
| from my_collection import logger
if __name__ == "__main__":
logger.now().debug("debug1")
logger.now().debug("debug2")
logger.now().info("hello1")
logger.now().info("hello2")
logger.now().with_field("key", "val").error("with field1")
logger.now().with_field("key", "val").error("with field2")
| none | 1 | 2.274148 | 2 | |
robotframework_iperf3/__main__.py | scathaig/robotframework-iperf3 | 0 | 3762 | <gh_stars>0
import argparse
from robotremoteserver import RobotRemoteServer
from .iperf3 import Iperf3
if __name__ == '__main__':
# create commandline parser
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.prog = 'python3 -m robotframework_iperf3'
# ad... | import argparse
from robotremoteserver import RobotRemoteServer
from .iperf3 import Iperf3
if __name__ == '__main__':
# create commandline parser
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.prog = 'python3 -m robotframework_iperf3'
# add parser opt... | en | 0.044978 | # create commandline parser # add parser options | 2.745499 | 3 |
h2o-docs/src/booklets/v2_2015/source/Python_Vignette_code_examples/python_combine_frames_append_one_as_columns.py | ahmedengu/h2o-3 | 6,098 | 3763 | <filename>h2o-docs/src/booklets/v2_2015/source/Python_Vignette_code_examples/python_combine_frames_append_one_as_columns.py
df8.cbind(df9)
# A B C D A0 B0 C0 D0
# ----- ------ ------ ------ ------ ----- ----- -----
# -0.09 0.944 0.160 0.271 -0.351 1.66 -2.32 -0.86
# -0.95 0.669 0.... | <filename>h2o-docs/src/booklets/v2_2015/source/Python_Vignette_code_examples/python_combine_frames_append_one_as_columns.py
df8.cbind(df9)
# A B C D A0 B0 C0 D0
# ----- ------ ------ ------ ------ ----- ----- -----
# -0.09 0.944 0.160 0.271 -0.351 1.66 -2.32 -0.86
# -0.95 0.669 0.... | en | 0.164724 | # A B C D A0 B0 C0 D0 # ----- ------ ------ ------ ------ ----- ----- ----- # -0.09 0.944 0.160 0.271 -0.351 1.66 -2.32 -0.86 # -0.95 0.669 0.664 1.535 -0.633 -1.78 0.32 1.27 # 0.17 0.657 0.970 -0.419 -1.413 -0.51 0.64 -1.25 # 0.58 -0.516 -1.598 -1.346 0.711 1.09 0.05 0... | 3.021594 | 3 |
FluentPython/dynamic_attr_and_prop/frozen_json.py | xu6148152/Binea_Python_Project | 0 | 3764 | <gh_stars>0
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
from collections import abc
from keyword import iskeyword
class FronzenJSON:
def __init__(self, mapping):
self._data = {}
for key, value in mapping.items():
if iskeyword(key):
key += '_'
# sel... | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
from collections import abc
from keyword import iskeyword
class FronzenJSON:
def __init__(self, mapping):
self._data = {}
for key, value in mapping.items():
if iskeyword(key):
key += '_'
# self._data = di... | en | 0.204915 | #!/usr/bin/env python3 # -*- encoding: utf-8 -*- # self._data = dict(mapping) # return FronzenJSON.build(self._data[name]) | 2.879601 | 3 |
pomdp_problems/tag/models/transition_model.py | Semanti1/pomdp_findit | 0 | 3765 | <reponame>Semanti1/pomdp_findit
"""The Tag problem. Implemented according to the paper `Anytime Point-Based
Approximations for Large POMDPs <https://arxiv.org/pdf/1110.0027.pdf>`_.
Transition model: the robot moves deterministically. The target's movement
depends on the robot; With Pr=0.8 the target moves away... | """The Tag problem. Implemented according to the paper `Anytime Point-Based
Approximations for Large POMDPs <https://arxiv.org/pdf/1110.0027.pdf>`_.
Transition model: the robot moves deterministically. The target's movement
depends on the robot; With Pr=0.8 the target moves away from the robot,
and with P... | en | 0.777818 | The Tag problem. Implemented according to the paper `Anytime Point-Based
Approximations for Large POMDPs <https://arxiv.org/pdf/1110.0027.pdf>`_.
Transition model: the robot moves deterministically. The target's movement
depends on the robot; With Pr=0.8 the target moves away from the robot,
and with Pr=0... | 2.541597 | 3 |
packit/fedpkg.py | bocekm/packit | 0 | 3766 | <gh_stars>0
# MIT License
#
# Copyright (c) 2019 Red Hat, Inc.
# 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, mo... | # MIT License
#
# Copyright (c) 2019 Red Hat, Inc.
# 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,... | en | 0.792416 | # MIT License # # Copyright (c) 2019 Red Hat, Inc. # 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, ... | 1.750785 | 2 |
tests/test_MaskedArrayCollection.py | ahaldane/NDducktype_tests | 3 | 3767 | #!/usr/bin/env python
from ndarray_ducktypes.ArrayCollection import ArrayCollection
from ndarray_ducktypes.MaskedArray import MaskedArray
from ndarray_ducktypes.MaskedArrayCollection import MaskedArrayCollection
import numpy as np
# Tests for Masked ArrayCollections.
#
# First try: Simply make an arraycollection of Ma... | #!/usr/bin/env python
from ndarray_ducktypes.ArrayCollection import ArrayCollection
from ndarray_ducktypes.MaskedArray import MaskedArray
from ndarray_ducktypes.MaskedArrayCollection import MaskedArrayCollection
import numpy as np
# Tests for Masked ArrayCollections.
#
# First try: Simply make an arraycollection of Ma... | en | 0.618626 | #!/usr/bin/env python # Tests for Masked ArrayCollections. # # First try: Simply make an arraycollection of MaskedArrays. Downside: this # strategy does not give a "filled" method. Probably to get a masked # ArrayCollection we should really subclass ArrayCollection to have a # fill_value and a filled() method #a = Mask... | 3.078651 | 3 |
src/models/text_node.py | moevm/nosql1h19-text-graph | 0 | 3768 | <gh_stars>0
from neomodel import StructuredNode, StringProperty, JSONProperty, \
Relationship, IntegerProperty
import numpy as np
import re
from models.text_relation import TextRelation
__all__ = ['TextNode']
class TextNode(StructuredNode):
order_id = IntegerProperty(required=True, unique_... | from neomodel import StructuredNode, StringProperty, JSONProperty, \
Relationship, IntegerProperty
import numpy as np
import re
from models.text_relation import TextRelation
__all__ = ['TextNode']
class TextNode(StructuredNode):
order_id = IntegerProperty(required=True, unique_index=True)
... | ru | 0.244067 | <h1>Фрагмент: {self.order_id} </h1> <table border="1" width=100%> <caption> Информация о вершине </caption> <tr> <th>Количество символов</th> <td>{self.character_num()}</td> </tr> ... | 2.519123 | 3 |
tests/test_bishop_generate.py | otaviocarvalho/chess-negamax | 6 | 3769 | import unittest
from .helpers import StubBoard, StubPiece, C, WHITE, BLACK
class TestBishopGenerate(unittest.TestCase):
def get_bishop(self, board, team, position):
from chess.models import Bishop
return Bishop(board, team, position)
def compare_list(self, expected, results):
compared ... | import unittest
from .helpers import StubBoard, StubPiece, C, WHITE, BLACK
class TestBishopGenerate(unittest.TestCase):
def get_bishop(self, board, team, position):
from chess.models import Bishop
return Bishop(board, team, position)
def compare_list(self, expected, results):
compared ... | none | 1 | 2.994596 | 3 | |
lib/fmdplugins/list_records.py | GonzaloAlvarez/py-ga-sysadmin | 2 | 3770 | from lib.fmd.namedentity import NamedEntity
from lib.fmd.decorators import Action, ListStage, GetStage
from lib.exceptions.workflow import EntryException
@Action(ListStage.DATAGATHERING)
def list_records(context, output):
output = []
if hasattr(context, 'filter'):
context.log.debug('Using filter [%s]'... | from lib.fmd.namedentity import NamedEntity
from lib.fmd.decorators import Action, ListStage, GetStage
from lib.exceptions.workflow import EntryException
@Action(ListStage.DATAGATHERING)
def list_records(context, output):
output = []
if hasattr(context, 'filter'):
context.log.debug('Using filter [%s]'... | none | 1 | 2.122839 | 2 | |
pysoa/server/action/switched.py | zetahernandez/pysoa | 0 | 3771 | <gh_stars>0
from __future__ import (
absolute_import,
unicode_literals,
)
import abc
import six
from pysoa.server.internal.types import is_switch
__all__ = (
'SwitchedAction',
)
def _len(item):
# Safe length that won't raise an error on values that don't support length
return getattr(item, '_... | from __future__ import (
absolute_import,
unicode_literals,
)
import abc
import six
from pysoa.server.internal.types import is_switch
__all__ = (
'SwitchedAction',
)
def _len(item):
# Safe length that won't raise an error on values that don't support length
return getattr(item, '__len__', lam... | en | 0.859666 | # Safe length that won't raise an error on values that don't support length Validate the switch_to_action_map when the class is created, instead of doing it every time the class is instantiated. This identifies problems earlier (on import) and improves performance by not performing this validation every... | 2.460132 | 2 |
Seeder/settings/tests.py | WebarchivCZ/Seeder | 8 | 3772 | from .base import *
SECRET_KEY = 'test'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['127.0.0.1']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'sqlite3.db',
'USER': '',
'PASSWO... | from .base import *
SECRET_KEY = 'test'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['127.0.0.1']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'sqlite3.db',
'USER': '',
'PASSWO... | en | 0.953551 | # SECURITY WARNING: don't run with debug turned on in production! | 1.468254 | 1 |
blobStore.py | odeke-em/resty | 0 | 3773 | #!/usr/bin/env python3
# Author: <NAME> <<EMAIL>>
# This example steps you through using resty & restAssured to save pickled/serialized
# data as a blob and then later re-using it in after deserialization.
# Sample usage might be in collaborative computing ie publish results from an expensive
# computation on one mach... | #!/usr/bin/env python3
# Author: <NAME> <<EMAIL>>
# This example steps you through using resty & restAssured to save pickled/serialized
# data as a blob and then later re-using it in after deserialization.
# Sample usage might be in collaborative computing ie publish results from an expensive
# computation on one mach... | en | 0.888333 | #!/usr/bin/env python3 # Author: <NAME> <<EMAIL>> # This example steps you through using resty & restAssured to save pickled/serialized # data as a blob and then later re-using it in after deserialization. # Sample usage might be in collaborative computing ie publish results from an expensive # computation on one machi... | 2.96372 | 3 |
venv/Lib/site-packages/dataframe/_dataframe_column_set.py | kavanAdeshara/Expense_Tracker | 0 | 3774 | # dataframe: a data-frame implementation using method piping
#
# Copyright (C) 2016 <NAME>
#
# This file is part of dataframe.
#
# dataframe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of ... | # dataframe: a data-frame implementation using method piping
#
# Copyright (C) 2016 <NAME>
#
# This file is part of dataframe.
#
# dataframe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of ... | en | 0.807642 | # dataframe: a data-frame implementation using method piping # # Copyright (C) 2016 <NAME> # # This file is part of dataframe. # # dataframe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of ... | 3.363556 | 3 |
java/image.bzl | Springworks/rules_docker | 0 | 3775 | # Copyright 2017 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 a... | # Copyright 2017 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 a... | en | 0.886829 | # Copyright 2017 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 a... | 1.782635 | 2 |
cupyx/jit/_builtin_funcs.py | khushi-411/cupy | 0 | 3776 | import warnings
import cupy
from cupy_backends.cuda.api import runtime
from cupy.cuda import device
from cupyx.jit import _cuda_types
from cupyx.jit._internal_types import BuiltinFunc
from cupyx.jit._internal_types import Data
from cupyx.jit._internal_types import Constant
from cupyx.jit._internal_types import Range
... | import warnings
import cupy
from cupy_backends.cuda.api import runtime
from cupy.cuda import device
from cupyx.jit import _cuda_types
from cupyx.jit._internal_types import BuiltinFunc
from cupyx.jit._internal_types import Data
from cupyx.jit._internal_types import Constant
from cupyx.jit._internal_types import Range
... | en | 0.652596 | Range with loop unrolling support. Args: start (int): Same as that of built-in :obj:`range`. stop (int): Same as that of built-in :obj:`range`. step (int): Same as that of built-in :obj:`range`. unroll (int or bool ... | 2.233002 | 2 |
python-basic-grammer/python-basic/02-python-variables-and-string/string_strip_demo.py | jinrunheng/base-of-python | 0 | 3777 | # 字符串删除空白
str1 = " hello "
print(str1)
print(len(str1))
# 去除两端的空格
print(str1.strip())
print(len(str1.strip()))
# 去除左侧的空格
print(str1.lstrip())
print(len(str1.lstrip()))
# 去除右侧的空格
print(str1.rstrip())
print(len(str1.rstrip())) | # 字符串删除空白
str1 = " hello "
print(str1)
print(len(str1))
# 去除两端的空格
print(str1.strip())
print(len(str1.strip()))
# 去除左侧的空格
print(str1.lstrip())
print(len(str1.lstrip()))
# 去除右侧的空格
print(str1.rstrip())
print(len(str1.rstrip())) | zh | 0.885649 | # 字符串删除空白 # 去除两端的空格 # 去除左侧的空格 # 去除右侧的空格 | 3.980923 | 4 |
bruges/util/__init__.py | hyperiongeo/bruges | 0 | 3778 | <filename>bruges/util/__init__.py<gh_stars>0
# -*- coding: utf-8 -*-
from .util import rms
from .util import moving_average
from .util import moving_avg_conv
from .util import moving_avg_fft
from .util import normalize
from .util import next_pow2
from .util import top_and_tail
from .util import extrapolate
from .util i... | <filename>bruges/util/__init__.py<gh_stars>0
# -*- coding: utf-8 -*-
from .util import rms
from .util import moving_average
from .util import moving_avg_conv
from .util import moving_avg_fft
from .util import normalize
from .util import next_pow2
from .util import top_and_tail
from .util import extrapolate
from .util i... | en | 0.769321 | # -*- coding: utf-8 -*- | 1.376829 | 1 |
toontown/estate/DistributedHouseDoor.py | CrankySupertoon01/Toontown-2 | 1 | 3779 | <gh_stars>1-10
from toontown.toonbase.ToonBaseGlobal import *
from panda3d.core import *
from direct.interval.IntervalGlobal import *
from direct.distributed.ClockDelta import *
from direct.distributed import DistributedObject
from toontown.toonbase import ToontownGlobals
from direct.directnotify import DirectNotifyGlo... | from toontown.toonbase.ToonBaseGlobal import *
from panda3d.core import *
from direct.interval.IntervalGlobal import *
from direct.distributed.ClockDelta import *
from direct.distributed import DistributedObject
from toontown.toonbase import ToontownGlobals
from direct.directnotify import DirectNotifyGlobal
from direct... | none | 1 | 1.782233 | 2 | |
Neuro-Cognitive Models/Runs/Nonhier_run/res_nonhier.py | AGhaderi/spatial_attenNCM | 0 | 3780 | #!/home/a.ghaderi/.conda/envs/envjm/bin/python
# Model 2
import pystan
import pandas as pd
import numpy as np
import sys
sys.path.append('../../')
import utils
parts = 1
data = utils.get_data() #loading dateset
data = data[data['participant']==parts]
mis = np.where((data['n200lat']<.101)|(data['n200lat']>.... | #!/home/a.ghaderi/.conda/envs/envjm/bin/python
# Model 2
import pystan
import pandas as pd
import numpy as np
import sys
sys.path.append('../../')
import utils
parts = 1
data = utils.get_data() #loading dateset
data = data[data['participant']==parts]
mis = np.where((data['n200lat']<.101)|(data['n200lat']>.... | en | 0.755119 | #!/home/a.ghaderi/.conda/envs/envjm/bin/python # Model 2 #loading dateset # missing data for n200lat # observation and missing data for n200lat # number of missing data # number of observed data #reading the model span # Compile the model stan #Number of coherence conditions #Number of spatial conditions #Number of con... | 2.319272 | 2 |
rq_dashboard/dashboard.py | refgenomics/rq-dashboard | 0 | 3781 | <reponame>refgenomics/rq-dashboard<gh_stars>0
from redis import Redis
from redis import from_url
from rq import push_connection, pop_connection
from rq.job import Job
from functools import wraps
import times
from flask import Blueprint
from flask import current_app, url_for, abort
from flask import render_template
from... | from redis import Redis
from redis import from_url
from rq import push_connection, pop_connection
from rq.job import Job
from functools import wraps
import times
from flask import Blueprint
from flask import current_app, url_for, abort
from flask import render_template
from rq import Queue, Worker
from rq import cancel... | en | 0.901051 | Allow the parent app to authenticate user's access to the dashboard with it's own auth_handler method that must return True or False # Show the failed queue by default if it contains any jobs | 2.218834 | 2 |
layers/layer1_python3/0300_acquisition/acquisition/__init__.py | moas/mfdata | 0 | 3782 | from acquisition.step import AcquisitionStep
from acquisition.stats import AcquisitionStatsDClient
from acquisition.move_step import AcquisitionMoveStep
from acquisition.delete_step import AcquisitionDeleteStep
from acquisition.batch_step import AcquisitionBatchStep
from acquisition.reinject_step import AcquisitionRein... | from acquisition.step import AcquisitionStep
from acquisition.stats import AcquisitionStatsDClient
from acquisition.move_step import AcquisitionMoveStep
from acquisition.delete_step import AcquisitionDeleteStep
from acquisition.batch_step import AcquisitionBatchStep
from acquisition.reinject_step import AcquisitionRein... | none | 1 | 1.333144 | 1 | |
frappe-bench/apps/erpnext/erpnext/non_profit/doctype/member/member.py | Semicheche/foa_frappe_docker | 0 | 3783 | # -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
from frappe.model.document import Document
from frappe.contacts.address_and_contact import load_address_and_contact
class Member(Docum... | # -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
from frappe.model.document import Document
from frappe.contacts.address_and_contact import load_address_and_contact
class Member(Docum... | en | 0.744322 | # -*- coding: utf-8 -*- # Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt Load address and contacts in `__onload` | 2.091041 | 2 |
networks/networks.py | ayyuriss/TRHPO | 0 | 3784 | <reponame>ayyuriss/TRHPO
from torch import nn
import numpy as np
import base.basenetwork as BaseN
from networks.cholesky import CholeskyBlock
class FCNet(BaseN.BaseNetwork):
name ="FCNet"
def __init__(self,input_shape,output_shape,owner_name=""):
super(FCNet,self).__init__(input_shape,output_shape,owne... | from torch import nn
import numpy as np
import base.basenetwork as BaseN
from networks.cholesky import CholeskyBlock
class FCNet(BaseN.BaseNetwork):
name ="FCNet"
def __init__(self,input_shape,output_shape,owner_name=""):
super(FCNet,self).__init__(input_shape,output_shape,owner_name)
... | none | 1 | 2.565292 | 3 | |
icenews/api_important_words.py | sverrirab/icenews | 4 | 3785 | import logging
from pydantic import BaseModel, Field
from typing import List
from .similar import important_words
from .server import app
_MAX_LENGTH = 2000
logger = logging.getLogger(__name__)
class ImportantWordsResponse(BaseModel):
important_words: List[str] = Field(..., description="List of lemmas")
cla... | import logging
from pydantic import BaseModel, Field
from typing import List
from .similar import important_words
from .server import app
_MAX_LENGTH = 2000
logger = logging.getLogger(__name__)
class ImportantWordsResponse(BaseModel):
important_words: List[str] = Field(..., description="List of lemmas")
cla... | en | 0.74749 | # Strange things happen with error handling when using alias - splitting up into two input models | 2.417684 | 2 |
try-except.py | kmarcini/Learn-Python---Full-Course-for-Beginners-Tutorial- | 0 | 3786 | <reponame>kmarcini/Learn-Python---Full-Course-for-Beginners-Tutorial-<filename>try-except.py
try:
# num = 10 / 0
number = int(input("Enter a number: "))
print(number)
# catch specific errors
except ZeroDivisionError as err:
print(err)
except ValueError:
print("Invalid input")
| try:
# num = 10 / 0
number = int(input("Enter a number: "))
print(number)
# catch specific errors
except ZeroDivisionError as err:
print(err)
except ValueError:
print("Invalid input") | en | 0.506247 | # num = 10 / 0 # catch specific errors | 3.672957 | 4 |
peaksampl.py | Gattocrucco/sipmfilter | 0 | 3787 | <reponame>Gattocrucco/sipmfilter
import numpy as np
def _adddims(a, b):
n = max(a.ndim, b.ndim)
a = np.expand_dims(a, tuple(range(n - a.ndim)))
b = np.expand_dims(b, tuple(range(n - b.ndim)))
return a, b
def _yz(y, z, t, yout):
"""
Shared implementation of peaksampl and sumpeaks.
"""
y... | import numpy as np
def _adddims(a, b):
n = max(a.ndim, b.ndim)
a = np.expand_dims(a, tuple(range(n - a.ndim)))
b = np.expand_dims(b, tuple(range(n - b.ndim)))
return a, b
def _yz(y, z, t, yout):
"""
Shared implementation of peaksampl and sumpeaks.
"""
y = np.asarray(y)
z = np.asarr... | en | 0.817182 | Shared implementation of peaksampl and sumpeaks. Get peak amplitudes given their sum. This assumes that the position of the signals is given by peaks positions even when they are summed. Parameters ---------- y : array (..., M,) The single signal shape. z : array (..., N,) ... | 2.656549 | 3 |
arachne/hdl/xilinx/ps8/resources/pmu.py | shrine-maiden-heavy-industries/arachne | 3 | 3788 | <reponame>shrine-maiden-heavy-industries/arachne<filename>arachne/hdl/xilinx/ps8/resources/pmu.py<gh_stars>1-10
# SPDX-License-Identifier: BSD-3-Clause
from amaranth import *
from amaranth.build import *
from .common import PS8Resource, MIOSet
__all__ = (
'PMUResource',
)
class PMUResource(PS8Resource)... | # SPDX-License-Identifier: BSD-3-Clause
from amaranth import *
from amaranth.build import *
from .common import PS8Resource, MIOSet
__all__ = (
'PMUResource',
)
class PMUResource(PS8Resource):
name = 'pmu'
claimable_mio = [ ]
def __init__(self):
super().__init__(0, 0, None, False)
def used_mio(... | de | 0.317936 | # SPDX-License-Identifier: BSD-3-Clause # :nocov: # :nocov: | 1.956491 | 2 |
backend/Washlist/tests.py | henrikhorluck/tdt4140-washlists | 0 | 3789 | <filename>backend/Washlist/tests.py
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from Dormroom.models import Dormroom
from SIFUser.mixins import AuthTestMixin
from StudentVillage.models import StudentVillage
from Washlist.jobs import reset_washlists
from Washlist.... | <filename>backend/Washlist/tests.py
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from Dormroom.models import Dormroom
from SIFUser.mixins import AuthTestMixin
from StudentVillage.models import StudentVillage
from Washlist.jobs import reset_washlists
from Washlist.... | en | 0.911444 | Create a Washlist item that is completed the method also sets up a village and a room to relate the Washlist item to satisfy the db constraints Test that job to reset Washlist items when run manually actually rests the databases Washlist items | 2.5165 | 3 |
torchvision/prototype/models/mobilenetv3.py | piyush01123/vision | 0 | 3790 | from functools import partial
from typing import Any, Optional, List
from torchvision.prototype.transforms import ImageNetEval
from torchvision.transforms.functional import InterpolationMode
from ...models.mobilenetv3 import MobileNetV3, _mobilenet_v3_conf, InvertedResidualConfig
from ._api import WeightsEnum, Weight... | from functools import partial
from typing import Any, Optional, List
from torchvision.prototype.transforms import ImageNetEval
from torchvision.transforms.functional import InterpolationMode
from ...models.mobilenetv3 import MobileNetV3, _mobilenet_v3_conf, InvertedResidualConfig
from ._api import WeightsEnum, Weight... | en | 0.407429 | #mobilenetv3-large--small", #new-recipe-with-reg-tuning", #mobilenetv3-large--small", | 2.130223 | 2 |
rest_auth/registration/urls.py | soul4code/django-rest-auth | 0 | 3791 | from django.urls import re_path
from django.views.generic import TemplateView
from .views import RegisterView, VerifyEmailView
urlpatterns = [
re_path(r'^$', RegisterView.as_view(), name='rest_register'),
re_path(r'^verify-email/$', VerifyEmailView.as_view(), name='rest_verify_email'),
# This url is use... | from django.urls import re_path
from django.views.generic import TemplateView
from .views import RegisterView, VerifyEmailView
urlpatterns = [
re_path(r'^$', RegisterView.as_view(), name='rest_register'),
re_path(r'^verify-email/$', VerifyEmailView.as_view(), name='rest_verify_email'),
# This url is use... | en | 0.848344 | # This url is used by django-allauth and empty TemplateView is # defined just to allow reverse() call inside app, for example when email # with verification link is being sent, then it's required to render email # content. # account_confirm_email - You should override this view to handle it in # your API client somehow... | 1.852597 | 2 |
crawler/tests.py | mental689/paddict | 1 | 3792 | from django.test import TestCase
# Create your tests here.
from crawler.download import *
from crawler.models import *
class AnimalDownloadTestCase(TestCase):
def setUp(self):
self.stopWords = ["CVPR 2019", "Computer Vision Foundation."]
self.url = "/Users/tuannguyenanh/Desktop/cvpr2019.html"#"htt... | from django.test import TestCase
# Create your tests here.
from crawler.download import *
from crawler.models import *
class AnimalDownloadTestCase(TestCase):
def setUp(self):
self.stopWords = ["CVPR 2019", "Computer Vision Foundation."]
self.url = "/Users/tuannguyenanh/Desktop/cvpr2019.html"#"htt... | en | 0.500157 | # Create your tests here. #print(get_html(self.url)) #print(bibtexs) | 2.43295 | 2 |
test_scripts/xml_example.py | petervdb/testrep1 | 1 | 3793 | <gh_stars>1-10
#!/usr/bin/python3
from urllib.request import urlopen
from xml.etree.ElementTree import parse
# Download the RSS feed and parse it
u = urlopen('http://planet.python.org/rss20.xml')
doc = parse(u)
# Extract and output tags of interest
for item in doc.iterfind('channel/item'):
title = item.findtext('ti... | #!/usr/bin/python3
from urllib.request import urlopen
from xml.etree.ElementTree import parse
# Download the RSS feed and parse it
u = urlopen('http://planet.python.org/rss20.xml')
doc = parse(u)
# Extract and output tags of interest
for item in doc.iterfind('channel/item'):
title = item.findtext('title')
date = i... | en | 0.535322 | #!/usr/bin/python3 # Download the RSS feed and parse it # Extract and output tags of interest | 3.284784 | 3 |
contacts/urls.py | anthowen/duplify | 1 | 3794 | """dedupper_app URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-... | """dedupper_app URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-... | en | 0.390205 | dedupper_app URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-bas... | 2.579752 | 3 |
pydm/PyQt/uic.py | klauer/pydm | 0 | 3795 | <gh_stars>0
from . import qtlib
QT_LIB = qtlib.QT_LIB
if QT_LIB == 'PyQt5':
from PyQt5.uic import *
| from . import qtlib
QT_LIB = qtlib.QT_LIB
if QT_LIB == 'PyQt5':
from PyQt5.uic import * | none | 1 | 1.268222 | 1 | |
CPB100/lab2b/scheduled/ingestapp.py | pranaynanda/training-data-analyst | 0 | 3796 | #!/usr/bin/env python
# Copyright 2016 Google Inc.
#
# 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 ... | #!/usr/bin/env python
# Copyright 2016 Google Inc.
#
# 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 ... | en | 0.802968 | #!/usr/bin/env python # Copyright 2016 Google Inc. # # 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 ... | 2.385305 | 2 |
index.py | StarSky1/microsoft-python-study | 0 | 3797 | name=input('input your name:');
print('hello');
print(name.capitalize()); | name=input('input your name:');
print('hello');
print(name.capitalize()); | none | 1 | 3.626682 | 4 | |
credentials.py | Machel54/-pass-locker- | 0 | 3798 | import pyperclip
import random
import string
class Credential:
'''
class that generates new credentials
'''
credential_list = []
def __init__(self,username,sitename,password):
self.username = username
self.password = password
self.sitename = sitename
def save_credential(self):
'''
sav... | import pyperclip
import random
import string
class Credential:
'''
class that generates new credentials
'''
credential_list = []
def __init__(self,username,sitename,password):
self.username = username
self.password = password
self.sitename = sitename
def save_credential(self):
'''
sav... | en | 0.881198 | class that generates new credentials save_cred method saves the user objects into creds_list Class method to show the list of credentials saved delete_contact method deletes a saved credential from the credential_list Function to generate a password where a user can generate a password based on their length of choice #... | 3.706204 | 4 |
tests/test_dice.py | mehulsatardekar/dice-on-demand | 1 | 3799 | <reponame>mehulsatardekar/dice-on-demand
import unittest
import app
def test_test():
assert app.test() == "Works!"
| import unittest
import app
def test_test():
assert app.test() == "Works!" | none | 1 | 2.063394 | 2 |