code
stringlengths
1
25.8M
language
stringclasses
18 values
source
stringclasses
4 values
repo
stringclasses
78 values
path
stringlengths
0
268
<?php namespace Illuminate\Console\Concerns; use Symfony\Component\Console\Completion\CompletionInput; use Symfony\Component\Console\Completion\CompletionSuggestions; use Symfony\Component\Console\Completion\Suggestion; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; trait HasParameters { /** * Specify the arguments and options on the command. * * @return void */ protected function specifyParameters() { // We will loop through all of the arguments and options for the command and // set them all on the base command instance. This specifies what can get // passed into these commands as "parameters" to control the execution. foreach ($this->getArguments() as $arguments) { if ($arguments instanceof InputArgument) { $this->getDefinition()->addArgument($arguments); } else { $this->addArgument(...$arguments); } } foreach ($this->getOptions() as $options) { if ($options instanceof InputOption) { $this->getDefinition()->addOption($options); } else { $this->addOption(...$options); } } } /** * Get the console command arguments. * * @return (InputArgument|array{ * 0: non-empty-string, * 1?: InputArgument::REQUIRED|InputArgument::OPTIONAL|InputArgument::IS_ARRAY, * 2?: string, * 3?: mixed, * 4?: list<string|Suggestion>|\Closure(CompletionInput, CompletionSuggestions): list<string|Suggestion> * })[] */ protected function getArguments() { return []; } /** * Get the console command options. * * @return (InputOption|array{ * 0: non-empty-string, * 1?: string|non-empty-array<string>, * 2?: InputOption::VALUE_*, * 3?: string, * 4?: mixed, * 5?: list<string|Suggestion>|\Closure(CompletionInput, CompletionSuggestions): list<string|Suggestion> * })[] */ protected function getOptions() { return []; } }
php
github
https://github.com/laravel/framework
src/Illuminate/Console/Concerns/HasParameters.php
- Feature Name: Adding new SQL features with syntax - recommendations - Status: active - Start Date: 2017-08-06 - Authors: knz, Dan Harrison, Andrew Couch - RFC PR: #17569 - Cockroach Issue: N/A # Summary This RFC recommends some general steps for projects that add features visible through SQL syntax (either by adding new syntax or repurposing existing syntax). There are two aspects to the RFC: - one that focuses on changes to the SQL grammar; in short, new syntactic features should be discussed via the RFC process and merged with the same PR that actually implements the feature. - one that focuses on the general process of adding new language features; this serves as point-in-time reminder of the work currently needed. Acknowledgement: This RFC complements/accompanies the [codelab for adding a new SQL statement](../codelabs/00-sql-function.md) by Andrew Couch. # Motivation Until this point there have been instances in the past where the SQL grammar was modified/extended to "prepare" for some yet-to-be-implemented feature, thereby reserving a space in the set of valid SQL statements for future use. The main motivation for that approach was to ensure that a later PR introducing said functionality would contain fewer commits / changes to review, to ease the review process. This RFC posits this motivation is misguided and instead the SQL contributors should aim to avoid the following pitfalls: - "Things happen" with the grammar over time - cleanups, refactorings, optimizations, renames, etc. This is routine work for the SQL team, but it's also work where the people doing the work need to have ownership of the SQL grammar. The problem with having an orphan syntax, especially without a comment about who's responsible for it, what it is to become and when, is that we can't really work around that in the grammar without risking breaking that person's plans. - there is such a thing about the UI of a language, and that is its grammar. There is also such a thing as UI design, which ensures a number of properties: 1) that the UI is consistent 2) that it's orthogonal 3) that it is extensible at low cost 4) that it's well-documented and, most important for us 5) that we don't run the risk of defining something that will conflict with some industry standard later (such as a standard SQL feature *we* may not have heard of yet but our customers will want us to look at). Granted, SQL is not really "pleasant" to look at but it has some internal structure and general patterns regarding extensibility that have been adopted as the result of 40 years of accumulated wisdom. For example, the first keyword in a statement has semantic properties all over the place in the language. One cannot just add a new statement prefix and not expect *lots* of work; whereas adding an alternate form for an existing prefix is relatively harmless. - the natural progression of this practice we've started already would be a grammar definition that is fostering a large population of orphan syntax without functionality, created for projects abandoned before completion. We do not have this problem now, but from experience this just happens with team/company growth unless we're unrealistically careful (in other words, in this author's experience this really is a problem waiting to happen). # Mindset A contributor to CockroachDB often has good reasons to suggest a SQL language extension. One should always approach this task with a clear mindset that distinguishes the *mechanisms* which deliver the desired feature from the *interface* presented to users to control it. The SQL syntax is the "interface". The code behind the syntax is the mechanism. We can have multiple interfaces for the same mechanism: either two or more ways to access the mechanism in SQL directly, or other interfaces (e.g. an admin RPC) that enable access to the mechanism besides SQL. **As a matter of good engineering, it is always useful to discuss and define the mechanisms separately from the design of the interfaces.** (And preferably mechanisms no latter than interfaces.) Soliciting input on both is equally important. That's why both should undergo the RFC process. *If your functionality mainly "takes place" elsewhere than the SQL layer but you still need a SQL interface, be sure to involve the SQL team in the SQL-related discussion for the interface part of your RFC.* # Case for really reserved syntax This RFC proposes to delay merging syntax additions until the change that actually implements the functionality. We foresee three accepted and documented exceptions to this policy. ## Standard SQL syntax We can reserve syntax that is specified in the SQL standard but currently unsupported in CockroachDB. This provides us a convenient way to ensure we don't introduce conflicting syntax while also giving us a natural mechanism to inform the user that, yes, we know that's a reasonable thing to ask, and that there is GH issue where they can see why we don't support it yet and perhaps provide arguments to influence our roadmap. ## Features for sole consumption by CockroachDB internals We can reserve syntax also when a new mechanism RFC has been accepted which benefits from exposing common functionality to different parts of CockroachDB, *but not client applications*, via a SQL syntax extension. In this case, the contributor should be mindful that a feature that is once considered "internal" may be serendipitously found later useful by end-users; to prepare for this eventuality we must pave the road to "publicize" a feature once internal: - the SQL syntax for the internal feature should still follow the principles presented in "Choice of syntax" below. - the new syntax contains the word "INTERNAL" or similar, to denote explicitly in the syntax the feature is not meant for public consumption. - the new syntax is fully hidden from user-facing documentation. Preferably, the code should also contain provision to make the syntax invalid for regular client sessions, e.g. by requiring special permissions or a planner flag. ## Multi-person or multi-stage projects We can reserve syntax also when all the following conditions hold: - a new mechanism RFC in demand of dedicated syntax has been discussed and resources have already been allocated to start the work (i.e. even if the RFC may not yet be finalized, the project has a green light to proceed); - one or more candidate user-facing SQL interfaces have been discussed in an RFC (possibly bundled with the corresponding mechanism RFC). - the MVP (minimum viable product) for the functionality requires intervention from two or more contributors, or requires spreading across multiple layers of work (= multiple PRs), or both. - the contributors deem it preferable to establish a common set of tests using the new SQL syntax upfront of the work that needs to be done. In this case, adding new syntax is acceptable, given the following conditions: - the new syntax contains the word "EXPERIMENTAL" either standalone or as prefix to some keyword (new syntax rules) or identifier (new built-in functions) (e.g. `experimental_uuid_v4()`, `ALTER TABLE EXPERIMENTAL ...`) - the new syntax is properly documented, yet marked clearly in documentation as a feature that is subject to change without notice. - it is still possible to build and run CockroachDB successfully in production (albeit without full support for the new feature) if the corresponding grammar/built-in functions are elided from the source code. # Structure of a proposal In CockroachDB SQL features will need work at multiple levels, touching the various architectural components discussed in the [SQL architecture document](../tech-notes/sql.md). An RFC planning to add a new SQL feature would therefore do well to outline and clearly distinguish the following aspects: - Mechanism: - Specification of input parameters - Specification of desired behavior - Logical planning changes (if needed) - Transaction logic changes (if needed) - Schema change logic changes (if needed) - Updates to the SQL execution engine(s) or CCL interface - Updates to other parts of CockroachDB (if needed) - Interface: - Specification of lexical and syntactic elements - Using examples! - Definition of new/extended Abstract Syntax representations (if needed) - Desugaring to existing abstract syntax (highly recommended, if possible) - Typing and normalization rules - **Envisioned documentation: how do we explain this?** # Choice of syntax Somewhere in the process of writing about those things comes the question: *what should the SQL interface be?* Whether the author already has a clear idea about what they want/recommend or whether they don't, the RFC should at least cursorily examine past work in other SQL engines and suggest how other SQL engines have offered similar functionality (if at all). Then two situations can arise: - either similar functionality is available in one or more other SQL engines: - if similar functionality has already been *standardized*, then just use that, unless strongly argued against in the RFC. - is it possible to reuse the same syntax as some other engine? - possible to use as is: use just that, unless strong arguments against. - possible to use with minor alterations: propose reuse, but also suggest alternatives. - possible to use with major alterations: suggest reuse, and emphasize alternatives. - no similar functionality *as a whole* is available elsewhere: - does the functionality "group" with other existing SQL statements? - if so, reuse at least the first keyword and the general structure - does the functionality create / delete entities? - do not forget about IF EXISTS / IF NOT EXISTS - does the functionality take optional parameters? - consider WITH - does the functionality need to input data from a relation/query? - consider FROM In general: - if a *part* of another SQL statement corresponds more or less to what your new envisioned syntax requires, consider reusing the same syntactic structure. This is moreso true if there are two or more other SQL statements that have these commonalities. - If possible, reuse existing keywords rather than defining new keywords, particularly if the new keyword would have to be reserved. # New abstract syntax or desugaring? During parsing the code translates the input text into an abstract syntax tree (AST). Different node types carry different semantics. Sometimes a new feature with different syntax can *reuse* existing AST nodes; we (compiler community) say that the new syntax is "sugar" for a semantic construct that was already valid in principle. For example, the syntax `a IS UNKNOWN` can be desugared into `a IS NULL`, `SHOW ALL CLUSTER SETTINGS` can be desugared into `SHOW CLUSTER SETTING "all"`, etc. **In general, the fewer the AST nodes the better.** Each new AST node multiplies the work by the number of algorithms/transforms in the SQL middle-end layer. Sometimes, you can't reuse an existing AST node as-is, but it is possible to update/enhance it so that it becomes reusable both for the new features and the statement(s) that already use it. Consider doing that instead of adding a new AST node. And *in general it is not required that a given SQL input text can be parsed and its AST pretty-printed back to exactly the same SQL input*. Desugaring is *good*, use it whenever possible. # Composability and generality Even though *you* may only have a few use cases in mind to use the new feature being proposed, try to not restrict/tailor the syntax and semantics of the SQL interface to just these use cases. For example, suppose you are designing a feature to "import CSV data into CockroachDB": - Ad-hoc, use-case-specific, not general: `IMPORTCSV FILE <filename> INTO <tablename> USING DELIMITER <string>` - Slightly more general: `IMPORT <format> FILE <filename> INTO <tablename> [WITH <option>...]` - Even more general: `IMPORT [INTO] <relation> <format> DATA (<URL>...) [WITH <option>...]` General principles: - make a feature as general and orthogonal as possible given the two points below; - you may only support a sub-set of the cases in your MVP/PoC (e.g. just `format` = `CSV`); - do not make proposals that prevent us from changing our mind later, e.g. by promising generality in a domain where there is no 100% upfront confidence that all the possible cases make sense. # Code highlights / pitfalls - Do not forget `parse_test.go` - Do not forget contextual inline help. Check out `sql/parser/README.md`. - If your feature needs to use SQL expressions: - try at all costs to avoid changes or constraints to the typing system! - look at how other statements use `analyzeExpr()` and do the same; - use `RunFilter()` for conditions instead of evaluating manually and comparing the `DBool` value. - If your feature needs to support placeholders: - do not forget to extend `WalkableStmt` if you're adding a new statement type; - add a placeholder test in `pgwire_test.go`. - If your feature is adding a new SQL statement type: - what should its PG tag be in the pgwire protocol? Are clients going to notice/care? - be mindful about the difference between DDL and non-DDL statements # Alternatives - Not do anything - makes the work of the SQL team harder. - Delegate all syntax choices to a specifically mandated committee - not scalable. # Unresolved questions None.
unknown
github
https://github.com/cockroachdb/cockroach
docs/RFCS/20171011_adding_sql_syntax.md
from langchain_core.exceptions import TracerException from langchain_core.tracers.base import BaseTracer __all__ = ["BaseTracer", "TracerException"]
python
github
https://github.com/langchain-ai/langchain
libs/langchain/langchain_classic/schema/callbacks/tracers/base.py
#ifndef RUBY_ID_TABLE_H #define RUBY_ID_TABLE_H 1 #include "ruby/internal/config.h" #include <stddef.h> #include "ruby/ruby.h" struct rb_id_table; /* compatible with ST_* */ enum rb_id_table_iterator_result { ID_TABLE_CONTINUE = ST_CONTINUE, ID_TABLE_STOP = ST_STOP, ID_TABLE_DELETE = ST_DELETE, ID_TABLE_REPLACE = ST_REPLACE, ID_TABLE_ITERATOR_RESULT_END }; struct rb_id_table *rb_id_table_create(size_t size); struct rb_id_table *rb_id_table_init(struct rb_id_table *tbl, size_t capa); void rb_id_table_free(struct rb_id_table *tbl); void rb_id_table_free_items(struct rb_id_table *tbl); void rb_id_table_clear(struct rb_id_table *tbl); size_t rb_id_table_memsize(const struct rb_id_table *tbl); int rb_id_table_insert(struct rb_id_table *tbl, ID id, VALUE val); int rb_id_table_lookup(struct rb_id_table *tbl, ID id, VALUE *valp); int rb_id_table_delete(struct rb_id_table *tbl, ID id); typedef enum rb_id_table_iterator_result rb_id_table_update_value_callback_func_t(VALUE *val, void *data, int existing); typedef enum rb_id_table_iterator_result rb_id_table_foreach_func_t(ID id, VALUE val, void *data); typedef enum rb_id_table_iterator_result rb_id_table_foreach_values_func_t(VALUE val, void *data); void rb_id_table_foreach(struct rb_id_table *tbl, rb_id_table_foreach_func_t *func, void *data); void rb_id_table_foreach_values(struct rb_id_table *tbl, rb_id_table_foreach_values_func_t *func, void *data); void rb_id_table_foreach_values_with_replace(struct rb_id_table *tbl, rb_id_table_foreach_values_func_t *func, rb_id_table_update_value_callback_func_t *replace, void *data); VALUE rb_managed_id_table_create(const rb_data_type_t *type, size_t capa); VALUE rb_managed_id_table_new(size_t capa); VALUE rb_managed_id_table_dup(VALUE table); int rb_managed_id_table_insert(VALUE table, ID id, VALUE val); int rb_managed_id_table_lookup(VALUE table, ID id, VALUE *valp); size_t rb_managed_id_table_size(VALUE table); void rb_managed_id_table_foreach(VALUE table, rb_id_table_foreach_func_t *func, void *data); void rb_managed_id_table_foreach_values(VALUE table, rb_id_table_foreach_values_func_t *func, void *data); int rb_managed_id_table_delete(VALUE table, ID id); extern const rb_data_type_t rb_managed_id_table_type; RUBY_SYMBOL_EXPORT_BEGIN size_t rb_id_table_size(const struct rb_id_table *tbl); RUBY_SYMBOL_EXPORT_END #endif /* RUBY_ID_TABLE_H */
c
github
https://github.com/ruby/ruby
id_table.h
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is based on # Lib/posixpath.py of cpython # It is licensed under the PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 # # 1. This LICENSE AGREEMENT is between the Python Software Foundation # ("PSF"), and the Individual or Organization ("Licensee") accessing and # otherwise using this software ("Python") in source or binary form and # its associated documentation. # # 2. Subject to the terms and conditions of this License Agreement, PSF hereby # grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, # analyze, test, perform and/or display publicly, prepare derivative works, # distribute, and otherwise use Python alone or in any derivative version, # provided, however, that PSF's License Agreement and PSF's notice of copyright, # i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, # 2011, 2012, 2013, 2014, 2015 Python Software Foundation; All Rights Reserved" # are retained in Python alone or in any derivative version prepared by Licensee. # # 3. In the event Licensee prepares a derivative work that is based on # or incorporates Python or any part thereof, and wants to make # the derivative work available to others as provided herein, then # Licensee hereby agrees to include in any such work a brief summary of # the changes made to Python. # # 4. PSF is making Python available to Licensee on an "AS IS" # basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR # IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND # DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS # FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT # INFRINGE ANY THIRD PARTY RIGHTS. # # 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON # FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS # A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, # OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. # # 6. This License Agreement will automatically terminate upon a material # breach of its terms and conditions. # # 7. Nothing in this License Agreement shall be deemed to create any # relationship of agency, partnership, or joint venture between PSF and # Licensee. This License Agreement does not grant permission to use PSF # trademarks or trade name in a trademark sense to endorse or promote # products or services of Licensee, or any third party. # # 8. By copying, installing or otherwise using Python, Licensee # agrees to be bound by the terms and conditions of this License # Agreement. import os def ismount(path): """Test whether a path is a mount point clone of os.path.ismount (from cpython Lib/posixpath.py) fixed to solve https://github.com/ansible/ansible-modules-core/issues/2186 and workaround non-fixed http://bugs.python.org/issue2466 this should be rewritten as soon as python issue 2466 is fixed probably check for python version and use os.path.ismount if fixed to remove replace in this file ismount( -> os.path.ismount( and remove this function""" try: s1 = os.lstat(path) except OSError: # the OSError should be handled with more care # it could be a "permission denied" but path is still a mount return False else: # A symlink can never be a mount point if os.path.stat.S_ISLNK(s1.st_mode): return False parent = os.path.join(path, os.path.pardir) parent = os.path.realpath(parent) try: s2 = os.lstat(parent) except OSError: # one should handle the returned OSError with more care to figure # out whether this is still a mount return False if s1.st_dev != s2.st_dev: return True # path/.. on a different device as path if s1.st_ino == s2.st_ino: return True # path/.. is the same i-node as path, i.e. path=='/' return False
unknown
codeparrot/codeparrot-clean
/*------------------------------------------------------------------------- * * hashsort.c * Sort tuples for insertion into a new hash index. * * When building a very large hash index, we pre-sort the tuples by bucket * number to improve locality of access to the index, and thereby avoid * thrashing. We use tuplesort.c to sort the given index tuples into order. * * Note: if the number of rows in the table has been underestimated, * bucket splits may occur during the index build. In that case we'd * be inserting into two or more buckets for each possible masked-off * hash code value. That's no big problem though, since we'll still have * plenty of locality of access. * * * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION * src/backend/access/hash/hashsort.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include "access/hash.h" #include "commands/progress.h" #include "miscadmin.h" #include "pgstat.h" #include "port/pg_bitutils.h" #include "utils/tuplesort.h" /* * Status record for spooling/sorting phase. */ struct HSpool { Tuplesortstate *sortstate; /* state data for tuplesort.c */ Relation index; /* * We sort the hash keys based on the buckets they belong to, then by the * hash values themselves, to optimize insertions onto hash pages. The * masks below are used in _hash_hashkey2bucket to determine the bucket of * a given hash key. */ uint32 high_mask; uint32 low_mask; uint32 max_buckets; }; /* * create and initialize a spool structure */ HSpool * _h_spoolinit(Relation heap, Relation index, uint32 num_buckets) { HSpool *hspool = palloc0_object(HSpool); hspool->index = index; /* * Determine the bitmask for hash code values. Since there are currently * num_buckets buckets in the index, the appropriate mask can be computed * as follows. * * NOTE : This hash mask calculation should be in sync with similar * calculation in _hash_init_metabuffer. */ hspool->high_mask = pg_nextpower2_32(num_buckets + 1) - 1; hspool->low_mask = (hspool->high_mask >> 1); hspool->max_buckets = num_buckets - 1; /* * We size the sort area as maintenance_work_mem rather than work_mem to * speed index creation. This should be OK since a single backend can't * run multiple index creations in parallel. */ hspool->sortstate = tuplesort_begin_index_hash(heap, index, hspool->high_mask, hspool->low_mask, hspool->max_buckets, maintenance_work_mem, NULL, TUPLESORT_NONE); return hspool; } /* * clean up a spool structure and its substructures. */ void _h_spooldestroy(HSpool *hspool) { tuplesort_end(hspool->sortstate); pfree(hspool); } /* * spool an index entry into the sort file. */ void _h_spool(HSpool *hspool, const ItemPointerData *self, const Datum *values, const bool *isnull) { tuplesort_putindextuplevalues(hspool->sortstate, hspool->index, self, values, isnull); } /* * given a spool loaded by successive calls to _h_spool, * create an entire index. */ void _h_indexbuild(HSpool *hspool, Relation heapRel) { IndexTuple itup; int64 tups_done = 0; #ifdef USE_ASSERT_CHECKING uint32 hashkey = 0; #endif tuplesort_performsort(hspool->sortstate); while ((itup = tuplesort_getindextuple(hspool->sortstate, true)) != NULL) { /* * Technically, it isn't critical that hash keys be found in sorted * order, since this sorting is only used to increase locality of * access as a performance optimization. It still seems like a good * idea to test tuplesort.c's handling of hash index tuple sorts * through an assertion, though. */ #ifdef USE_ASSERT_CHECKING uint32 lasthashkey = hashkey; hashkey = _hash_hashkey2bucket(_hash_get_indextuple_hashkey(itup), hspool->max_buckets, hspool->high_mask, hspool->low_mask); Assert(hashkey >= lasthashkey); #endif /* the tuples are sorted by hashkey, so pass 'sorted' as true */ _hash_doinsert(hspool->index, itup, heapRel, true); /* allow insertion phase to be interrupted, and track progress */ CHECK_FOR_INTERRUPTS(); pgstat_progress_update_param(PROGRESS_CREATEIDX_TUPLES_DONE, ++tups_done); } }
c
github
https://github.com/postgres/postgres
src/backend/access/hash/hashsort.c
#!/usr/bin/env python # Copyright (C) 2011 Genome Research Limited -- See full notice at end # of module. # Create a plot of ZMW productivity by x/y position on the # SMRTcell. First parameter is input .bas.h5 file. Output png file is # optional command line parameter, defaulting to productivity.png. import sys import optparse import numpy as np import h5py from tt_log import logger import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt DEF_OUTPUT = 'productivity.png' def main (): logger.debug("%s starting" % sys.argv[0]) opt, args = getParms() infile_name = args[0] infile = h5py.File (infile_name, 'r') colours = ('grey', 'red', 'green') legends = ('non-seq', 'prod-0', 'prod-1') top = h5py.Group (infile, '/') ZMW = top["PulseData/BaseCalls/ZMW"] ZMWMetrics = top["PulseData/BaseCalls/ZMWMetrics"] holeStatus = ZMW["HoleStatus"] holeXY = ZMW["HoleXY"] holeProd = ZMWMetrics["Productivity"] nonseqHoles = holeStatus[:]!=0 # ZMWs other than sequencing prod0Holes = np.logical_and(holeProd[:]==0, np.logical_not(nonseqHoles)) prod1Holes = np.logical_and(holeProd[:]==1, np.logical_not(nonseqHoles)) holesByType = (nonseqHoles, prod0Holes, prod1Holes) for which in xrange(len(holesByType)): whichHoles = holesByType[which] howMany = sum(whichHoles) logger.debug("%5d %s" % (howMany, legends[which])); if howMany > 0: plt.scatter (holeXY[whichHoles,0], holeXY[whichHoles,1], \ s=1, c=colours[which], edgecolor='face', \ label="%5d %s" % (howMany, legends[which])) plt.axis ('equal') plt.legend (scatterpoints=3, prop={'size':8}) plt.savefig (opt.output) infile.close() logger.debug("complete") def getParms (): # use default input sys.argv[1:] parser = optparse.OptionParser(usage='%prog [options] <bas_file>') parser.add_option ('--output', help='Output file name (def: %default)') parser.set_defaults (output=DEF_OUTPUT) opt, args = parser.parse_args() return opt, args if __name__ == "__main__": main() # Copyright (C) 2011 Genome Research Limited # # This library is free software. You can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>.
unknown
codeparrot/codeparrot-clean
import pytest import rpm_version expected_pkgs = { "spam": { "name": "spam", "version": "3.2.1", }, "eggs": { "name": "eggs", "version": "3.2.1", }, } @pytest.mark.parametrize('pkgs, expect_not_found', [ ( {}, ["spam", "eggs"], # none found ), ( {"spam": ["3.2.1", "4.5.1"]}, ["eggs"], # completely missing ), ( { "spam": ["3.2.1", "4.5.1"], "eggs": ["3.2.1"], }, [], # all found ), ]) def test_check_pkg_found(pkgs, expect_not_found): if expect_not_found: with pytest.raises(rpm_version.RpmVersionException) as e: rpm_version._check_pkg_versions(pkgs, expected_pkgs) assert "not found to be installed" in str(e.value) assert set(expect_not_found) == set(e.value.problem_pkgs) else: rpm_version._check_pkg_versions(pkgs, expected_pkgs) @pytest.mark.parametrize('pkgs, expect_not_found', [ ( { 'spam': ['3.2.1'], 'eggs': ['3.3.2'], }, { "eggs": { "required_versions": ["3.2"], "found_versions": ["3.3"], } }, # not the right version ), ( { 'spam': ['3.1.2', "3.3.2"], 'eggs': ['3.3.2', "1.2.3"], }, { "eggs": { "required_versions": ["3.2"], "found_versions": ["3.3", "1.2"], }, "spam": { "required_versions": ["3.2"], "found_versions": ["3.1", "3.3"], } }, # not the right version ), ]) def test_check_pkg_version_found(pkgs, expect_not_found): if expect_not_found: with pytest.raises(rpm_version.RpmVersionException) as e: rpm_version._check_pkg_versions(pkgs, expected_pkgs) assert "found to be installed with an incorrect version" in str(e.value) assert expect_not_found == e.value.problem_pkgs else: rpm_version._check_pkg_versions(pkgs, expected_pkgs)
unknown
codeparrot/codeparrot-clean
# TODO.TXT-CLI-python test script # Copyright (C) 2011-2012 Sigmavirus24, Jeff Stein # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # TLDR: This is licensed under the GPLv3. See LICENSE for more details. # Common functions for test_*_todo.py import datetime import os import re import sys import unittest sys.path.insert(0, '..') import todo todotxt = todo.CONFIG["TODO_FILE"] = "test_todo.txt" donetxt = todo.CONFIG["DONE_FILE"] = "test_done.txt" class BaseTest(unittest.TestCase): num = 50 def default_config(self): pass def setUp(self): todo.CONFIG["PRE_DATE"] = False todo.CONFIG["TODO_PY"] = "testing" todo.default_config = self.default_config sys.stdout = open(os.devnull, 'w') open(todotxt, "w+").close() open(donetxt, "w+").close() def tearDown(self): sys.stdout = sys.__stdout__ if os.path.isfile(todotxt): os.unlink(todotxt) if os.path.isfile(donetxt): os.unlink(donetxt) def count_matches(self, regexp=None): count = 0 for line in todo.iter_todos(): if regexp == None or re.match(regexp, line): count += 1 return count def _test_lines_no_pri(self, num): return ["Test {0}".format(i) for i in range(0, num)] def _test_lines_pri(self, num): n = len(todo.PRIORITIES) p = todo.PRIORITIES return ["({0}) Test {1}".format(p[i % n], i) for i in range(0, num)] def _test_lines_date(self, num): l = self._test_lines_pri(num) m = [] start_date = datetime.date.today() for d, l in zip((start_date + datetime.timedelta(n) for n in range(num)), l): m.append(todo.concat([l, " #{%s}" % d.isoformat()])) return m def _test_lines_project(self, num): projects = ["+foo", "+bar", "+bogus", "+github", "+school", "+work", "+inthemorning", "+agenda", "+noagenda"] n = len(projects) l = self._test_lines_pri(num) m = [] for i in range(0, num): m.append(todo.concat([l[i], projects[i % n]], " ")) return m def _test_lines_context(self, num): projects = ["@foo", "@bar", "@bogus", "@github", "@school", "@work", "@inthemorning", "@agenda", "@noagenda"] n = len(projects) l = self._test_lines_pri(num) m = [] for i in range(0, num): m.append(todo.concat([l[i], projects[i % n]], " ")) return m def assertNumLines(self, exp, regexp=None): c = self.count_matches(regexp) self.assertEqual(exp, c) def assertIsInstance(self, obj, cls, msg=None): if sys.version_info >= (2, 7): super(BaseTest, self).assertIsInstance(obj, cls, msg) else: self.assertTrue(isinstance(obj, cls)) def assertIsNotNone(self, expr, msg=None): if sys.version_info >= (2, 7): super(BaseTest, self).assertIsNotNone(expr, msg) else: if not expr: self.fail(msg) def force_print(self, message): sys.stderr.write(''.join([message, '\n'])) sys.stderr.flush()
unknown
codeparrot/codeparrot-clean
"""Fixer for __metaclass__ = X -> (metaclass=X) methods. The various forms of classef (inherits nothing, inherits once, inherints many) don't parse the same in the CST so we look at ALL classes for a __metaclass__ and if we find one normalize the inherits to all be an arglist. For one-liner classes ('class X: pass') there is no indent/dedent so we normalize those into having a suite. Moving the __metaclass__ into the classdef can also cause the class body to be empty so there is some special casing for that as well. This fixer also tries very hard to keep original indenting and spacing in all those corner cases. """ # Author: Jack Diederich # Local imports from .. import fixer_base from ..pygram import token from ..fixer_util import Name, syms, Node, Leaf def has_metaclass(parent): """ we have to check the cls_node without changing it. There are two possiblities: 1) clsdef => suite => simple_stmt => expr_stmt => Leaf('__meta') 2) clsdef => simple_stmt => expr_stmt => Leaf('__meta') """ for node in parent.children: if node.type == syms.suite: return has_metaclass(node) elif node.type == syms.simple_stmt and node.children: expr_node = node.children[0] if expr_node.type == syms.expr_stmt and expr_node.children: left_side = expr_node.children[0] if isinstance(left_side, Leaf) and \ left_side.value == '__metaclass__': return True return False def fixup_parse_tree(cls_node): """ one-line classes don't get a suite in the parse tree so we add one to normalize the tree """ for node in cls_node.children: if node.type == syms.suite: # already in the preferred format, do nothing return # !%@#! oneliners have no suite node, we have to fake one up for i, node in enumerate(cls_node.children): if node.type == token.COLON: break else: raise ValueError("No class suite and no ':'!") # move everything into a suite node suite = Node(syms.suite, []) while cls_node.children[i+1:]: move_node = cls_node.children[i+1] suite.append_child(move_node.clone()) move_node.remove() cls_node.append_child(suite) node = suite def fixup_simple_stmt(parent, i, stmt_node): """ if there is a semi-colon all the parts count as part of the same simple_stmt. We just want the __metaclass__ part so we move everything after the semi-colon into its own simple_stmt node """ for semi_ind, node in enumerate(stmt_node.children): if node.type == token.SEMI: # *sigh* break else: return node.remove() # kill the semicolon new_expr = Node(syms.expr_stmt, []) new_stmt = Node(syms.simple_stmt, [new_expr]) while stmt_node.children[semi_ind:]: move_node = stmt_node.children[semi_ind] new_expr.append_child(move_node.clone()) move_node.remove() parent.insert_child(i, new_stmt) new_leaf1 = new_stmt.children[0].children[0] old_leaf1 = stmt_node.children[0].children[0] new_leaf1.prefix = old_leaf1.prefix def remove_trailing_newline(node): if node.children and node.children[-1].type == token.NEWLINE: node.children[-1].remove() def find_metas(cls_node): # find the suite node (Mmm, sweet nodes) for node in cls_node.children: if node.type == syms.suite: break else: raise ValueError("No class suite!") # look for simple_stmt[ expr_stmt[ Leaf('__metaclass__') ] ] for i, simple_node in list(enumerate(node.children)): if simple_node.type == syms.simple_stmt and simple_node.children: expr_node = simple_node.children[0] if expr_node.type == syms.expr_stmt and expr_node.children: # Check if the expr_node is a simple assignment. left_node = expr_node.children[0] if isinstance(left_node, Leaf) and \ left_node.value == '__metaclass__': # We found a assignment to __metaclass__. fixup_simple_stmt(node, i, simple_node) remove_trailing_newline(simple_node) yield (node, i, simple_node) def fixup_indent(suite): """ If an INDENT is followed by a thing with a prefix then nuke the prefix Otherwise we get in trouble when removing __metaclass__ at suite start """ kids = suite.children[::-1] # find the first indent while kids: node = kids.pop() if node.type == token.INDENT: break # find the first Leaf while kids: node = kids.pop() if isinstance(node, Leaf) and node.type != token.DEDENT: if node.prefix: node.prefix = '' return else: kids.extend(node.children[::-1]) class FixMetaclass(fixer_base.BaseFix): BM_compatible = True PATTERN = """ classdef<any*> """ def transform(self, node, results): if not has_metaclass(node): return fixup_parse_tree(node) # find metaclasses, keep the last one last_metaclass = None for suite, i, stmt in find_metas(node): last_metaclass = stmt stmt.remove() text_type = node.children[0].type # always Leaf(nnn, 'class') # figure out what kind of classdef we have if len(node.children) == 7: # Node(classdef, ['class', 'name', '(', arglist, ')', ':', suite]) # 0 1 2 3 4 5 6 if node.children[3].type == syms.arglist: arglist = node.children[3] # Node(classdef, ['class', 'name', '(', 'Parent', ')', ':', suite]) else: parent = node.children[3].clone() arglist = Node(syms.arglist, [parent]) node.set_child(3, arglist) elif len(node.children) == 6: # Node(classdef, ['class', 'name', '(', ')', ':', suite]) # 0 1 2 3 4 5 arglist = Node(syms.arglist, []) node.insert_child(3, arglist) elif len(node.children) == 4: # Node(classdef, ['class', 'name', ':', suite]) # 0 1 2 3 arglist = Node(syms.arglist, []) node.insert_child(2, Leaf(token.RPAR, ')')) node.insert_child(2, arglist) node.insert_child(2, Leaf(token.LPAR, '(')) else: raise ValueError("Unexpected class definition") # now stick the metaclass in the arglist meta_txt = last_metaclass.children[0].children[0] meta_txt.value = 'metaclass' orig_meta_prefix = meta_txt.prefix if arglist.children: arglist.append_child(Leaf(token.COMMA, ',')) meta_txt.prefix = ' ' else: meta_txt.prefix = '' # compact the expression "metaclass = Meta" -> "metaclass=Meta" expr_stmt = last_metaclass.children[0] assert expr_stmt.type == syms.expr_stmt expr_stmt.children[1].prefix = '' expr_stmt.children[2].prefix = '' arglist.append_child(last_metaclass) fixup_indent(suite) # check for empty suite if not suite.children: # one-liner that was just __metaclass_ suite.remove() pass_leaf = Leaf(text_type, 'pass') pass_leaf.prefix = orig_meta_prefix node.append_child(pass_leaf) node.append_child(Leaf(token.NEWLINE, '\n')) elif len(suite.children) > 1 and \ (suite.children[-2].type == token.INDENT and suite.children[-1].type == token.DEDENT): # there was only one line in the class body and it was __metaclass__ pass_leaf = Leaf(text_type, 'pass') suite.insert_child(-1, pass_leaf) suite.insert_child(-1, Leaf(token.NEWLINE, '\n'))
unknown
codeparrot/codeparrot-clean
__author__ = 'tan' from juliabox.jbox_tasks import JBPluginTask from juliabox.interactive import SessContainer from juliabox.srvr_jboxd import jboxd_method from user_cluster import UserCluster class ParallelHousekeep(JBPluginTask): provides = [JBPluginTask.JBP_CLUSTER] @staticmethod def terminate_or_delete_cluster(cluster_id): uc = UserCluster(None, gname=cluster_id) uc.terminate_or_delete() @staticmethod @jboxd_method def do_periodic_task(_mode): active_clusters = UserCluster.list_all_groupids() ParallelHousekeep.log_info("%d active clusters", len(active_clusters)) if len(active_clusters) == 0: return active_sessions = SessContainer.get_active_sessions() for cluster_id in active_clusters: sess_id = "/" + UserCluster.sessname_for_cluster(cluster_id) if sess_id not in active_sessions: ParallelHousekeep.log_info("Session (%s) corresponding to cluster (%s) not found. Terminating cluster.", sess_id, cluster_id) ParallelHousekeep.terminate_or_delete_cluster(cluster_id)
unknown
codeparrot/codeparrot-clean
prelude: | def call(*val) case val in [String => body] [200, {}, [body]] in [Integer => status] [status, {}, [""]] in [Integer, String] => response [response[0], {}, [response[1]]] in [Integer, Hash, String] => response [response[0], response[1], [response[2]]] end end benchmark: first_match: call("ok") second_match: call(401) third_match: call(200, "ok") fourth_match: call(201, {}, "created")
unknown
github
https://github.com/ruby/ruby
benchmark/pm_array.yml
import {ApplicationConfig} from '@angular/core'; import {routes} from './app.routes'; import {provideRouter} from '@angular/router'; import {provideProtractorTestingSupport} from '@angular/platform-browser'; import {provideAnimations} from '@angular/platform-browser/animations'; export const appConfig: ApplicationConfig = { providers: [ // needed for supporting e2e tests provideProtractorTestingSupport(), provideRouter(routes), provideAnimations(), ], };
typescript
github
https://github.com/angular/angular
adev/src/content/examples/animations/src/app/app.config.ts
__author__ = 'amelie' from math import sqrt from mock import Mock import unittest2 import numpy from preimage.inference.bound_calculator import BoundCalculatorMock from preimage.inference.node import MaxNode from preimage.inference.node_creator import NodeCreator class TestNodeCreator(unittest2.TestCase): def setUp(self): self.setup_alphabet() self.setup_node_creator_one_gram() self.setup_node_creator_two_gram() self.setup_nodes() def setup_alphabet(self): self.one_grams = ['a', 'b', 'c'] self.two_grams = ['aa', 'ab', 'ba', 'bb'] def setup_node_creator_one_gram(self): min_bound_calculator_mock = Mock() min_bound_calculator_mock.get_start_node_real_values.return_value = numpy.array([1, 2, 3], dtype=numpy.float64) min_bound_calculator_mock.get_start_node_bounds.return_value = numpy.array([4, 5, 6], dtype=numpy.float64) min_bound_calculator_mock.compute_bound.return_value = {'real_value': 1, 'bound_value': 2} min_bound_calculator = BoundCalculatorMock(min_bound_calculator_mock) max_bound_calculator_mock = Mock() max_bound_calculator_mock.get_start_node_real_values.return_value = numpy.array([7, 8, 9], dtype=numpy.float64) max_bound_calculator_mock.get_start_node_bounds.return_value = numpy.array([10, 11, 12], dtype=numpy.float64) max_bound_calculator_mock.compute_bound.return_value = {'real_value': 3, 'bound_value': 4} max_bound_calculator = BoundCalculatorMock(max_bound_calculator_mock) self.node_creator_one_gram = NodeCreator(min_bound_calculator, max_bound_calculator, self.one_grams) def setup_node_creator_two_gram(self): min_bound_calculator_mock = Mock() min_bound_calculator_mock.get_start_node_real_values.return_value = numpy.array([1, 3, 5, 7], dtype=numpy.float64) min_bound_calculator_mock.get_start_node_bounds.return_value = numpy.array([9, 11, 13, 15], dtype=numpy.float64) min_bound_calculator_mock.compute_bound.return_value = {'real_value': 0.1, 'bound_value': 0.2} min_bound_calculator = BoundCalculatorMock(min_bound_calculator_mock) max_bound_calculator_mock = Mock() max_bound_calculator_mock.get_start_node_real_values.return_value = numpy.array([2, 4, 6, 8], dtype=numpy.float64) max_bound_calculator_mock.get_start_node_bounds.return_value = numpy.array([10, 12, 14, 16], dtype=numpy.float64) max_bound_calculator_mock.compute_bound.return_value = {'real_value': 0.3, 'bound_value': 0.4} max_bound_calculator = BoundCalculatorMock(max_bound_calculator_mock) self.node_creator_two_gram = NodeCreator(min_bound_calculator, max_bound_calculator, self.two_grams) def setup_nodes(self): self.a_b_c_nodes_length_one = [MaxNode('a', 10. / sqrt(4), 1., 7.), MaxNode('b', 11. / sqrt(5), 2., 8.), MaxNode('c', 12. / sqrt(6), 3., 9.)] self.aa_ab_ba_bb = [MaxNode('aa', 10. / sqrt(9), 1, 2), MaxNode('ab', 12 / sqrt(11), 3, 4), MaxNode('ba', 14. / sqrt(13), 5, 6), MaxNode('bb', 16 / sqrt(15), 7, 8)] self.aa_parent_node = MaxNode('a', 5. / sqrt(2), 1, 2) self.aa_node_one_gram = MaxNode('aa', 4. / sqrt(2), 1, 3) self.abc_parent_node = MaxNode('bc', 2., 1, 3) self.abc_node_two_gram = MaxNode('abc', 0.4 / sqrt(0.2), 0.1, 0.3) def test_one_gram_length_one_get_start_nodes_returns_expected_nodes(self): start_nodes = self.node_creator_one_gram.get_start_nodes_python(1) for node_index, start_node in enumerate(start_nodes): with self.subTest(y=start_node.y): self.assertEqual(start_node, self.a_b_c_nodes_length_one[node_index], msg=self.get_message(start_node, self.a_b_c_nodes_length_one[node_index])) def test_two_gram_length_three_get_start_nodes_returns_expected_nodes(self): start_nodes = self.node_creator_two_gram.get_start_nodes_python(3) for node_index, start_node in enumerate(start_nodes): with self.subTest(y=start_node.y): self.assertEqual(start_node, self.aa_ab_ba_bb[node_index], msg=self.get_message(start_node, self.aa_ab_ba_bb[node_index])) def test_one_gram_create_node_returns_expected_node(self): length = 3 node = self.node_creator_one_gram.create_node_python('aa', self.aa_parent_node, length) self.assertEqual(node, self.aa_node_one_gram, msg=self.get_message(node, self.aa_node_one_gram)) def test_two_gram_create_node_returns_expected_node(self): length = 4 node = self.node_creator_two_gram.create_node_python('abc', self.abc_parent_node, length) self.assertEqual(node, self.abc_node_two_gram, msg=self.get_message(node, self.abc_node_two_gram)) def get_message(self, actual, expected): return "{} != {}".format(str(actual), str(expected)) if __name__ == '__main__': unittest2.main()
unknown
codeparrot/codeparrot-clean
""" Creates permissions for all installed apps that need permissions. """ from __future__ import unicode_literals import getpass import unicodedata from django.apps import apps from django.contrib.auth import models as auth_app, get_permission_codename from django.core import exceptions from django.core.management.base import CommandError from django.db import DEFAULT_DB_ALIAS, router from django.db.models import signals from django.utils.encoding import DEFAULT_LOCALE_ENCODING from django.utils import six def _get_all_permissions(opts, ctype): """ Returns (codename, name) for all permissions in the given opts. """ builtin = _get_builtin_permissions(opts) custom = list(opts.permissions) _check_permission_clashing(custom, builtin, ctype) return builtin + custom def _get_builtin_permissions(opts): """ Returns (codename, name) for all autogenerated permissions. By default, this is ('add', 'change', 'delete') """ perms = [] for action in opts.default_permissions: perms.append((get_permission_codename(action, opts), 'Can %s %s' % (action, opts.verbose_name_raw))) return perms def _check_permission_clashing(custom, builtin, ctype): """ Check that permissions for a model do not clash. Raises CommandError if there are duplicate permissions. """ pool = set() builtin_codenames = set(p[0] for p in builtin) for codename, _name in custom: if codename in pool: raise CommandError( "The permission codename '%s' is duplicated for model '%s.%s'." % (codename, ctype.app_label, ctype.model_class().__name__)) elif codename in builtin_codenames: raise CommandError( "The permission codename '%s' clashes with a builtin permission " "for model '%s.%s'." % (codename, ctype.app_label, ctype.model_class().__name__)) pool.add(codename) def create_permissions(app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, **kwargs): if not app_config.models_module: return try: Permission = apps.get_model('auth', 'Permission') except LookupError: return if not router.allow_migrate(using, Permission): return from django.contrib.contenttypes.models import ContentType # This will hold the permissions we're looking for as # (content_type, (codename, name)) searched_perms = list() # The codenames and ctypes that should exist. ctypes = set() for klass in app_config.get_models(): # Force looking up the content types in the current database # before creating foreign keys to them. ctype = ContentType.objects.db_manager(using).get_for_model(klass) ctypes.add(ctype) for perm in _get_all_permissions(klass._meta, ctype): searched_perms.append((ctype, perm)) # Find all the Permissions that have a content_type for a model we're # looking for. We don't need to check for codenames since we already have # a list of the ones we're going to create. all_perms = set(Permission.objects.using(using).filter( content_type__in=ctypes, ).values_list( "content_type", "codename" )) perms = [ Permission(codename=codename, name=name, content_type=ct) for ct, (codename, name) in searched_perms if (ct.pk, codename) not in all_perms ] # Validate the permissions before bulk_creation to avoid cryptic # database error when the verbose_name is longer than 50 characters permission_name_max_length = Permission._meta.get_field('name').max_length verbose_name_max_length = permission_name_max_length - 11 # len('Can change ') prefix for perm in perms: if len(perm.name) > permission_name_max_length: raise exceptions.ValidationError( "The verbose_name of %s is longer than %s characters" % ( perm.content_type, verbose_name_max_length, ) ) Permission.objects.using(using).bulk_create(perms) if verbosity >= 2: for perm in perms: print("Adding permission '%s'" % perm) def get_system_username(): """ Try to determine the current system user's username. :returns: The username as a unicode string, or an empty string if the username could not be determined. """ try: result = getpass.getuser() except (ImportError, KeyError): # KeyError will be raised by os.getpwuid() (called by getuser()) # if there is no corresponding entry in the /etc/passwd file # (a very restricted chroot environment, for example). return '' if six.PY2: try: result = result.decode(DEFAULT_LOCALE_ENCODING) except UnicodeDecodeError: # UnicodeDecodeError - preventive treatment for non-latin Windows. return '' return result def get_default_username(check_db=True): """ Try to determine the current system user's username to use as a default. :param check_db: If ``True``, requires that the username does not match an existing ``auth.User`` (otherwise returns an empty string). :returns: The username, or an empty string if no username can be determined. """ # If the User model has been swapped out, we can't make any assumptions # about the default user name. if auth_app.User._meta.swapped: return '' default_username = get_system_username() try: default_username = (unicodedata.normalize('NFKD', default_username) .encode('ascii', 'ignore').decode('ascii') .replace(' ', '').lower()) except UnicodeDecodeError: return '' # Run the username validator try: auth_app.User._meta.get_field('username').run_validators(default_username) except exceptions.ValidationError: return '' # Don't return the default username if it is already taken. if check_db and default_username: try: auth_app.User._default_manager.get(username=default_username) except auth_app.User.DoesNotExist: pass else: return '' return default_username signals.post_migrate.connect(create_permissions, dispatch_uid="django.contrib.auth.management.create_permissions")
unknown
codeparrot/codeparrot-clean
from vint.ast.node_type import NodeType from vint.linting.level import Level from vint.linting.policy.abstract_policy import AbstractPolicy from vint.linting.policy_registry import register_policy from vint.ast.plugin.scope_plugin import ExplicityOfScopeVisibility @register_policy class ProhibitImplicitScopeVariable(AbstractPolicy): def __init__(self): super(ProhibitImplicitScopeVariable, self).__init__() self.reference = 'Anti-pattern of vimrc (Scope of identifier)' self.level = Level.STYLE_PROBLEM def listen_node_types(self): return [NodeType.IDENTIFIER] def is_valid(self, identifier, lint_context): """ Whether the identifier has a scope prefix. """ scope_plugin = lint_context['plugins']['scope'] explicity = scope_plugin.get_explicity_of_scope_visibility(identifier) is_valid = (scope_plugin.is_function_identifier(identifier) or explicity is not ExplicityOfScopeVisibility.IMPLICIT) if not is_valid: self._make_description(identifier, scope_plugin) return is_valid def _make_description(self, identifier, scope_plugin): self.description = 'Make the scope explicit like `{good_example}`'.format( good_example=scope_plugin.normalize_variable_name(identifier) )
unknown
codeparrot/codeparrot-clean
from django.test import TestCase from django.utils.translation import ugettext_lazy as _ from userena import forms from userena import settings as userena_settings from userena.utils import get_user_model class SignupFormTests(TestCase): """ Test the signup form. """ fixtures = ['users'] def test_signup_form(self): """ Test that the ``SignupForm`` checks for unique usernames and unique e-mail addresses. """ invalid_data_dicts = [ # Non-alphanumeric username. {'data': {'username': 'foo@bar', 'email': 'foo@example.com', 'password': 'foo', 'password2': 'foo', 'tos': 'on'}, 'error': ('username', [_(u'Username must contain only letters, numbers, dots and underscores.')])}, # Password is not the same {'data': {'username': 'katy-', 'email': 'katy@newexample.com', 'password1': 'foo', 'password2': 'foo2', 'tos': 'on'}, 'error': ('__all__', [_(u'The two password fields didn\'t match.')])}, # Already taken username {'data': {'username': 'john', 'email': 'john@newexample.com', 'password1': 'foo', 'password2': 'foo', 'tos': 'on'}, 'error': ('username', [_(u'This username is already taken.')])}, # Forbidden username {'data': {'username': 'SignUp', 'email': 'foo@example.com', 'password': 'foo', 'password2': 'foo2', 'tos': 'on'}, 'error': ('username', [_(u'This username is not allowed.')])}, # Already taken email {'data': {'username': 'alice', 'email': 'john@example.com', 'password': 'foo', 'password2': 'foo', 'tos': 'on'}, 'error': ('email', [_(u'This email is already in use. Please supply a different email.')])}, ] for invalid_dict in invalid_data_dicts: form = forms.SignupForm(data=invalid_dict['data']) self.failIf(form.is_valid()) self.assertEqual(form.errors[invalid_dict['error'][0]], invalid_dict['error'][1]) # And finally, a valid form. form = forms.SignupForm(data={'username': 'foo.bla', 'email': 'foo@example.com', 'password1': 'foo', 'password2': 'foo', 'tos': 'on'}) self.failUnless(form.is_valid()) class AuthenticationFormTests(TestCase): """ Test the ``AuthenticationForm`` """ fixtures = ['users',] def test_signin_form(self): """ Check that the ``SigninForm`` requires both identification and password """ invalid_data_dicts = [ {'data': {'identification': '', 'password': 'inhalefish'}, 'error': ('identification', [u'Either supply us with your email or username.'])}, {'data': {'identification': 'john', 'password': 'inhalefish'}, 'error': ('__all__', [u'Please enter a correct username or email and password. Note that both fields are case-sensitive.'])} ] for invalid_dict in invalid_data_dicts: form = forms.AuthenticationForm(data=invalid_dict['data']) self.failIf(form.is_valid()) self.assertEqual(form.errors[invalid_dict['error'][0]], invalid_dict['error'][1]) valid_data_dicts = [ {'identification': 'john', 'password': 'blowfish'}, {'identification': 'john@example.com', 'password': 'blowfish'} ] for valid_dict in valid_data_dicts: form = forms.AuthenticationForm(valid_dict) self.failUnless(form.is_valid()) def test_signin_form_email(self): """ Test that the signin form has a different label is ``USERENA_WITHOUT_USERNAME`` is set to ``True`` """ userena_settings.USERENA_WITHOUT_USERNAMES = True form = forms.AuthenticationForm(data={'identification': "john", 'password': "blowfish"}) correct_label = "Email" self.assertEqual(form.fields['identification'].label, correct_label) # Restore default settings userena_settings.USERENA_WITHOUT_USERNAMES = False class SignupFormOnlyEmailTests(TestCase): """ Test the :class:`SignupFormOnlyEmail`. This is the same form as :class:`SignupForm` but doesn't require an username for a successfull signup. """ fixtures = ['users'] def test_signup_form_only_email(self): """ Test that the form has no username field. And that the username is generated in the save method """ valid_data = {'email': 'hans@gretel.com', 'password1': 'blowfish', 'password2': 'blowfish'} form = forms.SignupFormOnlyEmail(data=valid_data) # Should have no username field self.failIf(form.fields.get('username', False)) # Form should be valid. self.failUnless(form.is_valid()) # Creates an unique username user = form.save() self.failUnless(len(user.username), 5) class ChangeEmailFormTests(TestCase): """ Test the ``ChangeEmailForm`` """ fixtures = ['users'] def test_change_email_form(self): user = get_user_model().objects.get(pk=1) invalid_data_dicts = [ # No change in e-mail address {'data': {'email': 'john@example.com'}, 'error': ('email', [u'You\'re already known under this email.'])}, # An e-mail address used by another {'data': {'email': 'jane@example.com'}, 'error': ('email', [u'This email is already in use. Please supply a different email.'])}, ] for invalid_dict in invalid_data_dicts: form = forms.ChangeEmailForm(user, data=invalid_dict['data']) self.failIf(form.is_valid()) self.assertEqual(form.errors[invalid_dict['error'][0]], invalid_dict['error'][1]) # Test a valid post form = forms.ChangeEmailForm(user, data={'email': 'john@newexample.com'}) self.failUnless(form.is_valid()) def test_form_init(self): """ The form must be initialized with a ``User`` instance. """ self.assertRaises(TypeError, forms.ChangeEmailForm, None) class EditAccountFormTest(TestCase): """ Test the ``EditAccountForm`` """ pass
unknown
codeparrot/codeparrot-clean
imports: - { resource: ../config/default.yml } framework: type_info: ~ json_streamer: default_options: include_null_properties: true custom_key: custom_value services: _defaults: autoconfigure: true json_streamer.stream_writer.alias: alias: json_streamer.stream_writer public: true json_streamer.stream_reader.alias: alias: json_streamer.stream_reader public: true json_streamer.cache_warmer.streamer.alias: alias: .json_streamer.cache_warmer.streamer public: true Symfony\Bundle\FrameworkBundle\Tests\Functional\app\JsonStreamer\Dto\Dummy: ~ Symfony\Bundle\FrameworkBundle\Tests\Functional\app\JsonStreamer\StringToRangeValueTransformer: ~ Symfony\Bundle\FrameworkBundle\Tests\Functional\app\JsonStreamer\RangeToStringValueTransformer: ~
unknown
github
https://github.com/symfony/symfony
src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/JsonStreamer/config.yml
# Copyright 2015-2017 Capital One Services, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed 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 __future__ import absolute_import, division, print_function, unicode_literals from c7n.manager import resources from c7n.query import QueryResourceManager @resources.register('support-case') class SupportCase(QueryResourceManager): class resource_type(object): service = 'support' enum_spec = ('describe_cases', 'q', None) filter_name = 'caseIdList' filter_type = 'list' id = 'caseId' name = 'displayId' date = 'timeCreated' dimension = None
unknown
codeparrot/codeparrot-clean
from datetime import timedelta from flask import make_response, request, current_app from functools import update_wrapper def crossdomain(origin=None, methods=None, headers=None, max_age=21600, attach_to_all=True, automatic_options=True): if methods is not None: methods = ', '.join(sorted(x.upper() for x in methods)) if headers is not None and not isinstance(headers, basestring): headers = ', '.join(x.upper() for x in headers) if not isinstance(origin, basestring): origin = ', '.join(origin) if isinstance(max_age, timedelta): max_age = max_age.total_seconds() def get_methods(): if methods is not None: return methods options_resp = current_app.make_default_options_response() return options_resp.headers['allow'] def decorator(f): def wrapped_function(*args, **kwargs): if automatic_options and request.method == 'OPTIONS': resp = current_app.make_default_options_response() else: resp = make_response(f(*args, **kwargs)) if not attach_to_all and request.method != 'OPTIONS': return resp h = resp.headers h['Access-Control-Allow-Origin'] = origin h['Access-Control-Allow-Methods'] = get_methods() h['Access-Control-Max-Age'] = str(max_age) if headers is not None: h['Access-Control-Allow-Headers'] = headers return resp f.provide_automatic_options = False return update_wrapper(wrapped_function, f) return decorator
unknown
codeparrot/codeparrot-clean
import operator import sys import traceback from pprint import pprint import random import collections def is_iterable(item): return isinstance(item, collections.Iterable) and not isinstance(item,str) def is_not_iterable(item): return not isinstance(item, collections.Iterable) def flatten(x): if isinstance(x, collections.Iterable) and not isinstance(x, str): return [a for i in x for a in flatten(i)] else: return [x] def hashify(item): if is_iterable(item): return tuple([hashify(i) for i in item]) else: return item def brokify(item): if is_iterable(item): return Broken(*[brokify(i) for i in item]) else: return item class Broken(list): for i in ['mul', 'add', 'sub', 'mod', 'div', 'pow']: exec("def __{operation}__(self,operand): return self.op_check(operand)".format(operation=i)) for i in ['len', 'sum', 'max', 'min', 'str', 'int']: exec('@property\ndef {function}(self): return {function}(self)'.format(function=i)) del i def __init__(self, *args): super(Broken, self).__init__([]) self.__dict__['set'] = set() if is_iterable(args): self[:] += args else: super(Broken, self).append(args) self.__dict__['set'] = set(hashify(self[:])) # else: # pass# self.append(*args) def op_transform(self, operand): func_name = traceback.extract_stack()[-3][2][2:-2] # eg mul add ect self[:] = [eval("operator.{func_name}(i,{operand})".format(func_name=func_name, operand=operand)) for i in self] def op_list(self, l): func_name = traceback.extract_stack()[-3][2][2:-2] self[:] = [eval("operator.{func_name}(a,b)".format(func_name=func_name)) for a, b in zip(self, l)] def op_check(self, operand): if isinstance(operand, list): self.op_list(operand) elif isinstance(operand, int): self.op_transform(operand) return self def __contains__(self, item): return item in self.set def append(self, *args): self[:] += brokify(args) for i in args: self.set.add(i if isinstance(i, collections.Hashable) else hashify(i)) return self def __and__(self, item): return list(self.set & set(item)) def __or__(self, item): return list(self.set | set(item)) @property def shuffle(self): random.shuffle(self) return self def __int__(self): return int(''.join(str(i) for i in self)) def unique(self): self[:] = list(self.set) return self def difference(self, item): return list(self.set - set(item)) def symmetric_difference(self, item): return list(self.set ^ set(item)) @property def clear(self): self[:] = [] self.__dict__['set'] = set() return self @property def sort(self): self[:] = sorted(self) return self def add(self, item): if hashify(item) not in self.set: self.append(item) return self def remove(self, item): for i in self: if i == item: a = list(self[:]) a.remove(i) if i not in self: self.set.remove(i) self[:] = a break return self def remove_all(self, item): while item in self.set: self.remove(item) return self def _get_index(self,item): if self.flen > 3: for i,j in enumerate(self): if hasattr(j, '__iter__') and j[0] == item: temp = self[i][1:][0] if is_not_iterable(temp): self.__dict__['index_num'] = i pass else: self.__dict__['index_num'] = i pass elif self.flen <= 3 and not self.flen == 2 and self.len == 2: temp = self[1:][0] self.__dict__['index_num'] = self.index(temp) pass elif self.flen <= 3 and not self.flen == 2: temp = self[1:][0] self.__dict__['index_num'] = self.index(temp) pass elif self.flen == 2: pass def __getattr__(self, item): if self.flen > 3: for i,j in enumerate(self): if hasattr(j, '__iter__') and j[0] == item: temp = self[i][1:][0] if is_not_iterable(temp): self.__dict__['index_num'] = i return Broken(temp)[0] else: self.__dict__['index_num'] = i return Broken(*temp) elif self.flen <= 3 and not self.flen == 2 and self.len == 2: temp = self[1:][0] self.__dict__['index_num'] = self.index(temp) return Broken(*temp) elif self.flen <= 3 and not self.flen == 2: temp = self[1:][0] self.__dict__['index_num'] = self.index(temp) return Broken(*temp) elif self.flen == 2: return Broken(self[1:][0])[0] def __getitem__(self, item): #super(Broken, self).__getitem__(item) if isinstance(item, int): return self[:][item] elif isinstance(item,str): for i, j in enumerate(self): if self.len == 2 and isinstance(j, str): return brokify(self[:][1]) elif is_iterable(j): if isinstance(j[0], str): return brokify(self[:][i][1]) @property def flatten(self): if is_iterable(self): return Broken(*[a for i in self for a in flatten(i)]) else: return self @property def flen(self): return self.flatten.len def __setattr__(self, name, value): try: #super(Broken, self).__setattr__(name, value) #self.__dict__[name] = value self.__dict__[name] = brokify(value) self._get_index(name) if is_iterable(value): # print self.index_num # print self[self.index_num] self[self.index_num][1] = brokify(value) else: # print self.index_num # print self[self.index_num] self[self.index_num][1] = brokify(value) except: pass def __setitem__(self, name, value): try: #super(Broken, self).__setattr__(name, value) #self.__dict__[name] = value self.__dict__[name] = brokify(value) self._get_index(name) if is_iterable(value): # print self.index_num # print self[self.index_num] self[self.index_num][1] = brokify(value) else: # print self.index_num # print self[self.index_num] self[self.index_num][1] = brokify(value) except: pass if __name__ == '__main__': a = Broken(1, 2, 3, ['ey', ['i', ['ju7', 5]]])
unknown
codeparrot/codeparrot-clean
// Copyright (c) HashiCorp, Inc. // SPDX-License-Identifier: BUSL-1.1 package arguments // View represents the global command-line arguments which configure the view. type View struct { // NoColor is used to disable the use of terminal color codes in all // output. NoColor bool // CompactWarnings is used to coalesce duplicate warnings, to reduce the // level of noise when multiple instances of the same warning are raised // for a configuration. CompactWarnings bool } // ParseView processes CLI arguments, returning a View value and a // possibly-modified slice of arguments. If any of the supported flags are // found, they will be removed from the slice. func ParseView(args []string) (*View, []string) { common := &View{} // Keep track of the length of the returned slice. When we find an // argument we support, i will not be incremented. i := 0 for _, v := range args { switch v { case "-no-color": common.NoColor = true case "-compact-warnings": common.CompactWarnings = true default: // Unsupported argument: move left to the current position, and // increment the index. args[i] = v i++ } } // Reduce the slice to the number of unsupported arguments. Any remaining // to the right of i have already been moved left. args = args[:i] return common, args }
go
github
https://github.com/hashicorp/terraform
internal/command/arguments/view.go
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class OperationStatusResponse(Model): """Operation status response. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: Operation ID :vartype name: str :ivar status: Operation status :vartype status: str :ivar start_time: Start time of the operation :vartype start_time: datetime :ivar end_time: End time of the operation :vartype end_time: datetime :ivar error: Api error :vartype error: ~azure.mgmt.compute.v2016_04_30_preview.models.ApiError """ _validation = { 'name': {'readonly': True}, 'status': {'readonly': True}, 'start_time': {'readonly': True}, 'end_time': {'readonly': True}, 'error': {'readonly': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'status': {'key': 'status', 'type': 'str'}, 'start_time': {'key': 'startTime', 'type': 'iso-8601'}, 'end_time': {'key': 'endTime', 'type': 'iso-8601'}, 'error': {'key': 'error', 'type': 'ApiError'}, } def __init__(self, **kwargs): super(OperationStatusResponse, self).__init__(**kwargs) self.name = None self.status = None self.start_time = None self.end_time = None self.error = None
unknown
codeparrot/codeparrot-clean
''' pathmtu.py Created on: May 14, 2009 Authors: dh $LastChangedBy$ $LastChangedDate$ $Revision$ (C) 2008-2009 by Computer Networks and Internet, University of Tuebingen This file is part of UNISONO Unified Information Service for Overlay Network Optimization. UNISONO is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. UNISONO is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with UNISONO. If not, see <http://www.gnu.org/licenses/>. ''' import logging from unisono.mmplugins import mmtemplates from ctypes import * from os import path from unisono.dataitem import DataItem class PathMTUResult(Structure): ''' Result structure for the PathMTU module ''' _fields_ = [('PATHMTU', c_int), ('HOPCOUNT', c_int), ('error', c_int), ('errortext', c_char_p)] class PathMTU(mmtemplates.MMcTemplate): ''' Wrapper class for the PathMTU module ''' logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) def __init__(self, *args): ''' Constructor ''' super().__init__(*args) self.libfile = path.join(path.dirname(__file__), 'libPathMTU.so') self.cresstruct = PathMTUResult() self.cost = 10000 self.dataitems = [DataItem('PATHMTU',2,600,1200), DataItem('HOPCOUNT',2,600,1200)] self.load_library() def checkrequest(self, request): return True
unknown
codeparrot/codeparrot-clean
# # Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. # Use of this file is governed by the BSD 3-clause license that # can be found in the LICENSE.txt file in the project root. #/ # Map a predicate to a predicted alternative.#/ from io import StringIO from antlr4.atn.ATNConfigSet import ATNConfigSet class PredPrediction(object): def __init__(self, pred, alt): self.alt = alt self.pred = pred def __str__(self): return unicode(self) def __unicode__(self): return u"(" + unicode(self.pred) + u", " + unicode(self.alt) + u")" # A DFA state represents a set of possible ATN configurations. # As Aho, Sethi, Ullman p. 117 says "The DFA uses its state # to keep track of all possible states the ATN can be in after # reading each input symbol. That is to say, after reading # input a1a2..an, the DFA is in a state that represents the # subset T of the states of the ATN that are reachable from the # ATN's start state along some path labeled a1a2..an." # In conventional NFA&rarr;DFA conversion, therefore, the subset T # would be a bitset representing the set of states the # ATN could be in. We need to track the alt predicted by each # state as well, however. More importantly, we need to maintain # a stack of states, tracking the closure operations as they # jump from rule to rule, emulating rule invocations (method calls). # I have to add a stack to simulate the proper lookahead sequences for # the underlying LL grammar from which the ATN was derived. # # <p>I use a set of ATNConfig objects not simple states. An ATNConfig # is both a state (ala normal conversion) and a RuleContext describing # the chain of rules (if any) followed to arrive at that state.</p> # # <p>A DFA state may have multiple references to a particular state, # but with different ATN contexts (with same or different alts) # meaning that state was reached via a different set of rule invocations.</p> #/ class DFAState(object): def __init__(self, stateNumber=-1, configs=ATNConfigSet()): self.stateNumber = stateNumber self.configs = configs # {@code edges[symbol]} points to target of symbol. Shift up by 1 so (-1) # {@link Token#EOF} maps to {@code edges[0]}. self.edges = None self.isAcceptState = False # if accept state, what ttype do we match or alt do we predict? # This is set to {@link ATN#INVALID_ALT_NUMBER} when {@link #predicates}{@code !=null} or # {@link #requiresFullContext}. self.prediction = 0 self.lexerActionExecutor = None # Indicates that this state was created during SLL prediction that # discovered a conflict between the configurations in the state. Future # {@link ParserATNSimulator#execATN} invocations immediately jumped doing # full context prediction if this field is true. self.requiresFullContext = False # During SLL parsing, this is a list of predicates associated with the # ATN configurations of the DFA state. When we have predicates, # {@link #requiresFullContext} is {@code false} since full context prediction evaluates predicates # on-the-fly. If this is not null, then {@link #prediction} is # {@link ATN#INVALID_ALT_NUMBER}. # # <p>We only use these for non-{@link #requiresFullContext} but conflicting states. That # means we know from the context (it's $ or we don't dip into outer # context) that it's an ambiguity not a conflict.</p> # # <p>This list is computed by {@link ParserATNSimulator#predicateDFAState}.</p> self.predicates = None # Get the set of all alts mentioned by all ATN configurations in this # DFA state. def getAltSet(self): if self.configs is not None: return set(cfg.alt for cfg in self.configs) or None return None def __hash__(self): return hash(self.configs) # Two {@link DFAState} instances are equal if their ATN configuration sets # are the same. This method is used to see if a state already exists. # # <p>Because the number of alternatives and number of ATN configurations are # finite, there is a finite number of DFA states that can be processed. # This is necessary to show that the algorithm terminates.</p> # # <p>Cannot test the DFA state numbers here because in # {@link ParserATNSimulator#addDFAState} we need to know if any other state # exists that has this exact set of ATN configurations. The # {@link #stateNumber} is irrelevant.</p> def __eq__(self, other): # compare set of ATN configurations in this set with other if self is other: return True elif not isinstance(other, DFAState): return False else: return self.configs==other.configs def __str__(self): return unicode(self) def __unicode__(self): with StringIO() as buf: buf.write(unicode(self.stateNumber)) buf.write(u":") buf.write(unicode(self.configs)) if self.isAcceptState: buf.write(u"=>") if self.predicates is not None: buf.write(unicode(self.predicates)) else: buf.write(unicode(self.prediction)) return buf.getvalue()
unknown
codeparrot/codeparrot-clean
from django.conf import settings from django.shortcuts import get_object_or_404, redirect from django.template.response import TemplateResponse from django.utils.translation import get_language_from_request from oioioi.base.permissions import enforce_condition, is_superuser from oioioi.newsfeed.forms import NewsLanguageVersionFormset from oioioi.newsfeed.models import News, NewsLanguageVersion @enforce_condition(is_superuser) def add_news_view(request): if request.method == 'POST': formset = NewsLanguageVersionFormset(request.POST) if formset.is_valid(): instances = formset.save(commit=False) news = News() news.save() for news_language_version in instances: news_language_version.news = news news_language_version.save() for news_language_version in formset.deleted_objects: news_language_version.delete() return redirect('newsfeed') else: current_language = get_language_from_request(request) formset = NewsLanguageVersionFormset( initial=[ {'language': lang_short, 'DELETE': lang_short != current_language} for lang_short, _ in settings.LANGUAGES ], queryset=NewsLanguageVersion.objects.none(), ) return TemplateResponse(request, 'newsfeed/news-add.html', {'formset': formset}) @enforce_condition(is_superuser) def delete_news_view(request, news_id): news_item = get_object_or_404(News, id=news_id) news_item.delete() return redirect('newsfeed') @enforce_condition(is_superuser) def edit_news_view(request, news_id): news_item = get_object_or_404(News, id=news_id) if request.method == 'POST': formset = NewsLanguageVersionFormset(request.POST) if formset.is_valid(): instances = formset.save(commit=False) for news_language_version in instances: news_language_version.news = news_item news_language_version.save() for news_language_version in formset.deleted_objects: news_language_version.delete() return redirect('newsfeed') else: current_language = get_language_from_request(request) languages = [lang_short for lang_short, _ in settings.LANGUAGES] queryset = NewsLanguageVersion.objects.filter(news=news_item) for news_language_version in queryset: languages.remove(news_language_version.language) formset = NewsLanguageVersionFormset( initial=[ {'language': lang, 'DELETE': lang != current_language} for lang in languages ], queryset=NewsLanguageVersion.objects.filter(news=news_item), ) return TemplateResponse(request, 'newsfeed/news-edit.html', {'formset': formset}) def newsfeed_view(request): news_list = News.objects.order_by('-date').prefetch_related('versions') news_version_list = [] for news in news_list: news_version_list.append(news.get_content(request)) return TemplateResponse( request, 'newsfeed/newsfeed-view.html', {'news_version_list': news_version_list} )
unknown
codeparrot/codeparrot-clean
# Copyright (c) 2017 Presslabs SRL # # 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 __future__ import absolute_import, unicode_literals import uuid import logging from decimal import Decimal from annoying.functions import get_object_or_None from django.core.serializers.json import DjangoJSONEncoder from django_fsm import FSMField, post_transition, transition from django.core.exceptions import ValidationError from django.core.validators import MinValueValidator from django.db import models, transaction from django.db.models import Q, JSONField from django.db.models.signals import post_save from django.dispatch import receiver from django.utils import timezone from django.utils.encoding import force_str from django.utils.translation import gettext_lazy as _ from silver.models import Invoice, Proforma from silver.models.transactions.codes import FAIL_CODES, REFUND_CODES, CANCEL_CODES from silver.utils.international import currencies from silver.utils.models import AutoDateTimeField, AutoCleanModelMixin logger = logging.getLogger(__name__) class Transaction(AutoCleanModelMixin, models.Model): _provider = None amount = models.DecimalField( decimal_places=2, max_digits=12, validators=[MinValueValidator(Decimal('0.00'))] ) currency = models.CharField( choices=currencies, max_length=4, help_text='The currency used for billing.' ) class Meta: ordering = ['-id'] class States: Initial = 'initial' Pending = 'pending' Settled = 'settled' Failed = 'failed' Canceled = 'canceled' Refunded = 'refunded' @classmethod def as_list(cls): return [getattr(cls, state) for state in vars(cls).keys() if state[0].isupper()] @classmethod def as_choices(cls): return ( (state, _(state.capitalize())) for state in cls.as_list() ) external_reference = models.CharField(max_length=256, null=True, blank=True) data = JSONField(default=dict, null=True, blank=True, encoder=DjangoJSONEncoder) state = FSMField(max_length=8, choices=States.as_choices(), default=States.Initial) proforma = models.ForeignKey("BillingDocumentBase", null=True, blank=True, on_delete=models.SET_NULL, related_name='proforma_transactions') invoice = models.ForeignKey("BillingDocumentBase", null=True, blank=True, on_delete=models.SET_NULL, related_name='invoice_transactions') payment_method = models.ForeignKey('PaymentMethod', on_delete=models.PROTECT) uuid = models.UUIDField(default=uuid.uuid4) valid_until = models.DateTimeField(null=True, blank=True) last_access = models.DateTimeField(null=True, blank=True) created_at = models.DateTimeField(default=timezone.now) updated_at = AutoDateTimeField(default=timezone.now) fail_code = models.CharField( choices=[(code, code) for code in FAIL_CODES.keys()], max_length=64, null=True, blank=True ) refund_code = models.CharField( choices=[(code, code) for code in REFUND_CODES.keys()], max_length=32, null=True, blank=True ) cancel_code = models.CharField( choices=[(code, code) for code in CANCEL_CODES.keys()], max_length=32, null=True, blank=True ) @property def final_fields(self): fields = ['proforma', 'invoice', 'uuid', 'payment_method', 'amount', 'currency', 'created_at'] return fields def __init__(self, *args, **kwargs): self.form_class = kwargs.pop('form_class', None) super(Transaction, self).__init__(*args, **kwargs) @transition(field=state, source=States.Initial, target=States.Pending) def process(self): pass @transition(field=state, source=[States.Initial, States.Pending], target=States.Settled) def settle(self): pass @transition(field=state, source=[States.Initial, States.Pending], target=States.Canceled) def cancel(self, cancel_code='default', cancel_reason='Unknown cancel reason'): self.cancel_code = cancel_code logger.error(str(cancel_reason)) @transition(field=state, source=[States.Initial, States.Pending], target=States.Failed) def fail(self, fail_code='default', fail_reason='Unknown fail reason'): self.fail_code = fail_code logger.error(str(fail_reason)) @transition(field=state, source=States.Settled, target=States.Refunded) def refund(self, refund_code='default', refund_reason='Unknown refund reason'): self.refund_code = refund_code logger.error(str(refund_reason)) @transaction.atomic() def save(self, *args, **kwargs): if not self.pk: # Creating a new Transaction so we lock the DB rows for related billing documents and # transactions if self.proforma: Proforma.objects.select_for_update().filter(pk=self.proforma.pk) elif self.invoice: Invoice.objects.select_for_update().filter(pk=self.invoice.pk) Transaction.objects.select_for_update().filter(Q(proforma=self.proforma) | Q(invoice=self.invoice)) super(Transaction, self).save(*args, **kwargs) def clean(self): # Validate documents document = self.document if not document: raise ValidationError( 'The transaction must have at least one billing document ' '(invoice or proforma).' ) if document.state == document.STATES.DRAFT: raise ValidationError( 'The transaction must have a non-draft billing document ' '(invoice or proforma).' ) if self.invoice and self.proforma: if self.invoice.related_document != self.proforma: raise ValidationError('Invoice and proforma are not related.') else: if self.invoice: self.proforma = self.invoice.related_document else: self.invoice = self.proforma.related_document if document.customer != self.customer: raise ValidationError( 'Customer doesn\'t match with the one in documents.' ) # New transaction if not self.pk: if document.state != document.STATES.ISSUED: raise ValidationError( 'Transactions can only be created for issued documents.' ) if self.currency: if self.currency != self.document.transaction_currency: message = "Transaction currency is different from it's document's "\ "transaction_currency." raise ValidationError(message) else: self.currency = self.document.transaction_currency if (self.payment_method.allowed_currencies and self.currency not in self.payment_method.allowed_currencies): message = 'Currency {} is not allowed by the payment method. Allowed currencies ' \ 'are {}.'.format( self.currency, self.payment_method.allowed_currencies ) raise ValidationError(message) if self.amount: if self.amount > self.document.amount_to_be_charged_in_transaction_currency: message = "Amount is greater than the amount that should be charged in order " \ "to pay the billing document." raise ValidationError(message) else: self.amount = self.document.amount_to_be_charged_in_transaction_currency else: # clean final fields errors = {} for field in self.final_fields: old_value = self.initial_state.get(field) current_value = self.current_state.get(field) if old_value is not None and old_value != current_value: errors[field] = 'This field may not be modified.' if errors: raise ValidationError(errors) def full_clean(self, *args, **kwargs): # 'amount' and 'currency' are handled in our clean method kwargs['exclude'] = kwargs.get('exclude', []) + ['currency', 'amount'] super(Transaction, self).full_clean(*args, **kwargs) @property def can_be_consumed(self): if self.valid_until and self.valid_until < timezone.now(): return False if self.state != Transaction.States.Initial: return False return True @property def customer(self): return self.payment_method.customer @property def document(self): return self.invoice or self.proforma @document.setter def document(self, value): if isinstance(value, Invoice): self.invoice = value elif isinstance(value, Proforma): self.proforma = value else: raise ValueError( 'The provided document is not an invoice or a proforma.' ) @property def provider(self): return self._provider or self.document.provider @provider.setter def provider(self, provider): self._provider = provider @property def payment_processor(self): return self.payment_method.payment_processor def update_document_state(self): if ( self.state == Transaction.States.Settled and not self.document.amount_to_be_charged_in_transaction_currency and self.document.state != self.document.STATES.PAID ): self.document.pay() def __str__(self): return force_str(self.uuid) @receiver(post_transition) def post_transition_callback(sender, instance, name, source, target, **kwargs): if issubclass(sender, Transaction): setattr(instance, '.recently_transitioned', target) @receiver(post_save, sender=Transaction) def post_transaction_save(sender, instance, **kwargs): transaction = instance if hasattr(transaction, '.recently_transitioned'): delattr(transaction, '.recently_transitioned') transaction.update_document_state() if hasattr(transaction, '.cleaned'): delattr(transaction, '.cleaned') if not getattr(transaction, 'previous_instance', None): # we know this instance is freshly made as it doesn't have an old_value logger.info('[Models][Transaction]: %s', { 'detail': 'A transaction was created.', 'transaction_id': transaction.id, 'customer_id': transaction.customer.id, 'invoice_id': transaction.invoice.id if transaction.invoice else None, 'proforma_id': transaction.proforma.id if transaction.proforma else None })
unknown
codeparrot/codeparrot-clean
/* * Copyright 2012-present the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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. */ package org.springframework.boot.logging; import java.io.IOException; import java.io.UncheckedIOException; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.function.Predicate; import java.util.function.UnaryOperator; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.jspecify.annotations.Nullable; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; /** * Utility class that can be used to format a correlation identifier for logging based on * <a href= * "https://www.w3.org/TR/trace-context/#examples-of-http-traceparent-headers">W3C</a> * recommendations. * <p> * The formatter can be configured with a comma-separated list of names and the expected * length of their resolved value. Each item should be specified in the form * {@code "<name>(length)"}. For example, {@code "traceId(32),spanId(16)"} specifies the * names {@code "traceId"} and {@code "spanId"} with expected lengths of {@code 32} and * {@code 16} respectively. * <p> * Correlation IDs are formatted as dash separated strings surrounded in square brackets. * Formatted output is always of a fixed width and with trailing space. Dashes are omitted * if none of the named items can be resolved. * <p> * The following example would return a formatted result of * {@code "[01234567890123456789012345678901-0123456789012345] "}: <pre class="code"> * CorrelationIdFormatter formatter = CorrelationIdFormatter.of("traceId(32),spanId(16)"); * Map&lt;String, String&gt; mdc = Map.of("traceId", "01234567890123456789012345678901", "spanId", "0123456789012345"); * return formatter.format(mdc::get); * </pre> * <p> * If {@link #of(String)} is called with an empty spec the {@link #DEFAULT} formatter will * be used. * * @author Phillip Webb * @since 3.2.0 * @see #of(String) * @see #of(Collection) */ public final class CorrelationIdFormatter { /** * Default {@link CorrelationIdFormatter}. */ public static final CorrelationIdFormatter DEFAULT = CorrelationIdFormatter.of("traceId(32),spanId(16)"); private final List<Part> parts; private final String blank; private CorrelationIdFormatter(List<Part> parts) { this.parts = parts; this.blank = String.format("[%s] ", parts.stream().map(Part::blank).collect(Collectors.joining(" "))); } /** * Format a correlation from the values in the given resolver. * @param resolver the resolver used to resolve named values * @return a formatted correlation id */ public String format(UnaryOperator<@Nullable String> resolver) { StringBuilder result = new StringBuilder(this.blank.length()); formatTo(resolver, result); return result.toString(); } /** * Format a correlation from the values in the given resolver and append it to the * given {@link Appendable}. * @param resolver the resolver used to resolve named values * @param appendable the appendable for the formatted correlation id */ public void formatTo(UnaryOperator<@Nullable String> resolver, Appendable appendable) { Predicate<Part> canResolve = (part) -> StringUtils.hasLength(resolver.apply(part.name())); try { if (this.parts.stream().anyMatch(canResolve)) { appendable.append('['); for (Iterator<Part> iterator = this.parts.iterator(); iterator.hasNext();) { appendable.append(iterator.next().resolve(resolver)); if (iterator.hasNext()) { appendable.append('-'); } } appendable.append("] "); } else { appendable.append(this.blank); } } catch (IOException ex) { throw new UncheckedIOException(ex); } } @Override public String toString() { return this.parts.stream().map(Part::toString).collect(Collectors.joining(",")); } /** * Create a new {@link CorrelationIdFormatter} instance from the given specification. * @param spec a comma-separated specification * @return a new {@link CorrelationIdFormatter} instance */ public static CorrelationIdFormatter of(@Nullable String spec) { try { return (!StringUtils.hasText(spec)) ? DEFAULT : of(List.of(spec.split(","))); } catch (Exception ex) { throw new IllegalStateException("Unable to parse correlation formatter spec '%s'".formatted(spec), ex); } } /** * Create a new {@link CorrelationIdFormatter} instance from the given specification. * @param spec a pre-separated specification * @return a new {@link CorrelationIdFormatter} instance */ public static CorrelationIdFormatter of(String @Nullable [] spec) { return of((spec != null) ? List.of(spec) : Collections.emptyList()); } /** * Create a new {@link CorrelationIdFormatter} instance from the given specification. * @param spec a pre-separated specification * @return a new {@link CorrelationIdFormatter} instance */ public static CorrelationIdFormatter of(Collection<String> spec) { if (CollectionUtils.isEmpty(spec)) { return DEFAULT; } List<Part> parts = spec.stream().map(Part::of).toList(); return new CorrelationIdFormatter(parts); } /** * A part of the correlation id. * * @param name the name of the correlation part * @param length the expected length of the correlation part */ record Part(String name, int length) { private static final Pattern pattern = Pattern.compile("^(.+?)\\((\\d+)\\)$"); String resolve(UnaryOperator<@Nullable String> resolver) { String resolved = resolver.apply(name()); if (resolved == null) { return blank(); } int padding = length() - resolved.length(); return (padding <= 0) ? resolved : resolved + " ".repeat(padding); } String blank() { return " ".repeat(this.length); } @Override public String toString() { return "%s(%s)".formatted(name(), length()); } static Part of(String part) { Matcher matcher = pattern.matcher(part.trim()); Assert.state(matcher.matches(), () -> "Invalid specification part '%s'".formatted(part)); String name = matcher.group(1); int length = Integer.parseInt(matcher.group(2)); return new Part(name, length); } } }
java
github
https://github.com/spring-projects/spring-boot
core/spring-boot/src/main/java/org/springframework/boot/logging/CorrelationIdFormatter.java
# Copyright (c) 2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. """ Request Body limiting middleware. Compatibility shim for Kilo, while operators migrate to oslo.middleware. """ from oslo_config import cfg from oslo_log import versionutils from oslo_middleware import sizelimit # Default request size is 112k max_request_body_size_opt = cfg.IntOpt('osapi_max_request_body_size', default=114688, help='Max size for body of a request') CONF = cfg.CONF CONF.register_opt(max_request_body_size_opt) @versionutils.deprecated(as_of=versionutils.deprecated.KILO, in_favor_of='oslo_middleware.RequestBodySizeLimiter') class RequestBodySizeLimiter(sizelimit.RequestBodySizeLimiter): """Add a 'cinder.context' to WSGI environ.""" pass
unknown
codeparrot/codeparrot-clean
from totalimpact.providers import provider from totalimpact.providers.provider import Provider, ProviderContentMalformedError import re import logging logger = logging.getLogger('ti.providers.figshare') class Figshare(Provider): example_id = ("doi", "10.6084/m9.figshare.92393") url = "http://figshare.com" descr = "Make all of your research outputs sharable, citable and visible in the browser for free." biblio_url_template = "http://api.figshare.com/v1/articles/%s" aliases_url_template = "http://api.figshare.com/v1/articles/%s" metrics_url_template = "http://api.figshare.com/v1/articles/%s" provenance_url_template = "http://dx.doi.org/%s" member_items_url_template = "http://api.figshare.com/v1/authors/%s?page=%s" static_meta_dict = { "shares": { "display_name": "shares", "provider": "figshare", "provider_url": "http://figshare.com", "description": "The number of times this has been shared", "icon": "http://figshare.com/static/img/favicon.png", }, "downloads": { "display_name": "downloads", "provider": "figshare", "provider_url": "http://figshare.com", "description": "The number of times this has been downloaded", "icon": "http://figshare.com/static/img/favicon.png", }, "views": { "display_name": "views", "provider": "figshare", "provider_url": "http://figshare.com", "description": "The number of times this item has been viewed", "icon": "http://figshare.com/static/img/favicon.png", } } def __init__(self): super(Figshare, self).__init__() def is_relevant_alias(self, alias): (namespace, nid) = alias is_figshare_doi = (namespace == "doi") and (".figshare." in nid.lower()) return is_figshare_doi @property def provides_members(self): return True def get_figshare_userid_from_author_url(self, url): match = re.findall("figshare.com\/authors\/.*?\/(\d+)", url) try: userid = match[0] except IndexError: userid = None return userid def _extract_aliases(self, page, id=None): dict_of_keylists = {"url": ["figshare_url"]} item = self._extract_figshare_record(page, id) aliases_dict = provider._extract_from_data_dict(item, dict_of_keylists) if aliases_dict: aliases_list = [(namespace, nid) for (namespace, nid) in aliases_dict.iteritems()] else: aliases_list = [] return aliases_list def _extract_biblio(self, page, id=None): dict_of_keylists = { 'title' : ['title'], 'genre' : ['defined_type'], #'authors_literal' : ['authors'], 'published_date' : ['published_date'] } item = self._extract_figshare_record(page, id) biblio_dict = provider._extract_from_data_dict(item, dict_of_keylists) biblio_dict["repository"] = "figshare" try: biblio_dict["year"] = int(biblio_dict["published_date"][-4:]) except (KeyError, TypeError): pass if "genre" in biblio_dict: genre = biblio_dict["genre"].lower() #override if genre in ["figure", "poster"]: genre = biblio_dict["genre"] elif genre == "presentation": genre = "slides" elif genre == "paper": genre = "article" elif genre == "media": genre = "video" else: genre = "dataset" #includes fileset biblio_dict["genre"] = genre if biblio_dict["genre"] == "article": biblio_dict["free_fulltext_url"] = self._get_templated_url(self.provenance_url_template, id, "provenance") # the authors data is messy, so just give up for now # if "authors_literal" in biblio_dict: # surname_list = [author["last_name"] for author in biblio_dict["authors_literal"]] # if surname_list: # biblio_dict["authors"] = ", ".join(surname_list) # del biblio_dict["authors_literal"] return biblio_dict def _extract_figshare_record(self, page, id): data = provider._load_json(page) if not data: return {} item = data["items"][0] if str(item["article_id"]) in id: return item else: return {} def _extract_metrics(self, page, status_code=200, id=None): if status_code != 200: if status_code == 404: return {} else: raise(self._get_error(status_code)) dict_of_keylists = { 'figshare:shares' : ['shares'], 'figshare:downloads' : ['downloads'], 'figshare:views' : ['views'] } item = self._extract_figshare_record(page, id) metrics_dict = provider._extract_from_data_dict(item, dict_of_keylists) return metrics_dict def _extract_members(self, page, query_string=None): data = provider._load_json(page) dois = [item["DOI"].replace("http://dx.doi.org/", "") for item in data["items"]] doi_aliases = [("doi", doi) for doi in dois] return(doi_aliases) # default method; providers can override def member_items(self, account_name, provider_url_template=None, cache_enabled=True): if not self.provides_members: raise NotImplementedError() self.logger.debug(u"%s getting member_items for %s" % (self.provider_name, account_name)) if not provider_url_template: provider_url_template = self.member_items_url_template members = [] figshare_userid = self.get_figshare_userid_from_author_url(account_name) if not figshare_userid: raise ProviderContentMalformedError("no figshare user id found") next_page = 1 while next_page: url = provider_url_template % (figshare_userid, next_page) # try to get a response from the data provider response = self.http_get(url, cache_enabled=cache_enabled) if response.status_code != 200: self.logger.info(u"%s status_code=%i" % (self.provider_name, response.status_code)) if response.status_code == 404: raise ProviderItemNotFoundError elif response.status_code == 303: #redirect pass else: self._get_error(response.status_code, response) # extract the member ids number_of_items_per_page = 10 #figshare default try: page = response.text data = provider._load_json(page) if data["items_found"] > next_page*number_of_items_per_page: next_page += 1 else: next_page = None members += self._extract_members(page, account_name) except (AttributeError, TypeError): next_page = None return(members)
unknown
codeparrot/codeparrot-clean
import pytest from pandas._libs.tslibs.dtypes import NpyDatetimeUnit from pandas.errors import OutOfBoundsTimedelta from pandas import Timedelta class TestAsUnit: def test_as_unit(self): td = Timedelta(days=1) assert td.as_unit("us") is td res = td.as_unit("ns") assert res._value == td._value * 1000 assert res._creso == NpyDatetimeUnit.NPY_FR_ns.value rt = res.as_unit("us") assert rt._value == td._value assert rt._creso == td._creso res = td.as_unit("ms") assert res._value == td._value // 1_000 assert res._creso == NpyDatetimeUnit.NPY_FR_ms.value rt = res.as_unit("us") assert rt._value == td._value assert rt._creso == td._creso res = td.as_unit("s") assert res._value == td._value // 1_000_000 assert res._creso == NpyDatetimeUnit.NPY_FR_s.value rt = res.as_unit("us") assert rt._value == td._value assert rt._creso == td._creso def test_as_unit_overflows(self): # microsecond that would be just out of bounds for nano us = 9223372800000000 td = Timedelta._from_value_and_reso(us, NpyDatetimeUnit.NPY_FR_us.value) msg = "Cannot cast 106752 days 00:00:00 to unit='ns' without overflow" with pytest.raises(OutOfBoundsTimedelta, match=msg): td.as_unit("ns") res = td.as_unit("ms") assert res._value == us // 1000 assert res._creso == NpyDatetimeUnit.NPY_FR_ms.value def test_as_unit_rounding(self): td = Timedelta(microseconds=1500) res = td.as_unit("ms") expected = Timedelta(milliseconds=1) assert res == expected assert res._creso == NpyDatetimeUnit.NPY_FR_ms.value assert res._value == 1 with pytest.raises(ValueError, match="Cannot losslessly convert units"): td.as_unit("ms", round_ok=False) def test_as_unit_non_nano(self): # case where we are going neither to nor from nano td = Timedelta(days=1).as_unit("ms") assert td.days == 1 assert td._value == 86_400_000 assert td.components.days == 1 assert td._d == 1 assert td.total_seconds() == 86400 res = td.as_unit("us") assert res._value == 86_400_000_000 assert res.components.days == 1 assert res.components.hours == 0 assert res._d == 1 assert res._h == 0 assert res.total_seconds() == 86400
python
github
https://github.com/pandas-dev/pandas
pandas/tests/scalar/timedelta/methods/test_as_unit.py
# -*- coding: utf-8 -*- """ Deployment publishing operations module """ import codecs import os import shutil import hashlib import datetime import ZipHelper import xmlParamsHealper import JsonParamsHelper class PublisherHealperConfig: """Class for setting up publisher Healper""" moduleName = "" # name of the module to be processing destinationDir = "" # folder to deploy to sourceDir = "" # folder from with to deploy doBackup = False # does publisher need to make a backup bacupType = 'Folder' # "Folder" to backup whole destinationDir, "Files" to backup only owerwritten files backupFolder = "" # folder in witch the backup will be stored includeFolders = [] # folders to publish # includeFolders = [ # SAMPLE # { # "folder": "testFolder", # Folder to include. Do not provide this for source root folder # "recursive": True, # Process folder recursively? Default is False # "includeExtensions": ["py"], # extensions to be included. Do not provide this for all files in Folder # "excludeExtensions": ["pyc"], # extensions to be excluded. Do not provide this if dont needed # "clearExtensions": ["pyc"], # extensions to be deleted from destination. Do not provide this if dont needed # "includeFiles": ["somespecificfile.py"], # files to be specificly included. Do not provide this if dont needed # "excludeFiles": ["somespecificfile.py"], # files to be specificly excluded. Do not provide this if dont needed # "clearFiles": ["somespecificfile.py"], # files to be specificly deleted from destination. Do not provide this if dont needed # "renameFiles": {"somefilenamefromtorename.py": "somewithdifferentname.py"} # } # ] configFilesJson = [] # config files of type Json to be processed configFilesXML = [] # config files of type XML to be processed # configFilesXML = [ # SAMPLE # { # "file": "Web.config", # relative path in destination # "changes": [ # List of changes to be made # { # "xpath": '/Test/Level1/Level2/Level3', # xpath to tag to be changed (first found will be processed) # "atribute": "someatribute", # Atribute to be updated. Do not provide this if tag text is to be updated # "value": "value to be writen" # value to be writen # } # ] # } # ] replacementMap = {} # replacementMap = { # SAMPLE # 'test.json': { # '[find sting to replace]': 'replacement value' # } # } class PublisherHealper(object): """Class for easing the Rar file operations""" def __init__(self): """Class initialization procedure Args: self: The reserved object 'self' """ self.backup_zip_file = '' def Deply(self, config): """Does the dployment Args: self: The reserved object 'self' config ([PublisherHealperConfig]): Configuration of deplyment """ print u'... start publish for {}'.format(config.moduleName) self.backup_zip_file = "{}_{}.zip".format(config.moduleName, _now_for_file()) destination_dir = config.destinationDir if not os.path.exists(destination_dir): raise AttributeError(u'destination folder {} not found'.format(destination_dir)) self.__create_backup(config) for folder in config.includeFolders: self.__do_deploy(folder, config) self.__do_process_xml(config) self.__do_process_json(config) self.__do_string_repalce(config) def __create_backup(self, config): """Does the backup creation Args: self: The reserved object 'self' config ([PublisherHealperConfig]): Configuration of deplyment """ if hasattr(config, "doBackup") and config.doBackup: if config.bacupType.upper() == 'FOLDER': backup_dir = config.backupFolder if not os.path.exists(backup_dir): os.makedirs(backup_dir) print u'... created backup folder {}'.format(backup_dir) backup_file_name = os.path.join(backup_dir, self.backup_zip_file) ZipHelper.ZipHelper().CompressDir(config.destinationDir, backup_file_name) print u'... backup created!' def __create_backup_one_file(self, file_path, config): """Does the backup creation for one file Args: self: The reserved object 'self' config ([PublisherHealperConfig]): Configuration of deplyment """ if hasattr(config, "doBackup") and config.doBackup: if config.bacupType.upper() == 'FILES': backup_dir = config.backupFolder if not os.path.exists(backup_dir): os.makedirs(backup_dir) print u'... created backup folder {}'.format(backup_dir) backup_file_name = os.path.join(backup_dir, self.backup_zip_file) ZipHelper.ZipHelper().CompressFileList( filePathList=[file_path], zipFileName=backup_file_name, base_dir=config.destinationDir, append=os.path.exists(backup_file_name)) print u'... file {} backup created!'.format(file_path) def __do_deploy(self, folder, config): """Does the backup creation Args: self: The reserved object 'self' folder ([string]): relative path to folder to be processed config ([PublisherHealperConfig]): Configuration of deplyment """ self.__clear(folder, config) files_to_copy = self.__files_to_copy(folder, config) self.__do_copy_files_to_dest(folder, files_to_copy, config) def __clear(self, folder, config): """Clears unnececery files Args: self: The reserved object 'self' folder ([string]): relative path to folder to be processed config ([PublisherHealperConfig]): Configuration of deplyment """ if folder.has_key("clearExtensions") or folder.has_key("clearFiles"): clear_extensions = folder[u'clearExtensions'] if folder.has_key("clearExtensions") else [] clear_files = folder[u'clearFiles'] if folder.has_key("clearFiles") else [] recursive = folder[u'recursive'] if folder.has_key("recursive") else False source_dir = os.path.join(config.sourceDir, folder["folder"]) if folder.has_key("folder") else config.sourceDir destination_dir = os.path.join(config.destinationDir, folder["folder"]) if folder.has_key("folder") else config.destinationDir if not recursive: include_folders = [] else: include_folders = _find_all_folders(destination_dir) include_folders.append(destination_dir) files_to_delete = [] for infolder in include_folders: for ext in clear_extensions: destination_folder = infolder.replace(source_dir, destination_dir) if not os.path.exists(destination_folder): os.makedirs(destination_folder) print u'... output folder created {}'.format(destination_folder) found_files = _find_file(os.path.join(destination_dir, infolder), ext) if found_files: files_to_delete = files_to_delete + found_files for file_to_clear in clear_files: file_name = os.path.join(destination_dir, infolder, file_to_clear) if os.path.exists(file_name): files_to_delete.append(file_name) for file_to_delate in files_to_delete: os.remove(file_to_delate) print u'... file deleted {}'.format(file_to_delate) def __files_to_copy(self, folder, config): """Finds files to be copyed Args: self: The reserved object 'self' folder ([string]): relative path to folder to be processed config ([PublisherHealperConfig]): Configuration of deplyment """ recursive = folder[u'recursive'] if folder.has_key("recursive") else False source_dir = os.path.join(config.sourceDir, folder["folder"]) if folder.has_key("folder") else config.sourceDir destination_dir = os.path.join(config.destinationDir, folder["folder"]) if folder.has_key("folder") else config.destinationDir if not recursive: include_folders = [] else: include_folders = _find_all_folders(source_dir) include_folders.append(source_dir) files_to_copy = [] if folder.has_key("includeExtensions") or folder.has_key("includeFiles"): files_to_copy = self.__find_files_to_include(folder, include_folders, source_dir, destination_dir) else: files_to_copy = self.__find_all_files_to_include(folder, include_folders, source_dir, destination_dir) if folder.has_key("excludeExtensions") or folder.has_key("excludeFiles"): files_to_copy = self.__exclude_files(folder, files_to_copy) return files_to_copy def __find_files_to_include(self, folder, include_folders, source_dir, destination_dir): files_to_copy = [] include_extensions = folder[u'includeExtensions'] if folder.has_key("includeExtensions") else [] include_files = folder[u'includeFiles'] if folder.has_key("includeFiles") else [] for infolder in include_folders: for ext in include_extensions: found_files = _find_file(infolder, ext) if found_files: files_to_copy = files_to_copy + found_files if not infolder == source_dir: destination_folder = infolder.replace(source_dir, destination_dir) if not os.path.exists(destination_folder): os.makedirs(destination_folder) print u'... output folder created {}'.format(destination_folder) for file_name in include_files: found_files = _find_file_by_name(infolder, file_name) if found_files: files_to_copy = files_to_copy + found_files if not infolder == source_dir: destination_folder = infolder.replace(source_dir, destination_dir) if not os.path.exists(destination_folder): os.makedirs(destination_folder) print u'... output folder created {}'.format(destination_folder) return files_to_copy def __find_all_files_to_include(self, folder, include_folders, source_dir, destination_dir): files_to_copy = [] for infolder in include_folders: found_files = _find_all_files(os.path.join(source_dir, infolder)) if found_files: files_to_copy = files_to_copy + found_files if not folder == source_dir: dir_name = infolder.replace(source_dir + '\\', '') destination_folder = os.path.join(destination_dir, dir_name) if not os.path.exists(destination_folder): os.makedirs(destination_folder) print u'... output folder created {}'.format(destination_folder) return files_to_copy def __exclude_files(self, folder, files_to_copy): exclude_extensions = folder[u'excludeExtensions'] if folder.has_key("excludeExtensions") else [] exclude_files = folder[u'excludeFiles'] if folder.has_key("excludeFiles") else [] for ext in exclude_extensions: files_to_copy = list(fn for fn in files_to_copy if not os.path.basename(fn).lower().endswith('.' + (ext.lower()))) for exclude_file in exclude_files: files_to_copy = list(fn for fn in files_to_copy if not os.path.basename(fn).lower() == exclude_file.lower()) return files_to_copy def __do_copy_files_to_dest(self, folder, files_to_copy, config,): """Finds files to be copyed Args: self: The reserved object 'self' folder ([string]): relative path to folder to be processed files_to_copy ([list]): path of files to be copyed config ([PublisherHealperConfig]): Configuration of deplyment """ source_dir = os.path.join(config.sourceDir, folder["folder"]) if folder.has_key("folder") else config.sourceDir destination_dir = os.path.join(config.destinationDir, folder["folder"]) if folder.has_key("folder") else config.destinationDir for copy_file in files_to_copy: dest_file = copy_file dest_file = dest_file.replace(source_dir, destination_dir) dest_file = self.__rename_file_if_needed(dest_file, folder) replaced = False thesame = False if os.path.exists(dest_file): copy_hash = _md5(copy_file) dest_hash = _md5(dest_file) if copy_hash <> dest_hash: self.__create_backup_one_file(dest_file, config) os.remove(dest_file) replaced = True else: thesame = True if not thesame: if not os.path.isdir(os.path.dirname(dest_file)): os.makedirs(os.path.dirname(dest_file)) shutil.copy2(copy_file, dest_file) if not replaced: print u'... file copy {}'.format(dest_file) else: print u'... file replace {}'.format(dest_file) def __rename_file_if_needed(self, dest_file, folder): rename_files = folder[u'renameFiles'] if folder.has_key("renameFiles") else {} dir_name, file_name = os.path.split(dest_file) for rename_file in rename_files: if file_name.upper() == rename_file.upper(): return os.path.join(dir_name, rename_files[rename_file]) return dest_file def __do_process_xml(self, config): """Changes required values in config xml Args: self: The reserved object 'self' config ([PublisherHealperConfig]): Configuration of deplyment """ for config_file in config.configFilesXML: params_helper = xmlParamsHealper.XMLParams(None, None, os.path.join(config.destinationDir, config_file['file'])) params_helper.GetParams() for change in config_file['changes']: is_string = False do_append = False if change.has_key('string'): if change['string']: is_string = True if change.has_key('append'): if change['append']: do_append = True if do_append: attribute = None key = None if change.has_key("atribute"): attribute = change['atribute'] if change.has_key("appendKey"): key = change['appendKey'] params_helper.AppendValueByPath(change['xpath'], key, change['value'], attribute, isString=is_string) else: if change.has_key("atribute"): params_helper.UpdateAtributeByPath(change['xpath'], change['atribute'], change['value']) else: params_helper.UpdateValueByPath(change['xpath'], change['value']) params_helper.WriteParams() print u'... config file {} updated'.format(config_file['file']) def __do_process_json(self, config): """Changes required values in config xml Args: self: The reserved object 'self' config ([PublisherHealperConfig]): Configuration of deplyment """ for config_file in config.configFilesJson: params_helper = JsonParamsHelper.JsonParams(None, None, os.path.join(config.destinationDir, config_file['file'])) params_helper.GetParams() for change in config_file['changes']: is_json = False do_append = False if change.has_key('json'): if change['json']: is_json = True if change.has_key('append'): if change['append']: do_append = True if do_append: params_helper.AppendValueByPath(change['xpath'], change['appendKey'], change['value'], is_json) else: params_helper.UpdateValueByPath(change['xpath'], change['value'], is_json) params_helper.WriteParams(False) print u'... config file {} updated'.format(config_file['file']) def __do_string_repalce(self, config): """Replace required values by sring replacement Args: self: The reserved object 'self' config ([PublisherHealperConfig]): Configuration of deplyment """ for file_name in config.replacementMap: replacement_map = config.replacementMap[file_name] path = os.path.join(config.destinationDir, file_name) _replace_in_file(path, replacement_map) print u'... file {} replaced strings'.format(path) def _replace_in_file(path, replace_map): """replaces values in files using replace_map """ with codecs.open(path, 'r') as f: newlines = [] for line in f.readlines(): for key, value in replace_map.items(): line = line.replace(key, value) newlines.append(line) with open(path, 'w') as f: for line in newlines: f.write(line) def _find_all_files(directory): """Finds files in the directory Args: dir: The directory in which to look for the file """ found_files = [directory + "\\" + fn for fn in os.listdir(directory) if os.path.isfile(directory + "\\" + fn)] found_files.sort() return found_files def _find_file(directory, ext): """Finds files in the directory Args: Dir: The directory in which to look for the file Ext: The extension to search for """ found_files = [directory + "\\" + fn for fn in os.listdir(directory) if fn.lower().endswith('.' + (ext.lower()))] found_files.sort() return found_files def _find_file_by_name(directory, file_name): """Finds files in the directory Args: Dir: The directory in which to look for the file fileName: File name to search for """ found_files = [directory + "\\" + fn for fn in os.listdir(directory) if fn.lower() == file_name.lower()] found_files.sort() return found_files def _find_all_folders(directory): """Finds files in the directory Args: Dir: The directory in which to look for the file Ext: The extension to search for """ result = [] for root, dirs, files in os.walk(directory): for name in dirs: result.append(os.path.join(root, name)) return result def _md5(filename): """calculates file md5 cheksumm Args: fname ([string]): File path Returns: [string]: hex digest """ hash_md5 = hashlib.md5() with open(filename, "rb") as opened_file: for chunk in iter(lambda: opened_file.read(4096), b""): hash_md5.update(chunk) return hash_md5.hexdigest() def _now_for_file(): """returns date now formated for filename Returns: [string]: [date reprezentation as string] """ return datetime.datetime.strftime(datetime.datetime.now(), "%Y%m%d_%H%M%S")
unknown
codeparrot/codeparrot-clean
""" Watches the key ``paste.httpserver.thread_pool`` to see how many threads there are and report on any wedged threads. """ import sys import cgi import time import traceback from cStringIO import StringIO from thread import get_ident from paste import httpexceptions from paste.request import construct_url, parse_formvars from paste.util.template import HTMLTemplate, bunch page_template = HTMLTemplate(''' <html> <head> <style type="text/css"> body { font-family: sans-serif; } table.environ tr td { border-bottom: #bbb 1px solid; } table.environ tr td.bottom { border-bottom: none; } table.thread { border: 1px solid #000; margin-bottom: 1em; } table.thread tr td { border-bottom: #999 1px solid; padding-right: 1em; } table.thread tr td.bottom { border-bottom: none; } table.thread tr.this_thread td { background-color: #006; color: #fff; } a.button { background-color: #ddd; border: #aaa outset 2px; text-decoration: none; margin-top: 10px; font-size: 80%; color: #000; } a.button:hover { background-color: #eee; border: #bbb outset 2px; } a.button:active { border: #bbb inset 2px; } </style> <title>{{title}}</title> </head> <body> <h1>{{title}}</h1> {{if kill_thread_id}} <div style="background-color: #060; color: #fff; border: 2px solid #000;"> Thread {{kill_thread_id}} killed </div> {{endif}} <div>Pool size: {{nworkers}} {{if actual_workers > nworkers}} + {{actual_workers-nworkers}} extra {{endif}} ({{nworkers_used}} used including current request)<br> idle: {{len(track_threads["idle"])}}, busy: {{len(track_threads["busy"])}}, hung: {{len(track_threads["hung"])}}, dying: {{len(track_threads["dying"])}}, zombie: {{len(track_threads["zombie"])}}</div> {{for thread in threads}} <table class="thread"> <tr {{if thread.thread_id == this_thread_id}}class="this_thread"{{endif}}> <td> <b>Thread</b> {{if thread.thread_id == this_thread_id}} (<i>this</i> request) {{endif}}</td> <td> <b>{{thread.thread_id}} {{if allow_kill}} <form action="{{script_name}}/kill" method="POST" style="display: inline"> <input type="hidden" name="thread_id" value="{{thread.thread_id}}"> <input type="submit" value="kill"> </form> {{endif}} </b> </td> </tr> <tr> <td>Time processing request</td> <td>{{thread.time_html|html}}</td> </tr> <tr> <td>URI</td> <td>{{if thread.uri == 'unknown'}} unknown {{else}}<a href="{{thread.uri}}">{{thread.uri_short}}</a> {{endif}} </td> <tr> <td colspan="2" class="bottom"> <a href="#" class="button" style="width: 9em; display: block" onclick=" var el = document.getElementById('environ-{{thread.thread_id}}'); if (el.style.display) { el.style.display = ''; this.innerHTML = \'&#9662; Hide environ\'; } else { el.style.display = 'none'; this.innerHTML = \'&#9656; Show environ\'; } return false ">&#9656; Show environ</a> <div id="environ-{{thread.thread_id}}" style="display: none"> {{if thread.environ:}} <table class="environ"> {{for loop, item in looper(sorted(thread.environ.items()))}} {{py:key, value=item}} <tr> <td {{if loop.last}}class="bottom"{{endif}}>{{key}}</td> <td {{if loop.last}}class="bottom"{{endif}}>{{value}}</td> </tr> {{endfor}} </table> {{else}} Thread is in process of starting {{endif}} </div> {{if thread.traceback}} <a href="#" class="button" style="width: 9em; display: block" onclick=" var el = document.getElementById('traceback-{{thread.thread_id}}'); if (el.style.display) { el.style.display = ''; this.innerHTML = \'&#9662; Hide traceback\'; } else { el.style.display = 'none'; this.innerHTML = \'&#9656; Show traceback\'; } return false ">&#9656; Show traceback</a> <div id="traceback-{{thread.thread_id}}" style="display: none"> <pre class="traceback">{{thread.traceback}}</pre> </div> {{endif}} </td> </tr> </table> {{endfor}} </body> </html> ''', name='watchthreads.page_template') class WatchThreads(object): """ Application that watches the threads in ``paste.httpserver``, showing the length each thread has been working on a request. If allow_kill is true, then you can kill errant threads through this application. This application can expose private information (specifically in the environment, like cookies), so it should be protected. """ def __init__(self, allow_kill=False): self.allow_kill = allow_kill def __call__(self, environ, start_response): if 'paste.httpserver.thread_pool' not in environ: start_response('403 Forbidden', [('Content-type', 'text/plain')]) return ['You must use the threaded Paste HTTP server to use this application'] if environ.get('PATH_INFO') == '/kill': return self.kill(environ, start_response) else: return self.show(environ, start_response) def show(self, environ, start_response): start_response('200 OK', [('Content-type', 'text/html')]) form = parse_formvars(environ) if form.get('kill'): kill_thread_id = form['kill'] else: kill_thread_id = None thread_pool = environ['paste.httpserver.thread_pool'] nworkers = thread_pool.nworkers now = time.time() workers = thread_pool.worker_tracker.items() workers.sort(key=lambda v: v[1][0]) threads = [] for thread_id, (time_started, worker_environ) in workers: thread = bunch() threads.append(thread) if worker_environ: thread.uri = construct_url(worker_environ) else: thread.uri = 'unknown' thread.thread_id = thread_id thread.time_html = format_time(now-time_started) thread.uri_short = shorten(thread.uri) thread.environ = worker_environ thread.traceback = traceback_thread(thread_id) page = page_template.substitute( title="Thread Pool Worker Tracker", nworkers=nworkers, actual_workers=len(thread_pool.workers), nworkers_used=len(workers), script_name=environ['SCRIPT_NAME'], kill_thread_id=kill_thread_id, allow_kill=self.allow_kill, threads=threads, this_thread_id=get_ident(), track_threads=thread_pool.track_threads()) return [page] def kill(self, environ, start_response): if not self.allow_kill: exc = httpexceptions.HTTPForbidden( 'Killing threads has not been enabled. Shame on you ' 'for trying!') return exc(environ, start_response) vars = parse_formvars(environ) thread_id = int(vars['thread_id']) thread_pool = environ['paste.httpserver.thread_pool'] if thread_id not in thread_pool.worker_tracker: exc = httpexceptions.PreconditionFailed( 'You tried to kill thread %s, but it is not working on ' 'any requests' % thread_id) return exc(environ, start_response) thread_pool.kill_worker(thread_id) script_name = environ['SCRIPT_NAME'] or '/' exc = httpexceptions.HTTPFound( headers=[('Location', script_name+'?kill=%s' % thread_id)]) return exc(environ, start_response) def traceback_thread(thread_id): """ Returns a plain-text traceback of the given thread, or None if it can't get a traceback. """ if not hasattr(sys, '_current_frames'): # Only 2.5 has support for this, with this special function return None frames = sys._current_frames() if not thread_id in frames: return None frame = frames[thread_id] out = StringIO() traceback.print_stack(frame, file=out) return out.getvalue() hide_keys = ['paste.httpserver.thread_pool'] def format_environ(environ): if environ is None: return environ_template.substitute( key='---', value='No environment registered for this thread yet') environ_rows = [] for key, value in sorted(environ.items()): if key in hide_keys: continue try: if key.upper() != key: value = repr(value) environ_rows.append( environ_template.substitute( key=cgi.escape(str(key)), value=cgi.escape(str(value)))) except Exception, e: environ_rows.append( environ_template.substitute( key=cgi.escape(str(key)), value='Error in <code>repr()</code>: %s' % e)) return ''.join(environ_rows) def format_time(time_length): if time_length >= 60*60: # More than an hour time_string = '%i:%02i:%02i' % (int(time_length/60/60), int(time_length/60) % 60, time_length % 60) elif time_length >= 120: time_string = '%i:%02i' % (int(time_length/60), time_length % 60) elif time_length > 60: time_string = '%i sec' % time_length elif time_length > 1: time_string = '%0.1f sec' % time_length else: time_string = '%0.2f sec' % time_length if time_length < 5: return time_string elif time_length < 120: return '<span style="color: #900">%s</span>' % time_string else: return '<span style="background-color: #600; color: #fff">%s</span>' % time_string def shorten(s): if len(s) > 60: return s[:40]+'...'+s[-10:] else: return s def make_watch_threads(global_conf, allow_kill=False): from paste.deploy.converters import asbool return WatchThreads(allow_kill=asbool(allow_kill)) make_watch_threads.__doc__ = WatchThreads.__doc__ def make_bad_app(global_conf, pause=0): pause = int(pause) def bad_app(environ, start_response): import thread if pause: time.sleep(pause) else: count = 0 while 1: print "I'm alive %s (%s)" % (count, thread.get_ident()) time.sleep(10) count += 1 start_response('200 OK', [('content-type', 'text/plain')]) return ['OK, paused %s seconds' % pause] return bad_app
unknown
codeparrot/codeparrot-clean
// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Pack is a simple version of the traditional Unix ar tool. It implements only the operations needed by Go. Usage: go tool pack op file.a [name...] Pack applies the operation to the archive, using the names as arguments to the operation. The operation op is given by one of these letters: c append files (from the file system) to a new archive p print files from the archive r append files (from the file system) to the archive t list files from the archive x extract files from the archive The archive argument to the c command must be non-existent or a valid archive file, which will be cleared before adding new entries. It is an error if the file exists but is not an archive. For the p, t, and x commands, listing no names on the command line causes the operation to apply to all files in the archive. In contrast to Unix ar, the r operation always appends to the archive, even if a file with the given name already exists in the archive. In this way pack's r operation is more like Unix ar's rq operation. Adding the letter v to an operation, as in pv or rv, enables verbose operation: For the c and r commands, names are printed as files are added. For the p command, each file is prefixed by the name on a line by itself. For the t command, the listing includes additional file metadata. For the x command, names are printed as files are extracted. */ package main
go
github
https://github.com/golang/go
src/cmd/pack/doc.go
"""ML-Ensemble :author: Sebastian Flennerhag :copyright: 2017-2018 :license: MIT Parallel processing backend classes. Manages memory-mapping of data, estimation caching and job scheduling. """ # pylint: disable=too-few-public-methods # pylint: disable=too-many-arguments # pylint: disable=too-many-instance-attributes # pylint: disable=useless-super-delegation from __future__ import with_statement, division import gc import os import shutil import subprocess import tempfile import warnings from abc import ABCMeta, abstractmethod import numpy as np from scipy.sparse import issparse, hstack from .. import config from ..externals.joblib import Parallel, dump, load from ..utils import check_initialized from ..utils.exceptions import (ParallelProcessingError, ParallelProcessingWarning) from ..externals.sklearn.validation import check_random_state ############################################################################### def _dtype(a, b=None): """Utility for getting a dtype""" return getattr(a, 'dtype', getattr(b, 'dtype', None)) def dump_array(array, name, path): """Dump array for memmapping. Parameters ---------- array : array-like Array to be persisted name : str Name of file path : str Path to cache. Returns ------- f: array-like memory-mapped array. """ # First check if the array is on file if isinstance(array, str): # Load file from disk. Need to dump if not memmaped already if not array.split('.')[-1] in ['mmap', 'npy', 'npz']: # Try loading the file assuming a csv-like format array = _load(array) if isinstance(array, str): # If arr remains a string, it's pointing to an mmap file f = array else: # Dump ndarray on disk f = os.path.join(path, '%s.mmap' % name) if os.path.exists(f): os.unlink(f) dump(array, f) return f def _load(arr): """Load array from file using default settings.""" if arr.split('.')[-1] in ['npy', 'npz']: return np.load(arr) else: try: return np.genfromtxt(arr) except Exception as e: raise IOError("Could not load X from %s, does not " "appear to be a valid ndarray. " "Details:\n%r" % (arr, e)) def _load_mmap(f): """Load a mmap presumably dumped by joblib, otherwise try numpy.""" try: return load(f, mmap_mode='r') except (IndexError, KeyError): # Joblib's 'load' func fails on npy and npz: use numpy.load return np.load(f, mmap_mode='r') def _set_path(job, path, threading): """Build path as a cache or list depending on whether using threading""" if path: if not isinstance(path, str) and not threading: raise ValueError("Path must be a str with backend=multiprocessing." " Got %r" % path.__class__) elif not isinstance(path, (str, dict)): raise ValueError("Invalid path format. Should be one of " "str, dict. Got %r" % path.__class__) job.dir = path return job if threading: # No need to pickle job.dir = dict() return job # Else, need a directory path = config.get_tmpdir() try: job.tmp = tempfile.TemporaryDirectory( prefix=config.get_prefix(), dir=path) job.dir = job.tmp.name except AttributeError: # Fails on python 2 job.dir = tempfile.mkdtemp(prefix=config.get_prefix(), dir=path) return job ############################################################################### class Job(object): """Container class for holding and managing job data. :class:`Job` is intended as a on-the-fly job handler that keeps track of input data, predictions, and manages estimation caches. .. versionchanged:: 0.2.0 See Also -------- :class:`ParallelProcessing`, :class:`ParallelEvaluation` Parameters ---------- job : str Type of job to run. One of ``'fit'``, ``'transform'``, ``'predict'``. stack : bool Whether to stack outputs when calls to :func:`~mlens.parallel.backend.Job.update` are made. This will make the ``predict_out`` array become ``predict_in``. split : bool Whether to create a new sub-cache when the :attr:`~mlens.parallel.backend.Job.args` property is called. dir : str, dict, optional estimation cache. Pass dictionary for use with multiprocessing or a string pointing to the disk directory to create the cache in tmp : obj, optional a Tempfile object for temporary directories targets : array-like of shape [n_in_samples,], optional input targets predict_in : array-like of shape [n_in_samples, n_in_features], optional input data predict_out : array_like of shape [n_out_samples, n_out_features], optional prediction output array """ __slots__ = ['targets', 'predict_in', 'predict_out', 'dir', 'job', 'tmp', '_n_dir', 'kwargs', 'stack', 'split'] def __init__(self, job, stack, split, dir=None, tmp=None, predict_in=None, targets=None, predict_out=None): self.job = job self.stack = stack self.split = split self.targets = targets self.predict_in = predict_in self.predict_out = predict_out self.tmp = tmp self.dir = dir self._n_dir = 0 def clear(self): """Clear output data for new task""" self.predict_out = None def update(self): """Updated output array and shift to input if stacked. If stacking is en force, the output array will replace the input array, and used as input for subsequent jobs. Sparse matrices are force-converted to ``csr`` format. """ if self.predict_out is None: return if (issparse(self.predict_out) and not self.predict_out.__class__.__name__.startswith('csr')): # Enforce csr on spare matrices self.predict_out = self.predict_out.tocsr() if self.stack: self.predict_in = self.predict_out self.rebase() def rebase(self): """Rebase output labels to input indexing. Some indexers that only generate predictions for subsets of the training data require the targets to be rebased. Since indexers operate in a strictly sequential manner, rebase simply drop the first ``n`` observations in the target vector until number of observations remaining coincide. .. seealso:: :class:`~mlens.index.blend.BlendIndex` """ if self.targets is not None and ( self.targets.shape[0] > self.predict_in.shape[0]): # This is legal if X is a prediction matrix generated by predicting # only a subset of the original training set. # Since indexing is strictly monotonic, we can simply discard # the first observations in y to get the corresponding labels. rebase = self.targets.shape[0] - self.predict_in.shape[0] self.targets = self.targets[rebase:] def shuffle(self, random_state): """Shuffle inputs. Permutes the indexing of ``predict_in`` and ``y`` arrays. Parameters ---------- random_state : int, obj Random seed number or generator to use. """ r = check_random_state(random_state) idx = r.permutation(self.targets.shape[0]) self.predict_in = self.predict_in[idx] self.targets = self.targets[idx] def subdir(self): """Return a cache subdirectory If ``split`` is en force, a new sub-cache will be created in the main cache. Otherwise the same sub-cache as used in previous call will be returned. .. versionadded:: 0.2.0 Returns ------- cache : str, list Either a string pointing to a cache persisted to disk, or an in-memory cache in the form of a list. """ path_name = "task_%s" % str(self._n_dir) if self.split: # Increment sub-cache counter self._n_dir += 1 if isinstance(self.dir, str): path = os.path.join(self.dir, path_name) cache_exists = os.path.exists(path) # Persist cache to disk if cache_exists and self.split: raise ParallelProcessingError( "Subdirectory %s exist. Clear cache." % path_name) elif not cache_exists: os.mkdir(path) return path # Keep in memory if path_name in self.dir and self.split: raise ParallelProcessingError( "Subdirectory %s exist. Clear cache." % path_name) elif path_name not in self.dir: self.dir[path_name] = list() return self.dir[path_name] def args(self, **kwargs): """Produce args dict .. versionadded:: 0.2.0 Returns the arguments dictionary passed to a task of a parallel processing manager. Output dictionary has the following form:: out = {'auxiliary': {'X': self.predict_in, 'P': self.predict_out}, 'main': {'X': self.predict_in, 'P': self.predict_out}, 'dir': self.subdir(), 'job': self.job } Parameters ---------- **kwargs : optional Optional keyword arguments to pass to the task. Returns ------- args : dict Arguments dictionary """ aux_feed = {'X': self.predict_in, 'P': None} main_feed = {'X': self.predict_in, 'P': self.predict_out} if self.job in ['fit', 'evaluate']: main_feed['y'] = self.targets aux_feed['y'] = self.targets out = dict() if kwargs: out.update(kwargs) out = {'auxiliary': aux_feed, 'main': main_feed, 'dir': self.subdir(), 'job': self.job} return out ############################################################################### class BaseProcessor(object): """Parallel processing base class. Base class for parallel processing engines. Parameters ---------- backend: str, optional Type of backend. One of ``'threading'``, ``'multiprocessing'``, ``'sequential'``. n_jobs : int, optional Degree of concurrency. verbose: bool, int, optional Level of verbosity of the :class:`~mlens.externals.joblib.parallel.Parallel` instance. """ __meta_class__ = ABCMeta __slots__ = ['caller', '__initialized__', '__threading__', 'job', 'n_jobs', 'backend', 'verbose'] @abstractmethod def __init__(self, backend=None, n_jobs=None, verbose=None): self.job = None self.__initialized__ = 0 self.backend = config.get_backend() if not backend else backend self.n_jobs = -1 if not n_jobs else n_jobs self.verbose = False if not verbose else verbose self.__threading__ = self.backend == 'threading' def __enter__(self): return self def initialize(self, job, X, y, path, warm_start=False, return_preds=False, **kwargs): """Initialize processing engine. Set up the job parameters before an estimation call. Calling :func:`~mlens.parallel.backend.BaseProcessor.clear` undoes initialization. Parameters ---------- job : str type of job to complete with each task. One of ``'fit'``, ``'predict'`` and ``'transform'``. X : array-like of shape [n_samples, n_features] Input data y : array-like of shape [n_samples,], optional. targets. Required for fit, should not be passed to predict or transform jobs. path : str or dict, optional Custom estimation cache. Pass a string to force use of persistent cache on disk. Pass a ``dict`` for in-memory cache (requires ``backend != 'multiprocessing'``. return_preds : bool or list, optional whether to return prediction ouput. If ``True``, final prediction is returned. Alternatively, pass a list of task names for which output should be returned. warm_start : bool, optional whether to re-use previous input data initialization. Useful if repeated jobs are made on the same input arrays. **kwargs : optional optional keyword arguments to pass onto the task's call method. Returns ------- out : dict An output parameter dictionary to pass to pass to an estimation method. Either ``None`` (no output), or ``{'final':True}`` for only final prediction, or ``{'final': False, 'return_names': return_preds}`` if a list of task-specific output was passed. """ if not warm_start: self._initialize(job=job, X=X, y=y, path=path, **kwargs) if return_preds is True: return {'return_final': True} if return_preds is False: return {} return {'return_final': False, 'return_names': return_preds} def _initialize(self, job, X, y=None, path=None, **kwargs): """Create a job instance for estimation. See :func:`~mlens.parallel.backend.BaseProcess.initialize` for further details. """ job = Job(job, **kwargs) job = _set_path(job, path, self.__threading__) # --- Prepare inputs for name, arr in zip(('X', 'y'), (X, y)): if arr is None: continue # Dump data in cache if self.__threading__: # No need to memmap f = None if isinstance(arr, str): arr = _load(arr) else: f = dump_array(arr, name, job.dir) # Store data for processing if name == 'y' and arr is not None: job.targets = arr if self.__threading__ else _load_mmap(f) elif name == 'X': job.predict_in = arr \ if self.__threading__ else _load_mmap(f) self.job = job self.__initialized__ = 1 gc.collect() return self def __exit__(self, *args): self.clear() def clear(self): """Destroy cache and reset instance job parameters.""" # Detach Job instance job = self.job self.job = None self.__initialized__ = 0 if job: path = job.dir path_handle = job.tmp # Release shared memory references del job gc.collect() # Destroy cache try: # If the cache has been persisted to disk, remove it if isinstance(path, str): path_handle.cleanup() except (AttributeError, OSError): # Python 2 has no handler, can also fail on windows # Use explicit shutil process, or fall back on subprocess try: shutil.rmtree(path) except OSError: # Can fail on windows, need to use the shell try: subprocess.Popen( 'rmdir /S /Q %s' % path, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).kill() except OSError: warnings.warn( "Failed to delete cache at %s." "If created with default settings, will be " "removed on reboot. For immediate " "removal, manual removal is required." % path, ParallelProcessingWarning) finally: del path, path_handle gc.collect() if gc.garbage: warnings.warn( "Clearing cache failed, uncollected:\n%r" % gc.garbage, ParallelProcessingWarning) class ParallelProcessing(BaseProcessor): """Parallel processing engine. Engine for running computational graph. :class:`ParallelProcessing` is a manager for executing a sequence of tasks in a given caller, where each task is run sequentially, but assumed to be parallelized internally. The main responsibility of :class:`ParallelProcessing` is to handle memory-mapping, estimation cache updates, input and output array updates and output collection. Parameters ---------- caller : obj the caller of the job. Either a Layer or a meta layer class such as Sequential. *args : optional Optional arguments to :class:`~mlens.parallel.backend.BaseProcessor` **kwargs : optional Optional keyword arguments to :class:`~mlens.parallel.backend.BaseProcessor`. """ def __init__(self, *args, **kwargs): super(ParallelProcessing, self).__init__(*args, **kwargs) def map(self, caller, job, X, y=None, path=None, return_preds=False, wart_start=False, split=False, **kwargs): """Parallel task mapping. Run independent tasks in caller in parallel. Warning ------- By default, the :~mlens.parallel.backend.ParallelProcessing.map` runs on a shallow cache, where all tasks share the same cache. As such, the user must ensure that each task has a unique name, or cache retrieval will be corrupted. To commit a seperate sub-cache to each task, set ``split=True``. Parameters ---------- caller : iterable Iterable that generates accepted task instances. Caller should be a child of the :class:`~mlens.parallel.base.BaseBackend` class, and tasks need to implement an appropriate call method. job : str type of job to complete with each task. One of ``'fit'``, ``'predict'`` and ``'transform'``. X : array-like of shape [n_samples, n_features] Input data y : array-like of shape [n_samples,], optional. targets. Required for fit, should not be passed to predict or transform jobs. path : str or dict, optional Custom estimation cache. Pass a string to force use of persistent cache on disk. Pass a ``dict`` for in-memory cache (requires ``backend != 'multiprocessing'``. return_preds : bool or list, optional whether to return prediction ouput. If ``True``, final prediction is returned. Alternatively, pass a list of task names for which output should be returned. warm_start : bool, optional whether to re-use previous input data initialization. Useful if repeated jobs are made on the same input arrays. split : bool, default = False whether to commit a separate sub-cache to each task. **kwargs : optional optional keyword arguments to pass onto each task. Returns ------- out: array-like, list, optional Prediction array(s). """ out = self.initialize( job=job, X=X, y=y, path=path, warm_start=wart_start, return_preds=return_preds, split=split, stack=False) return self.process(caller=caller, out=out, **kwargs) def stack(self, caller, job, X, y=None, path=None, return_preds=False, warm_start=False, split=True, **kwargs): """Stacked parallel task mapping. Run stacked tasks in caller in parallel. This method runs a stack of tasks as a stack, where the output of each task is the input to the next. Warning ------- By default, the :func:`~mlens.parallel.backend.ParallelProcessing.stack` method runs on a deep cache, where each tasks has a separate cache. As such, the user must ensure that tasks don't depend on data cached by previous tasks. To run all tasks in a single sub-cache, set ``split=False``. Parameters ---------- caller : iterable Iterable that generates accepted task instances. Caller should be a child of the :class:`~mlens.parallel.base.BaseBackend` class, and tasks need to implement an appropriate call method. job : str type of job to complete with each task. One of ``'fit'``, ``'predict'`` and ``'transform'``. X : array-like of shape [n_samples, n_features] Input data y : array-like of shape [n_samples,], optional. targets. Required for fit, should not be passed to predict or transform jobs. path : str or dict, optional Custom estimation cache. Pass a string to force use of persistent cache on disk. Pass a ``dict`` for in-memory cache (requires ``backend != 'multiprocessing'``. return_preds : bool or list, optional whether to return prediction output. If ``True``, final prediction is returned. Alternatively, pass a list of task names for which output should be returned. warm_start : bool, optional whether to re-use previous input data initialization. Useful if repeated jobs are made on the same input arrays. split : bool, default = True whether to commit a separate sub-cache to each task. **kwargs : optional optional keyword arguments to pass onto each task. Returns ------- out: array-like, list, optional Prediction array(s). """ out = self.initialize( job=job, X=X, y=y, path=path, warm_start=warm_start, return_preds=return_preds, split=split, stack=True) return self.process(caller=caller, out=out, **kwargs) def process(self, caller, out, **kwargs): """Process job. Main method for processing a caller. Requires the instance to be setup by a prior call to :func:`~mlens.parallel.backend.BaseProcessor.initialize`. .. seealso:: :func:`~mlens.parallel.backend.ParallelProcessing.map`, :func:`~mlens.parallel.backend.ParallelProcessing.stack` Parameters ---------- caller : iterable Iterable that generates accepted task instances. Caller should be a child of the :class:`~mlens.parallel.base.BaseBackend` class, and tasks need to implement an appropriate call method. out : dict A dictionary with output parameters. Pass an empty dict for no output. See :func:`~mlens.parallel.backend.BaseProcessor.initialize` for more details. Returns ------- out: array-like, list, optional Prediction array(s). """ check_initialized(self) return_names = out.pop('return_names', []) return_final = out.pop('return_final', False) out = list() if return_names else None tf = self.job.dir if not isinstance(self.job.dir, list) else None with Parallel(n_jobs=self.n_jobs, temp_folder=tf, max_nbytes=None, mmap_mode='w+', verbose=self.verbose, backend=self.backend) as parallel: for task in caller: self.job.clear() self._partial_process(task, parallel, **kwargs) if task.name in return_names: out.append(self.get_preds(dtype=_dtype(task))) self.job.update() if return_final: out = self.get_preds(dtype=_dtype(task)) return out def _partial_process(self, task, parallel, **kwargs): """Process given task""" if self.job.job == 'fit' and getattr(task, 'shuffle', False): self.job.shuffle(getattr(task, 'random_state', None)) task.setup(self.job.predict_in, self.job.targets, self.job.job) if not task.__no_output__: self._gen_prediction_array(task, self.job.job, self.__threading__) task(self.job.args(**kwargs), parallel=parallel) if not task.__no_output__ and getattr(task, 'n_feature_prop', 0): self._propagate_features(task) def _propagate_features(self, task): """Propagate features from input array to output array.""" p_out, p_in = self.job.predict_out, self.job.predict_in # Check for loss of obs between layers (i.e. with blendindex) n_in, n_out = p_in.shape[0], p_out.shape[0] r = int(n_in - n_out) if not issparse(p_in): # Simple item setting p_out[:, :task.n_feature_prop] = p_in[r:, task.propagate_features] else: # Need to populate propagated features using scipy sparse hstack self.job.predict_out = hstack( [p_in[r:, task.propagate_features], p_out[:, task.n_feature_prop:]] ).tolil() def _gen_prediction_array(self, task, job, threading): """Generate prediction array either in-memory or persist to disk.""" shape = task.shape(job) if threading: self.job.predict_out = np.zeros(shape, dtype=_dtype(task)) else: f = os.path.join(self.job.dir, '%s_out_array.mmap' % task.name) try: self.job.predict_out = np.memmap( filename=f, dtype=_dtype(task), mode='w+', shape=shape) except Exception as exc: raise OSError( "Cannot create prediction matrix of shape (" "%i, %i), size %i MBs, for %s.\n Details:\n%r" % (shape[0], shape[1], 8 * shape[0] * shape[1] / (1024 ** 2), task.name, exc)) def get_preds(self, dtype=None, order='C'): """Return prediction matrix. Parameters ---------- dtype : numpy dtype object, optional data type to return order : str (default = 'C') data order. See :class:`numpy.asarray` for details. Returns ------- P: array-like Prediction array """ if not hasattr(self, 'job'): raise ParallelProcessingError( "Processor has been terminated:\ncannot retrieve final " "prediction array from cache.") if dtype is None: dtype = config.get_dtype() if issparse(self.job.predict_out): return self.job.predict_out return np.asarray(self.job.predict_out, dtype=dtype, order=order) ############################################################################### class ParallelEvaluation(BaseProcessor): """Parallel cross-validation engine. Minimal parallel processing engine. Similar to :class:`ParallelProcessing`, but offers less features, only fits the *callers* indexer, and excepts no task output. """ def __init__(self, *args, **kwargs): super(ParallelEvaluation, self).__init__(*args, **kwargs) def process(self, caller, case, X, y, path=None, **kwargs): """Process caller. Parameters ---------- caller: iterable Iterable for evaluation job.s Expected caller is a :class:`Evaluator` instance. case: str evaluation case to run on the evaluator. One of ``'preprocess'`` and ``'evaluate'``. X: array-like of shape [n_samples, n_features] Input data y: array-like of shape [n_samples,], optional. targets. Required for fit, should not be passed to predict or transform jobs. path: str or dict, optional Custom estimation cache. Pass a string to force use of persistent cache on disk. Pass a ``dict`` for in-memory cache (requires ``backend != 'multiprocessing'``. """ self._initialize( job='fit', X=X, y=y, path=path, split=False, stack=False) check_initialized(self) # Use context manager to ensure same parallel job during entire process tf = self.job.dir if not isinstance(self.job.dir, list) else None with Parallel(n_jobs=self.n_jobs, temp_folder=tf, max_nbytes=None, mmap_mode='w+', verbose=self.verbose, backend=self.backend) as parallel: caller.indexer.fit(self.job.predict_in, self.job.targets, self.job.job) caller(parallel, self.job.args(**kwargs), case)
unknown
codeparrot/codeparrot-clean
import numpy as np import pytest from pandas._libs.tslibs import IncompatibleFrequency from pandas import ( DataFrame, Period, Series, Timestamp, date_range, period_range, to_datetime, ) import pandas._testing as tm @pytest.fixture def date_range_frame(): """ Fixture for DataFrame of ints with date_range index Columns are ['A', 'B']. """ N = 50 rng = date_range("1/1/1990", periods=N, freq="53s") return DataFrame({"A": np.arange(N), "B": np.arange(N)}, index=rng) class TestFrameAsof: def test_basic(self, date_range_frame): # Explicitly cast to float to avoid implicit cast when setting np.nan df = date_range_frame.astype({"A": "float"}) N = 50 df.loc[df.index[15:30], "A"] = np.nan dates = date_range("1/1/1990", periods=N * 3, freq="25s") result = df.asof(dates) assert result.notna().all(axis=1).all() lb = df.index[14] ub = df.index[30] dates = list(dates) result = df.asof(dates) assert result.notna().all(axis=1).all() mask = (result.index >= lb) & (result.index < ub) rs = result[mask] assert (rs == 14).all(axis=1).all() def test_subset(self, date_range_frame): N = 10 # explicitly cast to float to avoid implicit upcast when setting to np.nan df = date_range_frame.iloc[:N].copy().astype({"A": "float"}) df.loc[df.index[4:8], "A"] = np.nan dates = date_range("1/1/1990", periods=N * 3, freq="25s") # with a subset of A should be the same result = df.asof(dates, subset="A") expected = df.asof(dates) tm.assert_frame_equal(result, expected) # same with A/B result = df.asof(dates, subset=["A", "B"]) expected = df.asof(dates) tm.assert_frame_equal(result, expected) # B gives df.asof result = df.asof(dates, subset="B") expected = df.resample("25s", closed="right").ffill().reindex(dates) expected.iloc[20:] = 9 # no "missing", so "B" can retain int dtype (df["A"].dtype platform-dependent) expected["B"] = expected["B"].astype(df["B"].dtype) tm.assert_frame_equal(result, expected) def test_missing(self, date_range_frame): # GH 15118 # no match found - `where` value before earliest date in index N = 10 # Cast to 'float64' to avoid upcast when introducing nan in df.asof df = date_range_frame.iloc[:N].copy().astype("float64") result = df.asof("1989-12-31") expected = Series( index=["A", "B"], name=Timestamp("1989-12-31"), dtype=np.float64 ) tm.assert_series_equal(result, expected) result = df.asof(to_datetime(["1989-12-31"])) expected = DataFrame( index=to_datetime(["1989-12-31"]), columns=["A", "B"], dtype="float64" ) tm.assert_frame_equal(result, expected) # Check that we handle PeriodIndex correctly, dont end up with # period.ordinal for series name df = df.to_period("D") result = df.asof("1989-12-31") assert isinstance(result.name, Period) def test_asof_all_nans(self, frame_or_series): # GH 15713 # DataFrame/Series is all nans result = frame_or_series([np.nan]).asof([0]) expected = frame_or_series([np.nan]) tm.assert_equal(result, expected) def test_all_nans(self, date_range_frame): # GH 15713 # DataFrame is all nans # testing non-default indexes, multiple inputs N = 150 rng = date_range_frame.index dates = date_range("1/1/1990", periods=N, freq="25s") result = DataFrame(np.nan, index=rng, columns=["A"]).asof(dates) expected = DataFrame(np.nan, index=dates, columns=["A"]) tm.assert_frame_equal(result, expected) # testing multiple columns dates = date_range("1/1/1990", periods=N, freq="25s") result = DataFrame(np.nan, index=rng, columns=["A", "B", "C"]).asof(dates) expected = DataFrame(np.nan, index=dates, columns=["A", "B", "C"]) tm.assert_frame_equal(result, expected) # testing scalar input result = DataFrame(np.nan, index=[1, 2], columns=["A", "B"]).asof([3]) expected = DataFrame(np.nan, index=[3], columns=["A", "B"]) tm.assert_frame_equal(result, expected) result = DataFrame(np.nan, index=[1, 2], columns=["A", "B"]).asof(3) expected = Series(np.nan, index=["A", "B"], name=3) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "stamp,expected", [ ( Timestamp("2018-01-01 23:22:43.325+00:00"), Series(2, name=Timestamp("2018-01-01 23:22:43.325+00:00")), ), ( Timestamp("2018-01-01 22:33:20.682+01:00"), Series(1, name=Timestamp("2018-01-01 22:33:20.682+01:00")), ), ], ) def test_time_zone_aware_index(self, stamp, expected): # GH21194 # Testing awareness of DataFrame index considering different # UTC and timezone df = DataFrame( data=[1, 2], index=[ Timestamp("2018-01-01 21:00:05.001+00:00"), Timestamp("2018-01-01 22:35:10.550+00:00"), ], ) result = df.asof(stamp) tm.assert_series_equal(result, expected) def test_asof_periodindex_mismatched_freq(self): N = 50 rng = period_range("1/1/1990", periods=N, freq="h") df = DataFrame(np.random.default_rng(2).standard_normal(N), index=rng) # Mismatched freq msg = "Input has different freq" with pytest.raises(IncompatibleFrequency, match=msg): df.asof(rng.asfreq("D")) def test_asof_preserves_bool_dtype(self): # GH#16063 was casting bools to floats dti = date_range("2017-01-01", freq="MS", periods=4) ser = Series([True, False, True], index=dti[:-1]) ts = dti[-1] res = ser.asof([ts]) expected = Series([True], index=[ts]) tm.assert_series_equal(res, expected)
python
github
https://github.com/pandas-dev/pandas
pandas/tests/frame/methods/test_asof.py
/* NOLINT(build/header_guard) */ /* Copyright 2010 Google Inc. All Rights Reserved. Distributed under MIT license. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT */ /* template parameters: FN */ /* A (forgetful) hash table to the data seen by the compressor, to help create backward references to previous data. This is a hash map of fixed size (bucket_size_) to a ring buffer of fixed size (block_size_). The ring buffer contains the last block_size_ index positions of the given hash key in the compressed data. */ #define HashLongestMatch HASHER() #define TAG_HASH_BITS 8 #define TAG_HASH_MASK ((1 << TAG_HASH_BITS) - 1) static BROTLI_INLINE size_t FN(HashTypeLength)(void) { return 4; } static BROTLI_INLINE size_t FN(StoreLookahead)(void) { return 4; } /* HashBytes is the function that chooses the bucket to place the address in. */ static uint32_t FN(HashBytes)( const uint8_t* BROTLI_RESTRICT data, const int shift) { uint32_t h = BROTLI_UNALIGNED_LOAD32LE(data) * kHashMul32; /* The higher bits contain more mixture from the multiplication, so we take our results from there. */ return (uint32_t)(h >> shift); } typedef struct HashLongestMatch { /* Number of hash buckets. */ size_t bucket_size_; /* Only block_size_ newest backward references are kept, and the older are forgotten. */ size_t block_size_; /* Left-shift for computing hash bucket index from hash value. */ int hash_shift_; /* Mask for accessing entries in a block (in a ring-buffer manner). */ uint32_t block_mask_; int block_bits_; int num_last_distances_to_check_; /* Shortcuts. */ HasherCommon* common_; /* --- Dynamic size members --- */ /* Number of entries in a particular bucket. */ uint16_t* num_; /* uint16_t[bucket_size]; */ uint8_t* tags_; /* Buckets containing block_size_ of backward references. */ uint32_t* buckets_; /* uint32_t[bucket_size * block_size]; */ } HashLongestMatch; static void FN(Initialize)( HasherCommon* common, HashLongestMatch* BROTLI_RESTRICT self, const BrotliEncoderParams* params) { self->common_ = common; BROTLI_UNUSED(params); self->hash_shift_ = 32 - common->params.bucket_bits - TAG_HASH_BITS; self->bucket_size_ = (size_t)1 << common->params.bucket_bits; self->block_size_ = (size_t)1 << common->params.block_bits; self->block_mask_ = (uint32_t)(self->block_size_ - 1); self->num_ = (uint16_t*)common->extra[0]; self->tags_ = (uint8_t*)common->extra[1]; self->buckets_ = (uint32_t*)common->extra[2]; self->block_bits_ = common->params.block_bits; self->num_last_distances_to_check_ = common->params.num_last_distances_to_check; } static void FN(Prepare)( HashLongestMatch* BROTLI_RESTRICT self, BROTLI_BOOL one_shot, size_t input_size, const uint8_t* BROTLI_RESTRICT data) { uint16_t* BROTLI_RESTRICT num = self->num_; /* Partial preparation is 100 times slower (per socket). */ size_t partial_prepare_threshold = self->bucket_size_ >> 6; if (one_shot && input_size <= partial_prepare_threshold) { size_t i; for (i = 0; i < input_size; ++i) { const uint32_t hash = FN(HashBytes)(&data[i], self->hash_shift_); const uint32_t key = hash >> TAG_HASH_BITS; num[key] = 65535; } } else { /* Set all the bytes of num to 255, which makes each uint16_t 65535. */ memset(num, 255, self->bucket_size_ * sizeof(num[0])); } } static BROTLI_INLINE void FN(HashMemAllocInBytes)( const BrotliEncoderParams* params, BROTLI_BOOL one_shot, size_t input_size, size_t* alloc_size) { size_t bucket_size = (size_t)1 << params->hasher.bucket_bits; size_t block_size = (size_t)1 << params->hasher.block_bits; BROTLI_UNUSED(one_shot); BROTLI_UNUSED(input_size); alloc_size[0] = sizeof(uint16_t) * bucket_size; alloc_size[1] = sizeof(uint8_t) * bucket_size * block_size; alloc_size[2] = sizeof(uint32_t) * bucket_size * block_size; } /* Look at 4 bytes at &data[ix & mask]. Compute a hash from these, and store the value of ix at that position. */ static BROTLI_INLINE void FN(Store)( HashLongestMatch* BROTLI_RESTRICT self, const uint8_t* BROTLI_RESTRICT data, const size_t mask, const size_t ix) { uint16_t* BROTLI_RESTRICT num = self->num_; uint8_t* BROTLI_RESTRICT tags = self->tags_; uint32_t* BROTLI_RESTRICT buckets = self->buckets_; const size_t hash = FN(HashBytes)(&data[ix & mask], self->hash_shift_); const size_t key = hash >> TAG_HASH_BITS; const uint8_t tag = hash & TAG_HASH_MASK; const size_t minor_ix = num[key] & self->block_mask_; const size_t offset = minor_ix + (key << self->block_bits_); --num[key]; buckets[offset] = (uint32_t)ix; tags[offset] = tag; } static BROTLI_INLINE void FN(StoreRange)(HashLongestMatch* BROTLI_RESTRICT self, const uint8_t* BROTLI_RESTRICT data, const size_t mask, const size_t ix_start, const size_t ix_end) { size_t i; for (i = ix_start; i < ix_end; ++i) { FN(Store)(self, data, mask, i); } } static BROTLI_INLINE void FN(StitchToPreviousBlock)( HashLongestMatch* BROTLI_RESTRICT self, size_t num_bytes, size_t position, const uint8_t* ringbuffer, size_t ringbuffer_mask) { if (num_bytes >= FN(HashTypeLength)() - 1 && position >= 3) { /* Prepare the hashes for three last bytes of the last write. These could not be calculated before, since they require knowledge of both the previous and the current block. */ FN(Store)(self, ringbuffer, ringbuffer_mask, position - 3); FN(Store)(self, ringbuffer, ringbuffer_mask, position - 2); FN(Store)(self, ringbuffer, ringbuffer_mask, position - 1); } } static BROTLI_INLINE void FN(PrepareDistanceCache)( HashLongestMatch* BROTLI_RESTRICT self, int* BROTLI_RESTRICT distance_cache) { PrepareDistanceCache(distance_cache, self->num_last_distances_to_check_); } /* Find a longest backward match of &data[cur_ix] up to the length of max_length and stores the position cur_ix in the hash table. REQUIRES: FN(PrepareDistanceCache) must be invoked for current distance cache values; if this method is invoked repeatedly with the same distance cache values, it is enough to invoke FN(PrepareDistanceCache) once. Does not look for matches longer than max_length. Does not look for matches further away than max_backward. Writes the best match into |out|. |out|->score is updated only if a better match is found. */ static BROTLI_INLINE void FN(FindLongestMatch)( HashLongestMatch* BROTLI_RESTRICT self, const BrotliEncoderDictionary* dictionary, const uint8_t* BROTLI_RESTRICT data, const size_t ring_buffer_mask, const int* BROTLI_RESTRICT distance_cache, const size_t cur_ix, const size_t max_length, const size_t max_backward, const size_t dictionary_distance, const size_t max_distance, HasherSearchResult* BROTLI_RESTRICT out) { uint16_t* BROTLI_RESTRICT num = self->num_; uint32_t* BROTLI_RESTRICT buckets = self->buckets_; uint8_t* BROTLI_RESTRICT tags = self->tags_; const size_t cur_ix_masked = cur_ix & ring_buffer_mask; /* Don't accept a short copy from far away. */ score_t min_score = out->score; score_t best_score = out->score; size_t best_len = out->len; size_t i; /* Precalculate the hash key and prefetch the bucket. */ const uint32_t hash = FN(HashBytes)(&data[cur_ix_masked], self->hash_shift_); const uint32_t key = hash >> TAG_HASH_BITS; uint32_t* BROTLI_RESTRICT bucket = &buckets[key << self->block_bits_]; uint8_t* BROTLI_RESTRICT tag_bucket = &tags[key << self->block_bits_]; PREFETCH_L1(bucket); PREFETCH_L1(tag_bucket); if (self->block_bits_ > 4) PREFETCH_L1(bucket + 16); out->len = 0; out->len_code_delta = 0; BROTLI_DCHECK(cur_ix_masked + max_length <= ring_buffer_mask); /* Try last distance first. */ for (i = 0; i < (size_t)self->num_last_distances_to_check_; ++i) { const size_t backward = (size_t)distance_cache[i]; size_t prev_ix = (size_t)(cur_ix - backward); if (prev_ix >= cur_ix) { continue; } if (BROTLI_PREDICT_FALSE(backward > max_backward)) { continue; } prev_ix &= ring_buffer_mask; if (cur_ix_masked + best_len > ring_buffer_mask) { break; } if (prev_ix + best_len > ring_buffer_mask || data[cur_ix_masked + best_len] != data[prev_ix + best_len]) { continue; } { const size_t len = FindMatchLengthWithLimit(&data[prev_ix], &data[cur_ix_masked], max_length); if (len >= 3 || (len == 2 && i < 2)) { /* Comparing for >= 2 does not change the semantics, but just saves for a few unnecessary binary logarithms in backward reference score, since we are not interested in such short matches. */ score_t score = BackwardReferenceScoreUsingLastDistance(len); if (best_score < score) { if (i != 0) score -= BackwardReferencePenaltyUsingLastDistance(i); if (best_score < score) { best_score = score; best_len = len; out->len = best_len; out->distance = backward; out->score = best_score; } } } } } /* we require matches of len >4, so increase best_len to 3, so we can compare * 4 bytes all the time. */ if (best_len < 3) { best_len = 3; } { const uint8_t tag = hash & TAG_HASH_MASK; const size_t head = (num[key] + 1) & self->block_mask_; uint64_t matches = GetMatchingTagMask(self->block_size_ / 16, tag, tag_bucket, head); /* Mask off any matches from uninitialized tags. */ uint16_t n = 65535 - num[key]; uint64_t block_has_unused_slots = self->block_size_ > n; uint64_t mask = (block_has_unused_slots << (n & (64 - 1))) - 1; matches &= mask; for (; matches > 0; matches &= (matches - 1)) { const size_t rb_index = (head + (size_t)BROTLI_TZCNT64(matches)) & self->block_mask_; size_t prev_ix = bucket[rb_index]; const size_t backward = cur_ix - prev_ix; if (BROTLI_PREDICT_FALSE(backward > max_backward)) { break; } prev_ix &= ring_buffer_mask; if (cur_ix_masked + best_len > ring_buffer_mask) { break; } if (prev_ix + best_len > ring_buffer_mask || /* compare 4 bytes ending at best_len + 1 */ BrotliUnalignedRead32(&data[cur_ix_masked + best_len - 3]) != BrotliUnalignedRead32(&data[prev_ix + best_len - 3])) { continue; } { const size_t len = FindMatchLengthWithLimit(&data[prev_ix], &data[cur_ix_masked], max_length); if (len >= 4) { /* Comparing for >= 3 does not change the semantics, but just saves for a few unnecessary binary logarithms in backward reference score, since we are not interested in such short matches. */ score_t score = BackwardReferenceScore(len, backward); if (best_score < score) { best_score = score; best_len = len; out->len = best_len; out->distance = backward; out->score = best_score; } } } } bucket[num[key] & self->block_mask_] = (uint32_t)cur_ix; tag_bucket[num[key] & self->block_mask_] = tag; --num[key]; } if (min_score == out->score) { SearchInStaticDictionary(dictionary, self->common_, &data[cur_ix_masked], max_length, dictionary_distance, max_distance, out, BROTLI_FALSE); } } #undef HashLongestMatch
c
github
https://github.com/nodejs/node
deps/brotli/c/enc/hash_longest_match_simd_inc.h
from couchpotato.core.event import fireEvent from couchpotato.core.helpers.encoding import tryUrlencode from couchpotato.core.helpers.rss import RSS from couchpotato.core.helpers.variable import cleanHost from couchpotato.core.logger import CPLog from couchpotato.core.providers.nzb.base import NZBProvider from couchpotato.environment import Env from dateutil.parser import parse from urllib2 import HTTPError from urlparse import urlparse import time import traceback import xml.etree.ElementTree as XMLTree log = CPLog(__name__) class Newznab(NZBProvider, RSS): urls = { 'download': 'get&id=%s', 'detail': 'details&id=%s', 'search': 'movie', } limits_reached = {} cat_ids = [ ([2010], ['dvdr']), ([2030], ['cam', 'ts', 'dvdrip', 'tc', 'r5', 'scr']), ([2040], ['720p', '1080p']), ([2050], ['bd50']), ] cat_backup_id = 2000 http_time_between_calls = 1 # Seconds def feed(self): hosts = self.getHosts() results = [] for host in hosts: result = self.singleFeed(host) if result: results.extend(result) return results def singleFeed(self, host): results = [] if self.isDisabled(host): return results arguments = tryUrlencode({ 't': self.cat_backup_id, 'r': host['api_key'], 'i': 58, }) url = "%s?%s" % (cleanHost(host['host']) + 'rss', arguments) cache_key = 'newznab.%s.feed.%s' % (host['host'], arguments) results = self.createItems(url, cache_key, host, for_feed = True) return results def search(self, movie, quality): hosts = self.getHosts() results = [] for host in hosts: result = self.singleSearch(host, movie, quality) if result: results.extend(result) return results def singleSearch(self, host, movie, quality): results = [] if self.isDisabled(host): return results cat_id = self.getCatId(quality['identifier']) arguments = tryUrlencode({ 'imdbid': movie['library']['identifier'].replace('tt', ''), 'cat': cat_id[0], 'apikey': host['api_key'], 'extended': 1 }) url = "%s&%s" % (self.getUrl(host['host'], self.urls['search']), arguments) cache_key = 'newznab.%s.%s.%s' % (host['host'], movie['library']['identifier'], cat_id[0]) results = self.createItems(url, cache_key, host, movie = movie, quality = quality) return results def createItems(self, url, cache_key, host, movie = None, quality = None, for_feed = False): results = [] data = self.getCache(cache_key, url, cache_timeout = 1800, headers = {'User-Agent': Env.getIdentifier()}) if data: try: try: data = XMLTree.fromstring(data) nzbs = self.getElements(data, 'channel/item') except Exception, e: log.debug('%s, %s', (self.getName(), e)) return results results = [] for nzb in nzbs: date = '' size = 0 for item in nzb: if item.attrib.get('name') == 'size': size = item.attrib.get('value') elif item.attrib.get('name') == 'usenetdate': date = item.attrib.get('value') if date is '': log.debug('Date not parsed properly or not available for %s: %s', (host['host'], self.getTextElement(nzb, "title"))) if size is 0: log.debug('Size not parsed properly or not available for %s: %s', (host['host'], self.getTextElement(nzb, "title"))) id = self.getTextElement(nzb, "guid").split('/')[-1:].pop() new = { 'id': id, 'provider': self.getName(), 'type': 'nzb', 'name': self.getTextElement(nzb, "title"), 'age': self.calculateAge(int(time.mktime(parse(date).timetuple()))), 'size': int(size) / 1024 / 1024, 'url': (self.getUrl(host['host'], self.urls['download']) % id) + self.getApiExt(host), 'download': self.download, 'detail_url': '%sdetails/%s' % (cleanHost(host['host']), id), 'content': self.getTextElement(nzb, "description"), } if not for_feed: is_correct_movie = fireEvent('searcher.correct_movie', nzb = new, movie = movie, quality = quality, imdb_results = True, single = True) if is_correct_movie: new['score'] = fireEvent('score.calculate', new, movie, single = True) results.append(new) self.found(new) else: results.append(new) return results except SyntaxError: log.error('Failed to parse XML response from Newznab: %s', host) return results def getHosts(self): uses = [x.strip() for x in str(self.conf('use')).split(',')] hosts = [x.strip() for x in self.conf('host').split(',')] api_keys = [x.strip() for x in self.conf('api_key').split(',')] list = [] for nr in range(len(hosts)): list.append({ 'use': uses[nr], 'host': hosts[nr], 'api_key': api_keys[nr] }) return list def belongsTo(self, url, provider = None): hosts = self.getHosts() for host in hosts: result = super(Newznab, self).belongsTo(url, host = host['host'], provider = provider) if result: return result def getUrl(self, host, type): return cleanHost(host) + 'api?t=' + type def isDisabled(self, host): return not self.isEnabled(host) def isEnabled(self, host): return NZBProvider.isEnabled(self) and host['host'] and host['api_key'] and int(host['use']) def getApiExt(self, host): return '&apikey=%s' % host['api_key'] def download(self, url = '', nzb_id = ''): host = urlparse(url).hostname if self.limits_reached.get(host): # Try again in 3 hours if self.limits_reached[host] > time.time() - 10800: return 'try_next' try: data = self.urlopen(url, show_error = False) self.limits_reached[host] = False return data except HTTPError, e: if e.code == 503: response = e.read().lower() if 'maximum api' in response or 'download limit' in response: if not self.limits_reached.get(host): log.error('Limit reached for newznab provider: %s', host) self.limits_reached[host] = time.time() return 'try_next' log.error('Failed download from %s', (host, traceback.format_exc())) raise
unknown
codeparrot/codeparrot-clean
import logging from langchain_core.callbacks import ( AsyncCallbackManagerForRetrieverRun, CallbackManagerForRetrieverRun, ) from langchain_core.documents import Document from langchain_core.language_models import BaseLLM from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import BasePromptTemplate from langchain_core.prompts.prompt import PromptTemplate from langchain_core.retrievers import BaseRetriever from langchain_core.runnables import Runnable logger = logging.getLogger(__name__) # Default template DEFAULT_TEMPLATE = """You are an assistant tasked with taking a natural language \ query from a user and converting it into a query for a vectorstore. \ In this process, you strip out information that is not relevant for \ the retrieval task. Here is the user query: {question}""" # Default prompt DEFAULT_QUERY_PROMPT = PromptTemplate.from_template(DEFAULT_TEMPLATE) class RePhraseQueryRetriever(BaseRetriever): """Given a query, use an LLM to re-phrase it. Then, retrieve docs for the re-phrased query. """ retriever: BaseRetriever llm_chain: Runnable @classmethod def from_llm( cls, retriever: BaseRetriever, llm: BaseLLM, prompt: BasePromptTemplate = DEFAULT_QUERY_PROMPT, ) -> "RePhraseQueryRetriever": """Initialize from llm using default template. The prompt used here expects a single input: `question` Args: retriever: retriever to query documents from llm: llm for query generation using DEFAULT_QUERY_PROMPT prompt: prompt template for query generation Returns: RePhraseQueryRetriever """ llm_chain = prompt | llm | StrOutputParser() return cls( retriever=retriever, llm_chain=llm_chain, ) def _get_relevant_documents( self, query: str, *, run_manager: CallbackManagerForRetrieverRun, ) -> list[Document]: """Get relevant documents given a user question. Args: query: user question run_manager: callback handler to use Returns: Relevant documents for re-phrased question """ re_phrased_question = self.llm_chain.invoke( query, {"callbacks": run_manager.get_child()}, ) logger.info("Re-phrased question: %s", re_phrased_question) return self.retriever.invoke( re_phrased_question, config={"callbacks": run_manager.get_child()}, ) async def _aget_relevant_documents( self, query: str, *, run_manager: AsyncCallbackManagerForRetrieverRun, ) -> list[Document]: raise NotImplementedError
python
github
https://github.com/langchain-ai/langchain
libs/langchain/langchain_classic/retrievers/re_phraser.py
<!--Copyright 2022 The HuggingFace Team. 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. ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Pipelines para inferência Um [pipeline] simplifica o uso dos modelos no [Model Hub](https://huggingface.co/models) para a inferência de uma diversidade de tarefas, como a geração de texto, a segmentação de imagens e a classificação de áudio. Inclusive, se não tem experiência com alguma modalidade específica ou não compreende o código que forma os modelos, pode usar eles mesmo assim com o [pipeline]! Este tutorial te ensinará a: * Utilizar um [`pipeline`] para inferência. * Utilizar um tokenizador ou model específico. * Utilizar um [`pipeline`] para tarefas de áudio e visão computacional. <Tip> Acesse a documentação do [`pipeline`] para obter uma lista completa de tarefas possíveis. </Tip> ## Uso do pipeline Mesmo que cada tarefa tenha um [`pipeline`] associado, é mais simples usar a abstração geral do [`pipeline`] que contém todos os pipelines das tarefas mais específicas. O [`pipeline`] carrega automaticamenta um modelo predeterminado e um tokenizador com capacidade de inferência para sua tarefa. 1. Comece carregando um [`pipeline`] e especifique uma tarefa de inferência: ```py >>> from transformers import pipeline >>> generator = pipeline(task="text-generation") ``` 2. Passe seu dado de entrada, no caso um texto, ao [`pipeline`]: ```py >>> generator("Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone") [{'generated_text': 'Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone, Seven for the Iron-priests at the door to the east, and thirteen for the Lord Kings at the end of the mountain'}] ``` Se tiver mais de uma entrada, passe-a como uma lista: ```py >>> generator( ... [ ... "Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone", ... "Nine for Mortal Men, doomed to die, One for the Dark Lord on his dark throne", ... ] ... ) ``` Qualquer parâmetro adicional para a sua tarefa também pode ser incluído no [`pipeline`]. A tarefa `text-generation` tem um método [`~generation.GenerationMixin.generate`] com vários parâmetros para controlar a saída. Por exemplo, se quiser gerar mais de uma saída, defina-a no parâmetro `num_return_sequences`: ```py >>> generator( ... "Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone", ... num_return_sequences=2, ... ) ``` ### Selecionando um modelo e um tokenizador O [`pipeline`] aceita qualquer modelo do [Model Hub](https://huggingface.co/models). Há rótulos adicionais no Model Hub que te permitem filtrar pelo modelo que gostaria de usar para sua tarefa. Uma vez que tiver escolhido o modelo apropriado, carregue-o com as classes `AutoModelFor` e [`AutoTokenizer`] correspondentes. Por exemplo, carregue a classe [`AutoModelForCausalLM`] para uma tarefa de modelagem de linguagem causal: ```py >>> from transformers import AutoTokenizer, AutoModelForCausalLM >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2") >>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2") ``` Crie uma [`pipeline`] para a sua tarefa e especifíque o modelo e o tokenizador que foram carregados: ```py >>> from transformers import pipeline >>> generator = pipeline(task="text-generation", model=model, tokenizer=tokenizer) ``` Passe seu texto de entrada ao [`pipeline`] para gerar algum texto: ```py >>> generator("Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone") [{'generated_text': 'Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone, Seven for the Dragon-lords (for them to rule in a world ruled by their rulers, and all who live within the realm'}] ``` ## Pipeline de audio A flexibilidade do [`pipeline`] significa que também pode-se extender às tarefas de áudio. La flexibilidad de [`pipeline`] significa que también se puede extender a tareas de audio. Por exemplo, classifiquemos a emoção de um breve fragmento do famoso discurso de John F. Kennedy /home/rzimmerdev/dev/transformers/docs/source/pt/pipeline_tutorial.md Encontre um modelo de [audio classification](https://huggingface.co/models?pipeline_tag=audio-classification) para reconhecimento de emoções no Model Hub e carregue-o usando o [`pipeline`]: ```py >>> from transformers import pipeline >>> audio_classifier = pipeline( ... task="audio-classification", model="ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition" ... ) ``` Passe o arquivo de áudio ao [`pipeline`]: ```py >>> audio_classifier("jfk_moon_speech.wav") [{'label': 'calm', 'score': 0.13856211304664612}, {'label': 'disgust', 'score': 0.13148026168346405}, {'label': 'happy', 'score': 0.12635163962841034}, {'label': 'angry', 'score': 0.12439591437578201}, {'label': 'fearful', 'score': 0.12404385954141617}] ``` ## Pipeline de visão computacional Finalmente, utilizar um [`pipeline`] para tarefas de visão é praticamente a mesma coisa. Especifique a sua tarefa de visão e passe a sua imagem ao classificador. A imagem pode ser um link ou uma rota local à imagem. Por exemplo, que espécie de gato está presente na imagem? ![pipeline-cat-chonk](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg) ```py >>> from transformers import pipeline >>> vision_classifier = pipeline(task="image-classification") >>> vision_classifier( ... images="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg" ... ) [{'label': 'lynx, catamount', 'score': 0.4403027892112732}, {'label': 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor', 'score': 0.03433405980467796}, {'label': 'snow leopard, ounce, Panthera uncia', 'score': 0.032148055732250214}, {'label': 'Egyptian cat', 'score': 0.02353910356760025}, {'label': 'tiger cat', 'score': 0.023034192621707916}] ```
unknown
github
https://github.com/huggingface/transformers
docs/source/pt/pipeline_tutorial.md
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- MODEL_PARAMS = {'aggregationInfo': {'days': 0, 'fields': [], 'hours': 0, 'microseconds': 0, 'milliseconds': 0, 'minutes': 0, 'months': 0, 'seconds': 0, 'weeks': 0, 'years': 0}, 'model': 'CLA', 'modelParams': { 'anomalyParams': {u'anomalyCacheRecords': None, u'autoDetectThreshold': None, u'autoDetectWaitRecords': None}, 'clParams': {'alpha': 0.005, 'regionName': 'SDRClassifierRegion', 'implementation': 'py', 'steps': '5'}, 'inferenceType': 'TemporalMultiStep', 'sensorParams': {'encoders': { '_classifierInput': {'classifierOnly': True, 'clipInput': True, 'fieldname': 'passenger_count', 'maxval': 40000, 'minval': 0, 'n': 50 , 'name': '_classifierInput', 'type': 'ScalarEncoder', 'w': 29}, u'timeofday': {'clipInput': True, 'fieldname': 'timeofday', 'maxval': 1411, 'minval': 0, 'n': 600, 'name': 'timeofday', 'type': 'ScalarEncoder', 'periodic': True, 'verbosity': 0, 'w': 29}, u'dayofweek': {'clipInput': True, 'fieldname': 'dayofweek', 'maxval': 7, 'minval': 0, 'n': 100, 'name': 'dayofweek', 'type': 'ScalarEncoder', 'periodic': True, 'verbosity': 0, 'w': 29}, u'passenger_count': {'clipInput': True, 'fieldname': 'passenger_count', 'maxval': 40000, 'minval': 0, 'n': 109, 'name': 'passenger_count', 'type': 'ScalarEncoder', 'verbosity': 0, 'w': 29}}, 'sensorAutoReset': None, 'verbosity': 0}, 'spEnable': True, 'spParams': {'columnCount': 2048, 'globalInhibition': 1, 'inputWidth': 0, 'boostStrength': 0.0, 'numActiveColumnsPerInhArea': 40, 'potentialPct': 0.8, 'seed': 1956, 'spVerbosity': 1, 'spatialImp': 'cpp', 'synPermActiveInc': 0.005, 'synPermConnected': 0.5, 'synPermInactiveDec': 0.002}, 'tpEnable': True, 'tpParams': {'activationThreshold': 15, 'cellsPerColumn': 32, 'columnCount': 2048, 'globalDecay': 0.0, 'initialPerm': 0.21, 'inputWidth': 2048, 'maxAge': 0, 'maxSegmentsPerCell': 128, 'maxSynapsesPerSegment': 128, 'minThreshold': 15, 'newSynapseCount': 32, 'outputType': 'normal', 'pamLength': 1, 'permanenceDec': 0.1, 'permanenceInc': 0.1, 'predictedSegmentDecrement': 0.01, 'seed': 1960, 'temporalImp': 'tm_cpp', 'verbosity': 0}, 'trainSPNetOnlyIfRequested': False}, 'predictAheadTime': None, 'version': 1}
unknown
codeparrot/codeparrot-clean
""" Django settings for kanban project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '0&vwr2+g-jpq0)thn!gric1@h3cgc^u1%6#(eyklqz^p4zfic5' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')] ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'board', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'kanban.urls' WSGI_APPLICATION = 'kanban.wsgi.application' # Database # https://docs.djangoproject.com/en/1.7/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.7/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'EST' USE_I18N = True USE_L10N = True USE_TZ = True LOGIN_REDIRECT_URL='/board/' LOGIN_URL ='/board/login' LOGOUT_URL ='/board/logout' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.7/howto/static-files/ STATIC_URL = '/static/'
unknown
codeparrot/codeparrot-clean
// Copyright 2023 The etcd Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in 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. //nolint:unparam package validate import ( "errors" "math" "testing" "time" "github.com/anishathalye/porcupine" "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" clientv3 "go.etcd.io/etcd/client/v3" "go.etcd.io/etcd/tests/v3/robustness/identity" "go.etcd.io/etcd/tests/v3/robustness/model" "go.etcd.io/etcd/tests/v3/robustness/report" ) const infinite = math.MaxInt64 func TestPatchHistory(t *testing.T) { for _, tc := range []struct { name string historyFunc func(h *model.AppendableHistory) persistedRequest []model.EtcdRequest watchOperations []model.WatchOperation expectedRemainingOperations []porcupine.Operation }{ { name: "successful range remains", historyFunc: func(h *model.AppendableHistory) { h.AppendRange("key", "", 0, 0, 100, 200, &clientv3.GetResponse{}, nil) }, expectedRemainingOperations: []porcupine.Operation{ {Return: 200, Output: rangeResponse(0)}, }, }, { name: "successful put remains", historyFunc: func(h *model.AppendableHistory) { h.AppendPut("key", "value", 100, 200, &clientv3.PutResponse{}, nil) }, persistedRequest: []model.EtcdRequest{ putRequest("key", "value"), }, expectedRemainingOperations: []porcupine.Operation{ {Return: 200, Output: txnResponse(0, model.EtcdOperationResult{})}, }, }, { name: "failed put remains if there is a matching event, return time untouched", historyFunc: func(h *model.AppendableHistory) { h.AppendPut("key", "value", 100, 200, nil, errors.New("failed")) }, persistedRequest: []model.EtcdRequest{ putRequest("key", "value"), }, expectedRemainingOperations: []porcupine.Operation{ {Return: infinite, Output: model.MaybeEtcdResponse{Persisted: true}}, }, }, { name: "failed put remains if there is a matching event, uniqueness allows for return time to be based on next persisted request", historyFunc: func(h *model.AppendableHistory) { h.AppendPut("key1", "value", 100, 200, nil, errors.New("failed")) h.AppendPut("key2", "value", 300, 400, &clientv3.PutResponse{}, nil) }, persistedRequest: []model.EtcdRequest{ putRequest("key1", "value"), putRequest("key2", "value"), }, expectedRemainingOperations: []porcupine.Operation{ {Return: 399, Output: model.MaybeEtcdResponse{Persisted: true}}, {Return: 400, Output: txnResponse(0, model.EtcdOperationResult{})}, }, }, { name: "failed put remains if there is a matching persisted request, uniqueness allows for revision to be based on watch", historyFunc: func(h *model.AppendableHistory) { h.AppendPut("key", "value", 100, 200, nil, errors.New("failed")) }, persistedRequest: []model.EtcdRequest{ putRequest("key", "value"), }, watchOperations: watchResponse(300, putEvent("key", "value", 2)), expectedRemainingOperations: []porcupine.Operation{ {Return: infinite, Output: model.MaybeEtcdResponse{Persisted: true, PersistedRevision: 2}}, }, }, { name: "failed put remains if there is a matching persisted request, lack of uniqueness causes time to be untouched regardless of persisted event and watch", historyFunc: func(h *model.AppendableHistory) { h.AppendPut("key", "value", 1, 2, nil, errors.New("failed")) h.AppendPut("key", "value", 3, 4, &clientv3.PutResponse{}, nil) }, persistedRequest: []model.EtcdRequest{ putRequest("key", "value"), putRequest("key", "value"), }, watchOperations: watchResponse(3, putEvent("key", "value", 2), putEvent("key", "value", 3)), expectedRemainingOperations: []porcupine.Operation{ {Return: infinite, Output: model.MaybeEtcdResponse{Error: "failed"}}, {Return: 4, Output: txnResponse(0, model.EtcdOperationResult{})}, }, }, { name: "failed put is dropped if event has different key", historyFunc: func(h *model.AppendableHistory) { h.AppendPut("key2", "value", 100, 200, &clientv3.PutResponse{}, nil) h.AppendPut("key1", "value", 300, 400, nil, errors.New("failed")) }, persistedRequest: []model.EtcdRequest{ putRequest("key2", "value"), }, expectedRemainingOperations: []porcupine.Operation{ {Return: 200, Output: txnResponse(0, model.EtcdOperationResult{})}, }, }, { name: "failed put is dropped if event has different value", historyFunc: func(h *model.AppendableHistory) { h.AppendPut("key", "value2", 100, 200, &clientv3.PutResponse{}, nil) h.AppendPut("key", "value1", 300, 400, nil, errors.New("failed")) }, persistedRequest: []model.EtcdRequest{ putRequest("key", "value2"), }, expectedRemainingOperations: []porcupine.Operation{ {Return: 200, Output: txnResponse(0, model.EtcdOperationResult{})}, }, }, { name: "failed put with lease remains if there is a matching event, return time untouched", historyFunc: func(h *model.AppendableHistory) { h.AppendPutWithLease("key", "value", 123, 100, 200, nil, errors.New("failed")) }, persistedRequest: []model.EtcdRequest{ putRequestWithLease("key", "value", 123), }, expectedRemainingOperations: []porcupine.Operation{ {Return: infinite, Output: model.MaybeEtcdResponse{Persisted: true}}, }, }, { name: "failed put with lease remains if there is a matching event, uniqueness allows return time to be based on next persisted request", historyFunc: func(h *model.AppendableHistory) { h.AppendPutWithLease("key1", "value", 123, 100, 200, nil, errors.New("failed")) h.AppendPutWithLease("key2", "value", 234, 300, 400, &clientv3.PutResponse{}, nil) }, persistedRequest: []model.EtcdRequest{ putRequestWithLease("key1", "value", 123), putRequestWithLease("key2", "value", 234), }, expectedRemainingOperations: []porcupine.Operation{ {Return: 399, Output: model.MaybeEtcdResponse{Persisted: true}}, {Return: 400, Output: txnResponse(0, model.EtcdOperationResult{})}, }, }, { name: "failed put with lease remains if there is a matching event, uniqueness allows for revision to be based on watch", historyFunc: func(h *model.AppendableHistory) { h.AppendPutWithLease("key", "value", 123, 1, 2, nil, errors.New("failed")) }, persistedRequest: []model.EtcdRequest{ putRequestWithLease("key", "value", 123), }, watchOperations: watchResponse(3, putEvent("key", "value", 2)), expectedRemainingOperations: []porcupine.Operation{ {Return: infinite, Output: model.MaybeEtcdResponse{Persisted: true, PersistedRevision: 2}}, }, }, { name: "failed put with lease remains if there is a matching persisted request, lack of uniqueness causes time to be untouched regardless of persisted event and watch", historyFunc: func(h *model.AppendableHistory) { h.AppendPutWithLease("key", "value", 123, 1, 2, nil, errors.New("failed")) h.AppendPutWithLease("key", "value", 321, 3, 4, &clientv3.PutResponse{}, nil) }, persistedRequest: []model.EtcdRequest{ putRequestWithLease("key", "value", 123), putRequestWithLease("key", "value", 321), }, watchOperations: watchResponse(3, putEvent("key", "value", 2), putEvent("key", "value", 3)), expectedRemainingOperations: []porcupine.Operation{ {Return: infinite, Output: model.MaybeEtcdResponse{Error: "failed"}}, {Return: 4, Output: txnResponse(0, model.EtcdOperationResult{})}, }, }, { name: "failed put is dropped", historyFunc: func(h *model.AppendableHistory) { h.AppendPut("key", "value", 100, 200, nil, errors.New("failed")) }, expectedRemainingOperations: []porcupine.Operation{}, }, { name: "failed put with lease is dropped", historyFunc: func(h *model.AppendableHistory) { h.AppendPutWithLease("key", "value", 123, 100, 200, nil, errors.New("failed")) }, expectedRemainingOperations: []porcupine.Operation{}, }, { name: "successful delete remains", historyFunc: func(h *model.AppendableHistory) { h.AppendDelete("key", 100, 200, &clientv3.DeleteResponse{}, nil) }, expectedRemainingOperations: []porcupine.Operation{ {Return: 200, Output: txnResponse(0, model.EtcdOperationResult{})}, }, }, { name: "failed delete with lease is dropped", historyFunc: func(h *model.AppendableHistory) { h.AppendDelete("key", 100, 200, nil, errors.New("failed")) }, expectedRemainingOperations: []porcupine.Operation{}, }, { name: "failed delete remains, if there is a persisted request", historyFunc: func(h *model.AppendableHistory) { h.AppendDelete("key", 100, 200, nil, errors.New("failed")) }, persistedRequest: []model.EtcdRequest{ deleteRequest("key"), }, expectedRemainingOperations: []porcupine.Operation{ {Return: infinite, Output: model.MaybeEtcdResponse{Persisted: true}}, }, }, { name: "failed delete remains, if there is a persisted request, revision is not patched based on watch due to leaseRevoke also triggering delete watch events", historyFunc: func(h *model.AppendableHistory) { h.AppendDelete("key", 100, 200, nil, errors.New("failed")) }, persistedRequest: []model.EtcdRequest{ deleteRequest("key"), }, watchOperations: watchResponse(3, deleteEvent("key", 2)), expectedRemainingOperations: []porcupine.Operation{ {Return: infinite, Output: model.MaybeEtcdResponse{Persisted: true}}, }, }, { name: "failed delete remains, if there is a matching persisted request, uniqueness of this operation and following operation allows patching based on following operation", historyFunc: func(h *model.AppendableHistory) { h.AppendDelete("key", 100, 200, nil, errors.New("failed")) h.AppendPut("key", "value", 300, 400, &clientv3.PutResponse{}, nil) }, persistedRequest: []model.EtcdRequest{ deleteRequest("key"), putRequest("key", "value"), }, expectedRemainingOperations: []porcupine.Operation{ {Return: 399, Output: model.MaybeEtcdResponse{Persisted: true}}, {Return: 400, Output: txnResponse(0, model.EtcdOperationResult{})}, }, }, { name: "failed delete remains if there is a matching persisted request, lack of uniqueness of this operation prevents patching based on following operation", historyFunc: func(h *model.AppendableHistory) { h.AppendDelete("key", 100, 200, nil, errors.New("failed")) h.AppendPut("key", "value", 300, 400, &clientv3.PutResponse{}, nil) h.AppendDelete("key", 500, 600, &clientv3.DeleteResponse{}, nil) }, persistedRequest: []model.EtcdRequest{ deleteRequest("key"), putRequest("key", "value"), deleteRequest("key"), }, expectedRemainingOperations: []porcupine.Operation{ {Return: infinite, Output: model.MaybeEtcdResponse{Error: "failed"}}, {Return: 400, Output: txnResponse(0, model.EtcdOperationResult{})}, {Return: 600, Output: txnResponse(0, model.EtcdOperationResult{})}, }, }, { name: "failed empty txn is dropped", historyFunc: func(h *model.AppendableHistory) { h.AppendTxn(nil, []clientv3.Op{}, []clientv3.Op{}, 100, 200, nil, errors.New("failed")) }, expectedRemainingOperations: []porcupine.Operation{}, }, { name: "failed txn put is dropped", historyFunc: func(h *model.AppendableHistory) { h.AppendTxn(nil, []clientv3.Op{clientv3.OpPut("key", "value")}, []clientv3.Op{}, 100, 200, nil, errors.New("failed")) }, expectedRemainingOperations: []porcupine.Operation{}, }, { name: "failed txn put remains if there is a matching event", historyFunc: func(h *model.AppendableHistory) { h.AppendTxn(nil, []clientv3.Op{clientv3.OpPut("key", "value")}, []clientv3.Op{}, 100, 200, nil, errors.New("failed")) }, persistedRequest: []model.EtcdRequest{ putRequest("key", "value"), }, expectedRemainingOperations: []porcupine.Operation{ {Return: infinite, Output: model.MaybeEtcdResponse{Persisted: true}}, }, }, { name: "failed txn delete remains", historyFunc: func(h *model.AppendableHistory) { h.AppendTxn(nil, []clientv3.Op{clientv3.OpDelete("key")}, []clientv3.Op{}, 100, 200, nil, errors.New("failed")) }, persistedRequest: []model.EtcdRequest{ deleteRequest("key"), }, expectedRemainingOperations: []porcupine.Operation{ {Return: infinite, Output: model.MaybeEtcdResponse{Persisted: true}}, }, }, { name: "successful txn put/delete remains", historyFunc: func(h *model.AppendableHistory) { h.AppendTxn(nil, []clientv3.Op{clientv3.OpPut("key", "value")}, []clientv3.Op{clientv3.OpDelete("key")}, 100, 200, &clientv3.TxnResponse{Succeeded: true}, nil) }, persistedRequest: []model.EtcdRequest{ putRequest("key", "value"), }, expectedRemainingOperations: []porcupine.Operation{ // It's successful, so it remains as-is with its original response {Return: 200, Output: txnResponse(0)}, }, }, { name: "failed txn empty/delete is dropped", historyFunc: func(h *model.AppendableHistory) { h.AppendTxn(nil, []clientv3.Op{}, []clientv3.Op{clientv3.OpDelete("key")}, 100, 200, nil, errors.New("failed")) }, expectedRemainingOperations: []porcupine.Operation{}, }, { name: "failed txn delete/put remains", historyFunc: func(h *model.AppendableHistory) { h.AppendTxn(nil, []clientv3.Op{clientv3.OpDelete("key")}, []clientv3.Op{clientv3.OpPut("key", "value")}, 100, 200, nil, errors.New("failed")) }, persistedRequest: []model.EtcdRequest{ deleteRequest("key"), }, expectedRemainingOperations: []porcupine.Operation{ {Return: infinite, Output: model.MaybeEtcdResponse{Persisted: true}}, }, }, { name: "failed txn empty/put is dropped", historyFunc: func(h *model.AppendableHistory) { h.AppendTxn(nil, []clientv3.Op{}, []clientv3.Op{clientv3.OpPut("key", "value")}, 100, 200, nil, errors.New("failed")) }, expectedRemainingOperations: []porcupine.Operation{}, }, { name: "failed txn empty/put remains if there is a matching event", historyFunc: func(h *model.AppendableHistory) { h.AppendTxn(nil, []clientv3.Op{clientv3.OpPut("key", "value")}, []clientv3.Op{}, 100, 200, nil, errors.New("failed")) }, persistedRequest: []model.EtcdRequest{ putRequest("key", "value"), }, expectedRemainingOperations: []porcupine.Operation{ {Return: infinite, Output: model.MaybeEtcdResponse{Persisted: true}}, }, }, { name: "failed put remains if there is a matching persisted request, uniqueness of this operation and following operation allows patching based on following operation", historyFunc: func(h *model.AppendableHistory) { h.AppendPut("key1", "value1", 300, 400, nil, errors.New("failed")) h.AppendPut("key2", "value2", 500, 600, &clientv3.PutResponse{}, nil) }, persistedRequest: []model.EtcdRequest{ putRequest("key1", "value1"), putRequest("key2", "value2"), }, expectedRemainingOperations: []porcupine.Operation{ {Return: 599, Output: model.MaybeEtcdResponse{Persisted: true}}, {Return: 600, Output: txnResponse(0, model.EtcdOperationResult{})}, }, }, { name: "failed put remains if there is a matching persisted request, lack of uniqueness of this operation prevents patching based on following operation", historyFunc: func(h *model.AppendableHistory) { h.AppendPut("key1", "value1", 100, 200, &clientv3.PutResponse{}, nil) h.AppendPut("key1", "value1", 300, 400, nil, errors.New("failed")) h.AppendPut("key2", "value2", 500, 600, &clientv3.PutResponse{}, nil) }, persistedRequest: []model.EtcdRequest{ putRequest("key1", "value1"), putRequest("key1", "value1"), putRequest("key2", "value2"), }, expectedRemainingOperations: []porcupine.Operation{ {Return: 200, Output: txnResponse(0, model.EtcdOperationResult{})}, {Return: infinite, Output: model.MaybeEtcdResponse{Error: "failed"}}, {Return: 600, Output: txnResponse(0, model.EtcdOperationResult{})}, }, }, { name: "failed put remains if there is a matching persisted request, lack of uniqueness of following operation prevents patching based on following operation", historyFunc: func(h *model.AppendableHistory) { h.AppendPut("key2", "value2", 100, 200, &clientv3.PutResponse{}, nil) h.AppendPut("key1", "value1", 300, 400, nil, errors.New("failed")) h.AppendPut("key2", "value2", 500, 600, &clientv3.PutResponse{}, nil) }, persistedRequest: []model.EtcdRequest{ putRequest("key2", "value2"), putRequest("key1", "value1"), putRequest("key2", "value2"), }, expectedRemainingOperations: []porcupine.Operation{ {Return: 200, Output: txnResponse(0, model.EtcdOperationResult{})}, // TODO: We can infer that failed operation finished before last operation matching following. {Return: infinite, Output: model.MaybeEtcdResponse{Persisted: true}}, {Return: 600, Output: txnResponse(0, model.EtcdOperationResult{})}, }, }, { name: "failed txn empty/delete remains", historyFunc: func(h *model.AppendableHistory) { h.AppendTxn(nil, []clientv3.Op{}, []clientv3.Op{clientv3.OpDelete("key")}, 100, 200, nil, errors.New("failed")) }, persistedRequest: []model.EtcdRequest{ deleteRequest("key"), }, expectedRemainingOperations: []porcupine.Operation{ {Return: infinite, Output: model.MaybeEtcdResponse{Persisted: true}}, }, }, { name: "failed txn put&delete is dropped", historyFunc: func(h *model.AppendableHistory) { h.AppendTxn(nil, []clientv3.Op{clientv3.OpPut("key", "value1"), clientv3.OpDelete("key")}, []clientv3.Op{}, 100, 200, nil, errors.New("failed")) }, expectedRemainingOperations: []porcupine.Operation{}, }, { name: "failed txn empty/put&delete is dropped", historyFunc: func(h *model.AppendableHistory) { h.AppendTxn(nil, []clientv3.Op{}, []clientv3.Op{clientv3.OpPut("key", "value1"), clientv3.OpDelete("key")}, 100, 200, nil, errors.New("failed")) }, expectedRemainingOperations: []porcupine.Operation{}, }, { name: "failed txn put&delete/put&delete is dropped", historyFunc: func(h *model.AppendableHistory) { h.AppendTxn(nil, []clientv3.Op{clientv3.OpPut("key", "value1"), clientv3.OpDelete("key")}, []clientv3.Op{clientv3.OpPut("key", "value2"), clientv3.OpDelete("key")}, 100, 200, nil, errors.New("failed")) }, expectedRemainingOperations: []porcupine.Operation{}, }, { name: "failed delete remains, time untouched due to non-uniqueness", historyFunc: func(h *model.AppendableHistory) { h.AppendDelete("key", 100, 200, nil, errors.New("failed")) h.AppendDelete("key", 300, 400, &clientv3.DeleteResponse{}, nil) h.AppendPut("key", "value", 500, 600, &clientv3.PutResponse{}, nil) }, persistedRequest: []model.EtcdRequest{ deleteRequest("key"), deleteRequest("key"), putRequest("key", "value"), }, watchOperations: watchResponse(250, deleteEvent("key", 2)), expectedRemainingOperations: []porcupine.Operation{ {Return: infinite, Output: model.MaybeEtcdResponse{Error: "failed"}}, {Return: 400, Output: txnResponse(0, model.EtcdOperationResult{})}, {Return: 600, Output: txnResponse(0, model.EtcdOperationResult{})}, }, }, { name: "failed txn delete is dropped when not persisted", historyFunc: func(h *model.AppendableHistory) { h.AppendTxn(nil, []clientv3.Op{clientv3.OpDelete("key")}, []clientv3.Op{}, 100, 200, nil, errors.New("failed")) }, expectedRemainingOperations: []porcupine.Operation{}, }, { name: "successful compact with unique revision keeps original return time", historyFunc: func(h *model.AppendableHistory) { h.AppendCompact(5, 100, 200, &clientv3.CompactResponse{}, nil) h.AppendPut("key", "value", 300, 400, &clientv3.PutResponse{}, nil) }, persistedRequest: []model.EtcdRequest{ compactRequest(5), putRequest("key", "value"), }, expectedRemainingOperations: []porcupine.Operation{ {Return: 200, Output: model.MaybeEtcdResponse{EtcdResponse: model.EtcdResponse{Revision: -1, Compact: &model.CompactResponse{}}}}, {Return: 400, Output: txnResponse(0, model.EtcdOperationResult{})}, }, }, { name: "failed compact with unique revision is patched with return time", historyFunc: func(h *model.AppendableHistory) { h.AppendCompact(5, 100, 200, nil, errors.New("failed")) h.AppendPut("key", "value", 300, 400, &clientv3.PutResponse{}, nil) }, persistedRequest: []model.EtcdRequest{ compactRequest(5), putRequest("key", "value"), }, expectedRemainingOperations: []porcupine.Operation{ {Return: 399, Output: model.MaybeEtcdResponse{Error: "failed"}}, {Return: 400, Output: txnResponse(0, model.EtcdOperationResult{})}, }, }, { name: "failed compact with non-unique revision remains unchanged", historyFunc: func(h *model.AppendableHistory) { h.AppendCompact(5, 100, 200, nil, errors.New("failed")) h.AppendCompact(5, 300, 400, &clientv3.CompactResponse{}, nil) h.AppendPut("key", "value", 500, 600, &clientv3.PutResponse{}, nil) }, persistedRequest: []model.EtcdRequest{ compactRequest(5), compactRequest(5), putRequest("key", "value"), }, expectedRemainingOperations: []porcupine.Operation{ {Return: infinite, Output: model.MaybeEtcdResponse{Error: "failed"}}, {Return: 400, Output: model.MaybeEtcdResponse{EtcdResponse: model.EtcdResponse{Revision: -1, Compact: &model.CompactResponse{}}}}, {Return: 600, Output: txnResponse(0, model.EtcdOperationResult{})}, }, }, { name: "failed compact with unique revision is dropped when not persisted", historyFunc: func(h *model.AppendableHistory) { h.AppendCompact(5, 100, 200, nil, errors.New("failed")) }, persistedRequest: []model.EtcdRequest{}, expectedRemainingOperations: []porcupine.Operation{}, }, } { t.Run(tc.name, func(t *testing.T) { history := model.NewAppendableHistory(identity.NewIDProvider()) tc.historyFunc(history) reports := []report.ClientReport{ { ClientID: 0, KeyValue: history.History.Operations(), Watch: tc.watchOperations, }, } operations, _, _ := prepareAndCategorizeOperations(reports) patched := patchLinearizableOperations(operations, reports, tc.persistedRequest) if diff := cmp.Diff(tc.expectedRemainingOperations, patched, cmpopts.EquateEmpty(), cmpopts.IgnoreFields(porcupine.Operation{}, "Input", "Call", "ClientId"), ); diff != "" { t.Errorf("Response didn't match expected, diff:\n%s", diff) } }) } } func txnResponse(rev int64, result ...model.EtcdOperationResult) model.MaybeEtcdResponse { return model.MaybeEtcdResponse{EtcdResponse: model.EtcdResponse{Revision: rev, Txn: &model.TxnResponse{Results: result}}} } func watchResponse(responseTime int64, events ...model.WatchEvent) []model.WatchOperation { return []model.WatchOperation{ { Responses: []model.WatchResponse{ { Time: time.Duration(responseTime), Events: events, }, }, }, } } func putEvent(key, value string, revision int64) model.WatchEvent { return model.WatchEvent{ PersistedEvent: model.PersistedEvent{ Event: model.Event{ Type: model.PutOperation, Key: key, Value: model.ToValueOrHash(value), }, Revision: revision, }, } } func deleteEvent(key string, revision int64) model.WatchEvent { return model.WatchEvent{ PersistedEvent: model.PersistedEvent{ Event: model.Event{ Type: model.DeleteOperation, Key: key, }, Revision: revision, }, } } func compactRequest(revision int64) model.EtcdRequest { return model.EtcdRequest{ Type: model.Compact, Compact: &model.CompactRequest{ Revision: revision, }, } }
go
github
https://github.com/etcd-io/etcd
tests/robustness/validate/patch_history_test.go
# Merge a pull request When a pull request has been reviewed and approved by at least one person and all checks have passed, then it's time to merge the pull request. ## Who is expected to merge a pull request? Maintainers are responsible for merging all pull requests. If a maintainer has opened a pull request, then the general rule is that the same maintainer merges the pull request. If a non-maintainer has opened a pull request, then it's suggested that one of the maintainers who reviews the pull request should merge the pull request. ## Checklist of considerations Consider (and ask about) the items on the following checklist before merging a pull request: - Is it reviewed and approved? - Have all checks passed? - Does it have a proper pull request title? - Does it need to be added to the changelog (release notes)? - Does it need backporting? ## Before merge Before actually merging a pull request, consider the following things: ### Status checks Before you can merge a pull request, it must have a review approval, and all the required status checks must pass. ### Format the pull request title The pull request title should be formatted according to `<Area>: <Summary>` (Both "Area" and "Summary" should start with a capital letter). Keep the summary short and understandable for the community as a whole. All commits in a pull request are squashed when merged and the pull request title will be the default subject line of the squashed commit message. It's also used for the [changelog](#what-to-include-in-changelog-and-release-notes). **Example:** `Docs: Change url to URL in all documentation files` See [formatting guidelines](create-pull-request.md#formatting-guidelines) for more information. ### Assign a milestone (automated) The Grafana release process uses a bot to automatically assign pull requests to a milestone to make it easier for release managers to track changes. For example, [generating changelog (release note)](#what-to-include-in-changelog-and-release-notes) must be in a milestone. That being said, _you don't have to assign a milestone manually_ to a pull request. Instead, when it is merged and closed, a bot will then look for the most appropriate milestone and assign it to the pull request. The bot-assigned milestone should always reflect the branch into which the pull request is merged. For example: - For every major and minor release, there is a milestone ending with `.x` (for example, `10.0.x` for the 10.0.x releases). - Pull requests targeting `main` use the `.x` milestone of the next minor (or major) version (you can find that version number inside the `package.json` file). - Backport pull requests use the version of the target branch (for example, `9.4.x` for the `v9.4.x` branch). ### What to include in changelog and release notes At Grafana we generate the [changelog](https://github.com/grafana/grafana/blob/main/CHANGELOG.md) and [release notes](https://grafana.com/docs/grafana/latest/release-notes/) based on merged pull requests. Including changes in the changelog (release notes) is very important to provide a relatively complete picture of what changes a Grafana release actually includes. There's a GitHub action available in the repository named [Update changelog](https://github.com/grafana/grafana/blob/main/.github/workflows/update-changelog.yml) that can be triggered manually to re-generate the changelog and release notes for any release. Exactly what changes should be added to the changelog is hard to answer but here's some general guidance: - Include any bug fix in general. - Include any change that you think would be interesting for the community as a whole. - Skip larger features divided into multiple pull requests since they might go into the release's What's New article. - Use your best judgement and, if you aren't sure, then ask other maintainers for advice. - It's better to err on the side of inclusion. Introducing an unnecessary or duplicate change in the changelog is better than leaving out a change. - Always keep the guidelines in [Format the pull request title](#format-the-pull-request-title) in mind. An active decision to include a change in the changelog needs to be taken for every pull request. There's a pull request check named **Changelog Check** that enforces this rule. By adding or removing labels on the pull request or updating the pull request title, description, or both, the check is re-evaluated. #### Skip changelog If you don't want to include your change in changelog, you need to add a label named **no-changelog** to the pull request. #### Include in changelog To include a pull request in the changelog, add a label named `add to changelog` to the pull request. Then the following additional validation rules are checked: - The title must be formatted according to [Format the pull request title](#format-the-pull-request-title) - The description must include a breaking change notice if the change is labeled to be a breaking change. Refer to [Breaking changes](#breaking-changes) below for more information. Not complying with above rules can make the **Changelog Check** fail with validation errors. The changelog is divided into various sections. Here's how to make a description of a pull request show up in a certain section of the release notes: **Features and enhancements:** Label the pull request with `add to changelog` and any of the other section rules don't apply. **Bug fixes:** Label the pull request with `add to changelog` and either label with `type/bug` or the pull request title contains `fix` or `fixes`. **Plugin development fixes and changes:** Label the pull request with `area/grafana/ui` or `area/grafana/runtime`. **Deprecations:** In case the pull request introduces a deprecation you should document this. Label the pull request with `add to changelog` and use the following template at the end of the pull request description to describe the deprecation change. ```md # Deprecation notice <Deprecation description> ``` **Breaking changes:**<a name="breaking-changes"></a> In case the pull request introduces a breaking change you should document this. Label the pull request with `add to changelog` and `breaking change` and use the following template at the end of the pull request description describing the breaking change: ```md # Release notice breaking change <Breaking change description> ``` ### Backporting Backporting is the process of copying the pull request into the version branch of one or multiple previous releases. Backporting should be a rare exception, reserved only for critical bug fixes, and must be initiated by a Grafana Labs employee. We generally avoid automatic backports, as these changes carry some risk: they typically receive less manual testing than changes included in regular point releases. If a pull request addresses a critical bug and backporting is warranted, a Grafana Labs team member can apply the appropriate `backport vx.x` labels for the relevant release branches. The team will review and approve the backport before proceeding. When the pull request is merged, seperate backport PRs will automatically be creataed. #### Required labels We aim to ensure that we don't backport pull requests unnecessarily. The only scenarios for backporting are typically pull requests that address bugs, have a product approval, or refer to documentation changes. Backport labels need to be followed by either: - `type/bug` label: Pull requests which address bugs - `product-approved` label: Urgent fixes which need product approval, in order to get merged - `type/docs` label: Docs changes - `type/ci` label: Changes to the CI automation > **Note:** You can still backport a pull request after it's been merged. ## Doing the actual merge The best time to actually merge the pull request varies from case to case. All commits in a pull request are squashed. You can change the commit message before merging. Please remember that developers might use the commit information for tasks like reviewing changes of files, doing Git blame, and resolving merge conflicts. While there aren't formal best practices around this process, you can consider the following guidance: **Do:** - Make sure the pull request title is formatted properly before merging. Doing so automatically gives you a good and short summary of the commit. - Leave `Co-authored-by:` lines as is so that co-authors are credited for the contribution. - Remove any commit information that doesn't bring any context to the change. **Consider:** - Keep any references to issues that the pull request fixes, closes, or references. Doing this allows cross-reference between the commit and referenced issue or issues. To finalize the merge, click the **Confirm squash and merge** button. ## After the merge Make sure to close any referenced or related issues. We recommend that you assign the same milestone on the issues that the pull request fixes or closes, but this isn't required.
unknown
github
https://github.com/grafana/grafana
contribute/merge-pull-request.md
# -*- encoding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'French Payroll', 'category': 'Localization/Payroll', 'author': 'Yannick Buron (SYNERPGY)', 'depends': ['hr_payroll', 'l10n_fr'], 'version': '1.0', 'description': """ French Payroll Rules. ===================== - Configuration of hr_payroll for French localization - All main contributions rules for French payslip, for 'cadre' and 'non-cadre' - New payslip report TODO: ----- - Integration with holidays module for deduction and allowance - Integration with hr_payroll_account for the automatic account_move_line creation from the payslip - Continue to integrate the contribution. Only the main contribution are currently implemented - Remake the report under webkit - The payslip.line with appears_in_payslip = False should appears in the payslip interface, but not in the payslip report """, 'active': False, 'data': [ 'l10n_fr_hr_payroll_view.xml', 'l10n_fr_hr_payroll_data.xml', 'views/report_l10nfrfichepaye.xml', 'l10n_fr_hr_payroll_reports.xml', ], 'installable': True }
unknown
codeparrot/codeparrot-clean
/* * Copyright 2002-present the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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. */ package org.springframework.context.annotation; import java.util.LinkedHashSet; import java.util.Set; import org.jspecify.annotations.Nullable; import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionDefaults; import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.BeanNameGenerator; import org.springframework.core.env.Environment; import org.springframework.core.env.EnvironmentCapable; import org.springframework.core.env.StandardEnvironment; import org.springframework.core.io.ResourceLoader; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; import org.springframework.util.PatternMatchUtils; /** * A bean definition scanner that detects bean candidates on the classpath, * registering corresponding bean definitions with a given registry ({@code BeanFactory} * or {@code ApplicationContext}). * * <p>Candidate classes are detected through configurable type filters. The * default filters include classes that are annotated with Spring's * {@link org.springframework.stereotype.Component @Component}, * {@link org.springframework.stereotype.Repository @Repository}, * {@link org.springframework.stereotype.Service @Service}, or * {@link org.springframework.stereotype.Controller @Controller} stereotype. * * <p>Also supports JSR-330's {@link jakarta.inject.Named} annotations, if available. * * @author Mark Fisher * @author Juergen Hoeller * @author Chris Beams * @since 2.5 * @see AnnotationConfigApplicationContext#scan * @see org.springframework.stereotype.Component * @see org.springframework.stereotype.Repository * @see org.springframework.stereotype.Service * @see org.springframework.stereotype.Controller */ public class ClassPathBeanDefinitionScanner extends ClassPathScanningCandidateComponentProvider { private final BeanDefinitionRegistry registry; private BeanDefinitionDefaults beanDefinitionDefaults = new BeanDefinitionDefaults(); private String @Nullable [] autowireCandidatePatterns; private BeanNameGenerator beanNameGenerator = AnnotationBeanNameGenerator.INSTANCE; private ScopeMetadataResolver scopeMetadataResolver = new AnnotationScopeMetadataResolver(); private boolean includeAnnotationConfig = true; /** * Create a new {@code ClassPathBeanDefinitionScanner} for the given bean factory. * @param registry the {@code BeanFactory} to load bean definitions into, in the form * of a {@code BeanDefinitionRegistry} */ public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry) { this(registry, true); } /** * Create a new {@code ClassPathBeanDefinitionScanner} for the given bean factory. * <p>If the passed-in bean factory does not only implement the * {@code BeanDefinitionRegistry} interface but also the {@code ResourceLoader} * interface, it will be used as default {@code ResourceLoader} as well. This will * usually be the case for {@link org.springframework.context.ApplicationContext} * implementations. * <p>If given a plain {@code BeanDefinitionRegistry}, the default {@code ResourceLoader} * will be a {@link org.springframework.core.io.support.PathMatchingResourcePatternResolver}. * <p>If the passed-in bean factory also implements {@link EnvironmentCapable} its * environment will be used by this reader. Otherwise, the reader will initialize and * use a {@link org.springframework.core.env.StandardEnvironment}. All * {@code ApplicationContext} implementations are {@code EnvironmentCapable}, while * normal {@code BeanFactory} implementations are not. * @param registry the {@code BeanFactory} to load bean definitions into, in the form * of a {@code BeanDefinitionRegistry} * @param useDefaultFilters whether to include the default filters for the * {@link org.springframework.stereotype.Component @Component}, * {@link org.springframework.stereotype.Repository @Repository}, * {@link org.springframework.stereotype.Service @Service}, and * {@link org.springframework.stereotype.Controller @Controller} stereotype annotations * @see #setResourceLoader * @see #setEnvironment */ public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters) { this(registry, useDefaultFilters, getOrCreateEnvironment(registry)); } /** * Create a new {@code ClassPathBeanDefinitionScanner} for the given bean factory and * using the given {@link Environment} when evaluating bean definition profile metadata. * <p>If the passed-in bean factory does not only implement the {@code * BeanDefinitionRegistry} interface but also the {@link ResourceLoader} interface, it * will be used as default {@code ResourceLoader} as well. This will usually be the * case for {@link org.springframework.context.ApplicationContext} implementations. * <p>If given a plain {@code BeanDefinitionRegistry}, the default {@code ResourceLoader} * will be a {@link org.springframework.core.io.support.PathMatchingResourcePatternResolver}. * @param registry the {@code BeanFactory} to load bean definitions into, in the form * of a {@code BeanDefinitionRegistry} * @param useDefaultFilters whether to include the default filters for the * {@link org.springframework.stereotype.Component @Component}, * {@link org.springframework.stereotype.Repository @Repository}, * {@link org.springframework.stereotype.Service @Service}, and * {@link org.springframework.stereotype.Controller @Controller} stereotype annotations * @param environment the Spring {@link Environment} to use when evaluating bean * definition profile metadata * @since 3.1 * @see #setResourceLoader */ public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters, Environment environment) { this(registry, useDefaultFilters, environment, (registry instanceof ResourceLoader resourceLoader ? resourceLoader : null)); } /** * Create a new {@code ClassPathBeanDefinitionScanner} for the given bean factory and * using the given {@link Environment} when evaluating bean definition profile metadata. * @param registry the {@code BeanFactory} to load bean definitions into, in the form * of a {@code BeanDefinitionRegistry} * @param useDefaultFilters whether to include the default filters for the * {@link org.springframework.stereotype.Component @Component}, * {@link org.springframework.stereotype.Repository @Repository}, * {@link org.springframework.stereotype.Service @Service}, and * {@link org.springframework.stereotype.Controller @Controller} stereotype annotations * @param environment the Spring {@link Environment} to use when evaluating bean * definition profile metadata * @param resourceLoader the {@link ResourceLoader} to use * @since 4.3.6 */ public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters, Environment environment, @Nullable ResourceLoader resourceLoader) { Assert.notNull(registry, "BeanDefinitionRegistry must not be null"); this.registry = registry; if (useDefaultFilters) { registerDefaultFilters(); } setEnvironment(environment); setResourceLoader(resourceLoader); } /** * Return the BeanDefinitionRegistry that this scanner operates on. */ @Override public final BeanDefinitionRegistry getRegistry() { return this.registry; } /** * Set the defaults to use for detected beans. * @see BeanDefinitionDefaults */ public void setBeanDefinitionDefaults(@Nullable BeanDefinitionDefaults beanDefinitionDefaults) { this.beanDefinitionDefaults = (beanDefinitionDefaults != null ? beanDefinitionDefaults : new BeanDefinitionDefaults()); } /** * Return the defaults to use for detected beans (never {@code null}). * @since 4.1 */ public BeanDefinitionDefaults getBeanDefinitionDefaults() { return this.beanDefinitionDefaults; } /** * Set the name-matching patterns for determining autowire candidates. * @param autowireCandidatePatterns the patterns to match against */ public void setAutowireCandidatePatterns(String @Nullable ... autowireCandidatePatterns) { this.autowireCandidatePatterns = autowireCandidatePatterns; } /** * Set the BeanNameGenerator to use for detected bean classes. * <p>Default is a {@link AnnotationBeanNameGenerator}. */ public void setBeanNameGenerator(@Nullable BeanNameGenerator beanNameGenerator) { this.beanNameGenerator = (beanNameGenerator != null ? beanNameGenerator : AnnotationBeanNameGenerator.INSTANCE); } /** * Set the ScopeMetadataResolver to use for detected bean classes. * Note that this will override any custom "scopedProxyMode" setting. * <p>The default is an {@link AnnotationScopeMetadataResolver}. * @see #setScopedProxyMode */ public void setScopeMetadataResolver(@Nullable ScopeMetadataResolver scopeMetadataResolver) { this.scopeMetadataResolver = (scopeMetadataResolver != null ? scopeMetadataResolver : new AnnotationScopeMetadataResolver()); } /** * Specify the proxy behavior for non-singleton scoped beans. * Note that this will override any custom "scopeMetadataResolver" setting. * <p>The default is {@link ScopedProxyMode#NO}. * @see #setScopeMetadataResolver */ public void setScopedProxyMode(ScopedProxyMode scopedProxyMode) { this.scopeMetadataResolver = new AnnotationScopeMetadataResolver(scopedProxyMode); } /** * Specify whether to register annotation config post-processors. * <p>The default is to register the post-processors. Turn this off * to be able to ignore the annotations or to process them differently. */ public void setIncludeAnnotationConfig(boolean includeAnnotationConfig) { this.includeAnnotationConfig = includeAnnotationConfig; } /** * Perform a scan within the specified base packages. * @param basePackages the packages to check for annotated classes * @return number of beans registered */ public int scan(String... basePackages) { int beanCountAtScanStart = this.registry.getBeanDefinitionCount(); doScan(basePackages); // Register annotation config processors, if necessary. if (this.includeAnnotationConfig) { AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry); } return (this.registry.getBeanDefinitionCount() - beanCountAtScanStart); } /** * Perform a scan within the specified base packages, * returning the registered bean definitions. * <p>This method does <i>not</i> register an annotation config processor * but rather leaves this up to the caller. * @param basePackages the packages to check for annotated classes * @return set of beans registered if any for tooling registration purposes (never {@code null}) */ protected Set<BeanDefinitionHolder> doScan(String... basePackages) { Assert.notEmpty(basePackages, "At least one base package must be specified"); Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>(); for (String basePackage : basePackages) { Set<BeanDefinition> candidates = findCandidateComponents(basePackage); for (BeanDefinition candidate : candidates) { ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate); candidate.setScope(scopeMetadata.getScopeName()); String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry); if (candidate instanceof AbstractBeanDefinition abstractBeanDefinition) { postProcessBeanDefinition(abstractBeanDefinition, beanName); } if (candidate instanceof AnnotatedBeanDefinition annotatedBeanDefinition) { AnnotationConfigUtils.processCommonDefinitionAnnotations(annotatedBeanDefinition); } if (checkCandidate(beanName, candidate)) { BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName); definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry); beanDefinitions.add(definitionHolder); registerBeanDefinition(definitionHolder, this.registry); } } } return beanDefinitions; } /** * Apply further settings to the given bean definition, * beyond the contents retrieved from scanning the component class. * @param beanDefinition the scanned bean definition * @param beanName the generated bean name for the given bean */ protected void postProcessBeanDefinition(AbstractBeanDefinition beanDefinition, String beanName) { beanDefinition.applyDefaults(this.beanDefinitionDefaults); if (this.autowireCandidatePatterns != null) { beanDefinition.setAutowireCandidate(PatternMatchUtils.simpleMatch(this.autowireCandidatePatterns, beanName)); } } /** * Register the specified bean with the given registry. * <p>Can be overridden in subclasses, for example, to adapt the registration * process or to register further bean definitions for each scanned bean. * @param definitionHolder the bean definition plus bean name for the bean * @param registry the BeanDefinitionRegistry to register the bean with */ protected void registerBeanDefinition(BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) { BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, registry); } /** * Check the given candidate's bean name, determining whether the corresponding * bean definition needs to be registered or conflicts with an existing definition. * @param beanName the suggested name for the bean * @param beanDefinition the corresponding bean definition * @return {@code true} if the bean can be registered as-is; * {@code false} if it should be skipped because there is an * existing, compatible bean definition for the specified name * @throws IllegalStateException if an existing, incompatible bean definition * has been found for the specified name */ protected boolean checkCandidate(String beanName, BeanDefinition beanDefinition) throws IllegalStateException { if (!this.registry.containsBeanDefinition(beanName)) { return true; } BeanDefinition existingDef = this.registry.getBeanDefinition(beanName); BeanDefinition originatingDef = existingDef.getOriginatingBeanDefinition(); if (originatingDef != null) { existingDef = originatingDef; } // Explicitly registered overriding bean? if (!(existingDef instanceof ScannedGenericBeanDefinition) && (this.registry.isBeanDefinitionOverridable(beanName) || ObjectUtils.nullSafeEquals( beanDefinition.getBeanClassName(), existingDef.getBeanClassName()))) { return false; } // Scanned same file or equivalent class twice? if (isCompatible(beanDefinition, existingDef)) { return false; } throw new ConflictingBeanDefinitionException("Annotation-specified bean name '" + beanName + "' for bean class [" + beanDefinition.getBeanClassName() + "] conflicts with existing, " + "non-compatible bean definition of same name and class [" + existingDef.getBeanClassName() + "]"); } /** * Determine whether the given new bean definition is compatible with * the given existing bean definition. * <p>The default implementation considers them as compatible when the existing * bean definition comes from the same source or from a non-scanning source. * @param newDef the new bean definition, originated from scanning * @param existingDef the existing bean definition, potentially an * explicitly defined one or a previously generated one from scanning * @return whether the definitions are considered as compatible, with the * new definition to be skipped in favor of the existing definition */ protected boolean isCompatible(BeanDefinition newDef, BeanDefinition existingDef) { return ((newDef.getSource() != null && newDef.getSource().equals(existingDef.getSource())) || newDef.equals(existingDef)); } /** * Get the Environment from the given registry if possible, otherwise return a new * StandardEnvironment. */ private static Environment getOrCreateEnvironment(BeanDefinitionRegistry registry) { Assert.notNull(registry, "BeanDefinitionRegistry must not be null"); if (registry instanceof EnvironmentCapable environmentCapable) { return environmentCapable.getEnvironment(); } return new StandardEnvironment(); } }
java
github
https://github.com/spring-projects/spring-framework
spring-context/src/main/java/org/springframework/context/annotation/ClassPathBeanDefinitionScanner.java
# Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer for has_key(). Calls to .has_key() methods are expressed in terms of the 'in' operator: d.has_key(k) -> k in d CAVEATS: 1) While the primary target of this fixer is dict.has_key(), the fixer will change any has_key() method call, regardless of its class. 2) Cases like this will not be converted: m = d.has_key if m(k): ... Only *calls* to has_key() are converted. While it is possible to convert the above to something like m = d.__contains__ if m(k): ... this is currently not done. """ # Local imports from .. import pytree from ..pgen2 import token from .. import fixer_base from ..fixer_util import Name, parenthesize class FixHasKey(fixer_base.BaseFix): BM_compatible = True PATTERN = """ anchor=power< before=any+ trailer< '.' 'has_key' > trailer< '(' ( not(arglist | argument<any '=' any>) arg=any | arglist<(not argument<any '=' any>) arg=any ','> ) ')' > after=any* > | negation=not_test< 'not' anchor=power< before=any+ trailer< '.' 'has_key' > trailer< '(' ( not(arglist | argument<any '=' any>) arg=any | arglist<(not argument<any '=' any>) arg=any ','> ) ')' > > > """ def transform(self, node, results): assert results syms = self.syms if (node.parent.type == syms.not_test and self.pattern.match(node.parent)): # Don't transform a node matching the first alternative of the # pattern when its parent matches the second alternative return None negation = results.get("negation") anchor = results["anchor"] prefix = node.prefix before = [n.clone() for n in results["before"]] arg = results["arg"].clone() after = results.get("after") if after: after = [n.clone() for n in after] if arg.type in (syms.comparison, syms.not_test, syms.and_test, syms.or_test, syms.test, syms.lambdef, syms.argument): arg = parenthesize(arg) if len(before) == 1: before = before[0] else: before = pytree.Node(syms.power, before) before.prefix = " " n_op = Name("in", prefix=" ") if negation: n_not = Name("not", prefix=" ") n_op = pytree.Node(syms.comp_op, (n_not, n_op)) new = pytree.Node(syms.comparison, (arg, n_op, before)) if after: new = parenthesize(new) new = pytree.Node(syms.power, (new,) + tuple(after)) if node.parent.type in (syms.comparison, syms.expr, syms.xor_expr, syms.and_expr, syms.shift_expr, syms.arith_expr, syms.term, syms.factor, syms.power): new = parenthesize(new) new.prefix = prefix return new
unknown
codeparrot/codeparrot-clean
# Copyright (c) 2013 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. """ Middleware that will provide Dynamic Large Object (DLO) support. --------------- Using ``swift`` --------------- The quickest way to try out this feature is use the ``swift`` Swift Tool included with the `python-swiftclient`_ library. You can use the ``-S`` option to specify the segment size to use when splitting a large file. For example:: swift upload test_container -S 1073741824 large_file This would split the large_file into 1G segments and begin uploading those segments in parallel. Once all the segments have been uploaded, ``swift`` will then create the manifest file so the segments can be downloaded as one. So now, the following ``swift`` command would download the entire large object:: swift download test_container large_file ``swift`` command uses a strict convention for its segmented object support. In the above example it will upload all the segments into a second container named test_container_segments. These segments will have names like large_file/1290206778.25/21474836480/00000000, large_file/1290206778.25/21474836480/00000001, etc. The main benefit for using a separate container is that the main container listings will not be polluted with all the segment names. The reason for using the segment name format of <name>/<timestamp>/<size>/<segment> is so that an upload of a new file with the same name won't overwrite the contents of the first until the last moment when the manifest file is updated. ``swift`` will manage these segment files for you, deleting old segments on deletes and overwrites, etc. You can override this behavior with the ``--leave-segments`` option if desired; this is useful if you want to have multiple versions of the same large object available. .. _`python-swiftclient`: http://github.com/openstack/python-swiftclient ---------- Direct API ---------- You can also work with the segments and manifests directly with HTTP requests instead of having ``swift`` do that for you. You can just upload the segments like you would any other object and the manifest is just a zero-byte (not enforced) file with an extra ``X-Object-Manifest`` header. All the object segments need to be in the same container, have a common object name prefix, and sort in the order in which they should be concatenated. Object names are sorted lexicographically as UTF-8 byte strings. They don't have to be in the same container as the manifest file will be, which is useful to keep container listings clean as explained above with ``swift``. The manifest file is simply a zero-byte (not enforced) file with the extra ``X-Object-Manifest: <container>/<prefix>`` header, where ``<container>`` is the container the object segments are in and ``<prefix>`` is the common prefix for all the segments. It is best to upload all the segments first and then create or update the manifest. In this way, the full object won't be available for downloading until the upload is complete. Also, you can upload a new set of segments to a second location and then update the manifest to point to this new location. During the upload of the new segments, the original manifest will still be available to download the first set of segments. .. note:: When updating a manifest object using a POST request, a ``X-Object-Manifest`` header must be included for the object to continue to behave as a manifest object. The manifest file should have no content. However, this is not enforced. If the manifest path itself conforms to container/prefix specified in ``X-Object-Manifest``, and if manifest has some content/data in it, it would also be considered as segment and manifest's content will be part of the concatenated GET response. The order of concatenation follows the usual DLO logic which is - the order of concatenation adheres to order returned when segment names are sorted. Here's an example using ``curl`` with tiny 1-byte segments:: # First, upload the segments curl -X PUT -H 'X-Auth-Token: <token>' \ http://<storage_url>/container/myobject/00000001 --data-binary '1' curl -X PUT -H 'X-Auth-Token: <token>' \ http://<storage_url>/container/myobject/00000002 --data-binary '2' curl -X PUT -H 'X-Auth-Token: <token>' \ http://<storage_url>/container/myobject/00000003 --data-binary '3' # Next, create the manifest file curl -X PUT -H 'X-Auth-Token: <token>' \ -H 'X-Object-Manifest: container/myobject/' \ http://<storage_url>/container/myobject --data-binary '' # And now we can download the segments as a single object curl -H 'X-Auth-Token: <token>' \ http://<storage_url>/container/myobject """ import json import six from six.moves.urllib.parse import unquote from hashlib import md5 from swift.common import constraints from swift.common.exceptions import ListingIterError, SegmentError from swift.common.http import is_success from swift.common.swob import Request, Response, \ HTTPRequestedRangeNotSatisfiable, HTTPBadRequest, HTTPConflict from swift.common.utils import get_logger, \ RateLimitedIterator, quote, close_if_possible, closing_if_possible from swift.common.request_helpers import SegmentedIterable from swift.common.wsgi import WSGIContext, make_subrequest, load_app_config class GetContext(WSGIContext): def __init__(self, dlo, logger): super(GetContext, self).__init__(dlo.app) self.dlo = dlo self.logger = logger def _get_container_listing(self, req, version, account, container, prefix, marker=''): con_req = make_subrequest( req.environ, path='/'.join(['', version, account, container]), method='GET', headers={'x-auth-token': req.headers.get('x-auth-token')}, agent=('%(orig)s ' + 'DLO MultipartGET'), swift_source='DLO') con_req.query_string = 'prefix=%s' % quote(prefix) if marker: con_req.query_string += '&marker=%s' % quote(marker) con_resp = con_req.get_response(self.dlo.app) if not is_success(con_resp.status_int): return con_resp, None with closing_if_possible(con_resp.app_iter): return None, json.loads(''.join(con_resp.app_iter)) def _segment_listing_iterator(self, req, version, account, container, prefix, segments, first_byte=None, last_byte=None): # It's sort of hokey that this thing takes in the first page of # segments as an argument, but we need to compute the etag and content # length from the first page, and it's better to have a hokey # interface than to make redundant requests. if first_byte is None: first_byte = 0 if last_byte is None: last_byte = float("inf") marker = '' while True: for segment in segments: seg_length = int(segment['bytes']) if first_byte >= seg_length: # don't need any bytes from this segment first_byte = max(first_byte - seg_length, -1) last_byte = max(last_byte - seg_length, -1) continue elif last_byte < 0: # no bytes are needed from this or any future segment break seg_name = segment['name'] if isinstance(seg_name, six.text_type): seg_name = seg_name.encode("utf-8") # We deliberately omit the etag and size here; # SegmentedIterable will check size and etag if # specified, but we don't want it to. DLOs only care # that the objects' names match the specified prefix. # SegmentedIterable will instead check that the data read # from each segment matches the response headers. _path = "/".join(["", version, account, container, seg_name]) _first = None if first_byte <= 0 else first_byte _last = None if last_byte >= seg_length - 1 else last_byte yield { 'path': _path, 'first_byte': _first, 'last_byte': _last } first_byte = max(first_byte - seg_length, -1) last_byte = max(last_byte - seg_length, -1) if len(segments) < constraints.CONTAINER_LISTING_LIMIT: # a short page means that we're done with the listing break elif last_byte < 0: break marker = segments[-1]['name'] error_response, segments = self._get_container_listing( req, version, account, container, prefix, marker) if error_response: # we've already started sending the response body to the # client, so all we can do is raise an exception to make the # WSGI server close the connection early close_if_possible(error_response.app_iter) raise ListingIterError( "Got status %d listing container /%s/%s" % (error_response.status_int, account, container)) def get_or_head_response(self, req, x_object_manifest, response_headers=None): if response_headers is None: response_headers = self._response_headers container, obj_prefix = x_object_manifest.split('/', 1) container = unquote(container) obj_prefix = unquote(obj_prefix) version, account, _junk = req.split_path(2, 3, True) error_response, segments = self._get_container_listing( req, version, account, container, obj_prefix) if error_response: return error_response have_complete_listing = len(segments) < \ constraints.CONTAINER_LISTING_LIMIT first_byte = last_byte = None actual_content_length = None content_length_for_swob_range = None if req.range and len(req.range.ranges) == 1: content_length_for_swob_range = sum(o['bytes'] for o in segments) # This is a hack to handle suffix byte ranges (e.g. "bytes=-5"), # which we can't honor unless we have a complete listing. _junk, range_end = req.range.ranges_for_length(float("inf"))[0] # If this is all the segments, we know whether or not this # range request is satisfiable. # # Alternately, we may not have all the segments, but this range # falls entirely within the first page's segments, so we know # that it is satisfiable. if (have_complete_listing or range_end < content_length_for_swob_range): byteranges = req.range.ranges_for_length( content_length_for_swob_range) if not byteranges: headers = {'Accept-Ranges': 'bytes'} if have_complete_listing: headers['Content-Range'] = 'bytes */%d' % ( content_length_for_swob_range, ) return HTTPRequestedRangeNotSatisfiable( request=req, headers=headers) first_byte, last_byte = byteranges[0] # For some reason, swob.Range.ranges_for_length adds 1 to the # last byte's position. last_byte -= 1 actual_content_length = last_byte - first_byte + 1 else: # The range may or may not be satisfiable, but we can't tell # based on just one page of listing, and we're not going to go # get more pages because that would use up too many resources, # so we ignore the Range header and return the whole object. actual_content_length = None content_length_for_swob_range = None req.range = None response_headers = [ (h, v) for h, v in response_headers if h.lower() not in ("content-length", "content-range")] if content_length_for_swob_range is not None: # Here, we have to give swob a big-enough content length so that # it can compute the actual content length based on the Range # header. This value will not be visible to the client; swob will # substitute its own Content-Length. # # Note: if the manifest points to at least CONTAINER_LISTING_LIMIT # segments, this may be less than the sum of all the segments' # sizes. However, it'll still be greater than the last byte in the # Range header, so it's good enough for swob. response_headers.append(('Content-Length', str(content_length_for_swob_range))) elif have_complete_listing: actual_content_length = sum(o['bytes'] for o in segments) response_headers.append(('Content-Length', str(actual_content_length))) if have_complete_listing: response_headers = [(h, v) for h, v in response_headers if h.lower() != "etag"] etag = md5() for seg_dict in segments: etag.update(seg_dict['hash'].strip('"')) response_headers.append(('Etag', '"%s"' % etag.hexdigest())) app_iter = None if req.method == 'GET': listing_iter = RateLimitedIterator( self._segment_listing_iterator( req, version, account, container, obj_prefix, segments, first_byte=first_byte, last_byte=last_byte), self.dlo.rate_limit_segments_per_sec, limit_after=self.dlo.rate_limit_after_segment) app_iter = SegmentedIterable( req, self.dlo.app, listing_iter, ua_suffix="DLO MultipartGET", swift_source="DLO", name=req.path, logger=self.logger, max_get_time=self.dlo.max_get_time, response_body_length=actual_content_length) try: app_iter.validate_first_segment() except (SegmentError, ListingIterError): return HTTPConflict(request=req) resp = Response(request=req, headers=response_headers, conditional_response=True, app_iter=app_iter) return resp def handle_request(self, req, start_response): """ Take a GET or HEAD request, and if it is for a dynamic large object manifest, return an appropriate response. Otherwise, simply pass it through. """ resp_iter = self._app_call(req.environ) # make sure this response is for a dynamic large object manifest for header, value in self._response_headers: if (header.lower() == 'x-object-manifest'): close_if_possible(resp_iter) response = self.get_or_head_response(req, value) return response(req.environ, start_response) # Not a dynamic large object manifest; just pass it through. start_response(self._response_status, self._response_headers, self._response_exc_info) return resp_iter class DynamicLargeObject(object): def __init__(self, app, conf): self.app = app self.logger = get_logger(conf, log_route='dlo') # DLO functionality used to live in the proxy server, not middleware, # so let's try to go find config values in the proxy's config section # to ease cluster upgrades. self._populate_config_from_old_location(conf) self.max_get_time = int(conf.get('max_get_time', '86400')) self.rate_limit_after_segment = int(conf.get( 'rate_limit_after_segment', '10')) self.rate_limit_segments_per_sec = int(conf.get( 'rate_limit_segments_per_sec', '1')) def _populate_config_from_old_location(self, conf): if ('rate_limit_after_segment' in conf or 'rate_limit_segments_per_sec' in conf or 'max_get_time' in conf or '__file__' not in conf): return proxy_conf = load_app_config(conf['__file__']) for setting in ('rate_limit_after_segment', 'rate_limit_segments_per_sec', 'max_get_time'): if setting in proxy_conf: conf[setting] = proxy_conf[setting] def __call__(self, env, start_response): """ WSGI entry point """ req = Request(env) try: vrs, account, container, obj = req.split_path(4, 4, True) except ValueError: return self.app(env, start_response) if ((req.method == 'GET' or req.method == 'HEAD') and req.params.get('multipart-manifest') != 'get'): return GetContext(self, self.logger).\ handle_request(req, start_response) elif req.method == 'PUT': error_response = self._validate_x_object_manifest_header(req) if error_response: return error_response(env, start_response) return self.app(env, start_response) def _validate_x_object_manifest_header(self, req): """ Make sure that X-Object-Manifest is valid if present. """ if 'X-Object-Manifest' in req.headers: value = req.headers['X-Object-Manifest'] container = prefix = None try: container, prefix = value.split('/', 1) except ValueError: pass if not container or not prefix or '?' in value or '&' in value or \ prefix.startswith('/'): return HTTPBadRequest( request=req, body=('X-Object-Manifest must be in the ' 'format container/prefix')) def filter_factory(global_conf, **local_conf): conf = global_conf.copy() conf.update(local_conf) def dlo_filter(app): return DynamicLargeObject(app, conf) return dlo_filter
unknown
codeparrot/codeparrot-clean
# Some simple queue module tests, plus some failure conditions # to ensure the Queue locks remain stable. import queue import time import unittest from test import support threading = support.import_module('threading') QUEUE_SIZE = 5 def qfull(q): return q.maxsize > 0 and q.qsize() == q.maxsize # A thread to run a function that unclogs a blocked Queue. class _TriggerThread(threading.Thread): def __init__(self, fn, args): self.fn = fn self.args = args self.startedEvent = threading.Event() threading.Thread.__init__(self) def run(self): # The sleep isn't necessary, but is intended to give the blocking # function in the main thread a chance at actually blocking before # we unclog it. But if the sleep is longer than the timeout-based # tests wait in their blocking functions, those tests will fail. # So we give them much longer timeout values compared to the # sleep here (I aimed at 10 seconds for blocking functions -- # they should never actually wait that long - they should make # progress as soon as we call self.fn()). time.sleep(0.1) self.startedEvent.set() self.fn(*self.args) # Execute a function that blocks, and in a separate thread, a function that # triggers the release. Returns the result of the blocking function. Caution: # block_func must guarantee to block until trigger_func is called, and # trigger_func must guarantee to change queue state so that block_func can make # enough progress to return. In particular, a block_func that just raises an # exception regardless of whether trigger_func is called will lead to # timing-dependent sporadic failures, and one of those went rarely seen but # undiagnosed for years. Now block_func must be unexceptional. If block_func # is supposed to raise an exception, call do_exceptional_blocking_test() # instead. class BlockingTestMixin: def tearDown(self): self.t = None def do_blocking_test(self, block_func, block_args, trigger_func, trigger_args): self.t = _TriggerThread(trigger_func, trigger_args) self.t.start() self.result = block_func(*block_args) # If block_func returned before our thread made the call, we failed! if not self.t.startedEvent.is_set(): self.fail("blocking function '%r' appeared not to block" % block_func) self.t.join(10) # make sure the thread terminates if self.t.is_alive(): self.fail("trigger function '%r' appeared to not return" % trigger_func) return self.result # Call this instead if block_func is supposed to raise an exception. def do_exceptional_blocking_test(self,block_func, block_args, trigger_func, trigger_args, expected_exception_class): self.t = _TriggerThread(trigger_func, trigger_args) self.t.start() try: try: block_func(*block_args) except expected_exception_class: raise else: self.fail("expected exception of kind %r" % expected_exception_class) finally: self.t.join(10) # make sure the thread terminates if self.t.is_alive(): self.fail("trigger function '%r' appeared to not return" % trigger_func) if not self.t.startedEvent.is_set(): self.fail("trigger thread ended but event never set") class BaseQueueTestMixin(BlockingTestMixin): def setUp(self): self.cum = 0 self.cumlock = threading.Lock() def simple_queue_test(self, q): if q.qsize(): raise RuntimeError("Call this function with an empty queue") self.assertTrue(q.empty()) self.assertFalse(q.full()) # I guess we better check things actually queue correctly a little :) q.put(111) q.put(333) q.put(222) target_order = dict(Queue = [111, 333, 222], LifoQueue = [222, 333, 111], PriorityQueue = [111, 222, 333]) actual_order = [q.get(), q.get(), q.get()] self.assertEqual(actual_order, target_order[q.__class__.__name__], "Didn't seem to queue the correct data!") for i in range(QUEUE_SIZE-1): q.put(i) self.assertTrue(q.qsize(), "Queue should not be empty") self.assertTrue(not qfull(q), "Queue should not be full") last = 2 * QUEUE_SIZE full = 3 * 2 * QUEUE_SIZE q.put(last) self.assertTrue(qfull(q), "Queue should be full") self.assertFalse(q.empty()) self.assertTrue(q.full()) try: q.put(full, block=0) self.fail("Didn't appear to block with a full queue") except queue.Full: pass try: q.put(full, timeout=0.01) self.fail("Didn't appear to time-out with a full queue") except queue.Full: pass # Test a blocking put self.do_blocking_test(q.put, (full,), q.get, ()) self.do_blocking_test(q.put, (full, True, 10), q.get, ()) # Empty it for i in range(QUEUE_SIZE): q.get() self.assertTrue(not q.qsize(), "Queue should be empty") try: q.get(block=0) self.fail("Didn't appear to block with an empty queue") except queue.Empty: pass try: q.get(timeout=0.01) self.fail("Didn't appear to time-out with an empty queue") except queue.Empty: pass # Test a blocking get self.do_blocking_test(q.get, (), q.put, ('empty',)) self.do_blocking_test(q.get, (True, 10), q.put, ('empty',)) def worker(self, q): while True: x = q.get() if x < 0: q.task_done() return with self.cumlock: self.cum += x q.task_done() def queue_join_test(self, q): self.cum = 0 for i in (0,1): threading.Thread(target=self.worker, args=(q,)).start() for i in range(100): q.put(i) q.join() self.assertEqual(self.cum, sum(range(100)), "q.join() did not block until all tasks were done") for i in (0,1): q.put(-1) # instruct the threads to close q.join() # verify that you can join twice def test_queue_task_done(self): # Test to make sure a queue task completed successfully. q = self.type2test() try: q.task_done() except ValueError: pass else: self.fail("Did not detect task count going negative") def test_queue_join(self): # Test that a queue join()s successfully, and before anything else # (done twice for insurance). q = self.type2test() self.queue_join_test(q) self.queue_join_test(q) try: q.task_done() except ValueError: pass else: self.fail("Did not detect task count going negative") def test_simple_queue(self): # Do it a couple of times on the same queue. # Done twice to make sure works with same instance reused. q = self.type2test(QUEUE_SIZE) self.simple_queue_test(q) self.simple_queue_test(q) def test_negative_timeout_raises_exception(self): q = self.type2test(QUEUE_SIZE) with self.assertRaises(ValueError): q.put(1, timeout=-1) with self.assertRaises(ValueError): q.get(1, timeout=-1) def test_nowait(self): q = self.type2test(QUEUE_SIZE) for i in range(QUEUE_SIZE): q.put_nowait(1) with self.assertRaises(queue.Full): q.put_nowait(1) for i in range(QUEUE_SIZE): q.get_nowait() with self.assertRaises(queue.Empty): q.get_nowait() def test_shrinking_queue(self): # issue 10110 q = self.type2test(3) q.put(1) q.put(2) q.put(3) with self.assertRaises(queue.Full): q.put_nowait(4) self.assertEqual(q.qsize(), 3) q.maxsize = 2 # shrink the queue with self.assertRaises(queue.Full): q.put_nowait(4) class QueueTest(BaseQueueTestMixin, unittest.TestCase): type2test = queue.Queue class LifoQueueTest(BaseQueueTestMixin, unittest.TestCase): type2test = queue.LifoQueue class PriorityQueueTest(BaseQueueTestMixin, unittest.TestCase): type2test = queue.PriorityQueue # A Queue subclass that can provoke failure at a moment's notice :) class FailingQueueException(Exception): pass class FailingQueue(queue.Queue): def __init__(self, *args): self.fail_next_put = False self.fail_next_get = False queue.Queue.__init__(self, *args) def _put(self, item): if self.fail_next_put: self.fail_next_put = False raise FailingQueueException("You Lose") return queue.Queue._put(self, item) def _get(self): if self.fail_next_get: self.fail_next_get = False raise FailingQueueException("You Lose") return queue.Queue._get(self) class FailingQueueTest(BlockingTestMixin, unittest.TestCase): def failing_queue_test(self, q): if q.qsize(): raise RuntimeError("Call this function with an empty queue") for i in range(QUEUE_SIZE-1): q.put(i) # Test a failing non-blocking put. q.fail_next_put = True try: q.put("oops", block=0) self.fail("The queue didn't fail when it should have") except FailingQueueException: pass q.fail_next_put = True try: q.put("oops", timeout=0.1) self.fail("The queue didn't fail when it should have") except FailingQueueException: pass q.put("last") self.assertTrue(qfull(q), "Queue should be full") # Test a failing blocking put q.fail_next_put = True try: self.do_blocking_test(q.put, ("full",), q.get, ()) self.fail("The queue didn't fail when it should have") except FailingQueueException: pass # Check the Queue isn't damaged. # put failed, but get succeeded - re-add q.put("last") # Test a failing timeout put q.fail_next_put = True try: self.do_exceptional_blocking_test(q.put, ("full", True, 10), q.get, (), FailingQueueException) self.fail("The queue didn't fail when it should have") except FailingQueueException: pass # Check the Queue isn't damaged. # put failed, but get succeeded - re-add q.put("last") self.assertTrue(qfull(q), "Queue should be full") q.get() self.assertTrue(not qfull(q), "Queue should not be full") q.put("last") self.assertTrue(qfull(q), "Queue should be full") # Test a blocking put self.do_blocking_test(q.put, ("full",), q.get, ()) # Empty it for i in range(QUEUE_SIZE): q.get() self.assertTrue(not q.qsize(), "Queue should be empty") q.put("first") q.fail_next_get = True try: q.get() self.fail("The queue didn't fail when it should have") except FailingQueueException: pass self.assertTrue(q.qsize(), "Queue should not be empty") q.fail_next_get = True try: q.get(timeout=0.1) self.fail("The queue didn't fail when it should have") except FailingQueueException: pass self.assertTrue(q.qsize(), "Queue should not be empty") q.get() self.assertTrue(not q.qsize(), "Queue should be empty") q.fail_next_get = True try: self.do_exceptional_blocking_test(q.get, (), q.put, ('empty',), FailingQueueException) self.fail("The queue didn't fail when it should have") except FailingQueueException: pass # put succeeded, but get failed. self.assertTrue(q.qsize(), "Queue should not be empty") q.get() self.assertTrue(not q.qsize(), "Queue should be empty") def test_failing_queue(self): # Test to make sure a queue is functioning correctly. # Done twice to the same instance. q = FailingQueue(QUEUE_SIZE) self.failing_queue_test(q) self.failing_queue_test(q) if __name__ == "__main__": unittest.main()
unknown
codeparrot/codeparrot-clean
#!/usr/bin/env python # Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Wrapper script for launching application within the sel_ldr. """ import optparse import os import subprocess import sys import create_nmf import getos SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) NACL_SDK_ROOT = os.path.dirname(SCRIPT_DIR) if sys.version_info < (2, 6, 0): sys.stderr.write("python 2.6 or later is required run this script\n") sys.exit(1) class Error(Exception): pass def Log(msg): if Log.verbose: sys.stderr.write(str(msg) + '\n') Log.verbose = False def FindQemu(): qemu_locations = [os.path.join(SCRIPT_DIR, 'qemu_arm'), os.path.join(SCRIPT_DIR, 'qemu-arm')] qemu_locations += [os.path.join(path, 'qemu_arm') for path in os.environ["PATH"].split(os.pathsep)] qemu_locations += [os.path.join(path, 'qemu-arm') for path in os.environ["PATH"].split(os.pathsep)] # See if qemu is in any of these locations. qemu_bin = None for loc in qemu_locations: if os.path.isfile(loc) and os.access(loc, os.X_OK): qemu_bin = loc break return qemu_bin def main(argv): usage = 'Usage: %prog [options] <.nexe>' epilog = 'Example: sel_ldr.py my_nexe.nexe' parser = optparse.OptionParser(usage, description=__doc__, epilog=epilog) parser.add_option('-v', '--verbose', action='store_true', help='Verbose output') parser.add_option('-d', '--debug', action='store_true', help='Enable debug stub') parser.add_option('--debug-libs', action='store_true', help='For dynamic executables, reference debug ' 'libraries rather then release') # To enable bash completion for this command first install optcomplete # and then add this line to your .bashrc: # complete -F _optcomplete sel_ldr.py try: import optcomplete optcomplete.autocomplete(parser) except ImportError: pass options, args = parser.parse_args(argv) if not args: parser.error('No executable file specified') nexe = args[0] if options.verbose: Log.verbose = True osname = getos.GetPlatform() if not os.path.exists(nexe): raise Error('executable not found: %s' % nexe) if not os.path.isfile(nexe): raise Error('not a file: %s' % nexe) arch, dynamic = create_nmf.ParseElfHeader(nexe) if arch == 'arm' and osname != 'linux': raise Error('Cannot run ARM executables under sel_ldr on ' + osname) arch_suffix = arch.replace('-', '_') sel_ldr = os.path.join(SCRIPT_DIR, 'sel_ldr_%s' % arch_suffix) irt = os.path.join(SCRIPT_DIR, 'irt_core_%s.nexe' % arch_suffix) if osname == 'win': sel_ldr += '.exe' Log('ROOT = %s' % NACL_SDK_ROOT) Log('SEL_LDR = %s' % sel_ldr) Log('IRT = %s' % irt) cmd = [sel_ldr] if osname == 'linux': # Run sel_ldr under nacl_helper_bootstrap helper = os.path.join(SCRIPT_DIR, 'nacl_helper_bootstrap_%s' % arch_suffix) Log('HELPER = %s' % helper) cmd.insert(0, helper) cmd.append('--r_debug=0xXXXXXXXXXXXXXXXX') cmd.append('--reserved_at_zero=0xXXXXXXXXXXXXXXXX') cmd += ['-a', '-B', irt] if options.debug: cmd.append('-g') if not options.verbose: cmd += ['-l', os.devnull] if arch == 'arm': # Use the QEMU arm emulator if available. qemu_bin = FindQemu() if qemu_bin: qemu = [qemu_bin, '-cpu', 'cortex-a8', '-L', os.path.abspath(os.path.join(NACL_SDK_ROOT, 'toolchain', 'linux_arm_trusted'))] # '-Q' disables platform qualification, allowing arm binaries to run. cmd = qemu + cmd + ['-Q'] else: raise Error('Cannot run ARM executables under sel_ldr without an emulator' '. Try installing QEMU (http://wiki.qemu.org/).') if dynamic: if options.debug_libs: libpath = os.path.join(NACL_SDK_ROOT, 'lib', 'glibc_%s' % arch_suffix, 'Debug') else: libpath = os.path.join(NACL_SDK_ROOT, 'lib', 'glibc_%s' % arch_suffix, 'Release') toolchain = '%s_x86_glibc' % osname sdk_lib_dir = os.path.join(NACL_SDK_ROOT, 'toolchain', toolchain, 'x86_64-nacl') if arch == 'x86-64': sdk_lib_dir = os.path.join(sdk_lib_dir, 'lib') else: sdk_lib_dir = os.path.join(sdk_lib_dir, 'lib32') ldso = os.path.join(sdk_lib_dir, 'runnable-ld.so') cmd.append(ldso) Log('LD.SO = %s' % ldso) libpath += ':' + sdk_lib_dir cmd.append('--library-path') cmd.append(libpath) if args: # Append arguments for the executable itself. cmd += args Log(cmd) rtn = subprocess.call(cmd) return rtn if __name__ == '__main__': try: sys.exit(main(sys.argv[1:])) except Error as e: sys.stderr.write(str(e) + '\n') sys.exit(1)
unknown
codeparrot/codeparrot-clean
#!python # uses raw_input in Python 2.X # add triple quotes around a test you don't wish to run import sys if sys.version[0] == '2': input = raw_input # 2.X compatible print('test1') while True: reply = input('Enter text:') if reply == 'stop': break print(reply.upper()) print('test2') while True: reply = input('Enter text:') if reply == 'stop': break print(int(reply) ** 2) print('Bye') print('test3') while True: reply = input('Enter text:') if reply == 'stop': break elif not reply.isdigit(): print('Bad!' * 8) else: print(int(reply) ** 2) print('Bye') print('test4') while True: reply = input('Enter text:') if reply == 'stop': break try: num = int(reply) except: print('Bad!' * 8) else: print(num ** 2) print('Bye') print('test5') while True: reply = input('Enter text:') if reply == 'stop': break try: print(int(reply) ** 2) except: print('Bad!' * 8) print('Bye') print('test6') while True: reply = input('Enter text:') if reply == 'stop': break try: print(float(reply) ** 2) except: print('Bad!' * 8) print('Bye') print('test7') while True: reply = input('Enter text:') if reply == 'stop': break elif not reply.isdigit(): print('Bad!' * 8) else: num = int(reply) if num < 20: print('low') else: print(num ** 2) print('Bye')
unknown
codeparrot/codeparrot-clean
from django.utils.encoding import python_2_unicode_compatible from ..models import models from ..utils import gisfield_may_be_null @python_2_unicode_compatible class NamedModel(models.Model): name = models.CharField(max_length=30) objects = models.GeoManager() class Meta: abstract = True required_db_features = ['gis_enabled'] def __str__(self): return self.name class Country(NamedModel): mpoly = models.MultiPolygonField() # SRID, by default, is 4326 class City(NamedModel): point = models.PointField() class Meta: app_label = 'geoapp' required_db_features = ['gis_enabled'] # This is an inherited model from City class PennsylvaniaCity(City): county = models.CharField(max_length=30) founded = models.DateTimeField(null=True) # TODO: This should be implicitly inherited. objects = models.GeoManager() class Meta: app_label = 'geoapp' required_db_features = ['gis_enabled'] class State(NamedModel): poly = models.PolygonField(null=gisfield_may_be_null) # Allowing NULL geometries here. class Meta: app_label = 'geoapp' required_db_features = ['gis_enabled'] class Track(NamedModel): line = models.LineStringField() class MultiFields(NamedModel): city = models.ForeignKey(City, models.CASCADE) point = models.PointField() poly = models.PolygonField() class Meta: unique_together = ('city', 'point') required_db_features = ['gis_enabled', 'supports_geometry_field_unique_index'] class Truth(models.Model): val = models.BooleanField(default=False) objects = models.GeoManager() class Meta: required_db_features = ['gis_enabled'] class Feature(NamedModel): geom = models.GeometryField() class MinusOneSRID(models.Model): geom = models.PointField(srid=-1) # Minus one SRID. objects = models.GeoManager() class Meta: required_db_features = ['gis_enabled'] class NonConcreteField(models.IntegerField): def db_type(self, connection): return None def get_attname_column(self): attname, column = super(NonConcreteField, self).get_attname_column() return attname, None class NonConcreteModel(NamedModel): non_concrete = NonConcreteField() point = models.PointField(geography=True)
unknown
codeparrot/codeparrot-clean
from datetime import ( time, timezone, ) import zoneinfo import numpy as np import pytest from pandas._libs.tslibs import timezones from pandas.errors import Pandas4Warning from pandas import ( DataFrame, date_range, ) import pandas._testing as tm class TestAtTime: @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"]) def test_localized_at_time(self, tzstr, frame_or_series): tz = timezones.maybe_get_tz(tzstr) rng = date_range("4/16/2012", "5/1/2012", freq="h") ts = frame_or_series( np.random.default_rng(2).standard_normal(len(rng)), index=rng ) ts_local = ts.tz_localize(tzstr) result = ts_local.at_time(time(10, 0)) expected = ts.at_time(time(10, 0)).tz_localize(tzstr) tm.assert_equal(result, expected) assert timezones.tz_compare(result.index.tz, tz) def test_at_time(self, frame_or_series): rng = date_range("1/1/2000", "1/5/2000", freq="5min") ts = DataFrame( np.random.default_rng(2).standard_normal((len(rng), 2)), index=rng ) ts = tm.get_obj(ts, frame_or_series) rs = ts.at_time(rng[1]) assert (rs.index.hour == rng[1].hour).all() assert (rs.index.minute == rng[1].minute).all() assert (rs.index.second == rng[1].second).all() result = ts.at_time("9:30") expected = ts.at_time(time(9, 30)) tm.assert_equal(result, expected) def test_at_time_midnight(self, frame_or_series): # midnight, everything rng = date_range("1/1/2000", "1/31/2000") ts = DataFrame( np.random.default_rng(2).standard_normal((len(rng), 3)), index=rng ) ts = tm.get_obj(ts, frame_or_series) result = ts.at_time(time(0, 0)) tm.assert_equal(result, ts) def test_at_time_nonexistent(self, frame_or_series): # time doesn't exist rng = date_range("1/1/2012", freq="23Min", periods=384) ts = DataFrame(np.random.default_rng(2).standard_normal(len(rng)), rng) ts = tm.get_obj(ts, frame_or_series) rs = ts.at_time("16:00") assert len(rs) == 0 @pytest.mark.parametrize( "hour", ["1:00", "1:00AM", time(1), time(1, tzinfo=timezone.utc)] ) def test_at_time_errors(self, hour): # GH#24043 dti = date_range("2018", periods=3, freq="h") df = DataFrame(list(range(len(dti))), index=dti) if getattr(hour, "tzinfo", None) is None: result = df.at_time(hour) expected = df.iloc[1:2] tm.assert_frame_equal(result, expected) else: with pytest.raises(ValueError, match="Index must be timezone"): df.at_time(hour) def test_at_time_tz(self): # GH#24043 dti = date_range("2018", periods=3, freq="h", tz="US/Pacific") df = DataFrame(list(range(len(dti))), index=dti) result = df.at_time(time(4, tzinfo=zoneinfo.ZoneInfo("US/Eastern"))) expected = df.iloc[1:2] tm.assert_frame_equal(result, expected) def test_at_time_raises(self, frame_or_series): # GH#20725 obj = DataFrame([[1, 2, 3], [4, 5, 6]]) obj = tm.get_obj(obj, frame_or_series) msg = "Index must be DatetimeIndex" with pytest.raises(TypeError, match=msg): # index is not a DatetimeIndex obj.at_time("00:00") def test_at_time_axis(self, axis): # issue 8839 rng = date_range("1/1/2000", "1/2/2000", freq="5min") ts = DataFrame(np.random.default_rng(2).standard_normal((len(rng), len(rng)))) ts.index, ts.columns = rng, rng indices = rng[(rng.hour == 9) & (rng.minute == 30) & (rng.second == 0)] if axis in ["index", 0]: expected = ts.loc[indices, :] elif axis in ["columns", 1]: expected = ts.loc[:, indices] result = ts.at_time("9:30", axis=axis) # Without clearing freq, result has freq 1440T and expected 5T result.index = result.index._with_freq(None) expected.index = expected.index._with_freq(None) tm.assert_frame_equal(result, expected) def test_at_time_datetimeindex(self): index = date_range("2012-01-01", "2012-01-05", freq="30min") df = DataFrame( np.random.default_rng(2).standard_normal((len(index), 5)), index=index ) akey = time(12, 0, 0) ainds = [24, 72, 120, 168] result = df.at_time(akey) expected = df.loc[akey] expected2 = df.iloc[ainds] tm.assert_frame_equal(result, expected) tm.assert_frame_equal(result, expected2) assert len(result) == 4 def test_at_time_ambiguous_format_deprecation(self): # GH#50839 rng = date_range("1/1/2000", "1/5/2000", freq="125min") ts = DataFrame(list(range(len(rng))), index=rng) msg1 = "The string '.*' cannot be parsed" with tm.assert_produces_warning(Pandas4Warning, match=msg1): ts.at_time("2022-12-12 00:00:00") with tm.assert_produces_warning(Pandas4Warning, match=msg1): ts.at_time("2022-12-12 00:00:00 +09:00") with tm.assert_produces_warning(Pandas4Warning, match=msg1): ts.at_time("2022-12-12 00:00:00.000000") # The dateutil parser raises on these, so we can give the future behavior # immediately using pd.core.tools.to_time ts.at_time("235500") ts.at_time("115500PM")
python
github
https://github.com/pandas-dev/pandas
pandas/tests/frame/methods/test_at_time.py
import assert from 'assert'; import axios, {CanceledError, AxiosError, AxiosHeaders} from 'axios'; import settle from 'axios/unsafe/core/settle.js'; assert.strictEqual(typeof axios, 'function'); assert.strictEqual(typeof CanceledError, 'function'); assert.strictEqual(typeof AxiosError, 'function'); assert.strictEqual(typeof AxiosHeaders, 'function'); assert.strictEqual(axios.CanceledError, CanceledError); assert.strictEqual(axios.AxiosError, AxiosError); assert.strictEqual(axios.AxiosHeaders, AxiosHeaders); assert.strictEqual(typeof settle, 'function'); console.log('ESM importing test passed');
javascript
github
https://github.com/axios/axios
test/module/esm/index.js
// Copyright (c) HashiCorp, Inc. // SPDX-License-Identifier: BUSL-1.1 package terraform import ( "strings" "github.com/hashicorp/hcl/v2" "github.com/hashicorp/hcl/v2/hclsyntax" "github.com/zclconf/go-cty/cty" "github.com/hashicorp/terraform/internal/addrs" "github.com/hashicorp/terraform/internal/instances" "github.com/hashicorp/terraform/internal/tfdiags" ) func evalReplaceTriggeredByExpr(expr hcl.Expression, keyData instances.RepetitionData) (*addrs.Reference, tfdiags.Diagnostics) { var ref *addrs.Reference var diags tfdiags.Diagnostics traversal, diags := triggersExprToTraversal(expr, keyData) if diags.HasErrors() { return nil, diags } // We now have a static traversal, so we can just turn it into an addrs.Reference. ref, ds := addrs.ParseRef(traversal) diags = diags.Append(ds) return ref, diags } // trggersExprToTraversal takes an hcl expression limited to the syntax allowed // in replace_triggered_by, and converts it to a static traversal. The // RepetitionData contains the data necessary to evaluate the only allowed // variables in the expression, count.index and each.key. func triggersExprToTraversal(expr hcl.Expression, keyData instances.RepetitionData) (hcl.Traversal, tfdiags.Diagnostics) { var trav hcl.Traversal var diags tfdiags.Diagnostics switch e := expr.(type) { case *hclsyntax.RelativeTraversalExpr: t, d := triggersExprToTraversal(e.Source, keyData) diags = diags.Append(d) trav = append(trav, t...) trav = append(trav, e.Traversal...) case *hclsyntax.ScopeTraversalExpr: // a static reference, we can just append the traversal trav = append(trav, e.Traversal...) case *hclsyntax.IndexExpr: // Get the collection from the index expression t, d := triggersExprToTraversal(e.Collection, keyData) diags = diags.Append(d) if diags.HasErrors() { return nil, diags } trav = append(trav, t...) // The index key is the only place where we could have variables that // reference count and each, so we need to parse those independently. idx, hclDiags := parseReplaceTriggeredByKeyExpr(e.Key, keyData) diags = diags.Append(hclDiags) trav = append(trav, idx) default: // Something unexpected got through config validation. We're not sure // what it is, but we'll point it out in the diagnostics for the user // to fix. diags = diags.Append(&hcl.Diagnostic{ Severity: hcl.DiagError, Summary: "Invalid replace_triggered_by expression", Detail: "Unexpected expression found in replace_triggered_by.", Subject: e.Range().Ptr(), }) } return trav, diags } // parseReplaceTriggeredByKeyExpr takes an hcl.Expression and parses it as an index key, while // evaluating any references to count.index or each.key. This is also used in evaluateActionExpression. func parseReplaceTriggeredByKeyExpr(expr hcl.Expression, keyData instances.RepetitionData) (hcl.TraverseIndex, hcl.Diagnostics) { idx := hcl.TraverseIndex{ SrcRange: expr.Range(), } trav, diags := hcl.RelTraversalForExpr(expr) if diags.HasErrors() { return idx, diags } keyParts := []string{} for _, t := range trav { attr, ok := t.(hcl.TraverseAttr) if !ok { diags = append(diags, &hcl.Diagnostic{ Severity: hcl.DiagError, Summary: "Invalid index expression", Detail: "Only constant values, count.index or each.key are allowed in index expressions.", Subject: expr.Range().Ptr(), }) return idx, diags } keyParts = append(keyParts, attr.Name) } switch strings.Join(keyParts, ".") { case "count.index": if keyData.CountIndex == cty.NilVal { diags = diags.Append(&hcl.Diagnostic{ Severity: hcl.DiagError, Summary: `Reference to "count" in non-counted context`, Detail: `The "count" object can only be used in "resource" blocks when the "count" argument is set.`, Subject: expr.Range().Ptr(), }) } idx.Key = keyData.CountIndex case "each.key": if keyData.EachKey == cty.NilVal { diags = diags.Append(&hcl.Diagnostic{ Severity: hcl.DiagError, Summary: `Reference to "each" in context without for_each`, Detail: `The "each" object can be used only in "resource" blocks when the "for_each" argument is set.`, Subject: expr.Range().Ptr(), }) } idx.Key = keyData.EachKey default: // Something may have slipped through validation, probably from a json // configuration. diags = append(diags, &hcl.Diagnostic{ Severity: hcl.DiagError, Summary: "Invalid index expression", Detail: "Only constant values, count.index or each.key are allowed in index expressions.", Subject: expr.Range().Ptr(), }) } return idx, diags }
go
github
https://github.com/hashicorp/terraform
internal/terraform/evaluate_triggers.go
#========================================================================== # # Copyright Insight Software Consortium # # 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.txt # # 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. # #==========================================================================*/ # # Example on the use of the CurvatureAnisotropicDiffusionImageFilter # import itk from sys import argv itk.auto_progress(2) dim = 2 IType = itk.Image[itk.F, dim] OIType = itk.Image[itk.UC, dim] reader = itk.ImageFileReader[IType].New(FileName=argv[1]) filter = itk.CurvatureAnisotropicDiffusionImageFilter[IType, IType].New( reader, NumberOfIterations=eval( argv[ 3]), TimeStep=eval(argv[4]), ConductanceParameter=eval(argv[5])) cast = itk.RescaleIntensityImageFilter[IType, OIType].New(filter, OutputMinimum=0, OutputMaximum=255) writer = itk.ImageFileWriter[OIType].New(cast, FileName=argv[2]) writer.Update()
unknown
codeparrot/codeparrot-clean
// Copyright 2016 The etcd Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in 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. package contention import ( "sync" "time" ) // TimeoutDetector detects routine starvations by // observing the actual time duration to finish an action // or between two events that should happen in a fixed // interval. If the observed duration is longer than // the expectation, the detector will report the result. type TimeoutDetector struct { mu sync.Mutex // protects all maxDuration time.Duration // map from event to last seen time of event. records map[uint64]time.Time } // NewTimeoutDetector creates the TimeoutDetector. func NewTimeoutDetector(maxDuration time.Duration) *TimeoutDetector { return &TimeoutDetector{ maxDuration: maxDuration, records: make(map[uint64]time.Time), } } // Reset resets the TimeoutDetector. func (td *TimeoutDetector) Reset() { td.mu.Lock() defer td.mu.Unlock() td.records = make(map[uint64]time.Time) } // Observe observes an event of given id. It computes // the time elapsed between successive events of given id. // It returns whether this time elapsed exceeds the expectation, // and the amount by which it exceeds the expectation. func (td *TimeoutDetector) Observe(id uint64) (bool, time.Duration) { td.mu.Lock() defer td.mu.Unlock() ok := true now := time.Now() exceed := time.Duration(0) if pt, found := td.records[id]; found { exceed = now.Sub(pt) - td.maxDuration if exceed > 0 { ok = false } } td.records[id] = now return ok, exceed }
go
github
https://github.com/etcd-io/etcd
pkg/contention/contention.go
/* * Copyright (C) Igor Sysoev * Copyright (C) Nginx, Inc. */ #include <ngx_config.h> #include <ngx_core.h> static ngx_uint_t mday[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; time_t ngx_parse_http_time(u_char *value, size_t len) { u_char *p, *end; ngx_int_t month; ngx_uint_t day, year, hour, min, sec; uint64_t time; enum { no = 0, rfc822, /* Tue, 10 Nov 2002 23:50:13 */ rfc850, /* Tuesday, 10-Dec-02 23:50:13 */ isoc /* Tue Dec 10 23:50:13 2002 */ } fmt; fmt = 0; end = value + len; #if (NGX_SUPPRESS_WARN) day = 32; year = 2038; #endif for (p = value; p < end; p++) { if (*p == ',') { break; } if (*p == ' ') { fmt = isoc; break; } } for (p++; p < end; p++) { if (*p != ' ') { break; } } if (end - p < 18) { return NGX_ERROR; } if (fmt != isoc) { if (*p < '0' || *p > '9' || *(p + 1) < '0' || *(p + 1) > '9') { return NGX_ERROR; } day = (*p - '0') * 10 + (*(p + 1) - '0'); p += 2; if (*p == ' ') { if (end - p < 18) { return NGX_ERROR; } fmt = rfc822; } else if (*p == '-') { fmt = rfc850; } else { return NGX_ERROR; } p++; } switch (*p) { case 'J': month = *(p + 1) == 'a' ? 0 : *(p + 2) == 'n' ? 5 : 6; break; case 'F': month = 1; break; case 'M': month = *(p + 2) == 'r' ? 2 : 4; break; case 'A': month = *(p + 1) == 'p' ? 3 : 7; break; case 'S': month = 8; break; case 'O': month = 9; break; case 'N': month = 10; break; case 'D': month = 11; break; default: return NGX_ERROR; } p += 3; if ((fmt == rfc822 && *p != ' ') || (fmt == rfc850 && *p != '-')) { return NGX_ERROR; } p++; if (fmt == rfc822) { if (*p < '0' || *p > '9' || *(p + 1) < '0' || *(p + 1) > '9' || *(p + 2) < '0' || *(p + 2) > '9' || *(p + 3) < '0' || *(p + 3) > '9') { return NGX_ERROR; } year = (*p - '0') * 1000 + (*(p + 1) - '0') * 100 + (*(p + 2) - '0') * 10 + (*(p + 3) - '0'); p += 4; } else if (fmt == rfc850) { if (*p < '0' || *p > '9' || *(p + 1) < '0' || *(p + 1) > '9') { return NGX_ERROR; } year = (*p - '0') * 10 + (*(p + 1) - '0'); year += (year < 70) ? 2000 : 1900; p += 2; } if (fmt == isoc) { if (*p == ' ') { p++; } if (*p < '0' || *p > '9') { return NGX_ERROR; } day = *p++ - '0'; if (*p != ' ') { if (*p < '0' || *p > '9') { return NGX_ERROR; } day = day * 10 + (*p++ - '0'); } if (end - p < 14) { return NGX_ERROR; } } if (*p++ != ' ') { return NGX_ERROR; } if (*p < '0' || *p > '9' || *(p + 1) < '0' || *(p + 1) > '9') { return NGX_ERROR; } hour = (*p - '0') * 10 + (*(p + 1) - '0'); p += 2; if (*p++ != ':') { return NGX_ERROR; } if (*p < '0' || *p > '9' || *(p + 1) < '0' || *(p + 1) > '9') { return NGX_ERROR; } min = (*p - '0') * 10 + (*(p + 1) - '0'); p += 2; if (*p++ != ':') { return NGX_ERROR; } if (*p < '0' || *p > '9' || *(p + 1) < '0' || *(p + 1) > '9') { return NGX_ERROR; } sec = (*p - '0') * 10 + (*(p + 1) - '0'); if (fmt == isoc) { p += 2; if (*p++ != ' ') { return NGX_ERROR; } if (*p < '0' || *p > '9' || *(p + 1) < '0' || *(p + 1) > '9' || *(p + 2) < '0' || *(p + 2) > '9' || *(p + 3) < '0' || *(p + 3) > '9') { return NGX_ERROR; } year = (*p - '0') * 1000 + (*(p + 1) - '0') * 100 + (*(p + 2) - '0') * 10 + (*(p + 3) - '0'); } if (hour > 23 || min > 59 || sec > 59) { return NGX_ERROR; } if (day == 29 && month == 1) { if ((year & 3) || ((year % 100 == 0) && (year % 400) != 0)) { return NGX_ERROR; } } else if (day > mday[month]) { return NGX_ERROR; } /* * shift new year to March 1 and start months from 1 (not 0), * it is needed for Gauss' formula */ if (--month <= 0) { month += 12; year -= 1; } /* Gauss' formula for Gregorian days since March 1, 1 BC */ time = (uint64_t) ( /* days in years including leap years since March 1, 1 BC */ 365 * year + year / 4 - year / 100 + year / 400 /* days before the month */ + 367 * month / 12 - 30 /* days before the day */ + day - 1 /* * 719527 days were between March 1, 1 BC and March 1, 1970, * 31 and 28 days were in January and February 1970 */ - 719527 + 31 + 28) * 86400 + hour * 3600 + min * 60 + sec; #if (NGX_TIME_T_SIZE <= 4) if (time > 0x7fffffff) { return NGX_ERROR; } #endif return (time_t) time; }
c
github
https://github.com/nginx/nginx
src/core/ngx_parse_time.c
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not 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. */ package org.apache.hadoop.fs.gs; import com.google.cloud.storage.BlobId; import com.google.cloud.storage.BlobInfo; import com.google.cloud.storage.BlobWriteSession; import com.google.cloud.storage.Storage; import com.google.cloud.storage.Storage.BlobWriteOption; import com.google.cloud.storage.StorageException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import java.util.ArrayList; import java.util.List; /** * Implements WritableByteChannel to provide write access to GCS via java-storage client. */ class GoogleCloudStorageClientWriteChannel implements WritableByteChannel { private static final Logger LOG = LoggerFactory.getLogger(GoogleCloudStorageClientWriteChannel.class); private final StorageResourceId resourceId; private WritableByteChannel writableByteChannel; private GoogleCloudStorageItemInfo completedItemInfo = null; GoogleCloudStorageClientWriteChannel( final Storage storage, final StorageResourceId resourceId, final CreateFileOptions createOptions) throws IOException { this.resourceId = resourceId; BlobWriteSession blobWriteSession = getBlobWriteSession(storage, resourceId, createOptions); try { this.writableByteChannel = blobWriteSession.open(); } catch (StorageException e) { throw new IOException(e); } } private static BlobInfo getBlobInfo(final StorageResourceId resourceId, final CreateFileOptions createOptions) { BlobInfo blobInfo = BlobInfo.newBuilder( BlobId.of(resourceId.getBucketName(), resourceId.getObjectName(), resourceId.getGenerationId())).setContentType(createOptions.getContentType()) // .setMetadata(encodeMetadata(createOptions.getMetadata())) // TODO: .build(); return blobInfo; } private static BlobWriteSession getBlobWriteSession(final Storage storage, final StorageResourceId resourceId, final CreateFileOptions createOptions) { return storage.blobWriteSession(getBlobInfo(resourceId, createOptions), generateWriteOptions(createOptions)); } private static BlobWriteOption[] generateWriteOptions(final CreateFileOptions createOptions) { List<BlobWriteOption> blobWriteOptions = new ArrayList<>(); blobWriteOptions.add(BlobWriteOption.disableGzipContent()); blobWriteOptions.add(BlobWriteOption.generationMatch()); //TODO: Enable KMS and checksum return blobWriteOptions.toArray(new BlobWriteOption[blobWriteOptions.size()]); } @Override public boolean isOpen() { return writableByteChannel != null && writableByteChannel.isOpen(); } @Override public void close() throws IOException { try { if (!isOpen()) { return; } writableByteChannel.close(); } catch (Exception e) { throw new IOException( String.format("Upload failed for '%s'. reason=%s", resourceId, e.getMessage()), e); } finally { writableByteChannel = null; } } private int writeInternal(final ByteBuffer byteBuffer) throws IOException { int bytesWritten = writableByteChannel.write(byteBuffer); LOG.trace("{} bytes were written out of provided buffer of capacity {}", bytesWritten, byteBuffer.limit()); return bytesWritten; } @Override public int write(final ByteBuffer src) throws IOException { return writeInternal(src); } }
java
github
https://github.com/apache/hadoop
hadoop-cloud-storage-project/hadoop-gcp/src/main/java/org/apache/hadoop/fs/gs/GoogleCloudStorageClientWriteChannel.java
#!/usr/bin/env python # # Copyright 2009 Facebook # # 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. """Utility classes to write to and read from non-blocking files and sockets. Contents: * `BaseIOStream`: Generic interface for reading and writing. * `IOStream`: Implementation of BaseIOStream using non-blocking sockets. * `SSLIOStream`: SSL-aware version of IOStream. * `PipeIOStream`: Pipe-based IOStream implementation. """ from __future__ import absolute_import, division, print_function, with_statement import collections import errno import numbers import os import socket import sys import re from tornado.concurrent import TracebackFuture from tornado import ioloop from tornado.log import gen_log, app_log from tornado.netutil import ssl_wrap_socket, ssl_match_hostname, SSLCertificateError, _client_ssl_defaults, _server_ssl_defaults from tornado import stack_context from tornado.util import errno_from_exception try: from tornado.platform.posix import _set_nonblocking except ImportError: _set_nonblocking = None try: import ssl except ImportError: # ssl is not available on Google App Engine ssl = None # These errnos indicate that a non-blocking operation must be retried # at a later time. On most platforms they're the same value, but on # some they differ. _ERRNO_WOULDBLOCK = (errno.EWOULDBLOCK, errno.EAGAIN) if hasattr(errno, "WSAEWOULDBLOCK"): _ERRNO_WOULDBLOCK += (errno.WSAEWOULDBLOCK,) # These errnos indicate that a connection has been abruptly terminated. # They should be caught and handled less noisily than other errors. _ERRNO_CONNRESET = (errno.ECONNRESET, errno.ECONNABORTED, errno.EPIPE, errno.ETIMEDOUT) if hasattr(errno, "WSAECONNRESET"): _ERRNO_CONNRESET += (errno.WSAECONNRESET, errno.WSAECONNABORTED, errno.WSAETIMEDOUT) if sys.platform == 'darwin': # OSX appears to have a race condition that causes send(2) to return # EPROTOTYPE if called while a socket is being torn down: # http://erickt.github.io/blog/2014/11/19/adventures-in-debugging-a-potential-osx-kernel-bug/ # Since the socket is being closed anyway, treat this as an ECONNRESET # instead of an unexpected error. _ERRNO_CONNRESET += (errno.EPROTOTYPE,) # More non-portable errnos: _ERRNO_INPROGRESS = (errno.EINPROGRESS,) if hasattr(errno, "WSAEINPROGRESS"): _ERRNO_INPROGRESS += (errno.WSAEINPROGRESS,) class StreamClosedError(IOError): """Exception raised by `IOStream` methods when the stream is closed. Note that the close callback is scheduled to run *after* other callbacks on the stream (to allow for buffered data to be processed), so you may see this error before you see the close callback. The ``real_error`` attribute contains the underlying error that caused the stream to close (if any). .. versionchanged:: 4.3 Added the ``real_error`` attribute. """ def __init__(self, real_error=None): super(StreamClosedError, self).__init__('Stream is closed') self.real_error = real_error class UnsatisfiableReadError(Exception): """Exception raised when a read cannot be satisfied. Raised by ``read_until`` and ``read_until_regex`` with a ``max_bytes`` argument. """ pass class StreamBufferFullError(Exception): """Exception raised by `IOStream` methods when the buffer is full. """ class BaseIOStream(object): """A utility class to write to and read from a non-blocking file or socket. We support a non-blocking ``write()`` and a family of ``read_*()`` methods. All of the methods take an optional ``callback`` argument and return a `.Future` only if no callback is given. When the operation completes, the callback will be run or the `.Future` will resolve with the data read (or ``None`` for ``write()``). All outstanding ``Futures`` will resolve with a `StreamClosedError` when the stream is closed; users of the callback interface will be notified via `.BaseIOStream.set_close_callback` instead. When a stream is closed due to an error, the IOStream's ``error`` attribute contains the exception object. Subclasses must implement `fileno`, `close_fd`, `write_to_fd`, `read_from_fd`, and optionally `get_fd_error`. """ def __init__(self, io_loop=None, max_buffer_size=None, read_chunk_size=None, max_write_buffer_size=None): """`BaseIOStream` constructor. :arg io_loop: The `.IOLoop` to use; defaults to `.IOLoop.current`. Deprecated since Tornado 4.1. :arg max_buffer_size: Maximum amount of incoming data to buffer; defaults to 100MB. :arg read_chunk_size: Amount of data to read at one time from the underlying transport; defaults to 64KB. :arg max_write_buffer_size: Amount of outgoing data to buffer; defaults to unlimited. .. versionchanged:: 4.0 Add the ``max_write_buffer_size`` parameter. Changed default ``read_chunk_size`` to 64KB. """ self.io_loop = io_loop or ioloop.IOLoop.current() self.max_buffer_size = max_buffer_size or 104857600 # A chunk size that is too close to max_buffer_size can cause # spurious failures. self.read_chunk_size = min(read_chunk_size or 65536, self.max_buffer_size // 2) self.max_write_buffer_size = max_write_buffer_size self.error = None self._read_buffer = collections.deque() self._write_buffer = collections.deque() self._read_buffer_size = 0 self._write_buffer_size = 0 self._write_buffer_frozen = False self._read_delimiter = None self._read_regex = None self._read_max_bytes = None self._read_bytes = None self._read_partial = False self._read_until_close = False self._read_callback = None self._read_future = None self._streaming_callback = None self._write_callback = None self._write_future = None self._close_callback = None self._connect_callback = None self._connect_future = None # _ssl_connect_future should be defined in SSLIOStream # but it's here so we can clean it up in maybe_run_close_callback. # TODO: refactor that so subclasses can add additional futures # to be cancelled. self._ssl_connect_future = None self._connecting = False self._state = None self._pending_callbacks = 0 self._closed = False def fileno(self): """Returns the file descriptor for this stream.""" raise NotImplementedError() def close_fd(self): """Closes the file underlying this stream. ``close_fd`` is called by `BaseIOStream` and should not be called elsewhere; other users should call `close` instead. """ raise NotImplementedError() def write_to_fd(self, data): """Attempts to write ``data`` to the underlying file. Returns the number of bytes written. """ raise NotImplementedError() def read_from_fd(self): """Attempts to read from the underlying file. Returns ``None`` if there was nothing to read (the socket returned `~errno.EWOULDBLOCK` or equivalent), otherwise returns the data. When possible, should return no more than ``self.read_chunk_size`` bytes at a time. """ raise NotImplementedError() def get_fd_error(self): """Returns information about any error on the underlying file. This method is called after the `.IOLoop` has signaled an error on the file descriptor, and should return an Exception (such as `socket.error` with additional information, or None if no such information is available. """ return None def read_until_regex(self, regex, callback=None, max_bytes=None): """Asynchronously read until we have matched the given regex. The result includes the data that matches the regex and anything that came before it. If a callback is given, it will be run with the data as an argument; if not, this method returns a `.Future`. If ``max_bytes`` is not None, the connection will be closed if more than ``max_bytes`` bytes have been read and the regex is not satisfied. .. versionchanged:: 4.0 Added the ``max_bytes`` argument. The ``callback`` argument is now optional and a `.Future` will be returned if it is omitted. """ future = self._set_read_callback(callback) self._read_regex = re.compile(regex) self._read_max_bytes = max_bytes try: self._try_inline_read() except UnsatisfiableReadError as e: # Handle this the same way as in _handle_events. gen_log.info("Unsatisfiable read, closing connection: %s" % e) self.close(exc_info=True) return future except: if future is not None: # Ensure that the future doesn't log an error because its # failure was never examined. future.add_done_callback(lambda f: f.exception()) raise return future def read_until(self, delimiter, callback=None, max_bytes=None): """Asynchronously read until we have found the given delimiter. The result includes all the data read including the delimiter. If a callback is given, it will be run with the data as an argument; if not, this method returns a `.Future`. If ``max_bytes`` is not None, the connection will be closed if more than ``max_bytes`` bytes have been read and the delimiter is not found. .. versionchanged:: 4.0 Added the ``max_bytes`` argument. The ``callback`` argument is now optional and a `.Future` will be returned if it is omitted. """ future = self._set_read_callback(callback) self._read_delimiter = delimiter self._read_max_bytes = max_bytes try: self._try_inline_read() except UnsatisfiableReadError as e: # Handle this the same way as in _handle_events. gen_log.info("Unsatisfiable read, closing connection: %s" % e) self.close(exc_info=True) return future except: if future is not None: future.add_done_callback(lambda f: f.exception()) raise return future def read_bytes(self, num_bytes, callback=None, streaming_callback=None, partial=False): """Asynchronously read a number of bytes. If a ``streaming_callback`` is given, it will be called with chunks of data as they become available, and the final result will be empty. Otherwise, the result is all the data that was read. If a callback is given, it will be run with the data as an argument; if not, this method returns a `.Future`. If ``partial`` is true, the callback is run as soon as we have any bytes to return (but never more than ``num_bytes``) .. versionchanged:: 4.0 Added the ``partial`` argument. The callback argument is now optional and a `.Future` will be returned if it is omitted. """ future = self._set_read_callback(callback) assert isinstance(num_bytes, numbers.Integral) self._read_bytes = num_bytes self._read_partial = partial self._streaming_callback = stack_context.wrap(streaming_callback) try: self._try_inline_read() except: if future is not None: future.add_done_callback(lambda f: f.exception()) raise return future def read_until_close(self, callback=None, streaming_callback=None): """Asynchronously reads all data from the socket until it is closed. If a ``streaming_callback`` is given, it will be called with chunks of data as they become available, and the final result will be empty. Otherwise, the result is all the data that was read. If a callback is given, it will be run with the data as an argument; if not, this method returns a `.Future`. Note that if a ``streaming_callback`` is used, data will be read from the socket as quickly as it becomes available; there is no way to apply backpressure or cancel the reads. If flow control or cancellation are desired, use a loop with `read_bytes(partial=True) <.read_bytes>` instead. .. versionchanged:: 4.0 The callback argument is now optional and a `.Future` will be returned if it is omitted. """ future = self._set_read_callback(callback) self._streaming_callback = stack_context.wrap(streaming_callback) if self.closed(): if self._streaming_callback is not None: self._run_read_callback(self._read_buffer_size, True) self._run_read_callback(self._read_buffer_size, False) return future self._read_until_close = True try: self._try_inline_read() except: if future is not None: future.add_done_callback(lambda f: f.exception()) raise return future def write(self, data, callback=None): """Asynchronously write the given data to this stream. If ``callback`` is given, we call it when all of the buffered write data has been successfully written to the stream. If there was previously buffered write data and an old write callback, that callback is simply overwritten with this new callback. If no ``callback`` is given, this method returns a `.Future` that resolves (with a result of ``None``) when the write has been completed. If `write` is called again before that `.Future` has resolved, the previous future will be orphaned and will never resolve. .. versionchanged:: 4.0 Now returns a `.Future` if no callback is given. """ assert isinstance(data, bytes) self._check_closed() # We use bool(_write_buffer) as a proxy for write_buffer_size>0, # so never put empty strings in the buffer. if data: if (self.max_write_buffer_size is not None and self._write_buffer_size + len(data) > self.max_write_buffer_size): raise StreamBufferFullError("Reached maximum write buffer size") # Break up large contiguous strings before inserting them in the # write buffer, so we don't have to recopy the entire thing # as we slice off pieces to send to the socket. WRITE_BUFFER_CHUNK_SIZE = 128 * 1024 for i in range(0, len(data), WRITE_BUFFER_CHUNK_SIZE): self._write_buffer.append(data[i:i + WRITE_BUFFER_CHUNK_SIZE]) self._write_buffer_size += len(data) if callback is not None: self._write_callback = stack_context.wrap(callback) future = None else: future = self._write_future = TracebackFuture() future.add_done_callback(lambda f: f.exception()) if not self._connecting: self._handle_write() if self._write_buffer: self._add_io_state(self.io_loop.WRITE) self._maybe_add_error_listener() return future def set_close_callback(self, callback): """Call the given callback when the stream is closed. This is not necessary for applications that use the `.Future` interface; all outstanding ``Futures`` will resolve with a `StreamClosedError` when the stream is closed. """ self._close_callback = stack_context.wrap(callback) self._maybe_add_error_listener() def close(self, exc_info=False): """Close this stream. If ``exc_info`` is true, set the ``error`` attribute to the current exception from `sys.exc_info` (or if ``exc_info`` is a tuple, use that instead of `sys.exc_info`). """ if not self.closed(): if exc_info: if not isinstance(exc_info, tuple): exc_info = sys.exc_info() if any(exc_info): self.error = exc_info[1] if self._read_until_close: if (self._streaming_callback is not None and self._read_buffer_size): self._run_read_callback(self._read_buffer_size, True) self._read_until_close = False self._run_read_callback(self._read_buffer_size, False) if self._state is not None: self.io_loop.remove_handler(self.fileno()) self._state = None self.close_fd() self._closed = True self._maybe_run_close_callback() def _maybe_run_close_callback(self): # If there are pending callbacks, don't run the close callback # until they're done (see _maybe_add_error_handler) if self.closed() and self._pending_callbacks == 0: futures = [] if self._read_future is not None: futures.append(self._read_future) self._read_future = None if self._write_future is not None: futures.append(self._write_future) self._write_future = None if self._connect_future is not None: futures.append(self._connect_future) self._connect_future = None if self._ssl_connect_future is not None: futures.append(self._ssl_connect_future) self._ssl_connect_future = None for future in futures: future.set_exception(StreamClosedError(real_error=self.error)) if self._close_callback is not None: cb = self._close_callback self._close_callback = None self._run_callback(cb) # Delete any unfinished callbacks to break up reference cycles. self._read_callback = self._write_callback = None # Clear the buffers so they can be cleared immediately even # if the IOStream object is kept alive by a reference cycle. # TODO: Clear the read buffer too; it currently breaks some tests. self._write_buffer = None def reading(self): """Returns true if we are currently reading from the stream.""" return self._read_callback is not None or self._read_future is not None def writing(self): """Returns true if we are currently writing to the stream.""" return bool(self._write_buffer) def closed(self): """Returns true if the stream has been closed.""" return self._closed def set_nodelay(self, value): """Sets the no-delay flag for this stream. By default, data written to TCP streams may be held for a time to make the most efficient use of bandwidth (according to Nagle's algorithm). The no-delay flag requests that data be written as soon as possible, even if doing so would consume additional bandwidth. This flag is currently defined only for TCP-based ``IOStreams``. .. versionadded:: 3.1 """ pass def _handle_events(self, fd, events): if self.closed(): gen_log.warning("Got events for closed stream %s", fd) return try: if self._connecting: # Most IOLoops will report a write failed connect # with the WRITE event, but SelectIOLoop reports a # READ as well so we must check for connecting before # either. self._handle_connect() if self.closed(): return if events & self.io_loop.READ: self._handle_read() if self.closed(): return if events & self.io_loop.WRITE: self._handle_write() if self.closed(): return if events & self.io_loop.ERROR: self.error = self.get_fd_error() # We may have queued up a user callback in _handle_read or # _handle_write, so don't close the IOStream until those # callbacks have had a chance to run. self.io_loop.add_callback(self.close) return state = self.io_loop.ERROR if self.reading(): state |= self.io_loop.READ if self.writing(): state |= self.io_loop.WRITE if state == self.io_loop.ERROR and self._read_buffer_size == 0: # If the connection is idle, listen for reads too so # we can tell if the connection is closed. If there is # data in the read buffer we won't run the close callback # yet anyway, so we don't need to listen in this case. state |= self.io_loop.READ if state != self._state: assert self._state is not None, \ "shouldn't happen: _handle_events without self._state" self._state = state self.io_loop.update_handler(self.fileno(), self._state) except UnsatisfiableReadError as e: gen_log.info("Unsatisfiable read, closing connection: %s" % e) self.close(exc_info=True) except Exception: gen_log.error("Uncaught exception, closing connection.", exc_info=True) self.close(exc_info=True) raise def _run_callback(self, callback, *args): def wrapper(): self._pending_callbacks -= 1 try: return callback(*args) except Exception: app_log.error("Uncaught exception, closing connection.", exc_info=True) # Close the socket on an uncaught exception from a user callback # (It would eventually get closed when the socket object is # gc'd, but we don't want to rely on gc happening before we # run out of file descriptors) self.close(exc_info=True) # Re-raise the exception so that IOLoop.handle_callback_exception # can see it and log the error raise finally: self._maybe_add_error_listener() # We schedule callbacks to be run on the next IOLoop iteration # rather than running them directly for several reasons: # * Prevents unbounded stack growth when a callback calls an # IOLoop operation that immediately runs another callback # * Provides a predictable execution context for e.g. # non-reentrant mutexes # * Ensures that the try/except in wrapper() is run outside # of the application's StackContexts with stack_context.NullContext(): # stack_context was already captured in callback, we don't need to # capture it again for IOStream's wrapper. This is especially # important if the callback was pre-wrapped before entry to # IOStream (as in HTTPConnection._header_callback), as we could # capture and leak the wrong context here. self._pending_callbacks += 1 self.io_loop.add_callback(wrapper) def _read_to_buffer_loop(self): # This method is called from _handle_read and _try_inline_read. try: if self._read_bytes is not None: target_bytes = self._read_bytes elif self._read_max_bytes is not None: target_bytes = self._read_max_bytes elif self.reading(): # For read_until without max_bytes, or # read_until_close, read as much as we can before # scanning for the delimiter. target_bytes = None else: target_bytes = 0 next_find_pos = 0 # Pretend to have a pending callback so that an EOF in # _read_to_buffer doesn't trigger an immediate close # callback. At the end of this method we'll either # establish a real pending callback via # _read_from_buffer or run the close callback. # # We need two try statements here so that # pending_callbacks is decremented before the `except` # clause below (which calls `close` and does need to # trigger the callback) self._pending_callbacks += 1 while not self.closed(): # Read from the socket until we get EWOULDBLOCK or equivalent. # SSL sockets do some internal buffering, and if the data is # sitting in the SSL object's buffer select() and friends # can't see it; the only way to find out if it's there is to # try to read it. if self._read_to_buffer() == 0: break self._run_streaming_callback() # If we've read all the bytes we can use, break out of # this loop. We can't just call read_from_buffer here # because of subtle interactions with the # pending_callback and error_listener mechanisms. # # If we've reached target_bytes, we know we're done. if (target_bytes is not None and self._read_buffer_size >= target_bytes): break # Otherwise, we need to call the more expensive find_read_pos. # It's inefficient to do this on every read, so instead # do it on the first read and whenever the read buffer # size has doubled. if self._read_buffer_size >= next_find_pos: pos = self._find_read_pos() if pos is not None: return pos next_find_pos = self._read_buffer_size * 2 return self._find_read_pos() finally: self._pending_callbacks -= 1 def _handle_read(self): try: pos = self._read_to_buffer_loop() except UnsatisfiableReadError: raise except Exception as e: gen_log.warning("error on read: %s" % e) self.close(exc_info=True) return if pos is not None: self._read_from_buffer(pos) return else: self._maybe_run_close_callback() def _set_read_callback(self, callback): assert self._read_callback is None, "Already reading" assert self._read_future is None, "Already reading" if callback is not None: self._read_callback = stack_context.wrap(callback) else: self._read_future = TracebackFuture() return self._read_future def _run_read_callback(self, size, streaming): if streaming: callback = self._streaming_callback else: callback = self._read_callback self._read_callback = self._streaming_callback = None if self._read_future is not None: assert callback is None future = self._read_future self._read_future = None future.set_result(self._consume(size)) if callback is not None: assert (self._read_future is None) or streaming self._run_callback(callback, self._consume(size)) else: # If we scheduled a callback, we will add the error listener # afterwards. If we didn't, we have to do it now. self._maybe_add_error_listener() def _try_inline_read(self): """Attempt to complete the current read operation from buffered data. If the read can be completed without blocking, schedules the read callback on the next IOLoop iteration; otherwise starts listening for reads on the socket. """ # See if we've already got the data from a previous read self._run_streaming_callback() pos = self._find_read_pos() if pos is not None: self._read_from_buffer(pos) return self._check_closed() try: pos = self._read_to_buffer_loop() except Exception: # If there was an in _read_to_buffer, we called close() already, # but couldn't run the close callback because of _pending_callbacks. # Before we escape from this function, run the close callback if # applicable. self._maybe_run_close_callback() raise if pos is not None: self._read_from_buffer(pos) return # We couldn't satisfy the read inline, so either close the stream # or listen for new data. if self.closed(): self._maybe_run_close_callback() else: self._add_io_state(ioloop.IOLoop.READ) def _read_to_buffer(self): """Reads from the socket and appends the result to the read buffer. Returns the number of bytes read. Returns 0 if there is nothing to read (i.e. the read returns EWOULDBLOCK or equivalent). On error closes the socket and raises an exception. """ while True: try: chunk = self.read_from_fd() except (socket.error, IOError, OSError) as e: if errno_from_exception(e) == errno.EINTR: continue # ssl.SSLError is a subclass of socket.error if self._is_connreset(e): # Treat ECONNRESET as a connection close rather than # an error to minimize log spam (the exception will # be available on self.error for apps that care). self.close(exc_info=True) return self.close(exc_info=True) raise break if chunk is None: return 0 self._read_buffer.append(chunk) self._read_buffer_size += len(chunk) if self._read_buffer_size > self.max_buffer_size: gen_log.error("Reached maximum read buffer size") self.close() raise StreamBufferFullError("Reached maximum read buffer size") return len(chunk) def _run_streaming_callback(self): if self._streaming_callback is not None and self._read_buffer_size: bytes_to_consume = self._read_buffer_size if self._read_bytes is not None: bytes_to_consume = min(self._read_bytes, bytes_to_consume) self._read_bytes -= bytes_to_consume self._run_read_callback(bytes_to_consume, True) def _read_from_buffer(self, pos): """Attempts to complete the currently-pending read from the buffer. The argument is either a position in the read buffer or None, as returned by _find_read_pos. """ self._read_bytes = self._read_delimiter = self._read_regex = None self._read_partial = False self._run_read_callback(pos, False) def _find_read_pos(self): """Attempts to find a position in the read buffer that satisfies the currently-pending read. Returns a position in the buffer if the current read can be satisfied, or None if it cannot. """ if (self._read_bytes is not None and (self._read_buffer_size >= self._read_bytes or (self._read_partial and self._read_buffer_size > 0))): num_bytes = min(self._read_bytes, self._read_buffer_size) return num_bytes elif self._read_delimiter is not None: # Multi-byte delimiters (e.g. '\r\n') may straddle two # chunks in the read buffer, so we can't easily find them # without collapsing the buffer. However, since protocols # using delimited reads (as opposed to reads of a known # length) tend to be "line" oriented, the delimiter is likely # to be in the first few chunks. Merge the buffer gradually # since large merges are relatively expensive and get undone in # _consume(). if self._read_buffer: while True: loc = self._read_buffer[0].find(self._read_delimiter) if loc != -1: delimiter_len = len(self._read_delimiter) self._check_max_bytes(self._read_delimiter, loc + delimiter_len) return loc + delimiter_len if len(self._read_buffer) == 1: break _double_prefix(self._read_buffer) self._check_max_bytes(self._read_delimiter, len(self._read_buffer[0])) elif self._read_regex is not None: if self._read_buffer: while True: m = self._read_regex.search(self._read_buffer[0]) if m is not None: self._check_max_bytes(self._read_regex, m.end()) return m.end() if len(self._read_buffer) == 1: break _double_prefix(self._read_buffer) self._check_max_bytes(self._read_regex, len(self._read_buffer[0])) return None def _check_max_bytes(self, delimiter, size): if (self._read_max_bytes is not None and size > self._read_max_bytes): raise UnsatisfiableReadError( "delimiter %r not found within %d bytes" % ( delimiter, self._read_max_bytes)) def _handle_write(self): while self._write_buffer: try: if not self._write_buffer_frozen: # On windows, socket.send blows up if given a # write buffer that's too large, instead of just # returning the number of bytes it was able to # process. Therefore we must not call socket.send # with more than 128KB at a time. _merge_prefix(self._write_buffer, 128 * 1024) num_bytes = self.write_to_fd(self._write_buffer[0]) if num_bytes == 0: # With OpenSSL, if we couldn't write the entire buffer, # the very same string object must be used on the # next call to send. Therefore we suppress # merging the write buffer after an incomplete send. # A cleaner solution would be to set # SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER, but this is # not yet accessible from python # (http://bugs.python.org/issue8240) self._write_buffer_frozen = True break self._write_buffer_frozen = False _merge_prefix(self._write_buffer, num_bytes) self._write_buffer.popleft() self._write_buffer_size -= num_bytes except (socket.error, IOError, OSError) as e: if e.args[0] in _ERRNO_WOULDBLOCK: self._write_buffer_frozen = True break else: if not self._is_connreset(e): # Broken pipe errors are usually caused by connection # reset, and its better to not log EPIPE errors to # minimize log spam gen_log.warning("Write error on %s: %s", self.fileno(), e) self.close(exc_info=True) return if not self._write_buffer: if self._write_callback: callback = self._write_callback self._write_callback = None self._run_callback(callback) if self._write_future: future = self._write_future self._write_future = None future.set_result(None) def _consume(self, loc): if loc == 0: return b"" _merge_prefix(self._read_buffer, loc) self._read_buffer_size -= loc return self._read_buffer.popleft() def _check_closed(self): if self.closed(): raise StreamClosedError(real_error=self.error) def _maybe_add_error_listener(self): # This method is part of an optimization: to detect a connection that # is closed when we're not actively reading or writing, we must listen # for read events. However, it is inefficient to do this when the # connection is first established because we are going to read or write # immediately anyway. Instead, we insert checks at various times to # see if the connection is idle and add the read listener then. if self._pending_callbacks != 0: return if self._state is None or self._state == ioloop.IOLoop.ERROR: if self.closed(): self._maybe_run_close_callback() elif (self._read_buffer_size == 0 and self._close_callback is not None): self._add_io_state(ioloop.IOLoop.READ) def _add_io_state(self, state): """Adds `state` (IOLoop.{READ,WRITE} flags) to our event handler. Implementation notes: Reads and writes have a fast path and a slow path. The fast path reads synchronously from socket buffers, while the slow path uses `_add_io_state` to schedule an IOLoop callback. Note that in both cases, the callback is run asynchronously with `_run_callback`. To detect closed connections, we must have called `_add_io_state` at some point, but we want to delay this as much as possible so we don't have to set an `IOLoop.ERROR` listener that will be overwritten by the next slow-path operation. As long as there are callbacks scheduled for fast-path ops, those callbacks may do more reads. If a sequence of fast-path ops do not end in a slow-path op, (e.g. for an @asynchronous long-poll request), we must add the error handler. This is done in `_run_callback` and `write` (since the write callback is optional so we can have a fast-path write with no `_run_callback`) """ if self.closed(): # connection has been closed, so there can be no future events return if self._state is None: self._state = ioloop.IOLoop.ERROR | state with stack_context.NullContext(): self.io_loop.add_handler( self.fileno(), self._handle_events, self._state) elif not self._state & state: self._state = self._state | state self.io_loop.update_handler(self.fileno(), self._state) def _is_connreset(self, exc): """Return true if exc is ECONNRESET or equivalent. May be overridden in subclasses. """ return (isinstance(exc, (socket.error, IOError)) and errno_from_exception(exc) in _ERRNO_CONNRESET) class IOStream(BaseIOStream): r"""Socket-based `IOStream` implementation. This class supports the read and write methods from `BaseIOStream` plus a `connect` method. The ``socket`` parameter may either be connected or unconnected. For server operations the socket is the result of calling `socket.accept <socket.socket.accept>`. For client operations the socket is created with `socket.socket`, and may either be connected before passing it to the `IOStream` or connected with `IOStream.connect`. A very simple (and broken) HTTP client using this class: .. testcode:: import tornado.ioloop import tornado.iostream import socket def send_request(): stream.write(b"GET / HTTP/1.0\r\nHost: friendfeed.com\r\n\r\n") stream.read_until(b"\r\n\r\n", on_headers) def on_headers(data): headers = {} for line in data.split(b"\r\n"): parts = line.split(b":") if len(parts) == 2: headers[parts[0].strip()] = parts[1].strip() stream.read_bytes(int(headers[b"Content-Length"]), on_body) def on_body(data): print(data) stream.close() tornado.ioloop.IOLoop.current().stop() if __name__ == '__main__': s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) stream = tornado.iostream.IOStream(s) stream.connect(("friendfeed.com", 80), send_request) tornado.ioloop.IOLoop.current().start() .. testoutput:: :hide: """ def __init__(self, socket, *args, **kwargs): self.socket = socket self.socket.setblocking(False) super(IOStream, self).__init__(*args, **kwargs) def fileno(self): return self.socket def close_fd(self): self.socket.close() self.socket = None def get_fd_error(self): errno = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) return socket.error(errno, os.strerror(errno)) def read_from_fd(self): try: chunk = self.socket.recv(self.read_chunk_size) except socket.error as e: if e.args[0] in _ERRNO_WOULDBLOCK: return None else: raise if not chunk: self.close() return None return chunk def write_to_fd(self, data): return self.socket.send(data) def connect(self, address, callback=None, server_hostname=None): """Connects the socket to a remote address without blocking. May only be called if the socket passed to the constructor was not previously connected. The address parameter is in the same format as for `socket.connect <socket.socket.connect>` for the type of socket passed to the IOStream constructor, e.g. an ``(ip, port)`` tuple. Hostnames are accepted here, but will be resolved synchronously and block the IOLoop. If you have a hostname instead of an IP address, the `.TCPClient` class is recommended instead of calling this method directly. `.TCPClient` will do asynchronous DNS resolution and handle both IPv4 and IPv6. If ``callback`` is specified, it will be called with no arguments when the connection is completed; if not this method returns a `.Future` (whose result after a successful connection will be the stream itself). In SSL mode, the ``server_hostname`` parameter will be used for certificate validation (unless disabled in the ``ssl_options``) and SNI (if supported; requires Python 2.7.9+). Note that it is safe to call `IOStream.write <BaseIOStream.write>` while the connection is pending, in which case the data will be written as soon as the connection is ready. Calling `IOStream` read methods before the socket is connected works on some platforms but is non-portable. .. versionchanged:: 4.0 If no callback is given, returns a `.Future`. .. versionchanged:: 4.2 SSL certificates are validated by default; pass ``ssl_options=dict(cert_reqs=ssl.CERT_NONE)`` or a suitably-configured `ssl.SSLContext` to the `SSLIOStream` constructor to disable. """ self._connecting = True if callback is not None: self._connect_callback = stack_context.wrap(callback) future = None else: future = self._connect_future = TracebackFuture() try: self.socket.connect(address) except socket.error as e: # In non-blocking mode we expect connect() to raise an # exception with EINPROGRESS or EWOULDBLOCK. # # On freebsd, other errors such as ECONNREFUSED may be # returned immediately when attempting to connect to # localhost, so handle them the same way as an error # reported later in _handle_connect. if (errno_from_exception(e) not in _ERRNO_INPROGRESS and errno_from_exception(e) not in _ERRNO_WOULDBLOCK): if future is None: gen_log.warning("Connect error on fd %s: %s", self.socket.fileno(), e) self.close(exc_info=True) return future self._add_io_state(self.io_loop.WRITE) return future def start_tls(self, server_side, ssl_options=None, server_hostname=None): """Convert this `IOStream` to an `SSLIOStream`. This enables protocols that begin in clear-text mode and switch to SSL after some initial negotiation (such as the ``STARTTLS`` extension to SMTP and IMAP). This method cannot be used if there are outstanding reads or writes on the stream, or if there is any data in the IOStream's buffer (data in the operating system's socket buffer is allowed). This means it must generally be used immediately after reading or writing the last clear-text data. It can also be used immediately after connecting, before any reads or writes. The ``ssl_options`` argument may be either an `ssl.SSLContext` object or a dictionary of keyword arguments for the `ssl.wrap_socket` function. The ``server_hostname`` argument will be used for certificate validation unless disabled in the ``ssl_options``. This method returns a `.Future` whose result is the new `SSLIOStream`. After this method has been called, any other operation on the original stream is undefined. If a close callback is defined on this stream, it will be transferred to the new stream. .. versionadded:: 4.0 .. versionchanged:: 4.2 SSL certificates are validated by default; pass ``ssl_options=dict(cert_reqs=ssl.CERT_NONE)`` or a suitably-configured `ssl.SSLContext` to disable. """ if (self._read_callback or self._read_future or self._write_callback or self._write_future or self._connect_callback or self._connect_future or self._pending_callbacks or self._closed or self._read_buffer or self._write_buffer): raise ValueError("IOStream is not idle; cannot convert to SSL") if ssl_options is None: if server_side: ssl_options = _server_ssl_defaults else: ssl_options = _client_ssl_defaults socket = self.socket self.io_loop.remove_handler(socket) self.socket = None socket = ssl_wrap_socket(socket, ssl_options, server_hostname=server_hostname, server_side=server_side, do_handshake_on_connect=False) orig_close_callback = self._close_callback self._close_callback = None future = TracebackFuture() ssl_stream = SSLIOStream(socket, ssl_options=ssl_options, io_loop=self.io_loop) # Wrap the original close callback so we can fail our Future as well. # If we had an "unwrap" counterpart to this method we would need # to restore the original callback after our Future resolves # so that repeated wrap/unwrap calls don't build up layers. def close_callback(): if not future.done(): # Note that unlike most Futures returned by IOStream, # this one passes the underlying error through directly # instead of wrapping everything in a StreamClosedError # with a real_error attribute. This is because once the # connection is established it's more helpful to raise # the SSLError directly than to hide it behind a # StreamClosedError (and the client is expecting SSL # issues rather than network issues since this method is # named start_tls). future.set_exception(ssl_stream.error or StreamClosedError()) if orig_close_callback is not None: orig_close_callback() ssl_stream.set_close_callback(close_callback) ssl_stream._ssl_connect_callback = lambda: future.set_result(ssl_stream) ssl_stream.max_buffer_size = self.max_buffer_size ssl_stream.read_chunk_size = self.read_chunk_size return future def _handle_connect(self): err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: self.error = socket.error(err, os.strerror(err)) # IOLoop implementations may vary: some of them return # an error state before the socket becomes writable, so # in that case a connection failure would be handled by the # error path in _handle_events instead of here. if self._connect_future is None: gen_log.warning("Connect error on fd %s: %s", self.socket.fileno(), errno.errorcode[err]) self.close() return if self._connect_callback is not None: callback = self._connect_callback self._connect_callback = None self._run_callback(callback) if self._connect_future is not None: future = self._connect_future self._connect_future = None future.set_result(self) self._connecting = False def set_nodelay(self, value): if (self.socket is not None and self.socket.family in (socket.AF_INET, socket.AF_INET6)): try: self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1 if value else 0) except socket.error as e: # Sometimes setsockopt will fail if the socket is closed # at the wrong time. This can happen with HTTPServer # resetting the value to false between requests. if e.errno != errno.EINVAL and not self._is_connreset(e): raise class SSLIOStream(IOStream): """A utility class to write to and read from a non-blocking SSL socket. If the socket passed to the constructor is already connected, it should be wrapped with:: ssl.wrap_socket(sock, do_handshake_on_connect=False, **kwargs) before constructing the `SSLIOStream`. Unconnected sockets will be wrapped when `IOStream.connect` is finished. """ def __init__(self, *args, **kwargs): """The ``ssl_options`` keyword argument may either be an `ssl.SSLContext` object or a dictionary of keywords arguments for `ssl.wrap_socket` """ self._ssl_options = kwargs.pop('ssl_options', _client_ssl_defaults) super(SSLIOStream, self).__init__(*args, **kwargs) self._ssl_accepting = True self._handshake_reading = False self._handshake_writing = False self._ssl_connect_callback = None self._server_hostname = None # If the socket is already connected, attempt to start the handshake. try: self.socket.getpeername() except socket.error: pass else: # Indirectly start the handshake, which will run on the next # IOLoop iteration and then the real IO state will be set in # _handle_events. self._add_io_state(self.io_loop.WRITE) def reading(self): return self._handshake_reading or super(SSLIOStream, self).reading() def writing(self): return self._handshake_writing or super(SSLIOStream, self).writing() def _do_ssl_handshake(self): # Based on code from test_ssl.py in the python stdlib try: self._handshake_reading = False self._handshake_writing = False self.socket.do_handshake() except ssl.SSLError as err: if err.args[0] == ssl.SSL_ERROR_WANT_READ: self._handshake_reading = True return elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE: self._handshake_writing = True return elif err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN): return self.close(exc_info=True) elif err.args[0] == ssl.SSL_ERROR_SSL: try: peer = self.socket.getpeername() except Exception: peer = '(not connected)' gen_log.warning("SSL Error on %s %s: %s", self.socket.fileno(), peer, err) return self.close(exc_info=True) raise except socket.error as err: # Some port scans (e.g. nmap in -sT mode) have been known # to cause do_handshake to raise EBADF and ENOTCONN, so make # those errors quiet as well. # https://groups.google.com/forum/?fromgroups#!topic/python-tornado/ApucKJat1_0 if (self._is_connreset(err) or err.args[0] in (errno.EBADF, errno.ENOTCONN)): return self.close(exc_info=True) raise except AttributeError: # On Linux, if the connection was reset before the call to # wrap_socket, do_handshake will fail with an # AttributeError. return self.close(exc_info=True) else: self._ssl_accepting = False if not self._verify_cert(self.socket.getpeercert()): self.close() return self._run_ssl_connect_callback() def _run_ssl_connect_callback(self): if self._ssl_connect_callback is not None: callback = self._ssl_connect_callback self._ssl_connect_callback = None self._run_callback(callback) if self._ssl_connect_future is not None: future = self._ssl_connect_future self._ssl_connect_future = None future.set_result(self) def _verify_cert(self, peercert): """Returns True if peercert is valid according to the configured validation mode and hostname. The ssl handshake already tested the certificate for a valid CA signature; the only thing that remains is to check the hostname. """ if isinstance(self._ssl_options, dict): verify_mode = self._ssl_options.get('cert_reqs', ssl.CERT_NONE) elif isinstance(self._ssl_options, ssl.SSLContext): verify_mode = self._ssl_options.verify_mode assert verify_mode in (ssl.CERT_NONE, ssl.CERT_REQUIRED, ssl.CERT_OPTIONAL) if verify_mode == ssl.CERT_NONE or self._server_hostname is None: return True cert = self.socket.getpeercert() if cert is None and verify_mode == ssl.CERT_REQUIRED: gen_log.warning("No SSL certificate given") return False try: ssl_match_hostname(peercert, self._server_hostname) except SSLCertificateError as e: gen_log.warning("Invalid SSL certificate: %s" % e) return False else: return True def _handle_read(self): if self._ssl_accepting: self._do_ssl_handshake() return super(SSLIOStream, self)._handle_read() def _handle_write(self): if self._ssl_accepting: self._do_ssl_handshake() return super(SSLIOStream, self)._handle_write() def connect(self, address, callback=None, server_hostname=None): self._server_hostname = server_hostname # Pass a dummy callback to super.connect(), which is slightly # more efficient than letting it return a Future we ignore. super(SSLIOStream, self).connect(address, callback=lambda: None) return self.wait_for_handshake(callback) def _handle_connect(self): # Call the superclass method to check for errors. super(SSLIOStream, self)._handle_connect() if self.closed(): return # When the connection is complete, wrap the socket for SSL # traffic. Note that we do this by overriding _handle_connect # instead of by passing a callback to super().connect because # user callbacks are enqueued asynchronously on the IOLoop, # but since _handle_events calls _handle_connect immediately # followed by _handle_write we need this to be synchronous. # # The IOLoop will get confused if we swap out self.socket while the # fd is registered, so remove it now and re-register after # wrap_socket(). self.io_loop.remove_handler(self.socket) old_state = self._state self._state = None self.socket = ssl_wrap_socket(self.socket, self._ssl_options, server_hostname=self._server_hostname, do_handshake_on_connect=False) self._add_io_state(old_state) def wait_for_handshake(self, callback=None): """Wait for the initial SSL handshake to complete. If a ``callback`` is given, it will be called with no arguments once the handshake is complete; otherwise this method returns a `.Future` which will resolve to the stream itself after the handshake is complete. Once the handshake is complete, information such as the peer's certificate and NPN/ALPN selections may be accessed on ``self.socket``. This method is intended for use on server-side streams or after using `IOStream.start_tls`; it should not be used with `IOStream.connect` (which already waits for the handshake to complete). It may only be called once per stream. .. versionadded:: 4.2 """ if (self._ssl_connect_callback is not None or self._ssl_connect_future is not None): raise RuntimeError("Already waiting") if callback is not None: self._ssl_connect_callback = stack_context.wrap(callback) future = None else: future = self._ssl_connect_future = TracebackFuture() if not self._ssl_accepting: self._run_ssl_connect_callback() return future def write_to_fd(self, data): try: return self.socket.send(data) except ssl.SSLError as e: if e.args[0] == ssl.SSL_ERROR_WANT_WRITE: # In Python 3.5+, SSLSocket.send raises a WANT_WRITE error if # the socket is not writeable; we need to transform this into # an EWOULDBLOCK socket.error or a zero return value, # either of which will be recognized by the caller of this # method. Prior to Python 3.5, an unwriteable socket would # simply return 0 bytes written. return 0 raise def read_from_fd(self): if self._ssl_accepting: # If the handshake hasn't finished yet, there can't be anything # to read (attempting to read may or may not raise an exception # depending on the SSL version) return None try: # SSLSocket objects have both a read() and recv() method, # while regular sockets only have recv(). # The recv() method blocks (at least in python 2.6) if it is # called when there is nothing to read, so we have to use # read() instead. chunk = self.socket.read(self.read_chunk_size) except ssl.SSLError as e: # SSLError is a subclass of socket.error, so this except # block must come first. if e.args[0] == ssl.SSL_ERROR_WANT_READ: return None else: raise except socket.error as e: if e.args[0] in _ERRNO_WOULDBLOCK: return None else: raise if not chunk: self.close() return None return chunk def _is_connreset(self, e): if isinstance(e, ssl.SSLError) and e.args[0] == ssl.SSL_ERROR_EOF: return True return super(SSLIOStream, self)._is_connreset(e) class PipeIOStream(BaseIOStream): """Pipe-based `IOStream` implementation. The constructor takes an integer file descriptor (such as one returned by `os.pipe`) rather than an open file object. Pipes are generally one-way, so a `PipeIOStream` can be used for reading or writing but not both. """ def __init__(self, fd, *args, **kwargs): self.fd = fd _set_nonblocking(fd) super(PipeIOStream, self).__init__(*args, **kwargs) def fileno(self): return self.fd def close_fd(self): os.close(self.fd) def write_to_fd(self, data): return os.write(self.fd, data) def read_from_fd(self): try: chunk = os.read(self.fd, self.read_chunk_size) except (IOError, OSError) as e: if errno_from_exception(e) in _ERRNO_WOULDBLOCK: return None elif errno_from_exception(e) == errno.EBADF: # If the writing half of a pipe is closed, select will # report it as readable but reads will fail with EBADF. self.close(exc_info=True) return None else: raise if not chunk: self.close() return None return chunk def _double_prefix(deque): """Grow by doubling, but don't split the second chunk just because the first one is small. """ new_len = max(len(deque[0]) * 2, (len(deque[0]) + len(deque[1]))) _merge_prefix(deque, new_len) def _merge_prefix(deque, size): """Replace the first entries in a deque of strings with a single string of up to size bytes. >>> d = collections.deque(['abc', 'de', 'fghi', 'j']) >>> _merge_prefix(d, 5); print(d) deque(['abcde', 'fghi', 'j']) Strings will be split as necessary to reach the desired size. >>> _merge_prefix(d, 7); print(d) deque(['abcdefg', 'hi', 'j']) >>> _merge_prefix(d, 3); print(d) deque(['abc', 'defg', 'hi', 'j']) >>> _merge_prefix(d, 100); print(d) deque(['abcdefghij']) """ if len(deque) == 1 and len(deque[0]) <= size: return prefix = [] remaining = size while deque and remaining > 0: chunk = deque.popleft() if len(chunk) > remaining: deque.appendleft(chunk[remaining:]) chunk = chunk[:remaining] prefix.append(chunk) remaining -= len(chunk) # This data structure normally just contains byte strings, but # the unittest gets messy if it doesn't use the default str() type, # so do the merge based on the type of data that's actually present. if prefix: deque.appendleft(type(prefix[0])().join(prefix)) if not deque: deque.appendleft(b"") def doctests(): import doctest return doctest.DocTestSuite()
unknown
codeparrot/codeparrot-clean
import os from qtpy import QtGui, compat from glue.viewers.common.tool import Tool, CheckableTool from glue.config import viewer_tool from vispy import app, io RECORD_START_ICON = os.path.join(os.path.dirname(__file__), 'glue_record_start.png') RECORD_STOP_ICON = os.path.join(os.path.dirname(__file__), 'glue_record_stop.png') ROTATE_ICON = os.path.join(os.path.dirname(__file__), 'glue_rotate.png') @viewer_tool class ResetTool(Tool): icon = 'glue_home' tool_id = 'vispy:reset' action_text = 'Reset the view' tool_tip = 'Reset the view' def activate(self): self.viewer._vispy_widget.view.camera.reset() self.viewer._vispy_widget._toggle_perspective() self.viewer.state.reset_limits() @viewer_tool class SaveTool(Tool): icon = 'glue_filesave' tool_id = 'vispy:save' action_text = 'Save the figure to a file' tool_tip = 'Save the figure to a file' def activate(self): outfile, file_filter = compat.getsavefilename(caption='Save File', filters='PNG Files (*.png);;' 'JPEG Files (*.jpeg);;' 'TIFF Files (*.tiff);;', selectedfilter='PNG Files (*.png);;') # This indicates that the user cancelled if not outfile: return img = self.viewer._vispy_widget.canvas.render() try: file_filter = str(file_filter).split()[0] io.imsave(outfile, img, format=file_filter) except ImportError: # TODO: give out a window to notify that only .png file format is supported if '.' not in outfile: outfile += '.png' io.write_png(outfile, img) @viewer_tool class RecordTool(CheckableTool): icon = RECORD_START_ICON tool_id = 'vispy:record' action_text = 'Record an animation' tool_tip = 'Start/Stop the recording' def __init__(self, viewer): super(RecordTool, self).__init__(viewer=viewer) self.record_timer = app.Timer(connect=self.record) self.writer = None self.next_action = 'start' def activate(self): # pop up a window for file saving outfile, file_filter = compat.getsavefilename(caption='Save Animation', filters='GIF Files (*.gif);;') # if outfile is not set, the user cancelled if outfile: import imageio self.set_icon(RECORD_STOP_ICON) self.writer = imageio.get_writer(outfile) self.record_timer.start(0.1) def deactivate(self): self.record_timer.stop() if self.writer is not None: self.writer.close() self.set_icon(RECORD_START_ICON) def set_icon(self, icon): self.viewer.toolbar.actions[self.tool_id].setIcon(QtGui.QIcon(icon)) def record(self, event): im = self.viewer._vispy_widget.canvas.render() self.writer.append_data(im) @viewer_tool class RotateTool(CheckableTool): icon = ROTATE_ICON tool_id = 'vispy:rotate' action_text = 'Continuously rotate view' tool_tip = 'Start/Stop rotation' timer = None def activate(self): if self.timer is None: self.timer = app.Timer(connect=self.rotate) self.timer.start(0.1) def deactivate(self): self.timer.stop() def rotate(self, event): self.viewer._vispy_widget.view.camera.azimuth -= 1. # set speed as constant first
unknown
codeparrot/codeparrot-clean
/* * Copyright 2014-2025 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.webrtc import WebRTC.RTCDataBuffer import WebRTC.RTCDataChannel import WebRTC.RTCDataChannelDelegateProtocol import kotlinx.cinterop.ExperimentalForeignApi import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.launch import platform.darwin.NSObject /** * WebRtc data channel implementation for the Ios platform. * * [Report a problem](https://ktor.io/feedback/?fqname=io.ktor.client.webrtc.IosWebRtcDataChannel) */ @OptIn(ExperimentalForeignApi::class) public class IosWebRtcDataChannel( internal val nativeChannel: RTCDataChannel, private val coroutineScope: CoroutineScope, receiveOptions: DataChannelReceiveOptions ) : WebRtcDataChannel(receiveOptions) { override val id: Int? get() = nativeChannel.channelId.let { if (it < 0) null else it } override val label: String get() = nativeChannel.label() override val state: WebRtc.DataChannel.State get() = nativeChannel.readyState.toKtor() override val bufferedAmount: Long get() = nativeChannel.bufferedAmount().toLong() override var bufferedAmountLowThreshold: Long = 0 private set override val maxPacketLifeTime: Int get() = nativeChannel.maxPacketLifeTime.toInt() override val maxRetransmits: Int get() = nativeChannel.maxRetransmits.toInt() override val negotiated: Boolean get() = nativeChannel.isNegotiated override val ordered: Boolean get() = nativeChannel.isOrdered override val protocol: String get() = nativeChannel.protocol() private fun assertOpen() { if (!state.canSend()) { error("Data channel is closed.") } } override suspend fun send(text: String) { assertOpen() if (!nativeChannel.sendData(data = text.toRTCDataBuffer())) { error("Failed to send text message over DataChannel.") } } override suspend fun send(bytes: ByteArray) { assertOpen() if (!nativeChannel.sendData(data = bytes.toRTCDataBuffer())) { error("Failed to send binary message over DataChannel.") } } override fun setBufferedAmountLowThreshold(threshold: Long) { bufferedAmountLowThreshold = threshold } override fun closeTransport() { nativeChannel.close() } private fun runInConnectionScope(block: suspend CoroutineScope.() -> Unit) { coroutineScope.launch(start = CoroutineStart.UNDISPATCHED, block = block) } internal fun setupEvents(eventsEmitter: WebRtcConnectionEventsEmitter) { nativeChannel.setDelegate(object : RTCDataChannelDelegateProtocol, NSObject() { override fun dataChannel(dataChannel: RTCDataChannel, didChangeBufferedAmount: ULong) = runInConnectionScope { // guard against duplicate events if (didChangeBufferedAmount.toLong() < bufferedAmountLowThreshold) { return@runInConnectionScope } // buffer has dropped below the threshold if (bufferedAmount <= bufferedAmountLowThreshold) { val event = DataChannelEvent.BufferedAmountLow(this@IosWebRtcDataChannel) eventsEmitter.emitDataChannelEvent(event) } } override fun dataChannelDidChangeState(dataChannel: RTCDataChannel) = runInConnectionScope { val event = when (state) { WebRtc.DataChannel.State.CONNECTING -> null WebRtc.DataChannel.State.OPEN -> DataChannelEvent.Open(this@IosWebRtcDataChannel) WebRtc.DataChannel.State.CLOSING -> DataChannelEvent.Closing(this@IosWebRtcDataChannel) WebRtc.DataChannel.State.CLOSED -> { stopReceivingMessages() DataChannelEvent.Closed(this@IosWebRtcDataChannel) } } if (event != null) { eventsEmitter.emitDataChannelEvent(event) } } override fun dataChannel( dataChannel: RTCDataChannel, didReceiveMessageWithBuffer: RTCDataBuffer ) = runInConnectionScope { emitMessage(didReceiveMessageWithBuffer.toKtor()) } }) } } /** * Returns implementation of the data channel that is used under the hood. Use it with caution. * * [Report a problem](https://ktor.io/feedback/?fqname=io.ktor.client.webrtc.getNative) */ @OptIn(ExperimentalForeignApi::class) public fun WebRtcDataChannel.getNative(): RTCDataChannel { return (this as IosWebRtcDataChannel).nativeChannel }
kotlin
github
https://github.com/ktorio/ktor
ktor-client/ktor-client-webrtc/ios/src/io/ktor/client/webrtc/DataChannel.kt
"""HTML utilities suitable for global use.""" from __future__ import unicode_literals import re import string try: from urllib.parse import quote, unquote, urlsplit, urlunsplit except ImportError: # Python 2 from urllib import quote, unquote from urlparse import urlsplit, urlunsplit from django.utils.safestring import SafeData, mark_safe from django.utils.encoding import force_text, force_str from django.utils.functional import allow_lazy from django.utils import six from django.utils.text import normalize_newlines # Configuration for urlize() function. TRAILING_PUNCTUATION = ['.', ',', ':', ';', '.)'] WRAPPING_PUNCTUATION = [('(', ')'), ('<', '>'), ('[', ']'), ('&lt;', '&gt;')] # List of possible strings used for bullets in bulleted lists. DOTS = ['&middot;', '*', '\u2022', '&#149;', '&bull;', '&#8226;'] unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)') word_split_re = re.compile(r'(\s+)') simple_url_re = re.compile(r'^https?://\w', re.IGNORECASE) simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)$', re.IGNORECASE) simple_email_re = re.compile(r'^\S+@\S+\.\S+$') link_target_attribute_re = re.compile(r'(<a [^>]*?)target=[^\s>]+') html_gunk_re = re.compile(r'(?:<br clear="all">|<i><\/i>|<b><\/b>|<em><\/em>|<strong><\/strong>|<\/?smallcaps>|<\/?uppercase>)', re.IGNORECASE) hard_coded_bullets_re = re.compile(r'((?:<p>(?:%s).*?[a-zA-Z].*?</p>\s*)+)' % '|'.join([re.escape(x) for x in DOTS]), re.DOTALL) trailing_empty_content_re = re.compile(r'(?:<p>(?:&nbsp;|\s|<br \/>)*?</p>\s*)+\Z') strip_tags_re = re.compile(r'<[^>]*?>', re.IGNORECASE) def escape(text): """ Returns the given text with ampersands, quotes and angle brackets encoded for use in HTML. """ return mark_safe(force_text(text).replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;')) escape = allow_lazy(escape, six.text_type) _js_escapes = { ord('\\'): '\\u005C', ord('\''): '\\u0027', ord('"'): '\\u0022', ord('>'): '\\u003E', ord('<'): '\\u003C', ord('&'): '\\u0026', ord('='): '\\u003D', ord('-'): '\\u002D', ord(';'): '\\u003B', ord('\u2028'): '\\u2028', ord('\u2029'): '\\u2029' } # Escape every ASCII character with a value less than 32. _js_escapes.update((ord('%c' % z), '\\u%04X' % z) for z in range(32)) def escapejs(value): """Hex encodes characters for use in JavaScript strings.""" return mark_safe(force_text(value).translate(_js_escapes)) escapejs = allow_lazy(escapejs, six.text_type) def conditional_escape(text): """ Similar to escape(), except that it doesn't operate on pre-escaped strings. """ if isinstance(text, SafeData): return text else: return escape(text) def format_html(format_string, *args, **kwargs): """ Similar to str.format, but passes all arguments through conditional_escape, and calls 'mark_safe' on the result. This function should be used instead of str.format or % interpolation to build up small HTML fragments. """ args_safe = map(conditional_escape, args) kwargs_safe = dict([(k, conditional_escape(v)) for (k, v) in six.iteritems(kwargs)]) return mark_safe(format_string.format(*args_safe, **kwargs_safe)) def format_html_join(sep, format_string, args_generator): """ A wrapper of format_html, for the common case of a group of arguments that need to be formatted using the same format string, and then joined using 'sep'. 'sep' is also passed through conditional_escape. 'args_generator' should be an iterator that returns the sequence of 'args' that will be passed to format_html. Example: format_html_join('\n', "<li>{0} {1}</li>", ((u.first_name, u.last_name) for u in users)) """ return mark_safe(conditional_escape(sep).join( format_html(format_string, *tuple(args)) for args in args_generator)) def linebreaks(value, autoescape=False): """Converts newlines into <p> and <br />s.""" value = normalize_newlines(value) paras = re.split('\n{2,}', value) if autoescape: paras = ['<p>%s</p>' % escape(p).replace('\n', '<br />') for p in paras] else: paras = ['<p>%s</p>' % p.replace('\n', '<br />') for p in paras] return '\n\n'.join(paras) linebreaks = allow_lazy(linebreaks, six.text_type) def strip_tags(value): """Returns the given HTML with all tags stripped.""" return strip_tags_re.sub('', force_text(value)) strip_tags = allow_lazy(strip_tags) def remove_tags(html, tags): """Returns the given HTML with given tags removed.""" tags = [re.escape(tag) for tag in tags.split()] tags_re = '(%s)' % '|'.join(tags) starttag_re = re.compile(r'<%s(/?>|(\s+[^>]*>))' % tags_re, re.U) endtag_re = re.compile('</%s>' % tags_re) html = starttag_re.sub('', html) html = endtag_re.sub('', html) return html remove_tags = allow_lazy(remove_tags, six.text_type) def strip_spaces_between_tags(value): """Returns the given HTML with spaces between tags removed.""" return re.sub(r'>\s+<', '><', force_text(value)) strip_spaces_between_tags = allow_lazy(strip_spaces_between_tags, six.text_type) def strip_entities(value): """Returns the given HTML with all entities (&something;) stripped.""" return re.sub(r'&(?:\w+|#\d+);', '', force_text(value)) strip_entities = allow_lazy(strip_entities, six.text_type) def fix_ampersands(value): """Returns the given HTML with all unencoded ampersands encoded correctly.""" return unencoded_ampersands_re.sub('&amp;', force_text(value)) fix_ampersands = allow_lazy(fix_ampersands, six.text_type) def smart_urlquote(url): "Quotes a URL if it isn't already quoted." # Handle IDN before quoting. scheme, netloc, path, query, fragment = urlsplit(url) try: netloc = netloc.encode('idna').decode('ascii') # IDN -> ACE except UnicodeError: # invalid domain part pass else: url = urlunsplit((scheme, netloc, path, query, fragment)) url = unquote(force_str(url)) # See http://bugs.python.org/issue2637 url = quote(url, safe=b'!*\'();:@&=+$,/?#[]~') return force_text(url) def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): """ Converts any URLs in text into clickable links. Works on http://, https://, www. links, and also on links ending in one of the original seven gTLDs (.com, .edu, .gov, .int, .mil, .net, and .org). Links can have trailing punctuation (periods, commas, close-parens) and leading punctuation (opening parens) and it'll still do the right thing. If trim_url_limit is not None, the URLs in link text longer than this limit will truncated to trim_url_limit-3 characters and appended with an elipsis. If nofollow is True, the URLs in link text will get a rel="nofollow" attribute. If autoescape is True, the link text and URLs will get autoescaped. """ trim_url = lambda x, limit=trim_url_limit: limit is not None and (len(x) > limit and ('%s...' % x[:max(0, limit - 3)])) or x safe_input = isinstance(text, SafeData) words = word_split_re.split(force_text(text)) for i, word in enumerate(words): match = None if '.' in word or '@' in word or ':' in word: # Deal with punctuation. lead, middle, trail = '', word, '' for punctuation in TRAILING_PUNCTUATION: if middle.endswith(punctuation): middle = middle[:-len(punctuation)] trail = punctuation + trail for opening, closing in WRAPPING_PUNCTUATION: if middle.startswith(opening): middle = middle[len(opening):] lead = lead + opening # Keep parentheses at the end only if they're balanced. if (middle.endswith(closing) and middle.count(closing) == middle.count(opening) + 1): middle = middle[:-len(closing)] trail = closing + trail # Make URL we want to point to. url = None nofollow_attr = ' rel="nofollow"' if nofollow else '' if simple_url_re.match(middle): url = smart_urlquote(middle) elif simple_url_2_re.match(middle): url = smart_urlquote('http://%s' % middle) elif not ':' in middle and simple_email_re.match(middle): local, domain = middle.rsplit('@', 1) try: domain = domain.encode('idna').decode('ascii') except UnicodeError: continue url = 'mailto:%s@%s' % (local, domain) nofollow_attr = '' # Make link. if url: trimmed = trim_url(middle) if autoescape and not safe_input: lead, trail = escape(lead), escape(trail) url, trimmed = escape(url), escape(trimmed) middle = '<a href="%s"%s>%s</a>' % (url, nofollow_attr, trimmed) words[i] = mark_safe('%s%s%s' % (lead, middle, trail)) else: if safe_input: words[i] = mark_safe(word) elif autoescape: words[i] = escape(word) elif safe_input: words[i] = mark_safe(word) elif autoescape: words[i] = escape(word) return ''.join(words) urlize = allow_lazy(urlize, six.text_type) def clean_html(text): """ Clean the given HTML. Specifically, do the following: * Convert <b> and <i> to <strong> and <em>. * Encode all ampersands correctly. * Remove all "target" attributes from <a> tags. * Remove extraneous HTML, such as presentational tags that open and immediately close and <br clear="all">. * Convert hard-coded bullets into HTML unordered lists. * Remove stuff like "<p>&nbsp;&nbsp;</p>", but only if it's at the bottom of the text. """ from django.utils.text import normalize_newlines text = normalize_newlines(force_text(text)) text = re.sub(r'<(/?)\s*b\s*>', '<\\1strong>', text) text = re.sub(r'<(/?)\s*i\s*>', '<\\1em>', text) text = fix_ampersands(text) # Remove all target="" attributes from <a> tags. text = link_target_attribute_re.sub('\\1', text) # Trim stupid HTML such as <br clear="all">. text = html_gunk_re.sub('', text) # Convert hard-coded bullets into HTML unordered lists. def replace_p_tags(match): s = match.group().replace('</p>', '</li>') for d in DOTS: s = s.replace('<p>%s' % d, '<li>') return '<ul>\n%s\n</ul>' % s text = hard_coded_bullets_re.sub(replace_p_tags, text) # Remove stuff like "<p>&nbsp;&nbsp;</p>", but only if it's at the bottom # of the text. text = trailing_empty_content_re.sub('', text) return text clean_html = allow_lazy(clean_html, six.text_type)
unknown
codeparrot/codeparrot-clean
"""Getting uniprot txt files for proteins parsing them loading parsed data.""" import os, time, sys import files from collections import defaultdict def parseProteinName(protein): with open(mkTxtFile(protein)) as f: for line in f: # DE RecName: Full=Fatty acid synthase; if line[0:2] == 'DE' and 'RecName' in line: name = line.split(':')[1].split(';')[0].split('=')[1] return name elif line[0:2] == 'DE' and 'SubName' in line: name = line.split(':')[1].split(';')[0].split('=')[1] return name elif line[0:2] == 'GE' and 'Name' in line: name = line.split('Name=')[1].split(';')[0] return name def dumpProteinNames(proteins, nameFile): """ '../working/neal/proteins.names' """ with open(nameFile, 'w') as fout: for protein in proteins: print >> fout, '\t'.join((protein, parseProteinName(protein))) def loadProteinNames(nameFile): protein2name = {} with open(nameFile) as f: for line in f: protein, name = line.strip('\n').split('\t') protein2name[protein] = name return protein2name def mkTxtFile(proteinID): txtFile = files.dataDir + '/uniprot/txt/' + proteinID + '.txt' return txtFile def mkProteinToProsite(proteins): protein2prosite = defaultdict(dict) for protein in proteins: prosites = parseProsite(protein) for prosite in prosites: protein2prosite[protein][prosite] = prosites[prosite] return protein2prosite def parseProsite(protein): prosites = {} with open(mkTxtFile(protein)) as f: for line in f: # DR PROSITE; PS51257; PROKAR_LIPOPROTEIN; 1. # DR GO; GO:0046872; F:metal ion binding; IEA:UniProtKB-KW. if ('GO;' in line or 'PROSITE' in line or 'Pfam' in line or 'SMART' in line) and line[0:2] == 'DR': sp = [x.strip() for x in line.strip('\n').split(';')] prositeID, prositeName = sp[1:3] prosites[prositeID] = prositeName elif line[0:2] == 'KW': # KW NAD; NADP; Oxidoreductase; Phosphopantetheine; Phosphoprotein; sp = [x.strip().strip('.') for x in line.strip('\n').split(';')] for prosite in sp[1:]: if prosite: prosites['KW:'+prosite] = 'KW:' + prosite return prosites def download(proteinID): txtFile = mkTxtFile(proteinID) if not os.path.exists(txtFile): os.system('wget "http://www.uniprot.org/uniprot/%s.txt" -O %s' % (proteinID, txtFile)) time.sleep(2) def getProteins(): proteins = {} with open('../working/neal/proteins.xls') as f: for line in f: mod, proteinLs = line.strip('\n').split('\t') for p in proteinLs.split(';'): proteins[p] = True return proteins def updateTxtFiles(): proteins = getProteins() for p in proteins: download(p) def dumpProsite(proteins, prositeFile): """ '../working/neal/proteins.prosite' """ protein2prosite = mkProteinToProsite(proteins) with open(prositeFile, 'w') as fout: for protein in protein2prosite: for prosite in protein2prosite[protein]: print >> fout, '\t'.join( (protein, prosite, protein2prosite[protein][prosite]) ) def loadProteinToProsite(prositeFile): """ '../working/neal/proteins.prosite' """ protein2prosite = defaultdict(dict) with open(prositeFile) as f: for line in f: protein, prositeID, prositeName = line.strip('\n').split('\t') protein2prosite[protein][prositeID] = prositeName return protein2prosite def loadProteinToGOCC(prositeFile): """ '../working/neal/proteins.prosite' """ protein2prosite = defaultdict(dict) with open(prositeFile) as f: for line in f: protein, prositeID, prositeName = line.strip('\n').split('\t') if 'C:' in prositeName: protein2prosite[protein][prositeID] = prositeName return protein2prosite def loadGoCounts(proteinFile, goFile): """C,P,F counts for experimental proteins per mod '../working/neal/proteins.xls' '../working/neal/proteins.prosite' """ proteins = {'SNO':defaultdict(dict), 'RSG':defaultdict(dict), 'SPAL':defaultdict(dict), 'SOH':defaultdict(dict)} mod2proteins = defaultdict(dict) with open(proteinFile) as f: for line in f: mod, proteinLs = line.strip('\n').split('\t') for p in proteinLs.split(';'): mod2proteins[mod][p] = proteinLs with open(goFile) as f: for line in f: protein, prositeID, prositeName = line.strip('\n').split('\t') goType = prositeName.split(':')[0] if goType in ('C', 'F', 'P'): for mod in mod2proteins: if protein in mod2proteins[mod]: proteins[mod][goType][mod2proteins[mod][protein]] = True return proteins if __name__ == "__main__": dumpProteinNames() # dumpProsite()
unknown
codeparrot/codeparrot-clean
from .base import TestCase import os import mock import shutil import time from django.conf import settings import whisper import gzip from graphite.readers import WhisperReader, GzippedWhisperReader from graphite.wsgi import application # NOQA makes sure we have a working WSGI app class WhisperReadersTests(TestCase): start_ts = 0 # Create/wipe test whisper files hostcpu = os.path.join(settings.WHISPER_DIR, 'hosts/hostname/cpu.wsp') worker1 = hostcpu.replace('hostname', 'worker1') worker2 = hostcpu.replace('hostname', 'worker2') worker3 = hostcpu.replace('hostname', 'worker3') worker4 = hostcpu.replace('hostname', 'worker4') worker4 = worker4.replace('cpu.wsp', 'cpu.wsp.gz') def create_whisper_hosts(self): self.start_ts = int(time.time()) try: os.makedirs(self.worker1.replace('cpu.wsp', '')) os.makedirs(self.worker2.replace('cpu.wsp', '')) os.makedirs(self.worker3.replace('cpu.wsp', '')) os.makedirs(self.worker4.replace('cpu.wsp.gz', '')) except OSError: pass whisper.create(self.worker1, [(1, 60)]) whisper.create(self.worker2, [(1, 60)]) open(self.worker3, 'a').close() whisper.update(self.worker1, 1, self.start_ts) whisper.update(self.worker2, 2, self.start_ts) with open(self.worker1, 'rb') as f_in, gzip.open(self.worker4, 'wb') as f_out: shutil.copyfileobj(f_in, f_out) def wipe_whisper_hosts(self): try: os.remove(self.worker1) os.remove(self.worker2) os.remove(self.worker3) os.remove(self.worker4) shutil.rmtree(os.path.join(settings.WHISPER_DIR, 'hosts')) except OSError: pass # # GzippedWHisper Reader tests # # Confirm the reader object is not none def test_GzippedWhisperReader_init(self): self.create_whisper_hosts() self.addCleanup(self.wipe_whisper_hosts) reader = GzippedWhisperReader(self.worker4, 'hosts.worker4.cpu') self.assertIsNotNone(reader) # Confirm the intervals # Because the intervals returned from Whisper are subsecond, # we truncate to int for this comparison, otherwise it's impossible def test_GzippedWhisperReader_get_intervals(self): self.create_whisper_hosts() self.addCleanup(self.wipe_whisper_hosts) reader = GzippedWhisperReader(self.worker4, 'hosts.worker4.cpu') ts = int(time.time()) intervals = reader.get_intervals() for interval in intervals: self.assertEqual(int(interval.start), ts - 60) self.assertIn(int(interval.end), [ts, ts - 1]) # read it again to validate cache works intervals = reader.get_intervals() for interval in intervals: self.assertEqual(int(interval.start),ts - 60) self.assertIn(int(interval.end), [ts, ts - 1]) # Confirm fetch works. def test_GzippedWhisperReader_fetch(self): self.create_whisper_hosts() self.addCleanup(self.wipe_whisper_hosts) reader = GzippedWhisperReader(self.worker4, 'hosts.worker4.cpu') (_, values) = reader.fetch(self.start_ts-5, self.start_ts) self.assertEqual(values, [None, None, None, None, 1.0]) # # WHisper Reader tests # # Confirm the reader object is not none def test_WhisperReader_init(self): self.create_whisper_hosts() self.addCleanup(self.wipe_whisper_hosts) reader = WhisperReader(self.worker1, 'hosts.worker1.cpu') self.assertIsNotNone(reader) # Confirm the intervals # Because the intervals returned from Whisper are subsecond, # we truncate to int for this comparison, otherwise it's impossible def test_WhisperReader_get_intervals(self): self.create_whisper_hosts() self.addCleanup(self.wipe_whisper_hosts) reader = WhisperReader(self.worker1, 'hosts.worker1.cpu') ts = int(time.time()) intervals = reader.get_intervals() for interval in intervals: self.assertEqual(int(interval.start),ts - 60) self.assertIn(int(interval.end), [ts, ts - 1]) # read it again to validate cache works intervals = reader.get_intervals() for interval in intervals: self.assertEqual(int(interval.start),ts - 60) self.assertIn(int(interval.end), [ts, ts - 1]) # Confirm get_raw_step works def test_WhisperReader_get_raw_step(self): self.create_whisper_hosts() self.addCleanup(self.wipe_whisper_hosts) reader = WhisperReader(self.worker1, 'hosts.worker1.cpu') raw_step = reader.get_raw_step() self.assertEqual(int(raw_step),1) # read it again to validate cache works raw_step = reader.get_raw_step() self.assertEqual(int(raw_step),1) # Confirm fetch works. def test_WhisperReader_fetch(self): self.create_whisper_hosts() self.addCleanup(self.wipe_whisper_hosts) reader = WhisperReader(self.worker1, 'hosts.worker1.cpu') (_, values) = reader.fetch(self.start_ts-5, self.start_ts) self.assertEqual(values, [None, None, None, None, 1.0]) # Whisper Reader broken file @mock.patch('whisper.fetch') def test_WhisperReader_fetch_returns_no_data(self, whisper_fetch): self.create_whisper_hosts() self.addCleanup(self.wipe_whisper_hosts) reader = WhisperReader(self.worker1, 'hosts.worker1.cpu') whisper_fetch.return_value = None self.assertEqual(reader.fetch(self.start_ts-5, self.start_ts), None) # Whisper Reader broken file def test_WhisperReader_broken_file(self): self.create_whisper_hosts() self.addCleanup(self.wipe_whisper_hosts) # Test broken whisper file f = open(self.worker2, 'rb+') f.seek(10) f.write(b'Bad Data') f.close() reader = WhisperReader(self.worker2, 'hosts.worker2.cpu') with self.assertRaises(Exception): reader.fetch(self.start_ts-5, self.start_ts) # Whisper Reader missing file @mock.patch('graphite.logger.log.exception') def test_WhisperReader_missing_file(self, log_exception): path = 'missing/file.wsp' reader = WhisperReader(path, 'hosts.worker2.cpu') self.assertEqual(reader.fetch(self.start_ts-5, self.start_ts), None) log_exception.assert_called_with("Failed fetch of whisper file '%s'" % path) # Whisper Reader CarbonLink Query returns a dict @mock.patch('graphite.carbonlink.CarbonLinkPool.query') def test_WhisperReader_CarbonLinkQuery(self, carbonlink_query): self.create_whisper_hosts() self.addCleanup(self.wipe_whisper_hosts) carbonlink_query.return_value = {} reader = WhisperReader(self.worker1, 'hosts.worker1.cpu') (_, values) = reader.fetch(self.start_ts-5, self.start_ts) self.assertEqual(values, [None, None, None, None, 1.0])
unknown
codeparrot/codeparrot-clean
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # Copyright (C) 2010-2012 OpenERP s.a. (<http://openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import openerp.modules import logging _logger = logging.getLogger(__name__) def is_initialized(cr): """ Check if a database has been initialized for the ORM. The database can be initialized with the 'initialize' function below. """ cr.execute("SELECT relname FROM pg_class WHERE relkind='r' AND relname='ir_module_module'") return len(cr.fetchall()) > 0 def initialize(cr): """ Initialize a database with for the ORM. This executes base/base.sql, creates the ir_module_categories (taken from each module descriptor file), and creates the ir_module_module and ir_model_data entries. """ f = openerp.modules.get_module_resource('base', 'base.sql') if not f: m = "File not found: 'base.sql' (provided by module 'base')." _logger.critical(m) raise IOError(m) base_sql_file = openerp.tools.misc.file_open(f) try: cr.execute(base_sql_file.read()) cr.commit() finally: base_sql_file.close() for i in openerp.modules.get_modules(): mod_path = openerp.modules.get_module_path(i) if not mod_path: continue # This will raise an exception if no/unreadable descriptor file. info = openerp.modules.load_information_from_description_file(i) if not info: continue categories = info['category'].split('/') category_id = create_categories(cr, categories) if info['installable']: state = 'uninstalled' else: state = 'uninstallable' cr.execute('INSERT INTO ir_module_module \ (author, website, name, shortdesc, description, \ category_id, auto_install, state, web, license, application, icon, sequence, summary) \ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) RETURNING id', ( info['author'], info['website'], i, info['name'], info['description'], category_id, info['auto_install'], state, info['web'], info['license'], info['application'], info['icon'], info['sequence'], info['summary'])) id = cr.fetchone()[0] cr.execute('INSERT INTO ir_model_data \ (name,model,module, res_id, noupdate) VALUES (%s,%s,%s,%s,%s)', ( 'module_'+i, 'ir.module.module', 'base', id, True)) dependencies = info['depends'] for d in dependencies: cr.execute('INSERT INTO ir_module_module_dependency \ (module_id,name) VALUES (%s, %s)', (id, d)) # Install recursively all auto-installing modules while True: cr.execute("""SELECT m.name FROM ir_module_module m WHERE m.auto_install AND state != 'to install' AND NOT EXISTS ( SELECT 1 FROM ir_module_module_dependency d JOIN ir_module_module mdep ON (d.name = mdep.name) WHERE d.module_id = m.id AND mdep.state != 'to install' )""") to_auto_install = [x[0] for x in cr.fetchall()] if not to_auto_install: break cr.execute("""UPDATE ir_module_module SET state='to install' WHERE name in %s""", (tuple(to_auto_install),)) cr.commit() def create_categories(cr, categories): """ Create the ir_module_category entries for some categories. categories is a list of strings forming a single category with its parent categories, like ['Grand Parent', 'Parent', 'Child']. Return the database id of the (last) category. """ p_id = None category = [] while categories: category.append(categories[0]) xml_id = 'module_category_' + ('_'.join(map(lambda x: x.lower(), category))).replace('&', 'and').replace(' ', '_') # search via xml_id (because some categories are renamed) cr.execute("SELECT res_id FROM ir_model_data WHERE name=%s AND module=%s AND model=%s", (xml_id, "base", "ir.module.category")) c_id = cr.fetchone() if not c_id: cr.execute('INSERT INTO ir_module_category \ (name, parent_id) \ VALUES (%s, %s) RETURNING id', (categories[0], p_id)) c_id = cr.fetchone()[0] cr.execute('INSERT INTO ir_model_data (module, name, res_id, model) \ VALUES (%s, %s, %s, %s)', ('base', xml_id, c_id, 'ir.module.category')) else: c_id = c_id[0] p_id = c_id categories = categories[1:] return p_id def has_unaccent(cr): """ Test if the database has an unaccent function. The unaccent is supposed to be provided by the PostgreSQL unaccent contrib module but any similar function will be picked by OpenERP. """ cr.execute("SELECT proname FROM pg_proc WHERE proname='unaccent'") return len(cr.fetchall()) > 0 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
unknown
codeparrot/codeparrot-clean
#!/usr/bin/env python """ Convert the X11 locale.alias file into a mapping dictionary suitable for locale.py. Written by Marc-Andre Lemburg <mal@genix.com>, 2004-12-10. """ import locale # Location of the alias file LOCALE_ALIAS = '/usr/lib/X11/locale/locale.alias' def parse(filename): f = open(filename) lines = f.read().splitlines() data = {} for line in lines: line = line.strip() if not line: continue if line[:1] == '#': continue locale, alias = line.split() # Strip ':' if locale[-1] == ':': locale = locale[:-1] # Lower-case locale locale = locale.lower() # Ignore one letter locale mappings (except for 'c') if len(locale) == 1 and locale != 'c': continue # Normalize encoding, if given if '.' in locale: lang, encoding = locale.split('.')[:2] encoding = encoding.replace('-', '') encoding = encoding.replace('_', '') locale = lang + '.' + encoding if encoding.lower() == 'utf8': # Ignore UTF-8 mappings - this encoding should be # available for all locales continue data[locale] = alias return data def pprint(data): items = data.items() items.sort() for k,v in items: print ' %-40s%r,' % ('%r:' % k, v) def print_differences(data, olddata): items = olddata.items() items.sort() for k, v in items: if not data.has_key(k): print '# removed %r' % k elif olddata[k] != data[k]: print '# updated %r -> %r to %r' % \ (k, olddata[k], data[k]) # Additions are not mentioned if __name__ == '__main__': data = locale.locale_alias.copy() data.update(parse(LOCALE_ALIAS)) print_differences(data, locale.locale_alias) print print 'locale_alias = {' pprint(data) print '}'
unknown
codeparrot/codeparrot-clean
from test.support import verbose, run_unittest, import_module, reap_children #Skip these tests if either fcntl or termios is not available fcntl = import_module('fcntl') import_module('termios') import errno import pty import os import sys import select import signal import socket import unittest TEST_STRING_1 = b"I wish to buy a fish license.\n" TEST_STRING_2 = b"For my pet fish, Eric.\n" if verbose: def debug(msg): print(msg) else: def debug(msg): pass def normalize_output(data): # Some operating systems do conversions on newline. We could possibly # fix that by doing the appropriate termios.tcsetattr()s. I couldn't # figure out the right combo on Tru64 and I don't have an IRIX box. # So just normalize the output and doc the problem O/Ses by allowing # certain combinations for some platforms, but avoid allowing other # differences (like extra whitespace, trailing garbage, etc.) # This is about the best we can do without getting some feedback # from someone more knowledgable. # OSF/1 (Tru64) apparently turns \n into \r\r\n. if data.endswith(b'\r\r\n'): return data.replace(b'\r\r\n', b'\n') # IRIX apparently turns \n into \r\n. if data.endswith(b'\r\n'): return data.replace(b'\r\n', b'\n') return data # Marginal testing of pty suite. Cannot do extensive 'do or fail' testing # because pty code is not too portable. # XXX(nnorwitz): these tests leak fds when there is an error. class PtyTest(unittest.TestCase): def setUp(self): # isatty() and close() can hang on some platforms. Set an alarm # before running the test to make sure we don't hang forever. self.old_alarm = signal.signal(signal.SIGALRM, self.handle_sig) signal.alarm(10) def tearDown(self): # remove alarm, restore old alarm handler signal.alarm(0) signal.signal(signal.SIGALRM, self.old_alarm) def handle_sig(self, sig, frame): self.fail("isatty hung") def test_basic(self): try: debug("Calling master_open()") master_fd, slave_name = pty.master_open() debug("Got master_fd '%d', slave_name '%s'" % (master_fd, slave_name)) debug("Calling slave_open(%r)" % (slave_name,)) slave_fd = pty.slave_open(slave_name) debug("Got slave_fd '%d'" % slave_fd) except OSError: # " An optional feature could not be imported " ... ? raise unittest.SkipTest("Pseudo-terminals (seemingly) not functional.") self.assertTrue(os.isatty(slave_fd), 'slave_fd is not a tty') # Solaris requires reading the fd before anything is returned. # My guess is that since we open and close the slave fd # in master_open(), we need to read the EOF. # Ensure the fd is non-blocking in case there's nothing to read. orig_flags = fcntl.fcntl(master_fd, fcntl.F_GETFL) fcntl.fcntl(master_fd, fcntl.F_SETFL, orig_flags | os.O_NONBLOCK) try: s1 = os.read(master_fd, 1024) self.assertEqual(b'', s1) except OSError as e: if e.errno != errno.EAGAIN: raise # Restore the original flags. fcntl.fcntl(master_fd, fcntl.F_SETFL, orig_flags) debug("Writing to slave_fd") os.write(slave_fd, TEST_STRING_1) s1 = os.read(master_fd, 1024) self.assertEqual(b'I wish to buy a fish license.\n', normalize_output(s1)) debug("Writing chunked output") os.write(slave_fd, TEST_STRING_2[:5]) os.write(slave_fd, TEST_STRING_2[5:]) s2 = os.read(master_fd, 1024) self.assertEqual(b'For my pet fish, Eric.\n', normalize_output(s2)) os.close(slave_fd) os.close(master_fd) def test_fork(self): debug("calling pty.fork()") pid, master_fd = pty.fork() if pid == pty.CHILD: # stdout should be connected to a tty. if not os.isatty(1): debug("Child's fd 1 is not a tty?!") os._exit(3) # After pty.fork(), the child should already be a session leader. # (on those systems that have that concept.) debug("In child, calling os.setsid()") try: os.setsid() except OSError: # Good, we already were session leader debug("Good: OSError was raised.") pass except AttributeError: # Have pty, but not setsid()? debug("No setsid() available?") pass except: # We don't want this error to propagate, escaping the call to # os._exit() and causing very peculiar behavior in the calling # regrtest.py ! # Note: could add traceback printing here. debug("An unexpected error was raised.") os._exit(1) else: debug("os.setsid() succeeded! (bad!)") os._exit(2) os._exit(4) else: debug("Waiting for child (%d) to finish." % pid) # In verbose mode, we have to consume the debug output from the # child or the child will block, causing this test to hang in the # parent's waitpid() call. The child blocks after a # platform-dependent amount of data is written to its fd. On # Linux 2.6, it's 4000 bytes and the child won't block, but on OS # X even the small writes in the child above will block it. Also # on Linux, the read() will raise an OSError (input/output error) # when it tries to read past the end of the buffer but the child's # already exited, so catch and discard those exceptions. It's not # worth checking for EIO. while True: try: data = os.read(master_fd, 80) except OSError: break if not data: break sys.stdout.write(str(data.replace(b'\r\n', b'\n'), encoding='ascii')) ##line = os.read(master_fd, 80) ##lines = line.replace('\r\n', '\n').split('\n') ##if False and lines != ['In child, calling os.setsid()', ## 'Good: OSError was raised.', '']: ## raise TestFailed("Unexpected output from child: %r" % line) (pid, status) = os.waitpid(pid, 0) res = status >> 8 debug("Child (%d) exited with status %d (%d)." % (pid, res, status)) if res == 1: self.fail("Child raised an unexpected exception in os.setsid()") elif res == 2: self.fail("pty.fork() failed to make child a session leader.") elif res == 3: self.fail("Child spawned by pty.fork() did not have a tty as stdout") elif res != 4: self.fail("pty.fork() failed for unknown reasons.") ##debug("Reading from master_fd now that the child has exited") ##try: ## s1 = os.read(master_fd, 1024) ##except OSError: ## pass ##else: ## raise TestFailed("Read from master_fd did not raise exception") os.close(master_fd) # pty.fork() passed. class SmallPtyTests(unittest.TestCase): """These tests don't spawn children or hang.""" def setUp(self): self.orig_stdin_fileno = pty.STDIN_FILENO self.orig_stdout_fileno = pty.STDOUT_FILENO self.orig_pty_select = pty.select self.fds = [] # A list of file descriptors to close. self.files = [] self.select_rfds_lengths = [] self.select_rfds_results = [] def tearDown(self): pty.STDIN_FILENO = self.orig_stdin_fileno pty.STDOUT_FILENO = self.orig_stdout_fileno pty.select = self.orig_pty_select for file in self.files: try: file.close() except OSError: pass for fd in self.fds: try: os.close(fd) except OSError: pass def _pipe(self): pipe_fds = os.pipe() self.fds.extend(pipe_fds) return pipe_fds def _socketpair(self): socketpair = socket.socketpair() self.files.extend(socketpair) return socketpair def _mock_select(self, rfds, wfds, xfds): # This will raise IndexError when no more expected calls exist. self.assertEqual(self.select_rfds_lengths.pop(0), len(rfds)) return self.select_rfds_results.pop(0), [], [] def test__copy_to_each(self): """Test the normal data case on both master_fd and stdin.""" read_from_stdout_fd, mock_stdout_fd = self._pipe() pty.STDOUT_FILENO = mock_stdout_fd mock_stdin_fd, write_to_stdin_fd = self._pipe() pty.STDIN_FILENO = mock_stdin_fd socketpair = self._socketpair() masters = [s.fileno() for s in socketpair] # Feed data. Smaller than PIPEBUF. These writes will not block. os.write(masters[1], b'from master') os.write(write_to_stdin_fd, b'from stdin') # Expect two select calls, the last one will cause IndexError pty.select = self._mock_select self.select_rfds_lengths.append(2) self.select_rfds_results.append([mock_stdin_fd, masters[0]]) self.select_rfds_lengths.append(2) with self.assertRaises(IndexError): pty._copy(masters[0]) # Test that the right data went to the right places. rfds = select.select([read_from_stdout_fd, masters[1]], [], [], 0)[0] self.assertEqual([read_from_stdout_fd, masters[1]], rfds) self.assertEqual(os.read(read_from_stdout_fd, 20), b'from master') self.assertEqual(os.read(masters[1], 20), b'from stdin') def test__copy_eof_on_all(self): """Test the empty read EOF case on both master_fd and stdin.""" read_from_stdout_fd, mock_stdout_fd = self._pipe() pty.STDOUT_FILENO = mock_stdout_fd mock_stdin_fd, write_to_stdin_fd = self._pipe() pty.STDIN_FILENO = mock_stdin_fd socketpair = self._socketpair() masters = [s.fileno() for s in socketpair] os.close(masters[1]) socketpair[1].close() os.close(write_to_stdin_fd) # Expect two select calls, the last one will cause IndexError pty.select = self._mock_select self.select_rfds_lengths.append(2) self.select_rfds_results.append([mock_stdin_fd, masters[0]]) # We expect that both fds were removed from the fds list as they # both encountered an EOF before the second select call. self.select_rfds_lengths.append(0) with self.assertRaises(IndexError): pty._copy(masters[0]) def test_main(verbose=None): try: run_unittest(SmallPtyTests, PtyTest) finally: reap_children() if __name__ == "__main__": test_main()
unknown
codeparrot/codeparrot-clean
"""Test the example module auth module.""" from homeassistant import auth, data_entry_flow from homeassistant.auth.mfa_modules import auth_mfa_module_from_config from homeassistant.auth.models import Credentials from tests.common import MockUser async def test_validate(hass): """Test validating pin.""" auth_module = await auth_mfa_module_from_config(hass, { 'type': 'insecure_example', 'data': [{'user_id': 'test-user', 'pin': '123456'}] }) result = await auth_module.async_validate( 'test-user', {'pin': '123456'}) assert result is True result = await auth_module.async_validate( 'test-user', {'pin': 'invalid'}) assert result is False result = await auth_module.async_validate( 'invalid-user', {'pin': '123456'}) assert result is False async def test_setup_user(hass): """Test setup user.""" auth_module = await auth_mfa_module_from_config(hass, { 'type': 'insecure_example', 'data': [] }) await auth_module.async_setup_user( 'test-user', {'pin': '123456'}) assert len(auth_module._data) == 1 result = await auth_module.async_validate( 'test-user', {'pin': '123456'}) assert result is True async def test_depose_user(hass): """Test despose user.""" auth_module = await auth_mfa_module_from_config(hass, { 'type': 'insecure_example', 'data': [{'user_id': 'test-user', 'pin': '123456'}] }) assert len(auth_module._data) == 1 await auth_module.async_depose_user('test-user') assert len(auth_module._data) == 0 async def test_is_user_setup(hass): """Test is user setup.""" auth_module = await auth_mfa_module_from_config(hass, { 'type': 'insecure_example', 'data': [{'user_id': 'test-user', 'pin': '123456'}] }) assert await auth_module.async_is_user_setup('test-user') is True assert await auth_module.async_is_user_setup('invalid-user') is False async def test_login(hass): """Test login flow with auth module.""" hass.auth = await auth.auth_manager_from_config(hass, [{ 'type': 'insecure_example', 'users': [{'username': 'test-user', 'password': 'test-pass'}], }], [{ 'type': 'insecure_example', 'data': [{'user_id': 'mock-user', 'pin': '123456'}] }]) user = MockUser( id='mock-user', is_owner=False, is_active=False, name='Paulus', ).add_to_auth_manager(hass.auth) await hass.auth.async_link_user(user, Credentials( id='mock-id', auth_provider_type='insecure_example', auth_provider_id=None, data={'username': 'test-user'}, is_new=False, )) provider = hass.auth.auth_providers[0] result = await hass.auth.login_flow.async_init( (provider.type, provider.id)) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await hass.auth.login_flow.async_configure( result['flow_id'], { 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await hass.auth.login_flow.async_configure( result['flow_id'], { 'username': 'test-user', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await hass.auth.login_flow.async_configure( result['flow_id'], { 'username': 'test-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['step_id'] == 'mfa' assert result['data_schema'].schema.get('pin') == str result = await hass.auth.login_flow.async_configure( result['flow_id'], {'pin': 'invalid-code'}) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_code' result = await hass.auth.login_flow.async_configure( result['flow_id'], {'pin': '123456'}) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data'].id == 'mock-user' async def test_setup_flow(hass): """Test validating pin.""" auth_module = await auth_mfa_module_from_config(hass, { 'type': 'insecure_example', 'data': [{'user_id': 'test-user', 'pin': '123456'}] }) flow = await auth_module.async_setup_flow('new-user') result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({'pin': 'abcdefg'}) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert auth_module._data[1]['user_id'] == 'new-user' assert auth_module._data[1]['pin'] == 'abcdefg'
unknown
codeparrot/codeparrot-clean
from collections import defaultdict from openerp.tools import mute_logger from openerp.tests import common UID = common.ADMIN_USER_ID class TestORM(common.TransactionCase): """ test special behaviors of ORM CRUD functions TODO: use real Exceptions types instead of Exception """ def setUp(self): super(TestORM, self).setUp() cr, uid = self.cr, self.uid self.partner = self.registry('res.partner') self.users = self.registry('res.users') self.p1 = self.partner.name_create(cr, uid, 'W')[0] self.p2 = self.partner.name_create(cr, uid, 'Y')[0] self.ir_rule = self.registry('ir.rule') # sample unprivileged user employee_gid = self.ref('base.group_user') self.uid2 = self.users.create(cr, uid, {'name': 'test user', 'login': 'test', 'groups_id': [4,employee_gid]}) @mute_logger('openerp.models') def testAccessDeletedRecords(self): """ Verify that accessing deleted records works as expected """ cr, uid, uid2, p1, p2 = self.cr, self.uid, self.uid2, self.p1, self.p2 self.partner.unlink(cr, uid, [p1]) # read() is expected to skip deleted records because our API is not # transactional for a sequence of search()->read() performed from the # client-side... a concurrent deletion could therefore cause spurious # exceptions even when simply opening a list view! # /!\ Using unprileged user to detect former side effects of ir.rules! self.assertEqual([{'id': p2, 'name': 'Y'}], self.partner.read(cr, uid2, [p1,p2], ['name']), "read() should skip deleted records") self.assertEqual([], self.partner.read(cr, uid2, [p1], ['name']), "read() should skip deleted records") # Deleting an already deleted record should be simply ignored self.assertTrue(self.partner.unlink(cr, uid, [p1]), "Re-deleting should be a no-op") # Updating an already deleted record should raise, even as admin with self.assertRaises(Exception): self.partner.write(cr, uid, [p1], {'name': 'foo'}) @mute_logger('openerp.models') def testAccessFilteredRecords(self): """ Verify that accessing filtered records works as expected for non-admin user """ cr, uid, uid2, p1, p2 = self.cr, self.uid, self.uid2, self.p1, self.p2 partner_model = self.registry('ir.model').search(cr, uid, [('model','=','res.partner')])[0] self.ir_rule.create(cr, uid, {'name': 'Y is invisible', 'domain_force': [('id', '!=', p1)], 'model_id': partner_model}) # search as unprivileged user partners = self.partner.search(cr, uid2, []) self.assertFalse(p1 in partners, "W should not be visible...") self.assertTrue(p2 in partners, "... but Y should be visible") # read as unprivileged user with self.assertRaises(Exception): self.partner.read(cr, uid2, [p1], ['name']) # write as unprivileged user with self.assertRaises(Exception): self.partner.write(cr, uid2, [p1], {'name': 'foo'}) # unlink as unprivileged user with self.assertRaises(Exception): self.partner.unlink(cr, uid2, [p1]) # Prepare mixed case self.partner.unlink(cr, uid, [p2]) # read mixed records: some deleted and some filtered with self.assertRaises(Exception): self.partner.read(cr, uid2, [p1,p2], ['name']) # delete mixed records: some deleted and some filtered with self.assertRaises(Exception): self.partner.unlink(cr, uid2, [p1,p2]) def test_multi_read(self): record_id = self.partner.create(self.cr, UID, {'name': 'MyPartner1'}) records = self.partner.read(self.cr, UID, [record_id]) self.assertIsInstance(records, list) def test_one_read(self): record_id = self.partner.create(self.cr, UID, {'name': 'MyPartner1'}) record = self.partner.read(self.cr, UID, record_id) self.assertIsInstance(record, dict) @mute_logger('openerp.models') def test_search_read(self): # simple search_read self.partner.create(self.cr, UID, {'name': 'MyPartner1'}) found = self.partner.search_read(self.cr, UID, [['name', '=', 'MyPartner1']], ['name']) self.assertEqual(len(found), 1) self.assertEqual(found[0]['name'], 'MyPartner1') self.assertTrue('id' in found[0]) # search_read correct order self.partner.create(self.cr, UID, {'name': 'MyPartner2'}) found = self.partner.search_read(self.cr, UID, [['name', 'like', 'MyPartner']], ['name'], order="name") self.assertEqual(len(found), 2) self.assertEqual(found[0]['name'], 'MyPartner1') self.assertEqual(found[1]['name'], 'MyPartner2') found = self.partner.search_read(self.cr, UID, [['name', 'like', 'MyPartner']], ['name'], order="name desc") self.assertEqual(len(found), 2) self.assertEqual(found[0]['name'], 'MyPartner2') self.assertEqual(found[1]['name'], 'MyPartner1') # search_read that finds nothing found = self.partner.search_read(self.cr, UID, [['name', '=', 'Does not exists']], ['name']) self.assertEqual(len(found), 0) def test_exists(self): partner = self.partner.browse(self.cr, UID, []) # check that records obtained from search exist recs = partner.search([]) self.assertTrue(recs) self.assertEqual(recs.exists(), recs) # check that there is no record with id 0 recs = partner.browse([0]) self.assertFalse(recs.exists()) def test_groupby_date(self): partners = dict( A='2012-11-19', B='2012-12-17', C='2012-12-31', D='2013-01-07', E='2013-01-14', F='2013-01-28', G='2013-02-11', ) all_partners = [] partners_by_day = defaultdict(set) partners_by_month = defaultdict(set) partners_by_year = defaultdict(set) for name, date in partners.items(): p = self.partner.create(self.cr, UID, dict(name=name, date=date)) all_partners.append(p) partners_by_day[date].add(p) partners_by_month[date.rsplit('-', 1)[0]].add(p) partners_by_year[date.split('-', 1)[0]].add(p) def read_group(interval, domain=None): main_domain = [('id', 'in', all_partners)] if domain: domain = ['&'] + main_domain + domain else: domain = main_domain rg = self.partner.read_group(self.cr, self.uid, domain, ['date'], 'date' + ':' + interval) result = {} for r in rg: result[r['date:' + interval]] = set(self.partner.search(self.cr, self.uid, r['__domain'])) return result self.assertEqual(len(read_group('day')), len(partners_by_day)) self.assertEqual(len(read_group('month')), len(partners_by_month)) self.assertEqual(len(read_group('year')), len(partners_by_year)) rg = self.partner.read_group(self.cr, self.uid, [('id', 'in', all_partners)], ['date'], ['date:month', 'date:day'], lazy=False) self.assertEqual(len(rg), len(all_partners)) def test_write_duplicate(self): cr, uid, p1 = self.cr, self.uid, self.p1 self.partner.write(cr, uid, [p1, p1], {'name': 'X'}) class TestInherits(common.TransactionCase): """ test the behavior of the orm for models that use _inherits; specifically: res.users, that inherits from res.partner """ def setUp(self): super(TestInherits, self).setUp() self.partner = self.registry('res.partner') self.user = self.registry('res.users') def test_default(self): """ `default_get` cannot return a dictionary or a new id """ defaults = self.user.default_get(self.cr, UID, ['partner_id']) if 'partner_id' in defaults: self.assertIsInstance(defaults['partner_id'], (bool, int, long)) def test_create(self): """ creating a user should automatically create a new partner """ partners_before = self.partner.search(self.cr, UID, []) foo_id = self.user.create(self.cr, UID, {'name': 'Foo', 'login': 'foo', 'password': 'foo'}) foo = self.user.browse(self.cr, UID, foo_id) self.assertNotIn(foo.partner_id.id, partners_before) def test_create_with_ancestor(self): """ creating a user with a specific 'partner_id' should not create a new partner """ par_id = self.partner.create(self.cr, UID, {'name': 'Foo'}) partners_before = self.partner.search(self.cr, UID, []) foo_id = self.user.create(self.cr, UID, {'partner_id': par_id, 'login': 'foo', 'password': 'foo'}) partners_after = self.partner.search(self.cr, UID, []) self.assertEqual(set(partners_before), set(partners_after)) foo = self.user.browse(self.cr, UID, foo_id) self.assertEqual(foo.name, 'Foo') self.assertEqual(foo.partner_id.id, par_id) @mute_logger('openerp.models') def test_read(self): """ inherited fields should be read without any indirection """ foo_id = self.user.create(self.cr, UID, {'name': 'Foo', 'login': 'foo', 'password': 'foo'}) foo_values, = self.user.read(self.cr, UID, [foo_id]) partner_id = foo_values['partner_id'][0] partner_values, = self.partner.read(self.cr, UID, [partner_id]) self.assertEqual(foo_values['name'], partner_values['name']) foo = self.user.browse(self.cr, UID, foo_id) self.assertEqual(foo.name, foo.partner_id.name) @mute_logger('openerp.models') def test_copy(self): """ copying a user should automatically copy its partner, too """ foo_id = self.user.create(self.cr, UID, { 'name': 'Foo', 'login': 'foo', 'password': 'foo', 'supplier': True, }) foo_before, = self.user.read(self.cr, UID, [foo_id]) del foo_before['__last_update'] bar_id = self.user.copy(self.cr, UID, foo_id, { 'login': 'bar', 'password': 'bar', }) foo_after, = self.user.read(self.cr, UID, [foo_id]) del foo_after['__last_update'] self.assertEqual(foo_before, foo_after) foo, bar = self.user.browse(self.cr, UID, [foo_id, bar_id]) self.assertEqual(bar.name, 'Foo (copy)') self.assertEqual(bar.login, 'bar') self.assertEqual(foo.supplier, bar.supplier) self.assertNotEqual(foo.id, bar.id) self.assertNotEqual(foo.partner_id.id, bar.partner_id.id) @mute_logger('openerp.models') def test_copy_with_ancestor(self): """ copying a user with 'parent_id' in defaults should not duplicate the partner """ foo_id = self.user.create(self.cr, UID, {'name': 'Foo', 'login': 'foo', 'password': 'foo', 'login_date': '2016-01-01', 'signature': 'XXX'}) par_id = self.partner.create(self.cr, UID, {'name': 'Bar'}) foo_before, = self.user.read(self.cr, UID, [foo_id]) del foo_before['__last_update'] partners_before = self.partner.search(self.cr, UID, []) bar_id = self.user.copy(self.cr, UID, foo_id, {'partner_id': par_id, 'login': 'bar'}) foo_after, = self.user.read(self.cr, UID, [foo_id]) del foo_after['__last_update'] partners_after = self.partner.search(self.cr, UID, []) self.assertEqual(foo_before, foo_after) self.assertEqual(set(partners_before), set(partners_after)) foo, bar = self.user.browse(self.cr, UID, [foo_id, bar_id]) self.assertNotEqual(foo.id, bar.id) self.assertEqual(bar.partner_id.id, par_id) self.assertEqual(bar.login, 'bar', "login is given from copy parameters") self.assertFalse(bar.login_date, "login_date should not be copied from original record") self.assertEqual(bar.name, 'Bar', "name is given from specific partner") self.assertEqual(bar.signature, foo.signature, "signature should be copied") CREATE = lambda values: (0, False, values) UPDATE = lambda id, values: (1, id, values) DELETE = lambda id: (2, id, False) FORGET = lambda id: (3, id, False) LINK_TO = lambda id: (4, id, False) DELETE_ALL = lambda: (5, False, False) REPLACE_WITH = lambda ids: (6, False, ids) def sorted_by_id(list_of_dicts): "sort dictionaries by their 'id' field; useful for comparisons" return sorted(list_of_dicts, key=lambda d: d.get('id')) class TestO2MSerialization(common.TransactionCase): """ test the orm method 'write' on one2many fields """ def setUp(self): super(TestO2MSerialization, self).setUp() self.partner = self.registry('res.partner') def test_no_command(self): " empty list of commands yields an empty list of records " results = self.partner.resolve_2many_commands( self.cr, UID, 'child_ids', []) self.assertEqual(results, []) def test_CREATE_commands(self): " returns the VALUES dict as-is " values = [{'foo': 'bar'}, {'foo': 'baz'}, {'foo': 'baq'}] results = self.partner.resolve_2many_commands( self.cr, UID, 'child_ids', map(CREATE, values)) self.assertEqual(results, values) def test_LINK_TO_command(self): " reads the records from the database, records are returned with their ids. " ids = [ self.partner.create(self.cr, UID, {'name': 'foo'}), self.partner.create(self.cr, UID, {'name': 'bar'}), self.partner.create(self.cr, UID, {'name': 'baz'}) ] commands = map(LINK_TO, ids) results = self.partner.resolve_2many_commands( self.cr, UID, 'child_ids', commands, ['name']) self.assertEqual(sorted_by_id(results), sorted_by_id([ {'id': ids[0], 'name': 'foo'}, {'id': ids[1], 'name': 'bar'}, {'id': ids[2], 'name': 'baz'} ])) def test_bare_ids_command(self): " same as the equivalent LINK_TO commands " ids = [ self.partner.create(self.cr, UID, {'name': 'foo'}), self.partner.create(self.cr, UID, {'name': 'bar'}), self.partner.create(self.cr, UID, {'name': 'baz'}) ] results = self.partner.resolve_2many_commands( self.cr, UID, 'child_ids', ids, ['name']) self.assertEqual(sorted_by_id(results), sorted_by_id([ {'id': ids[0], 'name': 'foo'}, {'id': ids[1], 'name': 'bar'}, {'id': ids[2], 'name': 'baz'} ])) def test_UPDATE_command(self): " take the in-db records and merge the provided information in " id_foo = self.partner.create(self.cr, UID, {'name': 'foo'}) id_bar = self.partner.create(self.cr, UID, {'name': 'bar'}) id_baz = self.partner.create(self.cr, UID, {'name': 'baz', 'city': 'tag'}) results = self.partner.resolve_2many_commands( self.cr, UID, 'child_ids', [ LINK_TO(id_foo), UPDATE(id_bar, {'name': 'qux', 'city': 'tagtag'}), UPDATE(id_baz, {'name': 'quux'}) ], ['name', 'city']) self.assertEqual(sorted_by_id(results), sorted_by_id([ {'id': id_foo, 'name': 'foo', 'city': False}, {'id': id_bar, 'name': 'qux', 'city': 'tagtag'}, {'id': id_baz, 'name': 'quux', 'city': 'tag'} ])) def test_DELETE_command(self): " deleted records are not returned at all. " ids = [ self.partner.create(self.cr, UID, {'name': 'foo'}), self.partner.create(self.cr, UID, {'name': 'bar'}), self.partner.create(self.cr, UID, {'name': 'baz'}) ] commands = [DELETE(ids[0]), DELETE(ids[1]), DELETE(ids[2])] results = self.partner.resolve_2many_commands( self.cr, UID, 'child_ids', commands, ['name']) self.assertEqual(results, []) def test_mixed_commands(self): ids = [ self.partner.create(self.cr, UID, {'name': name}) for name in ['NObar', 'baz', 'qux', 'NOquux', 'NOcorge', 'garply'] ] results = self.partner.resolve_2many_commands( self.cr, UID, 'child_ids', [ CREATE({'name': 'foo'}), UPDATE(ids[0], {'name': 'bar'}), LINK_TO(ids[1]), DELETE(ids[2]), UPDATE(ids[3], {'name': 'quux',}), UPDATE(ids[4], {'name': 'corge'}), CREATE({'name': 'grault'}), LINK_TO(ids[5]) ], ['name']) self.assertEqual(sorted_by_id(results), sorted_by_id([ {'name': 'foo'}, {'id': ids[0], 'name': 'bar'}, {'id': ids[1], 'name': 'baz'}, {'id': ids[3], 'name': 'quux'}, {'id': ids[4], 'name': 'corge'}, {'name': 'grault'}, {'id': ids[5], 'name': 'garply'} ])) def test_LINK_TO_pairs(self): "LINK_TO commands can be written as pairs, instead of triplets" ids = [ self.partner.create(self.cr, UID, {'name': 'foo'}), self.partner.create(self.cr, UID, {'name': 'bar'}), self.partner.create(self.cr, UID, {'name': 'baz'}) ] commands = map(lambda id: (4, id), ids) results = self.partner.resolve_2many_commands( self.cr, UID, 'child_ids', commands, ['name']) self.assertEqual(sorted_by_id(results), sorted_by_id([ {'id': ids[0], 'name': 'foo'}, {'id': ids[1], 'name': 'bar'}, {'id': ids[2], 'name': 'baz'} ])) def test_singleton_commands(self): "DELETE_ALL can appear as a singleton" results = self.partner.resolve_2many_commands( self.cr, UID, 'child_ids', [DELETE_ALL()], ['name']) self.assertEqual(results, []) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
unknown
codeparrot/codeparrot-clean
# NOTE: This is a common file that is overwritten by realm/ci-actions sync service # and should only be modified in that repository. # syntax - https://github.com/redhat-plumbers-in-action/advanced-issue-labeler#policy # Below keys map from the option used in issue form dropdowns to issue labels # Limitation: # Currently it's not possible to use strings containing ,␣ in the dropdown menus in the issue forms. --- policy: - template: [bug.yml, feature.yml] section: - id: [frequency] label: - name: 'Frequency:Once' keys: ['Once'] - name: 'Frequency:Sometimes' keys: ['Sometimes'] - name: 'Frequency:Always' keys: ['Always'] - id: [repro] label: - name: 'Repro:Always' keys: ['Always'] - name: 'Repro:Sometimes' keys: ['Sometimes'] - name: 'Repro:No' keys: ['No'] - id: [sync, flavour, services] block-list: [] label: - name: 'SDK-Use:Local' keys: ['Local Database only'] - name: 'SDK-Use:Sync' keys: ['Atlas Device Sync'] - name: 'SDK-Use:Services' keys: ['Atlas App Services: Function or GraphQL or DataAPI etc'] - name: ['SDK-Use:All'] keys: ['Both Atlas Device Sync and Atlas App Services'] - id: [encryption] block-list: [] label: - name: 'Encryption:On' keys: ['Yes'] - name: 'Encryption:Off' keys: ['No'] - id: [app-type] block-list: [] label: - name: 'App-type:Unity' keys: ['Unity'] - name: 'App-type:Xamarin' keys: ['Xamarin'] - name: 'App-type:WPF' keys: ['WPF'] - name: 'App-type:Console' keys: ['Console or Server'] - name: 'App-type:Other' keys: ['Other'] - id: [importance] block-list: [] label: - name: 'Importance:Dealbraker' keys: ['Dealbreaker'] - name: 'Importance:Major' keys: ['Would be a major improvement'] - name: 'Importance:Workaround' keys: ['I would like to have it but have a workaround'] - name: 'Importance:Nice' keys: ['Fairly niche but nice to have anyway']
unknown
github
https://github.com/realm/realm-swift
.github/advanced-issue-labeler.yml
# # Author:: Matthew Kent (<mkent@magoazul.com>) # Copyright:: Copyright (c) 2009, 2011 Matthew Kent # License:: Apache License, Version 2.0 # # 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. # # yum-dump.py # Inspired by yumhelper.py by David Lutterkort # # Produce a list of installed, available and re-installable packages using yum # and dump the results to stdout. # # yum-dump invokes yum similarly to the command line interface which makes it # subject to most of the configuration parameters in yum.conf. yum-dump will # also load yum plugins in the same manor as yum - these can affect the output. # # Can be run as non root, but that won't update the cache. # # Intended to support yum 2.x and 3.x import os import sys import time import yum import re import errno from yum import Errors from optparse import OptionParser from distutils import version YUM_PID_FILE='/var/run/yum.pid' YUM_VER = version.StrictVersion(yum.__version__) YUM_MAJOR = YUM_VER.version[0] if YUM_MAJOR > 3 or YUM_MAJOR < 2: print >> sys.stderr, "yum-dump Error: Can't match supported yum version" \ " (%s)" % yum.__version__ sys.exit(1) # Required for Provides output if YUM_MAJOR == 2: import rpm import rpmUtils.miscutils def setup(yb, options): # Only want our output # if YUM_MAJOR == 3: try: if YUM_VER >= version.StrictVersion("3.2.22"): yb.preconf.errorlevel=0 yb.preconf.debuglevel=0 # initialize the config yb.conf else: yb.doConfigSetup(errorlevel=0, debuglevel=0) except yum.Errors.ConfigError, e: # suppresses an ignored exception at exit yb.preconf = None print >> sys.stderr, "yum-dump Config Error: %s" % e return 1 except ValueError, e: yb.preconf = None print >> sys.stderr, "yum-dump Options Error: %s" % e return 1 elif YUM_MAJOR == 2: yb.doConfigSetup() def __log(a,b): pass yb.log = __log yb.errorlog = __log # Give Chef every possible package version, it can decide what to do with them if YUM_MAJOR == 3: yb.conf.showdupesfromrepos = True elif YUM_MAJOR == 2: yb.conf.setConfigOption('showdupesfromrepos', True) # Optionally run only on cached repositories, but non root must use the cache if os.geteuid() != 0: if YUM_MAJOR == 3: yb.conf.cache = True elif YUM_MAJOR == 2: yb.conf.setConfigOption('cache', True) else: if YUM_MAJOR == 3: yb.conf.cache = options.cache elif YUM_MAJOR == 2: yb.conf.setConfigOption('cache', options.cache) # Handle repo toggle via id or glob exactly like yum for opt, repos in options.repo_control: for repo in repos: if opt == '--enablerepo': yb.repos.enableRepo(repo) elif opt == '--disablerepo': yb.repos.disableRepo(repo) return 0 def dump_packages(yb, list, output_provides): packages = {} if YUM_MAJOR == 2: yb.doTsSetup() yb.doRepoSetup() yb.doSackSetup() db = yb.doPackageLists(list) for pkg in db.installed: pkg.type = 'i' packages[str(pkg)] = pkg if YUM_VER >= version.StrictVersion("3.2.21"): for pkg in db.available: pkg.type = 'a' packages[str(pkg)] = pkg # These are both installed and available for pkg in db.reinstall_available: pkg.type = 'r' packages[str(pkg)] = pkg else: # Old style method - no reinstall list for pkg in yb.pkgSack.returnPackages(): if str(pkg) in packages: if packages[str(pkg)].type == "i": packages[str(pkg)].type = 'r' continue pkg.type = 'a' packages[str(pkg)] = pkg unique_packages = packages.values() unique_packages.sort(lambda x, y: cmp(x.name, y.name)) for pkg in unique_packages: if output_provides == "all" or \ (output_provides == "installed" and (pkg.type == "i" or pkg.type == "r")): # yum 2 doesn't have provides_print, implement it ourselves using methods # based on requires gathering in packages.py if YUM_MAJOR == 2: provlist = [] # Installed and available are gathered in different ways if pkg.type == 'i' or pkg.type == 'r': names = pkg.hdr[rpm.RPMTAG_PROVIDENAME] flags = pkg.hdr[rpm.RPMTAG_PROVIDEFLAGS] ver = pkg.hdr[rpm.RPMTAG_PROVIDEVERSION] if names is not None: tmplst = zip(names, flags, ver) for (n, f, v) in tmplst: prov = rpmUtils.miscutils.formatRequire(n, v, f) provlist.append(prov) # This is slow :( elif pkg.type == 'a': for prcoTuple in pkg.returnPrco('provides'): prcostr = pkg.prcoPrintable(prcoTuple) provlist.append(prcostr) provides = provlist else: provides = pkg.provides_print else: provides = "[]" print '%s %s %s %s %s %s %s %s' % ( pkg.name, pkg.epoch, pkg.version, pkg.release, pkg.arch, provides, pkg.type, pkg.repoid ) return 0 def yum_dump(options): lock_obtained = False yb = yum.YumBase() status = setup(yb, options) if status != 0: return status if options.output_options: print "[option installonlypkgs] %s" % " ".join(yb.conf.installonlypkgs) # Non root can't handle locking on rhel/centos 4 if os.geteuid() != 0: return dump_packages(yb, options.package_list, options.output_provides) # Wrap the collection and output of packages in yum's global lock to prevent # any inconsistencies. try: # Spin up to --yum-lock-timeout option countdown = options.yum_lock_timeout while True: try: yb.doLock(YUM_PID_FILE) lock_obtained = True except Errors.LockError, e: time.sleep(1) countdown -= 1 if countdown == 0: print >> sys.stderr, "yum-dump Locking Error! Couldn't obtain an " \ "exclusive yum lock in %d seconds. Giving up." % options.yum_lock_timeout return 200 else: break return dump_packages(yb, options.package_list, options.output_provides) # Ensure we clear the lock and cleanup any resources finally: try: yb.closeRpmDB() if lock_obtained == True: yb.doUnlock(YUM_PID_FILE) except Errors.LockError, e: print >> sys.stderr, "yum-dump Unlock Error: %s" % e return 200 # Preserve order of enable/disable repo args like yum does def gather_repo_opts(option, opt, value, parser): if getattr(parser.values, option.dest, None) is None: setattr(parser.values, option.dest, []) getattr(parser.values, option.dest).append((opt, value.split(','))) def main(): usage = "Usage: %prog [options]\n" + \ "Output a list of installed, available and re-installable packages via yum" parser = OptionParser(usage=usage) parser.add_option("-C", "--cache", action="store_true", dest="cache", default=False, help="run entirely from cache, don't update cache") parser.add_option("-o", "--options", action="store_true", dest="output_options", default=False, help="output select yum options useful to Chef") parser.add_option("-p", "--installed-provides", action="store_const", const="installed", dest="output_provides", default="none", help="output Provides for installed packages, big/wide output") parser.add_option("-P", "--all-provides", action="store_const", const="all", dest="output_provides", default="none", help="output Provides for all package, slow, big/wide output") parser.add_option("-i", "--installed", action="store_const", const="installed", dest="package_list", default="all", help="output only installed packages") parser.add_option("-a", "--available", action="store_const", const="available", dest="package_list", default="all", help="output only available and re-installable packages") parser.add_option("--enablerepo", action="callback", callback=gather_repo_opts, type="string", dest="repo_control", default=[], help="enable disabled repositories by id or glob") parser.add_option("--disablerepo", action="callback", callback=gather_repo_opts, type="string", dest="repo_control", default=[], help="disable repositories by id or glob") parser.add_option("--yum-lock-timeout", action="store", type="int", dest="yum_lock_timeout", default=30, help="Time in seconds to wait for yum process lock") (options, args) = parser.parse_args() try: return yum_dump(options) except yum.Errors.RepoError, e: print >> sys.stderr, "yum-dump Repository Error: %s" % e return 1 except yum.Errors.YumBaseError, e: print >> sys.stderr, "yum-dump General Error: %s" % e return 1 try: status = main() # Suppress a nasty broken pipe error when output is piped to utilities like 'head' except IOError, e: if e.errno == errno.EPIPE: sys.exit(1) else: raise sys.exit(status)
unknown
codeparrot/codeparrot-clean
def maxmin(a, type): if operation == 'max': type = True else: type = False height = len(a) matrix = [[0] * height for row in xrange(height)] for nr_signs in range(height): matrix[nr_signs][nr_signs] = int(a[nr_signs]) for nr_signs in range(1, height): # loop total number of signs needed to put for row in range(0, height - nr_signs): # loop total number of signs per row add = [] mult = [] pos = nr_signs + row # position in row where to put the element for operation in range(nr_signs): # number of operations per row per sign add.append(matrix[row][row + operation] + matrix[row + operation + 1][row + nr_signs]) mult.append(matrix[row][row + operation] * matrix[row + operation + 1][row + nr_signs]) if type: max_mult = max(mult) max_add = max(add) else: max_mult = min(mult) max_add = min(add) if max_mult >= max_add and type: matrix[row][pos] = max_mult elif type: matrix[row][pos] = max_add elif max_mult <= max_add: matrix[row][pos] = max_mult else: matrix[row][pos] = max_add return matrix numbers = [2, 1, 2, 1, 1, 3, 6, 10, 1, 2, 2, 1, 6, 1, 2, 2, 1, 7, 2, 1, 1, 3, 2, 1, 5, 1, 7, 2, 1, 2, 1, 2, 1, 2, 3, 1, 4, 4, 5, 2, 1, 2, 2, 2, 1, 1, 1, 2, 3] result_max = maxmin(numbers, "max") print('Max: ' + str(result_max[0][-1])) result_min = maxmin(numbers, "min") print('Min: ' + str(result_min[0][-1]))
unknown
codeparrot/codeparrot-clean
// Copyright 2022 The etcd Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in 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. //go:build integration package common import ( "go.etcd.io/etcd/tests/v3/framework" "go.etcd.io/etcd/tests/v3/framework/config" "go.etcd.io/etcd/tests/v3/framework/integration" ) func init() { testRunner = framework.IntegrationTestRunner clusterTestCases = integrationClusterTestCases } func integrationClusterTestCases() []testCase { return []testCase{ { name: "NoTLS", config: config.ClusterConfig{ClusterSize: 1}, }, { name: "PeerTLS and ClientTLS", config: config.ClusterConfig{ClusterSize: 3, PeerTLS: config.ManualTLS, ClientTLS: config.ManualTLS}, }, { name: "PeerAutoTLS and ClientAutoTLS", config: config.ClusterConfig{ClusterSize: 3, PeerTLS: config.AutoTLS, ClientTLS: config.AutoTLS}, }, } } func WithAuth(userName, password string) config.ClientOption { return integration.WithAuth(userName, password) } func WithAuthToken(token string) config.ClientOption { return integration.WithAuthToken(token) } func WithEndpoints(endpoints []string) config.ClientOption { return integration.WithEndpoints(endpoints) } func WithHTTP2Debug() config.ClusterOption { return integration.WithHTTP2Debug() } func WithUnixClient() config.ClusterOption { return integration.WithUnixClient() } func WithTCPClient() config.ClusterOption { return integration.WithTCPClient() }
go
github
https://github.com/etcd-io/etcd
tests/common/integration_test.go
['../evaluation_tmp.py', '10000'] mnist classes = 2 size: 10000 (2609,) (7391,) data size: 10000, nu: 0.2, gamma: 1 ============ 1. Fold of CV ============ 1) Incremental OCSVM 0 data points processed 1000 data points processed 2000 data points processed 3000 data points processed 4000 data points processed 5000 data points processed 6000 data points processed None Confusion matrix: Prediction -1 1 Target -1 2085 524 1 5915 1476 precision: 0.738, recall: 0.199702340685, f1-score: 0.314343520392 Number of support vectors: 8000 ----------- 2) cvxopt-OCSVM Confusion matrix: Prediction 1 Target -1 2609 1 7391 precision: 0.7391, recall: 1.0, f1-score: 0.849979874648 Number of support vectors: 8000 --------- 3) sklearn-OCSVM Confusion matrix: Prediction -1 1 Target -1 1677 932 1 4723 2668 Number of support vectors: 8000 precision: 0.741111111111, recall: 0.360979569747, f1-score: 0.485488126649 Wrote profile results to evaluation_tmp.py.lprof Timer unit: 1e-06 s Total time: 4446.27 s File: ../ocsvm.py Function: increment at line 97 Line # Hits Time Per Hit % Time Line Contents ============================================================== 97 @profile 98 def increment(self, Xc, init_ac=0, break_count=-1): 99 100 # epsilon 101 1 6 6.0 0.0 e = self._data._e 102 1 3 3.0 0.0 mu = 0 103 1 3 3.0 0.0 imin = None 104 105 # initialize existing X, coefficients a, C 106 1 7 7.0 0.0 X_origin = self._data.X() 107 1 6 6.0 0.0 K_X_origin = self._data.K_X() 108 1 6 6.0 0.0 n_data = X_origin.shape[0] 109 1 3 3.0 0.0 n_feature = X_origin.shape[1] 110 111 1 6 6.0 0.0 C = self._data.C() 112 1 6 6.0 0.0 a_origin = self._data.alpha() 113 114 # number of new incremental points 115 1 3 3.0 0.0 n_new = Xc.shape[0] 116 117 # number of all (new and existing) points 118 1 4 4.0 0.0 n_all = n_data + n_new 119 120 # concatenate all new points with all existing points 121 1 21 21.0 0.0 X = empty((n_new + n_data, n_feature)) 122 1 31954 31954.0 0.0 X[0:n_new, :] = Xc 123 1 8589 8589.0 0.0 X[n_new:, :] = X_origin 124 125 # create kernel matrix for all new and existing points 126 127 # create of all data points 128 1 8 8.0 0.0 if K_X_origin == None: 129 1 10559662 10559662.0 0.2 K_X = self.gram(X) 130 else: 131 K_X = empty((n_all, n_all)) 132 K_X[n_new:, n_new:] = K_X_origin 133 K_X_new = self.gram(Xc, X_origin) 134 K_X[0:n_new, :] = K_X_new 135 K_X[:, 0:n_new] = K_X_new.T 136 137 # creating coefficient vector alpha for all data points 138 1 28 28.0 0.0 a = empty(n_all) 139 1 19 19.0 0.0 a[n_new:] = a_origin 140 1 25 25.0 0.0 a[:n_new] = init_ac 141 142 # creating gradient vector 143 1 26 26.0 0.0 g = zeros(n_all) 144 145 # create sensitivity vector 146 1 7 7.0 0.0 gamma = empty(n_all) 147 1 4 4.0 0.0 check_gradient = False 148 # loop through all new points to increment 149 6316 34329 5.4 0.0 for x_count in range(n_new): 150 6315 34922 5.5 0.0 if x_count % 1000 == 0: 151 7 128 18.3 0.0 print "%s data points processed" % x_count 152 #print "--------- START %s ---------" % x_count 153 154 6315 25174 4.0 0.0 if x_count == break_count: 155 self._data.set_X(X) 156 self._data.set_alpha(a) 157 self._data.set_C(C) 158 self._data.set_K_X(K_X) 159 self.rho() 160 return False 161 162 # initialize X, a, C, g, indices, kernel values 163 6315 28553 4.5 0.0 start_origin = n_new - x_count 164 6315 23484 3.7 0.0 start_new = start_origin - 1 165 166 6315 22499 3.6 0.0 if x_count == 0: 167 1 4 4.0 0.0 inds = [] 168 1 4 4.0 0.0 indr = [] 169 1 3 3.0 0.0 inde = [] 170 1 4 4.0 0.0 indo = [] 171 1686 6578 3.9 0.0 for i in range(n_new, n_all): 172 1685 9710 5.8 0.0 if e < a[i] < C - e: 173 1685 7113 4.2 0.0 inds.append(i) 174 else: 175 indr.append(i) 176 if a[i] <= e: 177 indo.append(i) 178 else: 179 inde.append(i) 180 181 1 6 6.0 0.0 ls = len(inds) # support vectors length 182 1 4 4.0 0.0 lr = len(indr) # error and non-support vectors length 183 1 4 4.0 0.0 le = len(inde) # error vectors lenght 184 1 4 4.0 0.0 lo = len(indo) 185 #mu_old = mu 186 1 170 170.0 0.0 mu = - K_X[inds[0], :][start_origin:].dot(a[start_origin:]) 187 1 4 4.0 0.0 if lr > 0: 188 g[indr] = K_X[indr, :][:, start_origin:].dot(a[start_origin:]) + mu 189 # calculate mu according to KKT-conditions 190 191 192 6315 930130 147.3 0.0 c_inds = [start_new] + inds 193 194 # kernel of support vectors 195 #Kss = K_X[:, inds][inds, :] 196 #print "difference indo: %s" % unique(round(K_X[indo, :][:, start_origin:].dot(a[start_origin:]) + mu - g[indo],6)) 197 #check_gradient = True 198 #if check_gradient: 199 #g[indr] = K_X[indr, :][:, start_origin:].dot(a[start_origin:]) + mu 200 #g[indo] += K_X[indo[0], :][start_origin:].dot(a[start_origin:]) + mu - g[indo[0]] 201 #check_gradient = False 202 #print "difference indo: %s" % unique(round(K_X[indo, :][:, start_origin:].dot(a[start_origin:]) + mu - g[indo],6)) 203 6315 28325 4.5 0.0 if ls > 0: 204 6315 2500668 396.0 0.1 gc = K_X[start_new, start_origin:].dot(a[start_origin:]) + mu 205 206 6315 31463 5.0 0.0 ac = a[start_new] 207 208 6315 23865 3.8 0.0 if x_count == 0: 209 1 5438 5438.0 0.0 Q = ones((ls+1, ls+1)) 210 1 10 10.0 0.0 Q[0, 0] = 0 211 #Kss = self.gram(X[inds]) 212 1686 7977 4.7 0.0 inds_row = [[i] for i in inds] 213 1 371349 371349.0 0.0 Q[1:, 1:] = K_X[inds_row, inds] 214 1 6 6.0 0.0 try: 215 1 1887830 1887830.0 0.0 R = inv(Q) 216 except np.linalg.linalg.LinAlgError: 217 x = 1e-11 218 found = False 219 print "singular matrix" 220 while not found: 221 try: 222 R = inv(Q + diag(ones(ls+1) * x)) 223 found = True 224 except np.linalg.linalg.LinAlgError: 225 x = x*10 226 6315 24024 3.8 0.0 loop_count = 1 227 #print "gc: %s, ac: %s" % (gc, ac) 228 6315 96477 15.3 0.0 while gc < e and ac < C - e: 229 6315 24173 3.8 0.0 if ls == 0: check_gradient = True 230 #print "-------------------- incremental %s-%s ---------" % (x_count, loop_count) 231 232 6315 24031 3.8 0.0 if ls > 0: 233 6315 7278480 1152.6 0.2 n = K_X[start_new, :][c_inds] 234 6315 276420874 43772.1 6.2 beta = - R.dot(n) 235 6315 70854 11.2 0.0 betas = beta[1:] 236 237 # calculate gamma 238 6315 30666 4.9 0.0 if lr > 0 and ls > 0: 239 gamma_tmp = K_X[:, c_inds][start_new:] 240 gamma_tmp[:, 0] = 1 241 gamma[start_new:] = gamma_tmp.dot(beta) + K_X[start_new, :][start_new:] 242 gammac = gamma[start_new] 243 244 6315 26280 4.2 0.0 elif ls > 0: 245 # empty R set 246 6315 11314559 1791.7 0.3 gammac = K_X[start_new, :][c_inds].dot(beta) + 1 247 248 else: 249 # empty S set 250 gammac = 1 251 gamma[indr] = 1 252 #gamma[indo] = -1 253 254 # accounting 255 #case 1: Some alpha_i in S reaches a bound 256 6315 28753 4.6 0.0 if ls > 0: 257 6315 171869 27.2 0.0 IS_plus = betas > e 258 6315 115733 18.3 0.0 IS_minus = betas < - e 259 6315 297828 47.2 0.0 gsmax = ones(ls)*inf 260 #if np.isnan(np.min(gsmax)): 261 # gsmax = ones(ls)*inf 262 6315 6462461 1023.4 0.1 gsmax[IS_plus] = -a[inds][IS_plus] + C 263 6315 6554085 1037.9 0.1 gsmax[IS_minus] = - a[inds][IS_minus] 264 #gsmax[IS_plus] = -a[inds][IS_plus] 265 #gsmax[IS_plus] += C 266 #gsmax[IS_minus] = - a[inds][IS_minus] 267 6315 284358 45.0 0.0 gsmax = divide(gsmax, betas) 268 6315 4342393 687.6 0.1 gsmin = min(absolute(gsmax)) 269 #print where(absolute(gsmax) == gsmin) 270 6315 459013 72.7 0.0 ismin = where(absolute(gsmax) == gsmin)[0][0] 271 272 else: gsmin = inf 273 274 #case 2: Some g_i in E reaches zero 275 6315 27912 4.4 0.0 if le > 0: 276 277 gamma_inde = gamma[inde] 278 g_inde = g[inde] 279 Ie_plus = gamma_inde > e 280 281 if len(g_inde[Ie_plus]) > 0: 282 gec = divide(-g_inde[Ie_plus], gamma_inde[Ie_plus]) 283 gec[gec <= 0] = inf 284 gemin = min(gec) 285 if gemin < inf: 286 iemin = where(gec == gemin)[0][0] 287 else: gemin = inf 288 6315 27717 4.4 0.0 else: gemin = inf 289 #case 2: Some g_i in O reaches zero 290 6315 26844 4.3 0.0 if lo > 0 and ls > 0: 291 gamma_indo = gamma[indo] 292 g_indo = g[indo] 293 Io_minus = gamma_indo < - e 294 if len(g_indo[Io_minus]) > 0: 295 goc = divide(-g_indo[Io_minus], gamma_indo[Io_minus]) 296 goc[goc <= 0] = inf 297 goc[g_indo[Io_minus] < 0] = inf 298 gomin = min(goc) 299 if gomin < inf: 300 iomin = where(goc == gomin)[0][0] 301 else: gomin = inf 302 6315 26472 4.2 0.0 else: gomin = inf 303 304 # case 3: gc becomes zero 305 6315 52912 8.4 0.0 if gammac > e: gcmin = - gc/gammac 306 else: gcmin = inf 307 308 # case 4 309 6315 39095 6.2 0.0 if ls > 0: gacmin = C - ac 310 else: gacmin = inf 311 312 # determine minimum largest increment 313 6315 37991 6.0 0.0 all_deltas = [gsmin, gemin, gomin, gcmin, gacmin] 314 6315 51044 8.1 0.0 gmin = min(all_deltas) 315 6315 151241 23.9 0.0 imin = where(all_deltas == gmin)[0][0] 316 # update a, g 317 6315 28142 4.5 0.0 if ls > 0: 318 6315 40268 6.4 0.0 mu += beta[0]*gmin 319 6315 29448 4.7 0.0 ac += gmin 320 6315 11957014 1893.4 0.3 a[inds] += betas*gmin 321 else: 322 mu += gmin 323 6315 31456 5.0 0.0 if lr > 0: 324 g[indr] += gamma[indr] * gmin 325 6315 35200 5.6 0.0 gc += gammac * gmin 326 6315 44916 7.1 0.0 if imin == 0: # min = gsmin => move k from s to r 327 # if there are more than 1 minimum, just take 1 328 ak = a[inds][ismin] 329 330 # delete the elements from X,a and g 331 # => add it to the end of X,a,g 332 ind_del = inds[ismin] 333 inds.remove(ind_del) 334 c_inds = [start_new] + inds 335 indr.append(ind_del) 336 if ak < e: 337 indo.append(ind_del) 338 lo += 1 339 else: 340 inde.append(ind_del) 341 le += 1 342 343 lr += 1 344 #decrement R, delete row ismin and column ismin 345 346 if ls > 2: 347 ismin += 1 348 R_new = zeros((ls,ls)) 349 R_new[0:ismin, 0:ismin] = R[0:ismin, 0:ismin] 350 R_new[ismin:, 0:ismin] = R[ismin+1:,0:ismin] 351 R_new[0:ismin, ismin:] = R[0:ismin, ismin+1:] 352 R_new[ismin:, ismin:] = R[ismin+1:, ismin+1:] 353 betak = zeros(ls) 354 betak[:ismin] = R[ismin, :ismin] 355 betak[ismin:] = R[ismin, ismin+1:] 356 R_new -= outer(betak, betak)/R[ismin,ismin] 357 R = R_new 358 elif ls == 2: 359 R = ones((2, 2)) 360 R[1,1] = 0 361 R[0,0] = -1 362 else: 363 R = inf 364 ls -= 1 365 366 6315 33341 5.3 0.0 elif imin == 1: 367 # delete the elements from X,a and g => add it to the end of X,a,g 368 ### old version find index to delete 369 #Ieplus_l = [i for i,b in enumerate(Ie_plus) if b] 370 #ind_del = inde[Ieplus_l[iemin]] 371 ### old version find index to delete 372 ind_del = np.asarray(inde)[Ie_plus][iemin] 373 if ls > 0: 374 nk = K_X[ind_del, :][[ind_del] + inds] 375 betak = - R.dot(nk) 376 betak1 = ones(ls + 2) 377 betak1[:-1] = betak 378 R_old = R 379 R = 1/k * outer(betak1, betak1) 380 R[:-1,:-1] += R_old 381 else: 382 R = ones((2, 2)) 383 R[1,1] = 0 384 R[0,0] = -1 385 inds.append(ind_del) 386 c_inds = [start_new] + inds 387 indr.remove(ind_del) 388 inde.remove(ind_del) 389 ls += 1 390 lr -= 1 391 le -= 1 392 393 6315 32065 5.1 0.0 elif imin == 2: # min = gemin | gomin => move k from r to s 394 395 # delete the elements from X,a and g => add it to the end of X,a,g 396 397 ### old version find index to delete 398 #Io_minus_l = [i for i,b in enumerate(Io_minus) if b] 399 #ind_del = indo[Io_minus_l[iomin]] 400 ### old version find index to delete 401 ind_del = np.asarray(indo)[Io_minus][iomin] 402 if ls > 0: 403 nk = ones(ls+1) 404 nk[1:] = K_X[ind_del,:][inds] 405 betak = - R.dot(nk) 406 k = 1 - nk.dot(R).dot(nk) 407 betak1 = ones(ls+2) 408 betak1[:-1] = betak 409 R_old = R 410 R = 1/k * outer(betak1, betak1) 411 R[:-1,:-1] += R_old 412 else: 413 R = ones((2, 2)) 414 R[1,1] = 0 415 R[0,0] = -1 416 417 indo.remove(ind_del) 418 indr.remove(ind_del) 419 inds.append(ind_del) 420 c_inds = [start_new] + inds 421 lo -= 1 422 lr -= 1 423 ls += 1 424 6315 32323 5.1 0.0 elif imin == 3: 425 ''' 426 if ls > 0: 427 nk = ones(ls+1) 428 nk[1:] = K_X[start_new, :][inds] 429 betak = - R.dot(nk) 430 k = 1 - nk.dot(R).dot(nk) 431 betak1 = ones(ls + 2) 432 betak1[:-1] = betak 433 R_old = R 434 R = zeros((ls +2, ls +2)) 435 R[:-1,:-1] = R_old 436 R += 1/k * outer(betak1, betak1) 437 else: 438 R = ones((2, 2)) 439 R[1,1] = 0 440 R[0,0] = -1 441 ''' 442 6315 28391 4.5 0.0 break 443 else: 444 break 445 loop_count += 1 446 447 6315 31180 4.9 0.0 a[start_new] = ac 448 6315 31385 5.0 0.0 g[start_new] = gc 449 6315 34513 5.5 0.0 if ac < e: 450 indr.append(start_new) 451 indo.append(start_new) 452 lr += 1 453 lo += 1 454 6315 39033 6.2 0.0 elif ac > C - e: 455 indr.append(start_new) 456 inde.append(start_new) 457 lr += 1 458 le += 1 459 else: 460 6315 45526 7.2 0.0 inds.append(start_new) 461 6315 29069 4.6 0.0 g[start_new] = 0 462 6315 37538 5.9 0.0 if len(inds) == 1: 463 R = ones((2, 2)) 464 R[1,1] = 0 465 R[0,0] = -1 466 else: 467 6315 43113 6.8 0.0 if R.shape[0] != len(inds) + 1: 468 6315 127707 20.2 0.0 nk = ones(ls+1) 469 6315 7318330 1158.9 0.2 nk[1:] = K_X[start_new, :][inds[:-1]] 470 6315 276033663 43710.8 6.2 betak = - R.dot(nk) 471 6315 949917 150.4 0.0 k = 1 - nk.dot(R).dot(nk) 472 6315 221603 35.1 0.0 betak1 = ones(ls + 2) 473 6315 96065 15.2 0.0 betak1[:-1] = betak 474 6315 82876318 13123.7 1.9 R_old = R 475 6315 2616448189 414322.8 58.8 R = 1/k * outer(betak1, betak1) 476 6315 1114393414 176467.7 25.1 R[:-1,:-1] += R_old 477 478 6315 56172 8.9 0.0 ls += 1 479 # update X, a 480 1 27 27.0 0.0 self._data.set_X(X) 481 1 9 9.0 0.0 self._data.set_alpha(a) 482 1 9 9.0 0.0 self._data.set_C(C) 483 1 10 10.0 0.0 self._data.set_K_X(K_X) 484 1 4118987 4118987.0 0.1 print self.rho() *** PROFILER RESULTS *** incremental_ocsvm (../evaluation_tmp.py:185) function called 1 times 186226 function calls in 4458.908 seconds Ordered by: cumulative time, internal time, call count List reduced from 149 to 40 due to restriction <40> ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 4458.908 4458.908 evaluation_tmp.py:185(incremental_ocsvm) 1 0.062 0.062 4448.712 4448.712 line_profiler.py:95(wrapper) 1 2499.493 2499.493 4448.650 4448.650 ocsvm.py:97(increment) 6315 1372.956 0.217 1373.067 0.217 numeric.py:740(outer) 37892 554.850 0.015 554.850 0.015 {method 'dot' of 'numpy.ndarray' objects} 2 0.000 0.000 11.064 5.532 ocsvm.py:58(gram) 2 0.000 0.000 11.064 5.532 pairwise.py:1164(pairwise_kernels) 2 0.000 0.000 11.064 5.532 pairwise.py:949(_parallel_pairwise) 2 2.008 1.004 11.064 5.532 pairwise.py:740(rbf_kernel) 1 0.013 0.013 10.196 10.196 ocsvm.py:35(fit) 1 0.386 0.386 10.183 10.183 ocsvm.py:62(alpha) 1 0.003 0.003 9.108 9.108 coneprog.py:4159(qp) 1 0.005 0.005 9.104 9.104 coneprog.py:1441(coneqp) 2 0.890 0.445 9.029 4.515 pairwise.py:136(euclidean_distances) 5 0.000 0.000 8.759 1.752 coneprog.py:1984(kktsolver) 5 0.120 0.024 8.759 1.752 misc.py:1389(factor) 2 0.000 0.000 8.112 4.056 extmath.py:171(safe_sparse_dot) 2 0.000 0.000 8.112 4.056 extmath.py:129(fast_dot) 2 7.718 3.859 8.112 4.056 extmath.py:97(_fast_dot) 5 6.097 1.219 6.097 1.219 {cvxopt.base.syrk} 12647 4.239 0.000 4.239 0.000 {min} 1 3.809 3.809 4.074 4.074 ocsvm.py:45(rho) 1 0.000 0.000 1.888 1.888 linalg.py:404(inv) 1 0.000 0.000 1.883 1.883 linalg.py:244(solve) 1 1.740 1.740 1.740 1.740 {numpy.linalg.lapack_lite.dgesv} 5 1.316 0.263 1.316 0.263 {cvxopt.base.gemm} 10 1.191 0.119 1.191 0.119 {cvxopt.lapack.potrf} 8 0.000 0.000 0.438 0.055 validation.py:268(check_array) 8 0.000 0.000 0.429 0.054 validation.py:43(_assert_all_finite) 8 0.428 0.054 0.428 0.054 {method 'sum' of 'numpy.ndarray' objects} 4 0.000 0.000 0.394 0.099 extmath.py:87(_impose_f_order) 18950 0.115 0.000 0.369 0.000 numeric.py:1791(ones) 56 0.255 0.005 0.255 0.005 {cvxopt.base.gemv} 9 0.000 0.000 0.222 0.025 misc.py:1489(solve) 12630 0.210 0.000 0.210 0.000 {numpy.core.multiarray.where} 8 0.000 0.000 0.199 0.025 coneprog.py:2333(f4) 8 0.000 0.000 0.198 0.025 coneprog.py:2291(f4_no_ir) 2 0.000 0.000 0.160 0.080 shape_base.py:177(vstack) 2 0.158 0.079 0.158 0.079 {numpy.core.multiarray.concatenate} 1 0.157 0.157 0.158 0.158 data.py:29(Xs) *** PROFILER RESULTS *** cvxopt_ocsvm (../evaluation_tmp.py:181) function called 1 times 1399 function calls in 851.843 seconds Ordered by: cumulative time, internal time, call count List reduced from 123 to 40 due to restriction <40> ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 851.843 851.843 evaluation_tmp.py:181(cvxopt_ocsvm) 1 0.215 0.215 851.843 851.843 ocsvm.py:35(fit) 1 13.610 13.610 836.090 836.090 ocsvm.py:62(alpha) 1 0.085 0.085 805.091 805.091 coneprog.py:4159(qp) 1 0.009 0.009 805.006 805.006 coneprog.py:1441(coneqp) 5 0.000 0.000 797.632 159.526 coneprog.py:1984(kktsolver) 5 2.340 0.468 797.632 159.526 misc.py:1389(factor) 5 630.443 126.089 630.443 126.089 {cvxopt.base.syrk} 10 110.158 11.016 110.158 11.016 {cvxopt.lapack.potrf} 5 53.899 10.780 53.899 10.780 {cvxopt.base.gemm} 2 0.000 0.000 25.810 12.905 ocsvm.py:58(gram) 2 0.000 0.000 25.810 12.905 pairwise.py:1164(pairwise_kernels) 2 0.012 0.006 25.810 12.905 pairwise.py:949(_parallel_pairwise) 2 3.824 1.912 25.798 12.899 pairwise.py:740(rbf_kernel) 2 1.760 0.880 21.800 10.900 pairwise.py:136(euclidean_distances) 2 0.000 0.000 19.970 9.985 extmath.py:171(safe_sparse_dot) 2 0.000 0.000 19.970 9.985 extmath.py:129(fast_dot) 2 19.296 9.648 19.970 9.985 extmath.py:97(_fast_dot) 1 0.000 0.000 15.538 15.538 ocsvm.py:45(rho) 2 0.000 0.000 5.915 2.957 shape_base.py:177(vstack) 2 5.914 2.957 5.914 2.957 {numpy.core.multiarray.concatenate} 56 5.881 0.105 5.881 0.105 {cvxopt.base.gemv} 9 0.001 0.000 4.780 0.531 misc.py:1489(solve) 8 0.000 0.000 4.241 0.530 coneprog.py:2333(f4) 8 0.000 0.000 4.241 0.530 coneprog.py:2291(f4_no_ir) 10 0.000 0.000 2.122 0.212 coneprog.py:1900(fG) 10 0.000 0.000 2.122 0.212 misc.py:801(sgemv) 18 1.019 0.057 1.019 0.057 {cvxopt.blas.trsv} 10 0.000 0.000 0.893 0.089 validation.py:268(check_array) 2 0.001 0.001 0.841 0.420 twodim_base.py:220(diag) 4 0.840 0.210 0.840 0.210 {numpy.core.multiarray.zeros} 5 0.780 0.156 0.780 0.156 {cvxopt.blas.trsm} 10 0.000 0.000 0.763 0.076 validation.py:43(_assert_all_finite) 10 0.762 0.076 0.762 0.076 {method 'sum' of 'numpy.ndarray' objects} 4 0.000 0.000 0.674 0.168 extmath.py:87(_impose_f_order) 5 0.000 0.000 0.432 0.086 coneprog.py:1847(fP) 5 0.432 0.086 0.432 0.086 {cvxopt.base.symv} 2 0.256 0.128 0.257 0.129 data.py:29(Xs) 4 0.000 0.000 0.219 0.055 pairwise.py:57(check_pairwise_arrays) 39 0.130 0.003 0.130 0.003 {numpy.core.multiarray.array} *** PROFILER RESULTS *** sklearn_ocsvm (../evaluation_tmp.py:177) function called 1 times 61 function calls in 437.500 seconds Ordered by: cumulative time, internal time, call count ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 437.500 437.500 evaluation_tmp.py:177(sklearn_ocsvm) 1 0.004 0.004 437.500 437.500 classes.py:941(fit) 1 0.000 0.000 437.496 437.496 base.py:99(fit) 1 0.000 0.000 437.436 437.436 base.py:211(_dense_fit) 1 437.436 437.436 437.436 437.436 {sklearn.svm.libsvm.fit} 1 0.000 0.000 0.059 0.059 validation.py:268(check_array) 5 0.044 0.009 0.044 0.009 {numpy.core.multiarray.array} 1 0.000 0.000 0.015 0.015 validation.py:43(_assert_all_finite) 1 0.015 0.015 0.015 0.015 {method 'sum' of 'numpy.ndarray' objects} 1 0.000 0.000 0.000 0.000 base.py:193(_validate_targets) 1 0.000 0.000 0.000 0.000 validation.py:126(_shape_repr) 2 0.000 0.000 0.000 0.000 numeric.py:167(asarray) 1 0.000 0.000 0.000 0.000 numeric.py:1791(ones) 1 0.000 0.000 0.000 0.000 {method 'join' of 'str' objects} 2 0.000 0.000 0.000 0.000 base.py:553(isspmatrix) 1 0.000 0.000 0.000 0.000 {method 'fill' of 'numpy.ndarray' objects} 2 0.000 0.000 0.000 0.000 sputils.py:116(_isinstance) 2 0.000 0.000 0.000 0.000 numeric.py:237(asanyarray) 3 0.000 0.000 0.000 0.000 validation.py:153(<genexpr>) 1 0.000 0.000 0.000 0.000 getlimits.py:234(__init__) 2 0.000 0.000 0.000 0.000 {numpy.core.multiarray.empty} 1 0.000 0.000 0.000 0.000 validation.py:105(_num_samples) 1 0.000 0.000 0.000 0.000 {sklearn.svm.libsvm.set_verbosity_wrap} 1 0.000 0.000 0.000 0.000 shape_base.py:58(atleast_2d) 1 0.000 0.000 0.000 0.000 {method 'copy' of 'numpy.ndarray' objects} 1 0.000 0.000 0.000 0.000 validation.py:503(check_random_state) 3 0.000 0.000 0.000 0.000 {hasattr} 1 0.000 0.000 0.000 0.000 getlimits.py:259(max) 1 0.000 0.000 0.000 0.000 base.py:203(_warn_from_fit_status) 1 0.000 0.000 0.000 0.000 {method 'randint' of 'mtrand.RandomState' objects} 1 0.000 0.000 0.000 0.000 {method 'index' of 'list' objects} 6 0.000 0.000 0.000 0.000 {len} 4 0.000 0.000 0.000 0.000 {method 'split' of 'str' objects} 3 0.000 0.000 0.000 0.000 {isinstance} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 2 0.000 0.000 0.000 0.000 {callable} 1 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects} 0 0.000 0.000 profile:0(profiler)
unknown
codeparrot/codeparrot-clean
"""This test checks for correct wait4() behavior. """ import os import sys import unittest from test.fork_wait import ForkWait from test import support # If either of these do not exist, skip this test. if not support.has_fork_support: raise unittest.SkipTest("requires working os.fork()") support.get_attribute(os, 'wait4') class Wait4Test(ForkWait): def wait_impl(self, cpid, *, exitcode): option = os.WNOHANG if sys.platform.startswith('aix'): # Issue #11185: wait4 is broken on AIX and will always return 0 # with WNOHANG. option = 0 for _ in support.sleeping_retry(support.SHORT_TIMEOUT): # wait4() shouldn't hang, but some of the buildbots seem to hang # in the forking tests. This is an attempt to fix the problem. spid, status, rusage = os.wait4(cpid, option) if spid == cpid: break self.assertEqual(spid, cpid) self.assertEqual(os.waitstatus_to_exitcode(status), exitcode) self.assertTrue(rusage) def tearDownModule(): support.reap_children() if __name__ == "__main__": unittest.main()
python
github
https://github.com/python/cpython
Lib/test/test_wait4.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class Loki(MakefilePackage): """Loki is a C++ library of designs, containing flexible implementations of common design patterns and idioms.""" homepage = "http://loki-lib.sourceforge.net" url = "https://downloads.sourceforge.net/project/loki-lib/Loki/Loki%200.1.7/loki-0.1.7.tar.bz2" version('0.1.7', '33a24bcbb99fa2ec8fcbbab65649f3f6') variant('shared', default=True, description="Build shared libraries") def build(self, spec, prefix): if '+shared' in spec: make('-C', 'src', 'build-shared') else: make('-C', 'src', 'build-static') def install(self, spec, prefix): make('-C', 'include', 'install', 'prefix={0}'.format(prefix)) if '+shared' in spec: make('-C', 'src', 'install-shared', 'prefix={0}'.format(prefix)) else: make('-C', 'src', 'install-static', 'prefix={0}'.format(prefix))
unknown
codeparrot/codeparrot-clean
<?php namespace Illuminate\Tests\Queue; use Illuminate\Database\Capsule\Manager as DB; use Illuminate\Database\Schema\Blueprint; use Illuminate\Queue\Failed\DatabaseUuidFailedJobProvider; use Illuminate\Support\Carbon; use Illuminate\Support\Str; use PHPUnit\Framework\TestCase; use RuntimeException; class DatabaseUuidFailedJobProviderTest extends TestCase { public function testGettingIdsOfAllFailedJobs() { $provider = $this->getFailedJobProvider(); $provider->log('connection-1', 'queue-1', json_encode(['uuid' => 'uuid-1']), new RuntimeException()); $provider->log('connection-1', 'queue-1', json_encode(['uuid' => 'uuid-2']), new RuntimeException()); $provider->log('connection-2', 'queue-2', json_encode(['uuid' => 'uuid-3']), new RuntimeException()); $provider->log('connection-2', 'queue-2', json_encode(['uuid' => 'uuid-4']), new RuntimeException()); $this->assertSame(['uuid-1', 'uuid-2', 'uuid-3', 'uuid-4'], $provider->ids()); $this->assertSame(['uuid-1', 'uuid-2'], $provider->ids('queue-1')); $this->assertSame(['uuid-3', 'uuid-4'], $provider->ids('queue-2')); } public function testGettingAllFailedJobs() { $provider = $this->getFailedJobProvider(); $this->assertEmpty($provider->all()); $provider->log('connection-1', 'queue-1', json_encode(['uuid' => 'uuid-1']), new RuntimeException()); $provider->log('connection-1', 'queue-1', json_encode(['uuid' => 'uuid-2']), new RuntimeException()); $provider->log('connection-2', 'queue-2', json_encode(['uuid' => 'uuid-3']), new RuntimeException()); $provider->log('connection-2', 'queue-2', json_encode(['uuid' => 'uuid-4']), new RuntimeException()); $this->assertCount(4, $provider->all()); $this->assertSame( ['uuid-1', 'uuid-2', 'uuid-3', 'uuid-4'], array_column($provider->all(), 'id') ); } public function testFindingFailedJobsById() { $provider = $this->getFailedJobProvider(); $provider->log('connection-1', 'queue-1', json_encode(['uuid' => 'uuid-1']), new RuntimeException()); $this->assertNull($provider->find('uuid-2')); $this->assertEquals('uuid-1', $provider->find('uuid-1')->id); $this->assertEquals('queue-1', $provider->find('uuid-1')->queue); $this->assertEquals('connection-1', $provider->find('uuid-1')->connection); } public function testRemovingJobsById() { $provider = $this->getFailedJobProvider(); $provider->log('connection-1', 'queue-1', json_encode(['uuid' => 'uuid-1']), new RuntimeException()); $this->assertNotNull($provider->find('uuid-1')); $provider->forget('uuid-1'); $this->assertNull($provider->find('uuid-1')); } public function testRemovingAllFailedJobs() { $provider = $this->getFailedJobProvider(); $provider->log('connection-1', 'queue-1', json_encode(['uuid' => 'uuid-1']), new RuntimeException()); $provider->log('connection-2', 'queue-2', json_encode(['uuid' => 'uuid-2']), new RuntimeException()); $this->assertCount(2, $provider->all()); $provider->flush(); $this->assertEmpty($provider->all()); } public function testPruningFailedJobs() { $provider = $this->getFailedJobProvider(); Carbon::setTestNow(Carbon::createFromDate(2024, 4, 28)); $provider->log('connection-1', 'queue-1', json_encode(['uuid' => 'uuid-1']), new RuntimeException()); $provider->log('connection-2', 'queue-2', json_encode(['uuid' => 'uuid-2']), new RuntimeException()); $provider->prune(Carbon::createFromDate(2024, 4, 26)); $this->assertCount(2, $provider->all()); $provider->prune(Carbon::createFromDate(2024, 4, 30)); $this->assertEmpty($provider->all()); } public function testPruningFailedJobsWithRelativeHoursAndMinutes() { $provider = $this->getFailedJobProvider(); Carbon::setTestNow(Carbon::create(2025, 8, 24, 12, 30, 0)); $provider->log('connection-1', 'queue-1', json_encode(['uuid' => 'uuid-1']), new RuntimeException()); $provider->log('connection-2', 'queue-2', json_encode(['uuid' => 'uuid-2']), new RuntimeException()); $provider->prune(Carbon::create(2025, 8, 24, 12, 30, 0)); $this->assertCount(2, $provider->all()); $provider->prune(Carbon::create(2025, 8, 24, 13, 0, 0)); $this->assertEmpty($provider->all()); } public function testJobsCanBeCounted() { $provider = $this->getFailedJobProvider(); $this->assertSame(0, $provider->count()); $provider->log('connection-1', 'queue-1', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); $this->assertSame(1, $provider->count()); $provider->log('connection-1', 'queue-1', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); $provider->log('connection-2', 'queue-2', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); $this->assertSame(3, $provider->count()); } public function testJobsCanBeCountedByConnection() { $provider = $this->getFailedJobProvider(); $provider->log('connection-1', 'default', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); $provider->log('connection-2', 'default', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); $this->assertSame(1, $provider->count('connection-1')); $this->assertSame(1, $provider->count('connection-2')); $provider->log('connection-1', 'default', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); $this->assertSame(2, $provider->count('connection-1')); $this->assertSame(1, $provider->count('connection-2')); } public function testJobsCanBeCountedByQueue() { $provider = $this->getFailedJobProvider(); $provider->log('database', 'queue-1', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); $provider->log('database', 'queue-2', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); $this->assertSame(1, $provider->count(queue: 'queue-1')); $this->assertSame(1, $provider->count(queue: 'queue-2')); $provider->log('database', 'queue-1', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); $this->assertSame(2, $provider->count(queue: 'queue-1')); $this->assertSame(1, $provider->count(queue: 'queue-2')); } public function testJobsCanBeCountedByQueueAndConnection() { $provider = $this->getFailedJobProvider(); $provider->log('connection-1', 'queue-99', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); $provider->log('connection-1', 'queue-99', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); $provider->log('connection-2', 'queue-99', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); $provider->log('connection-1', 'queue-1', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); $provider->log('connection-2', 'queue-1', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); $provider->log('connection-2', 'queue-1', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); $this->assertSame(2, $provider->count('connection-1', 'queue-99')); $this->assertSame(1, $provider->count('connection-2', 'queue-99')); $this->assertSame(1, $provider->count('connection-1', 'queue-1')); $this->assertSame(2, $provider->count('connection-2', 'queue-1')); } protected function getFailedJobProvider(string $database = 'default', string $table = 'failed_jobs') { $db = new DB; $db->addConnection([ 'driver' => 'sqlite', 'database' => ':memory:', ]); $db->getConnection()->getSchemaBuilder()->create('failed_jobs', function (Blueprint $table) { $table->uuid(); $table->text('connection'); $table->text('queue'); $table->longText('payload'); $table->longText('exception'); $table->timestamp('failed_at')->useCurrent(); }); return new DatabaseUuidFailedJobProvider($db->getDatabaseManager(), $database, $table); } }
php
github
https://github.com/laravel/framework
tests/Queue/DatabaseUuidFailedJobProviderTest.php
#!/usr/bin/env python import os, sys, re, shutil from optparse import OptionParser, OptionGroup, Values # Determine the MOOSE Directory MOOSE_PYTHON_DIR = None if os.environ.has_key('MOOSE_DIR'): MOOSE_PYTHON_DIR = os.path.join(os.environ['MOOSE_DIR'], 'python') else: MOOSE_PYTHON_DIR = os.path.join(os.path.split(os.path.dirname(os.path.abspath(__file__)))[0], 'python') # Add moose/python to path if os.path.exists(MOOSE_PYTHON_DIR): sys.path.append(MOOSE_PYTHON_DIR) else: raise Exception('Unable to locate moose/python directory, please set MOOSE_DIR environment variable') # Import the TestHarness and Helper functions from the MOOSE toolkit from FactorySystem import InputParameters, Factory from ClusterLauncher import PBSJob import ParseGetPot # Default file to read if only a directory is supplied job_list = 'job_list' def getNextDirName(file_name, files): largest_serial_num = 0 for name in files: m = re.search(file_name + '_(\d{3})', name) if m != None and int(m.group(1)) > largest_serial_num: largest_serial_num = int(m.group(1)) return file_name + "_" + str(largest_serial_num+1).zfill(3) class ClusterLauncher: def __init__(self): self.factory = Factory() def parseJobsFile(self, template_dir, job_file): jobs = [] # We expect the job list to be named "job_list" filename = template_dir + job_file try: data = ParseGetPot.readInputFile(filename) except: # ParseGetPot class print "Parse Error: " + filename return jobs # We expect our root node to be called "Jobs" if 'Jobs' in data.children: jobs_node = data.children['Jobs'] # Get the active line active_jobs = None if 'active' in jobs_node.params: active_jobs = jobs_node.params['active'].split(' ') for jobname, job_node in jobs_node.children.iteritems(): # Make sure this job is active if active_jobs != None and not jobname in active_jobs: continue # First retrieve the type so we can get the valid params if 'type' not in job_node.params: print "Type missing in " + filename sys.exit(1) params = self.factory.validParams(job_node.params['type']) params['job_name'] = jobname # Now update all the base level keys params_parsed = set() params_ignored = set() for key, value in job_node.params.iteritems(): params_parsed.add(key) if key in params: if params.type(key) == list: params[key] = value.split(' ') else: if re.match('".*"', value): # Strip quotes params[key] = value[1:-1] else: params[key] = value else: params_ignored.add(key) # Make sure that all required parameters are supplied required_params_missing = params.required_keys() - params_parsed if len(required_params_missing): print 'Required Missing Parameter(s): ', required_params_missing sys.exit(1) if len(params_ignored): print 'Ignored Parameter(s): ', params_ignored jobs.append(params) return jobs def createAndLaunchJob(self, template_dir, job_file, specs, options): next_dir = getNextDirName(specs['job_name'], os.listdir('.')) os.mkdir(template_dir + next_dir) # Log it if options.message: f = open(template_dir + 'jobs.log', 'a') f.write(next_dir.ljust(20) + ': ' + options.message + '\n') f.close() saved_cwd = os.getcwd() os.chdir(template_dir + next_dir) # Turn the remaining work over to the Job instance # To keep everything consistent we'll also append our serial number to our job name specs['job_name'] = next_dir job_instance = self.factory.create(specs['type'], specs['job_name'], specs) # Copy files job_instance.copyFiles(job_file) # Prepare the Job Script job_instance.prepareJobScript() # Launch it! job_instance.launch() os.chdir(saved_cwd) def registerJobType(self, type, name): self.factory.register(type, name) ### Parameter Dump ### def printDump(self): self.factory.printDump("Jobs") sys.exit(0) def run(self, template_dir, job_file, options): jobs = self.parseJobsFile(template_dir, job_file) for job in jobs: self.createAndLaunchJob(template_dir, job_file, job, options) ######################################################## def main(): parser = OptionParser(usage='Usage: %prog [options] <template directory>') parser.add_option("--dump", action="store_true", dest="dump", default=False, help="Dump the parameters for the testers in GetPot Format") parser.add_option("-m", action="store", dest="message", help="A message that will be stored in a local log file that describes the job") (options, location) = parser.parse_args() cluster_launcher = ClusterLauncher() cluster_launcher.registerJobType(PBSJob, 'PBSJob') if options.dump: cluster_launcher.printDump() if not location: parser.print_help() sys.exit(1) # See if the user passed a file or a directory abs_location = os.path.abspath(location[0]) if os.path.isdir(abs_location): dir = abs_location file = job_list elif os.path.isfile(abs_location): (dir, file) = os.path.split(abs_location) dir = dir + '/' # Launch it cluster_launcher.run(dir, file, options) if __name__ == '__main__': main()
unknown
codeparrot/codeparrot-clean
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. @author: RaNaN """ from imp import find_module from os.path import join, exists from urllib import quote ENGINE = "" DEBUG = False JS = False PYV8 = False RHINO = False if not ENGINE: try: import subprocess subprocess.Popen(["js", "-v"], bufsize=-1, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() p = subprocess.Popen(["js", "-e", "print(23+19)"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() #integrity check if out.strip() == "42": ENGINE = "js" JS = True except: pass if not ENGINE or DEBUG: try: find_module("PyV8") ENGINE = "pyv8" PYV8 = True except: pass if not ENGINE or DEBUG: try: path = "" #path where to find rhino if exists("/usr/share/java/js.jar"): path = "/usr/share/java/js.jar" elif exists("js.jar"): path = "js.jar" elif exists(join(pypath, "js.jar")): #may raises an exception, but js.jar wasnt found anyway path = join(pypath, "js.jar") if not path: raise Exception import subprocess p = subprocess.Popen(["java", "-cp", path, "org.mozilla.javascript.tools.shell.Main", "-e", "print(23+19)"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() #integrity check if out.strip() == "42": ENGINE = "rhino" RHINO = True except: pass class JsEngine(): def __init__(self): self.engine = ENGINE self.init = False def __nonzero__(self): return False if not ENGINE else True def eval(self, script): if not self.init: if ENGINE == "pyv8" or (DEBUG and PYV8): import PyV8 global PyV8 self.init = True if type(script) == unicode: script = script.encode("utf8") if not ENGINE: raise Exception("No JS Engine") if not DEBUG: if ENGINE == "pyv8": return self.eval_pyv8(script) elif ENGINE == "js": return self.eval_js(script) elif ENGINE == "rhino": return self.eval_rhino(script) else: results = [] if PYV8: res = self.eval_pyv8(script) print "PyV8:", res results.append(res) if JS: res = self.eval_js(script) print "JS:", res results.append(res) if RHINO: res = self.eval_rhino(script) print "Rhino:", res results.append(res) warning = False for x in results: for y in results: if x != y: warning = True if warning: print "### WARNING ###: Different results" return results[0] def eval_pyv8(self, script): rt = PyV8.JSContext() rt.enter() return rt.eval(script) def eval_js(self, script): script = "print(eval(unescape('%s')))" % quote(script) p = subprocess.Popen(["js", "-e", script], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=-1) out, err = p.communicate() res = out.strip() return res def eval_rhino(self, script): script = "print(eval(unescape('%s')))" % quote(script) p = subprocess.Popen(["java", "-cp", path, "org.mozilla.javascript.tools.shell.Main", "-e", script], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=-1) out, err = p.communicate() res = out.strip() return res.decode("utf8").encode("ISO-8859-1") def error(self): return _("No js engine detected, please install either Spidermonkey, ossp-js, pyv8 or rhino") if __name__ == "__main__": js = JsEngine() test = u'"ü"+"ä"' js.eval(test)
unknown
codeparrot/codeparrot-clean
{ "name": "vault", "version": "0.0.0", "description": "The official UI for Vault by HashiCorp", "repository": "", "author": "", "directories": { "doc": "doc", "test": "tests" }, "scripts": { "postinstall": "pnpm build:jsondiffpatch", "build": "pnpm build:jsondiffpatch && ember build --environment=production && cp metadata.json ../http/web_ui/metadata.json", "build:dev": "pnpm build:jsondiffpatch && ember build", "build:jsondiffpatch": "webpack --config webpack.jsondiffpatch.config.js", "docs": "sh scripts/generate-docs.sh", "docfy-md": "node scripts/docfy-md.js", "lint:css": "stylelint \"**/*.css\"", "lint:css:fix": "pnpm lint:css --fix", "lint:fix": "concurrently -c \"auto\" -n lint: \"pnpm:lint:*:fix\"", "lint:hbs": "ember-template-lint '**/*.hbs'", "lint:hbs:quiet": "ember-template-lint '**/*.hbs' --quiet", "lint:hbs:fix": "ember-template-lint . --fix", "lint:js": "eslint . --cache", "lint:js:quiet": "eslint . --cache --quiet", "lint:js:fix": "eslint . --fix", "lint:types": "tsc --noEmit", "fmt": "concurrently -c \"auto\" -n fmt: \"pnpm:fmt:*\"", "fmt:js": "prettier --config .prettierrc.js --write '{app,tests,config,lib}/**/*.js'", "fmt:hbs": "prettier --config .prettierrc.js --write '**/*.hbs'", "fmt:styles": "prettier --write app/styles/**/*.*", "start": "VAULT_ADDR=http://127.0.0.1:8200; pnpm build:jsondiffpatch && ember server --proxy=$VAULT_ADDR", "start2": "pnpm build:jsondiffpatch && ember server --proxy=http://127.0.0.1:8202 --port=4202", "start:chroot": "ember server --proxy=http://127.0.0.1:8300 --port=4300", "lint": "concurrently --kill-others-on-fail -P -c \"auto\" -n lint:js,lint:hbs,lint:types \"pnpm:lint:js:quiet\" \"pnpm:lint:hbs:quiet\" \"pnpm:lint:types\"", "test": "pnpm lint && node scripts/start-vault.js", "test:enos": "concurrently --kill-others-on-fail -P -c \"auto\" -n lint:js,lint:hbs,lint:types,enos \"pnpm:lint:js:quiet\" \"pnpm:lint:hbs:quiet\" \"pnpm:lint:types\" \"node scripts/enos-test-ember.js {@}\" --", "test:oss": "pnpm test -f='!enterprise'", "test:ent": "node scripts/start-vault.js -f='enterprise'", "test:quick": "node scripts/start-vault.js --split=8 --preserve-test-name --parallel=1", "test:filter": "node scripts/start-vault.js --server -f='!enterprise'", "test:server": "node scripts/start-vault.js --server", "test:dev": "node scripts/start-vault.js", "vault": "VAULT_REDIRECT_ADDR=http://127.0.0.1:8200 vault server -log-level=error -dev -dev-root-token-id=root -dev-ha -dev-transactional", "vault:cluster": "VAULT_REDIRECT_ADDR=http://127.0.0.1:8202 vault server -log-level=error -dev -dev-root-token-id=root -dev-listen-address=127.0.0.1:8202 -dev-ha -dev-transactional" }, "devDependencies": { "@babel/cli": "~7.27.0", "@babel/core": "~7.26.10", "@babel/plugin-proposal-class-properties": "~7.18.6", "@babel/plugin-proposal-decorators": "^7.28.0", "@babel/plugin-proposal-object-rest-spread": "~7.20.7", "@babel/plugin-transform-block-scoping": "~7.27.0", "@babel/preset-env": "~7.26.9", "@babel/preset-typescript": "~7.27.0", "@codemirror/view": "^6.36.2", "@docfy/ember": "~0.8.5", "@ember/legacy-built-in-components": "~0.4.2", "@ember/optional-features": "~2.2.0", "@ember/render-modifiers": "~3.0.0", "@ember/string": "~4.0.1", "@ember/test-helpers": "~5.2.1", "@ember/test-waiters": "~4.1.0", "@embroider/macros": "1.15.0", "@glimmer/component": "~1.1.2", "@glimmer/tracking": "~1.1.2", "@glint/template": "^1.7.3", "@icholy/duration": "~5.1.0", "@lineal-viz/lineal": "~0.5.1", "@tsconfig/ember": "~2.0.0", "@types/d3-array": "~3.2.1", "@types/ember-data": "~4.4.16", "@types/qunit": "~2.19.12", "@types/rsvp": "~4.0.9", "@types/shell-quote": "~1.7.5", "@typescript-eslint/eslint-plugin": "~5.62.0", "@typescript-eslint/parser": "~5.62.0", "asn1js": "~3.0.6", "autosize": "~6.0.1", "babel-plugin-inline-json-import": "~0.3.2", "base64-js": "~1.5.1", "broccoli-asset-rev": "~3.0.0", "broccoli-sri-hash": "meirish/broccoli-sri-hash#rooturl", "chalk": "^4.1.2", "columnify": "~1.6.0", "concurrently": "~9.1.2", "d3-array": "~3.2.4", "d3-axis": "~3.0.0", "d3-format": "~3.1.0", "d3-scale": "~4.0.2", "d3-selection": "~3.0.0", "d3-shape": "~3.2.0", "date-fns": "~2.30.0", "date-fns-tz": "~1.3.8", "doctoc": "~2.2.1", "dompurify": "~3.2.5", "ember-a11y-testing": "~7.1.2", "ember-basic-dropdown": "~8.7.0", "ember-cli": "~5.8.0", "ember-cli-babel": "~8.2.0", "ember-cli-clean-css": "~3.0.0", "ember-cli-content-security-policy": "2.0.3", "ember-cli-dependency-checker": "~3.3.3", "ember-cli-deprecation-workflow": "~3.3.0", "ember-cli-flash": "4.0.0", "ember-cli-htmlbars": "~6.3.0", "ember-cli-inject-live-reload": "~2.1.0", "ember-cli-mirage": "~3.0.4", "ember-cli-page-object": "~2.3.1", "ember-cli-sass": "11.0.1", "ember-cli-sri": "meirish/ember-cli-sri#rooturl", "ember-cli-string-helpers": "6.1.0", "ember-cli-terser": "~4.0.2", "ember-composable-helpers": "5.0.0", "ember-concurrency": "~4.0.3", "ember-data": "~5.3.13", "ember-engines": "0.8.23", "ember-exam": "~9.1.0", "ember-inflector": "4.0.2", "ember-load-initializers": "~3.0.1", "ember-modifier": "~4.2.0", "ember-power-select": "~8.12.0", "ember-qrcode-shim": "~0.4.0", "ember-qunit": "~8.1.1", "ember-resolver": "~13.1.0", "ember-responsive": "5.0.0", "ember-service-worker": "meirish/ember-service-worker#configurable-scope", "ember-sinon-qunit": "~7.5.0", "ember-source": "~5.8.0", "ember-style-modifier": "~4.4.0", "ember-template-lint": "~6.1.0", "ember-template-lint-plugin-prettier": "~5.0.0", "ember-test-selectors": "7.1.0", "ember-tether": "3.1.1", "ember-truth-helpers": "4.0.3", "escape-string-regexp": "~2.0.0", "eslint": "~8.57.1", "eslint-config-prettier": "~9.1.0", "eslint-plugin-compat": "~4.2.0", "eslint-plugin-ember": "~11.12.0", "eslint-plugin-n": "~16.6.2", "eslint-plugin-prettier": "~5.2.6", "eslint-plugin-qunit": "~8.1.2", "execa": "^5.1.1", "filesize": "~4.2.1", "jsdoc-babel": "~0.5.0", "jsdoc-to-markdown": "~8.0.3", "jsondiffpatch": "0.7.3", "jsonlint": "~1.6.3", "lint-staged": "~16.0.0", "loader.js": "~4.7.0", "miragejs": "~0.1.48", "pkijs": "~2.4.0", "prettier": "3.0.3", "prettier-eslint-cli": "~7.1.0", "pvutils": "~1.1.3", "qunit": "~2.24.1", "qunit-dom": "~3.4.0", "sass": "~1.88.0", "shell-quote": "~1.8.2", "sinon": "~20.0.0", "stylelint": "~16.19.1", "stylelint-config-standard": "~38.0.0", "stylelint-prettier": "~5.0.3", "swagger-ui-dist": "~5.21.0", "text-encoder-lite": "2.0.0", "tracked-built-ins": "~3.4.0", "typescript": "~5.5.4", "webpack": "5.94.0", "webpack-cli": "^6.0.1" }, "pnpm": { "overrides": { "@babel/runtime": "7.27.0", "@embroider/macros": "1.15.0", "@messageformat/runtime": "3.0.2", "ansi-html": "0.0.8", "async": "2.6.4", "braces": "3.0.3", "eslint-utils": "1.4.3", "express": "4.22.1", "https-proxy-agent": "2.2.4", "ini": "1.3.8", "json5": "1.0.2", "kind-of": "6.0.3", "micromatch": "4.0.8", "prismjs": "1.30.0", "qs": "6.14.1", "rollup": "2.79.2", "serialize-javascript": "3.1.0", "socket.io": "4.8.1", "underscore": "1.13.7" } }, "engines": { "node": "20" }, "ember": { "edition": "octane" }, "private": true, "ember-addon": { "paths": [ "lib/config-ui", "lib/core", "lib/keep-gitkeep", "lib/kmip", "lib/kubernetes", "lib/kv", "lib/ldap", "lib/open-api-explorer", "lib/pki", "lib/replication", "lib/service-worker-authenticated-download", "lib/sync" ] }, "dependencies": { "@babel/core": "7.26.10", "@babel/eslint-parser": "^7.28.5", "@carbon/charts": "^1.27.2", "@hashicorp-internal/vault-reporting": "file:vault-reporting/0.8.0.tgz", "@hashicorp/design-system-components": "4.24.1", "@hashicorp/design-system-tokens": "3.0.0", "@hashicorp/vault-client-typescript": "hashicorp/vault-client-typescript", "ember-auto-import": "2.10.0", "handlebars": "4.7.8", "posthog-js": "1.236.1", "uuid": "9.0.1" }, "packageManager": "pnpm@10.22.0+sha512.bf049efe995b28f527fd2b41ae0474ce29186f7edcb3bf545087bd61fbbebb2bf75362d1307fda09c2d288e1e499787ac12d4fcb617a974718a6051f2eee741c", "scarfSettings": { "defaultOptIn": false, "enabled": false, "skipTraversal": true } }
json
github
https://github.com/hashicorp/vault
ui/package.json
package kotlinx.coroutines.internal import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue class LinkedListTest { data class IntNode(val i: Int) : LockFreeLinkedListNode() @Test fun testSimpleAddLastRemove() { val list = LockFreeLinkedListHead() assertContents(list) val n1 = IntNode(1).apply { list.addLast(this, Int.MAX_VALUE) } assertContents(list, 1) val n2 = IntNode(2).apply { list.addLast(this, Int.MAX_VALUE) } assertContents(list, 1, 2) val n3 = IntNode(3).apply { list.addLast(this, Int.MAX_VALUE) } assertContents(list, 1, 2, 3) val n4 = IntNode(4).apply { list.addLast(this, Int.MAX_VALUE) } assertContents(list, 1, 2, 3, 4) assertTrue(n1.remove()) assertContents(list, 2, 3, 4) assertTrue(n3.remove()) assertContents(list, 2, 4) assertTrue(n4.remove()) assertContents(list, 2) assertTrue(n2.remove()) assertFalse(n2.remove()) assertContents(list) } private fun assertContents(list: LockFreeLinkedListHead, vararg expected: Int) { val n = expected.size val actual = IntArray(n) var index = 0 list.forEach { if (it is IntNode) actual[index++] = it.i } assertEquals(n, index) for (i in 0 until n) assertEquals(expected[i], actual[i], "item i") } }
kotlin
github
https://github.com/Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/jsAndWasmShared/test/internal/LinkedListTest.kt
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not 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 wx import armid import Goal from GoalDialog import GoalDialog from DialogClassParameters import DialogClassParameters import ARM from DimensionBaseDialog import DimensionBaseDialog class GoalsDialog(DimensionBaseDialog): def __init__(self,parent): DimensionBaseDialog.__init__(self,parent,armid.GOALS_ID,'Goals',(930,300),'goal.png') self.theMainWindow = parent idList = [armid.GOALS_GOALLIST_ID,armid.GOALS_BUTTONADD_ID,armid.GOALS_BUTTONDELETE_ID] columnList = ['Name','Originator','Status'] self.buildControls(idList,columnList,self.dbProxy.getColouredGoals,'goal') listCtrl = self.FindWindowById(armid.GOALS_GOALLIST_ID) listCtrl.SetColumnWidth(0,300) def addObjectRow(self,listCtrl,listRow,goal): listCtrl.InsertStringItem(listRow,goal.name()) listCtrl.SetStringItem(listRow,1,goal.originator()) if (goal.colour() == 'black'): listCtrl.SetStringItem(listRow,2,'Check') elif (goal.colour() == 'red'): listCtrl.SetStringItem(listRow,2,'To refine') else: listCtrl.SetStringItem(listRow,2,'OK') def onAdd(self,evt): try: addParameters = DialogClassParameters(armid.GOAL_ID,'Add goal',GoalDialog,armid.GOAL_BUTTONCOMMIT_ID,self.dbProxy.addGoal,True) self.addObject(addParameters) except ARM.ARMException,errorText: dlg = wx.MessageDialog(self,str(errorText),'Add goal',wx.OK | wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy() return def onUpdate(self,evt): selectedObjt = self.objts[self.selectedLabel] try: updateParameters = DialogClassParameters(armid.GOAL_ID,'Edit goal',GoalDialog,armid.GOAL_BUTTONCOMMIT_ID,self.dbProxy.updateGoal,False) self.updateObject(selectedObjt,updateParameters) except ARM.ARMException,errorText: dlg = wx.MessageDialog(self,str(errorText),'Edit goal',wx.OK | wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy def onDelete(self,evt): try: self.deleteObject('No goal','Delete goal',self.dbProxy.deleteGoal) except ARM.ARMException,errorText: dlg = wx.MessageDialog(self,str(errorText),'Delete goal',wx.OK | wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy
unknown
codeparrot/codeparrot-clean
#pragma once // ${generated_comment} #ifdef TORCH_ASSERT_NO_OPERATORS #error This change adds a dependency on native_functions.yaml, \ meaning the file will need to be re-compiled every time an operator \ is changed or added. Consider if your change would be better placed in \ another file, or if a more specific header might achieve the same goal. \ See NOTE: [Tensor vs. TensorBase] #endif // Forward declarations of any types needed in the operator signatures. // We can't directly include these classes because it will cause circular include dependencies. // This file is included by TensorBody.h, which defines the Tensor class. #include <ATen/core/ATen_fwd.h> ${MethodOperators_includes} namespace at { namespace _ops { ${MethodOperators_declarations} } // namespace _ops } // namespace at
c
github
https://github.com/pytorch/pytorch
aten/src/ATen/templates/MethodOperators.h
from django.conf import settings from django.contrib.flatpages.models import FlatPage from django.contrib.sites.models import get_current_site from django.http import Http404, HttpResponse, HttpResponsePermanentRedirect from django.shortcuts import get_object_or_404 from django.template import loader, RequestContext from django.utils.safestring import mark_safe from django.views.decorators.csrf import csrf_protect DEFAULT_TEMPLATE = 'flatpages/default.html' # This view is called from FlatpageFallbackMiddleware.process_response # when a 404 is raised, which often means CsrfViewMiddleware.process_view # has not been called even if CsrfViewMiddleware is installed. So we need # to use @csrf_protect, in case the template needs {% csrf_token %}. # However, we can't just wrap this view; if no matching flatpage exists, # or a redirect is required for authentication, the 404 needs to be returned # without any CSRF checks. Therefore, we only # CSRF protect the internal implementation. def flatpage(request, url): """ Public interface to the flat page view. Models: `flatpages.flatpages` Templates: Uses the template defined by the ``template_name`` field, or :template:`flatpages/default.html` if template_name is not defined. Context: flatpage `flatpages.flatpages` object """ if not url.startswith('/'): url = '/' + url site_id = get_current_site(request).id try: f = get_object_or_404(FlatPage, url__exact=url, sites__id__exact=site_id) except Http404: if not url.endswith('/') and settings.APPEND_SLASH: url += '/' f = get_object_or_404(FlatPage, url__exact=url, sites__id__exact=site_id) return HttpResponsePermanentRedirect('%s/' % request.path) else: raise return render_flatpage(request, f) @csrf_protect def render_flatpage(request, f): """ Internal interface to the flat page view. """ # If registration is required for accessing this page, and the user isn't # logged in, redirect to the login page. if f.registration_required and not request.user.is_authenticated(): from django.contrib.auth.views import redirect_to_login return redirect_to_login(request.path) if f.template_name: t = loader.select_template((f.template_name, DEFAULT_TEMPLATE)) else: t = loader.get_template(DEFAULT_TEMPLATE) # To avoid having to always use the "|safe" filter in flatpage templates, # mark the title and content as already safe (since they are raw HTML # content in the first place). f.title = mark_safe(f.title) f.content = mark_safe(f.content) c = RequestContext(request, { 'flatpage': f, }) response = HttpResponse(t.render(c)) return response
unknown
codeparrot/codeparrot-clean
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright 2013 Kitware 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. ############################################################################### import cherrypy import json import time from datetime import datetime from ..describe import Description, autoDescribeRoute from ..rest import Resource, setResponseHeader from girder.constants import SettingKey, SortDir from girder.exceptions import RestException from girder.models.notification import Notification as NotificationModel from girder.models.setting import Setting from girder.utility import JsonEncoder from girder.api import access # If no timeout param is passed to stream, we default to this value DEFAULT_STREAM_TIMEOUT = 300 # When new events are seen, we will poll at the minimum interval MIN_POLL_INTERVAL = 0.5 # The interval increases when no new events are seen, capping at this value MAX_POLL_INTERVAL = 2 def sseMessage(event): """ Serializes an event into the server-sent events protocol. """ # Inject the current time on the server into the event so that # the client doesn't need to worry about clock synchronization # issues when restarting the event stream. event['_girderTime'] = int(time.time()) return 'data: %s\n\n' % json.dumps(event, sort_keys=True, allow_nan=False, cls=JsonEncoder) class Notification(Resource): def __init__(self): super(Notification, self).__init__() self.resourceName = 'notification' self.route('GET', ('stream',), self.stream) self.route('GET', (), self.listNotifications) @access.cookie @access.token @autoDescribeRoute( Description('Stream notifications for a given user via the SSE protocol.') .notes('This uses long-polling to keep the connection open for ' 'several minutes at a time (or longer) and should be requested ' 'with an EventSource object or other SSE-capable client. ' '<p>Notifications are returned within a few seconds of when ' 'they occur. When no notification occurs for the timeout ' 'duration, the stream is closed. ' '<p>This connection can stay open indefinitely long.') .param('timeout', 'The duration without a notification before the stream is closed.', dataType='integer', required=False, default=DEFAULT_STREAM_TIMEOUT) .param('since', 'Filter out events before this time stamp.', dataType='integer', required=False) .produces('text/event-stream') .errorResponse() .errorResponse('You are not logged in.', 403) .errorResponse('The notification stream is not enabled.', 503) ) def stream(self, timeout, params): if not Setting().get(SettingKey.ENABLE_NOTIFICATION_STREAM): raise RestException('The notification stream is not enabled.', code=503) user, token = self.getCurrentUser(returnToken=True) setResponseHeader('Content-Type', 'text/event-stream') setResponseHeader('Cache-Control', 'no-cache') since = params.get('since') if since is not None: since = datetime.utcfromtimestamp(since) def streamGen(): lastUpdate = since start = time.time() wait = MIN_POLL_INTERVAL while cherrypy.engine.state == cherrypy.engine.states.STARTED: wait = min(wait + MIN_POLL_INTERVAL, MAX_POLL_INTERVAL) for event in NotificationModel().get(user, lastUpdate, token=token): if lastUpdate is None or event['updated'] > lastUpdate: lastUpdate = event['updated'] wait = MIN_POLL_INTERVAL start = time.time() yield sseMessage(event) if time.time() - start > timeout: break time.sleep(wait) return streamGen @access.cookie @access.token @autoDescribeRoute( Description('List notification events') .notes('This endpoint can be used for manual long-polling when ' 'SSE support is disabled or otherwise unavailable. The events are always ' 'returned in chronological order.') .param('since', 'Filter out events before this date.', required=False, dataType='dateTime') .errorResponse() .errorResponse('You are not logged in.', 403) ) def listNotifications(self, since): user, token = self.getCurrentUser(returnToken=True) return list(NotificationModel().get( user, since, token=token, sort=[('updated', SortDir.ASCENDING)]))
unknown
codeparrot/codeparrot-clean
/* Copyright (c) 2014, 2025, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is designed to work with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have either included with the program or referenced in the documentation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef MALLOC_ALLOCATOR_INCLUDED #define MALLOC_ALLOCATOR_INCLUDED #include <assert.h> #include <limits> #include <new> #include <utility> // std::forward #include "my_sys.h" #include "mysql/service_mysql_alloc.h" #include "sql/psi_memory_key.h" /** Malloc_allocator is a C++ STL memory allocator based on my_malloc/my_free. This allows for P_S instrumentation of memory allocation done by internally by STL container classes. Example usage: vector<int, Malloc_allocator<int>> v((Malloc_allocator<int>(PSI_NOT_INSTRUMENTED))); If the type is complicated, you can just write Malloc_allocator<>(psi_key) as a shorthand for Malloc_allocator<My_complicated_type>(psi_key), as all Malloc_allocator instances are implicitly convertible to each other and there is a default template parameter. @note allocate() throws std::bad_alloc() similarly to the default STL memory allocator. This is necessary - STL functions which allocates memory expects it. Otherwise these functions will try to use the memory, leading to segfaults if memory allocation was not successful. @note This allocator cannot be used for std::basic_string with RHEL 6/7 because of this bug: https://bugzilla.redhat.com/show_bug.cgi?id=1546704 "Define _GLIBCXX_USE_CXX11_ABI gets ignored by gcc in devtoolset-7" */ template <class T = void *> class Malloc_allocator { // This cannot be const if we want to be able to swap. PSI_memory_key m_key; public: typedef T value_type; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef T *pointer; typedef const T *const_pointer; typedef T &reference; typedef const T &const_reference; pointer address(reference r) const { return &r; } const_pointer address(const_reference r) const { return &r; } explicit Malloc_allocator(PSI_memory_key key) : m_key(key) {} template <class U> Malloc_allocator(const Malloc_allocator<U> &other [[maybe_unused]]) : m_key(other.psi_key()) {} template <class U> Malloc_allocator &operator=(const Malloc_allocator<U> &other [[maybe_unused]]) { assert(m_key == other.psi_key()); // Don't swap key. } pointer allocate(size_type n, const_pointer hint [[maybe_unused]] = nullptr) { if (n == 0) return nullptr; if (n > max_size()) throw std::bad_alloc(); pointer p = static_cast<pointer>( my_malloc(m_key, n * sizeof(T), MYF(MY_WME | ME_FATALERROR))); if (p == nullptr) throw std::bad_alloc(); return p; } void deallocate(pointer p, size_type) { my_free(p); } template <class U, class... Args> void construct(U *p, Args &&...args) { assert(p != nullptr); try { ::new ((void *)p) U(std::forward<Args>(args)...); } catch (...) { assert(false); // Constructor should not throw an exception. } } void destroy(pointer p) { assert(p != nullptr); try { p->~T(); } catch (...) { assert(false); // Destructor should not throw an exception } } size_type max_size() const { return std::numeric_limits<size_t>::max() / sizeof(T); } template <class U> struct rebind { typedef Malloc_allocator<U> other; }; PSI_memory_key psi_key() const { return m_key; } }; template <class T> bool operator==(const Malloc_allocator<T> &a1, const Malloc_allocator<T> &a2) { return a1.psi_key() == a2.psi_key(); } template <class T> bool operator!=(const Malloc_allocator<T> &a1, const Malloc_allocator<T> &a2) { return a1.psi_key() != a2.psi_key(); } #endif // MALLOC_ALLOCATOR_INCLUDED
c
github
https://github.com/mysql/mysql-server
sql/malloc_allocator.h
"""This module contains all the request handlers for the service.""" import httplib import logging import tornado.web import tor_async_util from . import __api_version__ import async_actions import jsonschemas from .. import request_handlers _logger = logging.getLogger(__name__) class RequestHandler(request_handlers.RequestHandler): """Abstract base class for all request handlers.""" pass class HealthRequestHandler(RequestHandler): """Implements the /_health endpoint.""" url_spec = r'/%s/_health' % __api_version__ @tornado.web.asynchronous def get(self): tor_async_util.generate_health_check_response(self, tor_async_util.AsyncHealthCheck) class CrawlResultsRequestHandler(request_handlers.RequestHandler): """Implements the /crawl_results endpoint.""" url_spec = r'/%s/crawl_results/([a-f0-9]{40})' % __api_version__ # GDD = Get Debug Details GDD_ERROR_READING_CRAWL_RESULTS_FROM_CACHE = 0x0001 GDD_BAD_RESPONSE_BODY = 0x0002 @tornado.web.asynchronous def get(self, crawl_results_id): async_action = async_actions.AsyncCrawlResultsDatastoreRead(crawl_results_id) async_action.read(self._on_read_crawl_results_done) def _on_read_crawl_results_done(self, is_ok, base64_encoded_crawl_results, async_action): if not is_ok: self.set_status(httplib.INTERNAL_SERVER_ERROR) self.add_debug_details(self.GDD_ERROR_READING_CRAWL_RESULTS_FROM_CACHE) self.finish() return if base64_encoded_crawl_results is None: self.set_status(httplib.NOT_FOUND) self.finish() return (body, location) = self._crawl_results_as_dict_for_response_body( async_action.crawl_results_id, base64_encoded_crawl_results) if not self.write_and_verify(body, jsonschemas.get_crawl_results_response): self.set_status(httplib.INTERNAL_SERVER_ERROR) self.add_debug_details(self.GDD_BAD_RESPONSE_BODY) self.finish() return self.set_status(httplib.OK) self.set_header('Location', location) self.finish() # PDD = Put Debug Details PDD_BAD_REQUEST_BODY = 0x0001 PDD_BAD_RESPONSE_BODY = 0x0002 PDD_ERROR_WRITING_CRAWL_RESULTS_TO_CACHE = 0x0003 @tornado.web.asynchronous def put(self, crawl_results_id): schema = jsonschemas.put_crawl_results_request request_body = self.get_json_request_body(schema=schema) if request_body is None: self.write_bad_request_response(type(self).PDD_BAD_REQUEST_BODY) self.finish() return async_action = async_actions.AsyncCrawlResultsDatastoreWrite( crawl_results_id, request_body['base64_encoded_crawl_results'], request_body['ttl_in_seconds']) async_action.write(self._on_write_crawl_results_done) def _on_write_crawl_results_done(self, is_ok, async_action): if not is_ok: self.set_status(httplib.INTERNAL_SERVER_ERROR) self.add_debug_details(self.PDD_ERROR_WRITING_CRAWL_RESULTS_TO_CACHE) self.finish() return (_, location) = self._crawl_results_as_dict_for_response_body( async_action.crawl_results_id, async_action.base64_encoded_crawl_results) self.set_status(httplib.OK) self.set_header('Location', location) self.finish() def _crawl_results_as_dict_for_response_body(self, crawl_results_id, base64_encoded_crawl_results): location = '%s://%s/%s/crawl_results/%s' % ( self.request.protocol, self.request.host, __api_version__, crawl_results_id, ) body = { 'crawl_results_id': crawl_results_id, 'base64_encoded_crawl_results': base64_encoded_crawl_results, 'links': { 'self': { 'href': location, }, }, } return (body, location)
unknown
codeparrot/codeparrot-clean
""" =================================================== Recursive feature elimination with cross-validation =================================================== A recursive feature elimination example with automatic tuning of the number of features selected with cross-validation. """ print(__doc__) import matplotlib.pyplot as plt from sklearn.svm import SVC from sklearn.cross_validation import StratifiedKFold from sklearn.feature_selection import RFECV from sklearn.datasets import make_classification # Build a classification task using 3 informative features X, y = make_classification(n_samples=1000, n_features=25, n_informative=3, n_redundant=2, n_repeated=0, n_classes=8, n_clusters_per_class=1, random_state=0) # Create the RFE object and compute a cross-validated score. svc = SVC(kernel="linear") # The "accuracy" scoring is proportional to the number of correct # classifications rfecv = RFECV(estimator=svc, step=1, cv=StratifiedKFold(y, 2), scoring='accuracy') rfecv.fit(X, y) print("Optimal number of features : %d" % rfecv.n_features_) # Plot number of features VS. cross-validation scores plt.figure() plt.xlabel("Number of features selected") plt.ylabel("Cross validation score (nb of correct classifications)") plt.plot(range(1, len(rfecv.grid_scores_) + 1), rfecv.grid_scores_) plt.show()
unknown
codeparrot/codeparrot-clean
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os from pelican.generators import ArticlesGenerator from pelican.tests.support import unittest, get_settings from tempfile import mkdtemp from shutil import rmtree import photos CUR_DIR = os.path.dirname(__file__) class TestPhotos(unittest.TestCase): @classmethod def setUpClass(cls): cls.temp_path = mkdtemp(prefix='pelicantests.') cls.settings = get_settings(filenames={}) cls.settings['PATH'] = os.path.join(CUR_DIR, 'test_data') cls.settings['PHOTO_LIBRARY'] = os.path.join(CUR_DIR, 'test_data') cls.settings['DEFAULT_DATE'] = (1970, 1, 1) cls.settings['FILENAME_METADATA'] = '(?P<slug>[^.]+)' cls.settings['PLUGINS'] = [photos] cls.settings['CACHE_CONTENT'] = False cls.settings['OUTPUT_PATH'] = cls.temp_path photos.initialized(cls) cls.generator = ArticlesGenerator( context=cls.settings.copy(), settings=cls.settings, path=cls.settings['PATH'], theme=cls.settings['THEME'], output_path=cls.settings['OUTPUT_PATH']) photos.register() cls.generator.generate_context() photos.detect_gallery(cls.generator) photos.detect_image(cls.generator) @classmethod def tearDownClass(cls): rmtree(cls.temp_path) def test_image(self): for a in self.generator.articles: if 'image' in a.metadata: self.assertTrue( hasattr(a, 'photo_image'), msg="{} not recognized.".format(a.metadata['image'])) def test_gallery(self): for a in self.generator.articles: if 'gallety' in a.metadata: self.assertTrue( hasattr(a, 'photo_gallery'), msg="{} not recognized.".format(a.metadata['gallery'])) def get_article(self, slug): for a in self.generator.articles: if slug == a.slug: return a return None def test_photo_article_image(self): self.assertEqual(self.get_article('photo').photo_image, ('best.jpg', 'photos/agallery/besta.jpg', 'photos/agallery/bestt.jpg')) def test_photo_article_gallery(self): self.assertEqual(self.get_article('photo').photo_gallery[0], ('best.jpg', 'photos/agallery/best.jpg', 'photos/agallery/bestt.jpg', 'EXIF-best', 'Caption-best')) self.assertEqual(self.get_article('photo').photo_gallery[1], ('night.png', 'photos/agallery/night.jpg', 'photos/agallery/nightt.jpg', 'EXIF-night', '')) def test_photo_article_body(self): expected = ('<p>Here is my best photo, again.</p>\n' '<p><img alt="" src="/photos/agallery/besta.jpg" />.</p>') self.assertEqual(expected, self.get_article('photo').content) def test_filename_article_image(self): self.assertEqual( ('best.jpg', 'agallery/best.jpg', 'photos/agallery/bestt.jpg'), self.get_article('filename').photo_image) def test_filename_article_gallery(self): self.assertEqual(self.get_article('filename').photo_gallery[0], ('best.jpg', 'agallery/best.jpg', 'photos/agallery/bestt.jpg', 'EXIF-best', 'Caption-best')) self.assertEqual(self.get_article('filename').photo_gallery[1], ('night.png', 'agallery/night.png', 'photos/agallery/nightt.jpg', 'EXIF-night', '')) def test_filename_article_body(self): expected = ('<p>Here is my best photo, again.</p>\n' '<p><img alt="" src="{filename}agallery/best.jpg" />.</p>') self.assertEqual(expected, self.get_article('filename').content) def test_queue_resize(self): expected = [ ('photos/agallery/best.jpg', ('test_data/agallery/best.jpg', (1024, 768, 80))), ('photos/agallery/besta.jpg', ('test_data/agallery/best.jpg', (760, 506, 80))), ('photos/agallery/bestt.jpg', ('test_data/agallery/best.jpg', (192, 144, 60))), ('photos/agallery/night.jpg', ('test_data/agallery/night.png', (1024, 768, 80))), ('photos/agallery/nightt.jpg', ('test_data/agallery/night.png', (192, 144, 60)))] self.assertEqual(sorted(expected), sorted(photos.queue_resize.items())) if __name__ == '__main__': unittest.main()
unknown
codeparrot/codeparrot-clean
/* * Copyright 2012-present the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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. */ package org.springframework.boot.autoconfigure.condition; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import jakarta.servlet.Filter; import org.springframework.beans.factory.BeanFactory; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Conditional; import org.springframework.core.annotation.AliasFor; /** * {@link Conditional @Conditional} that only matches when no {@link Filter} beans of the * specified type are contained in the {@link BeanFactory}. This condition will detect * both directly registered {@link Filter} beans as well as those registered through a * {@link FilterRegistrationBean}. * <p> * When placed on a {@code @Bean} method, the bean class defaults to the return type of * the factory method or the type of the {@link Filter} if the bean is a * {@link FilterRegistrationBean}: * * <pre class="code"> * &#064;Configuration * public class MyAutoConfiguration { * * &#064;ConditionalOnMissingFilterBean * &#064;Bean * public MyFilter myFilter() { * ... * } * * }</pre> * <p> * In the sample above the condition will match if no bean of type {@code MyFilter} or * {@code FilterRegistrationBean<MyFilter>} is already contained in the * {@link BeanFactory}. * * @author Phillip Webb * @since 2.1.0 */ @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented @ConditionalOnMissingBean(parameterizedContainer = FilterRegistrationBean.class) public @interface ConditionalOnMissingFilterBean { /** * The filter bean type that must not be present. * @return the bean type */ @AliasFor(annotation = ConditionalOnMissingBean.class) Class<? extends Filter>[] value() default {}; }
java
github
https://github.com/spring-projects/spring-boot
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingFilterBean.java
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import re import subprocess import sys """Prints the lowest locally available SDK version greater than or equal to a given minimum sdk version to standard output. Usage: python find_sdk.py 10.6 # Ignores SDKs < 10.6 """ def parse_version(version_str): """'10.6' => [10, 6]""" return map(int, re.findall(r'(\d+)', version_str)) def find_sdk_dir(): job = subprocess.Popen(['xcode-select', '-print-path'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, err = job.communicate() if job.returncode != 0: print >>sys.stderr, out print >>sys.stderr, err raise Exception(('Error %d running xcode-select, you might have to run ' '|sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer| ' 'if you are using Xcode 4.') % job.returncode) # The Developer folder moved in Xcode 4.3. xcode43_sdk_path = os.path.join( out.rstrip(), 'Platforms/MacOSX.platform/Developer/SDKs') if os.path.isdir(xcode43_sdk_path): sdk_dir = xcode43_sdk_path else: sdk_dir = os.path.join(out.rstrip(), 'SDKs') return sdk_dir def main(): min_sdk_version = '10.6' if len(sys.argv) > 1: min_sdk_version = sys.argv[1] sdk_dir = find_sdk_dir() sdks = [re.findall('^MacOSX(10\.\d+)\.sdk$', s) for s in os.listdir(sdk_dir)] sdks = [s[0] for s in sdks if s] # [['10.5'], ['10.6']] => ['10.5', '10.6'] sdks = [s for s in sdks # ['10.5', '10.6'] => ['10.6'] if parse_version(s) >= parse_version(min_sdk_version)] if not sdks: raise Exception('No %s+ SDK found' % min_sdk_version) best_sdk = min(sdks, key=parse_version) return best_sdk if __name__ == '__main__': if sys.platform != 'darwin': raise Exception("This script only runs on Mac") print main()
unknown
codeparrot/codeparrot-clean
import { expect, it } from 'vitest' import { toKeyPath } from './to-key-path' it('can convert key paths to arrays', () => { expect(toKeyPath('fontSize.xs')).toEqual(['fontSize', 'xs']) expect(toKeyPath('fontSize.xs[1].lineHeight')).toEqual(['fontSize', 'xs', '1', 'lineHeight']) expect(toKeyPath('colors.red.500')).toEqual(['colors', 'red', '500']) expect(toKeyPath('colors[red].500')).toEqual(['colors', 'red', '500']) expect(toKeyPath('colors[red].[500]')).toEqual(['colors', 'red', '500']) expect(toKeyPath('colors[red]500')).toEqual(['colors', 'red', '500']) expect(toKeyPath('colors[red][500]')).toEqual(['colors', 'red', '500']) expect(toKeyPath('colors[red]500[50]5')).toEqual(['colors', 'red', '500', '50', '5']) })
typescript
github
https://github.com/tailwindlabs/tailwindcss
packages/tailwindcss/src/utils/to-key-path.test.ts
/* * Copyright 2002-present the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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. */ package org.springframework.context.support; import java.io.IOException; import org.jspecify.annotations.Nullable; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextException; /** * Base class for {@link org.springframework.context.ApplicationContext} * implementations which are supposed to support multiple calls to {@link #refresh()}, * creating a new internal bean factory instance every time. * Typically (but not necessarily), such a context will be driven by * a set of config locations to load bean definitions from. * * <p>The only method to be implemented by subclasses is {@link #loadBeanDefinitions}, * which gets invoked on each refresh. A concrete implementation is supposed to load * bean definitions into the given * {@link org.springframework.beans.factory.support.DefaultListableBeanFactory}, * typically delegating to one or more specific bean definition readers. * * <p><b>Note that there is a similar base class for WebApplicationContexts.</b> * {@link org.springframework.web.context.support.AbstractRefreshableWebApplicationContext} * provides the same subclassing strategy, but additionally pre-implements * all context functionality for web environments. There is also a * pre-defined way to receive config locations for a web context. * * <p>Concrete standalone subclasses of this base class, reading in a * specific bean definition format, are {@link ClassPathXmlApplicationContext} * and {@link FileSystemXmlApplicationContext}, which both derive from the * common {@link AbstractXmlApplicationContext} base class; * {@link org.springframework.context.annotation.AnnotationConfigApplicationContext} * supports {@code @Configuration}-annotated classes as a source of bean definitions. * * @author Juergen Hoeller * @author Chris Beams * @since 1.1.3 * @see #loadBeanDefinitions * @see org.springframework.beans.factory.support.DefaultListableBeanFactory * @see org.springframework.web.context.support.AbstractRefreshableWebApplicationContext * @see AbstractXmlApplicationContext * @see ClassPathXmlApplicationContext * @see FileSystemXmlApplicationContext * @see org.springframework.context.annotation.AnnotationConfigApplicationContext */ public abstract class AbstractRefreshableApplicationContext extends AbstractApplicationContext { private @Nullable Boolean allowBeanDefinitionOverriding; private @Nullable Boolean allowCircularReferences; /** Bean factory for this context. */ private volatile @Nullable DefaultListableBeanFactory beanFactory; /** * Create a new AbstractRefreshableApplicationContext with no parent. */ public AbstractRefreshableApplicationContext() { } /** * Create a new AbstractRefreshableApplicationContext with the given parent context. * @param parent the parent context */ public AbstractRefreshableApplicationContext(@Nullable ApplicationContext parent) { super(parent); } /** * Set whether it should be allowed to override bean definitions by registering * a different definition with the same name, automatically replacing the former. * If not, an exception will be thrown. Default is "true". * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowBeanDefinitionOverriding */ public void setAllowBeanDefinitionOverriding(boolean allowBeanDefinitionOverriding) { this.allowBeanDefinitionOverriding = allowBeanDefinitionOverriding; } /** * Set whether to allow circular references between beans - and automatically * try to resolve them. * <p>Default is "true". Turn this off to throw an exception when encountering * a circular reference, disallowing them completely. * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowCircularReferences */ public void setAllowCircularReferences(boolean allowCircularReferences) { this.allowCircularReferences = allowCircularReferences; } /** * This implementation performs an actual refresh of this context's underlying * bean factory, shutting down the previous bean factory (if any) and * initializing a fresh bean factory for the next phase of the context's lifecycle. */ @Override protected final void refreshBeanFactory() throws BeansException { if (hasBeanFactory()) { destroyBeans(); closeBeanFactory(); } try { DefaultListableBeanFactory beanFactory = createBeanFactory(); beanFactory.setSerializationId(getId()); beanFactory.setApplicationStartup(getApplicationStartup()); customizeBeanFactory(beanFactory); loadBeanDefinitions(beanFactory); this.beanFactory = beanFactory; } catch (IOException ex) { throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex); } } @Override protected void cancelRefresh(Throwable ex) { DefaultListableBeanFactory beanFactory = this.beanFactory; if (beanFactory != null) { beanFactory.setSerializationId(null); } super.cancelRefresh(ex); } @Override protected final void closeBeanFactory() { DefaultListableBeanFactory beanFactory = this.beanFactory; if (beanFactory != null) { beanFactory.setSerializationId(null); this.beanFactory = null; } } /** * Determine whether this context currently holds a bean factory, * i.e. has been refreshed at least once and not been closed yet. */ protected final boolean hasBeanFactory() { return (this.beanFactory != null); } @Override public final ConfigurableListableBeanFactory getBeanFactory() { DefaultListableBeanFactory beanFactory = this.beanFactory; if (beanFactory == null) { throw new IllegalStateException("BeanFactory not initialized or already closed - " + "call 'refresh' before accessing beans via the ApplicationContext"); } return beanFactory; } /** * Overridden to turn it into a no-op: With AbstractRefreshableApplicationContext, * {@link #getBeanFactory()} serves a strong assertion for an active context anyway. */ @Override protected void assertBeanFactoryActive() { } /** * Create an internal bean factory for this context. * Called for each {@link #refresh()} attempt. * <p>The default implementation creates a * {@link org.springframework.beans.factory.support.DefaultListableBeanFactory} * with the {@linkplain #getInternalParentBeanFactory() internal bean factory} of this * context's parent as parent bean factory. Can be overridden in subclasses, * for example to customize DefaultListableBeanFactory's settings. * @return the bean factory for this context * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowBeanDefinitionOverriding * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowEagerClassLoading * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowCircularReferences * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowRawInjectionDespiteWrapping */ protected DefaultListableBeanFactory createBeanFactory() { return new DefaultListableBeanFactory(getInternalParentBeanFactory()); } /** * Customize the internal bean factory used by this context. * Called for each {@link #refresh()} attempt. * <p>The default implementation applies this context's * {@linkplain #setAllowBeanDefinitionOverriding "allowBeanDefinitionOverriding"} * and {@linkplain #setAllowCircularReferences "allowCircularReferences"} settings, * if specified. Can be overridden in subclasses to customize any of * {@link DefaultListableBeanFactory}'s settings. * @param beanFactory the newly created bean factory for this context * @see DefaultListableBeanFactory#setAllowBeanDefinitionOverriding * @see DefaultListableBeanFactory#setAllowCircularReferences * @see DefaultListableBeanFactory#setAllowRawInjectionDespiteWrapping * @see DefaultListableBeanFactory#setAllowEagerClassLoading */ protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) { if (this.allowBeanDefinitionOverriding != null) { beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding); } if (this.allowCircularReferences != null) { beanFactory.setAllowCircularReferences(this.allowCircularReferences); } } /** * Load bean definitions into the given bean factory, typically through * delegating to one or more bean definition readers. * @param beanFactory the bean factory to load bean definitions into * @throws BeansException if parsing of the bean definitions failed * @throws IOException if loading of bean definition files failed * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader */ protected abstract void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException; }
java
github
https://github.com/spring-projects/spring-framework
spring-context/src/main/java/org/springframework/context/support/AbstractRefreshableApplicationContext.java
# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) %YAML 1.2 --- $id: http://devicetree.org/schemas/dma/socionext,uniphier-xdmac.yaml# $schema: http://devicetree.org/meta-schemas/core.yaml# title: Socionext UniPhier external DMA controller description: | This describes the devicetree bindings for an external DMA engine to perform memory-to-memory or peripheral-to-memory data transfer capable of supporting 16 channels, implemented in Socionext UniPhier SoCs. maintainers: - Kunihiko Hayashi <hayashi.kunihiko@socionext.com> allOf: - $ref: dma-controller.yaml# properties: compatible: const: socionext,uniphier-xdmac reg: maxItems: 1 interrupts: maxItems: 1 "#dma-cells": const: 2 description: | DMA request from clients consists of 2 cells: 1. Channel index 2. Transfer request factor number, If no transfer factor, use 0. The number is SoC-specific, and this should be specified with relation to the device to use the DMA controller. dma-channels: minimum: 1 maximum: 16 additionalProperties: false required: - compatible - reg - interrupts - "#dma-cells" - dma-channels examples: - | xdmac: dma-controller@5fc10000 { compatible = "socionext,uniphier-xdmac"; reg = <0x5fc10000 0x5300>; interrupts = <0 188 4>; #dma-cells = <2>; dma-channels = <16>; }; ...
unknown
github
https://github.com/torvalds/linux
Documentation/devicetree/bindings/dma/socionext,uniphier-xdmac.yaml
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT #![allow(clippy::result_large_err)] use serde::de::DeserializeOwned; use serde_json::Value; use std::ffi::OsStr; use std::path::{Path, PathBuf}; use thiserror::Error; /// All extensions that are possibly supported, but perhaps not enabled. const EXTENSIONS_SUPPORTED: &[&str] = &["json", "json5", "toml"]; /// All configuration formats that are currently enabled. const ENABLED_FORMATS: &[ConfigFormat] = &[ ConfigFormat::Json, #[cfg(feature = "config-json5")] ConfigFormat::Json5, #[cfg(feature = "config-toml")] ConfigFormat::Toml, ]; /// The available configuration formats. #[derive(Debug, Copy, Clone)] enum ConfigFormat { /// The default JSON (tauri.conf.json) format. Json, /// The JSON5 (tauri.conf.json5) format. Json5, /// The TOML (Tauri.toml file) format. Toml, } impl ConfigFormat { /// Maps the config format to its file name. fn into_file_name(self) -> &'static str { match self { Self::Json => "tauri.conf.json", Self::Json5 => "tauri.conf.json5", Self::Toml => "Tauri.toml", } } fn into_platform_file_name(self) -> &'static str { match self { Self::Json => { if cfg!(target_os = "macos") { "tauri.macos.conf.json" } else if cfg!(windows) { "tauri.windows.conf.json" } else { "tauri.linux.conf.json" } } Self::Json5 => { if cfg!(target_os = "macos") { "tauri.macos.conf.json5" } else if cfg!(windows) { "tauri.windows.conf.json5" } else { "tauri.linux.conf.json5" } } Self::Toml => { if cfg!(target_os = "macos") { "Tauri.macos.toml" } else if cfg!(windows) { "Tauri.windows.toml" } else { "Tauri.linux.toml" } } } } } /// Represents all the errors that can happen while reading the config. #[derive(Debug, Error)] #[non_exhaustive] pub enum ConfigError { /// Failed to parse from JSON. #[error("unable to parse JSON Tauri config file at {path} because {error}")] FormatJson { /// The path that failed to parse into JSON. path: PathBuf, /// The parsing [`serde_json::Error`]. error: serde_json::Error, }, /// Failed to parse from JSON5. #[cfg(feature = "config-json5")] #[error("unable to parse JSON5 Tauri config file at {path} because {error}")] FormatJson5 { /// The path that failed to parse into JSON5. path: PathBuf, /// The parsing [`json5::Error`]. error: ::json5::Error, }, /// Failed to parse from TOML. #[cfg(feature = "config-toml")] #[error("unable to parse toml Tauri config file at {path} because {error}")] FormatToml { /// The path that failed to parse into TOML. path: PathBuf, /// The parsing [`toml::Error`]. error: ::toml::de::Error, }, /// Unknown config file name encountered. #[error("unsupported format encountered {0}")] UnsupportedFormat(String), /// Known file extension encountered, but corresponding parser is not enabled (cargo features). #[error("supported (but disabled) format encountered {extension} - try enabling `{feature}` ")] DisabledFormat { /// The extension encountered. extension: String, /// The cargo feature to enable it. feature: String, }, /// A generic IO error with context of what caused it. #[error("unable to read Tauri config file at {path} because {error}")] Io { /// The path the IO error occurred on. path: PathBuf, /// The [`std::io::Error`]. error: std::io::Error, }, } /// See [`parse`] for specifics, returns a JSON [`Value`] instead of [`Config`]. pub fn parse_value(path: impl Into<PathBuf>) -> Result<(Value, PathBuf), ConfigError> { do_parse(path.into()) } fn do_parse<D: DeserializeOwned>(path: PathBuf) -> Result<(D, PathBuf), ConfigError> { let file_name = path .file_name() .map(OsStr::to_string_lossy) .unwrap_or_default(); let lookup_platform_config = ENABLED_FORMATS .iter() .any(|format| file_name == format.into_platform_file_name()); let json5 = path.with_file_name(if lookup_platform_config { ConfigFormat::Json5.into_platform_file_name() } else { ConfigFormat::Json5.into_file_name() }); let toml = path.with_file_name(if lookup_platform_config { ConfigFormat::Toml.into_platform_file_name() } else { ConfigFormat::Toml.into_file_name() }); let path_ext = path .extension() .map(OsStr::to_string_lossy) .unwrap_or_default(); if path.exists() { let raw = read_to_string(&path)?; // to allow us to easily use the compile-time #[cfg], we always bind #[allow(clippy::let_and_return)] let json = do_parse_json(&raw, &path); // we also want to support **valid** json5 in the .json extension if the feature is enabled. // if the json5 is not valid the serde_json error for regular json will be returned. // this could be a bit confusing, so we may want to encourage users using json5 to use the // .json5 extension instead of .json #[cfg(feature = "config-json5")] let json = { match do_parse_json5(&raw, &path) { json5 @ Ok(_) => json5, // assume any errors from json5 in a .json file is because it's not json5 Err(_) => json, } }; json.map(|j| (j, path)) } else if json5.exists() { #[cfg(feature = "config-json5")] { let raw = read_to_string(&json5)?; do_parse_json5(&raw, &path).map(|config| (config, json5)) } #[cfg(not(feature = "config-json5"))] Err(ConfigError::DisabledFormat { extension: ".json5".into(), feature: "config-json5".into(), }) } else if toml.exists() { #[cfg(feature = "config-toml")] { let raw = read_to_string(&toml)?; do_parse_toml(&raw, &path).map(|config| (config, toml)) } #[cfg(not(feature = "config-toml"))] Err(ConfigError::DisabledFormat { extension: ".toml".into(), feature: "config-toml".into(), }) } else if !EXTENSIONS_SUPPORTED.contains(&path_ext.as_ref()) { Err(ConfigError::UnsupportedFormat(path_ext.to_string())) } else { Err(ConfigError::Io { path, error: std::io::ErrorKind::NotFound.into(), }) } } fn do_parse_json<D: DeserializeOwned>(raw: &str, path: &Path) -> Result<D, ConfigError> { serde_json::from_str(raw).map_err(|error| ConfigError::FormatJson { path: path.into(), error, }) } #[cfg(feature = "config-json5")] fn do_parse_json5<D: DeserializeOwned>(raw: &str, path: &Path) -> Result<D, ConfigError> { ::json5::from_str(raw).map_err(|error| ConfigError::FormatJson5 { path: path.into(), error, }) } #[cfg(feature = "config-toml")] fn do_parse_toml<D: DeserializeOwned>(raw: &str, path: &Path) -> Result<D, ConfigError> { ::toml::from_str(raw).map_err(|error| ConfigError::FormatToml { path: path.into(), error, }) } /// Helper function to wrap IO errors from [`std::fs::read_to_string`] into a [`ConfigError`]. fn read_to_string(path: &Path) -> Result<String, ConfigError> { std::fs::read_to_string(path).map_err(|error| ConfigError::Io { path: path.into(), error, }) }
rust
github
https://github.com/tauri-apps/tauri
crates/tauri-utils/src/config_v1/parse.rs
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 NEC Corporation # 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. # # @author: Akihiro Motoki, NEC Corporation # import contextlib from oslo.config import cfg from quantum import context from quantum.extensions import portbindings from quantum.manager import QuantumManager from quantum.tests.unit import test_db_plugin class PortBindingsTestCase(test_db_plugin.QuantumDbPluginV2TestCase): # VIF_TYPE must be overridden according to plugin vif_type VIF_TYPE = portbindings.VIF_TYPE_OTHER # The plugin supports the port security feature such as # security groups and anti spoofing. HAS_PORT_FILTER = False def _check_response_portbindings(self, port): self.assertEqual(port['binding:vif_type'], self.VIF_TYPE) port_cap = port[portbindings.CAPABILITIES] self.assertEqual(port_cap[portbindings.CAP_PORT_FILTER], self.HAS_PORT_FILTER) def _check_response_no_portbindings(self, port): self.assertTrue('status' in port) self.assertFalse(portbindings.VIF_TYPE in port) self.assertFalse(portbindings.CAPABILITIES in port) def test_port_vif_details(self): plugin = QuantumManager.get_plugin() with self.port(name='name') as port: port_id = port['port']['id'] # Check a response of create_port self._check_response_portbindings(port['port']) # Check a response of get_port ctx = context.get_admin_context() port = plugin.get_port(ctx, port_id) self._check_response_portbindings(port) # By default user is admin - now test non admin user ctx = context.Context(user_id=None, tenant_id=self._tenant_id, is_admin=False, read_deleted="no") non_admin_port = plugin.get_port(ctx, port_id) self._check_response_no_portbindings(non_admin_port) def test_ports_vif_details(self): plugin = QuantumManager.get_plugin() cfg.CONF.set_default('allow_overlapping_ips', True) with contextlib.nested(self.port(), self.port()): ctx = context.get_admin_context() ports = plugin.get_ports(ctx) self.assertEqual(len(ports), 2) for port in ports: self._check_response_portbindings(port) # By default user is admin - now test non admin user ctx = context.Context(user_id=None, tenant_id=self._tenant_id, is_admin=False, read_deleted="no") ports = plugin.get_ports(ctx) self.assertEqual(len(ports), 2) for non_admin_port in ports: self._check_response_no_portbindings(non_admin_port)
unknown
codeparrot/codeparrot-clean
from __future__ import print_function, division import matplotlib import logging from sys import stdout matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab! from neuralnilm import (Net, RealApplianceSource, BLSTMLayer, DimshuffleLayer, BidirectionalRecurrentLayer) from neuralnilm.source import standardise, discretize, fdiff, power_and_fdiff from neuralnilm.experiment import run_experiment, init_experiment from neuralnilm.net import TrainingError from neuralnilm.layers import MixtureDensityLayer from neuralnilm.objectives import (scaled_cost, mdn_nll, scaled_cost_ignore_inactive, ignore_inactive, scaled_cost3) from neuralnilm.plot import MDNPlotter from lasagne.nonlinearities import sigmoid, rectify, tanh from lasagne.objectives import mse from lasagne.init import Uniform, Normal from lasagne.layers import (LSTMLayer, DenseLayer, Conv1DLayer, ReshapeLayer, FeaturePoolLayer, RecurrentLayer) from lasagne.updates import nesterov_momentum, momentum from functools import partial import os import __main__ from copy import deepcopy from math import sqrt import numpy as np import theano.tensor as T NAME = os.path.splitext(os.path.split(__main__.__file__)[1])[0] PATH = "/homes/dk3810/workspace/python/neuralnilm/figures" SAVE_PLOT_INTERVAL = 1000 GRADIENT_STEPS = 100 SEQ_LENGTH = 512 source_dict = dict( filename='/data/dk3810/ukdale.h5', appliances=[ ['fridge freezer', 'fridge', 'freezer'], # 'hair straighteners', # 'television', 'dish washer', ['washer dryer', 'washing machine'] ], max_appliance_powers=[300, 2500, 2400], on_power_thresholds=[5] * 5, max_input_power=5900, min_on_durations=[60, 1800, 1800], min_off_durations=[12, 1800, 600], window=("2013-06-01", "2014-07-01"), seq_length=SEQ_LENGTH, output_one_appliance=False, boolean_targets=False, train_buildings=[1], validation_buildings=[1], skip_probability=0.5, n_seq_per_batch=16, subsample_target=4, include_diff=False, clip_appliance_power=True, target_is_prediction=False, # independently_center_inputs = True, standardise_input=True, unit_variance_targets=True, input_padding=0, lag=0 # reshape_target_to_2D=True, # input_stats={'mean': np.array([ 0.05526326], dtype=np.float32), # 'std': np.array([ 0.12636775], dtype=np.float32)}, # target_stats={ # 'mean': np.array([ 0.04066789, 0.01881946, # 0.24639061, 0.17608672, 0.10273963], # dtype=np.float32), # 'std': np.array([ 0.11449792, 0.07338708, # 0.26608968, 0.33463112, 0.21250485], # dtype=np.float32)} ) N = 50 net_dict = dict( save_plot_interval=SAVE_PLOT_INTERVAL, # loss_function=partial(ignore_inactive, loss_func=mdn_nll, seq_length=SEQ_LENGTH), # loss_function=lambda x, t: mdn_nll(x, t).mean(), # loss_function=lambda x, t: mse(x, t).mean(), # loss_function=partial(scaled_cost, loss_func=mse), # loss_function=ignore_inactive, loss_function=partial(scaled_cost3, ignore_inactive=False), updates_func=momentum, learning_rate=1e-3, learning_rate_changes_by_iteration={ 500: 5e-4, 1000: 1e-4 # 4000: 1e-03, # 6000: 5e-06, # 7000: 1e-06 # 2000: 5e-06 # 3000: 1e-05 # 7000: 5e-06, # 10000: 1e-06, # 15000: 5e-07, # 50000: 1e-07 }, do_save_activations=True # plotter=MDNPlotter ) def exp_a(name): global source source_dict_copy = deepcopy(source_dict) source = RealApplianceSource(**source_dict_copy) net_dict_copy = deepcopy(net_dict) net_dict_copy.update(dict( experiment_name=name, source=source )) N = 50 net_dict_copy['layers_config'] = [ { 'type': BidirectionalRecurrentLayer, 'num_units': N, 'gradient_steps': GRADIENT_STEPS, 'W_in_to_hid': Normal(std=1.), 'nonlinearity': tanh }, { 'type': FeaturePoolLayer, 'ds': 2, # number of feature maps to be pooled together 'axis': 1, # pool over the time axis 'pool_function': T.max }, { 'type': BidirectionalRecurrentLayer, 'num_units': N, 'gradient_steps': GRADIENT_STEPS, 'W_in_to_hid': Normal(std=1/sqrt(N)), 'nonlinearity': tanh }, { 'type': FeaturePoolLayer, 'ds': 2, # number of feature maps to be pooled together 'axis': 1, # pool over the time axis 'pool_function': T.max }, { 'type': BidirectionalRecurrentLayer, 'num_units': N, 'gradient_steps': GRADIENT_STEPS, 'W_in_to_hid': Normal(std=1/sqrt(N)), 'nonlinearity': tanh }, # { # 'type': FeaturePoolLayer, # 'ds': 2, # number of feature maps to be pooled together # 'axis': 1, # pool over the time axis # 'pool_function': T.max # }, # { # 'type': BidirectionalRecurrentLayer, # 'num_units': N, # 'gradient_steps': GRADIENT_STEPS, # 'W_in_to_hid': Normal(std=1/sqrt(N)), # 'nonlinearity': tanh # }, { 'type': DenseLayer, 'num_units': source.n_outputs, 'W': Normal(std=1/sqrt(N)), 'nonlinearity': T.nnet.softplus } # { # 'type': MixtureDensityLayer, # 'num_units': source.n_outputs, # 'num_components': 1, # 'nonlinearity_mu': T.nnet.softplus # } ] net = Net(**net_dict_copy) return net def main(): # EXPERIMENTS = list('abcdefghijklmnopqrstuvwxyz') EXPERIMENTS = list('a') for experiment in EXPERIMENTS: full_exp_name = NAME + experiment func_call = init_experiment(PATH, experiment, full_exp_name) logger = logging.getLogger(full_exp_name) try: net = eval(func_call) run_experiment(net, epochs=None) except KeyboardInterrupt: logger.info("KeyboardInterrupt") break except Exception as exception: logger.exception("Exception") raise finally: logging.shutdown() if __name__ == "__main__": main()
unknown
codeparrot/codeparrot-clean
# coding: utf-8 from __future__ import unicode_literals import time import math import os.path import re from .common import InfoExtractor from ..compat import ( compat_html_parser, compat_urllib_parse, compat_urllib_request, compat_urlparse, ) from ..utils import ExtractorError class GroovesharkHtmlParser(compat_html_parser.HTMLParser): def __init__(self): self._current_object = None self.objects = [] compat_html_parser.HTMLParser.__init__(self) def handle_starttag(self, tag, attrs): attrs = dict((k, v) for k, v in attrs) if tag == 'object': self._current_object = {'attrs': attrs, 'params': []} elif tag == 'param': self._current_object['params'].append(attrs) def handle_endtag(self, tag): if tag == 'object': self.objects.append(self._current_object) self._current_object = None @classmethod def extract_object_tags(cls, html): p = cls() p.feed(html) p.close() return p.objects class GroovesharkIE(InfoExtractor): _VALID_URL = r'https?://(www\.)?grooveshark\.com/#!/s/([^/]+)/([^/]+)' _TEST = { 'url': 'http://grooveshark.com/#!/s/Jolene+Tenth+Key+Remix+Ft+Will+Sessions/6SS1DW?src=5', 'md5': '7ecf8aefa59d6b2098517e1baa530023', 'info_dict': { 'id': '6SS1DW', 'title': 'Jolene (Tenth Key Remix ft. Will Sessions)', 'ext': 'mp3', 'duration': 227, } } do_playerpage_request = True do_bootstrap_request = True def _parse_target(self, target): uri = compat_urlparse.urlparse(target) hash = uri.fragment[1:].split('?')[0] token = os.path.basename(hash.rstrip('/')) return (uri, hash, token) def _build_bootstrap_url(self, target): (uri, hash, token) = self._parse_target(target) query = 'getCommunicationToken=1&hash=%s&%d' % (compat_urllib_parse.quote(hash, safe=''), self.ts) return (compat_urlparse.urlunparse((uri.scheme, uri.netloc, '/preload.php', None, query, None)), token) def _build_meta_url(self, target): (uri, hash, token) = self._parse_target(target) query = 'hash=%s&%d' % (compat_urllib_parse.quote(hash, safe=''), self.ts) return (compat_urlparse.urlunparse((uri.scheme, uri.netloc, '/preload.php', None, query, None)), token) def _build_stream_url(self, meta): return compat_urlparse.urlunparse(('http', meta['streamKey']['ip'], '/stream.php', None, None, None)) def _build_swf_referer(self, target, obj): (uri, _, _) = self._parse_target(target) return compat_urlparse.urlunparse((uri.scheme, uri.netloc, obj['attrs']['data'], None, None, None)) def _transform_bootstrap(self, js): return re.split('(?m)^\s*try\s*{', js)[0] \ .split(' = ', 1)[1].strip().rstrip(';') def _transform_meta(self, js): return js.split('\n')[0].split('=')[1].rstrip(';') def _get_meta(self, target): (meta_url, token) = self._build_meta_url(target) self.to_screen('Metadata URL: %s' % meta_url) headers = {'Referer': compat_urlparse.urldefrag(target)[0]} req = compat_urllib_request.Request(meta_url, headers=headers) res = self._download_json(req, token, transform_source=self._transform_meta) if 'getStreamKeyWithSong' not in res: raise ExtractorError( 'Metadata not found. URL may be malformed, or Grooveshark API may have changed.') if res['getStreamKeyWithSong'] is None: raise ExtractorError( 'Metadata download failed, probably due to Grooveshark anti-abuse throttling. Wait at least an hour before retrying from this IP.', expected=True) return res['getStreamKeyWithSong'] def _get_bootstrap(self, target): (bootstrap_url, token) = self._build_bootstrap_url(target) headers = {'Referer': compat_urlparse.urldefrag(target)[0]} req = compat_urllib_request.Request(bootstrap_url, headers=headers) res = self._download_json(req, token, fatal=False, note='Downloading player bootstrap data', errnote='Unable to download player bootstrap data', transform_source=self._transform_bootstrap) return res def _get_playerpage(self, target): (_, _, token) = self._parse_target(target) webpage = self._download_webpage( target, token, note='Downloading player page', errnote='Unable to download player page', fatal=False) if webpage is not None: # Search (for example German) error message error_msg = self._html_search_regex( r'<div id="content">\s*<h2>(.*?)</h2>', webpage, 'error message', default=None) if error_msg is not None: error_msg = error_msg.replace('\n', ' ') raise ExtractorError('Grooveshark said: %s' % error_msg) if webpage is not None: o = GroovesharkHtmlParser.extract_object_tags(webpage) return (webpage, [x for x in o if x['attrs']['id'] == 'jsPlayerEmbed']) return (webpage, None) def _real_initialize(self): self.ts = int(time.time() * 1000) # timestamp in millis def _real_extract(self, url): (target_uri, _, token) = self._parse_target(url) # 1. Fill cookiejar by making a request to the player page swf_referer = None if self.do_playerpage_request: (_, player_objs) = self._get_playerpage(url) if player_objs is not None: swf_referer = self._build_swf_referer(url, player_objs[0]) self.to_screen('SWF Referer: %s' % swf_referer) # 2. Ask preload.php for swf bootstrap data to better mimic webapp if self.do_bootstrap_request: bootstrap = self._get_bootstrap(url) self.to_screen('CommunicationToken: %s' % bootstrap['getCommunicationToken']) # 3. Ask preload.php for track metadata. meta = self._get_meta(url) # 4. Construct stream request for track. stream_url = self._build_stream_url(meta) duration = int(math.ceil(float(meta['streamKey']['uSecs']) / 1000000)) post_dict = {'streamKey': meta['streamKey']['streamKey']} post_data = compat_urllib_parse.urlencode(post_dict).encode('utf-8') headers = { 'Content-Length': len(post_data), 'Content-Type': 'application/x-www-form-urlencoded' } if swf_referer is not None: headers['Referer'] = swf_referer return { 'id': token, 'title': meta['song']['Name'], 'http_method': 'POST', 'url': stream_url, 'ext': 'mp3', 'format': 'mp3 audio', 'duration': duration, 'http_post_data': post_data, 'http_headers': headers, }
unknown
codeparrot/codeparrot-clean
from django.forms.widgets import Widget, HiddenInput, TextInput from django.utils.safestring import mark_safe class AutoCompleteWidget(Widget): """ Widget that presents an <input> field that can be used to search for objects instead of a giant <select> field You will need to include jQuery UI with autocomplete which can be found here: http://jqueryui.com/demos/autocomplete/ Include media: basic/tools/media/stylesheets/autocomplete.css basic/tools/media/javascript/autocomplete.js Example form: from basic.tools.forms import fields class BookForm(forms.Form): authors = forms.ModelMultipleChoiceField( queryset=Author.objects.all(), widget=fields.AutoCompleteWidget(model=Author, url='/autocomplete/') ) Add data URL: url(r'^autocomplete/$', view='basic.tools.views.generic.auto_complete', kwargs={ 'queryset': Author.objects.all() 'fields': ('first_name__icontains', 'last_name__icontains') } ) """ text_field = '%s_auto_complete' hidden_field = '%s' def __init__(self, model, url, attrs=None, required=True): self.attrs = attrs or {} self.required = required self.Model = model self.url = url def render(self, name, value, attrs=None): text_html = self.create_input(TextInput, name, self.text_field) hidden_html = self.create_input(HiddenInput, name, self.hidden_field, value) results = '' if value: object_list = self.Model.objects.filter(pk__in=value) for obj in object_list: results += '<span class="ui-autocomplete-result"><a href="#%s">x</a>%s</span>\n' % (obj.pk, obj.__unicode__()) script = '<script type="text/javascript">new AutoCompleteWidget("id_%s", "%s");</script>' % (self.text_field % name, self.url) return mark_safe(u'\n'.join([text_html, results, hidden_html, script])) def create_input(self, Input, name, field, value=''): id_ = 'id_%s' % name local_attrs = self.build_attrs(id=field % id_) i = Input() if type(value) == list: value = ','.join(['%s' % v for v in value]) input_html = i.render(field % name, value, local_attrs) return input_html def value_from_datadict(self, data, files, name): hidden_data = data.get(self.hidden_field % name) if hidden_data: return hidden_data.split(',') return data.get(name, None)
unknown
codeparrot/codeparrot-clean