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 |
|---|---|---|---|---|---|---|---|---|---|---|
parliament_proposal_fetcher.py | Track-your-parliament/track-your-parliament-data | 0 | 7900 | import urllib.request, json
import pandas as pd
baseUrl = 'https://avoindata.eduskunta.fi/api/v1/tables/VaskiData'
parameters = 'rows?columnName=Eduskuntatunnus&columnValue=LA%25&perPage=100'
page = 0
df = ''
while True:
print(f'Fetching page number {page}')
with urllib.request.urlopen(f'{baseUrl}/{parameters... | import urllib.request, json
import pandas as pd
baseUrl = 'https://avoindata.eduskunta.fi/api/v1/tables/VaskiData'
parameters = 'rows?columnName=Eduskuntatunnus&columnValue=LA%25&perPage=100'
page = 0
df = ''
while True:
print(f'Fetching page number {page}')
with urllib.request.urlopen(f'{baseUrl}/{parameters... | none | 1 | 3.306531 | 3 | |
examples/Catboost_regression-scorer_usage.py | emaldonadocruz/UTuning | 0 | 7901 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 20 16:15:37 2021
@author: em42363
"""
# In[1]: Import functions
'''
CatBoost is a high-performance open source library for gradient boosting
on decision trees
'''
from catboost import CatBoostRegressor
from sklearn.model_selection import train_test_split
import pandas a... | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 20 16:15:37 2021
@author: em42363
"""
# In[1]: Import functions
'''
CatBoost is a high-performance open source library for gradient boosting
on decision trees
'''
from catboost import CatBoostRegressor
from sklearn.model_selection import train_test_split
import pandas a... | en | 0.642221 | # -*- coding: utf-8 -*- Created on Mon Sep 20 16:15:37 2021 @author: em42363 # In[1]: Import functions CatBoost is a high-performance open source library for gradient boosting on decision trees #df = pd.read_csv(r'C:\Users\eduar\OneDrive\PhD\UTuning\dataset\unconv_MV.csv') # In[1]: Split train test Perform split train... | 2.709847 | 3 |
sujson/_logger.py | PotasnikM/translator-to-suJSON | 2 | 7902 | import logging
from platform import system
from tqdm import tqdm
from multiprocessing import Lock
loggers = {}
# https://stackoverflow.com/questions/38543506/
class TqdmLoggingHandler(logging.Handler):
def __init__(self, level=logging.NOTSET):
super(TqdmLoggingHandler, self).__init__(level)
def emit... | import logging
from platform import system
from tqdm import tqdm
from multiprocessing import Lock
loggers = {}
# https://stackoverflow.com/questions/38543506/
class TqdmLoggingHandler(logging.Handler):
def __init__(self, level=logging.NOTSET):
super(TqdmLoggingHandler, self).__init__(level)
def emit... | en | 0.479285 | # https://stackoverflow.com/questions/38543506/ Create a logger with a certain name and level # if (logger.hasHandlers()): # logger.handlers.clear() | 2.602909 | 3 |
face-detect.py | Gicehajunior/face-recognition-detection-OpenCv-Python | 0 | 7903 | import cv2
import sys
import playsound
face_cascade = cv2.CascadeClassifier('cascades/haarcascade_frontalface_default.xml')
# capture video using cv2
video_capture = cv2.VideoCapture(0)
while True:
# capture frame by frame, i.e, one by one
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame... | import cv2
import sys
import playsound
face_cascade = cv2.CascadeClassifier('cascades/haarcascade_frontalface_default.xml')
# capture video using cv2
video_capture = cv2.VideoCapture(0)
while True:
# capture frame by frame, i.e, one by one
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame... | en | 0.860185 | # capture video using cv2 # capture frame by frame, i.e, one by one # for each face on the projected on the frame # minSize(35, 35) # loop through the video faces for detection | 3.127979 | 3 |
sis/enrollments.py | ryanlovett/sis-cli | 0 | 7904 | # vim:set et sw=4 ts=4:
import logging
import sys
import jmespath
from . import sis, classes
# logging
logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
logger = logging.getLogger(__name__)
# SIS endpoint
enrollments_uri = "https://apis.berkeley.edu/sis/v2/enrollments"
# apparently some courses have LA... | # vim:set et sw=4 ts=4:
import logging
import sys
import jmespath
from . import sis, classes
# logging
logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
logger = logging.getLogger(__name__)
# SIS endpoint
enrollments_uri = "https://apis.berkeley.edu/sis/v2/enrollments"
# apparently some courses have LA... | en | 0.800737 | # vim:set et sw=4 ts=4: # logging # SIS endpoint # apparently some courses have LAB without LEC (?) Gets a students enrollments. # maximum Gets a course section's enrollments. # maximum Return a section's course ID, e.g. "15807". Return a section's subject area, e.g. "STAT". Return a section's formatted catalog number,... | 2.044141 | 2 |
app.py | Nishanth-Gobi/Da-Vinci-Code | 0 | 7905 | from flask import Flask, render_template, request, redirect, url_for
from os.path import join
from stego import Steganography
app = Flask(__name__)
UPLOAD_FOLDER = 'static/files/'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
@app.route("/")
def home():
return render_te... | from flask import Flask, render_template, request, redirect, url_for
from os.path import join
from stego import Steganography
app = Flask(__name__)
UPLOAD_FOLDER = 'static/files/'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
@app.route("/")
def home():
return render_te... | en | 0.762725 | # Check if the user has entered the secret message | 2.594015 | 3 |
imitation_learning/generate_demonstrations/gen_envs.py | HaiDangDang/2020-flatland | 1 | 7906 | from flatland.envs.agent_utils import RailAgentStatus
from flatland.envs.malfunction_generators import malfunction_from_params, MalfunctionParameters
from flatland.envs.observations import GlobalObsForRailEnv
from flatland.envs.rail_env import RailEnv
from flatland.envs.rail_generators import sparse_rail_generator
from... | from flatland.envs.agent_utils import RailAgentStatus
from flatland.envs.malfunction_generators import malfunction_from_params, MalfunctionParameters
from flatland.envs.observations import GlobalObsForRailEnv
from flatland.envs.rail_env import RailEnv
from flatland.envs.rail_generators import sparse_rail_generator
from... | en | 0.248223 | #, 10 + random.randint(0, 10)) #return tid >= 3 #if not ShouldRunTest(test_id): # continue #stochastic_data = {'malfunction_rate': malfunction_rate, # 'min_duration': malfunction_min_duration, # 'max_duration': malfunction_max_duration # } #env = create_test_env(R... | 1.791044 | 2 |
job-queue-portal/postgres_django_queue/djangoenv/lib/python3.8/site-packages/django_celery_results/migrations/0006_taskresult_date_created.py | Sruthi-Ganesh/postgres-django-queue | 0 | 7907 | # -*- coding: utf-8 -*-
# Generated by Django 2.2.4 on 2019-08-21 19:53
# this file is auto-generated so don't do flake8 on it
# flake8: noqa
from __future__ import absolute_import, unicode_literals
from django.db import migrations, models
import django.utils.timezone
def copy_date_done_to_date_created(apps, schem... | # -*- coding: utf-8 -*-
# Generated by Django 2.2.4 on 2019-08-21 19:53
# this file is auto-generated so don't do flake8 on it
# flake8: noqa
from __future__ import absolute_import, unicode_literals
from django.db import migrations, models
import django.utils.timezone
def copy_date_done_to_date_created(apps, schem... | en | 0.775403 | # -*- coding: utf-8 -*- # Generated by Django 2.2.4 on 2019-08-21 19:53 # this file is auto-generated so don't do flake8 on it # flake8: noqa # the reverse of 'copy_date_done_to_date_created' is do nothing # because the 'date_created' will be removed. | 2.172062 | 2 |
remediar/modules/http/__init__.py | fabaff/remediar | 0 | 7908 | <filename>remediar/modules/http/__init__.py
"""Support for HTTP or web server issues."""
| <filename>remediar/modules/http/__init__.py
"""Support for HTTP or web server issues."""
| en | 0.710091 | Support for HTTP or web server issues. | 1.279388 | 1 |
Image Recognition/utils/BayesianModels/Bayesian3Conv3FC.py | AlanMorningLight/PyTorch-BayesianCNN | 1 | 7909 | import torch.nn as nn
from utils.BBBlayers import BBBConv2d, BBBLinearFactorial, FlattenLayer
class BBB3Conv3FC(nn.Module):
"""
Simple Neural Network having 3 Convolution
and 3 FC layers with Bayesian layers.
"""
def __init__(self, outputs, inputs):
super(BBB3Conv3FC, self).__init__()
... | import torch.nn as nn
from utils.BBBlayers import BBBConv2d, BBBLinearFactorial, FlattenLayer
class BBB3Conv3FC(nn.Module):
"""
Simple Neural Network having 3 Convolution
and 3 FC layers with Bayesian layers.
"""
def __init__(self, outputs, inputs):
super(BBB3Conv3FC, self).__init__()
... | en | 0.903543 | Simple Neural Network having 3 Convolution and 3 FC layers with Bayesian layers. | 2.884863 | 3 |
custom_scripts/load_animals.py | nphilou/influence-release | 0 | 7910 | import os
from tensorflow.contrib.learn.python.learn.datasets import base
import numpy as np
import IPython
from subprocess import call
from keras.preprocessing import image
from influence.dataset import DataSet
from influence.inception_v3 import preprocess_input
BASE_DIR = 'data' # TODO: change
def fill(X, Y, id... | import os
from tensorflow.contrib.learn.python.learn.datasets import base
import numpy as np
import IPython
from subprocess import call
from keras.preprocessing import image
from influence.dataset import DataSet
from influence.inception_v3 import preprocess_input
BASE_DIR = 'data' # TODO: change
def fill(X, Y, id... | en | 0.608122 | # TODO: change # X_valid = np.zeros([num_valid_examples, img_side, img_side, num_channels]) # Y_valid = np.zeros([num_valid_examples]) # For some reason, a lot of numbers are skipped. # validation = DataSet(X_valid, Y_valid) # Returns all class 0 # Hack to get the image files in the right order # image_files = [image_f... | 2.286287 | 2 |
src/qiskit_aws_braket_provider/awsbackend.py | carstenblank/qiskit-aws-braket-provider | 7 | 7911 | <reponame>carstenblank/qiskit-aws-braket-provider
# Copyright 2020 <NAME>
#
# 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 require... | # Copyright 2020 <NAME>
#
# 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... | en | 0.70666 | # Copyright 2020 <NAME> # # 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... | 1.407782 | 1 |
test/unit/Algorithms/GenericLinearTransportTest.py | thirtywang/OpenPNM | 0 | 7912 | import OpenPNM
import numpy as np
import OpenPNM.Physics.models as pm
class GenericLinearTransportTest:
def setup_class(self):
self.net = OpenPNM.Network.Cubic(shape=[5, 5, 5])
self.phase = OpenPNM.Phases.GenericPhase(network=self.net)
Ps = self.net.Ps
Ts = self.net.Ts
self... | import OpenPNM
import numpy as np
import OpenPNM.Physics.models as pm
class GenericLinearTransportTest:
def setup_class(self):
self.net = OpenPNM.Network.Cubic(shape=[5, 5, 5])
self.phase = OpenPNM.Phases.GenericPhase(network=self.net)
Ps = self.net.Ps
Ts = self.net.Ts
self... | none | 1 | 2.206882 | 2 | |
EC2 Auto Clean Room Forensics/Lambda-Functions/snapshotForRemediation.py | spartantri/aws-security-automation | 0 | 7913 | <filename>EC2 Auto Clean Room Forensics/Lambda-Functions/snapshotForRemediation.py
# MIT No Attribution
# 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... | <filename>EC2 Auto Clean Room Forensics/Lambda-Functions/snapshotForRemediation.py
# MIT No Attribution
# 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... | en | 0.728042 | # MIT No Attribution # 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, publish, distribute, sublicens... | 2.239901 | 2 |
gpu_bdb/queries/q26/gpu_bdb_query_26.py | VibhuJawa/gpu-bdb | 62 | 7914 | <reponame>VibhuJawa/gpu-bdb<gh_stars>10-100
#
# Copyright (c) 2019-2022, NVIDIA CORPORATION.
#
# 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... | #
# Copyright (c) 2019-2022, NVIDIA CORPORATION.
#
# 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... | en | 0.827343 | # # Copyright (c) 2019-2022, NVIDIA CORPORATION. # # 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... | 2.366876 | 2 |
tests/test_intbounds.py | alex/optimizer-model | 4 | 7915 | from optimizer.utils.intbounds import IntBounds
class TestIntBounds(object):
def test_make_gt(self):
i0 = IntBounds()
i1 = i0.make_gt(IntBounds(10, 10))
assert i1.lower == 11
def test_make_gt_already_bounded(self):
i0 = IntBounds()
i1 = i0.make_gt(IntBounds(10, 10))... | from optimizer.utils.intbounds import IntBounds
class TestIntBounds(object):
def test_make_gt(self):
i0 = IntBounds()
i1 = i0.make_gt(IntBounds(10, 10))
assert i1.lower == 11
def test_make_gt_already_bounded(self):
i0 = IntBounds()
i1 = i0.make_gt(IntBounds(10, 10))... | none | 1 | 3.084882 | 3 | |
tdclient/test/database_model_test.py | minchuang/td-client-python | 2 | 7916 | <reponame>minchuang/td-client-python
#!/usr/bin/env python
from __future__ import print_function
from __future__ import unicode_literals
try:
from unittest import mock
except ImportError:
import mock
from tdclient import models
from tdclient.test.test_helper import *
def setup_function(function):
unset_... | #!/usr/bin/env python
from __future__ import print_function
from __future__ import unicode_literals
try:
from unittest import mock
except ImportError:
import mock
from tdclient import models
from tdclient.test.test_helper import *
def setup_function(function):
unset_environ()
def test_database():
c... | ru | 0.26433 | #!/usr/bin/env python | 2.499113 | 2 |
setup.py | ballcap231/fireTS | 0 | 7917 | from setuptools import setup
dependencies = [
'numpy',
'scipy',
'scikit-learn',
]
setup(
name='fireTS',
version='0.0.7',
description='A python package for multi-variate time series prediction',
long_description=open('README.md').read(),
long_description_content_type="text/markdown",
... | from setuptools import setup
dependencies = [
'numpy',
'scipy',
'scikit-learn',
]
setup(
name='fireTS',
version='0.0.7',
description='A python package for multi-variate time series prediction',
long_description=open('README.md').read(),
long_description_content_type="text/markdown",
... | none | 1 | 1.2662 | 1 | |
euler/py/project_019.py | heyihan/scodes | 0 | 7918 | <filename>euler/py/project_019.py
# https://projecteuler.net/problem=19
def is_leap(year):
if year%4 != 0:
return False
if year%100 == 0 and year%400 != 0:
return False
return True
def year_days(year):
if is_leap(year):
return 366
return 365
def month_days(month, year):
... | <filename>euler/py/project_019.py
# https://projecteuler.net/problem=19
def is_leap(year):
if year%4 != 0:
return False
if year%100 == 0 and year%400 != 0:
return False
return True
def year_days(year):
if is_leap(year):
return 366
return 365
def month_days(month, year):
... | en | 0.149129 | # https://projecteuler.net/problem=19 #print(i, j, days, day_next_day1) | 3.605942 | 4 |
address_book/address_book.py | wowsuchnamaste/address_book | 0 | 7919 | """A simple address book."""
from ._tools import generate_uuid
class AddressBook:
"""
A simple address book.
"""
def __init__(self):
self._entries = []
def add_entry(self, entry):
"""Add an entry to the address book."""
self._entries.append(entry)
def get_entries(sel... | """A simple address book."""
from ._tools import generate_uuid
class AddressBook:
"""
A simple address book.
"""
def __init__(self):
self._entries = []
def add_entry(self, entry):
"""Add an entry to the address book."""
self._entries.append(entry)
def get_entries(sel... | en | 0.922794 | A simple address book. A simple address book. Add an entry to the address book. Returns a list of all entries in the address book. :return: ``list`` of ``Person`` objects. Parse whatever is passed as ``name`` and update ``self.name`` from that. :param name: A person's name as string or dictionary. ... | 3.717318 | 4 |
inference.py | zzhang87/ChestXray | 0 | 7920 | <filename>inference.py
import keras
import numpy as np
import pandas as pd
import cv2
import os
import json
import pdb
import argparse
import math
import copy
from vis.visualization import visualize_cam, overlay, visualize_activation
from vis.utils.utils import apply_modifications
from shutil import rmtree
import matp... | <filename>inference.py
import keras
import numpy as np
import pandas as pd
import cv2
import os
import json
import pdb
import argparse
import math
import copy
from vis.visualization import visualize_cam, overlay, visualize_activation
from vis.utils.utils import apply_modifications
from shutil import rmtree
import matp... | en | 0.775805 | # weights of the final fully-connected layer # activation before the last global pooling # weighted sum of the activation map | 2.38967 | 2 |
test/DQueueTest.py | MistSun-Chen/py_verifier | 0 | 7921 | from libTask import Queue
from common import configParams
from common import common
def main():
cp = configParams.ConfigParams("config.json")
detectGeneralQueue = Queue.DQueue(cp, len(cp.detect_general_ids), cp.modelPath, common.GENERALDETECT_METHOD_ID,
cp.GPUDevices, cp.detect_g... | from libTask import Queue
from common import configParams
from common import common
def main():
cp = configParams.ConfigParams("config.json")
detectGeneralQueue = Queue.DQueue(cp, len(cp.detect_general_ids), cp.modelPath, common.GENERALDETECT_METHOD_ID,
cp.GPUDevices, cp.detect_g... | none | 1 | 1.978631 | 2 | |
config.py | volgachen/Chinese-Tokenization | 0 | 7922 | class Config:
ngram = 2
train_set = "data/rmrb.txt"
modified_train_set = "data/rmrb_modified.txt"
test_set = ""
model_file = ""
param_file = ""
word_max_len = 10
proposals_keep_ratio = 1.0
use_re = 1
subseq_num = 15 | class Config:
ngram = 2
train_set = "data/rmrb.txt"
modified_train_set = "data/rmrb_modified.txt"
test_set = ""
model_file = ""
param_file = ""
word_max_len = 10
proposals_keep_ratio = 1.0
use_re = 1
subseq_num = 15 | none | 1 | 1.774057 | 2 | |
src/Knn-Tensor.py | python-itb/knn-from-scratch | 0 | 7923 | <reponame>python-itb/knn-from-scratch
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 13 18:52:28 2018
@author: amajidsinar
"""
from sklearn import datasets
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('seaborn-white')
iris = datasets.load_iris()
dataset = iris.data
# only ... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 13 18:52:28 2018
@author: amajidsinar
"""
from sklearn import datasets
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('seaborn-white')
iris = datasets.load_iris()
dataset = iris.data
# only take 0th and 1th column for X
data_kno... | en | 0.855187 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- Created on Tue Feb 13 18:52:28 2018 @author: amajidsinar # only take 0th and 1th column for X # y # the hard part # so matplotlib does not readily support labeling based on class # but we know that one of the feature of plt is that a plt call would give those set of numbe... | 3.263841 | 3 |
de_test_tron2.py | volpepe/detectron2-ResNeSt | 0 | 7924 | import torch, torchvision
import detectron2
from detectron2.utils.logger import setup_logger
setup_logger()
# import some common libraries
import numpy as np
import os, json, cv2, random
# import some common detectron2 utilities
from detectron2 import model_zoo
from detectron2.engine import DefaultPredic... | import torch, torchvision
import detectron2
from detectron2.utils.logger import setup_logger
setup_logger()
# import some common libraries
import numpy as np
import os, json, cv2, random
# import some common detectron2 utilities
from detectron2 import model_zoo
from detectron2.engine import DefaultPredic... | en | 0.765922 | # import some common libraries # import some common detectron2 utilities # get default cfg file # replace cfg from specific model yaml file # set threshold for this model # Find a model from detectron2's model zoo. You can use the https://dl.fbaipublicfiles... url as well #rgb image (::-1) | 2.291868 | 2 |
pika/data.py | Pankrat/pika | 0 | 7925 | """AMQP Table Encoding/Decoding"""
import struct
import decimal
import calendar
from datetime import datetime
from pika import exceptions
from pika.compat import unicode_type, PY2, long, as_bytes
def encode_short_string(pieces, value):
"""Encode a string value as short string and append it to pieces list
ret... | """AMQP Table Encoding/Decoding"""
import struct
import decimal
import calendar
from datetime import datetime
from pika import exceptions
from pika.compat import unicode_type, PY2, long, as_bytes
def encode_short_string(pieces, value):
"""Encode a string value as short string and append it to pieces list
ret... | en | 0.67811 | AMQP Table Encoding/Decoding Encode a string value as short string and append it to pieces list returning the size of the encoded value. :param list pieces: Already encoded values :param value: String value to encode :type value: str or unicode :rtype: int # 4.2.5.3 # Short strings, stored as an 8-... | 2.773486 | 3 |
tests/fixtures/data_sets/service/dummy/dummy_configurable.py | Agi-dev/pylaas_core | 0 | 7926 | from pylaas_core.abstract.abstract_service import AbstractService
import time
from pylaas_core.interface.technical.container_configurable_aware_interface import ContainerConfigurableAwareInterface
class DummyConfigurable(AbstractService, ContainerConfigurableAwareInterface):
def __init__(self) -> None:
... | from pylaas_core.abstract.abstract_service import AbstractService
import time
from pylaas_core.interface.technical.container_configurable_aware_interface import ContainerConfigurableAwareInterface
class DummyConfigurable(AbstractService, ContainerConfigurableAwareInterface):
def __init__(self) -> None:
... | none | 1 | 2.365911 | 2 | |
blogtech/src/blog/views.py | IVAN-URBACZKA/django-blog | 0 | 7927 | from django.urls import reverse_lazy, reverse
from django.utils.decorators import method_decorator
from django.views.generic import ListView, DetailView, CreateView, DeleteView, UpdateView
from .models import BlogPost
from django.contrib.auth.decorators import login_required
class BlogPostHomeView(ListView):
mode... | from django.urls import reverse_lazy, reverse
from django.utils.decorators import method_decorator
from django.views.generic import ListView, DetailView, CreateView, DeleteView, UpdateView
from .models import BlogPost
from django.contrib.auth.decorators import login_required
class BlogPostHomeView(ListView):
mode... | none | 1 | 2.19136 | 2 | |
apc_deep_vision/python/generate_data.py | Juxi/apb-baseline | 9 | 7928 | #! /usr/bin/env python
# ********************************************************************
# Software License Agreement (BSD License)
#
# Copyright (c) 2015, University of Colorado, Boulder
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted... | #! /usr/bin/env python
# ********************************************************************
# Software License Agreement (BSD License)
#
# Copyright (c) 2015, University of Colorado, Boulder
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted... | en | 0.691273 | #! /usr/bin/env python # ******************************************************************** # Software License Agreement (BSD License) # # Copyright (c) 2015, University of Colorado, Boulder # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted... | 1.087199 | 1 |
stats.py | shirshanka/fact-ory | 0 | 7929 | import numpy as np;
import sys
import matplotlib.pyplot as plt;
from matplotlib import cm;
from termcolor import colored;
class Stats():
def __init__(self, param1_range, param2_range):
self._total_times = 0;
self._total_time = 0.0;
self._wrong_answers = [];
self._time_dict = {};
self._param1_rang... | import numpy as np;
import sys
import matplotlib.pyplot as plt;
from matplotlib import cm;
from termcolor import colored;
class Stats():
def __init__(self, param1_range, param2_range):
self._total_times = 0;
self._total_time = 0.0;
self._wrong_answers = [];
self._time_dict = {};
self._param1_rang... | en | 0.630466 | # time penalty for wrong answer is 5 seconds # wrong answer # right answer: do nothing #plt.matshow(self._result_matrix, cmap=cm.Spectral_r, vmin=0, vmax=1) | 2.930981 | 3 |
examples/peptidecutter/advanced.py | zjuchenyuan/EasyLogin | 33 | 7930 | <gh_stars>10-100
from EasyLogin import EasyLogin
from pprint import pprint
def peptidecutter(oneprotein):
a = EasyLogin(proxy="socks5://127.0.0.1:1080") #speed up by using proxy
a.post("http://web.expasy.org/cgi-bin/peptide_cutter/peptidecutter.pl",
"protein={}&enzyme_number=all_enzymes&special_e... | from EasyLogin import EasyLogin
from pprint import pprint
def peptidecutter(oneprotein):
a = EasyLogin(proxy="socks5://127.0.0.1:1080") #speed up by using proxy
a.post("http://web.expasy.org/cgi-bin/peptide_cutter/peptidecutter.pl",
"protein={}&enzyme_number=all_enzymes&special_enzyme=Chym&min_pr... | en | 0.686117 | #speed up by using proxy #don't forget the last one #pprint(peptidecutter("SERVELAT")) | 2.676969 | 3 |
pgn2fixture/tests/test_utils.py | pointerish/pgn2fixture | 3 | 7931 | import unittest
from .. import utils
class TestUtils(unittest.TestCase):
def setUp(self) -> None:
self.pgn_string = '''
[Event "US Championship 1963/64"]
[Site "New York, NY USA"]
[Date "1964.01.01"]
[EventDate "1963.??.??"]
[Round "11"][Result "0-1"]
[Whit... | import unittest
from .. import utils
class TestUtils(unittest.TestCase):
def setUp(self) -> None:
self.pgn_string = '''
[Event "US Championship 1963/64"]
[Site "New York, NY USA"]
[Date "1964.01.01"]
[EventDate "1963.??.??"]
[Round "11"][Result "0-1"]
[Whit... | en | 0.553976 | [Event "US Championship 1963/64"] [Site "New York, NY USA"] [Date "1964.01.01"] [EventDate "1963.??.??"] [Round "11"][Result "0-1"] [White "<NAME>"] [Black "<NAME>"] [ECO "A33"] [WhiteElo "?"] [BlackElo "?"][PlyCount "112"] 1. c4 0... | 2.872694 | 3 |
manila/tests/share/test_snapshot_access.py | gouthampacha/manila | 3 | 7932 | # Copyright (c) 2016 <NAME>, 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... | # Copyright (c) 2016 <NAME>, 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... | en | 0.856152 | # Copyright (c) 2016 <NAME>, 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... | 1.888933 | 2 |
packages/pyright-internal/src/tests/samples/unnecessaryCast1.py | sasano8/pyright | 4,391 | 7933 | # This sample tests the type checker's reportUnnecessaryCast feature.
from typing import cast, Union
def foo(a: int):
# This should generate an error if
# reportUnnecessaryCast is enabled.
b = cast(int, a)
c: Union[int, str] = "hello"
d = cast(int, c)
| # This sample tests the type checker's reportUnnecessaryCast feature.
from typing import cast, Union
def foo(a: int):
# This should generate an error if
# reportUnnecessaryCast is enabled.
b = cast(int, a)
c: Union[int, str] = "hello"
d = cast(int, c)
| en | 0.69311 | # This sample tests the type checker's reportUnnecessaryCast feature. # This should generate an error if # reportUnnecessaryCast is enabled. | 2.443084 | 2 |
Python/1238.py | ArikBartzadok/beecrowd-challenges | 0 | 7934 | def execucoes():
return int(input())
def entradas():
return input().split(' ')
def imprimir(v):
print(v)
def tamanho_a(a):
return len(a)
def tamanho_b(b):
return len(b)
def diferenca_tamanhos(a, b):
return (len(a) <= len(b))
def analisar(e, i, s):
a, b = e
if(diferenca_tamanhos(a, ... | def execucoes():
return int(input())
def entradas():
return input().split(' ')
def imprimir(v):
print(v)
def tamanho_a(a):
return len(a)
def tamanho_b(b):
return len(b)
def diferenca_tamanhos(a, b):
return (len(a) <= len(b))
def analisar(e, i, s):
a, b = e
if(diferenca_tamanhos(a, ... | none | 1 | 3.400173 | 3 | |
metadata_service/api/popular_tables.py | worldwise001/amundsenmetadatalibrary | 0 | 7935 | from http import HTTPStatus
from typing import Iterable, Union, Mapping
from flask import request
from flask_restful import Resource, fields, marshal
from metadata_service.proxy import get_proxy_client
popular_table_fields = {
'database': fields.String,
'cluster': fields.String,
'schema': fields.String,
... | from http import HTTPStatus
from typing import Iterable, Union, Mapping
from flask import request
from flask_restful import Resource, fields, marshal
from metadata_service.proxy import get_proxy_client
popular_table_fields = {
'database': fields.String,
'cluster': fields.String,
'schema': fields.String,
... | en | 0.35124 | # Optional PopularTables API | 2.328978 | 2 |
tests/test1.py | SaijC/manhwaDownloader | 0 | 7936 | import requests
import logging
import cfscrape
import os
from manhwaDownloader.constants import CONSTANTS as CONST
logging.basicConfig(level=logging.DEBUG)
folderPath = os.path.join(CONST.OUTPUTPATH, 'serious-taste-of-forbbiden-fruit')
logging.info(len([file for file in os.walk(folderPath)]))
walkList = [file for fi... | import requests
import logging
import cfscrape
import os
from manhwaDownloader.constants import CONSTANTS as CONST
logging.basicConfig(level=logging.DEBUG)
folderPath = os.path.join(CONST.OUTPUTPATH, 'serious-taste-of-forbbiden-fruit')
logging.info(len([file for file in os.walk(folderPath)]))
walkList = [file for fi... | none | 1 | 1.997639 | 2 | |
others/Keras_custom_error.py | rahasayantan/Work-For-Reference | 0 | 7937 | # define custom R2 metrics for Keras backend
from keras import backend as K
def r2_keras(y_true, y_pred):
SS_res = K.sum(K.square( y_true - y_pred ))
SS_tot = K.sum(K.square( y_true - K.mean(y_true) ) )
return ( 1 - SS_res/(SS_tot + K.epsilon()) )
# base model architecture definition
def model():
... | # define custom R2 metrics for Keras backend
from keras import backend as K
def r2_keras(y_true, y_pred):
SS_res = K.sum(K.square( y_true - y_pred ))
SS_tot = K.sum(K.square( y_true - K.mean(y_true) ) )
return ( 1 - SS_res/(SS_tot + K.epsilon()) )
# base model architecture definition
def model():
... | en | 0.689487 | # define custom R2 metrics for Keras backend # base model architecture definition #input layer # hidden layers # output layer (y_pred) # compile this model # one may use 'mean_absolute_error' as alternative # you can add several if needed # Visualize NN architecture ################K2 # # Data preparation # # One-hot e... | 2.953036 | 3 |
tests/ut/python/parallel/test_manual_gatherv2.py | PowerOlive/mindspore | 3,200 | 7938 | # 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... | # 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... | en | 0.808111 | # 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... | 1.730067 | 2 |
ClemBot.Bot/bot/api/tag_route.py | makayla-moster/ClemBot | 121 | 7939 | <gh_stars>100-1000
from bot.api.api_client import ApiClient
from bot.api.base_route import BaseRoute
import typing as t
from bot.models import Tag
class TagRoute(BaseRoute):
def __init__(self, api_client: ApiClient):
super().__init__(api_client)
async def create_tag(self, name: str, content: str, g... | from bot.api.api_client import ApiClient
from bot.api.base_route import BaseRoute
import typing as t
from bot.models import Tag
class TagRoute(BaseRoute):
def __init__(self, api_client: ApiClient):
super().__init__(api_client)
async def create_tag(self, name: str, content: str, guild_id: int, user_... | en | 0.836019 | Makes a call to the API to delete a tag w/ the given GuildId and Name. If successful, the API will return a dict with the given values: - name The name of the tag. - content The content of the tag. - guildId The guild id the tag was in. Makes a call to the API to say a tag w/ th... | 2.248383 | 2 |
formfactor_AL.py | kirichoi/PolymerConnectome | 0 | 7940 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 7 10:59:00 2020
@author: user
"""
import numpy as np
import multiprocessing as mp
import matplotlib.pyplot as plt
import time
import itertools
import ctypes
def formfactor(args):
# with AL_dist_flat_glo.get_lock:
AL_dist_flat_glo_r = np.frombuffer(AL_dist_flat_... | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 7 10:59:00 2020
@author: user
"""
import numpy as np
import multiprocessing as mp
import matplotlib.pyplot as plt
import time
import itertools
import ctypes
def formfactor(args):
# with AL_dist_flat_glo.get_lock:
AL_dist_flat_glo_r = np.frombuffer(AL_dist_flat_... | en | 0.361903 | # -*- coding: utf-8 -*- Created on Mon Sep 7 10:59:00 2020 @author: user # with AL_dist_flat_glo.get_lock: # ffq = np.sum(np.cos(np.dot(np.logspace(-2,3,100)[args[0]]*np.array([1,0,0]), # np.subtract(AL_dist_flat_glo_s[args[1]], AL_dist_flat_glo_s[1+args[1]:]).T))) # cosxy = np.cos(np.dot(q... | 1.99023 | 2 |
utils/tests.py | nanodude/cairocffi | 0 | 7941 | # coding: utf-8
import io
import cairo # pycairo
import cairocffi
from pycairo_to_cairocffi import _UNSAFE_pycairo_context_to_cairocffi
from cairocffi_to_pycairo import _UNSAFE_cairocffi_context_to_pycairo
import pango_example
def test():
cairocffi_context = cairocffi.Context(cairocffi.PDFSurface(N... | # coding: utf-8
import io
import cairo # pycairo
import cairocffi
from pycairo_to_cairocffi import _UNSAFE_pycairo_context_to_cairocffi
from cairocffi_to_pycairo import _UNSAFE_cairocffi_context_to_pycairo
import pango_example
def test():
cairocffi_context = cairocffi.Context(cairocffi.PDFSurface(N... | en | 0.902625 | # coding: utf-8 # pycairo # Mostly test that this runs without raising. | 2.485461 | 2 |
riddle.py | robertlit/monty-hall-problem | 0 | 7942 | import random
goat1 = random.randint(1, 3)
goat2 = random.randint(1, 3)
while goat1 == goat2:
goat2 = random.randint(1, 3)
success = 0
tries = 1_000_000
for _ in range(tries):
options = [1, 2, 3]
choice = random.randint(1, 3)
options.remove(choice)
if choice == goat1:
options.remove(goat... | import random
goat1 = random.randint(1, 3)
goat2 = random.randint(1, 3)
while goat1 == goat2:
goat2 = random.randint(1, 3)
success = 0
tries = 1_000_000
for _ in range(tries):
options = [1, 2, 3]
choice = random.randint(1, 3)
options.remove(choice)
if choice == goat1:
options.remove(goat... | none | 1 | 3.506327 | 4 | |
gentable/gen_test_cases.py | selavy/studies | 0 | 7943 | #!/usr/bin/env python3
import random
N = 32
M = 64
# NOTE: 0 is a reserved value
randu = lambda x: random.randint(1, 2**x-1)
randU32 = lambda: randu(32)
randU64 = lambda: randu(64)
fmt_by_dtype = {
'u32hex': '0x{:08x}',
'u64hex': '0x{:016x}',
}
cpp_by_dtype = {
'u32hex': 'uint32_t',
'u64hex': 'ui... | #!/usr/bin/env python3
import random
N = 32
M = 64
# NOTE: 0 is a reserved value
randu = lambda x: random.randint(1, 2**x-1)
randU32 = lambda: randu(32)
randU64 = lambda: randu(64)
fmt_by_dtype = {
'u32hex': '0x{:08x}',
'u64hex': '0x{:016x}',
}
cpp_by_dtype = {
'u32hex': 'uint32_t',
'u64hex': 'ui... | en | 0.584581 | #!/usr/bin/env python3 # NOTE: 0 is a reserved value # key = randU32() # vals = [(key, randU32(), randU64()) for _ in range(N)] # keys = [(x[0], x[1]) for x in vals] # success = [random.choice(vals) for _ in range(M)] # failure = [] # print("const std::vector<std::tuple<uint32_t, uint32_t, uint64_t>> vs = {") # for _ i... | 2.875069 | 3 |
examples/toy_env/run_toy_env.py | aaspeel/deer | 0 | 7944 | <filename>examples/toy_env/run_toy_env.py
"""Toy environment launcher. See the docs for more details about this environment.
"""
import sys
import logging
import numpy as np
from deer.default_parser import process_args
from deer.agent import NeuralAgent
from deer.learning_algos.q_net_keras import MyQNetwork
from Toy... | <filename>examples/toy_env/run_toy_env.py
"""Toy environment launcher. See the docs for more details about this environment.
"""
import sys
import logging
import numpy as np
from deer.default_parser import process_args
from deer.agent import NeuralAgent
from deer.learning_algos.q_net_keras import MyQNetwork
from Toy... | en | 0.868153 | Toy environment launcher. See the docs for more details about this environment. # ---------------------- # Experiment Parameters # ---------------------- # ---------------------- # Environment Parameters # ---------------------- # ---------------------- # DQN Agent parameters: # ---------------------- # --- Parse param... | 2.086075 | 2 |
equilibration/sodium_models/seed_1/post_processing/rdf_calculations.py | Dynamical-Systems-Laboratory/IPMCsMD | 2 | 7945 | # ------------------------------------------------------------------
#
# RDF and CN related analysis
#
# ------------------------------------------------------------------
import sys
py_path = '../../../../postprocessing/'
sys.path.insert(0, py_path)
py_path = '../../../../postprocessing/io_operations/'
sys.path.inse... | # ------------------------------------------------------------------
#
# RDF and CN related analysis
#
# ------------------------------------------------------------------
import sys
py_path = '../../../../postprocessing/'
sys.path.insert(0, py_path)
py_path = '../../../../postprocessing/io_operations/'
sys.path.inse... | en | 0.358885 | # ------------------------------------------------------------------ # # RDF and CN related analysis # # ------------------------------------------------------------------ # # Input # # RDF and CN intput file # Output file # Number of bins # Number of columns | 2.400128 | 2 |
venv/Lib/site-packages/plotnine/geoms/geom_pointrange.py | EkremBayar/bayar | 0 | 7946 | from ..doctools import document
from .geom import geom
from .geom_path import geom_path
from .geom_point import geom_point
from .geom_linerange import geom_linerange
@document
class geom_pointrange(geom):
"""
Vertical interval represented by a line with a point
{usage}
Parameters
----------
... | from ..doctools import document
from .geom import geom
from .geom_path import geom_path
from .geom_point import geom_point
from .geom_linerange import geom_linerange
@document
class geom_pointrange(geom):
"""
Vertical interval represented by a line with a point
{usage}
Parameters
----------
... | en | 0.402598 | Vertical interval represented by a line with a point {usage} Parameters ---------- {common_parameters} fatten : float, optional (default: 2) A multiplicative factor used to increase the size of the point along the line-range. Draw a point in the box Parameters ----... | 2.544566 | 3 |
app/backend-test/core_models/keras-experiments/run02_try_simple_CNN_generate.py | SummaLabs/DLS | 32 | 7947 | <filename>app/backend-test/core_models/keras-experiments/run02_try_simple_CNN_generate.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'ar'
import json
import os
import skimage.io as skio
import matplotlib.pyplot as plt
import numpy as np
import keras
from keras.models import Model
from keras.layers import ... | <filename>app/backend-test/core_models/keras-experiments/run02_try_simple_CNN_generate.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'ar'
import json
import os
import skimage.io as skio
import matplotlib.pyplot as plt
import numpy as np
import keras
from keras.models import Model
from keras.layers import ... | de | 0.385947 | #!/usr/bin/python # -*- coding: utf-8 -*- ################################## # Conv 1'st # Conv 2'nd # Conv 3'rd # Conv 4'th # Conv 5'th # ################################## ################################## # plt.imshow(skio.imread(fimgModel)) # plt.show() # print (json.dumps(modelJson, indent=4)) | 2.738786 | 3 |
tests/integration/test_interface.py | Synodic-Software/CPPython | 0 | 7948 | """
Test the integrations related to the internal interface implementation and the 'Interface' interface itself
"""
import pytest
from cppython_core.schema import InterfaceConfiguration
from pytest_cppython.plugin import InterfaceIntegrationTests
from cppython.console import ConsoleInterface
class TestCLIInterface(... | """
Test the integrations related to the internal interface implementation and the 'Interface' interface itself
"""
import pytest
from cppython_core.schema import InterfaceConfiguration
from pytest_cppython.plugin import InterfaceIntegrationTests
from cppython.console import ConsoleInterface
class TestCLIInterface(... | en | 0.669554 | Test the integrations related to the internal interface implementation and the 'Interface' interface itself The tests for our CLI interface Override of the plugin provided interface fixture. Returns: ConsoleInterface -- The Interface object to use for the CPPython defined tests | 2.244931 | 2 |
solutions/python3/894.py | sm2774us/amazon_interview_prep_2021 | 42 | 7949 | class Solution:
def allPossibleFBT(self, N):
def constr(N):
if N == 1: yield TreeNode(0)
for i in range(1, N, 2):
for l in constr(i):
for r in constr(N - i - 1):
m = TreeNode(0)
m.left = l
... | class Solution:
def allPossibleFBT(self, N):
def constr(N):
if N == 1: yield TreeNode(0)
for i in range(1, N, 2):
for l in constr(i):
for r in constr(N - i - 1):
m = TreeNode(0)
m.left = l
... | none | 1 | 3.175186 | 3 | |
src/main.py | srijankr/DAIN | 3 | 7950 | #@contact <NAME> (<EMAIL>), Georgia Institute of Technology
#@version 1.0
#@date 2021-08-17
#Influence-guided Data Augmentation for Neural Tensor Completion (DAIN)
#This software is free of charge under research purposes.
#For commercial purposes, please contact the main author.
import torch
from torch imp... | #@contact <NAME> (<EMAIL>), Georgia Institute of Technology
#@version 1.0
#@date 2021-08-17
#Influence-guided Data Augmentation for Neural Tensor Completion (DAIN)
#This software is free of charge under research purposes.
#For commercial purposes, please contact the main author.
import torch
from torch imp... | en | 0.624461 | #@contact <NAME> (<EMAIL>), Georgia Institute of Technology #@version 1.0 #@date 2021-08-17 #Influence-guided Data Augmentation for Neural Tensor Completion (DAIN) #This software is free of charge under research purposes. #For commercial purposes, please contact the main author. #Step 4: data augmentation #... | 2.499927 | 2 |
pay-api/tests/unit/api/test_fee.py | saravanpa-aot/sbc-pay | 0 | 7951 | <filename>pay-api/tests/unit/api/test_fee.py
# Copyright © 2019 Province of British Columbia
#
# 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... | <filename>pay-api/tests/unit/api/test_fee.py
# Copyright © 2019 Province of British Columbia
#
# 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... | en | 0.814648 | # Copyright © 2019 Province of British Columbia # # 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 agr... | 2.02236 | 2 |
backend/app/auth/service.py | pers0n4/yoonyaho | 0 | 7952 | from datetime import datetime, timedelta
import jwt
from flask import current_app
from app import db
from app.user.repository import UserRepository
class AuthService:
def __init__(self) -> None:
self._user_repository = UserRepository(db.session)
def create_token(self, data) -> dict:
user = ... | from datetime import datetime, timedelta
import jwt
from flask import current_app
from app import db
from app.user.repository import UserRepository
class AuthService:
def __init__(self) -> None:
self._user_repository = UserRepository(db.session)
def create_token(self, data) -> dict:
user = ... | en | 0.961371 | # user not found # password # user not found | 2.605165 | 3 |
scripts/qlearn.py | kebaek/minigrid | 5 | 7953 | <filename>scripts/qlearn.py
import _init_paths
import argparse
import random
import time
import utils
import os
from collections import defaultdict
import numpy as np
import csv
from progress.bar import IncrementalBar
from utils.hash import *
def parse_arguments():
parser = argparse.ArgumentParser()
# add arg... | <filename>scripts/qlearn.py
import _init_paths
import argparse
import random
import time
import utils
import os
from collections import defaultdict
import numpy as np
import csv
from progress.bar import IncrementalBar
from utils.hash import *
def parse_arguments():
parser = argparse.ArgumentParser()
# add arg... | en | 0.045597 | # add arguments # parse arguments # create value function and q value function # train agent # output # parse arguments # create env # train agent | 2.53133 | 3 |
research/tunnel.py | carrino/FrisPy | 0 | 7954 | <filename>research/tunnel.py<gh_stars>0
import math
from pprint import pprint
import matplotlib.pyplot as plt
from scipy.optimize import minimize
from frispy import Disc
from frispy import Discs
from frispy import Model
model = Discs.roc
mph_to_mps = 0.44704
v = 56 * mph_to_mps
rot = -v / model.diameter
ceiling = 4... | <filename>research/tunnel.py<gh_stars>0
import math
from pprint import pprint
import matplotlib.pyplot as plt
from scipy.optimize import minimize
from frispy import Disc
from frispy import Discs
from frispy import Model
model = Discs.roc
mph_to_mps = 0.44704
v = 56 * mph_to_mps
rot = -v / model.diameter
ceiling = 4... | en | 0.15686 | # 4 meter ceiling # 4 meter wide tunnel #plt.plot(x, y) #plt.plot(x, z) #plt.plot(t, x) # feet | 2.253416 | 2 |
openfermioncirq/variational/ansatzes/swap_network_trotter_hubbard_test.py | unpilbaek/OpenFermion-Cirq | 278 | 7955 | <filename>openfermioncirq/variational/ansatzes/swap_network_trotter_hubbard_test.py
# 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
#
... | <filename>openfermioncirq/variational/ansatzes/swap_network_trotter_hubbard_test.py
# 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
#
... | en | 0.859654 | # 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, software # distribu... | 2.072568 | 2 |
Modules/Phylogenetic.py | DaneshMoradigaravand/PlasmidPerm | 0 | 7956 | import os
from Bio import AlignIO, Phylo
from Bio.Phylo.TreeConstruction import DistanceCalculator, DistanceTreeConstructor
class Phylogenetic:
def __init__(self, PATH):
self.PATH=PATH
def binary_sequence_generator(self, input_kmer_pattern, label):
string_inp="".join([ 'A' if x==0 else 'C'... | import os
from Bio import AlignIO, Phylo
from Bio.Phylo.TreeConstruction import DistanceCalculator, DistanceTreeConstructor
class Phylogenetic:
def __init__(self, PATH):
self.PATH=PATH
def binary_sequence_generator(self, input_kmer_pattern, label):
string_inp="".join([ 'A' if x==0 else 'C'... | none | 1 | 2.920527 | 3 | |
retrieve_regmod_values.py | cbcommunity/cbapi-examples | 17 | 7957 | #!/usr/bin/env python
#
#The MIT License (MIT)
#
# Copyright (c) 2015 Bit9 + Carbon Black
#
# 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 t... | #!/usr/bin/env python
#
#The MIT License (MIT)
#
# Copyright (c) 2015 Bit9 + Carbon Black
#
# 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 t... | en | 0.832871 | #!/usr/bin/env python # #The MIT License (MIT) # # Copyright (c) 2015 Bit9 + Carbon Black # # 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 t... | 1.263061 | 1 |
h/exceptions.py | ssin122/test-h | 2 | 7958 | <reponame>ssin122/test-h
# -*- coding: utf-8 -*-
"""Exceptions raised by the h application."""
from __future__ import unicode_literals
from h.i18n import TranslationString as _
# N.B. This class **only** covers exceptions thrown by API code provided by
# the h package. memex code has its own base APIError class.
c... | # -*- coding: utf-8 -*-
"""Exceptions raised by the h application."""
from __future__ import unicode_literals
from h.i18n import TranslationString as _
# N.B. This class **only** covers exceptions thrown by API code provided by
# the h package. memex code has its own base APIError class.
class APIError(Exception):... | en | 0.858972 | # -*- coding: utf-8 -*- Exceptions raised by the h application. # N.B. This class **only** covers exceptions thrown by API code provided by # the h package. memex code has its own base APIError class. Base exception for problems handling API requests. Exception raised if the client credentials provided for an API reque... | 2.6356 | 3 |
functest/opnfv_tests/openstack/shaker/shaker.py | opnfv-poc/functest | 0 | 7959 | <filename>functest/opnfv_tests/openstack/shaker/shaker.py
#!/usr/bin/env python
# Copyright (c) 2018 Orange and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at... | <filename>functest/opnfv_tests/openstack/shaker/shaker.py
#!/usr/bin/env python
# Copyright (c) 2018 Orange and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at... | en | 0.815735 | #!/usr/bin/env python # Copyright (c) 2018 Orange and others. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 Shaker_ wraps... | 1.990343 | 2 |
lib/models/bn_helper.py | hongrui16/naic2020_B | 0 | 7960 | import torch
import functools
if torch.__version__.startswith('0'):
from .sync_bn.inplace_abn.bn import InPlaceABNSync
BatchNorm2d = functools.partial(InPlaceABNSync, activation='none')
BatchNorm2d_class = InPlaceABNSync
relu_inplace = False
else:
# BatchNorm2d_class = BatchNorm2d = torch.nn.SyncBa... | import torch
import functools
if torch.__version__.startswith('0'):
from .sync_bn.inplace_abn.bn import InPlaceABNSync
BatchNorm2d = functools.partial(InPlaceABNSync, activation='none')
BatchNorm2d_class = InPlaceABNSync
relu_inplace = False
else:
# BatchNorm2d_class = BatchNorm2d = torch.nn.SyncBa... | en | 0.591816 | # BatchNorm2d_class = BatchNorm2d = torch.nn.SyncBatchNorm | 2.268766 | 2 |
ordered_model/tests/models.py | HiddenClever/django-ordered-model | 0 | 7961 | <reponame>HiddenClever/django-ordered-model
from django.db import models
from ordered_model.models import OrderedModel, OrderedModelBase
class Item(OrderedModel):
name = models.CharField(max_length=100)
class Question(models.Model):
pass
class TestUser(models.Model):
pass
class Answer(OrderedModel):... | from django.db import models
from ordered_model.models import OrderedModel, OrderedModelBase
class Item(OrderedModel):
name = models.CharField(max_length=100)
class Question(models.Model):
pass
class TestUser(models.Model):
pass
class Answer(OrderedModel):
question = models.ForeignKey(Question, ... | en | 0.500986 | #{0:d} of question #{1:d} for user #{2:d}".format(self.order, self.question_id, self.user_id) | 2.431099 | 2 |
library/pandas_utils.py | SACGF/variantgrid | 5 | 7962 | import os
import sys
import numpy as np
import pandas as pd
def get_columns_percent_dataframe(df: pd.DataFrame, totals_column=None, percent_names=True) -> pd.DataFrame:
""" @param totals_column: (default = use sum of columns)
@param percent_names: Rename names from 'col' => 'col %'
Return a dataframe... | import os
import sys
import numpy as np
import pandas as pd
def get_columns_percent_dataframe(df: pd.DataFrame, totals_column=None, percent_names=True) -> pd.DataFrame:
""" @param totals_column: (default = use sum of columns)
@param percent_names: Rename names from 'col' => 'col %'
Return a dataframe... | en | 0.65167 | @param totals_column: (default = use sum of columns) @param percent_names: Rename names from 'col' => 'col %' Return a dataframe as a percentage of totals_column if provided, or sum of columns # to get percent Return a dataframe as a percentage of sum of rows Return a dataframe as a percentage of sum of row... | 3.702787 | 4 |
app/services/base.py | grace1307/lan_mapper | 0 | 7963 | <reponame>grace1307/lan_mapper<filename>app/services/base.py
from app.db import db
# Ignore it if db can't find the row when updating/deleting
# Todo: not ignore it, raise some error, remove checkers in view
class BaseService:
__abstract__ = True
model = None
# Create
def add_one(self, **kwargs):
... | from app.db import db
# Ignore it if db can't find the row when updating/deleting
# Todo: not ignore it, raise some error, remove checkers in view
class BaseService:
__abstract__ = True
model = None
# Create
def add_one(self, **kwargs):
new_row = self.model(**kwargs)
db.session.add(ne... | en | 0.816564 | # Ignore it if db can't find the row when updating/deleting # Todo: not ignore it, raise some error, remove checkers in view # Create # sqlalchemy auto flushes so maybe this just need commit ? # Read # Update # Delete | 2.451184 | 2 |
set.py | QUDUSKUNLE/Python-Flask | 0 | 7964 | """
How to set up virtual environment
pip install virtualenv
pip install virtualenvwrapper
# export WORKON_HOME=~/Envs
source /usr/local/bin/virtualenvwrapper.sh
# To activate virtualenv and set up flask
1. mkvirtualenv my-venv
###2. workon my-venv
3. pip install Flask
4. pip freeze
5. #... | """
How to set up virtual environment
pip install virtualenv
pip install virtualenvwrapper
# export WORKON_HOME=~/Envs
source /usr/local/bin/virtualenvwrapper.sh
# To activate virtualenv and set up flask
1. mkvirtualenv my-venv
###2. workon my-venv
3. pip install Flask
4. pip freeze
5. #... | en | 0.639972 | How to set up virtual environment pip install virtualenv pip install virtualenvwrapper # export WORKON_HOME=~/Envs source /usr/local/bin/virtualenvwrapper.sh # To activate virtualenv and set up flask 1. mkvirtualenv my-venv ###2. workon my-venv 3. pip install Flask 4. pip freeze 5. # To pu... | 2.855571 | 3 |
test/test_generate_data_coassembly.py | Badboy-16/SemiBin | 0 | 7965 | from SemiBin.main import generate_data_single
import os
import pytest
import logging
import pandas as pd
def test_generate_data_coassembly():
logger = logging.getLogger('SemiBin')
logger.setLevel(logging.INFO)
sh = logging.StreamHandler()
sh.setFormatter(logging.Formatter('%(asctime)s - %(message)s'))
... | from SemiBin.main import generate_data_single
import os
import pytest
import logging
import pandas as pd
def test_generate_data_coassembly():
logger = logging.getLogger('SemiBin')
logger.setLevel(logging.INFO)
sh = logging.StreamHandler()
sh.setFormatter(logging.Formatter('%(asctime)s - %(message)s'))
... | none | 1 | 2.319043 | 2 | |
create/create_args_test.py | CarbonROM/android_tools_acloud | 0 | 7966 | # Copyright 2020 - The Android Open Source Project
#
# 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 2020 - The Android Open Source Project
#
# 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.735465 | # Copyright 2020 - The Android Open Source Project # # 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 ... | 1.863546 | 2 |
setup.py | Kannuki-san/msman | 0 | 7967 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from cx_Freeze import setup,Executable
icondata='icon.ico'
base = None
# GUI=有効, CUI=無効 にする
if sys.platform == 'win32' : base = 'win32GUI'
exe = Executable(script = 'main.py',
base = base,
#icon=icondata
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from cx_Freeze import setup,Executable
icondata='icon.ico'
base = None
# GUI=有効, CUI=無効 にする
if sys.platform == 'win32' : base = 'win32GUI'
exe = Executable(script = 'main.py',
base = base,
#icon=icondata
... | ja | 0.579002 | #!/usr/bin/env python # -*- coding: utf-8 -*- # GUI=有効, CUI=無効 にする #icon=icondata | 1.950983 | 2 |
stereotype/roles.py | petee-d/stereotype | 6 | 7968 | <gh_stars>1-10
from __future__ import annotations
from threading import Lock
from typing import List, Set, Optional, Any, Tuple
from stereotype.utils import ConfigurationError
class Role:
__slots__ = ('code', 'name', 'empty_by_default')
def __init__(self, name: str, empty_by_default: bool = False):
... | from __future__ import annotations
from threading import Lock
from typing import List, Set, Optional, Any, Tuple
from stereotype.utils import ConfigurationError
class Role:
__slots__ = ('code', 'name', 'empty_by_default')
def __init__(self, name: str, empty_by_default: bool = False):
self.name = na... | none | 1 | 2.492157 | 2 | |
WEB21-1-12/WEB2/power/zvl_test.py | coderdq/vuetest | 0 | 7969 | <gh_stars>0
# coding:utf-8
'''
矢网的测试项,包括增益,带内波动,VSWR
一个曲线最多建10个marker
'''
import os
import logging
from commoninterface.zvlbase import ZVLBase
logger = logging.getLogger('ghost')
class HandleZVL(object):
def __init__(self, ip, offset):
self.zvl = None
self.ip = ip
self.offset = float(offs... | # coding:utf-8
'''
矢网的测试项,包括增益,带内波动,VSWR
一个曲线最多建10个marker
'''
import os
import logging
from commoninterface.zvlbase import ZVLBase
logger = logging.getLogger('ghost')
class HandleZVL(object):
def __init__(self, ip, offset):
self.zvl = None
self.ip = ip
self.offset = float(offset)
def... | zh | 0.430545 | # coding:utf-8 矢网的测试项,包括增益,带内波动,VSWR 一个曲线最多建10个marker # 存储图片的路径 :param low_edge: float单位MHz :param up_edge: float单位MHz :return: :param tracen: int form:str, means:str,'S11','S12','S21','S22' :return: # zvl.set_ref_value(zvlhandler, tracen, -40) # 设置marker点 # max marker # create_m... | 2.385178 | 2 |
kshell/partial_level_density.py | ErlendLima/70Zn | 0 | 7970 | from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import shellmodelutilities as smutil
# Set bin width and range
bin_width = 0.20
Emax = 14
Nbins = int(np.ceil(Emax/bin_width))
Emax_adjusted = bin_width*Nbins # Trick to get an integer number of bins
bins = np.linspace(0,Emax_adjust... | from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import shellmodelutilities as smutil
# Set bin width and range
bin_width = 0.20
Emax = 14
Nbins = int(np.ceil(Emax/bin_width))
Emax_adjusted = bin_width*Nbins # Trick to get an integer number of bins
bins = np.linspace(0,Emax_adjust... | en | 0.803474 | # Set bin width and range # Trick to get an integer number of bins # Define list of calculation input files and corresponding label names # Instantiate figure which we will fill # Read energy levels from file # Choose which [2*J,pi] combinations to include in partial level density plot # Allocate (Ex,Jpi) matrix to sto... | 2.068034 | 2 |
tests/integration/test_provider_base.py | neuro-inc/platform-buckets-api | 0 | 7971 | <filename>tests/integration/test_provider_base.py
import abc
import secrets
from collections.abc import AsyncIterator, Awaitable, Callable, Mapping
from contextlib import AbstractAsyncContextManager, asynccontextmanager
from dataclasses import dataclass
from datetime import datetime, timezone
import pytest
from aiohtt... | <filename>tests/integration/test_provider_base.py
import abc
import secrets
from collections.abc import AsyncIterator, Awaitable, Callable, Mapping
from contextlib import AbstractAsyncContextManager, asynccontextmanager
from dataclasses import dataclass
from datetime import datetime, timezone
import pytest
from aiohtt... | en | 0.440272 | # Access checkers | 1.965176 | 2 |
sbpy/photometry/bandpass.py | jianyangli/sbpy | 1 | 7972 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
sbpy bandpass Module
"""
__all__ = [
'bandpass'
]
import os
from astropy.utils.data import get_pkg_data_filename
def bandpass(name):
"""Retrieve bandpass transmission spectrum from sbpy.
Parameters
----------
name : string
... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
sbpy bandpass Module
"""
__all__ = [
'bandpass'
]
import os
from astropy.utils.data import get_pkg_data_filename
def bandpass(name):
"""Retrieve bandpass transmission spectrum from sbpy.
Parameters
----------
name : string
... | en | 0.452316 | # Licensed under a 3-clause BSD style license - see LICENSE.rst sbpy bandpass Module Retrieve bandpass transmission spectrum from sbpy. Parameters ---------- name : string Name of the bandpass, case insensitive. See notes for available filters. Returns ------- bp : `~synphot... | 1.866113 | 2 |
appserver/search/views.py | sinag/SWE574-Horuscope | 0 | 7973 | from django.http import HttpResponse
from django.shortcuts import render, redirect
from community.models import Community
# Create your views here.
def search_basic(request):
communities = None
if request.POST:
community_query = request.POST.get('community_search', False)
communities = Commun... | from django.http import HttpResponse
from django.shortcuts import render, redirect
from community.models import Community
# Create your views here.
def search_basic(request):
communities = None
if request.POST:
community_query = request.POST.get('community_search', False)
communities = Commun... | en | 0.968116 | # Create your views here. | 2.081141 | 2 |
teams/migrations/0001_initial.py | Sudani-Coder/teammanager | 0 | 7974 | <filename>teams/migrations/0001_initial.py
# Generated by Django 3.1.2 on 2020-10-18 17:19
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='GameScore',
fiel... | <filename>teams/migrations/0001_initial.py
# Generated by Django 3.1.2 on 2020-10-18 17:19
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='GameScore',
fiel... | en | 0.823185 | # Generated by Django 3.1.2 on 2020-10-18 17:19 | 1.858458 | 2 |
qcodes_contrib_drivers/drivers/Oxford/ILM200.py | jenshnielsen/Qcodes_contrib_drivers | 0 | 7975 | # OxfordInstruments_ILM200.py class, to perform the communication between the Wrapper and the device
# Copyright (c) 2017 QuTech (Delft)
# Code is available under the available under the `MIT open-source license <https://opensource.org/licenses/MIT>`__
#
# <NAME> <<EMAIL>>, 2017
# <NAME> <<EMAIL>>, 2016
# <NAME> <<EMAI... | # OxfordInstruments_ILM200.py class, to perform the communication between the Wrapper and the device
# Copyright (c) 2017 QuTech (Delft)
# Code is available under the available under the `MIT open-source license <https://opensource.org/licenses/MIT>`__
#
# <NAME> <<EMAIL>>, 2017
# <NAME> <<EMAIL>>, 2016
# <NAME> <<EMAI... | en | 0.783209 | # OxfordInstruments_ILM200.py class, to perform the communication between the Wrapper and the device # Copyright (c) 2017 QuTech (Delft) # Code is available under the available under the `MIT open-source license <https://opensource.org/licenses/MIT>`__ # # <NAME> <<EMAIL>>, 2017 # <NAME> <<EMAIL>>, 2016 # <NAME> <<EMAI... | 2.264951 | 2 |
load_cifar_10.py | xgxofdream/CNN-Using-Local-CIFAR-10-dataset | 0 | 7976 | <reponame>xgxofdream/CNN-Using-Local-CIFAR-10-dataset
import numpy as np
import matplotlib.pyplot as plt
import pickle
"""
The CIFAR-10 dataset consists of 60000 32x32 colour images in 10 classes, with 6000 images per class. There are 50000
training images and 10000 test images.
The dataset is divided into five trai... | import numpy as np
import matplotlib.pyplot as plt
import pickle
"""
The CIFAR-10 dataset consists of 60000 32x32 colour images in 10 classes, with 6000 images per class. There are 50000
training images and 10000 test images.
The dataset is divided into five training batches and one test batch, each with 10000 image... | en | 0.669486 | The CIFAR-10 dataset consists of 60000 32x32 colour images in 10 classes, with 6000 images per class. There are 50000 training images and 10000 test images. The dataset is divided into five training batches and one test batch, each with 10000 images. The test batch contains exactly 1000 randomly-selected images from... | 3.208987 | 3 |
volatility3/framework/plugins/mac/lsmod.py | leohearts/volatility3 | 0 | 7977 | # This file is Copyright 2019 Volatility Foundation and licensed under the Volatility Software License 1.0
# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0
#
"""A module containing a collection of plugins that produce data typically
found in Mac's lsmod command."""
from volatility3.framewor... | # This file is Copyright 2019 Volatility Foundation and licensed under the Volatility Software License 1.0
# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0
#
"""A module containing a collection of plugins that produce data typically
found in Mac's lsmod command."""
from volatility3.framewor... | en | 0.800769 | # This file is Copyright 2019 Volatility Foundation and licensed under the Volatility Software License 1.0 # which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 # A module containing a collection of plugins that produce data typically found in Mac's lsmod command. Lists loaded kernel modules. Li... | 2.140901 | 2 |
instahunter.py | Araekiel/instahunter | 17 | 7978 | <gh_stars>10-100
'''
instahunter.py
Author: Araekiel
Copyright: Copyright © 2019, Araekiel
License: MIT
Version: 1.6.3
'''
import click
import requests
import json
from datetime import datetime
@click.group()
def cli():
"""Made by Araekiel | v1.6.3"""
headers = { "User-Agent": "Mozilla/5.0... | '''
instahunter.py
Author: Araekiel
Copyright: Copyright © 2019, Araekiel
License: MIT
Version: 1.6.3
'''
import click
import requests
import json
from datetime import datetime
@click.group()
def cli():
"""Made by Araekiel | v1.6.3"""
headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Inte... | en | 0.460898 | instahunter.py Author: Araekiel Copyright: Copyright © 2019, Araekiel License: MIT Version: 1.6.3 Made by Araekiel | v1.6.3 This command will fetch latest or top public posts with a Hashtag # Creating file if required, creating array json_data to store data if the file type is json # Looping through '... | 2.770931 | 3 |
pyscf/prop/esr/uks.py | azag0/pyscf | 2 | 7979 | <reponame>azag0/pyscf<gh_stars>1-10
#!/usr/bin/env python
# Copyright 2014-2019 The PySCF Developers. 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... | #!/usr/bin/env python
# Copyright 2014-2019 The PySCF Developers. 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
#
# U... | en | 0.745577 | #!/usr/bin/env python # Copyright 2014-2019 The PySCF Developers. 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 # # U... | 1.878816 | 2 |
examples/gather_demo.py | mununum/MAgent | 1 | 7980 | <reponame>mununum/MAgent
import random
import magent
from magent.builtin.rule_model import RandomActor
import numpy as np
def init_food(env, food_handle):
tree = np.asarray([[-1,0], [0,0], [0,-1], [0,1], [1,0]])
third = map_size//4 # mapsize includes walls
for i in range(1, 4):
for j in range(1, ... | import random
import magent
from magent.builtin.rule_model import RandomActor
import numpy as np
def init_food(env, food_handle):
tree = np.asarray([[-1,0], [0,0], [0,-1], [0,1], [1,0]])
third = map_size//4 # mapsize includes walls
for i in range(1, 4):
for j in range(1, 4):
base = np... | en | 0.513848 | # mapsize includes walls # add reward rule # cfg.add_reward_rule(e2, receiver=b, value=1, die=True) # cfg.add_reward_rule(e3, receiver=[a,b], value=[-1,-1]) # spawnrate = 0.1 # env.add_agents(rightgroup, method="custom", pos=rightstart) # simulate one step # render # get reward # clear dead agents # print info # if ste... | 2.203338 | 2 |
corehq/apps/domain/deletion.py | shyamkumarlchauhan/commcare-hq | 0 | 7981 | <reponame>shyamkumarlchauhan/commcare-hq
import itertools
import logging
from datetime import date
from django.apps import apps
from django.conf import settings
from django.db import connection, transaction
from django.db.models import Q
from dimagi.utils.chunked import chunked
from corehq.apps.accounting.models imp... | import itertools
import logging
from datetime import date
from django.apps import apps
from django.conf import settings
from django.db import connection, transaction
from django.db.models import Q
from dimagi.utils.chunked import chunked
from corehq.apps.accounting.models import Subscription
from corehq.apps.account... | en | 0.867128 | # The Django orm will properly turn a None domain_name to a # IS NULL filter. We don't want to allow deleting records for # NULL domain names since they might have special meaning (like # in some of the SMS models). # The CustomDataFieldsDefinition instances are cleaned up as part of the # bulk couch delete, but we als... | 1.741329 | 2 |
icosphere/icosphere.py | JackWalpole/icosahedron | 2 | 7982 | """Subdivided icosahedral mesh generation"""
from __future__ import print_function
import numpy as np
# following: http://blog.andreaskahler.com/2009/06/creating-icosphere-mesh-in-code.html
# hierarchy:
# Icosphere -> Triangle -> Point
class IcoSphere:
"""
Usage: IcoSphere(level)
Maximum supported level =... | """Subdivided icosahedral mesh generation"""
from __future__ import print_function
import numpy as np
# following: http://blog.andreaskahler.com/2009/06/creating-icosphere-mesh-in-code.html
# hierarchy:
# Icosphere -> Triangle -> Point
class IcoSphere:
"""
Usage: IcoSphere(level)
Maximum supported level =... | en | 0.615121 | Subdivided icosahedral mesh generation # following: http://blog.andreaskahler.com/2009/06/creating-icosphere-mesh-in-code.html # hierarchy: # Icosphere -> Triangle -> Point Usage: IcoSphere(level) Maximum supported level = 8 get started with: >>> A = IcoSphere(3) ... A.plot3d() # maximum level for ... | 3.419049 | 3 |
src/main.py | Lidenbrock-ed/challenge-prework-backend-python | 0 | 7983 | <gh_stars>0
# Resolve the problem!!
import string
import random
SYMBOLS = list('!"#$%&\'()*+,-./:;?@[]^_`{|}~')
def generate_password():
# Start coding here
letters_min = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','x','y','z']
letters_may = ['A','B','C','D','E... | # Resolve the problem!!
import string
import random
SYMBOLS = list('!"#$%&\'()*+,-./:;?@[]^_`{|}~')
def generate_password():
# Start coding here
letters_min = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','x','y','z']
letters_may = ['A','B','C','D','E','F','G','H... | en | 0.676035 | # Resolve the problem!! # Start coding here | 3.699143 | 4 |
targets/baremetal-sdk/curie-bsp/setup.py | ideas-detoxes/jerryscript | 4,324 | 7984 | #!/usr/bin/env python
# Copyright JS Foundation and other contributors, http://js.foundation
#
# 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.... | #!/usr/bin/env python
# Copyright JS Foundation and other contributors, http://js.foundation
#
# 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.... | en | 0.741096 | #!/usr/bin/env python # Copyright JS Foundation and other contributors, http://js.foundation # # 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... | 2.049077 | 2 |
pythonteste/aula08a.py | genisyskernel/cursoemvideo-python | 1 | 7985 | from math import sqrt
import emoji
num = int(input("Digite um número: "))
raiz = sqrt(num)
print("A raiz do número {0} é {1:.2f}.".format(num, raiz))
print(emoji.emojize("Hello World! :earth_americas:", use_aliases=True))
| from math import sqrt
import emoji
num = int(input("Digite um número: "))
raiz = sqrt(num)
print("A raiz do número {0} é {1:.2f}.".format(num, raiz))
print(emoji.emojize("Hello World! :earth_americas:", use_aliases=True))
| none | 1 | 4.239592 | 4 | |
duke-cs671-fall21-coupon-recommendation/outputs/rules/RF/17_features/numtrees_30/rule_20.py | apcarrik/kaggle | 0 | 7986 | <reponame>apcarrik/kaggle
def findDecision(obj): #obj[0]: Passanger, obj[1]: Weather, obj[2]: Time, obj[3]: Coupon, obj[4]: Coupon_validity, obj[5]: Gender, obj[6]: Age, obj[7]: Maritalstatus, obj[8]: Children, obj[9]: Education, obj[10]: Occupation, obj[11]: Income, obj[12]: Bar, obj[13]: Coffeehouse, obj[14]: Restaur... | def findDecision(obj): #obj[0]: Passanger, obj[1]: Weather, obj[2]: Time, obj[3]: Coupon, obj[4]: Coupon_validity, obj[5]: Gender, obj[6]: Age, obj[7]: Maritalstatus, obj[8]: Children, obj[9]: Education, obj[10]: Occupation, obj[11]: Income, obj[12]: Bar, obj[13]: Coffeehouse, obj[14]: Restaurant20to50, obj[15]: Direct... | en | 0.484483 | #obj[0]: Passanger, obj[1]: Weather, obj[2]: Time, obj[3]: Coupon, obj[4]: Coupon_validity, obj[5]: Gender, obj[6]: Age, obj[7]: Maritalstatus, obj[8]: Children, obj[9]: Education, obj[10]: Occupation, obj[11]: Income, obj[12]: Bar, obj[13]: Coffeehouse, obj[14]: Restaurant20to50, obj[15]: Direction_same, obj[16]: Dist... | 2.743604 | 3 |
main.py | AdrienCourtois/DexiNed | 0 | 7987 |
from __future__ import print_function
import argparse
import os
import time, platform
import cv2
import torch
import torch.optim as optim
from torch.utils.data import DataLoader
from datasets import DATASET_NAMES, BipedDataset, TestDataset, dataset_info
from losses import *
from model import DexiNed
# from model0C ... |
from __future__ import print_function
import argparse
import os
import time, platform
import cv2
import torch
import torch.optim as optim
from torch.utils.data import DataLoader
from datasets import DATASET_NAMES, BipedDataset, TestDataset, dataset_info
from losses import *
from model import DexiNed
# from model0C ... | en | 0.662844 | # from model0C import DexiNed # Put model in training mode # l_weight = [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 1.1] # for bdcn ori loss # before [0.6,0.6,1.1,1.1,0.4,0.4,1.3] [0.4,0.4,1.1,1.1,0.6,0.6,1.3],[0.4,0.4,1.1,1.1,0.8,0.8,1.3] # for bdcn loss theory 3 before the last 1.3 0.6-0..5 # l_weight = [[0.05, 2.], [0.05, 2.], ... | 2.191823 | 2 |
src/core/build/pretreat_targets.py | chaoyangcui/test_developertest | 0 | 7988 | <gh_stars>0
#!/usr/bin/env python3
# coding=utf-8
#
# Copyright (c) 2021 Huawei Device 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-... | #!/usr/bin/env python3
# coding=utf-8
#
# Copyright (c) 2021 Huawei Device 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
#
# Unle... | en | 0.343732 | #!/usr/bin/env python3 # coding=utf-8 # # Copyright (c) 2021 Huawei Device 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 # # Unles... | 2.132674 | 2 |
tests/testapp/urls.py | lukaszbanasiak/django-contrib-comments | 1 | 7989 | from __future__ import absolute_import
from django.conf.urls import patterns, url
from django_comments.feeds import LatestCommentFeed
from custom_comments import views
feeds = {
'comments': LatestCommentFeed,
}
urlpatterns = patterns('',
url(r'^post/$', views.custom_submit_comment),
url(r'^flag/(\d+)... | from __future__ import absolute_import
from django.conf.urls import patterns, url
from django_comments.feeds import LatestCommentFeed
from custom_comments import views
feeds = {
'comments': LatestCommentFeed,
}
urlpatterns = patterns('',
url(r'^post/$', views.custom_submit_comment),
url(r'^flag/(\d+)... | none | 1 | 1.829459 | 2 | |
pyTorch/utils.py | rajasekar-venkatesan/Deep_Learning | 0 | 7990 | <reponame>rajasekar-venkatesan/Deep_Learning
import pandas as pd, numpy as np
from sklearn.preprocessing import OneHotEncoder
author_int_dict = {'EAP':0,'HPL':1,'MWS':2}
def load_train_test_data (num_samples=None):
train_data = pd.read_csv('../data/train.csv')
train_data['author'] = [author_int_dict[a]... | import pandas as pd, numpy as np
from sklearn.preprocessing import OneHotEncoder
author_int_dict = {'EAP':0,'HPL':1,'MWS':2}
def load_train_test_data (num_samples=None):
train_data = pd.read_csv('../data/train.csv')
train_data['author'] = [author_int_dict[a] for a in train_data['author'].tolist()]
... | en | 0.208363 | #labels = OneHotEncoder().fit_transform(labels).todense() | 3.165597 | 3 |
example/dec/dec.py | TheBurningCrusade/A_mxnet | 159 | 7991 | # pylint: skip-file
import sys
import os
# code to automatically download dataset
curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
sys.path = [os.path.join(curr_path, "../autoencoder")] + sys.path
import mxnet as mx
import numpy as np
import data
from scipy.spatial.distance import cdist
from s... | # pylint: skip-file
import sys
import os
# code to automatically download dataset
curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
sys.path = [os.path.join(curr_path, "../autoencoder")] + sys.path
import mxnet as mx
import numpy as np
import data
from scipy.spatial.distance import cdist
from s... | en | 0.447345 | # pylint: skip-file # code to automatically download dataset | 2.471548 | 2 |
cctbx/maptbx/tst_target_and_gradients.py | rimmartin/cctbx_project | 0 | 7992 | from __future__ import division
from cctbx.array_family import flex
from cctbx import xray
from cctbx import crystal
from cctbx import maptbx
from cctbx.maptbx import minimization
from libtbx.test_utils import approx_equal
import random
from cctbx.development import random_structure
from cctbx import sgtbx
if (1):
r... | from __future__ import division
from cctbx.array_family import flex
from cctbx import xray
from cctbx import crystal
from cctbx import maptbx
from cctbx.maptbx import minimization
from libtbx.test_utils import approx_equal
import random
from cctbx.development import random_structure
from cctbx import sgtbx
if (1):
r... | en | 0.320213 | Exercise maptbx.target_and_gradients_diffmap . Exercise maptbx.target_and_gradients_diffmap in action: minimization. Exercise maptbx.target_and_gradients_diffmap in action: minimization (bigger model). Exercise maptbx.target_and_gradients_simple. # Exercise maptbx.target_and_gradients_simple in action: minimization ... | 1.747131 | 2 |
open_imagilib/matrix.py | viktor-ferenczi/open-imagilib | 2 | 7993 | <gh_stars>1-10
""" LED matrix
"""
__all__ = ['Matrix']
from .colors import Color, on, off
from .fonts import font_6x8
class Matrix(list):
def __init__(self, source=None) -> None:
if source is None:
row_iter = ([off for _ in range(8)] for _ in range(8))
elif isinstance(source, list):
... | """ LED matrix
"""
__all__ = ['Matrix']
from .colors import Color, on, off
from .fonts import font_6x8
class Matrix(list):
def __init__(self, source=None) -> None:
if source is None:
row_iter = ([off for _ in range(8)] for _ in range(8))
elif isinstance(source, list):
row... | en | 0.844907 | LED matrix | 3.275832 | 3 |
prml/linear/_classifier.py | alexandru-dinu/PRML | 0 | 7994 | <filename>prml/linear/_classifier.py
class Classifier(object):
"""Base class for classifiers."""
| <filename>prml/linear/_classifier.py
class Classifier(object):
"""Base class for classifiers."""
| en | 0.714258 | Base class for classifiers. | 1.32588 | 1 |
tests/env_config/test_base.py | DAtek/datek-app-utils | 0 | 7995 | from pytest import raises
from datek_app_utils.env_config.base import BaseConfig
from datek_app_utils.env_config.errors import InstantiationForbiddenError
class SomeOtherMixinWhichDoesntRelateToEnvConfig:
color = "red"
class TestConfig:
def test_iter(self, monkeypatch, key_volume, base_config_class):
... | from pytest import raises
from datek_app_utils.env_config.base import BaseConfig
from datek_app_utils.env_config.errors import InstantiationForbiddenError
class SomeOtherMixinWhichDoesntRelateToEnvConfig:
color = "red"
class TestConfig:
def test_iter(self, monkeypatch, key_volume, base_config_class):
... | none | 1 | 2.185494 | 2 | |
comprehend.py | korniichuk/cvr-features | 0 | 7996 | # -*- coding: utf-8 -*-
# Name: comprehend
# Version: 0.1a2
# Owner: <NAME>
# Maintainer(s):
import boto3
def get_sentiment(text, language_code='en'):
"""Get sentiment.
Inspects text and returns an inference of the prevailing sentiment
(positive, neutral, mixed, or negative).
Args:
text: UT... | # -*- coding: utf-8 -*-
# Name: comprehend
# Version: 0.1a2
# Owner: <NAME>
# Maintainer(s):
import boto3
def get_sentiment(text, language_code='en'):
"""Get sentiment.
Inspects text and returns an inference of the prevailing sentiment
(positive, neutral, mixed, or negative).
Args:
text: UT... | en | 0.929776 | # -*- coding: utf-8 -*- # Name: comprehend # Version: 0.1a2 # Owner: <NAME> # Maintainer(s): Get sentiment. Inspects text and returns an inference of the prevailing sentiment (positive, neutral, mixed, or negative). Args: text: UTF-8 text string. Each string must contain fewer that 5... | 3.325627 | 3 |
mapclientplugins/argonsceneexporterstep/ui_configuredialog.py | Kayvv/mapclientplugins.argonsceneexporterstep | 0 | 7997 | <gh_stars>0
# -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'configuredialog.ui'
##
## Created by: Qt User Interface Compiler version 5.15.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file... | # -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'configuredialog.ui'
##
## Created by: Qt User Interface Compiler version 5.15.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
##########... | de | 0.413164 | # -*- coding: utf-8 -*- ################################################################################ ## Form generated from reading UI file 'configuredialog.ui' ## ## Created by: Qt User Interface Compiler version 5.15.2 ## ## WARNING! All changes made in this file will be lost when recompiling UI file! ###########... | 2.110821 | 2 |
pbx_gs_python_utils/lambdas/utils/puml_to_slack.py | owasp-sbot/pbx-gs-python-utils | 3 | 7998 | <reponame>owasp-sbot/pbx-gs-python-utils<filename>pbx_gs_python_utils/lambdas/utils/puml_to_slack.py<gh_stars>1-10
import base64
import tempfile
import requests
from osbot_aws.apis import Secrets
from osbot_aws.apis.Lambdas import Lambdas
def upload_png_file(channel_id, file):
bot_token = Secret... | import base64
import tempfile
import requests
from osbot_aws.apis import Secrets
from osbot_aws.apis.Lambdas import Lambdas
def upload_png_file(channel_id, file):
bot_token = Secrets('slack-gs-bot').value()
my_file = {
'file': ('/tmp/myfile.png', open(file, 'rb'), 'png')
}
p... | none | 1 | 2.301006 | 2 | |
src/system_io/input.py | DeseineClement/bigdata-housing-classifier | 0 | 7999 | from sys import argv
from getopt import getopt
from os import R_OK, access
from string import Template
DEFAULT_DATASET_FILE_PATH = "dataset/data.csv"
DEFAULT_DATASET_COLUMNS = ['surface (m2)', 'height (m)', 'latitude', 'housing_type', 'longitude', 'country_code',
'city']
DEFAULT_VISU = ["sca... | from sys import argv
from getopt import getopt
from os import R_OK, access
from string import Template
DEFAULT_DATASET_FILE_PATH = "dataset/data.csv"
DEFAULT_DATASET_COLUMNS = ['surface (m2)', 'height (m)', 'latitude', 'housing_type', 'longitude', 'country_code',
'city']
DEFAULT_VISU = ["sca... | none | 1 | 2.956936 | 3 |