blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
288
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
112
| license_type
stringclasses 2
values | repo_name
stringlengths 5
115
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 684
values | visit_date
timestamp[us]date 2015-08-06 10:31:46
2023-09-06 10:44:38
| revision_date
timestamp[us]date 1970-01-01 02:38:32
2037-05-03 13:00:00
| committer_date
timestamp[us]date 1970-01-01 02:38:32
2023-09-06 01:08:06
| github_id
int64 4.92k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-04 01:52:49
2023-09-14 21:59:50
⌀ | gha_created_at
timestamp[us]date 2008-05-22 07:58:19
2023-08-21 12:35:19
⌀ | gha_language
stringclasses 147
values | src_encoding
stringclasses 25
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 128
12.7k
| extension
stringclasses 142
values | content
stringlengths 128
8.19k
| authors
listlengths 1
1
| author_id
stringlengths 1
132
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0099d67f95506a2f31cda7626005a332d94f78ee
|
2aaa58e7a83c4c8a4a2aa8b4a70df95a1ca10f19
|
/s_full1.py
|
de1275e660df53dc31509a7dc24c722912520572
|
[] |
no_license
|
federico0712/elitepro_astm
|
84cd8b1c3095f24a1cfded573debcd12894d60eb
|
07c2cc8dd3db58b966eeb138484a1fd073e65dde
|
refs/heads/master
| 2022-04-14T16:15:31.370068
| 2020-03-17T03:49:41
| 2020-03-17T03:49:41
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,373
|
py
|
#!/usr/bin/python3
import sys
import signal
import datetime
import serial
import logging
'''
This program reads all bytes and writes them to a file in /root/elite folder
first byte is ENQ last one is EOT
This help in capturing everything between ENQ and EOT and learn equipment specific need
'''
output_folder='/root/elite/' #remember ending/
input_tty='/dev/ttyUSB0'
def get_filename():
dt=datetime.datetime.now()
return output_folder+dt.strftime("%Y-%m-%d-%H-%M-%S-%f")
#Globals############################
byte_array=[]
byte=b'd'
#main loop##########################
port = serial.Serial(input_tty, baudrate=9600)
while byte!=b'':
byte=port.read(1)
byte_array=byte_array+[chr(ord(byte))] #add everything read to array
if(byte==b'\x05'):
port.write(b'\x06');
cur_file=get_filename() #get name of file to open
x=open(cur_file,'w') #open file
print("<ENQ>")
elif(byte==b'\x0a'):
print("<LF>")
port.write(b'\x06');
x.write(''.join(byte_array)) #write to file everytime LF received, to prevent big data memory problem
byte_array=[] #empty after writing
elif(byte==b'\x04'):
print("<EOF>")
x.write(''.join(byte_array)) #write last byte(EOF) to file
byte_array=[] #empty array
x.close() #close file
#else:
#byte_array=byte_array+[chr(ord(byte))]
|
[
"root@debian"
] |
root@debian
|
28707766a97f29fb0ccf49800aa19a65d89a6697
|
53fab060fa262e5d5026e0807d93c75fb81e67b9
|
/backup/user_355/ch117_2020_03_30_19_48_40_877571.py
|
985e837a3949e7e8f671c81eba218bc0348f2386
|
[] |
no_license
|
gabriellaec/desoft-analise-exercicios
|
b77c6999424c5ce7e44086a12589a0ad43d6adca
|
01940ab0897aa6005764fc220b900e4d6161d36b
|
refs/heads/main
| 2023-01-31T17:19:42.050628
| 2020-12-16T05:21:31
| 2020-12-16T05:21:31
| 306,735,108
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 152
|
py
|
import math
def snell_descartes (o2, o1, n1, n2 ):
o2 = arcsin(math.sin(o1)*(n1/n2))
y = o2 * 180 / math.pi
return degrees ( arcsin ( o2 ))
|
[
"you@example.com"
] |
you@example.com
|
7e94b07d17aaa223c1697a14ed1951afe126ebe0
|
8a25ada37271acd5ea96d4a4e4e57f81bec221ac
|
/home/pi/GrovePi/Software/Python/others/temboo/Library/Tumblr/Post/CreateLinkPost.py
|
ac3b9be49dc57291e0f74fc746a2da6b46aca1b7
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
lupyuen/RaspberryPiImage
|
65cebead6a480c772ed7f0c4d0d4e08572860f08
|
664e8a74b4628d710feab5582ef59b344b9ffddd
|
refs/heads/master
| 2021-01-20T02:12:27.897902
| 2016-11-17T17:32:30
| 2016-11-17T17:32:30
| 42,438,362
| 7
| 8
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 7,045
|
py
|
# -*- coding: utf-8 -*-
###############################################################################
#
# CreateLinkPost
# Creates a new link post for a specified Tumblr blog.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo 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 in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
#
#
###############################################################################
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class CreateLinkPost(Choreography):
def __init__(self, temboo_session):
"""
Create a new instance of the CreateLinkPost Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
"""
super(CreateLinkPost, self).__init__(temboo_session, '/Library/Tumblr/Post/CreateLinkPost')
def new_input_set(self):
return CreateLinkPostInputSet()
def _make_result_set(self, result, path):
return CreateLinkPostResultSet(result, path)
def _make_execution(self, session, exec_id, path):
return CreateLinkPostChoreographyExecution(session, exec_id, path)
class CreateLinkPostInputSet(InputSet):
"""
An InputSet with methods appropriate for specifying the inputs to the CreateLinkPost
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
"""
def set_URL(self, value):
"""
Set the value of the URL input for this Choreo. ((required, string) The link you want to post.)
"""
super(CreateLinkPostInputSet, self)._set_input('URL', value)
def set_APIKey(self, value):
"""
Set the value of the APIKey input for this Choreo. ((required, string) The API Key provided by Tumblr (AKA the OAuth Consumer Key).)
"""
super(CreateLinkPostInputSet, self)._set_input('APIKey', value)
def set_AccessTokenSecret(self, value):
"""
Set the value of the AccessTokenSecret input for this Choreo. ((required, string) The Access Token Secret retrieved during the OAuth process.)
"""
super(CreateLinkPostInputSet, self)._set_input('AccessTokenSecret', value)
def set_AccessToken(self, value):
"""
Set the value of the AccessToken input for this Choreo. ((required, string) The Access Token retrieved during the OAuth process.)
"""
super(CreateLinkPostInputSet, self)._set_input('AccessToken', value)
def set_BaseHostname(self, value):
"""
Set the value of the BaseHostname input for this Choreo. ((required, string) The standard or custom blog hostname (i.e. temboo.tumblr.com).)
"""
super(CreateLinkPostInputSet, self)._set_input('BaseHostname', value)
def set_Date(self, value):
"""
Set the value of the Date input for this Choreo. ((optional, date) The GMT date and time of the post. Can be an epoch timestamp in milliseconds or formatted like: Dec 8th, 2011 4:03pm. Defaults to NOW().)
"""
super(CreateLinkPostInputSet, self)._set_input('Date', value)
def set_Description(self, value):
"""
Set the value of the Description input for this Choreo. ((optional, string) A user-supplied description. HTML is allowed.)
"""
super(CreateLinkPostInputSet, self)._set_input('Description', value)
def set_Markdown(self, value):
"""
Set the value of the Markdown input for this Choreo. ((optional, boolean) Indicates whether the post uses markdown syntax. Defaults to false. Set to 1 to indicate true.)
"""
super(CreateLinkPostInputSet, self)._set_input('Markdown', value)
def set_ResponseFormat(self, value):
"""
Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that the response should be in. Can be set to xml or json. Defaults to json.)
"""
super(CreateLinkPostInputSet, self)._set_input('ResponseFormat', value)
def set_SecretKey(self, value):
"""
Set the value of the SecretKey input for this Choreo. ((required, string) The Secret Key provided by Tumblr (AKA the OAuth Consumer Secret).)
"""
super(CreateLinkPostInputSet, self)._set_input('SecretKey', value)
def set_Slug(self, value):
"""
Set the value of the Slug input for this Choreo. ((optional, string) Adds a short text summary to the end of the post URL.)
"""
super(CreateLinkPostInputSet, self)._set_input('Slug', value)
def set_State(self, value):
"""
Set the value of the State input for this Choreo. ((optional, string) The state of the post. Specify one of the following: published, draft, queue. Defaults to published.)
"""
super(CreateLinkPostInputSet, self)._set_input('State', value)
def set_Tags(self, value):
"""
Set the value of the Tags input for this Choreo. ((optional, string) Comma-separated tags for this post.)
"""
super(CreateLinkPostInputSet, self)._set_input('Tags', value)
def set_Title(self, value):
"""
Set the value of the Title input for this Choreo. ((optional, string) The title of the page the link points to. HTML entities should be escaped.)
"""
super(CreateLinkPostInputSet, self)._set_input('Title', value)
def set_Tweet(self, value):
"""
Set the value of the Tweet input for this Choreo. ((optional, string) Manages the autotweet (if enabled) for this post. Set to "off" for no tweet. Enter text to override the default tweet.)
"""
super(CreateLinkPostInputSet, self)._set_input('Tweet', value)
class CreateLinkPostResultSet(ResultSet):
"""
A ResultSet with methods tailored to the values returned by the CreateLinkPost Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
"""
def getJSONFromString(self, str):
return json.loads(str)
def get_Response(self):
"""
Retrieve the value for the "Response" output from this Choreo execution. (The response from Tumblr. Default is JSON, can be set to XML by entering 'xml' in ResponseFormat.)
"""
return self._output.get('Response', None)
class CreateLinkPostChoreographyExecution(ChoreographyExecution):
def _make_result_set(self, response, path):
return CreateLinkPostResultSet(response, path)
|
[
"lupyuen@gmail.com"
] |
lupyuen@gmail.com
|
1de081acd200b031145320d70d79be19ae3a8312
|
9510cd7f96e2cd6b8751fab988038228fe0568c7
|
/python/0343.Integer Break.py
|
fb6b957010a895615056dfe72d6838cee56b60b0
|
[] |
no_license
|
juechen-zzz/LeetCode
|
2df2e7efe2efe22dc1016447761a629a0da65eda
|
b5926a3d40ca4a9939e1d604887e0ad7e9501f16
|
refs/heads/master
| 2021-08-11T00:37:18.891256
| 2021-06-13T10:26:31
| 2021-06-13T10:26:31
| 180,496,839
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 492
|
py
|
"""
给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。
"""
class Solution:
def integerBreak(self, n: int) -> int:
dp = [1] * (n + 1)
for i in range(3, n+1):
for j in range(1, int(i / 2) + 1):
# 会出现极限情况,比如dp[2]=1,不应该拆2的
dp[i] = max(dp[i], max(dp[i-j], i-j) * max(dp[j], j))
return dp[-1]
|
[
"240553516@qq.com"
] |
240553516@qq.com
|
1e31bced9e56926fe0f486d8dd135d8d6c560de0
|
23611933f0faba84fc82a1bc0a85d97cf45aba99
|
/google-cloud-sdk/.install/.backup/lib/googlecloudsdk/api_lib/app/ext_runtimes/fingerprinting.py
|
083b9008e3b6aa13e21c03c748a2c8a5680106dc
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
KaranToor/MA450
|
1f112d1caccebdc04702a77d5a6cee867c15f75c
|
c98b58aeb0994e011df960163541e9379ae7ea06
|
refs/heads/master
| 2021-06-21T06:17:42.585908
| 2020-12-24T00:36:28
| 2020-12-24T00:36:28
| 79,285,433
| 1
| 1
|
Apache-2.0
| 2020-12-24T00:38:09
| 2017-01-18T00:05:44
|
Python
|
UTF-8
|
Python
| false
| false
| 3,153
|
py
|
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common functionality to support source fingerprinting."""
from googlecloudsdk.core import properties
_PROMPTS_DISABLED_ERROR_MESSAGE = (
'("disable_prompts" set to true, run "gcloud config set disable_prompts '
'False" to fix this)')
class Params(object):
"""Parameters passed to the the runtime module Fingerprint() methods.
Attributes:
appinfo: (apphosting.api.appinfo.AppInfoExternal or None) The parsed
app.yaml file for the module if it exists.
custom: (bool) True if the Configurator should generate a custom runtime.
runtime (str or None) Runtime (alias allowed) that should be enforced.
deploy: (bool) True if this is happening from deployment.
"""
def __init__(self, appinfo=None, custom=False, runtime=None, deploy=False):
self.appinfo = appinfo
self.custom = custom
self.runtime = runtime
self.deploy = deploy
def ToDict(self):
"""Returns the object converted to a dictionary.
Returns:
({str: object}) A dictionary that can be converted to json using
json.dump().
"""
return {'appinfo': self.appinfo and self.appinfo.ToDict(),
'custom': self.custom,
'runtime': self.runtime,
'deploy': self.deploy}
class Configurator(object):
"""Base configurator class.
Configurators generate config files for specific classes of runtimes. They
are returned by the Fingerprint functions in the runtimes sub-package after
a successful match of the runtime's heuristics.
"""
def GenerateConfigs(self):
"""Generate all configuration files for the module.
Generates config files in the current working directory.
Returns:
(callable()) Function that will delete all of the generated files.
"""
raise NotImplementedError()
def GetNonInteractiveErrorMessage():
"""Returns useful instructions when running non-interactive.
Certain fingerprinting modules require interactive functionality. It isn't
always obvious why gcloud is running in non-interactive mode (e.g. when
"disable_prompts" is set) so this returns an appropriate addition to the
error message in these circumstances.
Returns:
(str) The appropriate error message snippet.
"""
if properties.VALUES.core.disable_prompts.GetBool():
# We add a leading space to the raw message so that it meshes well with
# its display context.
return ' ' + _PROMPTS_DISABLED_ERROR_MESSAGE
else:
# The other case for non-interactivity (running detached from a terminal)
# should be obvious.
return ''
|
[
"toork@uw.edu"
] |
toork@uw.edu
|
1c2c7f77375d17cca4387f409b1116c826cd6c24
|
7f593761058b96792e51023e3b42af740f2006d7
|
/pkg/ampcor/dom/Raster.py
|
1366bf502713ca054646e88ecfdcc8ecdc06a924
|
[
"BSD-2-Clause"
] |
permissive
|
isce-framework/ampcor
|
2b3769e579ceaf993c9ea17f836553057a52ad6a
|
eafadcbe4380a85320d8c7e884ebe4d6d279770e
|
refs/heads/master
| 2020-05-07T16:06:06.364458
| 2019-04-10T22:09:45
| 2019-04-10T22:09:45
| 180,668,210
| 3
| 3
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 959
|
py
|
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis <michael.aivazis@para-sim.com>
# parasim
# (c) 1998-2019 all rights reserved
#
# framework
import ampcor
# declaration
class Raster(ampcor.protocol, family="ampcor.dom.rasters"):
"""
The base class for all pixel based data products
"""
# public data
shape = ampcor.properties.tuple(schema=ampcor.properties.int())
shape.doc = "the shape of the raster in pixels"
data = ampcor.properties.path()
data.doc = "the path to my binary data"
# requirements
@ampcor.provides
def size(self):
"""
Compute my memory footprint
"""
@ampcor.provides
def slice(self, begin, end):
"""
Grant access to a slice of my data bound by the index pair {begin} and {end}
"""
@ampcor.provides
def open(self, filename, mode="r"):
"""
Map me over the contents of {filename}
"""
# end of file
|
[
"michael.aivazis@para-sim.com"
] |
michael.aivazis@para-sim.com
|
4c698ed3717c85f27f6df1de04780252abdbb4b8
|
c0a7d9a057abbd1a065a4149b96777163e596727
|
/Placement Prepration/Recursion/lucky_number.py
|
286455a2666bc95261ea05ef88d07e5487863118
|
[] |
no_license
|
Sameer2898/Data-Structure-And-Algorithims
|
6471c2dabfbd2067d2a2c556ddd0b6615235cd4f
|
2f251570434ea9c1881de95b4b1a5e368d5b7f46
|
refs/heads/main
| 2023-02-16T16:18:08.177109
| 2021-01-14T06:33:22
| 2021-01-14T06:33:22
| 329,527,964
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 382
|
py
|
def isLucky(n):
global c
if c <= n:
if n % c == 0:
return 0
n = n-n//c
c += 1
return isLucky(n)
else:
return 1
c=2
if __name__ == '__main__':
t = int(input('Enter the number of test cases:- '))
for tcs in range(t):
c=2
n = int(input('Enter a number:- '))
print(isLucky(n))
|
[
"xdgsr1234@gmail.com"
] |
xdgsr1234@gmail.com
|
5780cc90cf158da08e08e1ce41888a4a1a87c818
|
a39ecd4dce4b14f5d17416233fa16c76d2d3f165
|
/Libraries/Python/CommonEnvironment/v1.0/CommonEnvironment/UnitTests/Process_UnitTest.py
|
9ea28ebb7b3352eaf881e69ecb187d70d541205f
|
[
"BSL-1.0",
"Python-2.0",
"OpenSSL",
"LicenseRef-scancode-unknown-license-reference",
"GPL-2.0-only"
] |
permissive
|
davidbrownell/Common_Environment_v3
|
8e6bbed15004a38a4c6e6f337d78eb2339484d64
|
2981ad1566e6d3c00fd390a67dbc1277ef40aaba
|
refs/heads/master
| 2022-09-03T19:04:57.270890
| 2022-06-28T01:33:31
| 2022-06-28T01:33:31
| 132,171,665
| 0
| 0
|
BSL-1.0
| 2021-08-13T21:19:48
| 2018-05-04T17:47:30
|
Python
|
UTF-8
|
Python
| false
| false
| 1,527
|
py
|
# ----------------------------------------------------------------------
# |
# | Process_UnitTest.py
# |
# | David Brownell <db@DavidBrownell.com>
# | 2018-08-21 07:38:01
# |
# ----------------------------------------------------------------------
# |
# | Copyright David Brownell 2018-22.
# | Distributed under the Boost Software License, Version 1.0.
# | (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
# |
# ----------------------------------------------------------------------
"""Unit test for Process.py"""
import os
import sys
import unittest
import CommonEnvironment
from CommonEnvironment.Process import *
# ----------------------------------------------------------------------
_script_fullpath = CommonEnvironment.ThisFullpath()
_script_dir, _script_name = os.path.split(_script_fullpath)
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
class StandardSuite(unittest.TestCase):
@unittest.skip("Not implemented")
def test_Placeholder(self):
self.assertTrue(False)
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
if __name__ == "__main__":
try: sys.exit(unittest.main(verbosity=2))
except KeyboardInterrupt: pass
|
[
"db@DavidBrownell.com"
] |
db@DavidBrownell.com
|
10aa036fce0bea713f5078ed34e900100942a4dd
|
9d733284e31476d85a42e2e2614c7a4cfed5aed1
|
/test/test_payment_setup_response_initiation.py
|
17f9b8d526229a97464b21c8929c57a54c440858
|
[
"MIT"
] |
permissive
|
roksela/openbanking-payment-client
|
be138ff7403989b8bce7ad7e95e885c676e7ad29
|
a17b3ded257e71be1dbf6bde6e206dd2f2abddd8
|
refs/heads/master
| 2021-04-29T17:17:27.102309
| 2018-02-17T08:07:40
| 2018-02-17T08:07:40
| 121,665,228
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,149
|
py
|
# coding: utf-8
"""
Python client for Payment Initiation API
Based on https://github.com/OpenBankingUK/payment-initiation-api-spec
OpenAPI spec version: v1.1.1
Spec: https://www.openbanking.org.uk/read-write-apis/
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import openbanking_payment_client
from openbanking_payment_client.model.payment_setup_response_initiation import PaymentSetupResponseInitiation # noqa: E501
from openbanking_payment_client.rest import ApiException
class TestPaymentSetupResponseInitiation(unittest.TestCase):
"""PaymentSetupResponseInitiation unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testPaymentSetupResponseInitiation(self):
"""Test PaymentSetupResponseInitiation"""
# FIXME: construct object with mandatory attributes with example values
# model = openbanking_payment_client.models.payment_setup_response_initiation.PaymentSetupResponseInitiation() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
|
[
"kris@dataservices.pro"
] |
kris@dataservices.pro
|
345a712888b96f9f8a07c642769a53db19af8b02
|
4a48593a04284ef997f377abee8db61d6332c322
|
/python/matplotlib/imshow_plt.py
|
f5fb22bf13f8310cc833ec64bc15b398c0e3947a
|
[
"MIT"
] |
permissive
|
jeremiedecock/snippets
|
8feaed5a8d873d67932ef798e16cb6d2c47609f0
|
b90a444041c42d176d096fed14852d20d19adaa7
|
refs/heads/master
| 2023-08-31T04:28:09.302968
| 2023-08-21T07:22:38
| 2023-08-21T07:22:38
| 36,926,494
| 26
| 9
|
MIT
| 2023-06-06T02:17:44
| 2015-06-05T10:19:09
|
Python
|
UTF-8
|
Python
| false
| false
| 1,081
|
py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Display data as an image (via pyplot)
See: http://matplotlib.org/examples/pylab_examples/image_demo.html
See also:
- http://matplotlib.org/examples/color/colormaps_reference.html (the list of all colormaps)
- http://matplotlib.org/users/colormaps.html?highlight=colormap#mycarta-banding (what is the right colormap to choose for a given plot)
"""
import numpy as np
import matplotlib.pyplot as plt
# MAKE DATAS ##################################################################
z_matrix = np.array([[xi * yi for xi in range(50)] for yi in range(50)])
# PLOT ########################################################################
# The list of all colormaps: http://matplotlib.org/examples/color/colormaps_reference.html
#interp='nearest' # "raw" (non smooth) map
interp = 'bilinear' # "smooth" map
plt.imshow(z_matrix, interpolation=interp, origin='lower')
plt.colorbar() # draw colorbar
# SAVE AND SHOW ###############################################################
plt.savefig("imshow_plt.png")
plt.show()
|
[
"jd.jdhp@gmail.com"
] |
jd.jdhp@gmail.com
|
de4c2a2948208b3b66fa65fdcb3f6e3e5189fced
|
cc9cf69b1534dc0d9530b4ff485084162a404e34
|
/create_date/creat_idcare.py
|
8f82e64de6c858a560cdd206f051e34b51942b1d
|
[] |
no_license
|
NASA2333/study
|
99a58b2c9979201e9a4fae0c797391a538de6f45
|
ba63bc18f3c788090e43406315497329b00ec0a5
|
refs/heads/master
| 2021-05-03T22:26:52.541760
| 2018-02-07T02:24:55
| 2018-02-07T02:24:55
| 104,988,265
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 858
|
py
|
import random
for i in range(1001):
Birthday =[] #生日
addrs =[str(random.choice(range(110000,999999))).zfill(6)] #地区
order = [str(random.choice(range(0,999))).zfill(3)] #序列
mult = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2]
check = [1,0,'X',9,8,7,6,5,4,3,2]
year = str(random.randint(1960,2017))
month = str(random.choice(range(1,13))).zfill(2)
if month ==2:
days = random.choice(range(1,29))
days = str(days).zfill(2)
elif month in (1,3,5,7,8,10,12):
days = str(random.choice(range(1,32))).zfill(2)
else:
days = str(random.choice(range(1,31))).zfill(2)
Birthday.extend((year,month,days))
list1 = addrs+Birthday+order
list2 =''.join(list1)
sum = 0
for i in range(len(list2)):
avg1 =int(list2[i])*mult[i]
sum +=avg1
mod = check[sum%11]
xpath = open(r'E:\idcare.txt','a')
xpath.write(list2+str(mod)+'\n')
|
[
"422282539@qq.com"
] |
422282539@qq.com
|
433b7cebbab4fb45f7bac8264fea88827e505dba
|
d5581fe82bbce4ae206bbfc8c6251cb19c87a5bf
|
/leetcode/python/065-validNumber.py
|
4d493885d458fa2b0746574e13fecccacdf96b70
|
[] |
no_license
|
yi-guo/coding-interview
|
23f2a422b69a84d648ba9d74ea1b05e42b8689af
|
fd22a407f096d7e0c4eefbeb4ed37e07043f185c
|
refs/heads/master
| 2016-09-06T11:15:41.133160
| 2015-03-28T22:30:52
| 2015-03-28T22:30:52
| 28,378,778
| 1
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,931
|
py
|
#!/usr/bin/python
# Validate if a given string is numeric.
# Some examples:
# "0" => true
# " 0.1 " => true
# "abc" => false
# "1 a" => false
# "2e10" => true
# Note: It is intended for the problem statement to be ambiguous.
# You should gather all requirements up front before implementing one.
import sys
# An automata solution. O(n).
def isNumber(s):
return s0(s.strip(), 0)
def s0(s, i):
if i == len(s):
return False
if s[i] == '.':
return s1(s, i + 1)
elif s[i] == '+' or s[i] == '-':
return s2(s, i + 1)
elif s[i].isdigit():
return s3(s, i + 1)
else:
return False
def s1(s, i):
if i == len(s):
return False
if s[i].isdigit():
return s4(s, i + 1)
else:
return False
def s2(s, i):
if i == len(s):
return False
if s[i] == '.':
return s1(s, i + 1)
elif s[i].isdigit():
return s3(s, i + 1)
else:
return False
def s3(s, i):
if i == len(s):
return True
if s[i] == '.':
return s4(s, i + 1)
elif s[i] == 'e':
return s5(s, i + 1)
elif s[i].isdigit():
return s3(s, i + 1)
else:
return False
def s4(s, i):
if i == len(s):
return True
if s[i] == 'e':
return s5(s, i + 1)
elif s[i].isdigit():
return s4(s, i + 1)
else:
return False
def s5(s, i):
if i == len(s):
return False
if s[i] == '+' or s[i] == '-':
return s6(s, i + 1)
elif s[i].isdigit():
return s7(s, i + 1)
else:
return False
def s6(s, i):
if i == len(s):
return False
if s[i].isdigit():
return s7(s, i + 1)
else:
return False
def s7(s, i):
if i == len(s):
return True
if s[i].isdigit():
return s7(s, i + 1)
else:
return False
def main():
print isNumber(sys.argv[1])
main()
|
[
"yi.guo@yahoo.com"
] |
yi.guo@yahoo.com
|
eff3f6c40e851c6068020b6fbbb0f2563e8ce039
|
12967293f285decb1568bd56af38b1df4e5c533d
|
/.eggs/boto-2.48.0-py2.7.egg/boto/pyami/installers/ubuntu/mysql.py
|
d844aaf25ce8a16b5337783fbd6f58d6feaf9a88
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT"
] |
permissive
|
martbhell/git-bigstore
|
36cd16276379833fbade252a77c73cf3644aa30f
|
960e9ea64d4d5646af3ce411adf46f3236b64d7e
|
refs/heads/master
| 2020-05-16T17:51:52.011171
| 2019-03-12T20:54:42
| 2019-03-12T20:54:42
| 183,206,409
| 0
| 0
|
Apache-2.0
| 2019-04-24T10:29:48
| 2019-04-24T10:29:47
| null |
UTF-8
|
Python
| false
| false
| 4,856
|
py
|
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# 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, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
"""
This installer will install mysql-server on an Ubuntu machine.
In addition to the normal installation done by apt-get, it will
also configure the new MySQL server to store it's data files in
a different location. By default, this is /mnt but that can be
configured in the [MySQL] section of the boto config file passed
to the instance.
"""
from boto.pyami.installers.ubuntu.installer import Installer
import os
import boto
from boto.utils import ShellCommand
from boto.compat import ConfigParser
import time
ConfigSection = """
[MySQL]
root_password = <will be used as MySQL root password, default none>
data_dir = <new data dir for MySQL, default is /mnt>
"""
class MySQL(Installer):
def install(self):
self.run('apt-get update')
self.run('apt-get -y install mysql-server', notify=True, exit_on_error=True)
# def set_root_password(self, password=None):
# if not password:
# password = boto.config.get('MySQL', 'root_password')
# if password:
# self.run('mysqladmin -u root password %s' % password)
# return password
def change_data_dir(self, password=None):
data_dir = boto.config.get('MySQL', 'data_dir', '/mnt')
fresh_install = False
is_mysql_running_command = ShellCommand('mysqladmin ping') # exit status 0 if mysql is running
is_mysql_running_command.run()
if is_mysql_running_command.getStatus() == 0:
# mysql is running. This is the state apt-get will leave it in. If it isn't running,
# that means mysql was already installed on the AMI and there's no need to stop it,
# saving 40 seconds on instance startup.
time.sleep(10) #trying to stop mysql immediately after installing it fails
# We need to wait until mysql creates the root account before we kill it
# or bad things will happen
i = 0
while self.run("echo 'quit' | mysql -u root") != 0 and i < 5:
time.sleep(5)
i = i + 1
self.run('/etc/init.d/mysql stop')
self.run("pkill -9 mysql")
mysql_path = os.path.join(data_dir, 'mysql')
if not os.path.exists(mysql_path):
self.run('mkdir %s' % mysql_path)
fresh_install = True
self.run('chown -R mysql:mysql %s' % mysql_path)
fp = open('/etc/mysql/conf.d/use_mnt.cnf', 'w')
fp.write('# created by pyami\n')
fp.write('# use the %s volume for data\n' % data_dir)
fp.write('[mysqld]\n')
fp.write('datadir = %s\n' % mysql_path)
fp.write('log_bin = %s\n' % os.path.join(mysql_path, 'mysql-bin.log'))
fp.close()
if fresh_install:
self.run('cp -pr /var/lib/mysql/* %s/' % mysql_path)
self.start('mysql')
else:
#get the password ubuntu expects to use:
config_parser = ConfigParser()
config_parser.read('/etc/mysql/debian.cnf')
password = config_parser.get('client', 'password')
# start the mysql deamon, then mysql with the required grant statement piped into it:
self.start('mysql')
time.sleep(10) #time for mysql to start
grant_command = "echo \"GRANT ALL PRIVILEGES ON *.* TO 'debian-sys-maint'@'localhost' IDENTIFIED BY '%s' WITH GRANT OPTION;\" | mysql" % password
while self.run(grant_command) != 0:
time.sleep(5)
# leave mysqld running
def main(self):
self.install()
# change_data_dir runs 'mysql -u root' which assumes there is no mysql password, i
# and changing that is too ugly to be worth it:
#self.set_root_password()
self.change_data_dir()
|
[
"dan@lionheartsw.com"
] |
dan@lionheartsw.com
|
c7d078ea821744e6c63f7379835300785d3e2926
|
1297634c6641ec62c31cf30b8fabe1886aa8d9ea
|
/products_and_services_client/models/maximum_price.py
|
dc83ab42d1c9d4be19edaa13186ee8a99e0b5357
|
[
"MIT"
] |
permissive
|
pitzer42/opbk-br-quickstart
|
d77f19743fcc264bed7af28a3d956dbc2d20ac1a
|
b3f86b2e5f82a6090aaefb563614e174a452383c
|
refs/heads/main
| 2023-03-04T13:06:34.205003
| 2021-02-21T23:41:56
| 2021-02-21T23:41:56
| 336,898,721
| 2
| 0
|
MIT
| 2021-02-07T22:03:15
| 2021-02-07T21:57:06
| null |
UTF-8
|
Python
| false
| false
| 4,175
|
py
|
# coding: utf-8
"""
API's OpenData do Open Banking Brasil
As API's descritas neste documento são referentes as API's da fase OpenData do Open Banking Brasil. # noqa: E501
OpenAPI spec version: 1.0.0-rc5.2
Contact: apiteam@swagger.io
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class MaximumPrice(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'value': 'str',
'currency': 'Currency'
}
attribute_map = {
'value': 'value',
'currency': 'currency'
}
def __init__(self, value=None, currency=None): # noqa: E501
"""MaximumPrice - a model defined in Swagger""" # noqa: E501
self._value = None
self._currency = None
self.discriminator = None
self.value = value
self.currency = currency
@property
def value(self):
"""Gets the value of this MaximumPrice. # noqa: E501
Valor máximo apurado para a tarifa de serviços sobre a base de clientes no mês de referência # noqa: E501
:return: The value of this MaximumPrice. # noqa: E501
:rtype: str
"""
return self._value
@value.setter
def value(self, value):
"""Sets the value of this MaximumPrice.
Valor máximo apurado para a tarifa de serviços sobre a base de clientes no mês de referência # noqa: E501
:param value: The value of this MaximumPrice. # noqa: E501
:type: str
"""
if value is None:
raise ValueError("Invalid value for `value`, must not be `None`") # noqa: E501
self._value = value
@property
def currency(self):
"""Gets the currency of this MaximumPrice. # noqa: E501
:return: The currency of this MaximumPrice. # noqa: E501
:rtype: Currency
"""
return self._currency
@currency.setter
def currency(self, currency):
"""Sets the currency of this MaximumPrice.
:param currency: The currency of this MaximumPrice. # noqa: E501
:type: Currency
"""
if currency is None:
raise ValueError("Invalid value for `currency`, must not be `None`") # noqa: E501
self._currency = currency
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(MaximumPrice, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, MaximumPrice):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
[
"arthurpitzer@id.uff.br"
] |
arthurpitzer@id.uff.br
|
a79d3bac4fb73d81f7b0d44129ef3e962424d788
|
79bb7105223895235263fd391906144f9f9645fd
|
/models/image/cifar10/cifar10_train.py
|
84f71d7a8274b757458f397c449a5c59eaea179a
|
[
"Apache-2.0"
] |
permissive
|
ml-lab/imcl-tensorflow
|
f863a81bfebe91af7919fb45036aa05304fd7cda
|
54ab3ec2e32087ce70ecae2f36b56a8a92f2ba89
|
refs/heads/master
| 2021-01-22T06:37:18.129405
| 2016-06-08T15:53:28
| 2016-06-08T15:53:28
| 63,518,098
| 1
| 2
| null | 2016-07-17T06:29:14
| 2016-07-17T06:29:13
| null |
UTF-8
|
Python
| false
| false
| 4,700
|
py
|
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""A binary to train CIFAR-10 using a single GPU.
Accuracy:
cifar10_train.py achieves ~86% accuracy after 100K steps (256 epochs of
data) as judged by cifar10_eval.py.
Speed: With batch_size 128.
System | Step Time (sec/batch) | Accuracy
------------------------------------------------------------------
1 Tesla K20m | 0.35-0.60 | ~86% at 60K steps (5 hours)
1 Tesla K40m | 0.25-0.35 | ~86% at 100K steps (4 hours)
Usage:
Please see the tutorial and website for how to download the CIFAR-10
data set, compile the program and train the model.
http://tensorflow.org/tutorials/deep_cnn/
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from datetime import datetime
import os.path
import time
import numpy as np
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
from tensorflow.models.image.cifar10 import cifar10
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('train_dir', '/tmp/cifar10_train',
"""Directory where to write event logs """
"""and checkpoint.""")
tf.app.flags.DEFINE_integer('max_steps', 1000000,
"""Number of batches to run.""")
tf.app.flags.DEFINE_boolean('log_device_placement', False,
"""Whether to log device placement.""")
def train():
"""Train CIFAR-10 for a number of steps."""
with tf.Graph().as_default():
global_step = tf.Variable(0, trainable=False)
# Get images and labels for CIFAR-10.
images, labels = cifar10.distorted_inputs()
# Build a Graph that computes the logits predictions from the
# inference model.
logits = cifar10.inference(images)
# Calculate loss.
loss = cifar10.loss(logits, labels)
# Build a Graph that trains the model with one batch of examples and
# updates the model parameters.
train_op = cifar10.train(loss, global_step)
# Create a saver.
saver = tf.train.Saver(tf.all_variables())
# Build the summary operation based on the TF collection of Summaries.
summary_op = tf.merge_all_summaries()
# Build an initialization operation to run below.
init = tf.initialize_all_variables()
# Start running operations on the Graph.
sess = tf.Session(config=tf.ConfigProto(
log_device_placement=FLAGS.log_device_placement))
sess.run(init)
# Start the queue runners.
tf.train.start_queue_runners(sess=sess)
summary_writer = tf.train.SummaryWriter(FLAGS.train_dir, sess.graph)
for step in xrange(FLAGS.max_steps):
start_time = time.time()
_, loss_value = sess.run([train_op, loss])
duration = time.time() - start_time
assert not np.isnan(loss_value), 'Model diverged with loss = NaN'
if step % 10 == 0:
num_examples_per_step = FLAGS.batch_size
examples_per_sec = num_examples_per_step / duration
sec_per_batch = float(duration)
format_str = ('%s: step %d, loss = %.2f (%.1f examples/sec; %.3f '
'sec/batch)')
print (format_str % (datetime.now(), step, loss_value,
examples_per_sec, sec_per_batch))
if step % 100 == 0:
summary_str = sess.run(summary_op)
summary_writer.add_summary(summary_str, step)
# Save the model checkpoint periodically.
if step % 1000 == 0 or (step + 1) == FLAGS.max_steps:
checkpoint_path = os.path.join(FLAGS.train_dir, 'model.ckpt')
saver.save(sess, checkpoint_path, global_step=step)
def main(argv=None): # pylint: disable=unused-argument
cifar10.maybe_download_and_extract()
if tf.gfile.Exists(FLAGS.train_dir):
tf.gfile.DeleteRecursively(FLAGS.train_dir)
tf.gfile.MakeDirs(FLAGS.train_dir)
train()
if __name__ == '__main__':
tf.app.run()
|
[
"mrlittlezhu@gmail.com"
] |
mrlittlezhu@gmail.com
|
4ab0d9b5dbf4bad4ce4e985cef21b404c9ddd7ec
|
30a3fe4623bda3cf271cf8ef24f87948b89de019
|
/app/utils.py
|
0ded1cb9dd3c89790b56992c698e0b14097d1fb3
|
[] |
no_license
|
kiminh/semantic-search-faiss
|
84e520e1a8a29a79d0ed313d815704ff7e2e5ddf
|
bc448f4839e3f0835b711cf7769421d64d11c909
|
refs/heads/master
| 2022-10-03T17:40:12.010550
| 2020-06-04T09:36:02
| 2020-06-04T09:36:02
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,001
|
py
|
import os
import json
import faiss
import numpy as np
OUTPUT_DIR = "output"
def normalize(sent: str):
"""Normalize sentence"""
sent = sent.replace('“', '"')
sent = sent.replace('”', '"')
sent = sent.replace('’', "'")
sent = sent.replace('‘', "'")
sent = sent.replace('—', '-')
return sent.replace("\n", "")
def load_dataset(f_input: str):
"""Load dataset from input directory"""
with open(f"{f_input}.json", "r", encoding="utf-8") as corpus:
lines = [normalize(line["title"])
for line in json.loads(corpus.read())]
return lines
def es_search(es, index: str, query: str, k: int=3):
"""Conduct ElasticSearch's search"""
results = es.search(
index=index,
body={
"from": 0,
"size": k,
"query": {
"match": {
"title": query
}
}
}
)
results = [result["_source"]["title"] for result in results["hits"]["hits"]]
return results
def create_es_index(es, index: str):
"""Create ElasticSearch indices"""
if not es.indices.exists(index=index):
es.indices.create(
index=index,
body={
"settings": {
"analysis": {
"analyzer": {
"nori": {
"tokenizer": "nori_tokenizer"
}
}
}
},
"mappings": {
"properties": {
"title": {
"type": "text",
"analyzer": "nori"
}
}
}
}
)
dataset = load_dataset("corpus")
for data in dataset:
doc = {
"title": normalize(data)
}
es.index(index=index, body=doc)
def faiss_search(encoder, indices, query: str, k: int=3):
"""Conduct FAISS top-k search"""
query_vec = encoder.encode(query)
top_k = indices.search(query_vec, k)[-1].tolist()[0]
data = load_dataset("corpus")
result = [data[idx] for idx in top_k]
return result
def create_faiss_index(encoder):
"""Create FAISS indices using encoder"""
if not os.path.exists(OUTPUT_DIR):
os.makedirs(OUTPUT_DIR)
if os.path.exists(f"{OUTPUT_DIR}/faiss.index"):
indices = faiss.read_index(
os.path.join(OUTPUT_DIR, "faiss.index")
)
return indices
dataset = load_dataset("corpus")
encoded = [encoder.encode(data) for data in dataset]
encoded = np.array(encoded)
indices = faiss.IndexIDMap(faiss.IndexFlatIP(encoder.dimension))
indices.add_with_ids(encoded, np.array(range(len(dataset))))
faiss.write_index(
indices,
os.path.join(OUTPUT_DIR, "faiss.index")
)
return indices
|
[
"huffonism@gmail.com"
] |
huffonism@gmail.com
|
ba27a0f3a80330eb4a3161bdba920d0f0031b4d9
|
70896c105c9a3cc2e7316883e50395fc0638fd25
|
/site/search-index/graph.py
|
40d6c8f8249c42cce1edc96d873af2fed57b6bd8
|
[
"MIT"
] |
permissive
|
chituma110/neupy
|
87e8c9c14b1eeb43012b214952460a86c7fb05ab
|
15de13b7d7018369a8d788c0d0ccf9a5c8176320
|
refs/heads/master
| 2021-01-13T12:18:54.597174
| 2017-01-03T13:09:57
| 2017-01-03T13:09:57
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 662
|
py
|
from collections import OrderedDict
class DirectedGraph(object):
def __init__(self):
self.graph = OrderedDict()
def add_node(self, node):
self.graph[node] = []
def add_edge(self, node_1, node_2):
if node_1 not in self.graph:
self.add_node(node_1)
if node_2 not in self.graph:
self.add_node(node_2)
self.graph[node_1].append(node_2)
def __iter__(self):
for from_node, to_nodes in self.graph.items():
yield from_node, to_nodes
def __len__(self):
return len(self.graph)
@property
def edges(self):
return list(self.graph.keys())
|
[
"mail@itdxer.com"
] |
mail@itdxer.com
|
5028e51bfd002a3d27ab6417f43c7ce234de56bc
|
5b93930ce8280b3cbc7d6b955df0bfc5504ee99c
|
/nodes/Bisong19Building/C_PartII/C_Chapter10/F_MatrixOperations/B_ElementWiseOperations/index.py
|
0e50f350af322d3b72ea3073845fe22ebb12e2a8
|
[] |
no_license
|
nimra/module_gen
|
8749c8d29beb700cac57132232861eba4eb82331
|
2e0a4452548af4fefd4cb30ab9d08d7662122cf4
|
refs/heads/master
| 2022-03-04T09:35:12.443651
| 2019-10-26T04:40:49
| 2019-10-26T04:40:49
| 213,980,247
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,323
|
py
|
# Lawrence McAfee
# ~~~~~~~~ import ~~~~~~~~
from modules.node.HierNode import HierNode
from modules.node.LeafNode import LeafNode
from modules.node.Stage import Stage
from modules.node.block.CodeBlock import CodeBlock as cbk
from modules.node.block.ImageBlock import ImageBlock as ibk
from modules.node.block.MarkdownBlock import MarkdownBlock as mbk
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Element-Wise Operations
# Element-wise matrix operations involve matrices operating on themselves in an
# element-wise fashion. The action can be an addition, subtraction, division, or
# multiplication (which is commonly called the Hadamard product). The matrices must be
# of the same shape. Please note that while a matrix is of shape n × n, a vector is of shape
# n × 1. These concepts easily apply to vectors as well. See Figure 10-2.
#
#
#
#
# Figure 10-2. Element-wise matrix operations
# Let’s have some examples.
#
# # Hadamard multiplication of A and B
# A * B
# 'Output':
# array([[ 570, 928, 528],
# [ 160, 690, 1196],
# [ 990, 658, 1056]])
# # add A and B
# A + B
# 'Output':
# array([[53, 61, 46],
# [37, 53, 72],
# [63, 61, 68]])
# # subtract A from B
# B - A
# 'Output':
# array([[ 23, 3, -2],
# [ 27, 7, 20],
# [ 3, 33, -20]])
# # divide A with B
# A / B
# 'Output':
# array([[ 0.39473684, 0.90625 , 1.09090909],
# [ 0.15625 , 0.76666667, 0.56521739],
# [ 0.90909091, 0.29787234, 1.83333333]])
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class Content(LeafNode):
def __init__(self):
super().__init__(
"Element-Wise Operations",
Stage.REMOVE_EXTRANEOUS,
# Stage.ORIG_BLOCKS,
# Stage.CUSTOM_BLOCKS,
# Stage.ORIG_FIGURES,
# Stage.CUSTOM_FIGURES,
# Stage.CUSTOM_EXERCISES,
)
self.add(mbk("# Element-Wise Operations"))
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class ElementWiseOperations(HierNode):
def __init__(self):
super().__init__("Element-Wise Operations")
self.add(Content())
# eof
|
[
"lawrence.mcafee@gmail.com"
] |
lawrence.mcafee@gmail.com
|
e66a6383de8c689572ca2d04c0adb3a49595775e
|
05c395df76d494d8239de86515a3b57cd08231c4
|
/test/lmp/tokenizer/_base_tokenizer/__init__.py
|
5d2fe53c608ba24438119b9611d5a2ab2595657f
|
[] |
no_license
|
SiuYingCheng/language-model-playground
|
61b74a28abea5707bc1c9d0a2280d2f24d959ae4
|
6bca79baceacf85c5c3683bbfdf586a00484ed19
|
refs/heads/master
| 2022-12-16T23:04:25.895156
| 2020-09-10T16:26:03
| 2020-09-10T16:26:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,099
|
py
|
r"""Test `lmp.tokenizer._base_tokenizer.py`.
Usage:
python -m unittest test.lmp.tokenizer._base_tokenizer.__init__
"""
# built-in modules
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import inspect
import unittest
class TestBaseTokenizer(unittest.TestCase):
r"""Test case for `lmp.tokenizer._base_tokenizer.py`."""
def test_signature(self):
r"""Ensure signature consistency."""
msg = 'Inconsistent module signature.'
try:
# pylint: disable=C0415
import lmp
import lmp.tokenizer
import lmp.tokenizer._base_tokenizer
# pylint: enable=C0415
# pylint: disable=W0212
self.assertTrue(
inspect.ismodule(lmp.tokenizer._base_tokenizer),
msg=msg
)
# pylint: enable=W0212
except ImportError:
self.fail(msg=msg)
def test_module_attributes(self):
r"""Declare required module attributes."""
msg1 = 'Missing module attribute `{}`.'
msg2 = 'Module attribute `{}` must be a class.'
msg3 = 'Inconsistent module signature.'
examples = ('BaseTokenizer',)
try:
# pylint: disable=C0415
import lmp
import lmp.tokenizer
import lmp.tokenizer._base_tokenizer
# pylint: enable=C0415
# pylint: disable=W0212
for attr in examples:
self.assertTrue(
hasattr(lmp.tokenizer._base_tokenizer, attr),
msg=msg1.format(attr)
)
self.assertTrue(
inspect.isclass(getattr(
lmp.tokenizer._base_tokenizer,
attr
)),
msg=msg2.format(attr)
)
# pylint: enable=W0212
except ImportError:
self.fail(msg=msg3)
if __name__ == '__main__':
unittest.main()
|
[
"ProFatXuanAll@gmail.com"
] |
ProFatXuanAll@gmail.com
|
27bf3ef14146afe4d99288cc61e3f95623475769
|
163bbb4e0920dedd5941e3edfb2d8706ba75627d
|
/Code/CodeRecords/2290/60627/252911.py
|
dd6e631f0e74990df90b56f6a7b3a0c769388514
|
[] |
no_license
|
AdamZhouSE/pythonHomework
|
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
|
ffc5606817a666aa6241cfab27364326f5c066ff
|
refs/heads/master
| 2022-11-24T08:05:22.122011
| 2020-07-28T16:21:24
| 2020-07-28T16:21:24
| 259,576,640
| 2
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 352
|
py
|
# 1
n = int(input())
for i in range(n):
input()
num = input().split()
for i in range(len(num)):
num[i] = int(num[i])
l = ''
for i in range(len(num)):
if i < len(num)-1:
if num[i] > num[i+1]:
l += str(num[i+1]) + ' '
else:
l += '-1 '
l += '-1'
print(l)
|
[
"1069583789@qq.com"
] |
1069583789@qq.com
|
2202083b47c93ec48c1625a519c96443a05b8997
|
02e4920166051129d1ca28a0da80405a982f1cfe
|
/exercícios_fixação/094.py
|
c12172adc3319a6db6eb420f79689481c4229452
|
[] |
no_license
|
felipeonf/Exercises_Python
|
1ab40cea2466d6bb5459b5384a1dde8e1066b3b4
|
8eb2d17a35a6352fd5268a5fa43b834443171c70
|
refs/heads/main
| 2023-07-23T22:30:13.567469
| 2021-08-25T03:34:33
| 2021-08-25T03:34:33
| 397,062,295
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,021
|
py
|
'''[DESAFIO] Desenvolva um aplicativo que tenha um procedimento chamado
Fibonacci() que recebe um único valor inteiro como parâmetro, indicando quantos
termos da sequência serão mostrados na tela. O seu procedimento deve receber
esse valor e mostrar a quantidade de elementos solicitados.
Obs: Use os exercícios 70 e 75 para te ajudar na solução
Ex:
Fibonacci(5) vai gerar 1 >> 1 >> 2 >> 3 >> 5 >> FIM
Fibonacci(9) vai gerar 1 >> 1 >> 2 >> 3 >> 5 >> 8 >> 13 >> 21 >> 34 >> FIM'''
def Fibonacci(termos):
termo = 1
termo_anterior = 0
if termos == 1:
print(0)
elif termos == 2:
print(0,'>>',1,'>>','FIM')
else:
print(0,end=' >> ')
print(1,end=' >> ')
for num in range(3,termos+1):
termo3 = termo_anterior + termo
print(termo3,end=' >> ')
termo_anterior = termo
termo = termo3
print('FIM')
termos = int(input('Digite a quantidade de termos que quer ver: '))
Fibonacci(termos)
|
[
"noreply@github.com"
] |
felipeonf.noreply@github.com
|
8c26bce3eb81c76ff44837fa243a825da36108a0
|
c7ea36544ae5f7a8e34bf95b8c38240ca6ebda83
|
/app/schema/answers/month_year_date_answer.py
|
bfca6e0fa0eb15b62fed5d38aacf62564fa094de
|
[
"LicenseRef-scancode-proprietary-license",
"MIT"
] |
permissive
|
qateam123/eq
|
40daa6ea214e61b572affd0b5ab9990371c70be4
|
704757952323647d659c49a71975c56406ff4047
|
refs/heads/master
| 2023-01-11T01:46:11.174792
| 2017-02-09T13:46:56
| 2017-02-09T13:46:56
| 80,821,577
| 0
| 0
|
MIT
| 2023-01-04T14:31:08
| 2017-02-03T11:02:24
|
JavaScript
|
UTF-8
|
Python
| false
| false
| 900
|
py
|
from app.schema.answer import Answer
from app.schema.exceptions import TypeCheckingException
from app.schema.widgets.month_year_date_widget import MonthYearDateWidget
from app.validation.month_year_date_type_check import MonthYearDateTypeCheck
class MonthYearDateAnswer(Answer):
def __init__(self, answer_id=None):
super().__init__(answer_id)
self.type_checkers.append(MonthYearDateTypeCheck())
self.widget = MonthYearDateWidget(self.id)
def get_typed_value(self, post_data):
user_input = self.get_user_input(post_data)
for checker in self.type_checkers:
result = checker.validate(user_input)
if not result.is_valid:
raise TypeCheckingException(result.errors[0])
return self._cast_user_input(user_input)
def get_user_input(self, post_vars):
return self.widget.get_user_input(post_vars)
|
[
"patelt@C02SQ3LDG8WL.local"
] |
patelt@C02SQ3LDG8WL.local
|
90fddcec4e7c01bc4e7411795fd3da100f7f7d65
|
09dd58f46b1e914278067a69142230c7af0165c2
|
/blackmamba/system.py
|
986fcef2f17be701ceb50130892f4a8a6e7dcc74
|
[
"MIT"
] |
permissive
|
zrzka/blackmamba
|
4e70262fbe3702553bf5d285a81b33eb6b3025ea
|
b298bc5d59e5aea9d494282910faf522c08ebba9
|
refs/heads/master
| 2021-01-01T18:43:19.490953
| 2020-01-20T08:26:33
| 2020-01-20T08:26:33
| 98,410,391
| 72
| 12
|
MIT
| 2020-01-20T08:26:35
| 2017-07-26T10:21:15
|
Python
|
UTF-8
|
Python
| false
| false
| 5,903
|
py
|
#!python3
"""System info and decorators.
.. warning:: This module must not introduce dependency on any other Black Mamba
modules and must be importable on any other platform as well.
"""
import sys
import traceback
import functools
try:
import console
except ImportError:
console = None
# 3.1, 301016
# 3.1.1 beta, 311008
PYTHONISTA = sys.platform == 'ios'
"""bool: True if we're running within Pythonista or False."""
PYTHONISTA_VERSION = None
"""str: Pythonista version or `None` if we're not within Pythonista."""
PYTHONISTA_BUNDLE_VERSION = None
"""int: Pythonista bundle version or `None` if we're not within Pythonista."""
PYTHONISTA_VERSION_TUPLE = None
"""tuple(int): Pythonista version tuple (3, 1, 1) or `None` if we're not within Pythonista."""
IOS = sys.platform == 'ios'
"""bool: `True` if we're running within iOS or `False`."""
IOS_VERSION = None
"""str: iOS version or `None` if we're not within iOS."""
IOS_VERSION_TUPLE = None
"""tuple(int): iOS version tuple (11, 0) or `None` if we're not within iOS."""
def _version_tuple(version):
if not version:
return None
return tuple(map(int, (version.split('.'))))
if PYTHONISTA:
import plistlib
import os
try:
plist_path = os.path.abspath(os.path.join(sys.executable, '..', 'Info.plist'))
plist = plistlib.readPlist(plist_path)
PYTHONISTA_VERSION = plist['CFBundleShortVersionString']
PYTHONISTA_BUNDLE_VERSION = int(plist['CFBundleVersion'])
PYTHONISTA_VERSION_TUPLE = _version_tuple(PYTHONISTA_VERSION)
except Exception:
pass
if IOS:
try:
from objc_util import ObjCClass
IOS_VERSION = str(ObjCClass('UIDevice').currentDevice().systemVersion())
IOS_VERSION_TUPLE = _version_tuple(IOS_VERSION)
except Exception:
pass
class _Available:
def __init__(self, from_version=None, to_version=None):
if from_version and to_version:
raise ValueError('Either from_version or to_version can be provided, not both')
self._from_version = _version_tuple(from_version)
self._to_version = _version_tuple(to_version)
def version(self):
raise Exception('Not implemented, return version as tuple(int)')
def _available(self):
current_version = self.version()
if not current_version:
return False
if self._to_version:
return current_version <= self._to_version
if self._from_version:
return current_version >= self._from_version
return True
def __call__(self, fn, *args, **kwargs):
def func(*args, **kwargs):
if self._available():
return fn(*args, **kwargs)
return None
return func
class iOS(_Available):
"""Decorator to execute function under specific iOS versions.
Return value is return value of decorated function or `None`
if iOS condition isn't met.
Examples:
Run function only within any iOS version::
@iOS()
def run_me():
pass
Run function only within iOS >= 11.0::
@iOS('11.0') # or @iOS(from_version='11.0')
def run_me():
pass
Run function only within iOS <= 11.0::
@iOS(None, '11.0') # or @iOS(to_version='11.0')
def run_me():
pass
"""
def version(self):
return IOS_VERSION_TUPLE
class Pythonista(_Available):
"""Decorator to execute function under specific Pythonista versions.
By default, function is not executed under application extension.
You have to pass ``appex=True`` if you'd like to run some function
under appex as well.
Return value is return value of decorated function or `None`
if Pythonista condition isn't met.
Examples:
Run function only within any Pythonista version::
@Pythonista()
def run_me():
pass
Run function only within any Pythonista version and allow appex::
@Pythonista(appex=True)
def run_me():
pass
Run function only within any Pythonista version and disallow appex::
@Pythonista(appex=False)
def run_me():
pass
Run function only within Pythonista >= 3.1.1::
@Pythonista('3.1.1') # or @Pythonista(from_version='3.1.1')
def run_me():
pass
Run function only within Pythonista <= 3.2::
@Pythonista(None, '3.2') # or @Pythonista(to_version='3.2')
def run_me():
pass
"""
def __init__(self, from_version=None, to_version=None, appex=None):
super().__init__(from_version, to_version)
self._appex = appex
def _available(self):
available = super()._available()
if available and self._appex is not None:
import appex
available = appex.is_running_extension() == self._appex
return available
def version(self):
return PYTHONISTA_VERSION_TUPLE
def catch_exceptions(func):
"""Decorator catching all exceptions and printing info to the console.
Use this decorator for functions handling keyboard shortcuts,
keyboard events, ... to avoid Pythonista crash.
Args:
func: Function to decorate
Returns:
Return value of decorated function.
"""
@functools.wraps(func)
def new_func(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception:
if console:
console.set_color(1, 0, 0)
print(traceback.format_exc())
print('Please, file an issue at {}'.format('https://github.com/zrzka/blackmamba/issues'))
if console:
console.set_color()
return new_func
|
[
"rvojta@me.com"
] |
rvojta@me.com
|
58c130b79a1188152e08dda276e3ffec20ed373c
|
0dae97b2205ef5d8ce884ec2af4bf99ad2baec43
|
/drf_admin/apps/cmdb/views/servers.py
|
d82da8146f097cad58b325c18915d1920c94e506
|
[
"MIT"
] |
permissive
|
15051882416/drf_admin
|
2520affacd0345d042b499c3e9a56a112cc235d5
|
0b31fa5248afb6fc20e6ef425b2dcc4d39977d81
|
refs/heads/master
| 2022-12-31T04:57:27.017134
| 2020-10-24T01:09:58
| 2020-10-24T01:09:58
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,461
|
py
|
# -*- coding: utf-8 -*-
"""
@author : Wang Meng
@github : https://github.com/tianpangji
@software : PyCharm
@file : servers.py
@create : 2020/10/17 18:45
"""
from django.contrib.auth.models import AnonymousUser
from django.db.models import Q
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.response import Response
from rest_framework.views import APIView
from cmdb.models import Assets, Servers
from cmdb.serializers.servers import ServersAssetsSerializers
from drf_admin.common.departments import get_departments_id
from drf_admin.utils.views import AdminViewSet
from system.models import Departments
class ServersViewSet(AdminViewSet):
"""
create:
服务器--新增
服务器新增, status: 201(成功), return: 新增服务器信息
destroy:
服务器--删除
服务器删除, status: 204(成功), return: None
multiple_delete:
服务器--批量删除
服务器批量删除, status: 204(成功), return: None
update:
服务器--修改
服务器修改, status: 200(成功), return: 修改增服务器信息
partial_update:
服务器--局部修改
服务器局部修改, status: 200(成功), return: 修改增服务器信息
list:
服务器--获取列表
服务器列表信息, status: 200(成功), return: 服务器信息列表
retrieve:
服务器--服务器详情
服务器详情信息, status: 200(成功), return: 单个服务器信息详情
"""
serializer_class = ServersAssetsSerializers
filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
filter_fields = ['asset_status']
search_fields = ('name', 'sn', 'manage_ip')
ordering_fields = ('id', 'name', 'sn')
def get_queryset(self):
# 解决drf-yasg加载报错
if isinstance(self.request.user, AnonymousUser):
return Assets.objects.none()
# ①管理员角色用户可查看所有
if {'name': 'admin'} in self.request.user.roles.values('name'):
return Assets.objects.filter(asset_type='server')
# ②每个用户只能查看到所属部门及其子部门下的服务器, 及该用户管理服务器
if self.request.user.department:
departments = get_departments_id(self.request.user.department.id)
return (Assets.objects.filter(asset_type='server').filter(
Q(department__in=departments) | Q(admin=self.request.user))).distinct()
else:
return Assets.objects.filter(asset_type='server', admin=self.request.user)
class ServersSystemTypeAPIView(APIView):
"""
get:
服务器--models系统类型列表
服务器models中的系统类型列表信息, status: 200(成功), return: 服务器models中的系统类型列表
"""
def get(self, request):
methods = [{'value': value[0], 'label': value[1]} for value in Servers.server_system_type_choice]
return Response(data={'results': methods})
class ServersTypeAPIView(APIView):
"""
get:
服务器--models类型列表
服务器models中的类型列表信息, status: 200(成功), return: 服务器models中的类型列表
"""
def get(self, request):
methods = [{'value': value[0], 'label': value[1]} for value in Servers.server_type_choice]
return Response(data={'results': methods})
|
[
"921781999@qq.com"
] |
921781999@qq.com
|
4021d5d523973384ebf72c8ba41a80e66b87be23
|
ff6248be9573caec94bea0fa2b1e4b6bf0aa682b
|
/raw_scripts/132.230.102.123-10.21.12.4/1569578039.py
|
747b1029c89ff144a79977e858b82b6acd08b556
|
[] |
no_license
|
LennartElbe/codeEvo
|
0e41b1a7705204e934ef71a5a28c047366c10f71
|
e89b329bc9edd37d5d9986f07ca8a63d50686882
|
refs/heads/master
| 2020-12-21T17:28:25.150352
| 2020-03-26T10:22:35
| 2020-03-26T10:22:35
| 236,498,032
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,522
|
py
|
import functools
import typing
import string
import random
import pytest
## Lösung Teile 1. und 2.
class Vigenere:
def __init__(self, schluesselwort):
raise len(schluesselwort) == 0
self.__key = schluesselwort
def encrypt(self, w):
test = {1:"A",2:"B",3:"C",4:"D"}
result = ""
for letter in w:
for letter2 in test:
if letter == letter2[1]:
result += letter2[0]
return result
def decryp(self,w):
test = {1:"A",2:"B",3:"C",4:"D"}
result = ""
for letter in w:
for letter2 in test:
if letter == letter2[0]:
result += letter2[1]
return result
######################################################################
## hidden code
def mk_coverage():
covered = set()
target = set(range(6))
count = 0
def coverage(func):
nonlocal covered, target, count
def wrapper(key):
nonlocal covered, count
if key == "A":
covered.add(0)
elif key != "":
covered.add(1)
if len (key) > 1:
covered.add(2)
if key == key[0] * len (key):
covered.add(4)
else:
covered.add(5)
if len (key) > 2:
covered.add (3)
r = func (key)
count += 1
return r
if func == "achieved": return len(covered)
if func == "required": return len(target)
if func == "count" : return count
functools.update_wrapper (wrapper, func)
return wrapper
return coverage
coverage = mk_coverage ()
try:
Vigenere = coverage (Vigenere)
except:
pass
## Lösung Teil 3. (Tests)
assert Vigenere("ABCD").encrypt() == "1234"
assert Vigenere("1234").encrypt() == "ABCD"
######################################################################
## hidden tests
pytest.main (["-v", "--assert=plain", "-p", "no:cacheprovider"])
from inspect import getfullargspec
class TestNames:
def test_Vigenere (self):
assert Vigenere
def test_encrypt(self):
assert Vigenere.encrypt
assert 'w' in getfullargspec(Vigenere.encrypt).args
def test_decrypt(self):
assert Vigenere.decrypt
assert 'w' in getfullargspec(Vigenere.decrypt).args
class TestGrades:
def test_coverage(self):
assert coverage("achieved") == coverage("required")
def test_Vigenere_is_a_class(self):
assert "class" in repr (Vigenere.__wrapped__)
def test_docstring_present(self):
assert Vigenere.__doc__ is not None
assert Vigenere.encrypt.__doc__ is not None
assert Vigenere.decrypt.__doc__ is not None
def test_empty_key (self):
with pytest.raises (Exception):
assert Vigenere ("")
def test_has_key(self):
k = "asfdg"
v = Vigenere(k)
assert v.key == k
def test_has_methods(self):
v = Vigenere("")
assert v.encrypt
assert v.decrypt
def test_identity(self):
charset = string.ascii_uppercase
v = Vigenere ("A")
for i in range (100):
s = ''.join(random.choice (charset) for j in range (100))
assert v.encrypt(s) == s
assert v.decrypt(s) == s
def test_inverses(self):
charset = string.ascii_uppercase
for i in range (100):
k = ''.join(random.choice (charset) for j in range (random.randrange (1,20)))
v = Vigenere (k)
for n in range (10):
s = ''.join(random.choice (charset) for j in range (100))
assert v.decrypt(v.encrypt(s)) == s
def test_shift (self):
charset = string.ascii_uppercase
for i in range (100):
k = random.choice (charset)
ok = ord (k) - ord ('A')
v = Vigenere (k * random.randrange (1, 100))
s = ''.join(random.choice (charset) for j in range (100))
se = v.encrypt (s)
assert len (se) == len (s)
for x, xe in zip (s, se):
d = (26 + ord (xe) - ord (x)) % 26
assert d == ok
sd = v.decrypt (s)
assert len (sd) == len (s)
for x, xd in zip (s, sd):
d = (26 + ord (x) - ord (xd)) % 26
assert d == ok
|
[
"lenni.elbe@gmail.com"
] |
lenni.elbe@gmail.com
|
ca66a5d5cbd1c66360f905b66c50a3a3a78e69fc
|
07ec5a0b3ba5e70a9e0fb65172ea6b13ef4115b8
|
/lib/python3.6/site-packages/pygments/lexers/ampl.py
|
88d9a335a05d787080d511248d6fb7102cf51e27
|
[] |
no_license
|
cronos91/ML-exercise
|
39c5cd7f94bb90c57450f9a85d40c2f014900ea4
|
3b7afeeb6a7c87384049a9b87cac1fe4c294e415
|
refs/heads/master
| 2021-05-09T22:02:55.131977
| 2017-12-14T13:50:44
| 2017-12-14T13:50:44
| 118,736,043
| 0
| 0
| null | 2018-01-24T08:30:23
| 2018-01-24T08:30:22
| null |
UTF-8
|
Python
| false
| false
| 129
|
py
|
version https://git-lfs.github.com/spec/v1
oid sha256:e80400498fbe866617b60933b2d859ca644ce1bcd0fd1419642e56bb84491be0
size 4120
|
[
"seokinj@jangseog-in-ui-MacBook-Pro.local"
] |
seokinj@jangseog-in-ui-MacBook-Pro.local
|
b84bc5c1ca3a1559be68059e22c3ad0797fb3b4e
|
5e0737c75087c2bb631f760979b9afe13ba1e9b5
|
/labs/Lab7_helper.py
|
4e5018db80a65f8d2930abeb89e3a9c69a6f2fc4
|
[] |
no_license
|
anderson-github-classroom/csc-369-student
|
f54bf89ec84f58405b5ea39f13cd431becf8d796
|
e8654e5656fdfc5e5c81022a6e1e0bca8ab97e04
|
refs/heads/main
| 2023-03-21T14:50:04.475831
| 2021-03-09T17:08:49
| 2021-03-09T17:08:49
| 325,129,939
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,084
|
py
|
from bson.objectid import ObjectId
from bson.code import Code
def exercise_1(col):
result = None
# Your solution here
return result
def exercise_2(col):
result = None
# Your solution here
return result
def process_exercise_3(result):
process_result = {}
for record in result:
process_result[record['_id']['state']] = record['sum']/record['count']
return process_result
def exercise_3(col,date1,date2):
result = None
# partial solution
# Your solution here
return result
def process_exercise_4(result):
process_result = {}
for record in result:
state,identifier = record['_id'].split(": ")
value = record['value']
if state not in process_result:
process_result[state] = 1.
if identifier == "sum":
process_result[state] *= value
elif identifier == "count":
process_result[state] *= 1/value
return process_result
def exercise_4(col,date1,date2):
result = None
# partial solution
# Your solution here
return result
|
[
"pauleanderson@gmail.com"
] |
pauleanderson@gmail.com
|
3735ecb70313723eec2dcb5a74478775404b1862
|
d6e65aa23ff8b2344dacac93fe00fcfcd64cc414
|
/ac_kth_excluded.py
|
0562543eaa475be4c06d1338eda33ac95cdd5e8e
|
[] |
no_license
|
diwadd/sport
|
c4b0ec3547cde882c549fa7b89e0132fdaf0c8fb
|
220dfaf1329b4feea5b5ca490ffc17ef7fe76cae
|
refs/heads/master
| 2023-05-29T13:17:23.516230
| 2023-05-20T22:08:28
| 2023-05-20T22:08:28
| 223,636,723
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,234
|
py
|
import bisect
nq = input().split(" ")
n = int(nq[0])
q = int(nq[1])
a_vec = input().split(" ")
a_vec = [int(a) for a in a_vec]
ranges_list = []
if a_vec[0] != 1:
ranges_list.append([0, a_vec[0]])
for i in range(1, len(a_vec)):
if a_vec[i] - a_vec[i-1] == 1:
continue
else:
ranges_list.append([a_vec[i-1], a_vec[i]])
if a_vec[-1] != 10*18:
ranges_list.append([a_vec[-1], 10**19])
numbers = [0 for _ in range(len(ranges_list))]
for i in range(len(ranges_list)):
numbers[i] = ranges_list[i][1] - ranges_list[i][0] - 1
prefix_sum = [0 for _ in range(len(numbers))]
prefix_sum[0] = numbers[0]
for i in range(1, len(numbers)):
prefix_sum[i] = prefix_sum[i-1] + numbers[i]
for _ in range(q):
k = int(input())
pos = bisect.bisect_left(prefix_sum, k)
res = None
if pos == len(ranges_list) - 1:
if pos - 1 >= 0:
res = ranges_list[pos][0] + k - prefix_sum[pos-1]
else:
res = ranges_list[pos][0] + k
elif pos == 0:
res = ranges_list[pos][0] + k
else:
if pos - 1 >= 0:
res = ranges_list[pos][0] + k - prefix_sum[pos-1]
else:
res = ranges_list[pos][0] + k
print(f"{res}")
|
[
"dawid.dul@gmail.com"
] |
dawid.dul@gmail.com
|
232fb2bc3b437ecc04e52293372acc262f8fc569
|
58f095f52d58afa9e8041c69fa903c5a9e4fa424
|
/examples/example10.py
|
d1559702fb592fcbbb38d226465818239f4e3b58
|
[
"BSD-3-Clause"
] |
permissive
|
cdeil/mystic
|
e41b397e9113aee1843bc78b5b4ca30bd0168114
|
bb30994987f36168b8f09431cb9c3823afd892cd
|
refs/heads/master
| 2020-12-25T23:18:52.086894
| 2014-08-13T14:36:09
| 2014-08-13T14:36:09
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,013
|
py
|
#!/usr/bin/env python
#
# Author: Mike McKerns (mmckerns @caltech and @uqfoundation)
# Copyright (c) 1997-2014 California Institute of Technology.
# License: 3-clause BSD. The full license text is available at:
# - http://trac.mystic.cacr.caltech.edu/project/mystic/browser/mystic/LICENSE
"""
Example:
- Solve 8th-order Chebyshev polynomial coefficients with DE.
- Plot (x2) of convergence to Chebyshev polynomial.
- Monitor (x2) Chi-Squared for Chebyshev polynomial.
Demonstrates:
- standard models
- expanded solver interface
- built-in random initial guess
- customized monitors and termination conditions
- customized DE mutation strategies
- use of solver members to retrieve results information
"""
# Differential Evolution solver
from mystic.solvers import DifferentialEvolutionSolver2
# Chebyshev polynomial and cost function
from mystic.models.poly import chebyshev8, chebyshev8cost
from mystic.models.poly import chebyshev8coeffs
# tools
from mystic.termination import VTR
from mystic.strategy import Best1Exp
from mystic.monitors import VerboseMonitor, Monitor
from mystic.tools import getch, random_seed
from mystic.math import poly1d
import pylab
pylab.ion()
# draw the plot
def plot_frame(label=None):
pylab.close()
pylab.title("8th-order Chebyshev coefficient convergence")
pylab.xlabel("Differential Evolution %s" % label)
pylab.ylabel("Chi-Squared")
pylab.draw()
return
# plot the polynomial trajectories
def plot_params(monitor):
x = range(len(monitor.y))
pylab.plot(x,monitor.y,'b-')
pylab.axis([1,0.5*x[-1],0,monitor.y[1]],'k-')
pylab.draw()
return
if __name__ == '__main__':
print "Differential Evolution"
print "======================"
# set range for random initial guess
ndim = 9
x0 = [(-100,100)]*ndim
random_seed(123)
# configure monitors
stepmon = VerboseMonitor(50)
evalmon = Monitor()
# use DE to solve 8th-order Chebyshev coefficients
npop = 10*ndim
solver = DifferentialEvolutionSolver2(ndim,npop)
solver.SetRandomInitialPoints(min=[-100]*ndim, max=[100]*ndim)
solver.SetEvaluationLimits(generations=999)
solver.SetEvaluationMonitor(evalmon)
solver.SetGenerationMonitor(stepmon)
solver.enable_signal_handler()
solver.Solve(chebyshev8cost, termination=VTR(0.01), strategy=Best1Exp, \
CrossProbability=1.0, ScalingFactor=0.9)
solution = solver.bestSolution
# get solved coefficients and Chi-Squared (from solver members)
iterations = solver.generations
cost = solver.bestEnergy
print "Generation %d has best Chi-Squared: %f" % (iterations, cost)
print "Solved Coefficients:\n %s\n" % poly1d(solver.bestSolution)
# plot convergence of coefficients per iteration
plot_frame('iterations')
plot_params(stepmon)
getch()
# plot convergence of coefficients per function call
plot_frame('function calls')
plot_params(evalmon)
getch()
# end of file
|
[
"mmckerns@968178ea-60bd-409e-af13-df8a517b6005"
] |
mmckerns@968178ea-60bd-409e-af13-df8a517b6005
|
250c99544b764054cbb51329107670b550aac94e
|
e4aab0a71dc5c047d8b1576380b16364e03e7c0d
|
/backup.py
|
8c72d7628780821364635e912abc49be03239e3f
|
[
"Apache-2.0"
] |
permissive
|
Joecastra/Watcher3
|
8ca66c44846030f0eb771d9d6ddeb9c37f637a4e
|
ce25d475f83ed36d6772f0cc35ef020d5e47c94b
|
refs/heads/master
| 2021-01-19T11:05:55.454351
| 2017-04-10T20:17:24
| 2017-04-10T20:17:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,478
|
py
|
import argparse
import os
import shutil
import sys
import zipfile
tmpdir = 'backup_tmp'
posterpath = os.path.join('static', 'images', 'posters')
def backup(require_confirm=True):
# check for files and paths
if not os.path.isfile('watcher.sqlite'):
if require_confirm is True:
if input('Database watcher.sqlite not found. Continue? (y/N): ').lower() != 'y':
return
database = False
else:
database = True
if not os.path.isfile('config.cfg'):
if require_confirm is True:
if input('Config config.cfg not found. Continue? (y/N): ').lower() != 'y':
return
config = False
else:
config = True
if not os.path.isdir(posterpath):
if require_confirm is True:
if input('Config config.cfg not found. Continue? (y/N): ').lower() != 'y':
return
posters = False
else:
posters = True
# make temp dir
if os.path.isdir(tmpdir):
print('Old temporary directory found. Removing.')
shutil.rmtree(tmpdir)
print('Creating temporary backup directory.')
os.mkdir('backup_tmp')
if database:
print('Copying database.')
shutil.copy2('watcher.sqlite', tmpdir)
if config:
print('Copying config.')
shutil.copy2('config.cfg', tmpdir)
if posters:
print('Copying posters.')
dst = os.path.join(tmpdir, 'posters/')
os.mkdir(dst)
for file in os.listdir(posterpath):
src = os.path.join(posterpath, file)
shutil.copy2(src, dst)
# create backup zip
print('Creating watcher.zip')
shutil.make_archive('watcher', 'zip', tmpdir)
print('Removing temporary backup directory.')
shutil.rmtree(tmpdir)
print('**############################################################**')
print('**##################### Backup finished ######################**')
print('**################# Zip backup: watcher.zip ##################**')
print('**############################################################**')
return
def restore(require_confirm=True):
cwd = os.getcwd()
if not os.path.isfile('watcher.zip'):
print('watcher.zip not found. Place watcher.zip in same directory as backup script.')
return
if require_confirm is True:
ans = input('Restoring backup. This will overwrite existing '
'database, config, and posters. Continue? (y/N): ')
if ans.lower() != 'y':
return
# make temp dir
if os.path.isdir(tmpdir):
print('Old temporary directory found. Removing.')
shutil.rmtree(tmpdir)
print('Creating temporary extraction directory.')
os.mkdir('backup_tmp')
print('Extracting zip.')
zipf = zipfile.ZipFile('watcher.zip')
zipf.extractall(tmpdir)
files = os.listdir(tmpdir)
if 'watcher.sqlite' in files:
print('Restoring database.')
src = os.path.join(tmpdir, 'watcher.sqlite')
if os.path.isfile('watcher.sqlite'):
os.remove('watcher.sqlite')
shutil.copy(src, cwd)
if 'config.cfg' in files:
print('Restoring config.')
src = os.path.join(tmpdir, 'config.cfg')
if os.path.isfile('config.cfg'):
os.remove('config.cfg')
shutil.copy(src, cwd)
if 'posters' in files:
print('Restoring posters.')
tmp_posters = os.path.join(tmpdir, 'posters')
if not os.path.isdir(tmp_posters):
print('Error restoring posters. Not a dir.')
# remove existing posters folder and contents
if os.path.isdir(posterpath):
shutil.rmtree(posterpath)
# make new poster dir
os.mkdir(posterpath)
for poster in os.listdir(tmp_posters):
src = os.path.join(tmp_posters, poster)
shutil.copy2(src, posterpath)
print('Removing temporary directory.')
shutil.rmtree(tmpdir)
print('**############################################################**')
print('**##################### Backup finished ######################**')
print('**################# Zip backup: watcher.zip ##################**')
print('**############################################################**')
return
if __name__ == '__main__':
print('**############################################################**')
print('**############### Watcher backup/restore tool ################**')
print('** Confirm that Watcher is not running while restoring backup **')
print('**############################################################**')
os.chdir(os.path.dirname(os.path.realpath(__file__)))
cwd = os.getcwd()
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument('-b', '--backup', help='Back up to watcher.zip.', action="store_true")
group.add_argument('-r', '--restore', help='Restore from watcher.zip.', action="store_true")
group.add_argument('-y', '--confirm', help='Ignore warnings and answer Y to prompts.', action="store_true")
args = parser.parse_args()
if args.confirm:
require_confirm = False
else:
require_confirm = True
if args.backup:
backup(require_confirm)
sys.exit(0)
elif args.restore:
restore(require_confirm)
sys.exit(0)
else:
print('Invalid arguments.')
sys.exit(0)
|
[
"nosmokingbandit@gmail.com"
] |
nosmokingbandit@gmail.com
|
a43cfa67569d76d94811a81eaf8ca5a7c3499126
|
cce63dc8bf66718746019c18df6355cabe34471a
|
/site_scons/ackward/constructor.py
|
9ff18482422125bf7a2ab234594f46856c5f0b1b
|
[
"MIT"
] |
permissive
|
abingham/ackward
|
1592495c31fff5812b484719d93a0c140d26c127
|
f1a45293de570f4b4429d9eaeb3f6c4da7d245bf
|
refs/heads/master
| 2016-08-12T08:28:07.824253
| 2012-04-29T13:24:50
| 2012-04-29T13:24:50
| 49,885,942
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,151
|
py
|
from .element import SigTemplateElement
from .include import ImplInclude
from .trace import trace
header_template = '${class_name}($header_signature);'
impl_template = '''
${class_name}::${class_name}($impl_signature) try :
core::Object (
${class_name}::cls()($parameters) )
$constructor_initializers
{
}
TRANSLATE_PYTHON_EXCEPTION()
'''
class Constructor(SigTemplateElement):
'''A template for class constructors.
'''
@trace
def __init__(self,
signature=[],
parent=None,
doc=None):
'''
Args:
* cls: The class to which this contructor belongs.
* signature: A sequence of parameter descriptions.
'''
SigTemplateElement.__init__(
self,
open_templates={
'header': header_template,
'impl': impl_template,
},
symbols = {
'signature' : signature,
},
parent=parent,
doc=doc)
self.add_child(
ImplInclude(
('ackward', 'core', 'ExceptionTranslation.hpp')))
|
[
"austin.bingham@gmail.com"
] |
austin.bingham@gmail.com
|
74c5b17fcf4cbff3689ddd9ddff7b7894f1efbfe
|
395cabaa64a3a823a74e0dc52dd801cb7846d6df
|
/fluids/two_phase_voidage.pyi
|
dbe07a821817c30716c2c99cbc6ad42fb5565190
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
CalebBell/fluids
|
883e28aae944e0f55cdc4e759edf9868714afebb
|
837acc99075f65060dfab4e209a72dff4c4fe479
|
refs/heads/master
| 2023-09-01T07:53:27.386513
| 2023-08-19T23:49:01
| 2023-08-19T23:49:01
| 48,924,523
| 298
| 85
|
MIT
| 2023-06-06T05:11:12
| 2016-01-02T21:31:10
|
Python
|
UTF-8
|
Python
| false
| false
| 5,192
|
pyi
|
# DO NOT EDIT - AUTOMATICALLY GENERATED BY tests/make_test_stubs.py!
from __future__ import annotations
from typing import List
from typing import (
List,
Optional,
)
def Armand(x: float, rhol: float, rhog: float) -> float: ...
def Baroczy(x: float, rhol: float, rhog: float, mul: float, mug: float) -> float: ...
def Beattie_Whalley(x: float, mul: float, mug: float, rhol: float, rhog: float) -> float: ...
def Chisholm_Armand(x: float, rhol: float, rhog: float) -> float: ...
def Chisholm_voidage(x: float, rhol: float, rhog: float) -> float: ...
def Cicchitti(x: float, mul: float, mug: float) -> float: ...
def Dix(x: float, rhol: float, rhog: float, sigma: float, m: float, D: float, g: float = ...) -> float: ...
def Domanski_Didion(x: float, rhol: float, rhog: float, mul: float, mug: float) -> float: ...
def Duckler(x: float, mul: float, mug: float, rhol: float, rhog: float) -> float: ...
def Fauske(x: float, rhol: float, rhog: float) -> float: ...
def Fourar_Bories(x: float, mul: float, mug: float, rhol: float, rhog: float) -> float: ...
def Graham(
x: float,
rhol: float,
rhog: float,
mul: float,
mug: float,
m: float,
D: float,
g: float = ...
) -> float: ...
def Gregory_Scott(x: float, rhol: float, rhog: float) -> float: ...
def Guzhov(x: float, rhol: float, rhog: float, m: float, D: float) -> float: ...
def Harms(
x: float,
rhol: float,
rhog: float,
mul: float,
mug: float,
m: float,
D: float
) -> float: ...
def Huq_Loth(x: float, rhol: float, rhog: float) -> float: ...
def Kawahara(x: float, rhol: float, rhog: float, D: float) -> float: ...
def Kopte_Newell_Chato(
x: float,
rhol: float,
rhog: float,
mul: float,
mug: float,
m: float,
D: float,
g: float = ...
) -> float: ...
def Lin_Kwok(x: float, mul: float, mug: float) -> float: ...
def Lockhart_Martinelli_Xtt(
x: float,
rhol: float,
rhog: float,
mul: float,
mug: float,
pow_x: float = ...,
pow_rho: float = ...,
pow_mu: float = ...,
n: Optional[float] = ...
) -> float: ...
def McAdams(x: float, mul: float, mug: float) -> float: ...
def Nicklin_Wilkes_Davidson(x: float, rhol: float, rhog: float, m: float, D: float, g: float = ...) -> float: ...
def Nishino_Yamazaki(x: float, rhol: float, rhog: float) -> float: ...
def Rouhani_1(x: float, rhol: float, rhog: float, sigma: float, m: float, D: float, g: float = ...) -> float: ...
def Rouhani_2(x: float, rhol: float, rhog: float, sigma: float, m: float, D: float, g: float = ...) -> float: ...
def Smith(x: float, rhol: float, rhog: float) -> float: ...
def Steiner(x: float, rhol: float, rhog: float, sigma: float, m: float, D: float, g: float = ...) -> float: ...
def Sun_Duffey_Peng(
x: float,
rhol: float,
rhog: float,
sigma: float,
m: float,
D: float,
P: float,
Pc: float,
g: float = ...
) -> float: ...
def Tandon_Varma_Gupta(
x: float,
rhol: float,
rhog: float,
mul: float,
mug: float,
m: float,
D: float
) -> float: ...
def Thom(x: float, rhol: float, rhog: float, mul: float, mug: float) -> float: ...
def Turner_Wallis(x: float, rhol: float, rhog: float, mul: float, mug: float) -> float: ...
def Woldesemayat_Ghajar(
x: float,
rhol: float,
rhog: float,
sigma: float,
m: float,
D: float,
P: float,
angle: float = ...,
g: float = ...
) -> float: ...
def Xu_Fang_voidage(x: float, rhol: float, rhog: float, m: float, D: float, g: float = ...) -> float: ...
def Yashar(
x: float,
rhol: float,
rhog: float,
mul: float,
mug: float,
m: float,
D: float,
g: float = ...
) -> float: ...
def Zivi(x: float, rhol: float, rhog: float) -> float: ...
def density_two_phase(alpha: float, rhol: float, rhog: float) -> float: ...
def gas_liquid_viscosity(
x: float,
mul: float,
mug: float,
rhol: Optional[float] = ...,
rhog: Optional[float] = ...,
Method: Optional[str] = ...
) -> float: ...
def gas_liquid_viscosity_methods(
rhol: Optional[float] = ...,
rhog: Optional[float] = ...,
check_ranges: bool = ...
) -> List[str]: ...
def homogeneous(x: float, rhol: float, rhog: float) -> float: ...
def liquid_gas_voidage(
x: float,
rhol: float,
rhog: float,
D: Optional[float] = ...,
m: Optional[float] = ...,
mul: Optional[float] = ...,
mug: Optional[float] = ...,
sigma: Optional[float] = ...,
P: Optional[float] = ...,
Pc: Optional[float] = ...,
angle: int = ...,
g: float = ...,
Method: Optional[str] = ...
) -> float: ...
def liquid_gas_voidage_methods(
x: float,
rhol: float,
rhog: float,
D: Optional[float] = ...,
m: Optional[float] = ...,
mul: Optional[float] = ...,
mug: Optional[float] = ...,
sigma: Optional[float] = ...,
P: Optional[float] = ...,
Pc: Optional[float] = ...,
angle: float = ...,
g: float = ...,
check_ranges: bool = ...
) -> List[str]: ...
def two_phase_voidage_experimental(rho_lg: float, rhol: float, rhog: float) -> float: ...
__all__: List[str]
|
[
"Caleb.Andrew.Bell@gmail.com"
] |
Caleb.Andrew.Bell@gmail.com
|
b358377477d8140adb098edf7df754b378f8c110
|
95133906bd7b95359080386ea7570afd26364882
|
/publishconf.py
|
2f4900957f007ee04033474b0248a67fbc928a37
|
[] |
no_license
|
jzuhone/jzuhone.com
|
94325e3afab4ce75d7b7a8268645597c6a4c80a8
|
3e3c3774701ed6a2251e71dc11a7a5e7596bdc92
|
refs/heads/master
| 2020-05-17T19:13:09.102206
| 2016-08-15T14:42:31
| 2016-08-15T14:42:31
| 14,403,842
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 548
|
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
# This file is only used if you use `make publish` or
# explicitly specify it as your config file.
import os
import sys
sys.path.append(os.curdir)
from pelicanconf import *
SITEURL = 'http://hea-www.cfa.harvard.edu/~jzuhone/'
RELATIVE_URLS = False
FEED_ALL_ATOM = 'feeds/all.atom.xml'
CATEGORY_FEED_ATOM = 'feeds/%s.atom.xml'
DELETE_OUTPUT_DIRECTORY = True
# Following items are often useful when publishing
#DISQUS_SITENAME = ""
#GOOGLE_ANALYTICS = ""
|
[
"jzuhone@gmail.com"
] |
jzuhone@gmail.com
|
01950fd457b021ccfdfbf35c8e3b03ab29f0d828
|
010279e2ba272d09e9d2c4e903722e5faba2cf7a
|
/contrib/python/ipywidgets/py2/ipywidgets/widgets/widget_layout.py
|
0b2d202761fa230489f593b60254cca4fb71ab8d
|
[
"Apache-2.0",
"BSD-3-Clause"
] |
permissive
|
catboost/catboost
|
854c1a1f439a96f1ae6b48e16644be20aa04dba2
|
f5042e35b945aded77b23470ead62d7eacefde92
|
refs/heads/master
| 2023-09-01T12:14:14.174108
| 2023-09-01T10:01:01
| 2023-09-01T10:22:12
| 97,556,265
| 8,012
| 1,425
|
Apache-2.0
| 2023-09-11T03:32:32
| 2017-07-18T05:29:04
|
Python
|
UTF-8
|
Python
| false
| false
| 6,462
|
py
|
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
"""Contains the Layout class"""
from traitlets import Unicode, Instance, CaselessStrEnum, validate
from .widget import Widget, register
from .._version import __jupyter_widgets_base_version__
CSS_PROPERTIES=['inherit', 'initial', 'unset']
@register
class Layout(Widget):
"""Layout specification
Defines a layout that can be expressed using CSS. Supports a subset of
https://developer.mozilla.org/en-US/docs/Web/CSS/Reference
When a property is also accessible via a shorthand property, we only
expose the shorthand.
For example:
- ``flex-grow``, ``flex-shrink`` and ``flex-basis`` are bound to ``flex``.
- ``flex-wrap`` and ``flex-direction`` are bound to ``flex-flow``.
- ``margin-[top/bottom/left/right]`` values are bound to ``margin``, etc.
"""
_view_name = Unicode('LayoutView').tag(sync=True)
_view_module = Unicode('@jupyter-widgets/base').tag(sync=True)
_view_module_version = Unicode(__jupyter_widgets_base_version__).tag(sync=True)
_model_name = Unicode('LayoutModel').tag(sync=True)
# Keys
align_content = CaselessStrEnum(['flex-start', 'flex-end', 'center', 'space-between',
'space-around', 'space-evenly', 'stretch'] + CSS_PROPERTIES, allow_none=True, help="The align-content CSS attribute.").tag(sync=True)
align_items = CaselessStrEnum(['flex-start', 'flex-end', 'center',
'baseline', 'stretch'] + CSS_PROPERTIES, allow_none=True, help="The align-items CSS attribute.").tag(sync=True)
align_self = CaselessStrEnum(['auto', 'flex-start', 'flex-end',
'center', 'baseline', 'stretch'] + CSS_PROPERTIES, allow_none=True, help="The align-self CSS attribute.").tag(sync=True)
bottom = Unicode(None, allow_none=True, help="The bottom CSS attribute.").tag(sync=True)
border = Unicode(None, allow_none=True, help="The border CSS attribute.").tag(sync=True)
display = Unicode(None, allow_none=True, help="The display CSS attribute.").tag(sync=True)
flex = Unicode(None, allow_none=True, help="The flex CSS attribute.").tag(sync=True)
flex_flow = Unicode(None, allow_none=True, help="The flex-flow CSS attribute.").tag(sync=True)
height = Unicode(None, allow_none=True, help="The height CSS attribute.").tag(sync=True)
justify_content = CaselessStrEnum(['flex-start', 'flex-end', 'center',
'space-between', 'space-around'] + CSS_PROPERTIES, allow_none=True, help="The justify-content CSS attribute.").tag(sync=True)
justify_items = CaselessStrEnum(['flex-start', 'flex-end', 'center'] + CSS_PROPERTIES,
allow_none=True, help="The justify-items CSS attribute.").tag(sync=True)
left = Unicode(None, allow_none=True, help="The left CSS attribute.").tag(sync=True)
margin = Unicode(None, allow_none=True, help="The margin CSS attribute.").tag(sync=True)
max_height = Unicode(None, allow_none=True, help="The max-height CSS attribute.").tag(sync=True)
max_width = Unicode(None, allow_none=True, help="The max-width CSS attribute.").tag(sync=True)
min_height = Unicode(None, allow_none=True, help="The min-height CSS attribute.").tag(sync=True)
min_width = Unicode(None, allow_none=True, help="The min-width CSS attribute.").tag(sync=True)
overflow = Unicode(None, allow_none=True, help="The overflow CSS attribute.").tag(sync=True)
overflow_x = CaselessStrEnum(['visible', 'hidden', 'scroll', 'auto'] + CSS_PROPERTIES, allow_none=True, help="The overflow-x CSS attribute (deprecated).").tag(sync=True)
overflow_y = CaselessStrEnum(['visible', 'hidden', 'scroll', 'auto'] + CSS_PROPERTIES, allow_none=True, help="The overflow-y CSS attribute (deprecated).").tag(sync=True)
order = Unicode(None, allow_none=True, help="The order CSS attribute.").tag(sync=True)
padding = Unicode(None, allow_none=True, help="The padding CSS attribute.").tag(sync=True)
right = Unicode(None, allow_none=True, help="The right CSS attribute.").tag(sync=True)
top = Unicode(None, allow_none=True, help="The top CSS attribute.").tag(sync=True)
visibility = CaselessStrEnum(['visible', 'hidden']+CSS_PROPERTIES, allow_none=True, help="The visibility CSS attribute.").tag(sync=True)
width = Unicode(None, allow_none=True, help="The width CSS attribute.").tag(sync=True)
object_fit = CaselessStrEnum(['contain', 'cover', 'fill', 'scale-down', 'none'], allow_none=True, help="The object-fit CSS attribute.").tag(sync=True)
object_position = Unicode(None, allow_none=True, help="The object-position CSS attribute.").tag(sync=True)
grid_auto_columns = Unicode(None, allow_none=True, help="The grid-auto-columns CSS attribute.").tag(sync=True)
grid_auto_flow = CaselessStrEnum(['column','row','row dense','column dense']+ CSS_PROPERTIES, allow_none=True, help="The grid-auto-flow CSS attribute.").tag(sync=True)
grid_auto_rows = Unicode(None, allow_none=True, help="The grid-auto-rows CSS attribute.").tag(sync=True)
grid_gap = Unicode(None, allow_none=True, help="The grid-gap CSS attribute.").tag(sync=True)
grid_template_rows = Unicode(None, allow_none=True, help="The grid-template-rows CSS attribute.").tag(sync=True)
grid_template_columns = Unicode(None, allow_none=True, help="The grid-template-columns CSS attribute.").tag(sync=True)
grid_template_areas = Unicode(None, allow_none=True, help="The grid-template-areas CSS attribute.").tag(sync=True)
grid_row = Unicode(None, allow_none=True, help="The grid-row CSS attribute.").tag(sync=True)
grid_column = Unicode(None, allow_none=True, help="The grid-column CSS attribute.").tag(sync=True)
grid_area = Unicode(None, allow_none=True, help="The grid-area CSS attribute.").tag(sync=True)
@validate('overflow_x', 'overflow_y')
def _validate_overflows(self, proposal):
if proposal.value is not None:
import warnings
warnings.warn("Layout properties overflow_x and overflow_y have been deprecated and will be dropped in a future release. Please use the overflow shorthand property instead", DeprecationWarning)
return proposal.value
class LayoutTraitType(Instance):
klass = Layout
def validate(self, obj, value):
if isinstance(value, dict):
return super(LayoutTraitType, self).validate(obj, self.klass(**value))
else:
return super(LayoutTraitType, self).validate(obj, value)
|
[
"akhropov@yandex-team.com"
] |
akhropov@yandex-team.com
|
68b76bbb367a0b66083de4dbb90308c8e0069ab5
|
4f4f7b28b4c50c8df4381f8a9e68ae515d747424
|
/examples/ndviz/0_basic_1d_signal.py
|
2ebc08601ab124c106cad1d172e557b81922ff85
|
[
"BSD-3-Clause"
] |
permissive
|
christian-oreilly/visbrain
|
6cd82c22c33039f5adfac1112ceba016c5a75a32
|
b5f480a16555a10b0032465699a0c371e2be31db
|
refs/heads/master
| 2020-06-01T12:24:57.810735
| 2017-09-09T12:44:25
| 2017-09-09T12:44:25
| 94,073,149
| 0
| 0
| null | 2017-06-12T08:29:51
| 2017-06-12T08:29:51
| null |
UTF-8
|
Python
| false
| false
| 2,692
|
py
|
"""
Plot a 1d signal
================
This example show how to display and control simple 1d signal.
.. image:: ../../picture/picndviz/ex_basic_signal.png
"""
import numpy as np
from visbrain import Ndviz
# Create an empty dictionary :
kw = {}
# Sampling frequency :
sf = 1024.
# Create a 10hz cardinal sinus :
time = np.arange(-1000.1, 1000.1) / 1024.
y = np.sinc(2 * 10 * time).astype(np.float32)
kw['sf'] = sf
# ===================================================================
# Nd-plot configuration :
# -----------------------
"""
The Nd-plot can be used to display a large number of signals. I this example,
we defined above a row signal. In that case, the Nd-plot is not really usefull
be we just illustrate some of the possible inputs.
"""
# ===================================================================
# Display the Nd-plot panel and display the grid :
kw['nd_visible'] = True
kw['nd_grid'] = True
# Add a title / xlabel / ylabel :
kw['nd_title'] = 'Press 0 to reset camera / <space> for playing / r to reset'
kw['nd_xlabel'] = 'Configure using the "Nd-plot" tab of quick settings panel'
kw['nd_ylabel'] = 'Display quick settings using CTRL + d'
# Use a dynamic color (across time) :
kw['nd_color'] = 'dyn_time'
kw['nd_cmap'] = 'Spectral_r'
# Set the linewidth :
kw['nd_lw'] = 2
# ===================================================================
# 1d-plot configuration :
# -----------------------
"""
The 1d-plot can be used to inspect signal by signal. The signal can be display
in several forms cad (press the shortcut in parenthesis):
- As a continuous line (l)
- As a markers cloud (m)
- As a histogram (h)
- As a spectrogram (s)
- As an image (i - not available in this exemple -)
"""
# ===================================================================
# Display the Nd-plot panel and display the grid :
kw['od_visible'] = True
kw['od_grid'] = True
kw['od_title'] = 'Press m (marker), h (histogram), s (spectrogram), l (line)'
kw['od_xlabel'] = 'Switch between different plotting types'
kw['od_ylabel'] = 'Configure using the "Inspect" tab of quick settings panel'
# Marker size :
kw['od_msize'] = 20
# Number of bins in the histogram :
kw['od_bins'] = 100
# Number of fft points / step / starting and ending frequency :
kw['od_nfft'] = 512.
kw['od_step'] = 10.
kw['od_fstart'] = 0.
kw['od_fend'] = 50
# The color dynamically change with the amplitude of the signal :
kw['od_cmap'] = 'viridis'
kw['od_color'] = 'dyn_minmax'
# Every values under 0 will be set to red :
kw['od_vmin'], kw['od_under'] = 0., '#ab4642'
# Every values over 0.9 will be set to gay :
kw['od_vmax'], kw['od_over'] = 0.9, 'gray'
# Linewidth :
kw['od_lw'] = 2
Ndviz(y, **kw).show()
|
[
"e.combrisson@gmail.com"
] |
e.combrisson@gmail.com
|
52ab19697e8c0bdd1412fc80b69662d2dd44def8
|
ce9d475cebeaec9cf10c467c577cb05c3b431fad
|
/code/chapter_12_example_05.py
|
66860a252dfe2b04999c9862d06c8c8188745f3b
|
[] |
no_license
|
Sundarmax/two-scoops-of-django-2.0-code-examples
|
9c8f98d145aaa5498bb558fc5125379cd39003e5
|
a15b2d4c240e879c03d2facf8592a644e27eb348
|
refs/heads/master
| 2022-04-19T10:14:53.795688
| 2020-03-04T15:16:25
| 2020-03-04T15:16:25
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,183
|
py
|
"""
Using This Code Example
=========================
The code examples provided are provided by Daniel Greenfeld and Audrey Roy of
Two Scoops Press to help you reference Two Scoops of Django: Best Practices
for Django 1.11 for Django 2.0 projects. Code Samples follow PEP-0008, with exceptions made for the
purposes of improving book formatting. Example code is provided "as is", and
is not intended to be, and should not be considered or labeled as "tutorial
code".
Permissions
============
In general, you may use the code we've provided with this book in your
programs and documentation. You do not need to contact us for permission
unless you're reproducing a significant portion of the code or using it in
commercial distributions. Examples:
* Writing a program that uses several chunks of code from this course does
not require permission.
* Selling or distributing a digital package from material taken from this
book does require permission.
* Answering a question by citing this book and quoting example code does not
require permission.
* Incorporating a significant amount of example code from this book into your
product's documentation does require permission.
Attributions usually include the title, author, publisher and an ISBN. For
example, "Two Scoops of Django: Best Practices for Django 1.11, by Daniel
Roy Greenfeld and Audrey Roy Greenfeld. Copyright 2017 Two Scoops Press
(978-0-692-91572-1)."
If you feel your use of code examples falls outside fair use of the permission
given here, please contact us at info@twoscoopspress.org.
"""
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import UpdateView
from .forms import TasterForm
from .models import Taster
class TasterUpdateView(LoginRequiredMixin, UpdateView):
model = Taster
form_class = TasterForm
success_url = '/someplace/'
def get_form_kwargs(self):
"""This method is what injects forms with keyword arguments."""
# grab the current set of form #kwargs
kwargs = super().get_form_kwargs()
# Update the kwargs with the user_id
kwargs['user'] = self.request.user
return kwargs
|
[
"pydanny@gmail.com"
] |
pydanny@gmail.com
|
2a23248df2d772216b33169abee1e6bddb4c1062
|
8637ef9b14db2d54199cc189ff1b500c2731a3d3
|
/analyze/scripts/contours.py
|
f0acf978bb6d70e09788f32110abe1fdc0800cd3
|
[] |
no_license
|
Vayel/MPD
|
76610b9380364154608aafc43c0aed433b2ccc16
|
80381367b4963ff0f3c3eeefbf648fd02b675b8d
|
refs/heads/master
| 2016-09-10T01:35:42.222213
| 2014-07-03T08:49:25
| 2014-07-03T08:49:25
| 20,148,560
| 4
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,271
|
py
|
# -*- coding: utf-8 -*-
# Python 2
# OpenCV required
import os
import sys
import numpy as np
import cv2
from cv_functions import loadImg
from global_functions import ensureDir
def main(path):
src = loadImg(path)
src = cv2.resize(src, (0,0), fx=0.7, fy=0.7)
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 127, 255, 0)[1]
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contoursLen = len(contours)
plantsNumber = 0
colorStep = int(200.0/contoursLen)
PERIMETER_LIMIT = 30
LINE_WIDTH = 2
for i in range(contoursLen):
perimeter = cv2.arcLength(contours[i], True)
if perimeter > PERIMETER_LIMIT:
plantsNumber += 1
val = (i+1) * colorStep
cv2.drawContours(src, [contours[i]], -1, (val,val,val), LINE_WIDTH)
print "(" + str(val) + "," + str(val) + "," + str(val) + ") : " + str(perimeter)
print "\n" + str(plantsNumber) + " plants."
cv2.imshow("Contours", src)
cv2.waitKey()
cv2.destroyAllWindows()
def printUsage():
print """
USAGE:
python contours.py <img-path>
e.g.: python contours.py bar/foo.jpg
"""
if __name__ == "__main__":
if len(sys.argv) > 1:
src = sys.argv[1]
main(src)
else:
printUsage()
|
[
"vincent.lefoulon@free.fr"
] |
vincent.lefoulon@free.fr
|
f296b5c06d5efae221488145545599ef45b172bd
|
200eea364c07a2ae5d2533ce66cd0b046ae929f4
|
/gca-cat
|
17c28e78b9824b53b59ab4ce4579fc9217a8bac9
|
[
"BSD-3-Clause"
] |
permissive
|
dalinhuang/GCA-Python
|
f024e7810f0ccc8010bf6726bddb1e8f47383ff2
|
135107cb98c697d20f929cf9db6358a7c403d685
|
refs/heads/master
| 2020-04-24T14:02:01.200668
| 2018-01-16T18:05:21
| 2018-01-16T18:05:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,066
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import codecs
import sys
from gca.core import Abstract
from collections import OrderedDict
class LastUpdatedOrderedDict(OrderedDict):
'Store items in the order the keys were last added'
def __setitem__(self, key, value):
if key in self:
del self[key]
OrderedDict.__setitem__(self, key, value)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='GCA Filter - filter list of abstract by files')
parser.add_argument('files', type=str, nargs='+')
args = parser.parse_args()
abstracts = LastUpdatedOrderedDict()
for f in args.files:
fd = codecs.open(f, 'r', encoding='utf-8') if f != '-' else sys.stdin
for a in Abstract.from_data(fd.read()):
abstracts[a.uuid] = a
fd.close()
abstracts = [a for a in abstracts.itervalues()]
data = Abstract.to_json(abstracts)
sys.stdout.write(data.encode('utf-8'))
|
[
"christian@kellner.me"
] |
christian@kellner.me
|
|
2d85b53a201f4797832bff154c5446bfa2f8676e
|
f3e1814436faac544cf9d56182b6658af257300a
|
/GOOGLE COMPETETIONS/codejam_Q_2_2021.py
|
c955dbe2b50bc045608df87b6c296a2553dfdf9a
|
[] |
no_license
|
preetmodh/COMPETETIVE_CODING_QUESTIONS
|
36961b8b75c9f34e127731eb4ffb5742e577e8a2
|
c73afb87d197e30d801d628a9db261adfd701be9
|
refs/heads/master
| 2023-07-15T03:19:15.330633
| 2021-05-16T10:17:20
| 2021-05-16T10:17:20
| 279,030,727
| 2
| 1
| null | 2021-01-12T03:55:26
| 2020-07-12T09:18:57
|
Python
|
UTF-8
|
Python
| false
| false
| 837
|
py
|
def change(string):
for i in range(len(string)):
if string[i]=="?":
if i==0:
string[i]=string[i+1]
elif i==len(string)-1:
string[i]=string[len(string)-2]
else:
string[i]=string[i-1]
else:
continue
string=''.join(string)
return string
testcase=int(input())
for t in range(testcase):
a=input().split()
X=int(a[0])
Y=int(a[1])
string=a[2]
string=list(string)
ans=0
if len(string)==1:
print("Case #"+str(t+1)+": "+str(abs(ans)))
else:
string =change(string)
ans=X*string.count("CJ")
ans+=Y*string.count("JC")
print("Case #"+str(testcase+1)+": "+str(ans))
|
[
"noreply@github.com"
] |
preetmodh.noreply@github.com
|
7b40dc66da5a51767209659cb82ca97ea7bd57e6
|
08e76791377ef548e37982d2060b1f0a6dd89970
|
/nuclear reacter.py
|
e1908dff710a0d2435f871f7b70effd59463b7d3
|
[] |
no_license
|
GuhanSGCIT/Trees-and-Graphs-problem
|
f975090b9118cf74c0c2efe271c010e9410fc0a7
|
b1b0eec7c7e44f62fa0eff28a8379127f4a66f4e
|
refs/heads/master
| 2023-02-12T21:43:28.362986
| 2021-01-18T16:34:48
| 2021-01-18T16:34:48
| 272,145,239
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,283
|
py
|
"""
Question:-
There are K nuclear reactor chambers labelled from 0 to K-1. Particles are bombarded onto chamber 0.The particles keep
collecting in the chamber 0. However if at any time, there are more than N particles in a chamber,a reaction will cause 1
particle to move to the immediate next chamber,and all the particles in the current chamber will be be destroyed and same
continues till no chamber has number of particles greater than N.
Given K,N and the total number of particles bombarded (A), find the final distribution of particles in the K chambers.
Particles are bombarded one at a time. After one particle is bombarded, the set of reactions, as described, take place.
After all reactions are over, the next particle is bombarded. If a particle is going out from the last chamber, it has
nowhere to go and is lost.
Input Desription:
The input will consist of one line containing three numbers A,N and K separated by spaces. A will be between
0 and 1000000000 inclusive. N will be between 0 and 100 inclusive. K will be between 1 and 100 inclusive.
All chambers start off with zero particles initially.
Output Desription:
Consists of K numbers on one line followed by a newline. The first number is the number of particles in chamber 0,
the second number is the number of particles in chamber 1 and so on.
Testases:
Input:
3 1 3
Output:
1 1.5 0.75
Explanation:
Total of 3 particles are bombarded. After particle 1 is bombarded, the chambers have particle distribution as "1 0 0".
After second particle is bombarded, number of particles in chamber 0 becomes 2 which is greater than 1. So, num of particles
in chamber 0 becomes 0 and in chamber 1 becomes 1. So now distribution is "0 1 0". After the 3rd particle is bombarded,
chamber 0 gets 1 particle and so distribution is "1 1 0" after all particles are bombarded one by one.t:
Input:
1 2 3
Output:
1 0.33 0.11
Input:
5 21 2
Output:
5 0.22
Input:
0 1 1
Output:
0
Input:
2 1 0
Output:
2 0.66
Solution:
"""
a ,n ,k = list(map(int,input().split()))
A = []
i = 0
while i < k and a != 0:
A.append(a % (n + 1))
#print(a % (n + 1))
a = a / (n + 1)
i = i + 1
while i < k:
A.append(0)
i = i + 1
print (' '.join(map(str,A)))
|
[
"noreply@github.com"
] |
GuhanSGCIT.noreply@github.com
|
6283a10e0d1bc367a0882b43b97ba5d9e23c2969
|
501615c82801733e69c7447ab9fd68d3883ed947
|
/hotfix/.svn/pristine/62/6283a10e0d1bc367a0882b43b97ba5d9e23c2969.svn-base
|
434ae5e6bf5a96cac5d9effc5c073fc8842df836
|
[] |
no_license
|
az0ne/python
|
b2e1cc1e925d1fcdb269e7dd4c48e24665deeeee
|
aec5d23bb412f7dfca374fb5c5b9988c1b817347
|
refs/heads/master
| 2021-07-18T02:08:46.314972
| 2017-10-27T06:23:36
| 2017-10-27T06:23:36
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 808
|
# -*- coding: utf-8 -*-
"""
@version: 2016/6/12
@author: Jackie
@contact: jackie@maiziedu.com
@file: urls.py
@time: 2016/6/12 16:13
@note: ??
"""
from django.conf.urls import patterns, url, include
urlpatterns = patterns(
'',
# add by jackie 20160612 488免费试学引导
# 课程大纲引导页
url(r'^(?P<course_short_name>.*?)/syllabus/$',
"mz_lps3_free.student.views.syllabus_index", name='syllabus'),
# 课程预约页
url(r'^(?P<course_short_name>.*?)/appointment/$',
"mz_lps3_free.student.views.appointment_index", name='appointment'),
# 学生端
url(r'^s/', include('mz_lps3_free.student.urls', namespace='student')),
# 老师端
url(r'^t/', include('mz_lps3_free.teacher.urls', namespace='teacher')),
)
|
[
"1461847795@qq.com"
] |
1461847795@qq.com
|
|
a737110b9a871f6e38e01d0309a80f741a69a80d
|
b66ca95d947ebc80713f8857c50dd7ed81e96812
|
/py/escher/static_site.py
|
4167a4e13d613001c660d421fd3fd302440979b6
|
[
"MIT"
] |
permissive
|
clusterinnovationcentre/escher
|
53b767a0e5358100342aab350aa4d6397c41bd40
|
db4212226cb35fd1ca63e49929e60433353bc6d8
|
refs/heads/master
| 2021-01-19T12:15:17.772388
| 2016-09-14T18:21:24
| 2016-09-14T18:21:24
| 69,043,308
| 1
| 0
| null | 2016-09-23T16:44:07
| 2016-09-23T16:44:06
| null |
UTF-8
|
Python
| false
| false
| 2,663
|
py
|
from __future__ import print_function, unicode_literals
from escher.plots import Builder
from escher.urls import get_url
from escher.version import __version__
from escher.urls import top_directory, root_directory
from os.path import join, dirname, realpath
from jinja2 import Environment, PackageLoader
import shutil
# set up jinja2 template location
env = Environment(loader=PackageLoader('escher', 'templates'))
def generate_static_site():
print('Generating static site at %s' % top_directory)
# index file
template = env.get_template('homepage.html')
def static_rel(path):
return 'py/' + path
data = template.render(d3=static_rel(get_url('d3', 'local')),
boot_css=static_rel(get_url('boot_css', 'local')),
homepage_css=static_rel(get_url('homepage_css', 'local')),
favicon=static_rel(get_url('favicon', 'local')),
logo=static_rel(get_url('logo', 'local')),
documentation=get_url('documentation', protocol='https'),
github=get_url('github', protocol='https'),
github_releases=get_url('github_releases', protocol='https'),
homepage_js=static_rel(get_url('homepage_js', 'local')),
version=__version__,
map_download_url=get_url('map_download', 'local'),
web_version=True,
server_index_url=static_rel(get_url('server_index', 'local')))
with open(join(top_directory, 'index.html'), 'wb') as f:
f.write(data.encode('utf-8'))
# viewer and builder
# make the builder
builder = Builder(safe=True, id='static_map')
filepath = join(top_directory, 'builder')
with open(join(root_directory, get_url('server_index', source='local')), 'r') as f:
index_json = f.read()
html = builder.save_html(filepath=filepath,
overwrite=True,
js_source='local',
protocol=None,
minified_js=True,
static_site_index_json=index_json)
# copy over the source maps
escher_map = get_url('escher_min', 'local') + '.map'
builder_css_map = get_url('builder_css_min', 'local') + '.map'
shutil.copy(join(root_directory, escher_map), join(top_directory, 'builder', escher_map))
shutil.copy(join(root_directory, builder_css_map), join(top_directory, 'builder', builder_css_map))
if __name__=='__main__':
generate_static_site()
|
[
"zaking17@gmail.com"
] |
zaking17@gmail.com
|
91ada56a8de2120490cdfea95028b3a323a3ccec
|
5f86944bdf1b810a84c63adc6ed01bbb48d2c59a
|
/kubernetes/client/models/v1_endpoints.py
|
09876472e90030b902b980502a694c788125d712
|
[
"Apache-2.0"
] |
permissive
|
m4ttshaw/client-python
|
384c721ba57b7ccc824d5eca25834d0288b211e2
|
4eac56a8b65d56eb23d738ceb90d3afb6dbd96c1
|
refs/heads/master
| 2021-01-13T06:05:51.564765
| 2017-06-21T08:31:03
| 2017-06-21T08:31:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 7,097
|
py
|
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.6.5
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class V1Endpoints(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, api_version=None, kind=None, metadata=None, subsets=None):
"""
V1Endpoints - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'api_version': 'str',
'kind': 'str',
'metadata': 'V1ObjectMeta',
'subsets': 'list[V1EndpointSubset]'
}
self.attribute_map = {
'api_version': 'apiVersion',
'kind': 'kind',
'metadata': 'metadata',
'subsets': 'subsets'
}
self._api_version = api_version
self._kind = kind
self._metadata = metadata
self._subsets = subsets
@property
def api_version(self):
"""
Gets the api_version of this V1Endpoints.
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#resources
:return: The api_version of this V1Endpoints.
:rtype: str
"""
return self._api_version
@api_version.setter
def api_version(self, api_version):
"""
Sets the api_version of this V1Endpoints.
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#resources
:param api_version: The api_version of this V1Endpoints.
:type: str
"""
self._api_version = api_version
@property
def kind(self):
"""
Gets the kind of this V1Endpoints.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds
:return: The kind of this V1Endpoints.
:rtype: str
"""
return self._kind
@kind.setter
def kind(self, kind):
"""
Sets the kind of this V1Endpoints.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds
:param kind: The kind of this V1Endpoints.
:type: str
"""
self._kind = kind
@property
def metadata(self):
"""
Gets the metadata of this V1Endpoints.
Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata
:return: The metadata of this V1Endpoints.
:rtype: V1ObjectMeta
"""
return self._metadata
@metadata.setter
def metadata(self, metadata):
"""
Sets the metadata of this V1Endpoints.
Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata
:param metadata: The metadata of this V1Endpoints.
:type: V1ObjectMeta
"""
self._metadata = metadata
@property
def subsets(self):
"""
Gets the subsets of this V1Endpoints.
The set of all endpoints is the union of all subsets. Addresses are placed into subsets according to the IPs they share. A single address with multiple ports, some of which are ready and some of which are not (because they come from different containers) will result in the address being displayed in different subsets for the different ports. No address will appear in both Addresses and NotReadyAddresses in the same subset. Sets of addresses and ports that comprise a service.
:return: The subsets of this V1Endpoints.
:rtype: list[V1EndpointSubset]
"""
return self._subsets
@subsets.setter
def subsets(self, subsets):
"""
Sets the subsets of this V1Endpoints.
The set of all endpoints is the union of all subsets. Addresses are placed into subsets according to the IPs they share. A single address with multiple ports, some of which are ready and some of which are not (because they come from different containers) will result in the address being displayed in different subsets for the different ports. No address will appear in both Addresses and NotReadyAddresses in the same subset. Sets of addresses and ports that comprise a service.
:param subsets: The subsets of this V1Endpoints.
:type: list[V1EndpointSubset]
"""
if subsets is None:
raise ValueError("Invalid value for `subsets`, must not be `None`")
self._subsets = subsets
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, V1Endpoints):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
|
[
"mehdy@google.com"
] |
mehdy@google.com
|
8c497cc002f4ef01eeff79c9cdbd5164f0b56620
|
192874fd96861ceb1864a71bf6f13932cc017d63
|
/hue/tools/app_reg/common.py
|
7c95d79fa30c878ca0bbface55ce0ecc1f9b104d
|
[
"Apache-2.0"
] |
permissive
|
OpenPOWER-BigData/HDP-hue
|
1de3efc0ac773f1e7b1acd03675f11b65c6f477d
|
23719febdaae26c916bdc9d0712645987ae7e0e4
|
refs/heads/master
| 2021-01-17T17:19:31.157051
| 2016-07-18T19:44:10
| 2016-07-18T19:44:10
| 63,631,863
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,657
|
py
|
#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you 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
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import glob
import logging
import os
import sys
from posixpath import curdir, sep, pardir, join
# The root of the Hue installation
INSTALL_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', '..'))
# The Hue config directory
HUE_CONF_DIR = os.path.join(INSTALL_ROOT, 'desktop', 'conf')
# Virtual env
VIRTUAL_ENV = os.path.join(INSTALL_ROOT, 'build', 'env')
# The Python executable in virtualenv
ENV_PYTHON = os.path.join(VIRTUAL_ENV, 'bin', 'python')
def cmp_version(ver1, ver2):
"""Compare two version strings in the form of 1.2.34"""
return cmp(ver1.split('.'), ver2.split('.'))
def _get_python_lib_dir():
glob_path = os.path.join(VIRTUAL_ENV, 'lib', 'python*')
res = glob.glob(glob_path)
if len(res) == 0:
raise SystemError("Cannot find a Python installation in %s. "
"Did you do `make hue'?" % glob_path)
elif len(res) > 1:
raise SystemError("Found multiple Python installations in %s. "
"Please `make clean' first." % glob_path)
return res[0]
def _get_python_site_packages_dir():
return os.path.join(_get_python_lib_dir(), 'site-packages')
# Creates os.path.relpath for Python 2.4 and 2.5
if not hasattr(os.path, 'relpath'):
# default to posixpath definition
# no windows support
def relpath(path, start=os.path.curdir):
"""Return a relative version of a path"""
if not path:
raise ValueError("no path specified")
start_list = os.path.abspath(start).split(os.path.sep)
path_list = os.path.abspath(path).split(os.path.sep)
# Work out how much of the filepath is shared by start and path.
i = len(os.path.commonprefix([start_list, path_list]))
rel_list = [os.path.pardir] * (len(start_list)-i) + path_list[i:]
if not rel_list:
return os.path.curdir
return os.path.join(*rel_list)
os.path.relpath = relpath
|
[
"afsanjar@gmail.com"
] |
afsanjar@gmail.com
|
bfef24a076e66dd7c4f8a3fff2a9944ce352f75b
|
e609a2e68426edc025e196fc87474d8b0c154286
|
/triage/model_results_generators.py
|
0fc4e27041fd8f5a5fb6570191e5f6bfab6f46fd
|
[
"MIT"
] |
permissive
|
pvdb2178/triage
|
0119db238a6ee6529ec9cdcdb9e6111b8d6d12fa
|
1fea55cea3165d4f8af0ae49fa225ea0366484be
|
refs/heads/master
| 2021-01-25T06:55:22.826502
| 2017-06-05T16:54:37
| 2017-06-05T16:54:37
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 323
|
py
|
class ModelResultsGenerator(object):
def __init__(self, trained_model_path, model_ids):
self.trained_model_path = trained_model_path
self.model_ids = model_ids
def generate(self):
"""TODO: for each trained model,
create metrics and write to Tyra-compatible database"""
pass
|
[
"tristan.h.crockett@gmail.com"
] |
tristan.h.crockett@gmail.com
|
853170d6ebcfcfa63ebccf1d5e418b943b3e0df1
|
ee8577b0d70ae783e42032fdf38bd4ec6c210ccf
|
/barddo/notifications/admin.py
|
5613ee702d99c99878bd3027f539e47e8511d172
|
[] |
no_license
|
bruno-ortiz/barddo
|
9192cfd5aff9ca0f296f476877b468919bdc5636
|
4f7aa41fd0697af61539efd1aba2062addb63009
|
refs/heads/master
| 2023-05-19T11:15:05.251642
| 2014-09-21T18:36:44
| 2014-09-21T18:36:44
| 374,435,120
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 318
|
py
|
# -*- coding: utf-8 -*-
from django.contrib import admin
from .models import Notification
class NotificationAdmin(admin.ModelAdmin):
list_display = ('recipient', 'actor',
'target', 'unread')
list_filter = ('unread', 'timestamp', )
admin.site.register(Notification, NotificationAdmin)
|
[
"devnull@localhost"
] |
devnull@localhost
|
0e18c5faf91f310952478e4fef2f0be98535c706
|
d7069bc46ab265f5787055a771886aba9af7949d
|
/zabbix/files/iops/check_io.py
|
22fd768a93489b59d7c93c200ea91bf495e4b003
|
[] |
no_license
|
lizhenfen/work
|
a82951abee20dc3b7f998ec880ca8323cb71c5f6
|
abf0f558a6a3a36931ea7bd95255db100b6d249f
|
refs/heads/master
| 2021-01-12T05:34:39.677154
| 2017-03-21T09:28:02
| 2017-03-21T09:28:02
| 77,131,224
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,020
|
py
|
#!/usr/bin/env python
#-*- coding: utf8 -*-
import json
import sys
PY2 = sys.version_info[0] == 2
def getDEVInfo():
res = {}
data = []
with open('/proc/mounts') as fp:
for line in fp:
dev_dict = {}
if '/boot' in line: continue
if line.startswith('/dev'):
line = line.split()
dev_name, mount_point = line[0], line[1]
if 'docker' in dev_name: continue
if 'var' in mount_point: continue
dev_dict['{#DEVNAME}'] = dev_name.split('/')[-1]
dev_dict['{#MOUNTNAME}'] = mount_point
data.append(dev_dict)
res['data'] = data
return json.dumps(res, sort_keys=True, indent=4)
def getDEVStatis(devName, item):
data = {}
with open('/proc/diskstats') as fp:
for line in fp:
if devName in line:
line = line.strip().split()
dev_read_counts = line[3]
dev_read_ms = line[6]
dev_write_counts = line[7]
dev_write_ms = line[8]
dev_io_ms = line[12]
dev_read_sector = line[5]
dev_write_sector = line[9]
data = {
'read.ops' : dev_read_counts,
'read.ms' : dev_read_ms,
'write.ops': dev_write_counts,
'write.ms' : dev_write_ms,
'io.ms' : dev_io_ms,
'read.sector' : dev_read_sector,
'write_sector': dev_write_sector
}
if PY2:
print data.get(item)
else:
print(data.get(item))
if __name__ == "__main__":
if sys.argv[1] == 'discovery':
print getDEVInfo()
elif sys.argv[1] == 'status':
getDEVStatis(sys.argv[2],sys.argv[3])
else:
print "ERROR: argument error"
|
[
"743564797@qq.com"
] |
743564797@qq.com
|
e3e9af5d81885990ee71c8798f9aa4149ac348cc
|
4e44c4bbe274b0a8ccca274f29c4140dfad16d5e
|
/Push2_MIDI_Scripts/decompiled 10.0.3b2 scripts/pushbase/touch_encoder_element.py
|
3b6d6c7f03e0827f3f845147d727d984560865cd
|
[] |
no_license
|
intergalacticfm/Push2_MIDI_Scripts
|
b48841e46b7a322f2673259d1b4131d2216f7db6
|
a074e2337b2e5d2e5d2128777dd1424f35580ae1
|
refs/heads/master
| 2021-06-24T15:54:28.660376
| 2020-10-27T11:53:57
| 2020-10-27T11:53:57
| 137,673,221
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,161
|
py
|
# uncompyle6 version 3.0.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.13 (default, Jan 19 2017, 14:48:08)
# [GCC 6.3.0 20170118]
# Embedded file name: c:\Jenkins\live\output\win_64_static\Release\python-bundle\MIDI Remote Scripts\pushbase\touch_encoder_element.py
# Compiled at: 2018-06-05 08:04:22
from __future__ import absolute_import, print_function, unicode_literals
from ableton.v2.control_surface.elements import TouchEncoderElement as TouchEncoderElementBase
class TouchEncoderObserver(object):
u""" Interface for observing the state of one or more TouchEncoderElements """
def on_encoder_touch(self, encoder):
pass
def on_encoder_parameter(self, encoder):
pass
class TouchEncoderElement(TouchEncoderElementBase):
u""" Class representing an encoder that is touch sensitive """
def __init__(self, undo_step_handler=None, delete_handler=None, *a, **k):
super(TouchEncoderElement, self).__init__(*a, **k)
self._trigger_undo_step = False
self._undo_step_open = False
self._undo_step_handler = undo_step_handler
self._delete_handler = delete_handler
self.set_observer(None)
return
def set_observer(self, observer):
if observer is None:
observer = TouchEncoderObserver()
self._observer = observer
return
def on_nested_control_element_value(self, value, control):
self._trigger_undo_step = value
if value:
param = self.mapped_parameter()
if self._delete_handler and self._delete_handler.is_deleting and param:
self._delete_handler.delete_clip_envelope(param)
else:
self.begin_gesture()
self._begin_undo_step()
self._observer.on_encoder_touch(self)
self.notify_touch_value(value)
else:
self._end_undo_step()
self._observer.on_encoder_touch(self)
self.notify_touch_value(value)
self.end_gesture()
def connect_to(self, parameter):
if parameter != self.mapped_parameter():
self.last_mapped_parameter = parameter
super(TouchEncoderElement, self).connect_to(parameter)
self._observer.on_encoder_parameter(self)
def release_parameter(self):
if self.mapped_parameter() != None:
super(TouchEncoderElement, self).release_parameter()
self._observer.on_encoder_parameter(self)
return
def receive_value(self, value):
self._begin_undo_step()
super(TouchEncoderElement, self).receive_value(value)
def disconnect(self):
super(TouchEncoderElement, self).disconnect()
self._undo_step_handler = None
return
def _begin_undo_step(self):
if self._undo_step_handler and self._trigger_undo_step:
self._undo_step_handler.begin_undo_step()
self._trigger_undo_step = False
self._undo_step_open = True
def _end_undo_step(self):
if self._undo_step_handler and self._undo_step_open:
self._undo_step_handler.end_undo_step()
|
[
"ratsnake.cbs@gmail.com"
] |
ratsnake.cbs@gmail.com
|
ed7db017e09ab445f8dc309bb5c7d7550dd29eca
|
c20f811f26afd1310dc0f75cb00992e237fdcfbd
|
/21-merge-two-sorted-lists.py
|
2db2b0f72463bcc00edca0051683d4d4b8e84092
|
[
"MIT"
] |
permissive
|
dchentech/leetcode
|
4cfd371fe4a320ab3e95925f1b5e00eed43b38b8
|
3111199beeaefbb3a74173e783ed21c9e53ab203
|
refs/heads/master
| 2022-10-21T09:59:08.300532
| 2016-01-04T03:21:16
| 2016-01-04T03:21:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,543
|
py
|
"""
Question:
Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Performance:
1. Total Accepted: 82513 Total Submissions: 250918 Difficulty: Easy
2. Your runtime beats 93.72% of python submissions.
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
# Make everything easy, just take the next at the end.
dummy_head = ListNode(0)
curr_node = dummy_head
while l1 is not None and l2 is not None:
if l1.val < l2.val:
curr_node.next = l1
l1 = l1.next
else:
curr_node.next = l2
l2 = l2.next
curr_node = curr_node.next
curr_node.next = l1 or l2 # append the rest.
return dummy_head.next
n1 = ListNode(1)
n2 = ListNode(2)
n3 = ListNode(3)
n4 = ListNode(4)
n5 = ListNode(5)
n6 = ListNode(6)
n7 = ListNode(7)
n8 = ListNode(8)
n1.next = n3
n3.next = n5
n5.next = n7
n2.next = n4
n4.next = n6
n6.next = n8
result = Solution().mergeTwoLists(n1, n2)
assert result is n1
assert n1.next is n2
assert n2.next is n3
assert n3.next is n4
assert n4.next is n5
assert n5.next is n6
assert n6.next is n7
assert n7.next is n8
|
[
"mvjome@gmail.com"
] |
mvjome@gmail.com
|
63515d7070e6f6fa471eceafd23c5d19fc3aaec5
|
34d6f67245baf6b96915a39f2dff92ceb8652265
|
/DjangoApp/settings.py
|
aa8dd1dce2fe8c302a621f08b64ec9e202771b94
|
[
"MIT"
] |
permissive
|
johnnynode/Django-1.11.11
|
917641dae0eeb892d8f61287b12357dffc6b1d15
|
421f4d23d2773a1338a5163605a2f29202c91396
|
refs/heads/master
| 2020-04-25T11:06:18.924593
| 2020-01-10T10:38:19
| 2020-01-10T10:38:19
| 172,733,799
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,341
|
py
|
"""
Django settings for DjangoApp project.
Generated by 'django-admin startproject' using Django 1.11.11.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'r043d-2qjdi=r7gj4jifc-$)g--ar7q3@huxk5rr&4#vu-pg9s'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['0.0.0.0']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app' # app.apps.AppConfig
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'DjangoApp.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'DjangoApp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydb',
'USER': 'root',
'PASSWORD': '123456_mysql',
'HOST': 'localhost',
'PORT': '3306'
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
|
[
"johnnynode@gmail.com"
] |
johnnynode@gmail.com
|
4c1bc83bd79f6d45d169909107af7299301e7b56
|
453daa2a6c0e7bcac5301b7a3c90431c44e8d6ff
|
/demos/blog_react/aiohttpdemo_blog/admin/posts.py
|
38dce4938f8f41f6985ec3be6d0e7e39d1407c75
|
[
"Apache-2.0"
] |
permissive
|
Deniallugo/aiohttp_admin
|
c4f68df50267fc64e36b9283bfeb80cb426009da
|
effeced4f4cb0fa48143030cd7e55aa9012203ac
|
refs/heads/master
| 2023-07-08T06:02:18.603089
| 2021-08-19T06:57:18
| 2021-08-19T06:57:18
| 296,005,355
| 1
| 0
|
Apache-2.0
| 2021-08-19T06:57:19
| 2020-09-16T10:55:28
| null |
UTF-8
|
Python
| false
| false
| 332
|
py
|
from aiohttp_admin.contrib import models
from aiohttp_admin.backends.sa import PGResource
from .main import schema
from ..db import post
@schema.register
class Posts(models.ModelAdmin):
fields = ('id', 'title', 'pictures', 'backlinks', 'subcategory',)
class Meta:
resource_type = PGResource
table = post
|
[
"nickolainovik@gmail.com"
] |
nickolainovik@gmail.com
|
176cdd36e2826a520c211721a826defe7432b198
|
ac2b3f97b4f2423a3724fbf9af69e362183f7f3a
|
/crimtech_final_project/crimsononline/newsletter/migrations/0004_auto_20160321_1749.py
|
eac989c6e541da79424f7b0e000948499959a6e7
|
[] |
no_license
|
cindyz8735/crimtechcomp
|
e4109855dd9a87fc11dd29fdf6bb81400c9ce97b
|
a9045ea79c73c7b864a391039799c2f22234fed3
|
refs/heads/master
| 2021-01-24T10:06:03.386553
| 2018-04-14T04:24:57
| 2018-04-14T04:24:57
| 123,037,281
| 0
| 0
| null | 2018-02-26T22:08:57
| 2018-02-26T22:08:56
| null |
UTF-8
|
Python
| false
| false
| 1,045
|
py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('newsletter', '0003_auto_20150826_0229'),
]
operations = [
migrations.CreateModel(
name='HarvardTodaySponsoredEvent',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('time', models.CharField(default=b'', max_length=20)),
('description', models.TextField(default=b'')),
],
),
migrations.AddField(
model_name='harvardtodaynewsletter',
name='others_list',
field=models.TextField(default=b'', blank=True),
),
migrations.AddField(
model_name='harvardtodaysponsoredevent',
name='newsletter',
field=models.ForeignKey(related_name='sponsored_events', to='newsletter.HarvardTodayNewsletter'),
),
]
|
[
"cindyz8735@gmail.com"
] |
cindyz8735@gmail.com
|
6d360f0233028c91624e539874a5429b1c382233
|
127e99fbdc4e04f90c0afc6f4d076cc3d7fdce06
|
/2021_하반기 코테연습/boj14620.py
|
7d9fc8ac42f2639b3e07a9a9888085fed91330c1
|
[] |
no_license
|
holim0/Algo_Study
|
54a6f10239368c6cf230b9f1273fe42caa97401c
|
ce734dcde091fa7f29b66dd3fb86d7a6109e8d9c
|
refs/heads/master
| 2023-08-25T14:07:56.420288
| 2021-10-25T12:28:23
| 2021-10-25T12:28:23
| 276,076,057
| 3
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,341
|
py
|
n = int(input())
mapp = []
for _ in range(n):
tmp = list(map(int, input().split()))
mapp.append(tmp)
check = [[False for _ in range(n)] for _ in range(n)]
answer = 1e10
dx = [1, -1, 0, 0]
dy = [0, 0, -1, 1]
def check_range(x, y):
if x>=0 and x<n and y>=0 and y<n:
return True
return False
def check_find(x, y):
global dx, dy
for i in range(4):
nx, ny = x+dx[i], y+dy[i]
if not check_range(nx, ny) or check[nx][ny]:
return False
return True
def get_sum(x, y):
global dx, dy
s = mapp[x][y]
for i in range(4):
nx, ny = x+dx[i], y+dy[i]
s+=mapp[nx][ny]
return s
def getSol(cur, cnt):
global answer, dx, dy
if cnt==3:
answer = min(answer, cur)
return
for i in range(n):
for j in range(n):
if not check[i][j] and check_find(i, j):
tmp= mapp[i][j]
for k in range(4):
nx, ny = i+dx[k], j+dy[k]
check[nx][ny] = True
tmp+=mapp[nx][ny]
getSol(cur+tmp, cnt+1)
for k in range(4):
nx, ny = i+dx[k], j+dy[k]
check[nx][ny] = False
getSol(0, 0)
print(answer)
|
[
"holim1226@gmail.com"
] |
holim1226@gmail.com
|
f4654a97d2589c028a6eb4ff6fc813d361ca27b5
|
93ab050518092de3a433b03744d09b0b49b541a6
|
/iniciante/Mundo 02/Exercícios Corrigidos/Exercício 036.py
|
6859a806e2d4e38fc694507fed1fb3ea02e4c1a7
|
[
"MIT"
] |
permissive
|
ggsant/pyladies
|
1e5df8772fe772f8f7d0d254070383b9b9f09ec6
|
37e11e0c9dc2fa2263ed5b42df5a395169408766
|
refs/heads/master
| 2023-01-02T11:49:44.836957
| 2020-11-01T18:36:43
| 2020-11-01T18:36:43
| 306,947,105
| 3
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 766
|
py
|
"""
EXERCÍCIO 036: Aprovando Empréstimo
Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa.
Pergunte o valor da casa, o salário do comprador e em quantos anos ele vai pagar.
A prestação mensal não pode exceder 30% do salário, ou então o empréstimo será negado.
"""
casa = float(input('Valor da casa: R$ '))
salario = float(input('Salário do comprador: R$ '))
anos = int(input('Quantos anos de financiamento? '))
prestacao = casa / (anos * 12)
minimo = salario * 30 / 100
print('Para pagar uma casa de R$ {:.2f} em {} anos,'.format(casa, anos), end=' ')
print('a prestação será de R$ {:.2f}.'.format(prestacao))
if prestacao <= minimo:
print('Empréstimo pode ser CONCEDIDO!')
else:
print('Empréstimo NEGADO!')
|
[
"61892998+ggsant@users.noreply.github.com"
] |
61892998+ggsant@users.noreply.github.com
|
3dc35cccc2f987013f4445f95435d2dad6a1f12b
|
2834298c6a50ff7cfada61fb028b9fd3fc796e85
|
/introd/programas/cap01_prob/exemp_cap_01_01_c.py
|
3265df1f052c7c1bad508ee770a2d6ad52fb0fa4
|
[] |
no_license
|
ernestojfcosta/IPRP_LIVRO_2013_06
|
73841c45d000dee7fc898279d4b10d008c039fd0
|
a7bb48745ad2fbfeb5bd4bc334cb7203d8f204a4
|
refs/heads/master
| 2021-01-22T05:00:57.868387
| 2013-06-07T11:00:55
| 2013-06-07T11:00:55
| 10,548,127
| 0
| 1
| null | null | null | null |
WINDOWS-1257
|
Python
| false
| false
| 472
|
py
|
# -*- coding: mac-roman -*-
# Exemplo simples entradas / sa’das / atribui¨›es
# Ernesto Costa
# Dada a altura calcula o peso ideal para uma pessoa
def main():
"""" Tem o peso ideal?
"""
# mensagem
altura = input("A sua altura por favor: ")
sexo = raw_input("O seu sexo por favor (M / F): ")
if sexo == 'M':
peso_ideal = 72.7 * altura - 58
else:
peso_ideal = 62.1 * altura - 44.7
print "O seu peso ideal e ", peso_ideal, "kilos"
main()
|
[
"ernesto@dei.uc.pt"
] |
ernesto@dei.uc.pt
|
dac804c33230879d67dd611d93deb94b2adc451b
|
bfe6c95fa8a2aae3c3998bd59555583fed72900a
|
/sumRootToLeaf.py
|
ee43ddceb5b9ce42b6f787cf5ea3e662d9ad0968
|
[] |
no_license
|
zzz136454872/leetcode
|
f9534016388a1ba010599f4771c08a55748694b2
|
b5ea6c21bff317884bdb3d7e873aa159b8c30215
|
refs/heads/master
| 2023-09-01T17:26:57.624117
| 2023-08-29T03:18:56
| 2023-08-29T03:18:56
| 240,464,565
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 534
|
py
|
from typing import Optional
from pytree import TreeNode
class Solution:
def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:
value = 0
res = 0
def dfs(root, value):
if not root:
return
value = 2 * value + root.val
if not root.left and not root.right:
nonlocal res
res += value
return
dfs(root.left, value)
dfs(root.right, value)
dfs(root, 0)
return res
|
[
"zzz136454872@163.com"
] |
zzz136454872@163.com
|
d5347447760b6c6389ec49923408c533d457bf16
|
f865fdd970f8e37ea2aa5157374af8c4d6ced987
|
/test/test_vehicle_list_list.py
|
249ea92d8240a677b23124e6d62fb0bcd81d0216
|
[] |
no_license
|
gkeep-openapi/python-sdk
|
7e809448355bff535b3d64e013f001e9196c5e19
|
7c4f3785b47a110386ef10109619654522c95de5
|
refs/heads/master
| 2022-05-28T16:13:06.643958
| 2022-05-13T14:58:39
| 2022-05-13T14:58:39
| 235,536,010
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 833
|
py
|
# coding: utf-8
"""
Gkeep API
Gkeep API # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import swagger_client
from models.vehicle_list_list import VehicleListList # noqa: E501
from swagger_client.rest import ApiException
class TestVehicleListList(unittest.TestCase):
"""VehicleListList unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testVehicleListList(self):
"""Test VehicleListList"""
# FIXME: construct object with mandatory attributes with example values
# model = swagger_client.models.vehicle_list_list.VehicleListList() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
|
[
"gkeep-ci-jenkins"
] |
gkeep-ci-jenkins
|
fbf785d429c68337f3d04cbc3305b64d88758482
|
9b20743ec6cd28d749a4323dcbadb1a0cffb281b
|
/07_Machine_Learning_Mastery_with_Python/10/gaussian_naive_bayes.py
|
b5529aced1162296ffe0b53527fd96f38568671a
|
[] |
no_license
|
jggrimesdc-zz/MachineLearningExercises
|
6e1c7e1f95399e69bba95cdfe17c4f8d8c90d178
|
ee265f1c6029c91daff172b3e7c1a96177646bc5
|
refs/heads/master
| 2023-03-07T19:30:26.691659
| 2021-02-19T08:00:49
| 2021-02-19T08:00:49
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 581
|
py
|
# Gaussian Naive Bayes Classification
from pandas import read_csv
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn.naive_bayes import GaussianNB
filename = 'pima-indians-diabetes.data.csv'
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
dataframe = read_csv(filename, names=names)
array = dataframe.values
X = array[:, 0:8]
Y = array[:, 8]
kfold = KFold(n_splits=10, random_state=7, shuffle=True)
model = GaussianNB()
results = cross_val_score(model, X, Y, cv=kfold)
print(results.mean())
|
[
"jgrimes@jgrimes.tech"
] |
jgrimes@jgrimes.tech
|
8acf901f02911518883bb83b3ee13e1155dde5be
|
971e0efcc68b8f7cfb1040c38008426f7bcf9d2e
|
/tests/artificial/transf_Integration/trend_LinearTrend/cycle_12/ar_12/test_artificial_1024_Integration_LinearTrend_12_12_0.py
|
ce9ad4b11a32844c2d9b12c61134643c26fb5ac1
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
antoinecarme/pyaf
|
a105d172c2e7544f8d580d75f28b751351dd83b6
|
b12db77cb3fa9292e774b2b33db8ce732647c35e
|
refs/heads/master
| 2023-09-01T09:30:59.967219
| 2023-07-28T20:15:53
| 2023-07-28T20:15:53
| 70,790,978
| 457
| 77
|
BSD-3-Clause
| 2023-03-08T21:45:40
| 2016-10-13T09:30:30
|
Python
|
UTF-8
|
Python
| false
| false
| 270
|
py
|
import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "LinearTrend", cycle_length = 12, transform = "Integration", sigma = 0.0, exog_count = 0, ar_order = 12);
|
[
"antoine.carme@laposte.net"
] |
antoine.carme@laposte.net
|
52ddde778566b011bf474203eeaab73b80a92abd
|
e1e5ffef1eeadd886651c7eaa814f7da1d2ade0a
|
/Systest/tests/acl-new/ACL_FUN_055.py
|
56f2d44de7774024373f48e52761bd1fba98265a
|
[] |
no_license
|
muttu2244/MyPython
|
1ddf1958e5a3514f9605d1f83c0930b24b856391
|
984ca763feae49a44c271342dbc15fde935174cf
|
refs/heads/master
| 2021-06-09T02:21:09.801103
| 2017-10-10T07:30:04
| 2017-10-10T07:30:04
| 13,803,605
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,939
|
py
|
#!/usr/bin/env python2.5
"""
#######################################################################
#
# Copyright (c) Stoke, Inc.
# All Rights Reserved.
#
# This code is confidential and proprietary to Stoke, Inc. and may only
# be used under a license from Stoke.
#
#######################################################################
DESCRIPTION:To Verify applying outbound access-list to a port-interface
TEST PLAN: ACL Test plans
TEST CASES:ACL_FUN_055
TOPOLOGY :
Linux1 (17.1.1.1/24) -> 3/0 (17.1.1.2/24) SSX
SSX (16.1.1.2/24) 2/0 -> Linux2 (16.1.1.1/24)
HOW TO RUN:python2.5 ACL_FUN_055.py
AUTHOR: jayanth@stoke.com
REVIEWER:
"""
import sys, os
mydir = os.path.dirname(__file__)
qa_lib_dir = os.path.join(mydir, "../../lib/py")
if qa_lib_dir not in sys.path:
sys.path.insert(1,qa_lib_dir)
#Import Frame-work libraries
from SSX import *
from Linux import *
from log import *
from StokeTest import test_case, test_suite, test_runner
from log import buildLogger
from logging import getLogger
from acl import *
from helpers import is_healthy
from misc import *
#import config and topo file
from config import *
from topo import *
class test_ACL_FUN_055(test_case):
myLog = getLogger()
def setUp(self):
#Establish a telnet session to the SSX box.
self.ssx = SSX(ssx["ip_addr"])
self.linux=Linux(linux['ip_addr'],linux['user_name'],linux['password'])
self.linux1=Linux(linux1['ip_addr'],linux1['user_name'],linux1['password'])
self.ssx.telnet()
self.linux.telnet()
self.linux1.telnet()
# Clear the SSX config
self.ssx.clear_config()
# wait for card to come up
self.ssx.wait4cards()
self.ssx.clear_health_stats()
def tearDown(self):
# Close the telnet session of SSX
self.ssx.close()
self.linux.close()
self.linux1.close()
def test_ACL_FUN_055(self):
# Push SSX config
self.ssx.config_from_string(script_var['ACL_FUN_055'])
self.linux1.configure_ip_interface(p1_ssx_linux1[1], script_var['linux_phy_iface1_ip_mask'])
self.linux1.configure_ip_interface(p1_ssx_linux2[1], script_var['linux_phy_iface2_ip_mask'])
self.linux.cmd("sudo /sbin/route add -net %s gw %s" %(script_var['client1_route'],script_var['client1_gateway']))
self.linux1.cmd("sudo /sbin/route add -net %s gw %s" %(script_var['client2_route'],script_var['client2_gateway']))
#changing context and clear port counters
self.ssx.cmd("context %s" %(script_var['context_name']))
self.ssx.cmd("clear ip access-list name subacl counters")
#applying nemesis tool for generating igmp packets
self.linux.cmd("ping -c 5 %s"%(script_var['linux_phy_iface2_ip']),timeout=40)
result=self.ssx.cmd("show ip access-list name subacl counters")
result=result.split('\n')
result=result[2]
result=result.split(' ')
output=result[5]
output=int(output)
self.failIfEqual(output,0,"Deny Outbound ICMP Failed")
self.ssx.cmd("clear ip access-list name subacl counters")
self.linux.cmd("sudo /usr/local/bin/nemesis tcp -S %s -D %s -d %s"%(script_var['linux_phy_iface1_ip'],script_var['linux_phy_iface2_ip'],p1_ssx_xpressvpn[1]))
result=self.ssx.cmd("show ip access-list name subacl counters")
result=result.split('\n')
result=result[2]
result=result.split(' ')
output=result[4]
output=int(output)
self.failIfEqual(output,0,"Permit Outbound TCP Failed")
# Checking SSX Health
hs = self.ssx.get_health_stats()
self.failUnless(is_healthy( hs), "Platform is not healthy")
if __name__ == '__main__':
filename = os.path.split(__file__)[1].replace('.py','.log')
log = buildLogger(filename, debug=True, console=True)
suite = test_suite()
suite.addTest(test_ACL_FUN_055)
test_runner(stream = sys.stdout).run(suite)
|
[
"muttu2244@yahoo.com"
] |
muttu2244@yahoo.com
|
f9d76b0440856d9311fe34261caa26b0b7aebe92
|
882c865cf0a4b94fdd117affbb5748bdf4e056d0
|
/python/BOJ/10_DFS_BFS/BOJ1697_숨바꼭질2.py
|
bc86af4e46dc7af94108fb47b8aaa7168c43897e
|
[] |
no_license
|
minhee0327/Algorithm
|
ebae861e90069e2d9cf0680159e14c833b2f0da3
|
fb0d3763b1b75d310de4c19c77014e8fb86dad0d
|
refs/heads/master
| 2023-08-15T14:55:49.769179
| 2021-09-14T04:05:11
| 2021-09-14T04:05:11
| 331,007,037
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 950
|
py
|
from collections import deque
N, K = map(int, input().split())
count = [0] * 100001
def bfs(x):
need_visit = deque([x])
while need_visit:
x = need_visit.popleft()
dx = [x-1, x+1, x*2]
if x == K:
return count[x]
for nx in dx:
if nx < 0 or nx > 100000:
continue
elif not count[nx]:
need_visit.append(nx)
count[nx] = count[x] + 1 # (이전에 방문 안했을때만, 이전 depth 기준 +1)
print(bfs(N))
# print(count)
'''
1. dequeue를 사용했더니 속도가 반 넘게 줄었다..!
2. 속도 관련
- list의 경우 pop(0) 의 경우 => O(N)
- dequeue 의 경우 양방향으로 pop가능. => O(1)
3. pop(0)을 많이 해야하는 경우 dequeue자료구조 활용
4. sys.stdin.readline()속도 줄이기는 입력을 많이 받아야하는 경우에 사용하자.(입력 량 적으면 큰 차이 없음)
'''
|
[
"queen.minhee@gmail.com"
] |
queen.minhee@gmail.com
|
0c62175729789e521b514d0ac7abca4b662ba72a
|
3c5e4086ff49fb28be692085855c63b624b00d37
|
/SuccessiveCommunities_IPAM/commonUsers.py
|
63a4f0bf34dfa4d52a609f79cf37b7eff868da7d
|
[] |
no_license
|
Roja-B/IPAM
|
bd1a708f053912ce401a99cbe827f2503eae9446
|
5a0e49299abcccda9eb1e7cc523315e6c14d5def
|
refs/heads/master
| 2016-08-08T05:09:02.910761
| 2013-02-06T06:01:11
| 2013-02-06T06:01:11
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,092
|
py
|
# Unipartite Projection
# Creates Unipartite graph using Jaccard Index from a bipartite graph
# Input: Bipartite Graph
# Form: "EdgeList"
import sys
from string import lower,upper
from PARAMETERS import *
bgraphname = PATH+"/myResults/20002012/bipartite.txt"
f1 = open(bgraphname,"r")
Participants = dict()
for line in f1:
L1 = line.strip().split("\t")
program = upper(L1[0])
participant = L1[1]
try: Participants[program].add(participant)
except KeyError:
Participants[program] = set()
Participants[program].add(participant)
f1.close()
print "IPAM data has been loaded."
Answer = raw_input('Would you like to see participant overlaps between two programs? Enter y or n: ')
while Answer == 'y':
prog1 = raw_input('Enter first program: ')
prog2 = raw_input('Enter second program: ')
CommonParticipants = set.intersection(Participants[upper(prog1)],Participants[upper(prog2)])
print "People who participated in both programs are as follows:"
print list(CommonParticipants)
Answer = raw_input('Enter y if you want to enter two other programs, otherwise press any key: ')
|
[
"roja@ucla.edu"
] |
roja@ucla.edu
|
e6f1aa570bf7102147e51ae3fc964e0a6563e419
|
4dcdc0533b89af0160bb13f729b1fb7be1454e6e
|
/Topics/Identity testing/Check the truth/main.py
|
d290b0cff6723c99e75d9e3e98bc17ccd891dc21
|
[] |
no_license
|
alendina/Numeric_Matrix
|
17227221d27278825868df8d78969ee7b6febca6
|
74b8ff3365eba858b6974f01812bfe2ca041b91c
|
refs/heads/master
| 2023-08-18T06:38:24.145454
| 2021-10-24T18:33:05
| 2021-10-24T18:33:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 145
|
py
|
def check_values(first_value, second_value):
if bool(first_value) and bool(second_value):
return True
else:
return False
|
[
"alendina@MacBook-Air-Olena.local"
] |
alendina@MacBook-Air-Olena.local
|
8f7d70e38632a557f44e50d6671c469fd196770d
|
c2d48caa5db7e746a38beca625406fcf47379d3c
|
/src/olympia/lib/storage.py
|
0413ca12fc2c4a45f994579b021cdea728b44eab
|
[] |
permissive
|
mozilla/addons-server
|
1f6269ec0a4aa5a0142a5f81978ef674daf213a7
|
e0f043bca8a64478e2ba62f877c9dc28620be22f
|
refs/heads/master
| 2023-09-01T09:34:41.867534
| 2023-09-01T07:21:22
| 2023-09-01T07:21:22
| 16,416,867
| 920
| 590
|
BSD-3-Clause
| 2023-09-14T16:15:01
| 2014-01-31T18:44:15
|
Python
|
UTF-8
|
Python
| false
| false
| 733
|
py
|
from django.contrib.staticfiles.storage import ManifestStaticFilesStorage
class ManifestStaticFilesStorageNotMaps(ManifestStaticFilesStorage):
patterns = (
(
'*.css',
(
# These regexs are copied from HashedFilesMixin in django4.1+
r"""(?P<matched>url\(['"]{0,1}\s*(?P<url>.*?)["']{0,1}\))""",
(
r"""(?P<matched>@import\s*["']\s*(?P<url>.*?)["'])""",
"""@import url("%(url)s")""",
),
# We are ommiting the sourceMappingURL regexs for .css and .js as they
# don't work how we copy over the souces in Makefile-docker.copy_node_js
),
),
)
|
[
"noreply@github.com"
] |
mozilla.noreply@github.com
|
c46fe73e6b759e76d94ab70e318253601e5e12b7
|
67f19ebb1fb3189e4c2f99484c1dc13af5099edb
|
/wii_packages/enso/fever/fever_idol7/fever_idol7.py
|
9e8af364fb989f103457962cc724befb394fa6d4
|
[] |
no_license
|
delguoqing/PyLMPlayer
|
609c4fe35e56e4ce3ce30eeb2e9244aad5ea1609
|
db8a1edf70ac1c11deffddc458788b3a2c2078df
|
refs/heads/master
| 2021-01-22T05:06:00.491732
| 2013-09-13T04:54:23
| 2013-09-13T04:54:23
| 8,878,510
| 5
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 243
|
py
|
def func0(this, _global):
this.stop()
def func1(this, _global):
this.gotoAndPlay("fever")
def func2(this, _global):
this.gotoAndStop(0)
def func3(this, _global):
this.gotoAndPlay("feverWide")
DATA = (
func0,
func1,
func2,
func3,
)
|
[
"delguoqing@hotmail.com"
] |
delguoqing@hotmail.com
|
9f0d2bf444ffbf8b751a89dbae76aa88747bb009
|
e6c7c0fe8ff901b02c02c8cfb342cc2bcd76a8b2
|
/lambda_p.py
|
0eb68693ab8a4e9920821997994dbc0c829f235e
|
[] |
no_license
|
VladyslavHnatchenko/theory
|
d7a3803e7887e60beb2936f24b9eb4056a04a711
|
d2a18d577c046b896fcab86684d9011db1d4867d
|
refs/heads/master
| 2020-04-08T10:42:55.198754
| 2018-12-25T06:00:17
| 2018-12-25T06:00:17
| 159,279,432
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,550
|
py
|
def multiply_all(numbers):
product = 1
for n in numbers:
product *= n
return product
numbers = [2, 1, 3, 4, 7, 11, 18]
product = multiply_all(numbers)
print(product)
# from functools import reduce
#
#
# numbers = [2, 1, 3, 4, 7, 11, 18]
# product = reduce(lambda x, y: x * y, numbers, 1)
#
# print(product)
# numbers = [2, 1, 3, 4, 7, 11, 18]
# squared_numbers = (n**2 for n in numbers)
# odd_numbers = (n for n in numbers if n % 2 == 1)
# print(odd_numbers)
# print(squared_numbers)
# print(numbers)
# numbers = [2, 1, 3, 4, 7, 11, 18]
# squared_numbers = map(lambda n: n**2, numbers)
# odd_numbers = filter(lambda n: n % 2 == 1, numbers)
# print(squared_numbers)
# print(odd_numbers)
# print(numbers)
# def color_of_point(point):
# (x, y), color = point
# return color
#
#
# points = [((1, 2), 'red'), ((3, 4), 'green')]
# points_by_color = sorted(points, key=color_of_point)
# print(points_by_color)
# def length_and_alphabetical(string):
# return len(string), string.casefold()
#
#
# colors = (["Goldenrod", "Purple", "Salmon", "Turquoise", "Cyan"])
# colors_by_length = sorted(colors, key=length_and_alphabetical)
# print(colors_by_length)
# colors = (["Goldenrod", "Purple", "Salmon", "Turquoise", "Cyan"])
# print(sorted(colors, key=lambda s: s.casefold()))
# normalized_colors = map(lambda s: s.casefold(), colors)
# colors = ["Goldenrod", "Purple", "Salmon", "Turquoise", "Cyan"]
#
#
# def normalize_case(string):
# return string.casefold()
#
#
# normalized_colors = map(normalize_case, colors)
|
[
"hnatchenko.vladyslav@gmail.com"
] |
hnatchenko.vladyslav@gmail.com
|
712c35310d6dded71e8bb56fe425b5331e450d82
|
7fa08c93ff0caa4c86d4fa1727643331e081c0d0
|
/brigid_api_client/models/aws_accounts_retrieve_expand.py
|
affdf90386d13f2fa7f0cb41d10e07e378faf6b2
|
[
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] |
permissive
|
caltechads/brigid-api-client
|
760768c05280a4fb2f485e27c05f6ae24fbb7c6f
|
3e885ac9e7b3c00b8a9e0cc1fb7b53b468d9e10a
|
refs/heads/master
| 2023-03-23T03:11:02.446720
| 2021-03-13T00:47:03
| 2021-03-13T00:47:03
| 338,424,261
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 263
|
py
|
from enum import Enum
class AwsAccountsRetrieveExpand(str, Enum):
AWSACCOUNTAWS_VPCS = "awsaccount.aws_vpcs"
AWSACCOUNTCONTACTS = "awsaccount.contacts"
AWSACCOUNTTEAM = "awsaccount.team"
def __str__(self) -> str:
return str(self.value)
|
[
"cmalek@caltech.edu"
] |
cmalek@caltech.edu
|
7ce76357c170555ecbb807b767bd856eaf8da2cc
|
afd2087e80478010d9df66e78280f75e1ff17d45
|
/torch/onnx/_internal/diagnostics/infra/sarif/_fix.py
|
5e3b944aa23983b9fbaa1e7015921124ae0f7c75
|
[
"BSD-3-Clause",
"BSD-2-Clause",
"LicenseRef-scancode-secret-labs-2011",
"LicenseRef-scancode-generic-cla",
"BSL-1.0",
"Apache-2.0"
] |
permissive
|
pytorch/pytorch
|
7521ac50c47d18b916ae47a6592c4646c2cb69b5
|
a6f7dd4707ac116c0f5fb5f44f42429f38d23ab4
|
refs/heads/main
| 2023-08-03T05:05:02.822937
| 2023-08-03T00:40:33
| 2023-08-03T04:14:52
| 65,600,975
| 77,092
| 24,610
|
NOASSERTION
| 2023-09-14T21:58:39
| 2016-08-13T05:26:41
|
Python
|
UTF-8
|
Python
| false
| false
| 1,069
|
py
|
# DO NOT EDIT! This file was generated by jschema_to_python version 0.0.1.dev29,
# with extension for dataclasses and type annotation.
from __future__ import annotations
import dataclasses
from typing import List, Optional
from torch.onnx._internal.diagnostics.infra.sarif import (
_artifact_change,
_message,
_property_bag,
)
@dataclasses.dataclass
class Fix(object):
"""A proposed fix for the problem represented by a result object. A fix specifies a set of artifacts to modify. For each artifact, it specifies a set of bytes to remove, and provides a set of new bytes to replace them."""
artifact_changes: List[_artifact_change.ArtifactChange] = dataclasses.field(
metadata={"schema_property_name": "artifactChanges"}
)
description: Optional[_message.Message] = dataclasses.field(
default=None, metadata={"schema_property_name": "description"}
)
properties: Optional[_property_bag.PropertyBag] = dataclasses.field(
default=None, metadata={"schema_property_name": "properties"}
)
# flake8: noqa
|
[
"pytorchmergebot@users.noreply.github.com"
] |
pytorchmergebot@users.noreply.github.com
|
c8cfea60f10bab3d2d252c18e5e0bdbc99706d03
|
2f898bb332097d11f321186207e94f6d156587f3
|
/dsp2019/classe4_dft/generar_audio.py
|
f41a4c4171677ad77f1be4e998e728e9ab7e47bf
|
[
"MIT"
] |
permissive
|
miltonsarria/teaching
|
ad2d07e9cfbfcf272c4b2fbef47321eae765a605
|
7a2b4e6c74d9f11562dfe34722e607ca081c1681
|
refs/heads/master
| 2022-01-05T05:58:13.163155
| 2019-05-02T20:45:46
| 2019-05-02T20:45:46
| 102,375,690
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 570
|
py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from scipy.io.wavfile import read
from scipy.io.wavfile import write
import numpy as np
import matplotlib.pyplot as plt
fs=16e3
longitud = 2# sec
n=np.linspace(1./fs,longitud,fs*longitud);
F=400 #frecuencia fundamental
w=2*np.pi*F #frecuencia angular
Vm=1 #valor de amplitud de la onda
#generar onda sinusoidal pura
x=Vm*np.cos(w*n)
#definir un nombre y guardar el archivp
filename = 'ejemplo1.wav'
write(filename,fs,x)
#mostrar en una grafica la sinusoidal guardada
plt.plot(x)
plt.show()
|
[
"miltonsarria@gmail.com"
] |
miltonsarria@gmail.com
|
f7e3e1ceda275bc64213308ab21495cb7d97b19a
|
8d2a124753905fb0455f624b7c76792c32fac070
|
/pytnon-month02/month02-lvze-notes/day15-lvze/save_file.py
|
9095c3857f57b6435b8db97a5bd1032e0fa61e98
|
[] |
no_license
|
Jeremy277/exercise
|
f38e4f19aae074c804d265f6a1c49709fd2cae15
|
a72dd82eb2424e4ae18e2f3e9cc66fc4762ec8fa
|
refs/heads/master
| 2020-07-27T09:14:00.286145
| 2019-09-17T11:31:44
| 2019-09-17T11:31:44
| 209,041,629
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 760
|
py
|
"""
save_file.py
二进制文件存取示例
"""
import pymysql
# 连接数据库
db = pymysql.connect(user='root',
password = '123456',
database = 'stu',
charset='utf8')
# 获取游标 (操作数据库,执行sql语句,得到执行结果)
cur = db.cursor()
# 执行语句
# 存入图片
with open('gakki.jpg','rb') as f:
data = f.read()
sql = "insert into images values (1,%s,%s)"
cur.execute(sql,[data,'初恋'])
db.commit()
# 提取图片
sql = "select photo from images \
where comment='初恋'"
cur.execute(sql)
data = cur.fetchone()[0] #元组里面有一个数据
with open('gakki_get.jpg','wb') as f:
f.write(data)
# 关闭游标
cur.close()
# 关闭数据库
db.close()
|
[
"13572093824@163.com"
] |
13572093824@163.com
|
61fb603d132eda1ba08b4a29b00a1112cafcd207
|
163bbb4e0920dedd5941e3edfb2d8706ba75627d
|
/Code/CodeRecords/2890/58634/237718.py
|
7875c0abb4bcd7b3b6440c09767567838f31d8cb
|
[] |
no_license
|
AdamZhouSE/pythonHomework
|
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
|
ffc5606817a666aa6241cfab27364326f5c066ff
|
refs/heads/master
| 2022-11-24T08:05:22.122011
| 2020-07-28T16:21:24
| 2020-07-28T16:21:24
| 259,576,640
| 2
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 511
|
py
|
a = [int(i) for i in input().split(" ")]
n = a[0]
x = a[1]
y = a[2]
different_k = []
not_have_k = False #与原点的连线垂直于x轴,没有斜率的
for i in range(n):
b = [int(i) for i in input().split(" ")]
x1 = b[0] - x#移动坐标轴,把意大利炮放在原点
y1 = b[1] - y
if x1 == 0:
not_have_k = True
else:
if different_k.count(y1/x1) == 0:
different_k.append(y1/x1)
if not_have_k:
print(len(different_k)+1)
else:
print(len(different_k))
|
[
"1069583789@qq.com"
] |
1069583789@qq.com
|
ce98326eec9e867cfa84bc1b3f0f2d96f6af855a
|
8cadad50417345f84ce275d455f4d9d851adcfcb
|
/accounts/views.py
|
77c71b57912235123ee133a106e9127927d80431
|
[] |
no_license
|
amirbigg/django-blog
|
b67427dc9b087937c91e62bead242690658f8584
|
23d6d47dd3e309fa736cd891654a09da18d08427
|
refs/heads/master
| 2023-04-28T17:35:00.298592
| 2022-02-11T18:15:47
| 2022-02-11T18:15:47
| 226,943,807
| 26
| 6
| null | 2023-04-21T21:28:17
| 2019-12-09T18:51:29
|
Python
|
UTF-8
|
Python
| false
| false
| 1,452
|
py
|
from django.shortcuts import render, redirect
from .forms import UserLoginForm, UserRegistrationForm
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.contrib.auth.models import User
def user_login(request):
if request.method == 'POST':
form = UserLoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
messages.success(request, 'you logged in successfully', 'success')
return redirect('blog:all_articles')
else:
messages.error(request, 'wrong username or password', 'warning')
else:
form = UserLoginForm()
return render(request, 'accounts/login.html', {'form':form})
def user_register(request):
if request.method == 'POST':
form = UserRegistrationForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
User.objects.create_user(cd['username'], cd['email'], cd['password1'])
messages.success(request, 'you registered successfully, now log in', 'success')
return redirect('accounts:user_login')
else:
form = UserRegistrationForm()
return render(request, 'accounts/register.html', {'form':form})
def user_logout(request):
logout(request)
messages.success(request, 'you logged out successfully', 'success')
return redirect('blog:all_articles')
|
[
"amirbig44@gmail.com"
] |
amirbig44@gmail.com
|
6c47467fdc2e3ac450e09175b287eb9a071c66b8
|
4cc4d9d488939dde56fda368faf58d8564047673
|
/test/vts/testcases/framework_test/SampleSl4aTest.py
|
0b1133ebb0c19c335cf4b803840db478b2dc7418
|
[] |
no_license
|
Tosotada/android-8.0.0_r4
|
24b3e4590c9c0b6c19f06127a61320061e527685
|
7b2a348b53815c068a960fe7243b9dc9ba144fa6
|
refs/heads/master
| 2020-04-01T11:39:03.926512
| 2017-08-28T16:26:25
| 2017-08-28T16:26:25
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,302
|
py
|
#!/usr/bin/env python
#
# Copyright (C) 2016 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import logging
from vts.runners.host import base_test
from vts.runners.host import test_runner
from vts.utils.python.controllers import android_device
class SampleSl4aTest(base_test.BaseTestClass):
"""An example showing making SL4A calls in VTS."""
def setUpClass(self):
self.dut = self.registerController(android_device)[0]
def testToast(self):
"""A sample test controlling Android device with sl4a. This will make a
toast message on the device screen."""
logging.info("A toast message should show up on the devce's screen.")
self.dut.sl4a.makeToast("Hello World!")
if __name__ == "__main__":
test_runner.main()
|
[
"xdtianyu@gmail.com"
] |
xdtianyu@gmail.com
|
c0df06b16069e147b3de2e0d270c87285e2aa0b6
|
41c5267c5b1bf6cf726dfce7f203828ab58280cc
|
/addons/speakers/search_indexes.py
|
ea8cdc9aa44bee11e7a61be39a41760d719cc403
|
[] |
no_license
|
fbates/tendenci-site
|
7484616ec13a07f05be3a7a9663bca6d6800360b
|
8eb0bcd8e3269e92b505e8db4f81b35442fb4ac4
|
refs/heads/master
| 2021-01-11T10:55:56.171005
| 2012-11-15T18:15:21
| 2012-11-15T18:15:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 559
|
py
|
from haystack import indexes
from haystack import site
from tendenci.core.perms.indexes import TendenciBaseSearchIndex
from addons.speakers.models import Speaker
class SpeakerIndex(TendenciBaseSearchIndex):
name = indexes.CharField(model_attr='name')
company = indexes.CharField(model_attr='company', null=True)
position = indexes.CharField(model_attr='position', null=True)
track = indexes.CharField(model_attr='track', null=True)
ordering = indexes.IntegerField(model_attr='ordering', null=True)
site.register(Speaker, SpeakerIndex)
|
[
"eloyz.email@gmail.com"
] |
eloyz.email@gmail.com
|
587d324910fd7515c01c9051e7f77212a24b4987
|
5d302c38acd02d5af4ad7c8cfe244200f8e8f877
|
/Array/1002. Find Common Characters(Easy).py
|
a9cdff36a75c8b1badf3cf74b7bdd55fe3ad92a2
|
[] |
no_license
|
nerohuang/LeetCode
|
2d5214a2938dc06600eb1afd21686044fe5b6db0
|
f273c655f37da643a605cc5bebcda6660e702445
|
refs/heads/master
| 2023-06-05T00:08:41.312534
| 2021-06-21T01:03:40
| 2021-06-21T01:03:40
| 230,164,258
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 861
|
py
|
class Solution:
def commonChars(self, A: List[str]) -> List[str]:
result = [];
chars = []
count = 0;
for char in A[0]:
chars.append(char);
for char in chars:
for i in range(1, len(A)):
if char in A[i]:
A[i] = A[i].replace(char, '', 1);
count += 1;
if count == len(A) - 1:
result.append(char);
count = 0;
return result;
##class Solution:
## def commonChars(self, A: List[str]) -> List[str]:
## answer = []
## sorted(A)
## for i,val in enumerate(A[0]):
## if all(val in string for string in A[1:]):
## for i in range(1,len(A)):
## A[i] = A[i].replace(val,'',1)
## answer.append(val)
## return answer
|
[
"huangxingyu00@gmail.com"
] |
huangxingyu00@gmail.com
|
749714a844151fe4c0679e06c57f2a0d1054a231
|
f6786f5f51c0a71a09213e2f729766d1a04dffa2
|
/두근두근_파이썬/12_PIL_Library/Challenge/353_mini_photo_shap.py
|
055593ec369b0c2a9d65d294dc06ecc7d76899b9
|
[] |
no_license
|
SuperstarterJaeeun/Learn-Programming-Book
|
4f075fdec386a0449da8d0d08bb8f1b6d6b2f304
|
f768acfffcb20b9fc97946ca491f6ffb20671896
|
refs/heads/master
| 2023-07-24T07:13:24.374240
| 2021-09-06T14:56:02
| 2021-09-06T14:56:02
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,554
|
py
|
import tkinter as tk
from PIL import Image, ImageTk, ImageFilter
from tkinter import filedialog as fd
im = None
tk_img = None
def open() :
global im, tk_img
filename = fd.askopenfilename()
im = Image.open(filename)
tk_img = ImageTk.PhotoImage(im)
canvas.create_image(250, 250, image = tk_img)
window.update()
def quit() :
window.quit()
def image_rotate() :
global im, tk_img
out = im.rotate(45)
tk_img = ImageTk.PhotoImage(out)
canvas.create_image(250, 250, image = tk_img)
window.update()
def image_blur() :
global im, tk_img
out = im.filter(ImageFilter.BLUR)
tk_img = ImageTk.PhotoImage(out)
canvas.create_image(250, 250, image = tk_img)
window.update()
def image_gray() :
global im, tk_img
out = im.convert('L')
tk_img = ImageTk.PhotoImage(out)
canvas.create_image(250, 250, image = tk_img)
window.update()
window = tk.Tk()
canvas = tk.Canvas(window, width = 500, height = 500)
canvas.pack()
menubar = tk.Menu(window)
filemenu = tk.Menu(menubar)
ipmenu = tk.Menu(menubar)
filemenu.add_command(label = "열기", command = open)
filemenu.add_command(label = "종료", command = quit)
ipmenu.add_command(label = "영상회전", command = image_rotate)
ipmenu.add_command(label = "영상흐리게", command = image_blur)
ipmenu.add_command(label = "영상흑백", command = image_gray)
menubar.add_cascade(label = "파일", menu = filemenu)
menubar.add_cascade(label = "영상처리", menu = ipmenu)
window.config(menu = menubar)
window.mainloop()
|
[
"eona1301@gmail.com"
] |
eona1301@gmail.com
|
5ca87bde902dd3bf4220c279adaa44f9c33f59ee
|
5b5178d073d6b1247feab1314004bae326bfcdba
|
/examples/comm_example3.py
|
e1cf73be2bba9c04fb90e163c6f7f8f0a9e10d25
|
[] |
no_license
|
abdcelikkanat/Evaluation
|
4df6512e43af17e4ec9decd54e47efb88ac11952
|
8aec5948f40b1d4601d6408a8bee5b41a77c1e35
|
refs/heads/master
| 2021-06-16T05:08:37.057794
| 2019-04-15T09:20:36
| 2019-04-15T09:20:36
| 135,060,670
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,118
|
py
|
import sys
sys.path.append("../../deepwalk/deepwalk")
import graph as dw
import networkx as nx
from gensim.models.word2vec import Word2Vec
from graphbase import randomgraph
from sklearn.cluster import KMeans
from community_detection.community_detection import *
N = 1000
kmeans_num_of_communities = 3
if kmeans_num_of_communities == 2:
sbm_params = {}
sbm_params['sbm_N'] = N # the number of nodes
sbm_params['sbm_P'] = [[0.7, 0.5], [0.4, 0.6]] # edge probability matrix between nodes belonging different communities
sbm_params['sbm_block_sizes'] = [300, 700]
elif kmeans_num_of_communities == 3:
sbm_params = {}
sbm_params['sbm_N'] = N # the number of nodes
sbm_params['sbm_P'] = [[0.7, 0.3, 0.4],
[0.3, 0.6, 0.2],
[0.4, 0.2, 0.9]] # edge probability matrix between nodes belonging different communities
sbm_params['sbm_block_sizes'] = [300, 500, 200]
def get_embeddings(embedding_file):
id2node = []
x = []
with open(embedding_file, 'r') as f:
f.readline()
for line in f.readlines():
tokens = line.strip().split()
id2node.append(tokens[0])
x.append([float(value) for value in tokens[1:]])
return id2node, x
g = nx.read_gml("./outputs/synthetic_n1000_c3.gml")
embedding_file = "./outputs/synthetic_n1000_c3_n80_l10_w10_k50_deepwalk_final_max.embedding"
#embedding_file = "./outputs/synthetic_n1000_c3_n80_l10_w10_k50_deepwalk_node.embedding"
id2node, x = get_embeddings(embedding_file)
kmeans = KMeans(n_clusters=kmeans_num_of_communities, random_state=0)
kmeans.fit(x)
labels = kmeans.labels_.tolist()
communities_true = nx.get_node_attributes(g, name='community')
communities_pred = {id2node[i]: [labels[i]] for i in range(len(x))}
#print(communities_true)
#print(communities_pred)
comdetect = CommunityDetection()
comdetect.set_graph(nxg=g)
number_of_communities = comdetect.detect_number_of_communities()
comdetect.set_number_of_communities(number_of_communities)
score = comdetect.nmi_score(communities_pred)
print("Score: {}".format(score))
|
[
"abdcelikkanat@gmail.com"
] |
abdcelikkanat@gmail.com
|
c1304d7e44ef08ace8e1237716eab05f1f68aca8
|
e0980f704a573894350e285f66f4cf390837238e
|
/.history/menus/models_20201030152904.py
|
6448852a1a6a190459f0a1fdf0323ae50934112d
|
[] |
no_license
|
rucpata/WagtailWebsite
|
28008474ec779d12ef43bceb61827168274a8b61
|
5aa44f51592f49c9a708fc5515ad877c6a29dfd9
|
refs/heads/main
| 2023-02-09T15:30:02.133415
| 2021-01-05T14:55:45
| 2021-01-05T14:55:45
| 303,961,094
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,664
|
py
|
from django.db import models
from django_extensions.db.fields import AutoSlugField
from modelcluster.models import ClusterableModel
from modelcluster.fields import ParentalKey
from wagtail.core.models import Orderable
from wagtail.admin.edit_handlers import FieldPanel, PageChooserPanel, InlinePanel
class MenuItem(Orderable):
link_title = models.CharField(blank=True, max_length=50)
link_url = models.CharField(max_length=500, blank=True)
link_page = models.ForeignKey(
'wagtailcore.Page',
null=True,
blank=True,
related_name='+',
on_delete=models.CASCADE,
)
open_in_new_tab = models.BooleanField(
default=False,
blank=True,
)
panels = [
FieldPanel('link_title'),
FieldPanel('link_url'),
PageChooserPanel('link_page'),
FieldPanel('open_in_new_tab',),
]
page = ParentalKey('Menu', related_name='menu_items')
@property
def link(self):
if self.link_page:
return self.link_page
elif self.link_url:
return self.link_url
return '#'
@property
def title(self):
if self.link_page and not self.link_title:
return self.link_page.title
elif self.link_title:
return self.link_title
class Menu(ClusterableModel):
title = models.CharField(max_length=100)
slug = AutoSlugField(
populate_from='title',
editable=True,
)
panels = [
FieldPanel('title'),
FieldPanel('slug'),
InlinePanel('menu_items', label='Menu Item'),
]
def __str__(self):
return self.title
|
[
"rucinska.patrycja@gmail.com"
] |
rucinska.patrycja@gmail.com
|
5f0f06a88ed13ff447815bfff00bb6f12829139f
|
e3b5f5a30c9ff552d0d67308410e595f7ba50e45
|
/hierarc/Likelihood/LensLikelihood/td_mag_likelihood.py
|
13c0388b57e84f80cf2f6f19eb9c719eb6f51c86
|
[
"BSD-3-Clause"
] |
permissive
|
LBJ-Wade/hierarc_SGL
|
2332c424d6868ce099c736eaf5fea58a9282cd0c
|
1dc2be90f44f99e82ab7014f2027fbb077b14f98
|
refs/heads/main
| 2023-08-12T02:23:14.328741
| 2021-08-16T21:06:01
| 2021-08-16T21:06:01
| 411,586,535
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,553
|
py
|
import numpy as np
from lenstronomy.Util import constants as const
from lenstronomy.Util.data_util import magnitude2cps
class TDMagLikelihood(object):
"""
likelihood of time delays and magnification likelihood
This likelihood uses linear flux units and linear lensing magnifications.
"""
def __init__(self, time_delay_measured, cov_td_measured, amp_measured, cov_amp_measured,
fermat_diff, magnification_model, cov_model, magnitude_zero_point=20):
"""
:param time_delay_measured: array, relative time delays (relative to the first image) [days]
:param cov_td_measured: 2d array, error covariance matrix of time delay measurement [days^2]
:param amp_measured: array, amplitudes of measured fluxes of image positions
:param cov_amp_measured: 2d array, error covariance matrix of the measured amplitudes
:param fermat_diff: mean Fermat potential differences (relative to the first image) in arcsec^2
:param magnification_model: mean magnification of the model prediction
:param cov_model: 2d array (length relative time delays + image amplitudes); model fermat potential differences
and lensing magnification covariances
:param magnitude_zero_point: magnitude zero point for which the image amplitudes and covariance matrix are
defined
"""
self._data_vector = np.append(time_delay_measured, amp_measured)
self._cov_td_measured = np.array(cov_td_measured)
self._cov_amp_measured = np.array(cov_amp_measured)
# check sizes of covariances matches
n_tot = len(self._data_vector)
self._n_td = len(time_delay_measured)
self._n_amp = len(amp_measured)
assert self._n_td == len(cov_td_measured)
assert self._n_amp == len(cov_amp_measured)
assert n_tot == len(cov_model)
# merge data covariance matrices from time delay and image amplitudes
self._cov_data = np.zeros((n_tot, n_tot))
self._cov_data[:self._n_td, :self._n_td] = self._cov_td_measured
self._cov_data[self._n_td:, self._n_td:] = self._cov_amp_measured
#self._fermat_diff = fermat_diff # in units arcsec^2
self._fermat_unit_conversion = const.Mpc / const.c / const.day_s * const.arcsec ** 2
#self._mag_model = mag_model
self._model_tot = np.append(fermat_diff, magnification_model)
self._cov_model = cov_model
self.num_data = n_tot
self._magnitude_zero_point = magnitude_zero_point
def log_likelihood(self, ddt, mu_intrinsic):
"""
:param ddt: time-delay distance (physical Mpc)
:param mu_intrinsic: intrinsic brightness of the source (already incorporating the inverse MST transform)
:return: log likelihood of the measured magnified images given the source brightness
"""
model_vector, cov_tot = self._model_cov(ddt, mu_intrinsic)
# invert matrix
try:
cov_tot_inv = np.linalg.inv(cov_tot)
except:
return -np.inf
# difference to data vector
delta = self._data_vector - model_vector
# evaluate likelihood
lnlikelihood = -delta.dot(cov_tot_inv.dot(delta)) / 2.
sign_det, lndet = np.linalg.slogdet(cov_tot)
lnlikelihood -= 1 / 2. * (self.num_data * np.log(2 * np.pi) + lndet)
return lnlikelihood
def _model_cov(self, ddt, mu_intrinsic):
"""
combined covariance matrix of the data and model when marginialized over the Gaussian model uncertainties
in the Fermat potential and magnification.
:param ddt: time-delay distance (physical Mpc)
:param mu_intrinsic: intrinsic brightness of the source (already incorporating the inverse MST transform)
:return: model vector, combined covariance matrix
"""
# compute model predicted magnified image amplitude and time delay
amp_intrinsic = magnitude2cps(magnitude=mu_intrinsic, magnitude_zero_point=self._magnitude_zero_point)
model_scale = np.append(ddt * self._fermat_unit_conversion * np.ones(self._n_td),
amp_intrinsic * np.ones(self._n_amp))
model_vector = model_scale * self._model_tot
# scale model covariance matrix with model_scale vector (in quadrature)
cov_model = model_scale * (self._cov_model * model_scale).T
# combine data and model covariance matrix
cov_tot = self._cov_data + cov_model
return model_vector, cov_tot
|
[
"sibirrer@gmail.com"
] |
sibirrer@gmail.com
|
0be820d8c37117b65098b0e8dcdf0506cc8231b6
|
44064ed79f173ddca96174913910c1610992b7cb
|
/Second_Processing_app/temboo/Library/Twitter/DirectMessages/__init__.py
|
1d26f95881809e14b918cc47d392e77b4e48342c
|
[] |
no_license
|
dattasaurabh82/Final_thesis
|
440fb5e29ebc28dd64fe59ecd87f01494ed6d4e5
|
8edaea62f5987db026adfffb6b52b59b119f6375
|
refs/heads/master
| 2021-01-20T22:25:48.999100
| 2014-10-14T18:58:00
| 2014-10-14T18:58:00
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 161
|
py
|
from GetDirectMessages import *
from SendDirectMessage import *
from DestroyDirectMessage import *
from GetMessageByID import *
from DirectMessagesSent import *
|
[
"dattasaurabh82@gmail.com"
] |
dattasaurabh82@gmail.com
|
8c28b115446dbdfb81f139fe921de4b0f92fdd98
|
2233f520493f64c6070dd3e77722e53a7dd738e8
|
/unittest_example/test_fixture.py
|
372b4c964d16e91c4d8e53f9fd56d8ddf350e948
|
[
"Apache-2.0"
] |
permissive
|
mpjeffin/pynet-ons-oct17
|
690bb31600b8ef5131439bb25ddce35b4855ba6a
|
d0daf9c250f79bc34b3b8b06b67004f56ef834a2
|
refs/heads/master
| 2021-09-07T00:00:02.234456
| 2018-02-13T19:58:11
| 2018-02-13T19:58:11
| 125,467,721
| 1
| 0
| null | 2018-03-16T05:26:10
| 2018-03-16T05:26:10
| null |
UTF-8
|
Python
| false
| false
| 621
|
py
|
import pytest
from getpass import getpass
from netmiko import ConnectHandler
# Fixtures
@pytest.fixture(scope="module")
def netmiko_connect():
cisco1 = {
'device_type': 'cisco_ios',
'ip': '184.105.247.70',
'username': 'pyclass',
'password': getpass()
}
return ConnectHandler(**cisco1)
def test_prompt(netmiko_connect):
print(netmiko_connect.find_prompt())
assert netmiko_connect.find_prompt() == 'pynet-rtr1#'
def test_show_version(netmiko_connect):
output = netmiko_connect.send_command("show version")
assert 'Configuration register is 0x2102' in output
|
[
"ktbyers@twb-tech.com"
] |
ktbyers@twb-tech.com
|
5e57b310c8982173953ff99d06116aa3e3553169
|
de24f83a5e3768a2638ebcf13cbe717e75740168
|
/moodledata/vpl_data/5/usersdata/67/2931/submittedfiles/atm.py
|
a41e9c31c6bb1ca25bc098784953451c866f8b20
|
[] |
no_license
|
rafaelperazzo/programacao-web
|
95643423a35c44613b0f64bed05bd34780fe2436
|
170dd5440afb9ee68a973f3de13a99aa4c735d79
|
refs/heads/master
| 2021-01-12T14:06:25.773146
| 2017-12-22T16:05:45
| 2017-12-22T16:05:45
| 69,566,344
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 219
|
py
|
# -*- coding: utf-8 -*-
from __future__ import division
import math
#COMECE SEU CODIGO AQUI
a=input("Digite o valor:")
c20=a/20
c10=a%20/10
c5=(a%20%10)/5
b=int(c20)
c=int(c10)
d=int(c5)
print(b)
print(c)
print(d)
|
[
"rafael.mota@ufca.edu.br"
] |
rafael.mota@ufca.edu.br
|
a17dee7c5fb944081c8050c5f45db1235e19af04
|
ba7be04fa897785fb9255df3ece0c1ffbead6acc
|
/db_model/__models.py
|
5e401af90c7c2baa39db7a572dafabe7e1a10704
|
[] |
no_license
|
backupalisher/part4_project
|
e1f402553502d010ffe974ecce73e313f90b8174
|
09ca16e3021aeac609fe6594e5c4f6c72832d112
|
refs/heads/master
| 2022-12-10T13:22:15.899332
| 2020-09-21T16:22:02
| 2020-09-21T16:22:02
| 233,295,277
| 0
| 0
| null | 2022-12-08T10:47:45
| 2020-01-11T20:49:10
|
Python
|
UTF-8
|
Python
| false
| false
| 3,601
|
py
|
from django.db import models
# Create your models here.
class Brands(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=255)
logotype = models.CharField(max_length=255)
class Meta:
db_table = 'brands'
class Cartridge(models.Model):
id = models.IntegerField(primary_key=True)
title = models.CharField(max_length=255)
model = models.CharField(max_length=255)
code = models.CharField(max_length=255)
analogs = models.TextField()
techs = models.TextField()
brand_id = models.ForeignKey('Brands', on_delete=models.DO_NOTHING)
class Meta:
db_table = 'cartridge'
class Details(models.Model):
id = models.IntegerField(primary_key=True)
partcode_id = models.IntegerField()
model_id = models.IntegerField()
module_id = models.IntegerField()
spr_detail_id = models.IntegerField()
class Meta:
db_table = 'details'
class DetailOptions(models.Model):
id = models.IntegerField(primary_key=True)
caption_spr_id = models.IntegerField()
detail_option_spr_id = models.IntegerField()
parent_id = models.IntegerField()
icon = models.CharField(max_length=255)
value = models.IntegerField()
class Meta:
db_table = 'detail_options'
class FilterSettings(models.Model):
id = models.IntegerField(primary_key=True)
caption = models.CharField(max_length=255)
subcaption = models.CharField(max_length=255)
sub_id = models.IntegerField()
type = models.CharField(max_length=255)
values = models.TextField()
caption_en = models.CharField(max_length=255)
subcaption_en = models.CharField(max_length=255)
parent_id = models.IntegerField()
class Meta:
db_table = 'filter_settings'
class LinkDetailsOptions(models.Model):
detail_id = models.IntegerField()
detail_option_id = models.IntegerField()
spr_details_id = models.IntegerField()
class Meta:
db_table = 'link_details_options'
class LinkModelModules(models.Model):
model_id = models.IntegerField()
module_id = models.IntegerField()
class Meta:
db_table = 'link_model_modules'
class Models(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=255)
brand_id = models.IntegerField()
main_image = models.ImageField()
image = models.TextField()
class Meta:
db_table = 'models'
verbose_name_plural = "Модели"
class Partcodes(models.Model):
id = models.IntegerField(primary_key=True)
code = models.TextField()
description = models.TextField()
images = models.CharField(max_length=1500)
class Meta:
db_table = 'partcodes'
class SprDetailOptions(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=255)
icon = models.CharField(max_length=255)
class Meta:
db_table = 'spr_detail_options'
class SprDetails(models.Model):
id = models.IntegerField(primary_key=True)
name = models.TextField()
name_ru = models.TextField()
desc = models.TextField()
seo = models.TextField()
base_img = models.CharField(max_length=1500)
class Meta:
db_table = 'spr_details'
class SprModules(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=255)
name_ru = models.CharField(max_length=255)
description = models.CharField(max_length=1500)
scheme_picture = models.CharField(max_length=255)
class Meta:
db_table = 'spr_modules'
|
[
"server.ares@gmail.com"
] |
server.ares@gmail.com
|
223ba6282c9bc94c5ed8e642a43f151280243ba3
|
bab8ce0d8b29292c8d6b0f2a6218b5ed84e7f98b
|
/account_cancel_with_reversal/tests/__init__.py
|
658d50d7baed691aa4ea364101434b8fe6518ca1
|
[] |
no_license
|
ecosoft-odoo/ecosoft_v8
|
98e4116be3eceb287e2f3e9589d97155d5b8b745
|
71c56b0a102e340a5d80470243343654d8810955
|
refs/heads/master
| 2020-04-06T10:04:03.807855
| 2016-09-25T05:00:04
| 2016-09-25T05:00:04
| 51,049,848
| 2
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 132
|
py
|
# -*- coding: utf-8 -*-
from . import test_account_move_reverse
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
[
"kittiu@gmail.com"
] |
kittiu@gmail.com
|
418af46acc26ae85ca432a2ce3ae0866495c20ba
|
68b64faeb8394817e202567bce7dfc21c3ec8656
|
/com/jian/keras/sequential_module.py
|
49f8ea3b17585f06f36592a33671ab98b0ba32cc
|
[] |
no_license
|
tianjiansmile/ML_filght
|
04248d5a1f4108defdcc626e5de5e68692b4f1de
|
d60b422ba12945e4875d47e7730d10b1d2193d03
|
refs/heads/master
| 2020-05-26T21:59:59.773474
| 2020-05-07T04:59:34
| 2020-05-07T04:59:34
| 188,387,929
| 1
| 3
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,878
|
py
|
from keras.layers import Input
from keras.models import Model
from keras.models import Sequential
from keras.layers import Dense, Activation
import keras
# 全连接网络
# This returns a tensor
inputs = Input(shape=(784,))
# a layer instance is callable on a tensor, and returns a tensor
x = Dense(64, activation='relu')(inputs)
x = Dense(64, activation='relu')(x)
predictions = Dense(10, activation='softmax')(x)
# This creates a model that includes
# the Input layer and three Dense layers
model = Model(inputs=inputs, outputs=predictions)
# 编译
model.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
# 训练
model.fit(data, labels) # starts training
# 全连接网络2
# 指定输入数据的shape
model = Sequential()
model.add(Dense(32, input_dim=784))
model = Sequential()
model.add(Dense(32, input_shape=(784,)))
model.add(Activation('relu'))
# 编译
# For a multi-class classification problem
model.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
# 训练
# 二分类
model = Sequential()
model.add(Dense(32, activation='relu', input_dim=100))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='rmsprop',
loss='binary_crossentropy',
metrics=['accuracy'])
# Generate dummy data
import numpy as np
data = np.random.random((1000, 100))
labels = np.random.randint(2, size=(1000, 1))
# Train the model, iterating on the data in batches of 32 samples
model.fit(data, labels, epochs=10, batch_size=32)
# 多分类 (categorical classification):
model = Sequential()
model.add(Dense(32, activation='relu', input_dim=100))
model.add(Dense(10, activation='softmax'))
model.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
# Generate dummy data
import numpy as np
data = np.random.random((1000, 100))
labels = np.random.randint(10, size=(1000, 1))
# Convert labels to categorical one-hot encoding
one_hot_labels = keras.utils.to_categorical(labels, num_classes=10)
# Train the model, iterating on the data in batches of 32 samples
model.fit(data, one_hot_labels, epochs=10, batch_size=32)
# 基于多层感知器的softmax多分类:
# Generate dummy data
from keras.layers import Dropout
from keras.optimizers import SGD
x_train = np.random.random((1000, 20))
y_train = keras.utils.to_categorical(np.random.randint(10, size=(1000, 1)), num_classes=10)
x_test = np.random.random((100, 20))
y_test = keras.utils.to_categorical(np.random.randint(10, size=(100, 1)), num_classes=10)
model = Sequential()
# Dense(64) is a fully-connected layer with 64 hidden units.
# in the first layer, you must specify the expected input data shape:
# here, 20-dimensional vectors.
model.add(Dense(64, activation='relu', input_dim=20))
model.add(Dropout(0.5))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy',
optimizer=sgd,
metrics=['accuracy'])
model.fit(x_train, y_train,
epochs=20,
batch_size=128)
score = model.evaluate(x_test, y_test, batch_size=128)
# 卷积神经网络
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.optimizers import SGD
# Generate dummy data
x_train = np.random.random((100, 100, 100, 3))
y_train = keras.utils.to_categorical(np.random.randint(10, size=(100, 1)), num_classes=10)
x_test = np.random.random((20, 100, 100, 3))
y_test = keras.utils.to_categorical(np.random.randint(10, size=(20, 1)), num_classes=10)
model = Sequential()
# input: 100x100 images with 3 channels -> (100, 100, 3) tensors.
# 二维卷积层,即对图像的空域卷积。该层对二维输入进行滑动窗卷积,当使用该层作为第一层时,
# 应提供input_shape参数。例如input_shape = (100,100,3)代表100*100的彩色RGB图像
# 32个 convolution filters 每一个 size 3x3 each.
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(100, 100, 3)))
model.add(Conv2D(32, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=sgd)
model.fit(x_train, y_train, batch_size=32, epochs=10)
score = model.evaluate(x_test, y_test, batch_size=32)
|
[
"1635374633@qq.com"
] |
1635374633@qq.com
|
b321d4867fffc42d14b955f41cfad9b8315c7d46
|
9206651d6b1acb483040dff19929851ce261bc73
|
/src/lecture4/notes/classes3.py
|
8403a8d3951fba3134667204a5528af74aff4485
|
[] |
no_license
|
Farooq-azam-khan/web-programming-with-python-and-javascript
|
eee8556b37b8f8bb4f420ce9d4949441fbf456dd
|
0875982ecbbb2bfd37e7b41a09a43623ee6d5a96
|
refs/heads/master
| 2022-12-10T15:31:39.703121
| 2018-07-18T06:51:02
| 2018-07-18T06:51:02
| 138,975,972
| 0
| 0
| null | 2022-12-08T02:12:59
| 2018-06-28T06:29:26
|
HTML
|
UTF-8
|
Python
| false
| false
| 627
|
py
|
class Flight:
def __init__(self, origin, destination, duration):
self.origin = origin
self.destination = destination
self.duration = duration
def print_info(self):
print(f"origin: {self.origin}")
print(f"destination: {self.destination}")
print(f"duration: {self.duration}")
def delay(self, amount):
self.duration += amount
def main():
f1 = Flight("New York", "Paris", 500)
f2 = Flight("Toronto", "Paris", 400)
f1.print_info()
f1.delay(10)
f1.print_info()
if __name__ == '__main__':
main()
|
[
"farooq1.khan@ryerson.ca"
] |
farooq1.khan@ryerson.ca
|
df1c11b2140c9abaa45d0d6347c2d2721cc4c3ed
|
8a73cde463081afd76427d5af1e6837bfa51cc47
|
/harvester/edurep/tests/harvest_metadata_command.py
|
7130625099872e671ff9870ad67d353dce224021
|
[
"MIT"
] |
permissive
|
surfedushare/search-portal
|
8af4103ec6464e255c5462c672b30f32cd70b4e1
|
63e30ad0399c193fcb686804062cedf3930a093c
|
refs/heads/acceptance
| 2023-06-25T13:19:41.051801
| 2023-06-06T13:37:01
| 2023-06-06T13:37:01
| 254,373,874
| 2
| 1
|
MIT
| 2023-06-06T12:04:44
| 2020-04-09T13:07:12
|
Python
|
UTF-8
|
Python
| false
| false
| 2,105
|
py
|
from core.tests.commands.harvest_metadata import TestMetadataHarvest, TestMetadataHarvestWithHistory
from core.constants import Repositories
from core.models import HarvestSource, Collection, Extension
from edurep.tests.factories import EdurepOAIPMHFactory
class TestMetadataHarvestEdurep(TestMetadataHarvest):
spec_set = "surfsharekit"
repository = Repositories.EDUREP
@classmethod
def setUpClass(cls):
super().setUpClass()
EdurepOAIPMHFactory.create_common_edurep_responses()
sharekit = HarvestSource.objects.get(id=1)
sharekit.repository = cls.repository
sharekit.spec = cls.spec_set
sharekit.save()
other = HarvestSource.objects.get(id=2)
other.repository = cls.repository
other.save()
extension = Extension.objects.get(id="5af0e26f-c4d2-4ddd-94ab-7dd0bd531751")
extension.id = extension.reference = "surfsharekit:oai:surfsharekit.nl:5af0e26f-c4d2-4ddd-94ab-7dd0bd531751"
extension.save()
class TestMetadataHarvestWithHistoryEdurep(TestMetadataHarvestWithHistory):
spec_set = "surfsharekit"
repository = Repositories.EDUREP
@classmethod
def setUpClass(cls):
super().setUpClass()
EdurepOAIPMHFactory.create_common_edurep_responses(include_delta=True)
sharekit = HarvestSource.objects.get(id=1)
sharekit.repository = cls.repository
sharekit.spec = cls.spec_set
sharekit.save()
other = HarvestSource.objects.get(id=2)
other.repository = cls.repository
other.save()
collection = Collection.objects.get(id=171)
collection.name = cls.spec_set
collection.save()
collection.documents \
.filter(properties__title="Using a Vortex | Wageningen UR") \
.update(reference="surfsharekit:oai:surfsharekit.nl:5be6dfeb-b9ad-41a8-b4f5-94b9438e4257")
collection.documents \
.filter(reference="5af0e26f-c4d2-4ddd-94ab-7dd0bd531751") \
.update(reference="surfsharekit:oai:surfsharekit.nl:5af0e26f-c4d2-4ddd-94ab-7dd0bd531751")
|
[
"email@fakoberkers.nl"
] |
email@fakoberkers.nl
|
ff86cf6de6529af0927862b17044cc444dd5d4b6
|
a7288d7cce714ce3ddf3de464f959a2cb6c62e80
|
/Flask/Validation/server.py
|
53b50278ff6439f50a7c5be10f3f8892f29e1ddb
|
[] |
no_license
|
jhflorey/Python
|
94d898c9cfa05a941e0ac0c3506587ad494b76ab
|
4d005000bb95ee4414a6aebef4cebdcbc13e4d99
|
refs/heads/master
| 2020-03-20T10:44:00.560147
| 2018-06-14T16:48:49
| 2018-06-14T16:48:49
| 137,382,015
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 460
|
py
|
from flask import Flask, render_template, redirect, request, session, flash
app = Flask(__name__)
app.secret_key = 'JessicaSecret'
@app.route('/')
def index():
return render_template('index.html')
@app.route('/process', methods=['POST'])
def process():
if len(request.form['name']) < 1:
flash("Name can't be empty!")
else:
print("Success! Your name is {}".format(request.form['name']))
return redirect('/')
app.run(debug=True)
|
[
"jhflorey@gmail.com"
] |
jhflorey@gmail.com
|
1ae7147831e43416858f5a4d9cb8bb2156ed809b
|
1ecde4178548f331f15717f245e3f657b58b9993
|
/cyh_crawler/scrapySchool_England/scrapySchool_England/scrapySchool_England/main.py
|
6a991c45461505cc2e4750caeff9610eac4cade2
|
[] |
no_license
|
gasbarroni8/python_spider
|
296dcb7c3fd9dd028423fe5ec0a321d994478b15
|
7935fa462926bc8ea9bf9883bd15265dd0d3e6df
|
refs/heads/master
| 2023-03-26T05:22:59.858422
| 2019-04-15T07:17:56
| 2019-04-15T07:17:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,495
|
py
|
from scrapy import cmdline
# cmdline.execute("scrapy crawl SwanseaUniversityPrifysgolAbertawe_U".split())
# cmdline.execute("scrapy crawl SwanseaUniversityPrifysgolAbertawe_P".split())
# cmdline.execute('scray crawl gaokao'.split())
# cmdline.execute('scrapy crawl picture'.split())
# cmdline.execute('scrapy crawl UniversityOfSouthampton_P'.split())
# cmdline.execute('scrapy crawl UniversityOfStAndrews_P'.split())
# cmdline.execute('scrapy crawl UniversityOfGlasgow_P'.split())
cmdline.execute('scrapy crawl UniversityOfTheArtsLondon_P'.split())
# cmdline.execute('scrapy crawl UniversityOfOxford_P'.split())
# cmdline.execute('scrapy crawl DeMontfortUniversity_P'.split())
# cmdline.execute('scrapy crawl BrunelUniversityLondon_P'.split())
# cmdline.execute('scrapy crawl HarperAdamsUniveristy_P'.split())
# cmdline.execute('scrapy crawl UniversityOfStirling_P'.split())
# cmdline.execute('scrapy crawl CoventryUniversity_P'.split())
# cmdline.execute('scrapy crawl CityUniversityOfLondon_P'.split())
# cmdline.execute('scrapy crawl UniversityOfLiverpool_P'.split())
# cmdline.execute('scrapy crawl UniversityCollegeLondon_P'.split())
# cmdline.execute('scrapy crawl UniversityOfYork_P'.split())
# cmdline.execute('scrapy crawl DurhamUniversity_P'.split())
# cmdline.execute('scrapy crawl LondonSouthBankUniversity_P'.split())
# cmdline.execute('scrapy crawl ManchesterMetropolitanUniversity_P'.split())
# cmdline.execute('scrapy crawl MiddlesexUniversity_P'.split())
# cmdline.execute('scrapy crawl NewmanUniversity_P'.split())
# cmdline.execute('scrapy crawl NorthumbriaUniversity_P'.split())
# cmdline.execute('scrapy crawl NorwichUniversityoftheArts_P'.split())
# cmdline.execute('scrapy crawl OxfordBrookesUniversity_P'.split())
# cmdline.execute('scrapy crawl QueenMargaretUniversity_P'.split())
# cmdline.execute('scrapy crawl LiverpoolJohnMooresUniversity_P'.split())
# cmdline.execute('scrapy crawl LeedsBeckettUniversity_P'.split())
# cmdline.execute('scrapy crawl LeedsTrinityUniversity_P'.split())
# cmdline.execute('scrapy crawl StMaryUniversityTwickenham_P'.split())
# cmdline.execute('scrapy crawl StaffordshireUniversity_P'.split())
# cmdline.execute('scrapy crawl UlsterUniversity_P'.split())
# cmdline.execute('scrapy crawl UniversityForTheCreativeArts_P'.split())
# cmdline.execute('scrapy crawl AngliaRuskinUniversity_P'.split())
# cmdline.execute('scrapy crawl UniversityofBedfordshire_P'.split())
# cmdline.execute('scrapy crawl UniversityOfLeicester_P'.split())
|
[
"18234405986@163.com"
] |
18234405986@163.com
|
053fc23b9d1e676b148f8576250daae9dab76e85
|
dfdb672bbe3b45175806928d7688a5924fc45fee
|
/Learn Python the Hard Way Exercises/ex6.py
|
bdc6a5f9f598451b3b7f4b3ccb790c295a9908c5
|
[] |
no_license
|
mathans1695/Python-Practice
|
bd567b5210a4d9bcd830607627293d64b4baa909
|
3a8fabf14bc65b8fe973488503f12fac224a44ed
|
refs/heads/master
| 2023-01-01T13:49:05.789809
| 2020-10-26T02:37:05
| 2020-10-26T02:37:05
| 306,300,672
| 2
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 394
|
py
|
x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)
print x
print y
print "I said: %r." % x
print "I also said: '%s'." % y
hilarious = 0
joke_evaluation = "Isn't that joke so funny?! %s"
print joke_evaluation % hilarious
w = "This is the left side of..."
e = "a string with a right side."
print w + e
|
[
"mathans1695@gmail.com"
] |
mathans1695@gmail.com
|
62f623a3627d7ac22b6f30c255b956e2e37f1f30
|
1515be3015ad988278d5a095416c0a0066a02757
|
/src/users/models/componentsschemasmicrosoft_graph_windowsdevicemalwarestateallof1.py
|
31ab5b0ad3a8ead943f9d1569c1e9baa891b4228
|
[
"MIT"
] |
permissive
|
peombwa/Sample-Graph-Python-Client
|
2ad494cc5b5fe026edd6ed7fee8cac2dd96aaa60
|
3396f531fbe6bb40a740767c4e31aee95a3b932e
|
refs/heads/master
| 2020-12-29T09:50:38.941350
| 2020-02-05T22:45:28
| 2020-02-05T22:45:28
| 238,561,578
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,670
|
py
|
# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class ComponentsschemasmicrosoftGraphWindowsdevicemalwarestateallof1(Model):
"""windowsDeviceMalwareState.
Malware detection entity.
:param display_name: Malware name
:type display_name: str
:param additional_information_url: Information URL to learn more about the
malware
:type additional_information_url: str
:param severity: Possible values include: 'unknown', 'low', 'moderate',
'high', 'severe'
:type severity: str or ~users.models.enum
:param catetgory: Possible values include: 'invalid', 'adware', 'spyware',
'passwordStealer', 'trojanDownloader', 'worm', 'backdoor',
'remoteAccessTrojan', 'trojan', 'emailFlooder', 'keylogger', 'dialer',
'monitoringSoftware', 'browserModifier', 'cookie', 'browserPlugin',
'aolExploit', 'nuker', 'securityDisabler', 'jokeProgram',
'hostileActiveXControl', 'softwareBundler', 'stealthNotifier',
'settingsModifier', 'toolBar', 'remoteControlSoftware', 'trojanFtp',
'potentialUnwantedSoftware', 'icqExploit', 'trojanTelnet', 'exploit',
'filesharingProgram', 'malwareCreationTool', 'remote_Control_Software',
'tool', 'trojanDenialOfService', 'trojanDropper', 'trojanMassMailer',
'trojanMonitoringSoftware', 'trojanProxyServer', 'virus', 'known',
'unknown', 'spp', 'behavior', 'vulnerability', 'policy',
'enterpriseUnwantedSoftware', 'ransom', 'hipsRule'
:type catetgory: str or ~users.models.enum
:param execution_state: Possible values include: 'unknown', 'blocked',
'allowed', 'running', 'notRunning'
:type execution_state: str or ~users.models.enum
:param state: Possible values include: 'unknown', 'detected', 'cleaned',
'quarantined', 'removed', 'allowed', 'blocked', 'cleanFailed',
'quarantineFailed', 'removeFailed', 'allowFailed', 'abandoned',
'blockFailed'
:type state: str or ~users.models.enum
:param threat_state: Possible values include: 'active', 'actionFailed',
'manualStepsRequired', 'fullScanRequired', 'rebootRequired',
'remediatedWithNonCriticalFailures', 'quarantined', 'removed', 'cleaned',
'allowed', 'noStatusCleared'
:type threat_state: str or ~users.models.enum
:param initial_detection_date_time: Initial detection datetime of the
malware
:type initial_detection_date_time: datetime
:param last_state_change_date_time: The last time this particular threat
was changed
:type last_state_change_date_time: datetime
:param detection_count: Number of times the malware is detected
:type detection_count: int
:param category: Possible values include: 'invalid', 'adware', 'spyware',
'passwordStealer', 'trojanDownloader', 'worm', 'backdoor',
'remoteAccessTrojan', 'trojan', 'emailFlooder', 'keylogger', 'dialer',
'monitoringSoftware', 'browserModifier', 'cookie', 'browserPlugin',
'aolExploit', 'nuker', 'securityDisabler', 'jokeProgram',
'hostileActiveXControl', 'softwareBundler', 'stealthNotifier',
'settingsModifier', 'toolBar', 'remoteControlSoftware', 'trojanFtp',
'potentialUnwantedSoftware', 'icqExploit', 'trojanTelnet', 'exploit',
'filesharingProgram', 'malwareCreationTool', 'remote_Control_Software',
'tool', 'trojanDenialOfService', 'trojanDropper', 'trojanMassMailer',
'trojanMonitoringSoftware', 'trojanProxyServer', 'virus', 'known',
'unknown', 'spp', 'behavior', 'vulnerability', 'policy',
'enterpriseUnwantedSoftware', 'ransom', 'hipsRule'
:type category: str or ~users.models.enum
"""
_validation = {
'detection_count': {'maximum': 2147483647, 'minimum': -2147483648},
}
_attribute_map = {
'display_name': {'key': 'displayName', 'type': 'str'},
'additional_information_url': {'key': 'additionalInformationUrl', 'type': 'str'},
'severity': {'key': 'severity', 'type': 'str'},
'catetgory': {'key': 'catetgory', 'type': 'str'},
'execution_state': {'key': 'executionState', 'type': 'str'},
'state': {'key': 'state', 'type': 'str'},
'threat_state': {'key': 'threatState', 'type': 'str'},
'initial_detection_date_time': {'key': 'initialDetectionDateTime', 'type': 'iso-8601'},
'last_state_change_date_time': {'key': 'lastStateChangeDateTime', 'type': 'iso-8601'},
'detection_count': {'key': 'detectionCount', 'type': 'int'},
'category': {'key': 'category', 'type': 'str'},
}
def __init__(self, display_name=None, additional_information_url=None, severity=None, catetgory=None, execution_state=None, state=None, threat_state=None, initial_detection_date_time=None, last_state_change_date_time=None, detection_count=None, category=None):
super(ComponentsschemasmicrosoftGraphWindowsdevicemalwarestateallof1, self).__init__()
self.display_name = display_name
self.additional_information_url = additional_information_url
self.severity = severity
self.catetgory = catetgory
self.execution_state = execution_state
self.state = state
self.threat_state = threat_state
self.initial_detection_date_time = initial_detection_date_time
self.last_state_change_date_time = last_state_change_date_time
self.detection_count = detection_count
self.category = category
|
[
"peombwa@microsoft.com"
] |
peombwa@microsoft.com
|
7cd31f6504ec6f2a009af57d51a4d7882dc91bc5
|
27398b2a8ed409354d6a36c5e1d2089dad45b4ac
|
/tests/common/models/test_token.py
|
8bdba91a77d0c587046d5ccedb7bbbd587801a7c
|
[
"Apache-2.0"
] |
permissive
|
amar266/ceph-lcm
|
e0d6c1f825f5ac07d2926bfbe6871e760b904340
|
6b23ffd5b581d2a1743c0d430f135261b7459e38
|
refs/heads/master
| 2021-04-15T04:41:55.950583
| 2018-03-23T12:51:26
| 2018-03-23T12:51:26
| 126,484,605
| 0
| 0
| null | 2018-03-23T12:50:28
| 2018-03-23T12:50:27
| null |
UTF-8
|
Python
| false
| false
| 2,667
|
py
|
# -*- coding: utf-8 -*-
# Copyright (c) 2016 Mirantis 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 in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This module contains tests for decapod_common.models.token."""
import pytest
from decapod_common.models import token
def test_create_token_in_db(configure_model, pymongo_connection, freeze_time):
user_id = pytest.faux.gen_uuid()
new_token = token.TokenModel.create(user_id)
db_token = pymongo_connection.db.token.find_one({"_id": new_token._id})
assert db_token
assert new_token.user_id == db_token["user_id"]
assert new_token.expires_at == db_token["expires_at"]
assert new_token.model_id == db_token["model_id"]
assert new_token.initiator_id == db_token["initiator_id"]
assert new_token.version == db_token["version"]
assert new_token.initiator_id == db_token["initiator_id"]
assert new_token.time_created == db_token["time_created"]
assert new_token.time_deleted == db_token["time_deleted"]
current_time = int(freeze_time.return_value)
assert new_token.time_created == current_time
assert not new_token.time_deleted
assert new_token.initiator_id == new_token.user_id
assert int(new_token.expires_at.timestamp()) \
== current_time + new_token.default_ttl
def test_create_token_different(configure_model):
user_id = pytest.faux.gen_uuid()
new_token1 = token.TokenModel.create(user_id)
new_token2 = token.TokenModel.create(user_id)
assert new_token1.expires_at == new_token2.expires_at
assert new_token1.version == new_token2.version
assert new_token1._id != new_token2._id
def test_token_api_specific_fields(configure_model):
new_token = token.TokenModel.create(pytest.faux.gen_uuid())
api = new_token.make_api_structure()
assert api == {
"id": str(new_token.model_id),
"model": token.TokenModel.MODEL_NAME,
"initiator_id": new_token.initiator_id,
"time_deleted": new_token.time_deleted,
"time_updated": new_token.time_created,
"version": new_token.version,
"data": {
"expires_at": int(new_token.expires_at.timestamp()),
"user": None
}
}
|
[
"sarkhipov@mirantis.com"
] |
sarkhipov@mirantis.com
|
1d6d4abe45b478740b0a9a93148f268895c3f441
|
20a0bd0a9675f52d4cbd100ee52f0f639fb552ef
|
/transit_odp/pipelines/receivers.py
|
1a5817d416f6c9c4c2c8269a5f55a6e304ca1274
|
[] |
no_license
|
yx20och/bods
|
2f7d70057ee9f21565df106ef28dc2c4687dfdc9
|
4e147829500a85dd1822e94a375f24e304f67a98
|
refs/heads/main
| 2023-08-02T21:23:06.066134
| 2021-10-06T16:49:43
| 2021-10-06T16:49:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,992
|
py
|
import celery
from django.db import transaction
from django.dispatch import receiver
from transit_odp.data_quality.tasks import task_dqs_download, task_dqs_report_etl
from transit_odp.organisation.constants import FeedStatus
from transit_odp.organisation.models import DatasetRevision
from transit_odp.organisation.receivers import logger
from transit_odp.pipelines.models import DataQualityTask
from transit_odp.pipelines.signals import dataset_changed, dataset_etl, dqs_report_etl
from transit_odp.timetables.tasks import task_dataset_pipeline
@receiver(dataset_etl)
def dataset_etl_handler(sender, revision: DatasetRevision, **kwargs):
"""
Listens on the feed_index and dispatches a Celery job to process the feed payload
"""
logger.debug(f"index_feed_handler called for DatasetRevision {revision.id}")
if not revision.status == FeedStatus.pending.value:
revision.to_pending()
revision.save()
# Trigger task once transactions have been fully committed
transaction.on_commit(lambda: task_dataset_pipeline.delay(revision.id))
@receiver(dqs_report_etl)
def dqs_report_etl_handler(sender, task: DataQualityTask, **kwargs):
"""
Listens on the dqs_report_etl and dispatches a Celery job chain to
process the ready DQS report
"""
logger.debug(
f"dqs_report_etl_handler called for "
f"DataQualityTask(id={task.id}, task_id={task.task_id})"
)
# Chain Celery tasks: download the report and then run ETL pipeline
transaction.on_commit(
lambda: celery.chain(task_dqs_download.s(task.id), task_dqs_report_etl.s())()
)
@receiver(dataset_changed)
def dataset_changed_handler(sender, revision: DatasetRevision, **kwargs):
"""
Listens on the task_dataset_etl and dispatches a Celery job to publish the revision
"""
logger.debug(f"dataset_changed called for DatasetRevision {revision.id}")
task_dataset_pipeline.apply_async(args=(revision.id,), kwargs={"do_publish": True})
|
[
"ciaran.mccormick@itoworld.com"
] |
ciaran.mccormick@itoworld.com
|
98f5ca074dd68ca76c524fdf9067f24985046436
|
e262e64415335060868e9f7f73ab8701e3be2f7b
|
/.history/Test002/数据类型_20201205162829.py
|
4ad60fe9cb60917905bd6b19edde771ad9404d47
|
[] |
no_license
|
Allison001/developer_test
|
6e211f1e2bd4287ee26fd2b33baf1c6a8d80fc63
|
b8e04b4b248b0c10a35e93128a5323165990052c
|
refs/heads/master
| 2023-06-18T08:46:40.202383
| 2021-07-23T03:31:54
| 2021-07-23T03:31:54
| 322,807,303
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 231
|
py
|
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
# print(fruits.count("apple"))
# a = fruits.index("banana",4)
# print(a)
# fruits.reverse()
# print(fruits)
# fruits.append("daka")
# print(fruits)
a= r
|
[
"zhangyingxbba@gmail.com"
] |
zhangyingxbba@gmail.com
|
500721d9011e251f5c83a5f683e8b128ba5cca62
|
6c6cf32f72c33c78ce07771328f5368564ebde5c
|
/autox/process_data/feature_type_recognition.py
|
302050a7b24e1e9654829b4b776cb113400dc69d
|
[
"Apache-2.0"
] |
permissive
|
emg110/AutoX
|
9f3fdce5602eef7e1dc8ec99e0e60c3236da43d1
|
26eb6bea33b8e8428ee1afcd4403ccae2948724e
|
refs/heads/master
| 2023-07-27T20:43:32.818251
| 2021-09-10T11:10:12
| 2021-09-10T11:10:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,769
|
py
|
import pandas as pd
import datetime
from autox.CONST import FEATURE_TYPE
# datetime的表现形式为:2015-08-28 16:43:37.283
# timestamp的表现形式为:1440751417.283
def detect_TIMESTAMP(df, col):
try:
ts_min = int(float(df.loc[~(df[col] == '') & (df[col].notnull()), col].min()))
ts_max = int(float(df.loc[~(df[col] == '') & (df[col].notnull()), col].max()))
datetime_min = datetime.datetime.utcfromtimestamp(ts_min).strftime('%Y-%m-%d %H:%M:%S')
datetime_max = datetime.datetime.utcfromtimestamp(ts_max).strftime('%Y-%m-%d %H:%M:%S')
if datetime_min > '2000-01-01 00:00:01' and datetime_max < '2030-01-01 00:00:01' and datetime_max > datetime_min:
return True
except:
return False
def detect_DATETIME(df, col):
is_DATETIME = False
if df[col].dtypes == 'object':
is_DATETIME = True
try:
pd.to_datetime(df[col])
except:
is_DATETIME = False
return is_DATETIME
def get_data_type(df, col):
if detect_DATETIME(df, col):
return FEATURE_TYPE['datetime']
if detect_TIMESTAMP(df, col):
return FEATURE_TYPE['timestamp']
if df[col].dtypes == object or df[col].dtypes == bool or str(df[col].dtypes) == 'category':
return FEATURE_TYPE['cat']
if 'int' in str(df[col].dtype) or 'float' in str(df[col].dtype):
return FEATURE_TYPE['num']
class Feature_type_recognition():
def __init__(self):
self.df = None
self.feature_type = None
def fit(self, df):
self.df = df
self.feature_type = {}
for col in self.df.columns:
cur_type = get_data_type(self.df, col)
self.feature_type[col] = cur_type
return self.feature_type
|
[
"946691288@qq.com"
] |
946691288@qq.com
|
801b1698f76fd72430f6d4989a09735ae2002cce
|
e3c8f786d09e311d6ea1cab50edde040bf1ea988
|
/Incident-Response/Tools/grr/grr/core/setup.py
|
c626095353055c7ac3288b16e37e0f43901a514b
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
foss2cyber/Incident-Playbook
|
d1add8aec6e28a19e515754c6ce2e524d67f368e
|
a379a134c0c5af14df4ed2afa066c1626506b754
|
refs/heads/main
| 2023-06-07T09:16:27.876561
| 2021-07-07T03:48:54
| 2021-07-07T03:48:54
| 384,988,036
| 1
| 0
|
MIT
| 2021-07-11T15:45:31
| 2021-07-11T15:45:31
| null |
UTF-8
|
Python
| false
| false
| 4,697
|
py
|
#!/usr/bin/env python
"""Setup configuration for the python grr modules."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import configparser
import itertools
import os
import shutil
import subprocess
import sys
from setuptools import Extension
from setuptools import find_packages
from setuptools import setup
from setuptools.command.develop import develop
from setuptools.command.install import install
from setuptools.command.sdist import sdist
THIS_DIRECTORY = os.path.dirname(os.path.realpath(__file__))
os.chdir(THIS_DIRECTORY)
def find_data_files(source, ignore_dirs=None):
ignore_dirs = ignore_dirs or []
result = []
for directory, dirnames, files in os.walk(source):
dirnames[:] = [d for d in dirnames if d not in ignore_dirs]
files = [os.path.join(directory, x) for x in files]
result.append((directory, files))
return result
def sync_artifacts():
"""Sync the artifact repo with upstream for distribution."""
subprocess.check_call([sys.executable, "makefile.py"],
cwd="grr_response_core/artifacts")
def get_config():
"""Get INI parser with version.ini data."""
ini_path = os.path.join(THIS_DIRECTORY, "version.ini")
if not os.path.exists(ini_path):
ini_path = os.path.join(THIS_DIRECTORY, "../../version.ini")
if not os.path.exists(ini_path):
raise RuntimeError("Couldn't find version.ini")
config = configparser.ConfigParser()
config.read(ini_path)
return config
VERSION = get_config()
class Develop(develop):
def run(self):
sync_artifacts()
develop.run(self)
class Sdist(sdist):
"""Build sdist."""
# TODO: Option name must be a byte string in Python 2. Remove
# this call once support for Python 2 is dropped.
user_options = sdist.user_options + [
(str("no-sync-artifacts"), None,
"Don't sync the artifact repo. This is unnecessary for "
"clients and old client build OSes can't make the SSL connection."),
]
def initialize_options(self):
self.no_sync_artifacts = None
sdist.initialize_options(self)
def run(self):
if not self.no_sync_artifacts:
sync_artifacts()
sdist.run(self)
def make_release_tree(self, base_dir, files):
sdist.make_release_tree(self, base_dir, files)
sdist_version_ini = os.path.join(base_dir, "version.ini")
if os.path.exists(sdist_version_ini):
os.unlink(sdist_version_ini)
shutil.copy(
os.path.join(THIS_DIRECTORY, "../../version.ini"), sdist_version_ini)
data_files = list(
itertools.chain(
find_data_files("executables"),
find_data_files("install_data"),
find_data_files("scripts"),
find_data_files("grr_response_core/artifacts"),
# TODO: For some reason, this path cannot be unicode string
# or else installation fails for Python 2 (with "too many values to
# unpack" error). This call should be removed once support for Python 2
# is dropped.
[str("version.ini")],
))
setup_args = dict(
name="grr-response-core",
version=VERSION.get("Version", "packageversion"),
description="GRR Rapid Response",
license="Apache License, Version 2.0",
url="https://github.com/google/grr",
maintainer="GRR Development Team",
maintainer_email="grr-dev@googlegroups.com",
python_requires=">=3.6",
packages=find_packages(),
zip_safe=False,
include_package_data=True,
ext_modules=[
Extension(
# TODO: In Python 2, extension name and sources have to
# be of type `bytes`. These calls should be removed once support for
# Python 2 is dropped.
name=str("grr_response_core._semantic"),
sources=[str("accelerated/accelerated.c")])
],
cmdclass={
"develop": Develop,
"install": install,
"sdist": Sdist,
},
install_requires=[
# TODO: This should be 3.3.2, but AppVeyor has issues with
# that version.
"cryptography==2.9.2",
"distro==1.5.0",
"fleetspeak==0.1.9",
"grr-response-proto==%s" % VERSION.get("Version", "packagedepends"),
"ipaddr==2.2.0",
"ipython==7.15.0",
"pexpect==4.8.0",
"pip>=21.0.1",
"psutil==5.7.0",
"python-crontab==2.5.1",
"python-dateutil==2.8.1",
"pytsk3==20200117",
"pytz==2020.1",
"PyYAML==5.4.1",
"requests==2.25.1",
"yara-python==4.0.1",
],
# Data files used by GRR. Access these via the config_lib "resource" filter.
data_files=data_files)
setup(**setup_args)
|
[
"a.songer@protonmail.com"
] |
a.songer@protonmail.com
|
68f9071bc2d3e1d43621faf123d7dcbc6640e22f
|
53fab060fa262e5d5026e0807d93c75fb81e67b9
|
/backup/user_294/ch31_2020_04_13_14_21_04_841403.py
|
bcd912b0ee45d59242beaa15252d42d13f62912d
|
[] |
no_license
|
gabriellaec/desoft-analise-exercicios
|
b77c6999424c5ce7e44086a12589a0ad43d6adca
|
01940ab0897aa6005764fc220b900e4d6161d36b
|
refs/heads/main
| 2023-01-31T17:19:42.050628
| 2020-12-16T05:21:31
| 2020-12-16T05:21:31
| 306,735,108
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 256
|
py
|
def eh_primo (n):
if n == 0 or n == 1:
return False
elif n == 2:
return True
for i in range (3, n,2):
if (n%i ==0):
return False
elif (n%i == 0):
return False
else:
return True
|
[
"you@example.com"
] |
you@example.com
|
b75873de168a812387237e063712ca12fa4a326b
|
eff7b3aae8b923ca1ca82bffcfb7327030fcfb08
|
/4/4.26.py
|
d0448e0908a9773136139dfa98a9dbe1a1a13daf
|
[] |
no_license
|
blegloannec/cryptopals
|
fec708c59caaa21ec2eeb47ed7dda7498a4c36b1
|
438bc0653981e59722a728c7232a1ea949e383ee
|
refs/heads/master
| 2022-05-19T02:48:47.967056
| 2021-12-28T13:02:04
| 2022-03-07T17:02:40
| 143,565,339
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,589
|
py
|
#!/usr/bin/env python3
# this is 2.16 (CBC bitflipping) for CTR, which is trivial
# as in CTR mode the plaintext is xored against the generated
# stream, hence it is directly vulnerable to bitflipping: any bit
# flipped in the ciphertext will be flipped in the decrypted text
from Cryptodome.Cipher import AES
from Cryptodome.Random import get_random_bytes
BS = 16
## SECRET DATA
PREF = b'comment1=cooking%20MCs;userdata='
SUFF = b';comment2=%20like%20a%20pound%20of%20bacon'
Key = get_random_bytes(BS)
Nonce = get_random_bytes(BS//2)
##
def encrypt(userdata: str) -> bytes:
userdata = userdata.replace(';','";"').replace('=','"="').encode()
data = PREF + userdata + SUFF
return AES.new(Key, AES.MODE_CTR, nonce=Nonce).encrypt(data)
# contrary to 2.16, here we can even decode the decrypted text without any problem!
TARGET = ';admin=true;'
def decrypt(ciph: bytes) -> bool:
data = AES.new(Key, AES.MODE_CTR, nonce=Nonce).decrypt(ciph).decode()
print(data)
return TARGET in data
if __name__=='__main__':
assert not decrypt(encrypt(TARGET))
# as in 2.16, we assume we already know BS and the prefix size
PREF_SIZE = len(PREF)
target = bytearray(TARGET.encode())
# we flip the parity bit of the filtered bytes of the target
flips = [i for i,c in enumerate(target) if c in b';=']
for b in flips:
target[b] ^= 1
target = target.decode()
ciph = encrypt(target)
# and simply flip them back in the ciphertext to
ciph = bytearray(ciph)
for b in flips:
ciph[PREF_SIZE+b] ^= 1
assert decrypt(ciph)
|
[
"blg@gmx.com"
] |
blg@gmx.com
|
ceb0496d20400be814da009ed346bfa457d2b81c
|
8c8463413e92149ad0ff16eac0b09303ec18de99
|
/ddt_python/ddt_container_nSvgTable.py
|
49598644a372ca534c89455733b6531bc85f4502
|
[
"MIT"
] |
permissive
|
dmccloskey/ddt_python
|
23d0d4d2193fe052545b890ef332056f869117cf
|
60624701a01520db81c89b36be6af385a5274aba
|
refs/heads/master
| 2021-01-19T02:01:57.769244
| 2016-12-02T01:21:11
| 2016-12-02T01:21:11
| 48,295,899
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 7,278
|
py
|
from .ddt_container import ddt_container
from .ddt_tile import ddt_tile
from .ddt_tile_html import ddt_tile_html
class ddt_container_nSvgTable(ddt_container):
def make_nSvgTable(self,
data1,data2,
data1_keys,data1_nestkeys,data1_keymap,
data2_keys,data2_nestkeys,data2_keymap,
tileheader,
svgtype,
tabletype,
svgx1axislabel='',
svgy1axislabel='',
single_plot_I=True,
svgkeymap = [],
svgtile2datamap=[0],
svgfilters=None,
tablefilters=None,
tableheaders=None
):
'''Make a filter menu + n SVGs + Table
INPUT:
data1 = listDict of all data
data2 = listDict of all data (single plot with a different data from data 1 or a single plot with data 1/2)
dictColumn of all data (dictionary of data split into different SVGs, required for multiple plots);
parameters for filtermenu and table
data1_keys
data1_nestkeys
data1_keymap
parameters for the svg objects
data2_keys
data2_nestkeys
data2_keymap
tileheader = title for each of the tiles
svgtype = type of svg (TODO: add optional input for specifying specific svgs for multiple plots)
tabletype = type of table
single_plot_I = plot all data on a single svg or partition into seperate SVGs
True, only data1 will be used
False, data2 must specified
OPTIONAL INPUT for single plot:
svgkeymap = default, [data2_keymap],
svgtile2datamap= default, [0],
'''
#make the form
form = ddt_tile();
form.make_tileparameters(
tileparameters={
'tileheader':'Filter menu',
'tiletype':'html',
'tileid':"filtermenu1",
'rowid':"row1",
'colid':"col1",
'tileclass':"panel panel-default",
'rowclass':"row",
'colclass':"col-sm-6"}
);
form.make_htmlparameters(
htmlparameters = {
'htmlid':'filtermenuform1',
"htmltype":'form_01',
"formsubmitbuttonidtext":{'id':'submit1','text':'submit'},
"formresetbuttonidtext":{'id':'reset1','text':'reset'},
"formupdatebuttonidtext":{'id':'update1','text':'update'}},
);
self.add_parameters(form.get_parameters());
self.update_tile2datamap("filtermenu1",[0]);
self.add_filtermenu(
{"filtermenuid":"filtermenu1",
"filtermenuhtmlid":"filtermenuform1",
"filtermenusubmitbuttonid":"submit1",
"filtermenuresetbuttonid":"reset1",
"filtermenuupdatebuttonid":"update1"}
);
# data 1:
self.add_data(
data1,
data1_keys,
data1_nestkeys
);
# tile 1-n features: count
if not single_plot_I:
rowcnt = 1;
colcnt = 1;
cnt = 0;
for k,v in data2.items():
svgtileid = "tilesvg"+str(cnt);
svgid = 'svg'+str(cnt);
iter=cnt+1; #start at 1
if (cnt % 2 == 0):
rowcnt = rowcnt+1;#even
colcnt = 1;
else:
colcnt = colcnt+1;
# svg
svg = ddt_tile();
svg.make_tileparameters(
tileparameters={
'tileheader':tileheader,
'tiletype':'svg',
'tileid':svgtileid,
'rowid':"row"+str(rowcnt),
'colid':"col"+str(colcnt),
'tileclass':"panel panel-default",
'rowclass':"row",
'colclass':"col-sm-6"
});
svg.make_svgparameters(
svgparameters={
"svgtype":svgtype,
"svgkeymap":[data2_keymap],
'svgid':'svg'+str(cnt),
"svgmargin":{ 'top': 50, 'right': 150, 'bottom': 50, 'left': 50 },
"svgwidth":500,
"svgheight":350,
"svgx1axislabel":data2_keymap['xdata'],
"svgy1axislabel":data2_keymap['ydata']
}
);
self.add_parameters(svg.get_parameters());
self.update_tile2datamap(svgtileid,[iter]);
self.add_data(
v,
data2_keys,
data2_nestkeys
);
cnt+=1;
else:
cnt = 0;
svgtileid = "tilesvg"+str(cnt);
svgid = 'svg'+str(cnt);
rowcnt = 2;
colcnt = 1;
# make the svg object
svg = ddt_tile();
svg.make_tileparameters(
tileparameters={
'tileheader':tileheader,
'tiletype':'svg',
'tileid':svgtileid,
'rowid':"row"+str(rowcnt),
'colid':"col"+str(colcnt),
'tileclass':"panel panel-default",
'rowclass':"row",
'colclass':"col-sm-6"
});
# make the svg parameters
if not svgkeymap:
svgkeymap = [data2_keymap];
svg.make_svgparameters(
svgparameters={
"svgtype":svgtype,
"svgkeymap":svgkeymap,
'svgid':svgid,
"svgmargin":{ 'top': 50, 'right': 150, 'bottom': 50, 'left': 50 },
"svgwidth":350,
"svgheight":250,
"svgx1axislabel":data2_keymap['xdata'],
"svgy1axislabel":data2_keymap['ydata']
}
);
self.add_parameters(svg.get_parameters());
self.update_tile2datamap(svgtileid,svgtile2datamap);
#add data 2
if data2:
self.add_data(
data2,
data2_keys,
data2_nestkeys
);
cnt+=1;
# make the table object
crosstable = ddt_tile();
crosstable.make_tileparameters(
tileparameters = {
'tileheader':'Table',
'tiletype':'table',
'tileid':"tabletile1",
'rowid':"row"+str(rowcnt+1),
'colid':"col1",
'tileclass':"panel panel-default",
'rowclass':"row",
'colclass':"col-sm-12"
}
);
crosstable.make_tableparameters(
tableparameters = {
"tabletype":tabletype,
'tableid':'table1',
"tablefilters":tablefilters,
"tableclass":"table table-condensed table-hover",
'tableformtileid':'tile1',
"tablekeymap":[data2_keymap],
"tableheaders":tableheaders,}
);
self.add_parameters(crosstable.get_parameters());
self.update_tile2datamap("tabletile1",[0]);
|
[
"dmccloskey87@gmail.com"
] |
dmccloskey87@gmail.com
|
c98ea5753067696b58095c2bc6f8717a0a9e8274
|
47cde4a1cfbb05aa256064e03c6ab85650865ee4
|
/jackbox/bombintern.py
|
7663ac4f0a2d2322468e04115302cc8865952578
|
[
"Apache-2.0"
] |
permissive
|
Gorialis/jackbox.py
|
54b5bbb25afd9233a594c6d1e861528b0dd3349e
|
509bdab63a56114b2d5c8d1fe3220bc7f04ea834
|
refs/heads/master
| 2021-01-15T00:13:26.902245
| 2020-02-24T16:15:19
| 2020-02-24T16:15:19
| 242,808,186
| 0
| 0
|
Apache-2.0
| 2020-02-24T18:13:48
| 2020-02-24T18:13:47
| null |
UTF-8
|
Python
| false
| false
| 6,784
|
py
|
"""
/jackbox/bombintern.py
Copyright (c) 2020 ShineyDev
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
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from jackbox.client import Client
class BombCorpClient(Client):
async def add(self, ingredient: str):
"""
|coro|
Adds an ingredient to a ``CoffeeBomb``.
Parameters
----------
ingredient: :class:`str`
The ingredient to add.
"""
data = {
"args": [{
"action": "SendMessageToRoomOwner",
"appId": self._wss.app_id,
"message": {"add": True,
"ingredient": ingredient},
"roomId": self._wss.room_id,
"type": "Action",
"userId": self._wss.user_id,
}],
"name": "msg",
}
await self._wss._send(5, data)
async def brew(self):
"""
|coro|
Brews the ``CoffeeBomb``.
"""
data = {
"args": [{
"action": "SendMessageToRoomOwner",
"appId": self._wss.app_id,
"message": {"brew": True},
"roomId": self._wss.room_id,
"type": "Action",
"userId": self._wss.user_id,
}],
"name": "msg",
}
await self._wss._send(5, data)
async def cut(self, index: int):
"""
|coro|
Cuts a wire on a ``WiredBomb``.
Parameters
----------
index: :class:`int`
The index of the wire.
.. note::
Indexing starts at ``1``.
"""
data = {
"args": [{
"action": "SendMessageToRoomOwner",
"appId": self._wss.app_id,
"message": {"index": index},
"roomId": self._wss.room_id,
"type": "Action",
"userId": self._wss.user_id,
}],
"name": "msg",
}
await self._wss._send(5, data)
async def file(self, name: str):
"""
|coro|
Files a file on a ``FilingBomb``.
Parameters
----------
name: :class:`str`
The **full** name of the file.
"""
data = {
"args": [{
"action": "SendMessageToRoomOwner",
"appId": self._wss.app_id,
"message": {"file": name},
"roomId": self._wss.room_id,
"type": "Action",
"userId": self._wss.user_id,
}],
"name": "msg",
}
await self._wss._send(5, data)
async def menu(self):
"""
|coro|
Returns to the menu.
"""
data = {
"args": [{
"action": "SendMessageToRoomOwner",
"appId": self._wss.app_id,
"message": {"decision": "Gameover_Menu"},
"roomId": self._wss.room_id,
"type": "Action",
"userId": self._wss.user_id,
}],
"name": "msg",
}
await self._wss._send(5, data)
async def next_day(self):
"""
|coro|
Starts the next day.
"""
data = {
"args": [{
"action": "SendMessageToRoomOwner",
"appId": self._wss.app_id,
"message": {"decision": "Gameover_Continue"},
"roomId": self._wss.room_id,
"type": "Action",
"userId": self._wss.user_id,
}],
"name": "msg",
}
await self._wss._send(5, data)
async def press(self, index: int):
"""
|coro|
Presses a button on a ``CopierBomb`` or a ``KeypadBomb``.
Parameters
----------
index: :class:`int`
The index of the button.
.. note::
Indexing starts at ``1``.
"""
data = {
"args": [{
"action": "SendMessageToRoomOwner",
"appId": self._wss.app_id,
"message": {"index": index},
"roomId": self._wss.room_id,
"type": "Action",
"userId": self._wss.user_id,
}],
"name": "msg",
}
await self._wss._send(5, data)
async def remove(self, ingredient: str):
"""
|coro|
Removes an ingredient from a ``CoffeeBomb``.
Parameters
----------
ingredient: :class:`str`
The ingredient to remove.
"""
data = {
"args": [{
"action": "SendMessageToRoomOwner",
"appId": self._wss.app_id,
"message": {"remove": True,
"ingredient": ingredient},
"roomId": self._wss.room_id,
"type": "Action",
"userId": self._wss.user_id,
}],
"name": "msg",
}
await self._wss._send(5, data)
async def retry_day(self):
"""
|coro|
Retries the current day.
"""
data = {
"args": [{
"action": "SendMessageToRoomOwner",
"appId": self._wss.app_id,
"message": {"decision": "Gameover_Retry"},
"roomId": self._wss.room_id,
"type": "Action",
"userId": self._wss.user_id,
}],
"name": "msg",
}
await self._wss._send(5, data)
async def smash(self, name: str):
"""
|coro|
Smashes an object on a ``SmashPuzzle``.
Parameters
----------
name: :class:`str`
The name of the object.
"""
data = {
"args": [{
"action": "SendMessageToRoomOwner",
"appId": self._wss.app_id,
"message": {"object": name},
"roomId": self._wss.room_id,
"type": "Action",
"userId": self._wss.user_id,
}],
"name": "msg",
}
await self._wss._send(5, data)
|
[
"contact@shiney.dev"
] |
contact@shiney.dev
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.