hexsha
stringlengths
40
40
size
int64
22
2.4M
ext
stringclasses
5 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
260
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
260
max_issues_repo_name
stringlengths
5
109
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
260
max_forks_repo_name
stringlengths
5
109
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
22
2.4M
avg_line_length
float64
5
169k
max_line_length
int64
5
786k
alphanum_fraction
float64
0.06
0.95
matches
listlengths
1
11
450d40f87b0f38e68bfc7f0b912fcd9fbd492e71
2,031
h
C
dbj++attempto/object_store/dbj_object_store.h
dbj-systems/dbj-laboratorium
ea497f9b68b78797d11bdc41b0f23a310c9325a9
[ "CC0-1.0" ]
2
2019-09-22T12:13:20.000Z
2019-10-24T04:17:33.000Z
dbj++attempto/object_store/dbj_object_store.h
dbj-systems/dbj-laboratorium
ea497f9b68b78797d11bdc41b0f23a310c9325a9
[ "CC0-1.0" ]
9
2019-03-06T06:52:56.000Z
2021-06-14T16:54:11.000Z
dbj++attempto/object_store/dbj_object_store.h
dbj-systems/dbj-laboratorium
ea497f9b68b78797d11bdc41b0f23a310c9325a9
[ "CC0-1.0" ]
1
2019-10-18T14:16:27.000Z
2019-10-18T14:16:27.000Z
#pragma once #include <string_view> #include <any> #include <map> namespace dbj::odm { using namespace std; // keep string_view as the hash made from it // users provide object keys as strings struct object_key { using value_type = size_t; // typename hash<string_view>::result_type; object_key(string_view arg_) : key_(hash<string_view>()(arg_)) { } bool operator == (const object_key& right) const noexcept { return this->key_ == right.key_; } bool operator < (const object_key& right) const noexcept { return this->key_ < right.key_; } const value_type& key() const noexcept { return key_; } private: value_type key_; }; template<typename IMP> struct storage { struct transformer { transformer() = delete; transformer(const any& arg_) : val_(arg_) {} //throws exception on wrong type template<typename T> operator T () const { return any_cast<T>(val_); } private: any val_; }; template <typename T> void store(string_view id, T value) { IMP::setDataImpl(id, any(value)); } template <typename T> T load(string_view id) const { any res = IMP::getDataImpl(id); return any_cast<T>(res); } // simpler user code transformer operator () (string_view id) const { any res = IMP::getDataImpl(id); return { res }; } }; /* in memory object map must understand these two messages void setDataImpl(string_view id, any const& value) ; any getDataImpl(string_view id) ; */ struct storage_map { inline static map< object_key, any > store_; static void setDataImpl(string_view id, any const& value) { store_[object_key( id )] = value; } static any getDataImpl(string_view id) { return store_[object_key(id)]; } }; DBJ_TEST_UNIT( object_storage_test ) { storage<storage_map> odb; odb.store("42", 42); int f42 = odb("42"); DBJ_TEST_ATOM( f42 == 42); struct X { string name_; }; X x{"dbj"}; odb.store("dbj", x); X y = odb("dbj") ; DBJ_TEST_ATOM (y.name_ == x.name_ ); } }
19.911765
65
0.657804
[ "object" ]
450f37e78146507d8c42a62b1d532c048f7bb185
529
h
C
src/fitparser.h
TheSufferfest/node-fit
88bdbab0c54c8e6f9b67298ec300d23b7a54e94f
[ "MIT" ]
1
2021-10-13T15:18:57.000Z
2021-10-13T15:18:57.000Z
src/fitparser.h
WahooFitness/node-fit
88bdbab0c54c8e6f9b67298ec300d23b7a54e94f
[ "MIT" ]
1
2018-09-26T17:38:03.000Z
2018-09-26T17:38:03.000Z
src/fitparser.h
WahooFitness/node-fit
88bdbab0c54c8e6f9b67298ec300d23b7a54e94f
[ "MIT" ]
1
2020-09-28T09:22:46.000Z
2020-09-28T09:22:46.000Z
#ifndef FITPARSER_H #define FITPARSER_H #include <node.h> #include <node_object_wrap.h> class FitParser : public node::ObjectWrap { public: static void Init(v8::Local<v8::Object> exports); private: FitParser(); ~FitParser(); static void New(const v8::FunctionCallbackInfo<v8::Value> &args); static void Decode(const v8::FunctionCallbackInfo<v8::Value> &args); static void Encode(const v8::FunctionCallbackInfo<v8::Value> &args); static v8::Persistent<v8::Function> constructor; }; #endif
23
71
0.706994
[ "object" ]
4544da2c121969f4f0133f030f8cac336aafb38a
1,023
h
C
include/SDRP/Core/Core.h
wrren/srdp
075b361df9f63129776af848ab07382b6d8da909
[ "MIT" ]
null
null
null
include/SDRP/Core/Core.h
wrren/srdp
075b361df9f63129776af848ab07382b6d8da909
[ "MIT" ]
null
null
null
include/SDRP/Core/Core.h
wrren/srdp
075b361df9f63129776af848ab07382b6d8da909
[ "MIT" ]
null
null
null
/************************************************************************ * Radicle Design * * Service Discovery Routing Protocol * * * * Author: Warren Kenny <warren.kenny@gmail.com> * * Platforms: ns-2, Unix, Windows * * * * Copyright 2010 Radicle Design. All rights reserved. * ************************************************************************/ #ifndef RD_SDRP_CORE_H #define RD_SDRP_CORE_H // STL #include <map> #include <set> #include <list> #include <vector> #include <string> #include <memory> #include <iostream> #include <algorithm> // Core #include <SDRP/Core/Types.h> #include <SDRP/Core/Macros.h> #include <SDRP/Core/Exception.h> #include <SDRP/Core/Publisher.h> #include <SDRP/Core/Connection.h> #include <SDRP/Core/ErrorCodes.h> #include <SDRP/Core/Definitions.h> #include <SDRP/Core/BloomFilter.h> #include <SDRP/Core/ISerializable.h> // Utilities #include <SDRP/Utilities/Logger.h> #include <SDRP/Utilities/Serializer.h> #endif // RD_SDRP_CORE_H
24.95122
74
0.59433
[ "vector" ]
45487a95e4d71a6f5931727a2fe0b6d378719609
999
c
C
Module-1/Encapsulation/encap2.c
JackieG19/OOP-Csharp
e9b87ea5c44acb8693985fc8ad545cc99f9d2952
[ "MIT" ]
null
null
null
Module-1/Encapsulation/encap2.c
JackieG19/OOP-Csharp
e9b87ea5c44acb8693985fc8ad545cc99f9d2952
[ "MIT" ]
null
null
null
Module-1/Encapsulation/encap2.c
JackieG19/OOP-Csharp
e9b87ea5c44acb8693985fc8ad545cc99f9d2952
[ "MIT" ]
null
null
null
/* Constructors are often used to specify initial or default values for data members within the new object, as shown by the following example: */ // Adding a Constructor public class DrinksMachine { public int Age { get; set; } public DrinksMachine() { Age = 0; } } /*A constructor that takes no parameters is known as the default constructor. This constructor is called whenever someone instantiates your class without providing any arguments. If you do not include a constructor in your class, the Visual C# compiler will automatically add an empty public default constructor to your compiled class.*/ /* Consumers of your class can use any of the constructors to create instances of your class, depending on the information that is available to them at the time. For example: */ // Calling Constructors: var dm1 = new DrinksMachine(2); var dm2 = new DrinksMachine("Fourth Coffee", "BeanCrusher 3000"); var dm3 = new DrinksMachine(3, "Fourth Coffee", "BeanToaster Turbo");
35.678571
100
0.757758
[ "object" ]
bf969f4b3325886cdeab699509fdfb7b77f68a8d
1,248
h
C
src/core/PipeLib/WinNamedPipe.h
hongweimao/dragonfly
8028ca28fc42097b15402414c3cab2b74daf0873
[ "BSD-3-Clause" ]
14
2016-09-06T02:15:18.000Z
2021-01-08T17:46:17.000Z
src/core/PipeLib/WinNamedPipe.h
hongweimao/dragonfly
8028ca28fc42097b15402414c3cab2b74daf0873
[ "BSD-3-Clause" ]
1
2019-03-06T18:24:15.000Z
2020-01-28T07:18:15.000Z
src/core/PipeLib/WinNamedPipe.h
hongweimao/dragonfly
8028ca28fc42097b15402414c3cab2b74daf0873
[ "BSD-3-Clause" ]
7
2017-10-02T19:24:15.000Z
2021-01-08T17:46:59.000Z
////////////////////////////////////////////////////////////////////// // // WinNamedPipe - represents one end of a bi-directional local named // pipe on a Windows system #ifndef _WINNAMEDPIPE_H_ #define _WINNAMEDPIPE_H_ #include "UPipe.h" extern "C" { #include "../../Util/PipeIO.h" } class WinNamedPipe : public UPipe { public: // Constructs a pipe object from a Windows OS pipe handle WinNamedPipe( PIPE_HANDLE hPipe); // // Overrides of abstract base methods // int GetCapacity( void); int Read( void *data_buffer, int n_bytes, bool blocking); void Write( void *data_buffer, int n_bytes); private: PIPE_HANDLE _hPipe; // Handle to underlying Windows OS pipe }; class WinNamedPipeServer : public UPipeServer { public: // Constructs a Windows named pipe server WinNamedPipeServer( char *server_name); // // Overrides of abstract base methods // public: UPipe* ReceiveData( void *buffer, int n_bytes); protected: void DoDisconnectClient( UPipe *client_pipe); UPipe* DoWaitForClient( void); private: PIPE_HANDLE _listeningPipe; }; class WinNamedPipeClient : public UPipeClient { public: // // Overrides of abstract base methods // UPipe* Connect( void); void Disconnect( void); }; #endif // _WINNAMEDPIPE_H_
20.459016
70
0.690705
[ "object" ]
bf97ae3d1ec5674997f35da835bec549f80dde62
2,298
h
C
Pod/Classes/Core/Operation Queue/OPExclusivityController.h
pronebird/Operative
31a7bb2897fff0a82de78a3ed4dc759d89affc51
[ "MIT" ]
null
null
null
Pod/Classes/Core/Operation Queue/OPExclusivityController.h
pronebird/Operative
31a7bb2897fff0a82de78a3ed4dc759d89affc51
[ "MIT" ]
null
null
null
Pod/Classes/Core/Operation Queue/OPExclusivityController.h
pronebird/Operative
31a7bb2897fff0a82de78a3ed4dc759d89affc51
[ "MIT" ]
null
null
null
// OPExclusivityController.h // Copyright (c) 2015 Tom Wilson <tom@toms-stuff.net> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import <Foundation/Foundation.h> #import "OPOperation.h" /** * `OPExclusivityController` is a singleton to keep track of all the in-flight * `OPOperation` instances that have declared themselves as requiring mutual exclusivity. * We use a singleton because mutual exclusivity must be enforced across the entire * app, regardless of the `OPOperationQueue` on which an `OPOperation` was executed. */ @interface OPExclusivityController : NSObject + (OPExclusivityController *)sharedExclusivityController; /** * Registers an operation as being mutually exclusive * * @param operation OPOperation object which requires exclusivity * @param categories Array of strings describing the name of the category of exclusivity */ - (void)addOperation:(OPOperation *)operation categories:(NSArray *)categories; /** * Unregisters an operation from being mutually exclusive. * * @param operation OPOperation object which requires exclusivity * @param categories Array of strings describing the name of the category of exclusivity */ - (void)removeOperation:(OPOperation *)operation categories:(NSArray *)categories; @end
43.358491
90
0.770235
[ "object" ]
bf9b4ad387a08249806995a8a552676012989d51
3,839
h
C
include/h5rd/File.h
readdy/readdy
ef400db60a29107672a7f2bc42f6c3db4de34eb0
[ "BSD-3-Clause" ]
51
2015-02-24T18:19:34.000Z
2022-03-30T06:57:47.000Z
include/h5rd/File.h
readdy/h5rd
bfcd8a7cd68bb37bf94ca0d2705826289da4c9f1
[ "BSD-3-Clause" ]
81
2016-05-25T22:29:39.000Z
2022-03-28T14:22:18.000Z
include/h5rd/File.h
readdy/h5rd
bfcd8a7cd68bb37bf94ca0d2705826289da4c9f1
[ "BSD-3-Clause" ]
15
2015-03-10T03:16:49.000Z
2021-10-11T11:26:39.000Z
/******************************************************************** * Copyright © 2018 Computational Molecular Biology Group, * * Freie Universität Berlin (GER) * * * * Redistribution and use in source and binary forms, with or * * without modification, are permitted provided that the * * following conditions are met: * * 1. Redistributions of source code must retain the above * * copyright notice, this list of conditions and the * * following disclaimer. * * 2. Redistributions in binary form must reproduce the above * * copyright notice, this list of conditions and the following * * disclaimer in the documentation and/or other materials * * provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of * * its contributors may be used to endorse or promote products * * derived from this software without specific * * prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ********************************************************************/ /** * << detailed description >> * * @file File.h * @brief << brief description >> * @author clonker * @date 05.09.17 * @copyright BSD-3 */ #pragma once #include "Node.h" #include "Object.h" namespace h5rd { class File : public Object, public Node<File>, public std::enable_shared_from_this<Object> { public: enum class Action { CREATE, OPEN }; enum class Flag { READ_ONLY = 0, READ_WRITE, OVERWRITE, FAIL_IF_EXISTS, CREATE_NON_EXISTING, DEFAULT /* = rw, create, truncate */ }; using Flags = std::vector<Flag>; static std::shared_ptr<File> open(const std::string &path, const Flag &flag); static std::shared_ptr<File> open(const std::string &path, const Flags &flags); static std::shared_ptr<File> create(const std::string &path, const Flag &flag); static std::shared_ptr<File> create(const std::string &path, const Flags &flags); File(const File &) = delete; File &operator=(const File &) = delete; File(File &&) = default; File &operator=(File &&) = default; ~File() override; void flush(); void close() override; ParentFileRef ref() const; protected: std::shared_ptr<Object> getptr(); static void setUp(std::shared_ptr<File> file); File(const std::string &path, const Action &action, const Flags &flags); File(const std::string &path, const Action &action, const Flag &flag = Flag::OVERWRITE); std::string path; Action action; Flags flags; }; } #include "detail/File_detail.h"
35.878505
119
0.581662
[ "object", "vector" ]
bfac60c61695563738c8c53c33346266bbecf908
3,067
h
C
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/libnl/1_3.4.0-r0/libnl-3.4.0/include/netlink/netlink.h
sotaoverride/backup
ca53a10b72295387ef4948a9289cb78ab70bc449
[ "Apache-2.0" ]
null
null
null
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/libnl/1_3.4.0-r0/libnl-3.4.0/include/netlink/netlink.h
sotaoverride/backup
ca53a10b72295387ef4948a9289cb78ab70bc449
[ "Apache-2.0" ]
null
null
null
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/libnl/1_3.4.0-r0/libnl-3.4.0/include/netlink/netlink.h
sotaoverride/backup
ca53a10b72295387ef4948a9289cb78ab70bc449
[ "Apache-2.0" ]
null
null
null
/* * netlink/netlink.h Netlink Interface * * This library 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 * of the License. * * Copyright (c) 2003-2013 Thomas Graf <tgraf@suug.ch> */ #ifndef NETLINK_NETLINK_H_ #define NETLINK_NETLINK_H_ #include <linux/genetlink.h> #include <linux/netfilter/nfnetlink.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <netdb.h> #include <netinet/tcp.h> #include <netlink/errno.h> #include <netlink/handlers.h> #include <netlink/netlink-compat.h> #include <netlink/object.h> #include <netlink/socket.h> #include <netlink/types.h> #include <netlink/version.h> #include <poll.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/types.h> #ifdef __cplusplus extern "C" { #endif struct nlmsghdr; struct ucred; struct nl_cache_ops; struct nl_parser_param; struct nl_object; struct nl_sock; extern int nl_debug; extern struct nl_dump_params nl_debug_dp; /* Connection Management */ extern int nl_connect(struct nl_sock*, int); extern void nl_close(struct nl_sock*); /* Send */ extern int nl_sendto(struct nl_sock*, void*, size_t); extern int nl_sendmsg(struct nl_sock*, struct nl_msg*, struct msghdr*); extern int nl_send(struct nl_sock*, struct nl_msg*); extern int nl_send_iovec(struct nl_sock*, struct nl_msg*, struct iovec*, unsigned); extern void nl_complete_msg(struct nl_sock*, struct nl_msg*); extern void nl_auto_complete(struct nl_sock*, struct nl_msg*); extern int nl_send_auto(struct nl_sock*, struct nl_msg*); extern int nl_send_auto_complete(struct nl_sock*, struct nl_msg*); extern int nl_send_sync(struct nl_sock*, struct nl_msg*); extern int nl_send_simple(struct nl_sock*, int, int, void*, size_t); /* Receive */ extern int nl_recv(struct nl_sock*, struct sockaddr_nl*, unsigned char**, struct ucred**); extern int nl_recvmsgs(struct nl_sock*, struct nl_cb*); extern int nl_recvmsgs_report(struct nl_sock*, struct nl_cb*); extern int nl_recvmsgs_default(struct nl_sock*); extern int nl_wait_for_ack(struct nl_sock*); extern int nl_pickup(struct nl_sock*, int (*parser)(struct nl_cache_ops*, struct sockaddr_nl*, struct nlmsghdr*, struct nl_parser_param*), struct nl_object**); extern int nl_pickup_keep_syserr(struct nl_sock* sk, int (*parser)(struct nl_cache_ops*, struct sockaddr_nl*, struct nlmsghdr*, struct nl_parser_param*), struct nl_object** result, int* syserror); /* Netlink Family Translations */ extern char* nl_nlfamily2str(int, char*, size_t); extern int nl_str2nlfamily(const char*); #ifdef __cplusplus } #endif #endif
31.295918
78
0.684056
[ "object" ]
bfb58990f65cd2ded6153efeaacaddce5175337e
2,353
c
C
fmu10/src/models/vanDerPol/vanDerPol.c
chrbertsch/FMUSDK_fork
dcbcecf597c349e849806c3c437be6a60900d552
[ "BSD-2-Clause" ]
null
null
null
fmu10/src/models/vanDerPol/vanDerPol.c
chrbertsch/FMUSDK_fork
dcbcecf597c349e849806c3c437be6a60900d552
[ "BSD-2-Clause" ]
null
null
null
fmu10/src/models/vanDerPol/vanDerPol.c
chrbertsch/FMUSDK_fork
dcbcecf597c349e849806c3c437be6a60900d552
[ "BSD-2-Clause" ]
null
null
null
/* ---------------------------------------------------------------------------* * Copyright QTronic GmbH. All rights reserved. * Sample implementation of an FMU - the Van der Pol oscillator. * See http://en.wikipedia.org/wiki/Van_der_Pol_oscillator * * der(x0) = x1 * der(x1) = mu * ((1 - x0 ^ 2) * x1) - x0; * * start values: x0=2, x1=0, mue=1 * ---------------------------------------------------------------------------*/ // define class name and unique id #define MODEL_IDENTIFIER vanDerPol #define MODEL_GUID "{8c4e810f-3da3-4a00-8276-176fa3c9f000}" // define model size #define NUMBER_OF_REALS 5 #define NUMBER_OF_INTEGERS 0 #define NUMBER_OF_BOOLEANS 0 #define NUMBER_OF_STRINGS 0 #define NUMBER_OF_STATES 2 #define NUMBER_OF_EVENT_INDICATORS 0 // include fmu header files, typedefs and macros #include "fmuTemplate.h" // define all model variables and their value references // conventions used here: // - if x is a variable, then macro x_ is its variable reference // - the vr of a variable is its index in array r, i, b or s // - if k is the vr of a real state, then k+1 is the vr of its derivative #define x0_ 0 #define der_x0_ 1 #define x1_ 2 #define der_x1_ 3 #define mu_ 4 // define state vector as vector of value references #define STATES { x0_, x1_ } // called by fmiInstantiateModel // Set values for all variables that define a start value // Settings used unless changed by fmiSetX before fmiInitialize void setStartValues(ModelInstance *comp) { r(x0_) = 2; r(x1_) = 0; r(mu_) = 1; } // called by fmiInitialize() after setting eventInfo to defaults // Used to set the first time event, if any. void initialize(ModelInstance* comp, fmiEventInfo* eventInfo) { } // called by fmiGetReal, fmiGetContinuousStates and fmiGetDerivatives fmiReal getReal(ModelInstance* comp, fmiValueReference vr){ switch (vr) { case x0_ : return r(x0_); case x1_ : return r(x1_); case der_x0_ : return r(x1_); case der_x1_ : return r(mu_) * ((1.0-r(x0_)*r(x0_))*r(x1_)) - r(x0_); case mu_ : return r(mu_); default: return 0; } } // Used to set the next time event, if any. void eventUpdate(fmiComponent comp, fmiEventInfo* eventInfo) { } // include code that implements the FMI based on the above definitions #include "fmuTemplate.c"
31.373333
80
0.652359
[ "vector", "model" ]
bfba9a7722da4a07751d2573983c2ff2c08aa96e
10,503
h
C
_src/map.h
HerbFargus/Super-Mario-War
9db86a7f2d8d9777636021ac34d83bb142311a5e
[ "Artistic-1.0-cl8" ]
9
2015-09-30T07:21:30.000Z
2021-12-22T11:50:31.000Z
_src/map.h
HerbFargus/Super-Mario-War
9db86a7f2d8d9777636021ac34d83bb142311a5e
[ "Artistic-1.0-cl8" ]
3
2016-02-29T22:36:53.000Z
2021-12-23T10:32:47.000Z
_src/map.h
HerbFargus/Super-Mario-War
9db86a7f2d8d9777636021ac34d83bb142311a5e
[ "Artistic-1.0-cl8" ]
6
2016-09-13T22:10:22.000Z
2019-02-22T00:03:23.000Z
#ifndef SMW_MAP_H #define SMW_MAP_H enum TileType{tile_nonsolid = 0, tile_solid = 1, tile_solid_on_top = 2, tile_ice = 3, tile_death = 4, tile_death_on_top = 5, tile_death_on_bottom = 6, tile_death_on_left = 7, tile_death_on_right = 8, tile_ice_on_top = 9, tile_ice_death_on_bottom = 10, tile_ice_death_on_left = 11, tile_ice_death_on_right = 12, tile_super_death = 13, tile_super_death_top = 14, tile_super_death_bottom = 15, tile_super_death_left = 16, tile_super_death_right = 17, tile_player_death = 18, tile_gap = 19}; enum ReadType{read_type_full = 0, read_type_preview = 1, read_type_summary = 2}; enum TileTypeFlag {tile_flag_nonsolid = 0, tile_flag_solid = 1, tile_flag_solid_on_top = 2, tile_flag_ice = 4, tile_flag_death_on_top = 8, tile_flag_death_on_bottom = 16, tile_flag_death_on_left = 32, tile_flag_death_on_right = 64, tile_flag_gap = 128, tile_flag_has_death = 8056, tile_flag_super_death_top = 256, tile_flag_super_death_bottom = 512, tile_flag_super_death_left = 1024, tile_flag_super_death_right = 2048, tile_flag_player_death = 4096, tile_flag_super_or_player_death_top = 4352, tile_flag_super_or_player_death_bottom = 4608, tile_flag_super_or_player_death_left = 5120, tile_flag_super_or_player_death_right = 6144, tile_flag_player_or_death_on_bottom = 4112}; /* PD SDR SDL SDB SDT G DR DL DB DT I SOT S tile_nonsolid = 0 0 0 0 0 0 0 0 0 0 0 0 0 0 tile_solid = 1 0 0 0 0 0 0 0 0 0 0 0 0 1 tile_solid_on_top = 2 0 0 0 0 0 0 0 0 0 0 0 1 0 tile_ice_on_top = 6 0 0 0 0 0 0 0 0 0 0 1 1 0 tile_ice = 5 0 0 0 0 0 0 0 0 0 0 1 0 1 tile_death = 121 0 0 0 0 0 0 1 1 1 1 0 0 1 tile_death_on_top = 9 0 0 0 0 0 0 0 0 0 1 0 0 1 tile_death_on_bottom = 17 0 0 0 0 0 0 0 0 1 0 0 0 1 tile_death_on_left = 33 0 0 0 0 0 0 0 1 0 0 0 0 1 tile_death_on_right = 65 0 0 0 0 0 0 1 0 0 0 0 0 1 tile_ice_death_on_bottom = 21 0 0 0 0 0 0 0 0 1 0 1 0 1 tile_ice_death_on_left = 37 0 0 0 0 0 0 0 1 0 0 1 0 1 tile_ice_death_on_right = 69 0 0 0 0 0 0 1 0 0 0 1 0 1 tile_gap = 128 0 0 0 0 0 1 0 0 0 0 0 0 0 tile_super_death = 3961 0 1 1 1 1 0 1 1 1 1 0 0 1 tile_super_death_top = 265 0 0 0 0 1 0 0 0 0 1 0 0 1 tile_super_death_bottom = 529 0 0 0 1 0 0 0 0 1 0 0 0 1 tile_super_death_left = 1057 0 0 1 0 0 0 0 1 0 0 0 0 1 tile_super_death_right = 2113 0 1 0 0 0 0 1 0 0 0 0 0 1 tile_player_death = 4096 1 0 0 0 0 0 0 0 0 0 0 0 0 */ class MovingPlatform; struct ScreenPoint { short x, y; }; struct Warp { short direction; short connection; short id; }; struct WarpExit { short direction; short connection; short id; short x; //Player location where player warps out of short y; short lockx; //Location to display lock icon short locky; short warpx; //map grid location for first block in warp short warpy; short numblocks; //number of warp blocks for this warp short locktimer; //If > 0, then warp is locked and has this many frames left until unlock }; struct SpawnArea { short left; short top; short width; short height; short size; }; struct MapItem { short itype; short ix; short iy; }; struct MapHazard { short itype; short ix; short iy; short iparam[NUMMAPHAZARDPARAMS]; float dparam[NUMMAPHAZARDPARAMS]; }; struct TilesetTile { short iID; short iCol; short iRow; }; struct TilesetTranslation { short iID; char szName[128]; }; struct AnimatedTile { short id; TilesetTile layers[4]; SDL_Rect rSrc[4][4]; SDL_Rect rAnimationSrc[2][4]; SDL_Rect rDest; bool fBackgroundAnimated; bool fForegroundAnimated; MovingPlatform * pPlatform; }; struct MapTile { TileType iType; int iFlags; }; struct MapBlock { short iType; short iSettings[NUM_BLOCK_SETTINGS]; bool fHidden; }; class IO_Block; class CMap { public: CMap(); ~CMap(); void clearMap(); void clearPlatforms(); void loadMap(const std::string& file, ReadType iReadType); void saveMap(const std::string& file); SDL_Surface * createThumbnailSurface(bool fUseClassicPack); void saveThumbnail(const std::string &file, bool fUseClassicPack); void UpdateAllTileGaps(); void UpdateTileGap(short i, short j); void loadPlatforms(FILE * mapfile, bool fPreview, int version[4], short * translationid = NULL, short * tilesetwidths = NULL, short * tilesetheights = NULL, short iMaxTilesetID = -1); //void convertMap(); void shift(int xshift, int yshift); void predrawbackground(gfxSprite &background, gfxSprite &mapspr); void predrawforeground(gfxSprite &foregroundspr); void SetupAnimatedTiles(); void preDrawPreviewBackground(SDL_Surface * targetSurface, bool fThumbnail); void preDrawPreviewBackground(gfxSprite * spr_background, SDL_Surface * targetSurface, bool fThumbnail); void preDrawPreviewBlocks(SDL_Surface * targetSurface, bool fThumbnail); void preDrawPreviewForeground(SDL_Surface * targetSurface, bool fThumbnail); void preDrawPreviewWarps(SDL_Surface * targetSurface, bool fThumbnail); void preDrawPreviewMapItems(SDL_Surface * targetSurface, bool fThumbnail); void drawfrontlayer(); bool checkforwarp(short iData1, short iData2, short iData3, short iDirection); void optimize(); //returns the tiletype at the specific position (map coordinates) of the //front most visible tile int map(int x, int y) { return mapdatatop[x][y].iFlags; } IO_Block * block(short x, short y) { return blockdata[x][y]; } Warp * warp(short x, short y) { return &warpdata[x][y]; } MapBlock * blockat(short x, short y) { return &objectdata[x][y]; } bool spawn(short iType, short x, short y) { return !nospawn[iType][x][y]; } void updatePlatforms(); void drawPlatforms(short iLayer); void drawPlatforms(short iOffsetX, short iOffsetY, short iLayer); void resetPlatforms(); void movingPlatformCollision(CPlayer * player); void movingPlatformCollision(IO_MovingObject * object); bool movingPlatformCheckSides(IO_MovingObject * object); bool isconnectionlocked(int connection) {return warplocked[connection];} void lockconnection(int connection); WarpExit * getRandomWarpExit(int connection, int currentID); void clearWarpLocks(); void drawWarpLocks(); void update(); void AddPermanentPlatform(MovingPlatform * platform); void AddTemporaryPlatform(MovingPlatform * platform); bool findspawnpoint(short iType, short * x, short * y, short width, short height, bool tilealigned); bool IsInPlatformNoSpawnZone(short x, short y, short width, short height); char szBackgroundFile[128]; short backgroundID; short eyecandy[3]; short musicCategoryID; short iNumMapItems; short iNumMapHazards; short iNumRaceGoals; short iNumFlagBases; private: void SetTileGap(short i, short j); void calculatespawnareas(short iType, bool fUseTempBlocks, bool fIgnoreDeath); TilesetTile mapdata[MAPWIDTH][MAPHEIGHT][MAPLAYERS]; MapTile mapdatatop[MAPWIDTH][MAPHEIGHT]; MapBlock objectdata[MAPWIDTH][MAPHEIGHT]; IO_Block* blockdata[MAPWIDTH][MAPHEIGHT]; bool nospawn[NUMSPAWNAREATYPES][MAPWIDTH][MAPHEIGHT]; std::vector<AnimatedTile*> animatedtiles; MovingPlatform ** platforms; short iNumPlatforms; std::list<MovingPlatform*> tempPlatforms; MapItem mapitems[MAXMAPITEMS]; MapHazard maphazards[MAXMAPHAZARDS]; SpawnArea spawnareas[NUMSPAWNAREATYPES][MAXSPAWNAREAS]; short numspawnareas[NUMSPAWNAREATYPES]; short totalspawnsize[NUMSPAWNAREATYPES]; Warp warpdata[MAPWIDTH][MAPHEIGHT]; short numwarpexits; //number of warp exits WarpExit warpexits[MAXWARPS]; short warplocktimer[10]; bool warplocked[10]; short maxConnection; SDL_Rect tilebltrect; SDL_Rect bltrect; SDL_Rect drawareas[MAXDRAWAREAS]; short numdrawareas; short iSwitches[4]; std::list<IO_Block*> switchBlocks[8]; bool fAutoFilter[NUM_AUTO_FILTERS]; ScreenPoint racegoallocations[MAXRACEGOALS]; ScreenPoint flagbaselocations[4]; short iTileAnimationTimer; short iTileAnimationFrame; short iAnimatedBackgroundLayers; SDL_Surface * animatedFrontmapSurface; SDL_Surface * animatedBackmapSurface; SDL_Surface * animatedTilesSurface; short iAnimatedTileCount; short iAnimatedVectorIndices[NUM_FRAMES_BETWEEN_TILE_ANIMATION + 1]; std::list<MovingPlatform*> platformdrawlayer[5]; void AnimateTiles(short iFrame); void ClearAnimatedTiles(); void draw(SDL_Surface *targetsurf, int layer); void drawThumbnailHazards(SDL_Surface * targetSurface); void drawThumbnailPlatforms(SDL_Surface * targetSurface); void drawPreview(SDL_Surface * targetsurf, int layer, bool fThumbnail); void drawPreviewBlocks(SDL_Surface * targetSurface, bool fThumbnail); void addPlatformAnimatedTiles(); friend class CPlayerAI; friend void drawmap(bool fScreenshot, short iBlockSize, bool fWithPlatforms); friend void drawlayer(int layer, bool fUseCopied, short iBlocksize); friend void takescreenshot(); friend bool copyselectedtiles(); friend void clearselectedmaptiles(); friend void pasteselectedtiles(int movex, int movey); friend TileType CalculateTileType(short x, short y); friend void UpdateTileType(short x, short y); friend bool TileTypeIsModified(short x, short y); friend void AdjustMapItems(short iClickX, short iClickY); friend void RemoveMapItemAt(short x, short y); friend int editor_edit(); friend int editor_tiles(); friend int editor_blocks(); friend int editor_warp(); friend int editor_modeitems(); friend int editor_properties(short iBlockCol, short iBlockRow); friend int editor_maphazards(); friend short NewMapHazard(); friend short * GetBlockProperty(short x, short y, short iBlockCol, short iBlockRow, short * iSettingIndex); friend int save_as(); friend int load(); friend void LoadMapObjects(bool fPreview); friend void LoadMapHazards(bool fPreview); friend void draw_platform(short iPlatform, bool fDrawTileTypes); friend void insert_platforms_into_map(); friend void loadcurrentmap(); friend void loadmap(char * szMapFile); friend void SetNoSpawn(short nospawnmode, short col, short row, bool value); friend int editor_platforms(); friend class B_BreakableBlock; friend class B_DonutBlock; friend class B_ThrowBlock; friend class B_OnOffSwitchBlock; friend class B_FlipBlock; friend class B_WeaponBreakableBlock; friend class MovingPlatform; friend class MapList; friend class MI_MapField; friend class CPlayer; friend class MO_FlagBase; friend class OMO_RaceGoal; }; #endif
28.618529
678
0.746263
[ "object", "vector" ]
bfc930c183ed23074ee801c717324b7fca0bb2e6
1,152
h
C
gateway/include/controller/ControllerConnection.h
helena-project/beetle
6f07d864c38ea6aed962263eca20ecf8436cfb4e
[ "Apache-2.0" ]
16
2016-06-27T08:08:04.000Z
2020-10-24T21:20:27.000Z
gateway/include/controller/ControllerConnection.h
helena-project/beetle
6f07d864c38ea6aed962263eca20ecf8436cfb4e
[ "Apache-2.0" ]
1
2018-01-23T19:18:06.000Z
2018-01-23T19:18:06.000Z
gateway/include/controller/ControllerConnection.h
helena-project/beetle
6f07d864c38ea6aed962263eca20ecf8436cfb4e
[ "Apache-2.0" ]
2
2018-03-16T08:49:10.000Z
2019-02-14T04:30:03.000Z
/* * ControllerConnection.h * * Created on: Jun 6, 2016 * Author: james */ #ifndef CONTROLLER_CONTROLLERCONNECTION_H_ #define CONTROLLER_CONTROLLERCONNECTION_H_ #include <boost/asio/ip/tcp.hpp> #include <memory> #include <string> #include <thread> #include <vector> #include "BeetleTypes.h" class ControllerClient; class ControllerConnection { public: ControllerConnection(Beetle &beetle, std::shared_ptr<ControllerClient> client, int maxReconnectionAttempts); virtual ~ControllerConnection(); /* * Blocks, waiting for CLI to exit. */ void join(); private: Beetle &beetle; std::shared_ptr<ControllerClient> client; int maxReconnectionAttempts; std::unique_ptr<boost::asio::ip::tcp::iostream> stream; bool getCommand(std::vector<std::string> &ret); bool reconnect(); void doMapLocal(const std::vector<std::string>& cmd); void doUnmapLocal(const std::vector<std::string>& cmd); void doMapRemote(const std::vector<std::string>& cmd); void doUnmapRemote(const std::vector<std::string>& cmd); void socketDaemon(); std::thread daemonThread; bool daemonRunning; }; #endif /* CONTROLLER_CONTROLLERCONNECTION_H_ */
21.333333
109
0.743924
[ "vector" ]
bfca185659cbd0214292d7cc91010a854451112c
3,335
h
C
Source/XLibrary/XIni.h
xylamic/lightrail-pubsub-integration-framework
a7abc543982dca46119c0135af1d31c6f182797c
[ "MIT" ]
1
2019-08-25T13:47:18.000Z
2019-08-25T13:47:18.000Z
Source/XLibrary/XIni.h
xylamic/lightrail-pubsub-integration-framework
a7abc543982dca46119c0135af1d31c6f182797c
[ "MIT" ]
null
null
null
Source/XLibrary/XIni.h
xylamic/lightrail-pubsub-integration-framework
a7abc543982dca46119c0135af1d31c6f182797c
[ "MIT" ]
null
null
null
/*! @file XIni.h @author Adam Jordan This file is part of the Xylasoft Lightrail product. Copyright (c) 2011 Adam Jordan, Xylasoft, All Rights Reserved http://www.xylasoft.com Licensed for use under the MIT License See accompanying LICENSE file for more information */ #ifndef XINI_H #define XINI_H #include "Xylasoft.h" #include <list> namespace Xylasoft { /*! This provides the facilities for reading and writing an INI file. This supports single values with an associated key, and comments on their own lines starting with ; or #. Currently, comments cannot be on the same line as a section name or key/value pair. */ class XIni { public: /*! Construct an empty file. */ XIni(); /*! Construct an object from the specified file. */ XIni(const wchar_t* filepath); /*! Save the contents of the file. @param[in] filepath The path to save the file. */ void Save(const wchar_t* filepath) const; /*! Get the list of keys in the specified section. @param[in] section The section to look up. @returns The list of keys in the section. */ std::list<std::wstring> GetKeysForSection(const wchar_t* section) const; /*! Get the value for the specified key. @param[in] section The section to lookup. @param[in] key The key to lookup. @returns The value found or an empty string if not found. */ std::wstring GetValueForKey(const wchar_t* section, const wchar_t* key) const; /*! Set the value for the specified section and key. @param[in] section The section of the value. @param[in] key The key of the value. @param[in] value The value to write. */ void SetKeyValueForSection(const wchar_t* section, const wchar_t* key, const wchar_t* value); /*! Remove the specified key. @param[in] section The section of the key. @param[in] key The key to remove in the section. */ void RemoveKey(const wchar_t* section, const wchar_t* key); protected: /*! Verify that the given section name is valid. @param[in] section The section name. */ void ValidateSectionName(const wchar_t* section) const; /*! Verify that the given key/value name is valid. @param[in] name The key/value name. */ void ValidateKeyValueName(const wchar_t* name) const; /*! Create the line for a section. @param[in] section The section name. @returns The section line. */ std::wstring CreateSectionLine(const wchar_t* section) const; /*! Create the line for a key/value pair. @param[in] key The key. @param[in] value The value. @returns The key/value line. */ std::wstring CreateKeyValueLine(const wchar_t* key, const wchar_t* value) const; /*! Get whether the given line contains a key/value pair. @param[in] line The line to parse. @param[out] key The key that was parsed. @param[out] value The value that was parsed. @returns True if this was a key/value line, false otherwise. */ bool IsKey(const std::wstring& line, std::wstring& key, std::wstring& value) const; /*! Get whether the given line contains a section pair. @param[in] line The line to parse. @param[out] section The section that was parsed. @returns True if this was a section line, false otherwise. */ bool IsSection(const std::wstring& line, std::wstring& sectionname) const; private: std::list<std::wstring> m_content; }; } #endif
26.259843
95
0.706147
[ "object" ]
bfdc5979c65d98a1393d0eecdae1b54b6ed50f8e
1,554
h
C
TestUtilities/TestRequest.h
Rahul-Bhargav/TestHarness
e0bf34ccd49648c592043b91cb03c17aed0f5d7d
[ "Apache-2.0" ]
null
null
null
TestUtilities/TestRequest.h
Rahul-Bhargav/TestHarness
e0bf34ccd49648c592043b91cb03c17aed0f5d7d
[ "Apache-2.0" ]
null
null
null
TestUtilities/TestRequest.h
Rahul-Bhargav/TestHarness
e0bf34ccd49648c592043b91cb03c17aed0f5d7d
[ "Apache-2.0" ]
null
null
null
#pragma once ///////////////////////////////////////////////////////////////////// // TestRequest.h - Creates and parses Test Requests // // ver 1.0 // // Jim Fawcett, CSE687 - Object Oriented Design, Fall 2018 // ///////////////////////////////////////////////////////////////////// /* * Package Operations: * ------------------- * TestRequest class instances create and parse TestRequests. * Each TestRequest instance holds: * - name: name of test request for display * - author: author of test request * - date: date test request was created * - one or more dll names * * Required Files: * --------------- * TestRequest.h, TestRequest.cpp * Properties.h, Properties.cpp * DateTime.h, DateTime.cpp * StringUtilities.h, StringUtilities.cpp * * Maintenance History: * -------------------- * ver 1.0 : 23 Oct 2018 * - first release */ #include <iostream> #include <string> #include <vector> #include "../Utilities/Properties/Properties.h" #include "../Utilities/DateTime/DateTime.h" #include "../Utilities/StringUtilities/StringUtilities.h" using Name = std::string; using Dll = std::string; using Request = std::vector<Dll>; using Author = std::string; using Date = std::string; using namespace Utilities; class TestRequest { public: Property<Name> name; Property<Request> request; Property<Author> author; Property<Date> date; void addDll(const Dll& dll); std::string toString(); static TestRequest fromString(const std::string& trStr); };
28.777778
69
0.589447
[ "object", "vector" ]
bfdd0c2922e72b645a72c8e474c006a874f41a1d
1,221
h
C
vendor/openfx/OCIOColorSpace.h
mjtitchener-fn/OpenColorIO
00b5362442b9fe954c4b1161fe0cec621fcf1915
[ "BSD-3-Clause" ]
628
2018-08-11T02:18:36.000Z
2022-03-31T15:05:23.000Z
vendor/openfx/OCIOColorSpace.h
mjtitchener-fn/OpenColorIO
00b5362442b9fe954c4b1161fe0cec621fcf1915
[ "BSD-3-Clause" ]
655
2019-04-16T15:15:31.000Z
2022-03-31T18:05:52.000Z
vendor/openfx/OCIOColorSpace.h
mjtitchener-fn/OpenColorIO
00b5362442b9fe954c4b1161fe0cec621fcf1915
[ "BSD-3-Clause" ]
181
2018-12-22T15:39:52.000Z
2022-03-22T09:52:27.000Z
// SPDX-License-Identifier: BSD-3-Clause // Copyright Contributors to the OpenColorIO Project. #ifndef INCLUDED_OFX_OCIOCOLORSPACE_H #define INCLUDED_OFX_OCIOCOLORSPACE_H #include "OCIOUtils.h" #include "ofxsImageEffect.h" class OCIOColorSpace : public OFX::ImageEffect { protected: // Do not need to delete these. The ImageEffect is managing them for us. OFX::Clip *dstClip_; OFX::Clip *srcClip_; OFX::ChoiceParam * srcCsNameParam_; OFX::ChoiceParam * dstCsNameParam_; OFX::BooleanParam * inverseParam_; OFX::PushButtonParam * swapSrcDstParam_; ParamMap contextParams_; public: OCIOColorSpace(OfxImageEffectHandle handle); /* Override the render */ void render(const OFX::RenderArguments & args) override; /* Override identity (~no-op) check */ bool isIdentity(const OFX::IsIdentityArguments & args, OFX::Clip *& identityClip, double & identityTime) override; /* Override changedParam */ void changedParam(const OFX::InstanceChangedArgs & args, const std::string & paramName) override; }; mDeclarePluginFactory(OCIOColorSpaceFactory, {}, {}); #endif // INCLUDED_OFX_OCIOCOLORSPACE_H
27.75
76
0.701884
[ "render" ]
bfe35503396582ac9a1a55d10ab4c105e181e983
485
h
C
DEM/Src/L3/AI/Stimuli/StimulusVisible.h
moltenguy1/deusexmachina
134f4ca4087fff791ec30562cb250ccd50b69ee1
[ "MIT" ]
2
2017-04-30T20:24:29.000Z
2019-02-12T08:36:26.000Z
DEM/Src/L3/AI/Stimuli/StimulusVisible.h
moltenguy1/deusexmachina
134f4ca4087fff791ec30562cb250ccd50b69ee1
[ "MIT" ]
null
null
null
DEM/Src/L3/AI/Stimuli/StimulusVisible.h
moltenguy1/deusexmachina
134f4ca4087fff791ec30562cb250ccd50b69ee1
[ "MIT" ]
null
null
null
#pragma once #ifndef __DEM_L3_AI_STIMULUS_VISIBLE_H__ #define __DEM_L3_AI_STIMULUS_VISIBLE_H__ #include <AI/Perception/Stimulus.h> // Stimulus produced by any visible object. Intensity depends on transparence, brightness etc. namespace AI { class CStimulusVisible: public CStimulus { DeclareRTTI; DeclareFactory(CStimulusVisible); protected: public: }; RegisterFactory(CStimulusVisible); typedef Ptr<CStimulusVisible> PStimulusVisible; } #endif
16.724138
95
0.76701
[ "object" ]
bfe4623e054d00cccee34f755bc5481bee97bb87
178
h
C
python-fastmap.h
definitelyuncertain/fastmap-python-bindings
1ee59f56605f799d568827c9cbdc0f2b0e9e824f
[ "MIT" ]
null
null
null
python-fastmap.h
definitelyuncertain/fastmap-python-bindings
1ee59f56605f799d568827c9cbdc0f2b0e9e824f
[ "MIT" ]
null
null
null
python-fastmap.h
definitelyuncertain/fastmap-python-bindings
1ee59f56605f799d568827c9cbdc0f2b0e9e824f
[ "MIT" ]
null
null
null
#include "def.h" #include "oa.h" #include "object.h" #include "matrix.h" #include "vector.h" #include <stdio.h> void fastmap_raw(double * X, int n, int d, int k, double * out);
19.777778
64
0.668539
[ "object", "vector" ]
3af84938bd5ce6b01020b0d29a91d7abe79a37ad
36,879
c
C
src/core/transform.c
bksaiki/minim
2131da60c07e73831f956e868980725d874ed122
[ "MIT" ]
null
null
null
src/core/transform.c
bksaiki/minim
2131da60c07e73831f956e868980725d874ed122
[ "MIT" ]
null
null
null
src/core/transform.c
bksaiki/minim
2131da60c07e73831f956e868980725d874ed122
[ "MIT" ]
null
null
null
#include "minimpriv.h" #define transform_type(x) (MINIM_OBJ_CLOSUREP(x) ? MINIM_TRANSFORM_MACRO : MINIM_TRANSFORM_UNKNOWN) // forward declaration MinimObject* transform_syntax(MinimEnv *env, MinimObject* ast); // ================================ Match table ================================ typedef struct MatchTable { MinimObject **objs; // associated objects size_t *depths; // pattern depth char **syms; // variable name size_t size; // number of variables } MatchTable; static void init_match_table(MatchTable *table) { table->objs = NULL; table->depths = NULL; table->syms = NULL; table->size = 0; } #define clear_match_table(table) init_match_table(table) static void match_table_add(MatchTable *table, char *sym, size_t depth, MinimObject *obj) { // no add if (strcmp(sym, "...") == 0 || // ellipse strcmp(sym, ".") == 0 || // dot strcmp(sym, "_") == 0) // wildcard return; ++table->size; table->objs = GC_realloc(table->objs, table->size * sizeof(MinimObject*)); table->depths = GC_realloc(table->depths, table->size * sizeof(size_t)); table->syms = GC_realloc(table->syms, table->size * sizeof(char*)); table->objs[table->size - 1] = obj; table->depths[table->size - 1] = depth; table->syms[table->size - 1] = sym; } static size_t match_table_get_depth(MatchTable *table, const char *sym) { for (size_t i = 0; i < table->size; ++i) { if (strcmp(table->syms[i], sym) == 0) return table->depths[i]; } return SIZE_MAX; } typedef struct SymbolList { char **syms; // names size_t size; } SymbolList; static void init_symbol_list(SymbolList *table, size_t size) { table->syms = GC_alloc(size * sizeof(char*)); table->size = size; } static bool symbol_list_contains(SymbolList *list, const char *sym) { for (size_t i = 0; i < list->size; ++i) { if (strcmp(list->syms[i], sym) == 0) return true; } return false; } // ================================ Transform ================================ static bool is_list_match_pattern(MinimObject *lst) { MinimObject *t = MINIM_CDR(lst); if (!MINIM_OBJ_PAIRP(t)) return false; t = MINIM_CAR(t); return MINIM_STX_SYMBOLP(t) && strcmp(MINIM_STX_SYMBOL(t), "...") == 0; } static bool is_vector_match_pattern(MinimObject *vec, size_t i) { return (i + 1 < MINIM_VECTOR_LEN(vec) && MINIM_STX_SYMBOLP(MINIM_VECTOR_REF(vec, i + 1)) && strcmp(MINIM_STX_SYMBOL(MINIM_VECTOR_REF(vec, i + 1)), "...") == 0); } static size_t list_ellipse_pos(MinimObject *lst) { size_t i = 0; for (MinimObject *it = lst; MINIM_OBJ_PAIRP(it); it = MINIM_CDR(it), ++i) { MinimObject *elem = MINIM_CAR(it); if (MINIM_STX_SYMBOLP(elem) && strcmp(MINIM_STX_SYMBOL(elem), "...") == 0) return i; } return 0; } static size_t vector_ellipse_pos(MinimObject *vec) { for (size_t i = 0; i < MINIM_VECTOR_LEN(vec); ++i) { MinimObject *elem = MINIM_VECTOR_REF(vec, i); if (MINIM_STX_SYMBOLP(elem) && strcmp(MINIM_STX_SYMBOL(elem), "...") == 0) return i; } return 0; } static void add_null_variables(MinimEnv *env, MinimObject *stx, SymbolList *reserved, size_t pdepth) { if (MINIM_STX_PAIRP(stx)) { MinimObject *it = MINIM_STX_VAL(stx); for (; MINIM_OBJ_PAIRP(it); it = MINIM_CDR(it)) { if (is_list_match_pattern(it)) { add_null_variables(env, MINIM_CAR(it), reserved, pdepth + 1); it = MINIM_CDR(it); } else { add_null_variables(env, MINIM_CAR(it), reserved, pdepth); } } if (!minim_nullp(it)) add_null_variables(env, MINIM_CAR(it), reserved, pdepth); } else if (MINIM_STX_VECTORP(stx)) { MinimObject *vec = MINIM_STX_VAL(stx); for (size_t i = 0; i < MINIM_VECTOR_LEN(vec); ++i) { if (is_vector_match_pattern(vec, i)) { add_null_variables(env, MINIM_VECTOR_REF(vec, i), reserved, pdepth + 1); ++i; } else { add_null_variables(env, MINIM_VECTOR_REF(vec, i), reserved, pdepth); } } } else if (MINIM_STX_SYMBOLP(stx)) { MinimObject *val; char *str = MINIM_STX_SYMBOL(stx); if (strcmp(str, "...") == 0 || // ellipse strcmp(str, "_") == 0 || // wildcard symbol_list_contains(reserved, str)) // reserved return; val = env_get_sym(env, str); if (val && MINIM_OBJ_TRANSFORMP(val)) // already bound return; val = minim_transform(minim_cons(minim_null, (void*) (pdepth + 1)), MINIM_TRANSFORM_PATTERN); env_intern_sym(env, str, val); } } static MinimObject *merge_pattern(MinimObject *a, MinimObject *b) { MinimObject *t; MINIM_TAIL(t, MINIM_CAR(MINIM_TRANSFORMER(a))); MINIM_CDR(t) = minim_cons(MINIM_CAR(MINIM_TRANSFORMER(b)), minim_null); return a; } static MinimObject *add_pattern(MinimObject *a) { MinimObject *val, *depth; val = MINIM_CAR(MINIM_TRANSFORMER(a)); depth = MINIM_CDR(MINIM_TRANSFORMER(a)); return minim_transform(minim_cons(minim_cons(val, minim_null), depth), MINIM_TRANSFORM_PATTERN); } // static void debug_pattern(MinimObject *o) // { // if (!MINIM_OBJ_TRANSFORMP(o)) // printf("Not a pattern!"); // debug_print_minim_object(MINIM_TRANSFORMER(o), NULL); // } // static void debug_pattern_table(MinimEnv *env, MinimObject *args) // { // PrintParams pp; // MinimObject *sym, *val, *pat; // size_t depth; // set_default_print_params(&pp); // for (size_t i = 0; i < MINIM_VECTOR_LEN(args); ++i) // { // sym = MINIM_CAR(MINIM_VECTOR_REF(args, i)); // pat = MINIM_TRANSFORMER(MINIM_CDR(MINIM_VECTOR_REF(args, i))); // val = MINIM_CAR(pat); // depth = (size_t) MINIM_CDR(pat); // printf("%s[%zu]: ", MINIM_SYMBOL(sym), depth); // debug_print_minim_object(val, NULL); // } // } static bool match_transform(MinimEnv *env, MinimObject *match, MinimObject *stx, SymbolList *reserved, size_t pdepth) { MinimObject *match_e, *stx_e; // printf("match: "); print_syntax_to_port(match, stdout); printf("\n"); // printf("stx: "); print_syntax_to_port(stx, stdout); printf("\n"); match_e = MINIM_STX_VAL(match); stx_e = MINIM_STX_VAL(stx); if (minim_nullp(match_e)) { return minim_nullp(stx_e); } else if (MINIM_OBJ_PAIRP(match_e)) { MinimObject *match_it, *stx_it; size_t match_len, stx_len, ell_pos; if (!MINIM_OBJ_PAIRP(stx_e) && !minim_nullp(stx_e)) return false; match_len = syntax_proper_list_len(match); stx_len = syntax_proper_list_len(stx); ell_pos = list_ellipse_pos(match_e); if (ell_pos != 0) // ellipse in pattern { size_t before, i; // must be a proper list if (stx_len == SIZE_MAX) return false; i = 0; before = ell_pos - 1; match_it = match_e; stx_it = stx_e; while (!minim_nullp(match_it)) { if (i == before) // ellipse encountered { if (stx_len + 2 == match_len) // null { add_null_variables(env, MINIM_CAR(match_it), reserved, pdepth); } else { MinimEnv *env2; MinimObject *after_it; if (stx_len + 2 < match_len) // not long enough return false; env2 = init_env(env); after_it = minim_list_drop(stx_it, stx_len + 2 - match_len); for (; stx_it != after_it; stx_it = MINIM_CDR(stx_it)) { MinimEnv *env3 = init_env(env); if (!match_transform(env3, MINIM_CAR(match_it), MINIM_CAR(stx_it), reserved, pdepth + 1)) return false; env_merge_local_symbols2(env2, env3, merge_pattern, add_pattern); } env_merge_local_symbols(env, env2); } match_it = MINIM_CDR(match_it); if (minim_nullp(match_it)) return false; match_it = MINIM_CDR(match_it); ++i; } else { if (minim_nullp(stx_it)) return false; if (!match_transform(env, MINIM_CAR(match_it), MINIM_CAR(stx_it), reserved, pdepth)) return false; match_it = MINIM_CDR(match_it); ++i; if (minim_nullp(stx_it)) return minim_nullp(match_it); stx_it = MINIM_CDR(stx_it); } } } else { if (match_len == SIZE_MAX) match_len = syntax_list_len(match); if (stx_len == SIZE_MAX) stx_len = syntax_list_len(stx); match_it = match_e; stx_it = stx_e; while (MINIM_OBJ_PAIRP(match_it)) { if (minim_nullp(stx_it)) return false; if (!match_transform(env, MINIM_CAR(match_it), MINIM_CAR(stx_it), reserved, pdepth)) return false; match_it = MINIM_CDR(match_it); stx_it = MINIM_CDR(stx_it); } } // proper list if (minim_nullp(match_it)) return minim_nullp(stx_it); // reform syntax stx = datum_to_syntax(env, stx_it); return match_transform(env, match_it, stx, reserved, pdepth); } if (MINIM_STX_VECTORP(match)) { size_t match_len, stx_len, ell_pos; // early exit not a vector if (!MINIM_OBJ_VECTORP(stx_e)) return false; // empty vector match_len = MINIM_VECTOR_LEN(match_e); stx_len = MINIM_VECTOR_LEN(stx_e); if (match_len == 0) return stx_len == 0; ell_pos = vector_ellipse_pos(match_e); if (ell_pos != 0) // ellipse in pattern { size_t before, after; before = ell_pos - 1; after = match_len - ell_pos - 1; // not enough space if (stx_len < before + after) return false; // try matching front for (size_t i = 0; i < before; ++i) { if (!match_transform(env, MINIM_VECTOR_REF(match_e, i), MINIM_VECTOR_REF(stx_e, i), reserved, pdepth)) return false; } if (stx_len == before + after) { // Bind null add_null_variables(env, MINIM_VECTOR_REF(match_e, ell_pos - 1), reserved, pdepth); return true; } else { MinimEnv *env2 = init_env(env); for (size_t i = before; i < stx_len - after; ++i) { MinimEnv *env3 = init_env(env); if (!match_transform(env3, MINIM_VECTOR_REF(match_e, ell_pos - 1), MINIM_VECTOR_REF(stx_e, i), reserved, pdepth + 1)) return false; env_merge_local_symbols2(env2, env3, merge_pattern, add_pattern); } env_merge_local_symbols(env, env2); } for (size_t i = ell_pos + 1, j = stx_len - after; i < match_len; ++i, ++j) { if (!match_transform(env, MINIM_VECTOR_REF(match_e, i), MINIM_VECTOR_REF(stx_e, i), reserved, pdepth)) return false; } } else { if (match_len != stx_len) return false; for (size_t i = 0; i < match_len; ++i) { if (!match_transform(env, MINIM_VECTOR_REF(match_e, i), MINIM_VECTOR_REF(stx_e, i), reserved, pdepth)) return false; } } return true; } else if (MINIM_OBJ_SYMBOLP(match_e)) { MinimObject *val, *pattern; if (strcmp(MINIM_SYMBOL(match_e), "_") == 0) // wildcard return true; if (symbol_list_contains(reserved, MINIM_SYMBOL(match_e))) // reserved name { return MINIM_OBJ_SYMBOLP(stx_e) && strcmp(MINIM_SYMBOL(match_e), MINIM_SYMBOL(stx_e)) == 0; } pattern = env_get_sym(env, MINIM_SYMBOL(match_e)); if (pattern && MINIM_OBJ_TRANSFORMP(pattern) && MINIM_TRANSFORM_TYPE(pattern) == MINIM_TRANSFORM_PATTERN) { return minim_equalp(MINIM_TRANSFORMER(pattern), stx_e); } val = minim_transform(minim_cons(stx_e, (void*) pdepth), MINIM_TRANSFORM_PATTERN); env_intern_sym(env, MINIM_SYMBOL(match_e), val); return true; } else { return minim_eqp(match_e, stx_e); } return false; } static void get_patterns(MinimEnv *env, MinimObject *stx, MinimObject **patterns) { if (MINIM_STX_PAIRP(stx)) { MinimObject *trailing = NULL; for (MinimObject *it = MINIM_STX_VAL(stx); MINIM_OBJ_PAIRP(it); it = MINIM_CDR(it)) { get_patterns(env, MINIM_CAR(it), patterns); trailing = it; } if (trailing && !minim_nullp(MINIM_CDR(trailing))) get_patterns(env, MINIM_CDR(trailing), patterns); } else if (MINIM_STX_VECTORP(stx)) { MinimObject *vec = MINIM_STX_VAL(stx); for (size_t i = 0; i < MINIM_VECTOR_LEN(vec); ++i) get_patterns(env, MINIM_VECTOR_REF(vec, i), patterns); } else if (MINIM_STX_SYMBOLP(stx)) { MinimObject *val; char *sym = MINIM_STX_SYMBOL(stx); if (strcmp(sym, "...") == 0 || strcmp(sym, ".") == 0) // early exit return; val = env_get_sym(env, sym); if (MINIM_OBJ_TRANSFORMP(val) && MINIM_TRANSFORM_TYPE(val) == MINIM_TRANSFORM_PATTERN) { size_t old_size; for (size_t i = 0; i < MINIM_VECTOR_LEN(*patterns); ++i) { MinimObject *key = MINIM_CAR(MINIM_VECTOR_REF(*patterns, i)); if (strcmp(MINIM_SYMBOL(key), sym) == 0) return; // already in list } old_size = MINIM_VECTOR_LEN(*patterns); MINIM_VECTOR_RESIZE(*patterns, old_size + 1); MINIM_VECTOR_REF(*patterns, old_size) = minim_cons(intern(MINIM_STX_SYMBOL(stx)), val); } } } static void next_patterns_rec(MinimEnv *env, MinimObject *stx, MinimObject *pats, MinimObject **npats) { if (MINIM_STX_PAIRP(stx)) { MinimObject *trailing = NULL; for (MinimObject *it = MINIM_STX_VAL(stx); MINIM_OBJ_PAIRP(it); it = MINIM_CDR(it)) { next_patterns_rec(env, MINIM_CAR(it), pats, npats); trailing = it; } if (trailing && !minim_nullp(MINIM_CDR(trailing))) next_patterns_rec(env, MINIM_CDR(trailing), pats, npats); } else if (MINIM_STX_VECTORP(stx)) { MinimObject *vec = MINIM_STX_VAL(stx); for (size_t i = 0; i < MINIM_VECTOR_LEN(vec); ++i) next_patterns_rec(env, MINIM_VECTOR_REF(vec, i), pats, npats); } else if (MINIM_STX_SYMBOLP(stx)) { char *name; if (strcmp(MINIM_STX_SYMBOL(stx), "...") == 0 || strcmp(MINIM_STX_SYMBOL(stx), ".") == 0) // early exit return; for (size_t i = 0; i < MINIM_VECTOR_LEN(pats); ++i) { name = MINIM_SYMBOL(MINIM_CAR(MINIM_VECTOR_REF(pats, i))); if (strcmp(MINIM_STX_SYMBOL(stx), name) == 0) // in pats { size_t old_size; for (size_t j = 0; j < MINIM_VECTOR_LEN(*npats); ++j) { name = MINIM_SYMBOL(MINIM_CAR(MINIM_VECTOR_REF(*npats, j))); if (strcmp(MINIM_STX_SYMBOL(stx), name) == 0) // in npats return; } old_size = MINIM_VECTOR_LEN(*npats); MINIM_VECTOR_RESIZE(*npats, old_size + 1); MINIM_VECTOR_REF(*npats, old_size) = MINIM_VECTOR_REF(pats, i); } } } } // Gathers pattern variables in the ast if they are also in `pats` static MinimObject * next_patterns(MinimEnv *env, MinimObject *stx, MinimObject *pats) { MinimObject *npats; npats = minim_vector(0); next_patterns_rec(env, stx, pats, &npats); return npats; } static size_t pattern_length(MinimObject *patterns) { MinimObject *trans; size_t depth; for (size_t i = 0; i < MINIM_VECTOR_LEN(patterns); ++i) { trans = MINIM_TRANSFORMER(MINIM_CDR(MINIM_VECTOR_REF(patterns, i))); depth = (size_t) MINIM_CDR(trans); if (depth > 0) return minim_list_length(MINIM_CAR(trans)); } // Panic!! THROW(NULL, minim_error("template contains no pattern variable before ellipse", "syntax-case")); return 0; } static MinimObject * next_depth_patterns(MinimEnv *env, MinimObject *fpats, size_t plen, size_t pc, size_t j) { MinimObject *npats, *sym, *trans, *val; size_t depth; npats = minim_vector(pc); for (size_t k = 0; k < pc; ++k) { sym = MINIM_CAR(MINIM_VECTOR_REF(fpats, k)); trans = MINIM_TRANSFORMER(MINIM_CDR(MINIM_VECTOR_REF(fpats, k))); val = MINIM_CAR(trans); depth = (size_t) MINIM_CDR(trans); if (depth > 0) { PrintParams pp; Buffer *bf; if (j == 0 && minim_list_length(val) != plen) { init_buffer(&bf); set_default_print_params(&pp); writes_buffer(bf, "pattern length mismatch: "); print_to_buffer(bf, val, env, &pp); THROW(env, minim_error(get_buffer(bf), NULL)); } val = minim_cons(minim_list_ref(val, j), (void*)(depth - 1)); trans = minim_transform(val, MINIM_TRANSFORM_PATTERN); MINIM_VECTOR_REF(npats, k) = minim_cons(sym, trans); } else { MINIM_VECTOR_REF(npats, k) = MINIM_VECTOR_REF(fpats, k); } } return npats; } static MinimObject * get_pattern(const char *sym, MinimObject *pats) { for (size_t i = 0; i < MINIM_VECTOR_LEN(pats); ++i) { if (strcmp(sym, MINIM_SYMBOL(MINIM_CAR(MINIM_VECTOR_REF(pats, i)))) == 0) return MINIM_CAR(MINIM_TRANSFORMER(MINIM_CDR(MINIM_VECTOR_REF(pats, i)))); } return NULL; } static MinimObject * apply_transformation(MinimEnv *env, MinimObject *stx, MinimObject *patterns) { // printf("trans: "); print_syntax_to_port(stx, stdout); printf("\n"); // debug_pattern_table(env, patterns); if (MINIM_STX_PAIRP(stx)) { MinimObject *hd, *tl, *trailing; hd = minim_null; tl = NULL; trailing = NULL; for (MinimObject *it = MINIM_STX_VAL(stx); MINIM_OBJ_PAIRP(it); it = MINIM_CDR(it)) { if (is_list_match_pattern(it)) { MinimObject *fpats; size_t plen, pc; fpats = next_patterns(env, MINIM_CAR(it), patterns); plen = pattern_length(fpats); pc = MINIM_VECTOR_LEN(fpats); if (plen != 0) { for (size_t j = 0; j < plen; ++j) { MinimObject *npats, *val; npats = next_depth_patterns(env, fpats, plen, pc, j); val = apply_transformation(env, MINIM_CAR(it), npats); if (tl != NULL) // list already started { MINIM_CDR(tl) = minim_cons(val, minim_null); tl = MINIM_CDR(tl); } else // start of list { hd = minim_cons(val, minim_null); tl = hd; } } } it = MINIM_CDR(it); } else { MinimObject *val = apply_transformation(env, MINIM_CAR(it), patterns); if (tl != NULL) // list already started { MINIM_CDR(tl) = minim_cons(val, minim_null); tl = MINIM_CDR(tl); } else // start of list { hd = minim_cons(val, minim_null); tl = hd; } } trailing = it; } // check for improper lists if (trailing && !minim_nullp(MINIM_CDR(trailing))) { MinimObject *rest = apply_transformation(env, MINIM_CDR(trailing), patterns); if (hd == trailing) // cons cell { MINIM_CDR(hd) = rest; return stx; } else // trailing { return minim_ast(minim_list_append2(hd, MINIM_STX_VAL(rest)), NULL); } } else { return minim_ast(hd, NULL); } } else if (MINIM_STX_VECTORP(stx)) { MinimObject *vec, *res; size_t len; vec = MINIM_STX_VAL(stx); len = MINIM_VECTOR_LEN(vec); res = minim_vector(len); for (size_t i = 0, r = 0; i < len; ++i, ++r) { if (is_vector_match_pattern(vec, i)) { MinimObject *fpats; size_t plen, pc; fpats = next_patterns(env, MINIM_VECTOR_REF(vec, i), patterns); plen = pattern_length(fpats); pc = MINIM_VECTOR_LEN(fpats); if (plen == 0) len -= 2; // reduce by 2 else if (plen == 1) len -= 1; // reduce by 1 else if (plen > 2) len -= (plen - 2); // expand by plen - 2 MINIM_VECTOR_RESIZE(res, len); if (plen != 0) { for (size_t j = 0; j < plen; ++j) { MinimObject *npats = next_depth_patterns(env, fpats, plen, pc, j); MINIM_VECTOR_REF(res, r + j) = apply_transformation(env, MINIM_VECTOR_REF(vec, i), npats); } } i += 1; r = (r + plen) - 1; } else { MINIM_VECTOR_REF(res, r) = apply_transformation(env, MINIM_VECTOR_REF(vec, i), patterns); } } return minim_ast(res, NULL); } else if (MINIM_STX_SYMBOLP(stx)) { MinimObject *v = get_pattern(MINIM_STX_SYMBOL(stx), patterns); if (!v) return minim_ast(MINIM_STX_VAL(stx), MINIM_STX_LOC(stx)); else if (MINIM_OBJ_ASTP(v)) return minim_ast(MINIM_STX_VAL(v), MINIM_STX_LOC(v)); else return datum_to_syntax(env, v); } else { return minim_ast(MINIM_STX_VAL(stx), MINIM_STX_LOC(stx)); } } MinimObject* transform_loc(MinimEnv *env, MinimObject *trans, MinimObject *stx) { MinimObject *res; if (MINIM_TRANSFORM_TYPE(trans) != MINIM_TRANSFORM_MACRO) { THROW(env, minim_syntax_error("illegal use of syntax transformer", MINIM_STX_SYMBOL(stx), stx, NULL)); } res = eval_lambda2(MINIM_CLOSURE(MINIM_TRANSFORMER(trans)), env, 1, &stx); if (!MINIM_OBJ_ASTP(res)) { THROW(env, minim_syntax_error("expected syntax as a result", MINIM_STX_SYMBOL(stx), stx, res)); } return res; } static bool valid_matchp(MinimEnv *env, MinimObject* match, MatchTable *table, SymbolList *reserved, size_t pdepth) { if (MINIM_STX_PAIRP(match)) { MinimObject *trailing = NULL; for (MinimObject *it = MINIM_STX_VAL(match); MINIM_OBJ_PAIRP(it); it = MINIM_CDR(it)) { if (is_list_match_pattern(it)) { if (!valid_matchp(env, MINIM_CAR(it), table, reserved, pdepth + 1)) return false; it = MINIM_CDR(it); // skip ellipse } else { if (!valid_matchp(env, MINIM_CAR(it), table, reserved, pdepth)) return false; } trailing = it; } // improper list if (trailing && !minim_nullp(MINIM_CDR(trailing)) && !valid_matchp(env, MINIM_CDR(trailing), table, reserved, pdepth)) return false; } else if (MINIM_STX_VECTORP(match)) { MinimObject *vec = MINIM_STX_VAL(match); for (size_t i = 0; i < MINIM_VECTOR_LEN(vec); ++i) { if (is_vector_match_pattern(vec, i)) { if (!valid_matchp(env, MINIM_VECTOR_REF(vec, i), table, reserved, pdepth + 1)) return false; ++i; // skip ellipse } else { if (!valid_matchp(env, MINIM_VECTOR_REF(vec, i), table, reserved, pdepth)) return false; } } } else if (MINIM_STX_SYMBOLP(match)) { if (strcmp(MINIM_STX_SYMBOL(match), "...") == 0) { THROW(env, minim_syntax_error("ellipse not allowed here", NULL, match, NULL)); return false; } if (!symbol_list_contains(reserved, MINIM_STX_SYMBOL(match)) && strcmp(MINIM_STX_SYMBOL(match), "_") != 0) match_table_add(table, MINIM_STX_SYMBOL(match), pdepth, minim_null); } return true; } static bool valid_replacep(MinimEnv *env, MinimObject* replace, MatchTable *table, SymbolList *reserved, size_t pdepth) { if (MINIM_STX_PAIRP(replace)) { MinimObject *trailing = NULL; for (MinimObject *it = MINIM_STX_VAL(replace); MINIM_OBJ_PAIRP(it); it = MINIM_CDR(it)) { if (is_list_match_pattern(it)) { if (!valid_replacep(env, MINIM_CAR(it), table, reserved, pdepth + 1)) return false; it = MINIM_CDR(it); // skip ellipse } else { if (!valid_replacep(env, MINIM_CAR(it), table, reserved, pdepth)) return false; } trailing = it; } // improper list if (trailing && !minim_nullp(MINIM_CDR(trailing)) && !valid_replacep(env, MINIM_CDR(trailing), table, reserved, pdepth)) { return false; } } else if (MINIM_STX_VECTORP(replace)) { MinimObject *vec = MINIM_STX_VAL(replace); for (size_t i = 0; i < MINIM_VECTOR_LEN(vec); ++i) { if (is_vector_match_pattern(vec, i)) { if (!valid_replacep(env, MINIM_VECTOR_REF(vec, i), table, reserved, pdepth + 1)) return false; ++i; // skip ellipse } else { if (!valid_replacep(env, MINIM_VECTOR_REF(vec, i), table, reserved, pdepth)) return false; } } } else if (MINIM_STX_SYMBOLP(replace)) { if (!symbol_list_contains(reserved, MINIM_SYMBOL(replace))) { size_t depth = match_table_get_depth(table, MINIM_SYMBOL(replace)); if (depth != SIZE_MAX && pdepth < depth) // in table but too deep { THROW(env, minim_syntax_error("too many ellipses in pattern", NULL, replace, NULL)); return false; } } } return true; } // ================================ Public ================================ MinimObject* transform_syntax(MinimEnv *env, MinimObject* stx) { if (MINIM_STX_PAIRP(stx)) { MinimObject *trailing; if (MINIM_STX_SYMBOLP(MINIM_STX_CAR(stx))) { MinimObject *op = env_get_sym(env, MINIM_STX_SYMBOL(MINIM_STX_CAR(stx))); if (op) { if (MINIM_OBJ_SYNTAXP(op)) { if (MINIM_SYNTAX(op) == minim_builtin_template || MINIM_SYNTAX(op) == minim_builtin_syntax || MINIM_SYNTAX(op) == minim_builtin_quote || MINIM_SYNTAX(op) == minim_builtin_quasiquote) { return stx; } if (MINIM_SYNTAX(op) == minim_builtin_def_syntaxes) { MinimObject *drop2 = minim_list_drop(MINIM_STX_VAL(stx), 2); MINIM_CAR(drop2) = transform_syntax(env, MINIM_CAR(drop2)); return stx; } if (MINIM_SYNTAX(op) == minim_builtin_syntax_case) { MinimObject *it, *r; it = minim_list_drop(MINIM_STX_VAL(stx), 3); while (!minim_nullp(it)) { r = MINIM_STX_CDR(MINIM_CAR(it)); MINIM_CAR(r) = transform_syntax(env, MINIM_CAR(r)); it = MINIM_CDR(it); } return stx; } } else if (MINIM_OBJ_TRANSFORMP(op)) { MinimObject *trans; // printf("t> "); print_syntax_to_port(stx, stdout); printf("\n"); trans = transform_loc(env, op, stx); // printf("t< "); print_syntax_to_port(trans, stdout); printf("\n"); return transform_syntax(env, trans); } } } trailing = NULL; for (MinimObject *it = MINIM_STX_VAL(stx); MINIM_OBJ_PAIRP(it); it = MINIM_CDR(it)) { MINIM_CAR(it) = transform_syntax(env, MINIM_CAR(it)); trailing = it; } if (trailing && !minim_nullp(MINIM_CDR(trailing))) { trailing = MINIM_CDR(trailing); MINIM_CAR(trailing) = transform_syntax(env, MINIM_CAR(trailing)); } } else if (MINIM_STX_VECTORP(stx)) { MinimObject *vec = MINIM_STX_VAL(stx); for (size_t i = 0; i < MINIM_VECTOR_LEN(vec); ++i) MINIM_VECTOR_REF(vec, i) = transform_syntax(env, MINIM_VECTOR_REF(vec, i)); } else if (MINIM_STX_SYMBOLP(stx)) { MinimObject *val = env_get_sym(env, MINIM_STX_SYMBOL(stx)); if (val && MINIM_OBJ_TRANSFORMP(val)) return transform_syntax(env, transform_loc(env, val, stx)); } return stx; } void check_transform(MinimEnv *env, MinimObject *match, MinimObject *replace, MinimObject *reserved) { MatchTable table; SymbolList reserved_lst; MinimObject *it; size_t reservedc; reservedc = syntax_list_len(reserved); init_symbol_list(&reserved_lst, reservedc); it = MINIM_STX_VAL(reserved); for (size_t i = 0; i < reservedc; ++i, it = MINIM_CDR(it)) reserved_lst.syms[i] = MINIM_STX_SYMBOL(MINIM_CAR(it)); init_match_table(&table); valid_matchp(env, match, &table, &reserved_lst, 0); valid_replacep(env, replace, &table, &reserved_lst, 0); } // ================================ Builtins ================================ MinimObject *minim_builtin_def_syntaxes(MinimEnv *env, size_t argc, MinimObject **args) { MinimObject *val, *trans; size_t bindc; bindc = syntax_list_len(args[0]); val = eval_ast_no_check(env, transform_syntax(env, args[1])); if (!MINIM_OBJ_VALUESP(val)) { if (bindc != 1) { THROW(env, minim_values_arity_error("def-syntaxes", bindc, 1, args[0])); } if (!MINIM_OBJ_CLOSUREP(val)) { THROW(env, minim_syntax_error("expected a procedure of 1 argument", "def-syntaxes", args[1], NULL)); } trans = minim_transform(val, transform_type(val)); env_intern_sym(env, MINIM_STX_SYMBOL(MINIM_STX_CAR(args[0])), trans); } else { MinimObject *it; if (MINIM_VALUES_SIZE(val) != bindc) { THROW(env, minim_values_arity_error("def-values", bindc, MINIM_VALUES_SIZE(val), args[0])); } it = MINIM_STX_VAL(args[0]); for (size_t i = 0; i < bindc; ++i) { env_intern_sym(env, MINIM_STX_SYMBOL(MINIM_CAR(it)), MINIM_VALUES(val)[i]); it = MINIM_STX_CDR(it); } } return minim_void; } MinimObject *minim_builtin_template(MinimEnv *env, size_t argc, MinimObject **args) { // Stores pattern data in a vector where each element // is a pair => (name, val) MinimObject *patterns; MinimObject *final; patterns = minim_vector(0); get_patterns(env, args[0], &patterns); // printf("template: "); print_syntax_to_port(args[0], stdout); printf("\n"); // debug_pattern_table(env, patterns); final = apply_transformation(env, args[0], patterns); // printf("final: "); print_syntax_to_port(final, stdout); printf("\n"); return final; } MinimObject *minim_builtin_syntax_case(MinimEnv *env, size_t argc, MinimObject **args) { SymbolList reserved; MinimObject *it, *datum; size_t resc; it = MINIM_STX_VAL(args[1]); resc = syntax_list_len(args[1]); init_symbol_list(&reserved, resc); for (size_t i = 0; i < resc; ++i) { reserved.syms[i] = MINIM_STX_SYMBOL(MINIM_CAR(it)); it = MINIM_CDR(it); } datum = eval_ast_no_check(env, args[0]); for (size_t i = 2; i < argc; ++i) { MinimObject *match, *replace; MinimEnv *match_env; match_env = init_env(NULL); match = MINIM_STX_CAR(args[i]); replace = MINIM_STX_CADR(args[i]); if (match_transform(match_env, match, datum, &reserved, 0)) { MinimEnv *env2; MinimObject *val, *trans; // printf("match: "); print_syntax_to_port(match, stdout); printf("\n"); // printf("replace: "); print_syntax_to_port(replace, stdout); printf("\n"); env2 = init_env(env); env_merge_local_symbols(env2, match_env); env2->flags &= ~MINIM_ENV_TAIL_CALLABLE; val = eval_ast_no_check(env2, replace); if (!MINIM_OBJ_ASTP(val)) THROW(env, minim_error("expected syntax as result", "syntax-case")); // printf("sc>: "); debug_print_minim_object(datum, NULL); // printf("sc<: "); debug_print_minim_object(val, NULL); trans = transform_syntax(env, val); return minim_ast(MINIM_STX_VAL(trans), MINIM_STX_LOC(args[0])); } } THROW(env, minim_syntax_error("bad syntax", NULL, datum_to_syntax(env, datum), NULL)); return NULL; }
31.655794
114
0.513653
[ "vector", "transform" ]
d7079ba2b7119e2452c6f24323ecbb27fdf51c2f
4,701
h
C
development/Common/Render/include/VTS/RenderConfigAssets.h
eglowacki/zloty
9c864ae0beb1ac64137a096795261768b7fc6710
[ "MIT" ]
null
null
null
development/Common/Render/include/VTS/RenderConfigAssets.h
eglowacki/zloty
9c864ae0beb1ac64137a096795261768b7fc6710
[ "MIT" ]
44
2018-06-28T03:01:44.000Z
2022-03-20T19:53:00.000Z
development/Common/Render/include/VTS/RenderConfigAssets.h
eglowacki/zloty
9c864ae0beb1ac64137a096795261768b7fc6710
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////// // RenderConfigAssets.h // // Copyright 9/7/2019 Edgar Glowacki // // Maintained by: Edgar // // NOTES: // Provides render/device configuration files // // // #include "VTS/RenderConfigAssets.h" // ////////////////////////////////////////////////////////////////////// //! \file #pragma once #include "YagetCore.h" #include "VTS/RenderResolvedAssets.h" namespace yaget { namespace io::render { //------------------------------------------------------------------------------------------------------------------------------- // D3D_DRIVER_TYPE // std::vector<D3D_FEATURE_LEVEL> // DebugLayer (bool) // BufferCount // MultiSample // DXGI_FORMAT (BufferFormat) class DeviceAsset : public JasonMetaDataAsset<D3D_DRIVER_TYPE, std::vector<D3D_FEATURE_LEVEL>, bool, uint32_t, uint32_t, DXGI_FORMAT> { public: DeviceAsset(const yaget::io::Tag& tag, yaget::io::Buffer buffer, const yaget::io::VirtualTransportSystem& vts) : JasonMetaDataAsset(tag, buffer, vts, "Device", []() { return true; }, [this]() { return json::GetValue<D3D_DRIVER_TYPE>(root, "DeviceType", D3D_DRIVER_TYPE_HARDWARE); }, [this]() { return json::GetValue<std::vector<D3D_FEATURE_LEVEL>>(root, "FeatureLevels", {}); }, [this]() { return json::GetValue<bool>(root, "DebugLayer", false); }, [this]() { return json::GetValue<uint32_t>(root, "BufferCount", 2); }, [this]() { return json::GetValue<uint32_t>(root, "MultiSample", 1); }, [this]() { return json::GetValue<DXGI_FORMAT>(root, "BufferFormat", DXGI_FORMAT_R8G8B8A8_UNORM); }) , mType(std::get<0>(mFields)) , mFeatureLevels(std::get<1>(mFields)) , mDebugLayer(std::get<2>(mFields)) , mBufferCount(std::get<3>(mFields)) , mMultiSample(std::get<4>(mFields)) , mBufferFormat(std::get<5>(mFields)) {} const D3D_DRIVER_TYPE& mType; const std::vector<D3D_FEATURE_LEVEL>& mFeatureLevels; const bool& mDebugLayer; const uint32_t& mBufferCount; const uint32_t& mMultiSample; const DXGI_FORMAT& mBufferFormat; }; } // namespace io::render namespace conv { //------------------------------------------------------------------------------------------------------------------------------- template <> struct Convertor<D3D_DRIVER_TYPE> { static std::string ToString(const D3D_DRIVER_TYPE& value) { return fmt::format("D3D_DRIVER_TYPE: '{}'", value); } }; //------------------------------------------------------------------------------------------------------------------------------- template <> struct Convertor<std::vector<D3D_FEATURE_LEVEL>> { static std::string ToString(const std::vector<D3D_FEATURE_LEVEL>& value) { std::string result = fmt::format("D3D_FEATURE_LEVELS: '{}' [", value.size()); std::string delim; for (const auto& v : value) { result += delim; result += fmt::format("'{}'", v); delim = ", "; } result += "]"; return result; } }; } // namespace conv } // namespace yaget NLOHMANN_JSON_SERIALIZE_ENUM(D3D_DRIVER_TYPE, { { D3D_DRIVER_TYPE_HARDWARE, nullptr }, { D3D_DRIVER_TYPE_HARDWARE, "Hardware" }, { D3D_DRIVER_TYPE_REFERENCE, "Reference" }, { D3D_DRIVER_TYPE_NULL, "Null" } }); NLOHMANN_JSON_SERIALIZE_ENUM(D3D_FEATURE_LEVEL, { { D3D_FEATURE_LEVEL_11_0, nullptr }, { D3D_FEATURE_LEVEL_9_1, "9_1" }, { D3D_FEATURE_LEVEL_9_2, "9_2" }, { D3D_FEATURE_LEVEL_10_0, "10_0" }, { D3D_FEATURE_LEVEL_10_1, "10_1" }, { D3D_FEATURE_LEVEL_11_0, "11_0" }, { D3D_FEATURE_LEVEL_11_1, "11_1" }, { D3D_FEATURE_LEVEL_12_0, "12_0" }, { D3D_FEATURE_LEVEL_12_1, "12_1" } }); NLOHMANN_JSON_SERIALIZE_ENUM(DXGI_FORMAT, { { DXGI_FORMAT_R8G8B8A8_UNORM, nullptr }, { DXGI_FORMAT_R8G8B8A8_UNORM, "R8G8B8A8_UNORM" }, { DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, "R8G8B8A8_UNORM_SRGB" } });
37.309524
141
0.483514
[ "render", "vector" ]
d708032adbbc9c658470a813e1391396157fcb41
3,942
h
C
core/fxcrt/xml/cxml_element.h
KnIfER/pdfpdf
2b918c8d05c922287efbc8858f029026cee31442
[ "BSD-3-Clause" ]
3
2019-01-12T07:06:18.000Z
2019-10-13T08:07:26.000Z
core/fxcrt/xml/cxml_element.h
KnIfER/pdf
2b918c8d05c922287efbc8858f029026cee31442
[ "BSD-3-Clause" ]
null
null
null
core/fxcrt/xml/cxml_element.h
KnIfER/pdf
2b918c8d05c922287efbc8858f029026cee31442
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2014 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #ifndef CORE_FXCRT_XML_CXML_ELEMENT_H_ #define CORE_FXCRT_XML_CXML_ELEMENT_H_ #include <memory> #include <vector> #include "core/fxcrt/fx_basic.h" #include "core/fxcrt/xml/cxml_attrmap.h" #include "core/fxcrt/xml/cxml_object.h" class CXML_Element : public CXML_Object { public: static std::unique_ptr<CXML_Element> Parse(const void* pBuffer, size_t size); CXML_Element(const CXML_Element* pParent, const CFX_ByteStringC& qSpace, const CFX_ByteStringC& tagname); ~CXML_Element() override; // CXML_Object: CXML_Element* AsElement() override; const CXML_Element* AsElement() const override; CFX_ByteString GetTagName(bool bQualified = false) const; CFX_ByteString GetNamespace(bool bQualified = false) const; CFX_ByteString GetNamespaceURI(const CFX_ByteString& qName) const; const CXML_Element* GetParent() const { return m_pParent.Get(); } uint32_t CountAttrs() const { return m_AttrMap.GetSize(); } void GetAttrByIndex(int index, CFX_ByteString* space, CFX_ByteString* name, CFX_WideString* value) const; bool HasAttr(const CFX_ByteStringC& qName) const; bool GetAttrValue(const CFX_ByteStringC& name, CFX_WideString& attribute) const; CFX_WideString GetAttrValue(const CFX_ByteStringC& name) const { CFX_WideString attr; GetAttrValue(name, attr); return attr; } bool GetAttrValue(const CFX_ByteStringC& space, const CFX_ByteStringC& name, CFX_WideString& attribute) const; CFX_WideString GetAttrValue(const CFX_ByteStringC& space, const CFX_ByteStringC& name) const { CFX_WideString attr; GetAttrValue(space, name, attr); return attr; } bool GetAttrInteger(const CFX_ByteStringC& name, int& attribute) const; int GetAttrInteger(const CFX_ByteStringC& name) const { int attr = 0; GetAttrInteger(name, attr); return attr; } bool GetAttrInteger(const CFX_ByteStringC& space, const CFX_ByteStringC& name, int& attribute) const; int GetAttrInteger(const CFX_ByteStringC& space, const CFX_ByteStringC& name) const { int attr = 0; GetAttrInteger(space, name, attr); return attr; } bool GetAttrFloat(const CFX_ByteStringC& name, float& attribute) const; float GetAttrFloat(const CFX_ByteStringC& name) const { float attr = 0; GetAttrFloat(name, attr); return attr; } bool GetAttrFloat(const CFX_ByteStringC& space, const CFX_ByteStringC& name, float& attribute) const; float GetAttrFloat(const CFX_ByteStringC& space, const CFX_ByteStringC& name) const { float attr = 0; GetAttrFloat(space, name, attr); return attr; } uint32_t CountChildren() const { return m_Children.size(); } uint32_t CountElements(const CFX_ByteStringC& space, const CFX_ByteStringC& tag) const; CXML_Object* GetChild(uint32_t index) const; CXML_Element* GetElement(const CFX_ByteStringC& space, const CFX_ByteStringC& tag, int nth) const; uint32_t FindElement(CXML_Element* pElement) const; void SetTag(const CFX_ByteStringC& qTagName); void RemoveChild(uint32_t index); private: friend class CXML_Parser; friend class CXML_Composer; CFX_UnownedPtr<const CXML_Element> const m_pParent; CFX_ByteString m_QSpaceName; CFX_ByteString m_TagName; CXML_AttrMap m_AttrMap; std::vector<std::unique_ptr<CXML_Object>> m_Children; }; #endif // CORE_FXCRT_XML_CXML_ELEMENT_H_
34.278261
80
0.689751
[ "vector" ]
d7158689eae96a91cb4dc08802fe7fe5d48329a0
779
h
C
src/AdventOfCode2021/Day05-HydrothermalVenture/LineSegment.h
dbartok/advent-of-code-cpp
c8c2df7a21980f8f3e42128f7bc5df8288f18490
[ "MIT" ]
null
null
null
src/AdventOfCode2021/Day05-HydrothermalVenture/LineSegment.h
dbartok/advent-of-code-cpp
c8c2df7a21980f8f3e42128f7bc5df8288f18490
[ "MIT" ]
null
null
null
src/AdventOfCode2021/Day05-HydrothermalVenture/LineSegment.h
dbartok/advent-of-code-cpp
c8c2df7a21980f8f3e42128f7bc5df8288f18490
[ "MIT" ]
null
null
null
#pragma once #include <AdventOfCodeCommon/DisableLibraryWarningsMacros.h> __BEGIN_LIBRARIES_DISABLE_WARNINGS #include <Eigen/Dense> #include <boost/functional/hash.hpp> #include <vector> __END_LIBRARIES_DISABLE_WARNINGS namespace AdventOfCode { namespace Year2021 { namespace Day05 { using Vector2D = Eigen::Matrix<int, 2, 1>; struct Vector2DHash { size_t operator()(const Vector2D& vec) const { size_t seed = 0; boost::hash_combine(seed, vec.x()); boost::hash_combine(seed, vec.y()); return seed; } }; class LineSegment { public: LineSegment(Vector2D start, Vector2D end); bool isAxisParallel() const; std::vector<Vector2D> getCoveredPoints() const; private: Vector2D m_start; Vector2D m_end; }; } } }
15.58
60
0.702182
[ "vector" ]
d719015fc0444a8e229448654f16d7351bb41798
3,868
c
C
linux-2.6.16-unmod/arch/i386/oprofile/op_model_ppro.c
ut-osa/syncchar
eba20da163260b6ae1ef3e334ad2137873a8d625
[ "BSD-3-Clause" ]
null
null
null
linux-2.6.16-unmod/arch/i386/oprofile/op_model_ppro.c
ut-osa/syncchar
eba20da163260b6ae1ef3e334ad2137873a8d625
[ "BSD-3-Clause" ]
null
null
null
linux-2.6.16-unmod/arch/i386/oprofile/op_model_ppro.c
ut-osa/syncchar
eba20da163260b6ae1ef3e334ad2137873a8d625
[ "BSD-3-Clause" ]
1
2019-05-14T16:36:45.000Z
2019-05-14T16:36:45.000Z
/** * @file op_model_ppro.h * pentium pro / P6 model-specific MSR operations * * @remark Copyright 2002 OProfile authors * @remark Read the file COPYING * * @author John Levon * @author Philippe Elie * @author Graydon Hoare */ #include <linux/oprofile.h> #include <asm/ptrace.h> #include <asm/msr.h> #include <asm/apic.h> #include "op_x86_model.h" #include "op_counter.h" #define NUM_COUNTERS 2 #define NUM_CONTROLS 2 #define CTR_READ(l,h,msrs,c) do {rdmsr(msrs->counters[(c)].addr, (l), (h));} while (0) #define CTR_WRITE(l,msrs,c) do {wrmsr(msrs->counters[(c)].addr, -(u32)(l), -1);} while (0) #define CTR_OVERFLOWED(n) (!((n) & (1U<<31))) #define CTRL_READ(l,h,msrs,c) do {rdmsr((msrs->controls[(c)].addr), (l), (h));} while (0) #define CTRL_WRITE(l,h,msrs,c) do {wrmsr((msrs->controls[(c)].addr), (l), (h));} while (0) #define CTRL_SET_ACTIVE(n) (n |= (1<<22)) #define CTRL_SET_INACTIVE(n) (n &= ~(1<<22)) #define CTRL_CLEAR(x) (x &= (1<<21)) #define CTRL_SET_ENABLE(val) (val |= 1<<20) #define CTRL_SET_USR(val,u) (val |= ((u & 1) << 16)) #define CTRL_SET_KERN(val,k) (val |= ((k & 1) << 17)) #define CTRL_SET_UM(val, m) (val |= (m << 8)) #define CTRL_SET_EVENT(val, e) (val |= e) static unsigned long reset_value[NUM_COUNTERS]; static void ppro_fill_in_addresses(struct op_msrs * const msrs) { msrs->counters[0].addr = MSR_P6_PERFCTR0; msrs->counters[1].addr = MSR_P6_PERFCTR1; msrs->controls[0].addr = MSR_P6_EVNTSEL0; msrs->controls[1].addr = MSR_P6_EVNTSEL1; } static void ppro_setup_ctrs(struct op_msrs const * const msrs) { unsigned int low, high; int i; /* clear all counters */ for (i = 0 ; i < NUM_CONTROLS; ++i) { CTRL_READ(low, high, msrs, i); CTRL_CLEAR(low); CTRL_WRITE(low, high, msrs, i); } /* avoid a false detection of ctr overflows in NMI handler */ for (i = 0; i < NUM_COUNTERS; ++i) { CTR_WRITE(1, msrs, i); } /* enable active counters */ for (i = 0; i < NUM_COUNTERS; ++i) { if (counter_config[i].enabled) { reset_value[i] = counter_config[i].count; CTR_WRITE(counter_config[i].count, msrs, i); CTRL_READ(low, high, msrs, i); CTRL_CLEAR(low); CTRL_SET_ENABLE(low); CTRL_SET_USR(low, counter_config[i].user); CTRL_SET_KERN(low, counter_config[i].kernel); CTRL_SET_UM(low, counter_config[i].unit_mask); CTRL_SET_EVENT(low, counter_config[i].event); CTRL_WRITE(low, high, msrs, i); } } } static int ppro_check_ctrs(struct pt_regs * const regs, struct op_msrs const * const msrs) { unsigned int low, high; int i; for (i = 0 ; i < NUM_COUNTERS; ++i) { CTR_READ(low, high, msrs, i); if (CTR_OVERFLOWED(low)) { oprofile_add_sample(regs, i); CTR_WRITE(reset_value[i], msrs, i); } } /* Only P6 based Pentium M need to re-unmask the apic vector but it * doesn't hurt other P6 variant */ apic_write(APIC_LVTPC, apic_read(APIC_LVTPC) & ~APIC_LVT_MASKED); /* We can't work out if we really handled an interrupt. We * might have caught a *second* counter just after overflowing * the interrupt for this counter then arrives * and we don't find a counter that's overflowed, so we * would return 0 and get dazed + confused. Instead we always * assume we found an overflow. This sucks. */ return 1; } static void ppro_start(struct op_msrs const * const msrs) { unsigned int low,high; CTRL_READ(low, high, msrs, 0); CTRL_SET_ACTIVE(low); CTRL_WRITE(low, high, msrs, 0); } static void ppro_stop(struct op_msrs const * const msrs) { unsigned int low,high; CTRL_READ(low, high, msrs, 0); CTRL_SET_INACTIVE(low); CTRL_WRITE(low, high, msrs, 0); } struct op_x86_model_spec const op_ppro_spec = { .num_counters = NUM_COUNTERS, .num_controls = NUM_CONTROLS, .fill_in_addresses = &ppro_fill_in_addresses, .setup_ctrs = &ppro_setup_ctrs, .check_ctrs = &ppro_check_ctrs, .start = &ppro_start, .stop = &ppro_stop };
26.861111
90
0.680196
[ "vector", "model" ]
d71958b357a9b71c98343288eccb640f2958fc8e
1,627
h
C
tests/juliet/testcases/CWE191_Integer_Underflow/s02/CWE191_Integer_Underflow__int_min_multiply_84.h
RanerL/analyzer
a401da4680f163201326881802ee535d6cf97f5a
[ "MIT" ]
28
2017-01-20T15:25:54.000Z
2020-03-17T00:28:31.000Z
testcases/CWE191_Integer_Underflow/s02/CWE191_Integer_Underflow__int_min_multiply_84.h
mellowCS/cwe_checker_juliet_suite
ae604f6fd94964251fbe88ef04d5287f6c1ffbe2
[ "MIT" ]
1
2017-01-20T15:26:27.000Z
2018-08-20T00:55:37.000Z
testcases/CWE191_Integer_Underflow/s02/CWE191_Integer_Underflow__int_min_multiply_84.h
mellowCS/cwe_checker_juliet_suite
ae604f6fd94964251fbe88ef04d5287f6c1ffbe2
[ "MIT" ]
2
2019-07-15T19:07:04.000Z
2019-09-07T14:21:04.000Z
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE191_Integer_Underflow__int_min_multiply_84.h Label Definition File: CWE191_Integer_Underflow__int.label.xml Template File: sources-sinks-84.tmpl.h */ /* * @description * CWE: 191 Integer Underflow * BadSource: min Set data to the minimum value for int * GoodSource: Set data to a small, non-zero number (negative two) * Sinks: multiply * GoodSink: Ensure there will not be an underflow before multiplying data by 2 * BadSink : If data is negative, multiply by 2, which can cause an underflow * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use * * */ #include "std_testcase.h" namespace CWE191_Integer_Underflow__int_min_multiply_84 { #ifndef OMITBAD class CWE191_Integer_Underflow__int_min_multiply_84_bad { public: CWE191_Integer_Underflow__int_min_multiply_84_bad(int dataCopy); ~CWE191_Integer_Underflow__int_min_multiply_84_bad(); private: int data; }; #endif /* OMITBAD */ #ifndef OMITGOOD class CWE191_Integer_Underflow__int_min_multiply_84_goodG2B { public: CWE191_Integer_Underflow__int_min_multiply_84_goodG2B(int dataCopy); ~CWE191_Integer_Underflow__int_min_multiply_84_goodG2B(); private: int data; }; class CWE191_Integer_Underflow__int_min_multiply_84_goodB2G { public: CWE191_Integer_Underflow__int_min_multiply_84_goodB2G(int dataCopy); ~CWE191_Integer_Underflow__int_min_multiply_84_goodB2G(); private: int data; }; #endif /* OMITGOOD */ }
26.241935
147
0.764597
[ "object" ]
d71d01b8274eef7a758d3e8b838b0cddc792de2e
3,852
h
C
AlphaGo/go_engine/src/board_t.h
PatWie/tensorpack-recipes
33962bb45e81f3619bfa6a8aeae5556cc7534caf
[ "Apache-2.0" ]
48
2018-06-14T18:09:22.000Z
2022-02-08T18:29:03.000Z
AlphaGo/go_engine/src/board_t.h
AmeerAnsari/tensorflow-recipes
33962bb45e81f3619bfa6a8aeae5556cc7534caf
[ "Apache-2.0" ]
1
2019-05-06T08:44:17.000Z
2019-05-06T18:26:54.000Z
AlphaGo/go_engine/src/board_t.h
AmeerAnsari/tensorflow-recipes
33962bb45e81f3619bfa6a8aeae5556cc7534caf
[ "Apache-2.0" ]
10
2018-06-21T10:18:56.000Z
2020-05-07T04:03:47.000Z
// Author: Patrick Wieschollek <mail@patwie.com> #ifndef ENGINE_BOARD_T_H #define ENGINE_BOARD_T_H #include "misc.h" #include "token_t.h" #include "field_t.h" #include <array> #include <memory> #include <vector> #include <map> class board_t { public: /** * @brief Create new board representation. */ board_t(); ~board_t(); /** * @brief Just for convenience. * * @param stream board configuration * @param b stream */ friend std::ostream& operator<< (std::ostream& stream, const board_t& b); /** * @brief Set a stone and update groups. * * @param x vertical axis (top -> bottom) * @param y horizontal axis (left ->right) * @param tok color of stone * @return 0 if success */ int play(int x, int y, token_t tok); int set(int x, int y, token_t tok); void update_groups(int x, int y); /** * @brief Return a group for a given field. * @details This creates a new group for the field if the field was without a group. * * @param id [description] * @return [description] */ group_t* find_or_create_group(int id); /** * @brief switch perspective of player */ const token_t opponent(token_t tok) const; /** * @brief test whether placing a token at x, y is legal for given player * * @param x [description] * @param y [description] * @param tok checking for token color of tok * @return valid? */ bool is_legal(int x, int y, token_t tok) const ; /** * @brief place token and count effect of captured stones * @details [long description] * * @param x [description] * @param y [description] * @param color_place [description] * @param color_count [description] * @return number of captured stones */ int estimate_captured_stones(int x, int y, token_t color_place, token_t color_count) const ; /** * @brief search for groups without liberties and remove them * @details [long description] * * @param x [description] * @param y [description] * @param focus just look at groups of this color * @return number of removed stones */ int count_and_remove_captured_stones(int x, int y, token_t focus); /** * @brief compute features of current board configuration as an input for the NN * @details ust 47 out of the 49 from the Nature paper * * @param planes 47x19x19 values * @param self perspective from (predict move for) */ void feature_planes(int *planes, token_t self) const; /** * @brief count liberties from a field * @details could benefit from a caching * * @param x [description] * @param y [description] * * @return [description] */ int liberties(int x, int y) const; /** * @brief Create a deep copy of current board configuration. * @details This copies all properties (fields, groups, counters) * @return new board (do not forget to delete this when not used anymore) */ board_t* clone() const ; /** * @brief get neighboring fields * @details hopefully the compiler can optimize this * * @param x anchor x * @param y anchor y * * @return list of (x, y) pairs */ const std::vector<std::pair<int, int> > neighbor_fields(int x, int y) const; bool is_ladder_capture(int x, int y, token_t hunter, token_t current, int recursion_depth, int fx, int fy) const; std::array<std::array<field_t, N>, N> fields; std::map<int, group_t*> groups; std::map<int, group_t*>::iterator groups_iter; int groupid; int played_moves = 0; float score_black; float score_white; }; #endif
25.852349
96
0.609553
[ "vector" ]
d72400338f7ff37fab5f713553a2c649cb098fdc
14,315
h
C
unsorted_include_todo/Game/ItemHoney/Mgr.h
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
33
2021-12-08T11:10:59.000Z
2022-03-26T19:59:37.000Z
unsorted_include_todo/Game/ItemHoney/Mgr.h
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
6
2021-12-22T17:54:31.000Z
2022-01-07T21:43:18.000Z
unsorted_include_todo/Game/ItemHoney/Mgr.h
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
2
2022-01-04T06:00:49.000Z
2022-01-26T07:27:28.000Z
#ifndef _GAME_ITEMHONEY_MGR_H #define _GAME_ITEMHONEY_MGR_H /* __vt__Q34Game9ItemHoney3Mgr: .4byte 0 .4byte 0 .4byte "doAnimation__Q24Game40FixedSizeItemMgr<Q34Game9ItemHoney4Item>Fv" .4byte "doEntry__Q24Game40FixedSizeItemMgr<Q34Game9ItemHoney4Item>Fv" .4byte "doSetView__Q24Game40FixedSizeItemMgr<Q34Game9ItemHoney4Item>Fi" .4byte "doViewCalc__Q24Game40FixedSizeItemMgr<Q34Game9ItemHoney4Item>Fv" .4byte "doSimulation__Q24Game40FixedSizeItemMgr<Q34Game9ItemHoney4Item>Ff" .4byte "doDirectDraw__Q24Game40FixedSizeItemMgr<Q34Game9ItemHoney4Item>FR8Graphics" .4byte doSimpleDraw__16GenericObjectMgrFP8Viewport .4byte loadResources__Q24Game11BaseItemMgrFv .4byte resetMgr__16GenericObjectMgrFv .4byte pausable__16GenericObjectMgrFv .4byte frozenable__16GenericObjectMgrFv .4byte getMatrixLoadType__16GenericObjectMgrFv .4byte "initDependency__Q24Game40FixedSizeItemMgr<Q34Game9ItemHoney4Item>Fv" .4byte "killAll__Q24Game40FixedSizeItemMgr<Q34Game9ItemHoney4Item>Fv" .4byte setup__Q24Game11BaseItemMgrFPQ24Game8BaseItem .4byte setupSoundViewerAndBas__Q24Game11BaseItemMgrFv .4byte onLoadResources__Q34Game9ItemHoney3MgrFv .4byte loadEverytime__Q24Game11BaseItemMgrFv .4byte updateUseList__Q24Game11BaseItemMgrFPQ24Game11GenItemParmi .4byte onUpdateUseList__Q24Game11BaseItemMgrFPQ24Game11GenItemParmi .4byte generatorGetID__Q34Game9ItemHoney3MgrFv .4byte "generatorBirth__Q34Game9ItemHoney3MgrFR10Vector3<f>R10Vector3<f>PQ24Game11GenItemParm" .4byte generatorWrite__Q24Game11BaseItemMgrFR6StreamPQ24Game11GenItemParm .4byte generatorRead__Q24Game11BaseItemMgrFR6StreamPQ24Game11GenItemParmUl .4byte generatorLocalVersion__Q24Game11BaseItemMgrFv .4byte generatorGetShape__Q24Game11BaseItemMgrFPQ24Game11GenItemParm .4byte generatorNewItemParm__Q24Game11BaseItemMgrFv .4byte 0 .4byte 0 .4byte "@48@__dt__Q34Game9ItemHoney3MgrFv" .4byte getChildCount__5CNodeFv .4byte "getObject__33Container<Q34Game9ItemHoney4Item>FPv" .4byte "@48@getNext__Q24Game40FixedSizeItemMgr<Q34Game9ItemHoney4Item>FPv" .4byte "@48@getStart__Q24Game40FixedSizeItemMgr<Q34Game9ItemHoney4Item>Fv" .4byte "@48@getEnd__Q24Game40FixedSizeItemMgr<Q34Game9ItemHoney4Item>Fv" .4byte "@48@get__Q24Game40FixedSizeItemMgr<Q34Game9ItemHoney4Item>FPv" .4byte "getAt__33Container<Q34Game9ItemHoney4Item>Fi" .4byte "getTo__33Container<Q34Game9ItemHoney4Item>Fv" .4byte onCreateModel__Q34Game9ItemHoney3MgrFPQ28SysShape5Model .4byte birth__Q34Game9ItemHoney3MgrFv .4byte "kill__Q24Game40FixedSizeItemMgr<Q34Game9ItemHoney4Item>FPQ34Game9ItemHoney4Item" .4byte "get__Q24Game40FixedSizeItemMgr<Q34Game9ItemHoney4Item>FPv" .4byte "getNext__Q24Game40FixedSizeItemMgr<Q34Game9ItemHoney4Item>FPv" .4byte "getStart__Q24Game40FixedSizeItemMgr<Q34Game9ItemHoney4Item>Fv" .4byte "getEnd__Q24Game40FixedSizeItemMgr<Q34Game9ItemHoney4Item>Fv" .4byte __dt__Q34Game9ItemHoney3MgrFv */ namespace Game { namespace FixedSizeItemMgr < Game { namespace ItemHoney { struct Item > { virtual void FixedSizeItemMgr < doAnimation(); // _00 virtual void FixedSizeItemMgr < doEntry(); // _04 virtual void FixedSizeItemMgr < doSetView(int); // _08 virtual void FixedSizeItemMgr < doViewCalc(); // _0C virtual void FixedSizeItemMgr < doSimulation(float); // _10 virtual void FixedSizeItemMgr < doDirectDraw(Graphics&); // _14 virtual void _18() = 0; // _18 virtual void _1C() = 0; // _1C virtual void _20() = 0; // _20 virtual void _24() = 0; // _24 virtual void _28() = 0; // _28 virtual void _2C() = 0; // _2C virtual void FixedSizeItemMgr < initDependency(); // _30 virtual void FixedSizeItemMgr < killAll(); // _34 virtual void _38() = 0; // _38 virtual void _3C() = 0; // _3C virtual void _40() = 0; // _40 virtual void _44() = 0; // _44 virtual void _48() = 0; // _48 virtual void _4C() = 0; // _4C virtual void _50() = 0; // _50 virtual void _54() = 0; // _54 virtual void _58() = 0; // _58 virtual void _5C() = 0; // _5C virtual void _60() = 0; // _60 virtual void _64() = 0; // _64 virtual void _68() = 0; // _68 virtual void _6C() = 0; // _6C virtual void _70() = 0; // _70 virtual void _74() = 0; // _74 virtual void _78() = 0; // _78 virtual void getObject(void*); // _7C virtual void _80() = 0; // _80 virtual void _84() = 0; // _84 virtual void _88() = 0; // _88 virtual void _8C() = 0; // _8C virtual void getAt(int); // _90 virtual void getTo(); // _94 virtual void _98() = 0; // _98 virtual void _9C() = 0; // _9C virtual void FixedSizeItemMgr < kill(Item*); // _A0 virtual void FixedSizeItemMgr < get(void*); // _A4 virtual void FixedSizeItemMgr < getNext(void*); // _A8 virtual void FixedSizeItemMgr < getStart(); // _AC virtual void FixedSizeItemMgr < getEnd(); // _B0 // _00 VTBL }; } // namespace ItemHoney } // namespace FixedSizeItemMgr<Game } // namespace Game struct GenericObjectMgr { virtual void _00() = 0; // _00 virtual void _04() = 0; // _04 virtual void _08() = 0; // _08 virtual void _0C() = 0; // _0C virtual void _10() = 0; // _10 virtual void _14() = 0; // _14 virtual void doSimpleDraw(Viewport*); // _18 virtual void _1C() = 0; // _1C virtual void resetMgr(); // _20 virtual void pausable(); // _24 virtual void frozenable(); // _28 virtual void getMatrixLoadType(); // _2C // _00 VTBL }; namespace Game { struct BaseItemMgr { virtual void _00() = 0; // _00 virtual void _04() = 0; // _04 virtual void _08() = 0; // _08 virtual void _0C() = 0; // _0C virtual void _10() = 0; // _10 virtual void _14() = 0; // _14 virtual void _18() = 0; // _18 virtual void loadResources(); // _1C virtual void _20() = 0; // _20 virtual void _24() = 0; // _24 virtual void _28() = 0; // _28 virtual void _2C() = 0; // _2C virtual void _30() = 0; // _30 virtual void _34() = 0; // _34 virtual void setup(BaseItem*); // _38 virtual void setupSoundViewerAndBas(); // _3C virtual void _40() = 0; // _40 virtual void loadEverytime(); // _44 virtual void updateUseList(GenItemParm*, int); // _48 virtual void onUpdateUseList(GenItemParm*, int); // _4C virtual void _50() = 0; // _50 virtual void _54() = 0; // _54 virtual void generatorWrite(Stream&, GenItemParm*); // _58 virtual void generatorRead(Stream&, GenItemParm*, unsigned long); // _5C virtual void generatorLocalVersion(); // _60 virtual void generatorGetShape(GenItemParm*); // _64 virtual void generatorNewItemParm(); // _68 // _00 VTBL }; } // namespace Game struct CNode { virtual void _00() = 0; // _00 virtual void _04() = 0; // _04 virtual void _08() = 0; // _08 virtual void _0C() = 0; // _0C virtual void _10() = 0; // _10 virtual void _14() = 0; // _14 virtual void _18() = 0; // _18 virtual void _1C() = 0; // _1C virtual void _20() = 0; // _20 virtual void _24() = 0; // _24 virtual void _28() = 0; // _28 virtual void _2C() = 0; // _2C virtual void _30() = 0; // _30 virtual void _34() = 0; // _34 virtual void _38() = 0; // _38 virtual void _3C() = 0; // _3C virtual void _40() = 0; // _40 virtual void _44() = 0; // _44 virtual void _48() = 0; // _48 virtual void _4C() = 0; // _4C virtual void _50() = 0; // _50 virtual void _54() = 0; // _54 virtual void _58() = 0; // _58 virtual void _5C() = 0; // _5C virtual void _60() = 0; // _60 virtual void _64() = 0; // _64 virtual void _68() = 0; // _68 virtual void _6C() = 0; // _6C virtual void _70() = 0; // _70 virtual void _74() = 0; // _74 virtual void getChildCount(); // _78 // _00 VTBL }; namespace Game { namespace ItemHoney { struct Mgr : public Item >, public GenericObjectMgr, public BaseItemMgr, public CNode { virtual void FixedSizeItemMgr < doAnimation(); // _00 virtual void FixedSizeItemMgr < doEntry(); // _04 virtual void FixedSizeItemMgr < doSetView(int); // _08 virtual void FixedSizeItemMgr < doViewCalc(); // _0C virtual void FixedSizeItemMgr < doSimulation(float); // _10 virtual void FixedSizeItemMgr < doDirectDraw(Graphics&); // _14 virtual void doSimpleDraw(Viewport*); // _18 virtual void loadResources(); // _1C virtual void resetMgr(); // _20 virtual void pausable(); // _24 virtual void frozenable(); // _28 virtual void getMatrixLoadType(); // _2C virtual void FixedSizeItemMgr < initDependency(); // _30 virtual void FixedSizeItemMgr < killAll(); // _34 virtual void setup(BaseItem*); // _38 virtual void setupSoundViewerAndBas(); // _3C virtual void onLoadResources(); // _40 virtual void loadEverytime(); // _44 virtual void updateUseList(GenItemParm*, int); // _48 virtual void onUpdateUseList(GenItemParm*, int); // _4C virtual void generatorGetID(); // _50 virtual void generatorBirth(Vector3<float>&, Vector3<float>&, GenItemParm*); // _54 virtual void generatorWrite(Stream&, GenItemParm*); // _58 virtual void generatorRead(Stream&, GenItemParm*, unsigned long); // _5C virtual void generatorLocalVersion(); // _60 virtual void generatorGetShape(GenItemParm*); // _64 virtual void generatorNewItemParm(); // _68 virtual void _6C() = 0; // _6C virtual void _70() = 0; // _70 virtual void @48 @__dt(); // _74 virtual void getChildCount(); // _78 virtual void getObject(void*); // _7C virtual void getAt(int); // _90 virtual void getTo(); // _94 virtual void onCreateModel(SysShape::Model*); // _98 virtual void birth(); // _9C virtual void FixedSizeItemMgr < kill(Item*); // _A0 virtual void FixedSizeItemMgr < get(void*); // _A4 virtual void FixedSizeItemMgr < getNext(void*); // _A8 virtual void FixedSizeItemMgr < getStart(); // _AC virtual void FixedSizeItemMgr < getEnd(); // _B0 virtual ~Mgr(); // _B4 // _00 VTBL }; } // namespace ItemHoney } // namespace Game #endif
56.137255
90
0.489487
[ "model" ]
d7269060097df3119955da98ccba997b59dfc731
1,228
h
C
RecoEgamma/EgammaTools/interface/Spot.h
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
RecoEgamma/EgammaTools/interface/Spot.h
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
RecoEgamma/EgammaTools/interface/Spot.h
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#ifndef RecoEgamma_EgammaTools_Spot_h #define RecoEgamma_EgammaTools_Spot_h #include "DataFormats/DetId/interface/DetId.h" #include <vector> namespace hgcal { class Spot{ public: Spot(DetId detid, double energy, const std::vector<double>& row, unsigned int layer, float fraction, double mip): detId_(detid),energy_(energy),row_(row),layer_(layer),fraction_(fraction), mip_(mip),multiplicity_(int(energy/mip)),subdet_(detid.subdetId()),isCore_(fraction>0.){} ~Spot(){} inline DetId detId() const {return detId_;} inline float energy() const {return energy_;} inline const double * row() const {return &row_[0];} inline float fraction() const {return fraction_;} inline float mip() const {return mip_;} inline int multiplicity() const {return multiplicity_;} inline unsigned int layer() const { return layer_;} inline int subdet() const {return subdet_;} inline bool isCore() const {return isCore_;} private: DetId detId_; float energy_; std::vector<double> row_; unsigned int layer_; float fraction_; float mip_; int multiplicity_; int subdet_; bool isCore_; }; } #endif
30.7
119
0.669381
[ "vector" ]
d731eab338063e85daaee228626c11bf485857ce
995
h
C
Engine/Core/Public/Scene/Mesh/MeshDataArchive.h
CrystaLamb/Seagull-Engine
85a83c7976957da86675674d28d9592bf12f07c7
[ "MIT" ]
1
2022-02-15T16:09:22.000Z
2022-02-15T16:09:22.000Z
Engine/Core/Public/Scene/Mesh/MeshDataArchive.h
CrystaLamb/Seagull-Engine
85a83c7976957da86675674d28d9592bf12f07c7
[ "MIT" ]
null
null
null
Engine/Core/Public/Scene/Mesh/MeshDataArchive.h
CrystaLamb/Seagull-Engine
85a83c7976957da86675674d28d9592bf12f07c7
[ "MIT" ]
null
null
null
#pragma once #include "Stl/vector.h" #include "Stl/string.h" #include "eastl/unordered_map.h" namespace SG { struct MeshData { vector<float> vertices; vector<UInt32> indices; string filename; bool bIsProceduralMesh; }; class MeshDataArchive { public: SG_CORE_API UInt32 SetData(const MeshData& meshData); SG_CORE_API void SetFlag(UInt32 meshId, bool bHaveInstance); SG_CORE_API const MeshData* GetData(UInt32 meshId) const; SG_CORE_API UInt32 GetMeshID(const string& filename) const; SG_CORE_API UInt32 GetNumMeshData() const { return static_cast<UInt32>(mMeshDatas.size()); } SG_CORE_API bool HaveInstance(UInt32 meshId) const; SG_CORE_API bool HaveMeshData(const string& filename); SG_CORE_API static MeshDataArchive* GetInstance(); private: MeshDataArchive() = default; private: eastl::unordered_map<UInt32, eastl::pair<MeshData, bool>> mMeshDatas; // meshId -> pair(MeshData, bHaveInstance) static UInt32 msCurrKey; }; }
23.690476
114
0.740704
[ "vector" ]
d733347c3c10483ec874a9843dd6885dc0cb9937
1,264
h
C
ccsources/rlink/rlink.h
WallyZambotti/Nitros9-CC-CrossCompiler
de01858f00df0ec22ac43a08bddbaf70eedecfb9
[ "Intel" ]
5
2020-04-27T02:49:27.000Z
2020-05-05T15:38:36.000Z
ccsources/rlink/rlink.h
WallyZambotti/Nitros9-CC-CrossCompiler
de01858f00df0ec22ac43a08bddbaf70eedecfb9
[ "Intel" ]
null
null
null
ccsources/rlink/rlink.h
WallyZambotti/Nitros9-CC-CrossCompiler
de01858f00df0ec22ac43a08bddbaf70eedecfb9
[ "Intel" ]
1
2020-04-27T10:30:14.000Z
2020-04-27T10:30:14.000Z
#ifndef COCO #include <stdlib.h> #include <rof.h> #else #include "rof.h" #endif #include "out.h" //#define DEBUG typedef unsigned u16; /* Little-endian coco int */ #define MAX_RFILES 64 #define MAX_LFILES 64 struct ext_ref { struct ext_ref *next; char name[SYMLEN + 1]; }; struct exp_sym { struct exp_sym *next; char name[SYMLEN + 1]; char flag; unsigned offset; }; struct ob_files { struct ob_files *next; char *filename; FILE *fp; long object; long locref; binhead hd; struct exp_sym *symbols; struct ext_ref *exts; char modname[MAXNAME + 1]; unsigned Code, IDat, UDat, IDpD, UDpD; }; /* Define DEBUG to get way more verbose output */ /* #define DEBUG */ #ifdef DEBUG #define DBGPNT(x) printf x #else #define DBGPNT(x) #endif extern int getname(); extern unsigned getwrd(); extern int chk_dup(); extern int rm_exref(); extern int check_name(); extern int ftext(); extern int (*pfheader)(); extern int (*pfbodybt)(); extern int (*pfbody)(); extern int (*pftail)(); #define mc(c) ((c)&0xff) #define DEF 1 #define REF 2
17.555556
51
0.572785
[ "object" ]
d745a786573d11a94e28d0a7b8e4cc3369d19dfa
7,624
h
C
DataMgr/ChunkMetadata.h
intel-go/omniscidb
86068a229beddf7b117febcacdbd6b60a0279282
[ "Apache-2.0" ]
2
2020-03-04T12:01:10.000Z
2020-07-24T15:12:55.000Z
DataMgr/ChunkMetadata.h
intel-go/omniscidb
86068a229beddf7b117febcacdbd6b60a0279282
[ "Apache-2.0" ]
18
2019-11-20T11:11:19.000Z
2020-08-27T13:21:12.000Z
DataMgr/ChunkMetadata.h
intel-go/omniscidb
86068a229beddf7b117febcacdbd6b60a0279282
[ "Apache-2.0" ]
1
2020-04-04T06:25:32.000Z
2020-04-04T06:25:32.000Z
/* * Copyright 2020 OmniSci, 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. */ #pragma once #include <cstddef> #include "../Shared/sqltypes.h" #include "Shared/types.h" #include <map> #include "Logger/Logger.h" struct ChunkStats { Datum min; Datum max; bool has_nulls; }; template <typename T> void fillChunkStats(ChunkStats& stats, const SQLTypeInfo& type, const T min, const T max, const bool has_nulls) { stats.has_nulls = has_nulls; switch (type.get_type()) { case kBOOLEAN: { stats.min.tinyintval = min; stats.max.tinyintval = max; break; } case kTINYINT: { stats.min.tinyintval = min; stats.max.tinyintval = max; break; } case kSMALLINT: { stats.min.smallintval = min; stats.max.smallintval = max; break; } case kINT: { stats.min.intval = min; stats.max.intval = max; break; } case kBIGINT: case kNUMERIC: case kDECIMAL: { stats.min.bigintval = min; stats.max.bigintval = max; break; } case kTIME: case kTIMESTAMP: case kDATE: { stats.min.bigintval = min; stats.max.bigintval = max; break; } case kFLOAT: { stats.min.floatval = min; stats.max.floatval = max; break; } case kDOUBLE: { stats.min.doubleval = min; stats.max.doubleval = max; break; } case kVARCHAR: case kCHAR: case kTEXT: if (type.get_compression() == kENCODING_DICT) { stats.min.intval = min; stats.max.intval = max; } break; default: { break; } } } inline void mergeStats(ChunkStats& lhs, const ChunkStats& rhs, const SQLTypeInfo& type) { lhs.has_nulls |= rhs.has_nulls; switch (type.is_array() ? type.get_subtype() : type.get_type()) { case kBOOLEAN: { lhs.min.tinyintval = std::min(lhs.min.tinyintval, rhs.min.tinyintval); lhs.max.tinyintval = std::max(lhs.max.tinyintval, rhs.max.tinyintval); break; } case kTINYINT: { lhs.min.tinyintval = std::min(lhs.min.tinyintval, rhs.min.tinyintval); lhs.max.tinyintval = std::max(lhs.max.tinyintval, rhs.max.tinyintval); break; } case kSMALLINT: { lhs.min.smallintval = std::min(lhs.min.smallintval, rhs.min.smallintval); lhs.max.smallintval = std::max(lhs.max.smallintval, rhs.max.smallintval); break; } case kINT: { lhs.min.intval = std::min(lhs.min.intval, rhs.min.intval); lhs.max.intval = std::max(lhs.max.intval, rhs.max.intval); break; } case kBIGINT: case kNUMERIC: case kDECIMAL: { lhs.min.bigintval = std::min(lhs.min.bigintval, rhs.min.bigintval); lhs.max.bigintval = std::max(lhs.max.bigintval, rhs.max.bigintval); break; } case kTIME: case kTIMESTAMP: case kDATE: { lhs.min.bigintval = std::min(lhs.min.bigintval, rhs.min.bigintval); lhs.max.bigintval = std::max(lhs.max.bigintval, rhs.max.bigintval); break; } case kFLOAT: { lhs.min.floatval = std::min(lhs.min.floatval, rhs.min.floatval); lhs.max.floatval = std::max(lhs.max.floatval, rhs.max.floatval); break; } case kDOUBLE: { lhs.min.doubleval = std::min(lhs.min.doubleval, rhs.min.doubleval); lhs.max.doubleval = std::max(lhs.max.doubleval, rhs.max.doubleval); break; } case kVARCHAR: case kCHAR: case kTEXT: if (type.get_compression() == kENCODING_DICT) { lhs.min.intval = std::min(lhs.min.intval, rhs.min.intval); lhs.max.intval = std::max(lhs.max.intval, rhs.max.intval); } break; default: { break; } } } struct ChunkMetadata { SQLTypeInfo sqlType; size_t numBytes; size_t numElements; ChunkStats chunkStats; #ifndef __CUDACC__ std::string dump() const { auto type = sqlType.is_array() ? sqlType.get_elem_type() : sqlType; // Unencoded strings have no min/max. if (type.is_string() && type.get_compression() == kENCODING_NONE) { return "type: " + sqlType.get_type_name() + " numBytes: " + to_string(numBytes) + " numElements " + to_string(numElements) + " min: <invalid>" + " max: <invalid>" + " has_nulls: " + to_string(chunkStats.has_nulls); } else if (type.is_string()) { return "type: " + sqlType.get_type_name() + " numBytes: " + to_string(numBytes) + " numElements " + to_string(numElements) + " min: " + to_string(chunkStats.min.intval) + " max: " + to_string(chunkStats.max.intval) + " has_nulls: " + to_string(chunkStats.has_nulls); } else { return "type: " + sqlType.get_type_name() + " numBytes: " + to_string(numBytes) + " numElements " + to_string(numElements) + " min: " + DatumToString(chunkStats.min, type) + " max: " + DatumToString(chunkStats.max, type) + " has_nulls: " + to_string(chunkStats.has_nulls); } } std::string toString() const { return dump(); } #endif ChunkMetadata(const SQLTypeInfo& sql_type, const size_t num_bytes, const size_t num_elements, const ChunkStats& chunk_stats) : sqlType(sql_type) , numBytes(num_bytes) , numElements(num_elements) , chunkStats(chunk_stats) {} ChunkMetadata() {} template <typename T> void fillChunkStats(const T min, const T max, const bool has_nulls) { ::fillChunkStats(chunkStats, sqlType, min, max, has_nulls); } void fillChunkStats(const Datum min, const Datum max, const bool has_nulls) { chunkStats.has_nulls = has_nulls; chunkStats.min = min; chunkStats.max = max; } bool operator==(const ChunkMetadata& that) const { return sqlType == that.sqlType && numBytes == that.numBytes && numElements == that.numElements && DatumEqual(chunkStats.min, that.chunkStats.min, sqlType.is_array() ? sqlType.get_elem_type() : sqlType) && DatumEqual(chunkStats.max, that.chunkStats.max, sqlType.is_array() ? sqlType.get_elem_type() : sqlType) && chunkStats.has_nulls == that.chunkStats.has_nulls; } }; inline int64_t extract_min_stat_int_type(const ChunkStats& stats, const SQLTypeInfo& ti) { return extract_int_type_from_datum(stats.min, ti); } inline int64_t extract_max_stat_int_type(const ChunkStats& stats, const SQLTypeInfo& ti) { return extract_int_type_from_datum(stats.max, ti); } inline double extract_min_stat_fp_type(const ChunkStats& stats, const SQLTypeInfo& ti) { return extract_fp_type_from_datum(stats.min, ti); } inline double extract_max_stat_fp_type(const ChunkStats& stats, const SQLTypeInfo& ti) { return extract_fp_type_from_datum(stats.max, ti); } using ChunkMetadataMap = std::map<int, std::shared_ptr<ChunkMetadata>>; using ChunkMetadataVector = std::vector<std::pair<ChunkKey, std::shared_ptr<ChunkMetadata>>>;
30.99187
90
0.630115
[ "vector" ]
d747405828ed7757c0814cfc2a7021b05d21aba1
648
h
C
ZhuangBei/zHuoyuan/View/LWHuoYuanThreeLevelListTableViewCell.h
1365102044/lw_zhuangbeiDeamo
0d6db574c81696b26c8ad8466029abe9886bb8de
[ "MIT" ]
null
null
null
ZhuangBei/zHuoyuan/View/LWHuoYuanThreeLevelListTableViewCell.h
1365102044/lw_zhuangbeiDeamo
0d6db574c81696b26c8ad8466029abe9886bb8de
[ "MIT" ]
null
null
null
ZhuangBei/zHuoyuan/View/LWHuoYuanThreeLevelListTableViewCell.h
1365102044/lw_zhuangbeiDeamo
0d6db574c81696b26c8ad8466029abe9886bb8de
[ "MIT" ]
1
2020-09-07T02:36:50.000Z
2020-09-07T02:36:50.000Z
// // LWHuoYuanThreeLevelListTableViewCell.h // ZhuangBei // // Created by LWQ on 2020/4/29. // Copyright © 2020 aa. All rights reserved. // #import <UIKit/UIKit.h> #import "LWHuoYuanDaTingModel.h" typedef void(^changeEditStatusBlock)(BOOL editing); typedef void(^clickItemsBlock)(gysListModel * model); @interface LWHuoYuanThreeLevelListTableViewCell : UITableViewCell<UIScrollViewDelegate> @property (nonatomic, strong) LWHuoYuanThreeLevelModel * model; @property (nonatomic, copy) clickItemsBlock clickItemsBlock; @property (nonatomic, copy) changeEditStatusBlock editBlock; // -1 没有 @property (nonatomic, assign) BOOL isEditing; @end
25.92
87
0.779321
[ "model" ]
d74a3cd54e26a3962befdbd1b934189e087ce123
5,691
h
C
client/OAIGroup.h
owncloud/libre-graph-api-qt5
7f7c9cf64394ef2771310c53bd1950011383d7bf
[ "Apache-2.0" ]
null
null
null
client/OAIGroup.h
owncloud/libre-graph-api-qt5
7f7c9cf64394ef2771310c53bd1950011383d7bf
[ "Apache-2.0" ]
null
null
null
client/OAIGroup.h
owncloud/libre-graph-api-qt5
7f7c9cf64394ef2771310c53bd1950011383d7bf
[ "Apache-2.0" ]
null
null
null
// model-header.mustache // licenseInfo.mustache /** * Libre Graph API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: v0.14.2 * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ /* * OAIGroup.h * * */ #ifndef OAIGroup_H #define OAIGroup_H #include <QJsonObject> #include "OAIDirectoryObject.h" #include "OAIDrive.h" #include <QDateTime> #include <QList> #include <QSet> #include <QString> #include "OAIEnum.h" #include "OAIObject.h" namespace OpenAPI { class OAIDirectoryObject; class OAIDrive; class OAIGroupPrivate; class OAIGroup : public OAIObject { public: OAIGroup(); OAIGroup(const OAIGroup &other); OAIGroup(QString json); ~OAIGroup() override; QString asJson() const override; QJsonObject asJsonObject() const override; void fromJsonObject(QJsonObject json) override; void fromJson(QString jsonString) override; QString getId() const; void setId(const QString &id); bool is_id_Set() const; bool is_id_Valid() const; QDateTime getDeletedDateTime() const; void setDeletedDateTime(const QDateTime &deleted_date_time); bool is_deleted_date_time_Set() const; bool is_deleted_date_time_Valid() const; QDateTime getCreatedDateTime() const; void setCreatedDateTime(const QDateTime &created_date_time); bool is_created_date_time_Set() const; bool is_created_date_time_Valid() const; QString getDescription() const; void setDescription(const QString &description); bool is_description_Set() const; bool is_description_Valid() const; QString getDisplayName() const; void setDisplayName(const QString &display_name); bool is_display_name_Set() const; bool is_display_name_Valid() const; QDateTime getExpirationDateTime() const; void setExpirationDateTime(const QDateTime &expiration_date_time); bool is_expiration_date_time_Set() const; bool is_expiration_date_time_Valid() const; QString getMail() const; void setMail(const QString &mail); bool is_mail_Set() const; bool is_mail_Valid() const; QString getOnPremisesDomainName() const; void setOnPremisesDomainName(const QString &on_premises_domain_name); bool is_on_premises_domain_name_Set() const; bool is_on_premises_domain_name_Valid() const; QDateTime getOnPremisesLastSyncDateTime() const; void setOnPremisesLastSyncDateTime(const QDateTime &on_premises_last_sync_date_time); bool is_on_premises_last_sync_date_time_Set() const; bool is_on_premises_last_sync_date_time_Valid() const; QString getOnPremisesSamAccountName() const; void setOnPremisesSamAccountName(const QString &on_premises_sam_account_name); bool is_on_premises_sam_account_name_Set() const; bool is_on_premises_sam_account_name_Valid() const; bool isOnPremisesSyncEnabled() const; void setOnPremisesSyncEnabled(const bool &on_premises_sync_enabled); bool is_on_premises_sync_enabled_Set() const; bool is_on_premises_sync_enabled_Valid() const; QString getPreferredLanguage() const; void setPreferredLanguage(const QString &preferred_language); bool is_preferred_language_Set() const; bool is_preferred_language_Valid() const; bool isSecurityEnabled() const; void setSecurityEnabled(const bool &security_enabled); bool is_security_enabled_Set() const; bool is_security_enabled_Valid() const; QString getSecurityIdentifier() const; void setSecurityIdentifier(const QString &security_identifier); bool is_security_identifier_Set() const; bool is_security_identifier_Valid() const; QString getVisibility() const; void setVisibility(const QString &visibility); bool is_visibility_Set() const; bool is_visibility_Valid() const; OAIDirectoryObject getCreatedOnBehalfOf() const; void setCreatedOnBehalfOf(const OAIDirectoryObject &created_on_behalf_of); bool is_created_on_behalf_of_Set() const; bool is_created_on_behalf_of_Valid() const; QList<OAIDirectoryObject> getMemberOf() const; void setMemberOf(const QList<OAIDirectoryObject> &member_of); bool is_member_of_Set() const; bool is_member_of_Valid() const; QList<OAIDirectoryObject> getMembers() const; void setMembers(const QList<OAIDirectoryObject> &members); bool is_members_Set() const; bool is_members_Valid() const; QList<OAIDirectoryObject> getOwners() const; void setOwners(const QList<OAIDirectoryObject> &owners); bool is_owners_Set() const; bool is_owners_Valid() const; OAIDrive getDrive() const; void setDrive(const OAIDrive &drive); bool is_drive_Set() const; bool is_drive_Valid() const; QList<OAIDrive> getDrives() const; void setDrives(const QList<OAIDrive> &drives); bool is_drives_Set() const; bool is_drives_Valid() const; bool isIsArchived() const; void setIsArchived(const bool &is_archived); bool is_is_archived_Set() const; bool is_is_archived_Valid() const; QSet<QString> getMembersodataBind() const; void setMembersodataBind(const QSet<QString> &membersodata_bind); bool is_membersodata_bind_Set() const; bool is_membersodata_bind_Valid() const; virtual bool isSet() const override; virtual bool isValid() const override; private: void initializeModel(); Q_DECLARE_PRIVATE(OAIGroup) QSharedPointer<OAIGroupPrivate> d_ptr; }; } // namespace OpenAPI Q_DECLARE_METATYPE(OpenAPI::OAIGroup) #endif // OAIGroup_H
30.762162
109
0.75716
[ "model" ]
d74c31b993495d8dc90bc8292db5c20e2384d60a
19,203
c
C
lib/abc/src/base/abc/abcBarBuf.c
Ace-Ma/LSOracle
6e940906303ef6c2c6b96352f44206567fdd50d3
[ "MIT" ]
9
2017-06-12T17:58:42.000Z
2021-02-04T00:02:29.000Z
reproduction-artifact/ssatABC/src/base/abc/abcBarBuf.c
nianzelee/PhD-Dissertation
061e22dd55b4e58b3de3b0e58bb1cbe11435decd
[ "Apache-2.0" ]
1
2020-12-15T05:59:37.000Z
2020-12-15T05:59:37.000Z
reproduction-artifact/ssatABC/src/base/abc/abcBarBuf.c
nianzelee/PhD-Dissertation
061e22dd55b4e58b3de3b0e58bb1cbe11435decd
[ "Apache-2.0" ]
3
2018-04-23T22:52:53.000Z
2020-12-15T16:36:19.000Z
/**CFile**************************************************************** FileName [abcHie.c] SystemName [ABC: Logic synthesis and verification system.] PackageName [Network and node package.] Synopsis [Procedures to handle hierarchy.] Author [Alan Mishchenko] Affiliation [UC Berkeley] Date [Ver. 1.0. Started - June 20, 2005.] Revision [$Id: abcHie.c,v 1.00 2005/06/20 00:00:00 alanmi Exp $] ***********************************************************************/ #include "abc.h" ABC_NAMESPACE_IMPL_START //////////////////////////////////////////////////////////////////////// /// DECLARATIONS /// //////////////////////////////////////////////////////////////////////// #define ABC_OBJ_VOID ((Abc_Obj_t *)(ABC_PTRINT_T)1) //////////////////////////////////////////////////////////////////////// /// FUNCTION DEFINITIONS /// //////////////////////////////////////////////////////////////////////// /**Function************************************************************* Synopsis [Checks the the hie design has no duplicated networks.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkCheckSingleInstance( Abc_Ntk_t * pNtk ) { Abc_Ntk_t * pTemp, * pModel; Abc_Obj_t * pBox; int i, k, RetValue = 1; if ( pNtk->pDesign == NULL ) return 1; Vec_PtrForEachEntry( Abc_Ntk_t *, pNtk->pDesign->vModules, pTemp, i ) pTemp->fHieVisited = 0; Vec_PtrForEachEntry( Abc_Ntk_t *, pNtk->pDesign->vModules, pTemp, i ) Abc_NtkForEachBox( pTemp, pBox, k ) { pModel = (Abc_Ntk_t *)pBox->pData; if ( pModel == NULL ) continue; if ( Abc_NtkLatchNum(pModel) > 0 ) { printf( "Network \"%s\" contains %d flops.\n", Abc_NtkName(pNtk), Abc_NtkLatchNum(pModel) ); RetValue = 0; } if ( pModel->fHieVisited ) { printf( "Network \"%s\" contains box \"%s\" whose model \"%s\" is instantiated more than once.\n", Abc_NtkName(pNtk), Abc_ObjName(pBox), Abc_NtkName(pModel) ); RetValue = 0; } pModel->fHieVisited = 1; } Vec_PtrForEachEntry( Abc_Ntk_t *, pNtk->pDesign->vModules, pTemp, i ) pTemp->fHieVisited = 0; return RetValue; } /**Function************************************************************* Synopsis [Collect PIs and POs of internal networks in the topo order.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkCollectPiPos_rec( Abc_Obj_t * pNet, Vec_Ptr_t * vLiMaps, Vec_Ptr_t * vLoMaps ) { extern int Abc_NtkCollectPiPos_int( Abc_Obj_t * pBox, Abc_Ntk_t * pNtk, Vec_Ptr_t * vLiMaps, Vec_Ptr_t * vLoMaps ); Abc_Obj_t * pObj, * pFanin; int i, Counter = 0; assert( Abc_ObjIsNet(pNet) ); if ( Abc_NodeIsTravIdCurrent( pNet ) ) return 0; Abc_NodeSetTravIdCurrent( pNet ); pObj = Abc_ObjFanin0(pNet); if ( Abc_ObjIsNode(pObj) ) Abc_ObjForEachFanin( pObj, pFanin, i ) Counter += Abc_NtkCollectPiPos_rec( pFanin, vLiMaps, vLoMaps ); if ( Abc_ObjIsNode(pObj) ) return Counter; if ( Abc_ObjIsBo(pObj) ) pObj = Abc_ObjFanin0(pObj); assert( Abc_ObjIsBox(pObj) ); Abc_ObjForEachFanout( pObj, pFanin, i ) Abc_NodeSetTravIdCurrent( Abc_ObjFanout0(pFanin) ); Abc_ObjForEachFanin( pObj, pFanin, i ) Counter += Abc_NtkCollectPiPos_rec( Abc_ObjFanin0(pFanin), vLiMaps, vLoMaps ); Counter += Abc_NtkCollectPiPos_int( pObj, Abc_ObjModel(pObj), vLiMaps, vLoMaps ); return Counter; } int Abc_NtkCollectPiPos_int( Abc_Obj_t * pBox, Abc_Ntk_t * pNtk, Vec_Ptr_t * vLiMaps, Vec_Ptr_t * vLoMaps ) { Abc_Obj_t * pObj; int i, Counter = 0; // mark primary inputs Abc_NtkIncrementTravId( pNtk ); Abc_NtkForEachPi( pNtk, pObj, i ) Abc_NodeSetTravIdCurrent( Abc_ObjFanout0(pObj) ); // add primary inputs if ( pBox ) { Abc_ObjForEachFanin( pBox, pObj, i ) Vec_PtrPush( vLiMaps, pObj ); Abc_NtkForEachPi( pNtk, pObj, i ) Vec_PtrPush( vLoMaps, pObj ); } // visit primary outputs Abc_NtkForEachPo( pNtk, pObj, i ) Counter += Abc_NtkCollectPiPos_rec( Abc_ObjFanin0(pObj), vLiMaps, vLoMaps ); // add primary outputs if ( pBox ) { Abc_NtkForEachPo( pNtk, pObj, i ) Vec_PtrPush( vLiMaps, pObj ); Abc_ObjForEachFanout( pBox, pObj, i ) Vec_PtrPush( vLoMaps, pObj ); Counter++; } return Counter; } int Abc_NtkCollectPiPos( Abc_Ntk_t * pNtk, Vec_Ptr_t ** pvLiMaps, Vec_Ptr_t ** pvLoMaps ) { assert( Abc_NtkIsNetlist(pNtk) ); *pvLiMaps = Vec_PtrAlloc( 1000 ); *pvLoMaps = Vec_PtrAlloc( 1000 ); return Abc_NtkCollectPiPos_int( NULL, pNtk, *pvLiMaps, *pvLoMaps ); } /**Function************************************************************* Synopsis [Derives logic network with barbufs from the netlist.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Abc_Obj_t * Abc_NtkToBarBufs_rec( Abc_Ntk_t * pNtkNew, Abc_Obj_t * pNet ) { Abc_Obj_t * pObj, * pFanin; int i; assert( Abc_ObjIsNet(pNet) ); if ( pNet->pCopy ) return pNet->pCopy; pObj = Abc_ObjFanin0(pNet); assert( Abc_ObjIsNode(pObj) ); pNet->pCopy = Abc_NtkDupObj( pNtkNew, pObj, 0 ); Abc_ObjForEachFanin( pObj, pFanin, i ) Abc_ObjAddFanin( pObj->pCopy, Abc_NtkToBarBufs_rec(pNtkNew, pFanin) ); return pNet->pCopy; } Abc_Ntk_t * Abc_NtkToBarBufs( Abc_Ntk_t * pNtk ) { char Buffer[1000]; Vec_Ptr_t * vLiMaps, * vLoMaps; Abc_Ntk_t * pNtkNew, * pTemp; Abc_Obj_t * pLatch, * pObjLi, * pObjLo; Abc_Obj_t * pObj, * pLiMap, * pLoMap; int i, k, nBoxes; assert( Abc_NtkIsNetlist(pNtk) ); if ( !Abc_NtkCheckSingleInstance(pNtk) ) return NULL; assert( pNtk->pDesign != NULL ); // start the network pNtkNew = Abc_NtkAlloc( ABC_NTK_LOGIC, pNtk->ntkFunc, 1 ); pNtkNew->pName = Extra_UtilStrsav(pNtk->pName); pNtkNew->pSpec = Extra_UtilStrsav(pNtk->pSpec); // clone CIs/CIs/boxes Abc_NtkCleanCopy_rec( pNtk ); Abc_NtkForEachPi( pNtk, pObj, i ) Abc_ObjFanout0(pObj)->pCopy = Abc_NtkDupObj( pNtkNew, pObj, 1 ); Abc_NtkForEachPo( pNtk, pObj, i ) Abc_NtkDupObj( pNtkNew, pObj, 1 ); // create latches and transfer copy labels nBoxes = Abc_NtkCollectPiPos( pNtk, &vLiMaps, &vLoMaps ); Vec_PtrForEachEntryTwo( Abc_Obj_t *, vLiMaps, Abc_Obj_t *, vLoMaps, pLiMap, pLoMap, i ) { pObjLi = Abc_NtkCreateBi(pNtkNew); pLatch = Abc_NtkCreateLatch(pNtkNew); pObjLo = Abc_NtkCreateBo(pNtkNew); Abc_ObjAddFanin( pLatch, pObjLi ); Abc_ObjAddFanin( pObjLo, pLatch ); pLatch->pData = (void *)ABC_INIT_ZERO; pTemp = NULL; if ( Abc_ObjFanin0(pLiMap)->pNtk != pNtk ) pTemp = Abc_ObjFanin0(pLiMap)->pNtk; else if ( Abc_ObjFanout0(pLoMap)->pNtk != pNtk ) pTemp = Abc_ObjFanout0(pLoMap)->pNtk; else assert( 0 ); sprintf( Buffer, "_%s_in", Abc_NtkName(pTemp) ); Abc_ObjAssignName( pObjLi, Abc_ObjName(Abc_ObjFanin0(pLiMap)), Buffer ); sprintf( Buffer, "_%s_out", Abc_NtkName(pTemp) ); Abc_ObjAssignName( pObjLo, Abc_ObjName(Abc_ObjFanout0(pLoMap)), Buffer ); pLiMap->pCopy = pObjLi; Abc_ObjFanout0(pLoMap)->pCopy = pObjLo; assert( Abc_ObjIsNet(Abc_ObjFanout0(pLoMap)) ); } Vec_PtrFree( vLiMaps ); Vec_PtrFree( vLoMaps ); // rebuild networks Vec_PtrForEachEntry( Abc_Ntk_t *, pNtk->pDesign->vModules, pTemp, i ) Abc_NtkForEachCo( pTemp, pObj, k ) Abc_ObjAddFanin( pObj->pCopy, Abc_NtkToBarBufs_rec(pNtkNew, Abc_ObjFanin0(pObj)) ); pNtkNew->nBarBufs = Abc_NtkLatchNum(pNtkNew); printf( "Hierarchy reader flattened %d instances of logic boxes and introduced %d barbufs.\n", nBoxes, pNtkNew->nBarBufs ); return pNtkNew; } /**Function************************************************************* Synopsis [Converts the logic with barbufs into a hierarchical network.] Description [The base network is the original hierarchical network. The second argument is the optimized network with barbufs. This procedure reconstructs the original hierarcical network which adding logic from the optimized network. It is assumed that the PIs/POs of the original network one-to-one mapping with the flops of the optimized network.] SideEffects [] SeeAlso [] ***********************************************************************/ Abc_Obj_t * Abc_NtkFromBarBufs_rec( Abc_Ntk_t * pNtkNew, Abc_Obj_t * pObj ) { Abc_Obj_t * pFanin; int i; if ( pObj->pCopy ) return pObj->pCopy; Abc_NtkDupObj( pNtkNew, pObj, 0 ); Abc_ObjForEachFanin( pObj, pFanin, i ) Abc_ObjAddFanin( pObj->pCopy, Abc_NtkFromBarBufs_rec(pNtkNew, pFanin) ); return pObj->pCopy; } Abc_Ntk_t * Abc_NtkFromBarBufs( Abc_Ntk_t * pNtkBase, Abc_Ntk_t * pNtk ) { Abc_Ntk_t * pNtkNew, * pTemp; Vec_Ptr_t * vLiMaps, * vLoMaps; Abc_Obj_t * pObj, * pLiMap, * pLoMap; int i, k; assert( pNtkBase->pDesign != NULL ); assert( Abc_NtkIsNetlist(pNtk) ); assert( Abc_NtkIsNetlist(pNtkBase) ); assert( Abc_NtkLatchNum(pNtkBase) == 0 ); assert( Abc_NtkLatchNum(pNtk) == pNtk->nBarBufs ); assert( Abc_NtkWhiteboxNum(pNtk) == 0 ); assert( Abc_NtkBlackboxNum(pNtk) == 0 ); assert( Abc_NtkPiNum(pNtk) == Abc_NtkPiNum(pNtkBase) ); assert( Abc_NtkPoNum(pNtk) == Abc_NtkPoNum(pNtkBase) ); // start networks Abc_NtkCleanCopy_rec( pNtkBase ); Vec_PtrForEachEntry( Abc_Ntk_t *, pNtkBase->pDesign->vModules, pTemp, i ) pTemp->pCopy = Abc_NtkStartFrom( pTemp, pNtk->ntkType, pNtk->ntkFunc ); Vec_PtrForEachEntry( Abc_Ntk_t *, pNtkBase->pDesign->vModules, pTemp, i ) pTemp->pCopy->pAltView = pTemp->pAltView ? pTemp->pAltView->pCopy : NULL; // update box models Vec_PtrForEachEntry( Abc_Ntk_t *, pNtkBase->pDesign->vModules, pTemp, i ) Abc_NtkForEachBox( pTemp, pObj, k ) if ( Abc_ObjIsWhitebox(pObj) || Abc_ObjIsBlackbox(pObj) ) pObj->pCopy->pData = Abc_ObjModel(pObj)->pCopy; // create the design pNtkNew = pNtkBase->pCopy; pNtkNew->pDesign = Abc_DesCreate( pNtkBase->pDesign->pName ); Vec_PtrForEachEntry( Abc_Ntk_t *, pNtkBase->pDesign->vModules, pTemp, i ) Abc_DesAddModel( pNtkNew->pDesign, pTemp->pCopy ); Vec_PtrForEachEntry( Abc_Ntk_t *, pNtkBase->pDesign->vTops, pTemp, i ) Vec_PtrPush( pNtkNew->pDesign->vTops, pTemp->pCopy ); assert( Vec_PtrEntry(pNtkNew->pDesign->vTops, 0) == pNtkNew ); // transfer copy attributes to pNtk Abc_NtkCleanCopy( pNtk ); Abc_NtkForEachPi( pNtk, pObj, i ) pObj->pCopy = Abc_NtkPi(pNtkNew, i); Abc_NtkForEachPo( pNtk, pObj, i ) pObj->pCopy = Abc_NtkPo(pNtkNew, i); Abc_NtkCollectPiPos( pNtkBase, &vLiMaps, &vLoMaps ); assert( Vec_PtrSize(vLiMaps) == Abc_NtkLatchNum(pNtk) ); assert( Vec_PtrSize(vLoMaps) == Abc_NtkLatchNum(pNtk) ); Vec_PtrForEachEntryTwo( Abc_Obj_t *, vLiMaps, Abc_Obj_t *, vLoMaps, pLiMap, pLoMap, i ) { pObj = Abc_NtkBox( pNtk, i ); Abc_ObjFanin0(pObj)->pCopy = pLiMap->pCopy; Abc_ObjFanout0(pObj)->pCopy = pLoMap->pCopy; } Vec_PtrFree( vLiMaps ); Vec_PtrFree( vLoMaps ); // create internal nodes Abc_NtkForEachCo( pNtk, pObj, i ) Abc_ObjAddFanin( pObj->pCopy, Abc_NtkFromBarBufs_rec(pObj->pCopy->pNtk, Abc_ObjFanin0(pObj)) ); // transfer net names Abc_NtkForEachCi( pNtk, pObj, i ) { if ( Abc_ObjFanoutNum(pObj->pCopy) == 0 ) // handle PI without fanout Abc_ObjAddFanin( Abc_NtkCreateNet(pObj->pCopy->pNtk), pObj->pCopy ); Nm_ManStoreIdName( pObj->pCopy->pNtk->pManName, Abc_ObjFanout0(pObj->pCopy)->Id, Abc_ObjFanout0(pObj->pCopy)->Type, Abc_ObjName(Abc_ObjFanout0(pObj)), NULL ); } Abc_NtkForEachCo( pNtk, pObj, i ) Nm_ManStoreIdName( pObj->pCopy->pNtk->pManName, Abc_ObjFanin0(pObj->pCopy)->Id, Abc_ObjFanin0(pObj->pCopy)->Type, Abc_ObjName(Abc_ObjFanin0(pObj)), NULL ); return pNtkNew; } /**Function************************************************************* Synopsis [Collect nodes in the barbuf-friendly order.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkToBarBufsCollect_rec( Abc_Obj_t * pObj, Vec_Ptr_t * vNodes ) { Abc_Obj_t * pFanin; int i; if ( Abc_NodeIsTravIdCurrent( pObj ) ) return; Abc_NodeSetTravIdCurrent( pObj ); assert( Abc_ObjIsNode(pObj) ); Abc_ObjForEachFanin( pObj, pFanin, i ) Abc_NtkToBarBufsCollect_rec( pFanin, vNodes ); Vec_PtrPush( vNodes, pObj ); } Vec_Ptr_t * Abc_NtkToBarBufsCollect( Abc_Ntk_t * pNtk ) { Vec_Ptr_t * vNodes; Abc_Obj_t * pObj; int i; assert( Abc_NtkIsLogic(pNtk) ); assert( pNtk->nBarBufs > 0 ); assert( pNtk->nBarBufs == Abc_NtkLatchNum(pNtk) ); vNodes = Vec_PtrAlloc( Abc_NtkObjNum(pNtk) ); Abc_NtkIncrementTravId( pNtk ); Abc_NtkForEachCi( pNtk, pObj, i ) { if ( i >= Abc_NtkCiNum(pNtk) - pNtk->nBarBufs ) break; Vec_PtrPush( vNodes, pObj ); Abc_NodeSetTravIdCurrent( pObj ); } Abc_NtkForEachCo( pNtk, pObj, i ) { if ( i < Abc_NtkCoNum(pNtk) - pNtk->nBarBufs ) continue; Abc_NtkToBarBufsCollect_rec( Abc_ObjFanin0(pObj), vNodes ); Vec_PtrPush( vNodes, pObj ); Vec_PtrPush( vNodes, Abc_ObjFanout0(pObj) ); Vec_PtrPush( vNodes, Abc_ObjFanout0(Abc_ObjFanout0(pObj)) ); Abc_NodeSetTravIdCurrent( pObj ); Abc_NodeSetTravIdCurrent( Abc_ObjFanout0(pObj) ); Abc_NodeSetTravIdCurrent( Abc_ObjFanout0(Abc_ObjFanout0(pObj)) ); } Abc_NtkForEachCo( pNtk, pObj, i ) { if ( i >= Abc_NtkCoNum(pNtk) - pNtk->nBarBufs ) break; Abc_NtkToBarBufsCollect_rec( Abc_ObjFanin0(pObj), vNodes ); Vec_PtrPush( vNodes, pObj ); Abc_NodeSetTravIdCurrent( pObj ); } assert( Vec_PtrSize(vNodes) == Abc_NtkObjNum(pNtk) ); return vNodes; } /**Function************************************************************* Synopsis [Count barrier buffers.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkCountBarBufs( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pObj; int i, Counter = 0; Abc_NtkForEachNode( pNtk, pObj, i ) Counter += Abc_ObjIsBarBuf( pObj ); return Counter; } /**Function************************************************************* Synopsis [Converts the network to dedicated barbufs and back.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Abc_Ntk_t * Abc_NtkBarBufsToBuffers( Abc_Ntk_t * pNtk ) { Vec_Ptr_t * vNodes; Abc_Ntk_t * pNtkNew; Abc_Obj_t * pObj, * pFanin; int i, k; assert( Abc_NtkIsLogic(pNtk) ); assert( pNtk->pDesign == NULL ); assert( pNtk->nBarBufs > 0 ); assert( pNtk->nBarBufs == Abc_NtkLatchNum(pNtk) ); vNodes = Abc_NtkToBarBufsCollect( pNtk ); // start the network pNtkNew = Abc_NtkAlloc( ABC_NTK_LOGIC, pNtk->ntkFunc, 1 ); pNtkNew->pName = Extra_UtilStrsav(pNtk->pName); pNtkNew->pSpec = Extra_UtilStrsav(pNtk->pSpec); // create objects Abc_NtkCleanCopy( pNtk ); Vec_PtrForEachEntry( Abc_Obj_t *, vNodes, pObj, i ) { if ( Abc_ObjIsPi(pObj) ) Abc_NtkDupObj( pNtkNew, pObj, 1 ); else if ( Abc_ObjIsPo( pObj) ) Abc_ObjAddFanin( Abc_NtkDupObj(pNtkNew, pObj, 1), Abc_ObjFanin0(pObj)->pCopy ); else if ( Abc_ObjIsBi(pObj) || Abc_ObjIsBo(pObj) ) pObj->pCopy = Abc_ObjFanin0(pObj)->pCopy; else if ( Abc_ObjIsLatch(pObj) ) Abc_ObjAddFanin( (pObj->pCopy = Abc_NtkCreateNode(pNtkNew)), Abc_ObjFanin0(pObj)->pCopy ); else if ( Abc_ObjIsNode(pObj) ) { Abc_NtkDupObj( pNtkNew, pObj, 1 ); Abc_ObjForEachFanin( pObj, pFanin, k ) Abc_ObjAddFanin( pObj->pCopy, pFanin->pCopy ); } else assert( 0 ); } Vec_PtrFree( vNodes ); return pNtkNew; } Abc_Ntk_t * Abc_NtkBarBufsFromBuffers( Abc_Ntk_t * pNtkBase, Abc_Ntk_t * pNtk ) { Abc_Ntk_t * pNtkNew; Abc_Obj_t * pObj, * pFanin, * pLatch; int i, k, nBarBufs; assert( Abc_NtkIsLogic(pNtkBase) ); assert( Abc_NtkIsLogic(pNtk) ); assert( pNtkBase->nBarBufs == Abc_NtkLatchNum(pNtkBase) ); // start the network pNtkNew = Abc_NtkStartFrom( pNtkBase, pNtk->ntkType, pNtk->ntkFunc ); // transfer PI pointers Abc_NtkForEachPi( pNtk, pObj, i ) pObj->pCopy = Abc_NtkPi(pNtkNew, i); // assuming that the order/number of barbufs remains the same nBarBufs = 0; Abc_NtkForEachNode( pNtk, pObj, i ) { if ( Abc_ObjIsBarBuf(pObj) ) { pLatch = Abc_NtkBox(pNtkNew, nBarBufs++); Abc_ObjAddFanin( Abc_ObjFanin0(pLatch), Abc_ObjFanin0(pObj)->pCopy ); pObj->pCopy = Abc_ObjFanout0(pLatch); } else { Abc_NtkDupObj( pNtkNew, pObj, 1 ); Abc_ObjForEachFanin( pObj, pFanin, k ) Abc_ObjAddFanin( pObj->pCopy, pFanin->pCopy ); } } assert( nBarBufs == pNtkBase->nBarBufs ); // connect POs Abc_NtkForEachPo( pNtk, pObj, i ) Abc_ObjAddFanin( Abc_NtkPo(pNtkNew, i), Abc_ObjFanin0(pObj)->pCopy ); return pNtkNew; } Abc_Ntk_t * Abc_NtkBarBufsOnOffTest( Abc_Ntk_t * pNtk ) { Abc_Ntk_t * pNtkNew, * pNtkNew2; pNtkNew = Abc_NtkBarBufsToBuffers( pNtk ); pNtkNew2 = Abc_NtkBarBufsFromBuffers( pNtk, pNtkNew ); Abc_NtkDelete( pNtkNew ); return pNtkNew2; } //////////////////////////////////////////////////////////////////////// /// END OF FILE /// //////////////////////////////////////////////////////////////////////// ABC_NAMESPACE_IMPL_END
37.359922
167
0.567255
[ "model" ]
d75b65fa6e94c7f77fcb39954b90a7f52e32c162
2,146
h
C
htssyn/htssyn.h
keeleinstituut/macspeechet
f92e285d6ae307f93e94f8b2644ad128ebdbafc2
[ "Unlicense" ]
null
null
null
htssyn/htssyn.h
keeleinstituut/macspeechet
f92e285d6ae307f93e94f8b2644ad128ebdbafc2
[ "Unlicense" ]
null
null
null
htssyn/htssyn.h
keeleinstituut/macspeechet
f92e285d6ae307f93e94f8b2644ad128ebdbafc2
[ "Unlicense" ]
null
null
null
#pragma once #include "../lib/proof/proof.h" #include "mappings.h" #include "utils.h" #define COUNT_CHILDREN(Function, Vector) \ INTPTR Function() const { \ INTPTR res = 0; \ for (INTPTR ip = 0; ip < Vector.GetSize(); ip++) { \ res += Vector[ip].Function(); \ } \ return res; \ } class CPhone { public: CPhone() { syl_p = word_p = phr_p = utt_p = 0; p6 = p7 = a1 = a3 = b1 = b3 = c1 = c3 = b4 = b5 = b6 = b7 = d2 = e2 = f2 = e3 = e4 = g1 = g2 = h1 = h2 = i1 = i2 = h3 = h4 = j1 = j2 = j3 = 0; } static CFSWString gpos(wchar_t c); CFSWString phone; CFSWString lpos, pos, rpos; INTPTR syl_p, word_p, phr_p, utt_p; INTPTR p6, p7, a1, a3, b1, b3, c1, c3, b4, b5, b6, b7, d2, e2, f2, e3, e4, g1, g2, h1, h2, i1, i2, h3, h4, j1, j2, j3; }; class CSyl { public: CSyl() { stress = 0; word_p = phr_p = 0; } void Process(); INTPTR GetPhoneCount() const { return phone_vector.GetSize(); } CFSWString syl; INTPTR stress; CFSArray<CPhone> phone_vector; INTPTR word_p, phr_p; //INTPTR utt_p; }; class CWord { public: CWord() { weight = 0; phr_p = 0; ref = NULL; } void Process(); INTPTR GetSylCount() const { return syl_vector.GetSize(); } COUNT_CHILDREN(GetPhoneCount, syl_vector); INTPTR GetWeight() const; protected: void CreateSyls(const CFSWString &root); public: CMorphInfo mi; CFSArray<CSyl> syl_vector; INTPTR weight; void *ref; INTPTR phr_p; //INTPTR utt_p; }; class CPhrase { public: void Process(); INTPTR GetWordCount() const { return word_vector.GetSize(); } COUNT_CHILDREN(GetSylCount, word_vector) //CFSWString s; CFSArray<CWord> word_vector; //INTPTR utt_p; }; class CUtterance { public: void Process(); void CreateLabels(CFSAStringArray &Labels) const; INTPTR GetPhraseCount() const { return phr_vector.GetSize(); } COUNT_CHILDREN(GetWordCount, phr_vector); COUNT_CHILDREN(GetSylCount, phr_vector); protected: void FillPositions(); void FillPhones(); void AddPauses(); public: //CFSWString s; CFSArray<CPhrase> phr_vector; };
18.99115
145
0.622088
[ "vector" ]
d764e1e0369a1ed7ca766609f026051144746814
6,732
c
C
lib/EMBOSS-6.6.0/emboss/equicktandem.c
alegione/CodonShuffle
bd6674b2eb21ee144a39d6d1e9b7264aba887240
[ "MIT" ]
5
2016-11-11T21:57:49.000Z
2021-07-27T14:13:31.000Z
lib/EMBOSS-6.6.0/emboss/equicktandem.c
frantallukas10/CodonShuffle
4c408e1a8617f2a52dcb0329bba9617e1be17313
[ "MIT" ]
4
2016-05-15T07:56:25.000Z
2020-05-20T05:21:48.000Z
lib/EMBOSS-6.6.0/emboss/equicktandem.c
frantallukas10/CodonShuffle
4c408e1a8617f2a52dcb0329bba9617e1be17313
[ "MIT" ]
10
2015-08-19T20:37:46.000Z
2020-04-07T06:49:23.000Z
/* @source equicktandem application ** ** Quick tandem repeat finder ** ** @author Copyright (C) Richard Durbin, J Thierry-Mieg ** @@ ** ** 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 2 ** 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, write to the Free Software ** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ******************************************************************************/ /* File: quicktandem.c ** Author: Richard Durbin (rd@mrc-lmba.cam.ac.uk) ** Copyright (C) J Thierry-Mieg and R Durbin, 1993 **------------------------------------------------------------------- ** This file is part of the ACEDB genome database package, written by ** Richard Durbin (MRC LMB, UK) rd@mrc-lmba.cam.ac.uk, and ** Jean Thierry-Mieg (CRBM du CNRS, France) mieg@crbm1.cnusc.fr ** ** Description: to prescreen sequences for tandem repeats. Use ** tandem on anything that looks significant. ** Exported functions: ** HISTORY: ** Created: Tue Jan 19 21:25:59 1993 (rd) **------------------------------------------------------------------- */ #include "emboss.h" static AjPFile outfile = NULL; static AjPSeqCvt cvt = NULL; static void equicktandem_print(AjPFile outf, ajint begin); static void equicktandem_report(AjPFeattable tab, ajint begin); static char *back = NULL; static char *front = NULL; static char *maxback = NULL; static char *maxfront = NULL; static char* sq = NULL; static ajint gap; static ajint max; static ajint score; /* @prog equicktandem ********************************************************* ** ** Finds tandem repeats ** ******************************************************************************/ int main(int argc, char **argv) { ajint thresh; ajint maxrepeat; AjPSeq sequence = NULL; AjPSeq saveseq = NULL; AjPStr tseq = NULL; AjPStr str = NULL; AjPStr substr = NULL; AjPFeattable tab = NULL; AjPReport report = NULL; AjPStr tmpstr = NULL; ajint begin; ajint end; ajint len; embInit("equicktandem", argc, argv); report = ajAcdGetReport("outfile"); outfile = ajAcdGetOutfile("origfile"); sequence = ajAcdGetSeq("sequence"); thresh = ajAcdGetInt("threshold"); maxrepeat = ajAcdGetInt("maxrepeat"); saveseq = ajSeqNewSeq(sequence); tab = ajFeattableNewSeq(saveseq); ajFmtPrintAppS(&tmpstr, "Threshold: %d\n", thresh); ajFmtPrintAppS(&tmpstr, "Maxrepeat: %d\n", maxrepeat); ajReportSetHeaderS(report, tmpstr); begin = ajSeqGetBegin(sequence) - 1; end = ajSeqGetEnd(sequence) - 1; substr = ajStrNew(); str = ajSeqGetSeqCopyS(sequence); ajStrAssignSubS(&substr,str,begin,end); ajSeqAssignSeqS(sequence,substr); cvt = ajSeqcvtNewNumberC("ACGTN"); /* 1-4=ACGT 5=N 0=other */ ajSeqConvertNum(sequence, cvt, &tseq); sq = ajStrGetuniquePtr(&tseq); /* careful - sequence can be shorter than the maximum repeat length */ if((len=ajStrGetLen(substr)) < maxrepeat) maxrepeat = ajStrGetLen(substr); for(gap = 1; gap <= maxrepeat; ++gap) { back = sq; front = back + gap; score = max = 0; while(front-sq<=len) { if(*front == 'Z') /* 'Z' marks a repeat */ { if(max >= thresh) { equicktandem_print(outfile, begin); equicktandem_report(tab, begin); back = maxfront; front = back + gap; score = max = 0; } else { back = front; front = back + gap; score = max = 0; } } else if(*front != *back) --score; else if(score <= 0) { if(max >= thresh) { equicktandem_print(outfile, begin); equicktandem_report(tab, begin); back = maxfront; front = back + gap; score = max = 0; } else { maxback = back; score = 1; } } else if(++score > max) { max = score; maxfront = front; } ++back; ++front; } if(max >= thresh) { equicktandem_print(outfile, begin); equicktandem_report(tab, begin); } } ajReportWrite(report, tab, saveseq); ajReportDel(&report); ajFileClose(&outfile); ajFeattableDel(&tab); ajSeqDel(&sequence); ajSeqDel(&saveseq); ajSeqcvtDel(&cvt); ajStrDel(&str); ajStrDel(&substr); ajStrDel(&tseq); ajStrDel(&tmpstr); embExit(); return 0; } /* @funcstatic equicktandem_print ********************************************* ** ** Prints the original output format, but simply returns if the ** output file is NULL. ** ** Sets the printed region to 'Z' to exclude it from further analysis. ** ** @param [u] outf [AjPFile] Undocumented ** @param [r] begin [ajint] Undocumented ** @@ ******************************************************************************/ static void equicktandem_print(AjPFile outf, ajint begin) { char* cp; if(!outf) return; ajFmtPrintF(outf, "%6d %10d %10d %2d %3d\n", max, 1+maxback-sq+begin, 1+maxfront-sq+begin, gap, (maxfront-maxback+1)/gap); for(cp = maxback; cp <= maxfront; ++cp) *cp = 'Z'; return; } /* @funcstatic equicktandem_report ******************************************** ** ** Saves a result as a feature. ** ** @param [u] tab [AjPFeattable] Undocumented ** @param [r] begin [ajint] Undocumented ** @@ ******************************************************************************/ static void equicktandem_report(AjPFeattable tab, ajint begin) { static char* cp; AjPFeature gf; AjPStr rpthit = NULL; AjPStr s = NULL; if(!rpthit) ajStrAssignC(&rpthit, "SO:0000705"); /* ajFmtPrintF(outf, "%6d %10d %10d %2d %3d\n", max, 1+maxback-sq+begin, 1+maxfront-sq+begin, gap, (maxfront-maxback+1)/gap); */ gf = ajFeatNew(tab, NULL, rpthit, 1+(ajint)(maxback-sq)+begin, 1+(ajint)(maxfront-sq)+begin, (float) max, '+', 0); ajFeatTagAddCC(gf, "rpt_type", "TANDEM"); ajFmtPrintS(&s, "*rpt_size %d", gap); ajFeatTagAddSS(gf, NULL, s); ajFmtPrintS(&s, "*rpt_count %d", (maxfront-maxback+1) / gap); ajFeatTagAddSS(gf, NULL, s); for(cp = maxback; cp <= maxfront; ++cp) *cp = 'Z'; ajStrDel(&rpthit); ajStrDel(&s); return; }
23.87234
79
0.577392
[ "3d" ]
c73c50edcead85ffaabcea98ab2ef3d3bc669a22
4,656
h
C
include/taskgraph/TaskGraph.h
heilhead/task-graph
71ac227ba9814fdb57e0fb7a0432a6d18803c7ad
[ "MIT" ]
null
null
null
include/taskgraph/TaskGraph.h
heilhead/task-graph
71ac227ba9814fdb57e0fb7a0432a6d18803c7ad
[ "MIT" ]
null
null
null
include/taskgraph/TaskGraph.h
heilhead/task-graph
71ac227ba9814fdb57e0fb7a0432a6d18803c7ad
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <thread> #include "Worker.h" #include "PoolAllocator.h" class TaskGraph; namespace { std::unique_ptr<TaskGraph> gInstance; } class Task { friend class TaskChainBuilder; friend class TaskGraph; public: using TaskCallback = void (*)(Task&); private: TaskCallback taskFn; TaskCallback teardownFn = nullptr; Task* parent; Task* next; std::atomic<size_t> childTaskCount; static constexpr size_t TASK_METADATA_SIZE = sizeof(taskFn) + sizeof(teardownFn) + sizeof(parent) + sizeof(next) // NOLINT(bugprone-sizeof-expression) + sizeof(childTaskCount); static constexpr size_t TASK_PAYLOAD_SIZE = std::hardware_destructive_interference_size - TASK_METADATA_SIZE; std::array<uint8_t, TASK_PAYLOAD_SIZE> payload; public: explicit Task(TaskCallback inTaskFn = nullptr, Task* parentTask = nullptr, Task* nextTask = nullptr); void run(); void finish(); void setTeardownFunc(TaskCallback inTeardownFn); template<typename T, typename... Args> void constructData(Args&& ... args) { constexpr auto size = sizeof(T); if constexpr (size <= TASK_PAYLOAD_SIZE) { new(payload.data())T(std::forward<Args>(args)...); } else { *(T**)(payload.data()) = new T(std::forward<Args>(args)...); } } template<typename T> void destroyData() { constexpr auto size = sizeof(T); if constexpr (size <= TASK_PAYLOAD_SIZE) { T* ptr = (T*)payload.data(); ptr->~T(); } else { T* ptr = *(T**)payload.data(); ptr->~T(); } } template<typename T> std::enable_if_t<!std::is_trivially_copyable_v<T>, const T&> getData() const { constexpr auto size = sizeof(T); if constexpr (size <= TASK_PAYLOAD_SIZE) { return *(T*)payload.data(); } else { return *(T**)payload.data(); } } template<typename T> [[maybe_unused]] std::enable_if_t<std::is_trivially_copyable_v<T> && (sizeof(T) <= TASK_PAYLOAD_SIZE)> setData(const T& data) { memcpy(payload.data(), &data, sizeof(data)); } template<typename T> std::enable_if_t<std::is_trivially_copyable_v<T> && (sizeof(T) <= TASK_PAYLOAD_SIZE), const T&> getData() const { return *(T*)payload.data(); } PoolItemHandle<Task> submit(); private: template<typename T> Task* then(T inTaskFn, PoolItemHandle<Task>* parentTask) { if (next == nullptr) { next = *TaskGraph::allocate(inTaskFn, parentTask); } else { next->then(inTaskFn, parentTask); } return this; } }; static_assert(sizeof(Task) == std::hardware_destructive_interference_size, "invalid task size"); class TaskChainBuilder { private: PoolItemHandle<Task> wrapper; PoolItemHandle<Task> first; PoolItemHandle<Task> next; public: TaskChainBuilder(); explicit TaskChainBuilder(PoolItemHandle<Task> parentTask); template<typename T> [[nodiscard]] TaskChainBuilder* add(T taskFn) { if (!first) { first = TaskGraph::allocate(taskFn, &wrapper); next = first; } else { next->then(taskFn, &wrapper); } return this; } PoolItemHandle<Task> submit(); TaskChainBuilder* operator->() { return this; } }; class TaskGraph { public: std::vector<Worker> workers; public: explicit TaskGraph(uint32_t numThreads); void stop(); Worker* getWorker(std::thread::id id); static Worker* getThreadWorker(); static TaskGraph* get(); static void init(uint32_t numThreads); static void shutdown(); template<typename T> static PoolItemHandle<Task> allocate(T inTaskFn, PoolItemHandle<Task>* parentTaskHandle) { auto* pool = Worker::getTaskPool(); auto* parentTask = parentTaskHandle != nullptr ? parentTaskHandle->data() : nullptr; auto* item = pool->obtain([](Task& task) { const auto& taskFn = task.template getData<T>(); taskFn(task); }, parentTask); // @TODO Throw if `item == nullptr` (pool is empty). auto* task = item->data(); task->template constructData<T>(inTaskFn); task->setTeardownFunc([](Task& task) { task.template destroyData<T>(); }); return PoolItemHandle<Task>(item); } };
27.388235
118
0.590206
[ "vector" ]
c742a1c746a912c7194028f6da49fd479d366281
1,605
h
C
snapgear_linux/user/microwin/src/include/nrender.h
impedimentToProgress/UCI-BlueChip
53e5d48b79079eaf60d42f7cb65bb795743d19fc
[ "MIT" ]
null
null
null
snapgear_linux/user/microwin/src/include/nrender.h
impedimentToProgress/UCI-BlueChip
53e5d48b79079eaf60d42f7cb65bb795743d19fc
[ "MIT" ]
null
null
null
snapgear_linux/user/microwin/src/include/nrender.h
impedimentToProgress/UCI-BlueChip
53e5d48b79079eaf60d42f7cb65bb795743d19fc
[ "MIT" ]
3
2016-06-13T13:20:56.000Z
2019-12-05T02:31:23.000Z
/* * NanoWidgets v0.2 * (C) 1999 Screen Media AS * * Written by Vidar Hokstad * * Contains code from The Nano Toolkit, * (C) 1999 by Alexander Peuchert. * */ #ifndef __NRENDER_H #define __NRENDER_H enum { RCOL_WIDGET_BACKGROUND, RCOL_WIDGET_TEXT, RCOL_WIDGET_TEXTBACKGROUND, RCOL_WIDGET_LIGHT, RCOL_WIDGET_MEDIUM, RCOL_WIDGET_DARK, RCOL_HIGHLIGHTED, RCOL_CURSOR, RCOL_MAXCOL }; DEFINE_NOBJECT(render,object) MWCOLORVAL colors[RCOL_MAXCOL]; END_NOBJECT DEFINE_NCLASS(render,object) NSLOT(int,init); NSLOT(void,border); /* Draw a pressed or unpressed border, typically for buttons etc. */ NSLOT(void,panel); /* Draw a pressed or unpressed panel, with surrounding border */ NSLOT(void,widgetbackground); /* Draw a pressed or unpressed widget background. How the background is * rendered is undefined. The background is assumed to be drawn before * the border, and before any "inner parts" of the widget is drawn */ NSLOT(MWCOLORVAL,getcolor); END_NCLASS #define n_render_init(__this__) n_call(render,init,__this__,(__this__)) #define n_render_getcolor(__this__,__col__) n_call(render,getcolor,__this__,(__this__,__col__)) #define n_render_border(__this__,widget,x,y,w,h,pressed) n_call(render,border,__this__,(__this__,widget,x,y,w,h,pressed)) #define n_render_panel(__this__,widget,x,y,w,h,pressed) n_call(render,panel,__this__,(__this__,widget,x,y,w,h,pressed)) typedef struct render_nobject NRENDER; void n_init_render_class(void); /* Initialise render class */ #endif
30.865385
121
0.727103
[ "render", "object" ]
c748ebbdd2d68ffa52d1085e38f816ce122aa3a6
1,256
h
C
examples/ocr.h
corleonechensiyu/ncnn-8-12
440cb87951ade24ca4fe595012978bfe0df5251b
[ "BSD-3-Clause" ]
null
null
null
examples/ocr.h
corleonechensiyu/ncnn-8-12
440cb87951ade24ca4fe595012978bfe0df5251b
[ "BSD-3-Clause" ]
null
null
null
examples/ocr.h
corleonechensiyu/ncnn-8-12
440cb87951ade24ca4fe595012978bfe0df5251b
[ "BSD-3-Clause" ]
null
null
null
#include <stdio.h> #include <vector> #include "platform.h" #include "net.h" #include <iostream> #include <string> #include "benchmark.h" #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <cpu.h> #include <unistd.h> using namespace std; static int detect(const cv::Mat& bgr , vector<float>& scores) { ncnn::Net ocr; ocr.load_param("dd-v3.param"); ocr.load_model("dd-v3.bin"); ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data,ncnn::Mat::PIXEL_BGR,bgr.cols,bgr.rows,64,32); const float mean_vals[3]={141.f,135.f,122.f}; in.substract_mean_normalize(mean_vals, 0); double start = ncnn::get_current_time(); ncnn::Extractor ex = ocr.create_extractor(); ex.set_num_threads(2); //ncnn::set_cpu_powersave(2); ex.input("data",in); ncnn::Mat out; ex.extract("result",out); double end = ncnn::get_current_time(); double time = end - start; static const char* ocr_names[]={"blank","0","1","2","3","4","5","6","7","8","9","."}; string str; scores.resize(5); for(int j=0;j<5;j++) { //scores[j]=out[j]; if(0<=out[j]-1 && out[j]<12) { scores[j]=out[j]; int index=scores[j]; str += ocr_names[index]; } } cout<<str<<endl; cout<<time<<endl; return 0; }
20.590164
108
0.636146
[ "vector" ]
c74b6e6ad98bafe84a2d46197bdbbe87dc05e694
2,072
c
C
utils/spktime2count.c
ShenghaoWu/SNOPS
64ffe8258eb632475bce5076c80211da0bb9f3d8
[ "MIT" ]
2
2021-11-06T03:07:04.000Z
2022-03-23T01:34:09.000Z
utils/spktime2count.c
ShenghaoWu/SNOPS
64ffe8258eb632475bce5076c80211da0bb9f3d8
[ "MIT" ]
null
null
null
utils/spktime2count.c
ShenghaoWu/SNOPS
64ffe8258eb632475bce5076c80211da0bb9f3d8
[ "MIT" ]
null
null
null
/* Y=spktime2count(s,idx, Tw, Ncount,option) */ /* transform spike trains to spike counts Y is neuron # x trial # counts are non-overlapping option=1, if neuronIdx is continuous and sorted, 0 if not count from t=0; */ #include "mex.h" #include "math.h" #include "time.h" #include "matrix.h" void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { int i,j,k, ID,count, temp, Nid, m1,m2,Ns, Ncount,ID1,ID2,option; double *neuronIdx, *s; double Tw, T, *Pr,ts, *Y; /****** * Import variables from matlab * This is messy looking and is specific to mex. * Ignore if you're implementing this outside of mex. *******/ s = mxGetPr(prhs[0]); m1 = mxGetM(prhs[0]); Ns = mxGetN(prhs[0]); if(m1!=2){ mexErrMsgTxt("s should be 2xNs"); } neuronIdx = mxGetPr(prhs[1]); Nid = mxGetM(prhs[1]); m1 = mxGetN(prhs[1]); if(m1!=1){ temp=Nid; Nid=m1; m1=temp; } if(m1!=1){ mexErrMsgTxt("neuron id needs to be a vector or a row."); } Tw = mxGetScalar(prhs[2]); Ncount = (int)mxGetScalar(prhs[3]); option = (int)mxGetScalar(prhs[4]); /* 1, if neuronIdx is continuous and sorted, 0 if not */ if(option){ ID1=neuronIdx[0]; ID2=neuronIdx[Nid-1]; /* mexPrintf("ID1=%d,ID2=%d,option=%d",ID1,ID2,option); */ } /* Allocate output vector */ /* mexPrintf("Ns=%d, Ncount=%d, Nid=%d",Ns,Ncount,Nid); mexErrMsgTxt("stop"); */ plhs[0] = mxCreateDoubleMatrix(Nid, Ncount, mxREAL); Y=mxGetPr(plhs[0]); /* main codes */ for(i=0;i<Nid*Ncount;i++){ Y[i]=0; } Pr=&s[0]; for(k=0;k<Ns;k++){ ts=*Pr; count=(int)floor(ts/Tw); if(count<Ncount){ Pr++;ID=(int)*Pr; if(option){ if(ID>ID1-0.1&ID<ID2+0.1){ j=ID-ID1; Y[j+count*Nid]++;} } else{ for(j=0;j<Nid;j++){ if(((int)neuronIdx[j])==ID){ Y[j+count*Nid]++;} } } } else{ break;} Pr++; } }
19.923077
92
0.533784
[ "vector", "transform" ]
c751075eda42460384d95f5ae27a643e3c600267
2,909
h
C
libraries/AudioDspDriver/AudioDspDriver.h
novaprimexex/LittleArduinoProjects
382d9827459882c19afe20513cc1232214a047c6
[ "MIT" ]
1
2020-12-27T17:38:55.000Z
2020-12-27T17:38:55.000Z
libraries/AudioDspDriver/AudioDspDriver.h
novaprimexex/LittleArduinoProjects
382d9827459882c19afe20513cc1232214a047c6
[ "MIT" ]
null
null
null
libraries/AudioDspDriver/AudioDspDriver.h
novaprimexex/LittleArduinoProjects
382d9827459882c19afe20513cc1232214a047c6
[ "MIT" ]
null
null
null
#ifndef AudioDspDriver_h #define AudioDspDriver_h #define __STDC_LIMIT_MACROS #include <stdint.h> #include <Arduino.h> #define DEFAULT_LED_PIN (13) #define DEFAULT_FOOTSWITCH_PIN (12) #define DEFAULT_TOGGLE_PIN (2) #define DEFAULT_PUSHBUTTON_LEFT_PIN (A5) #define DEFAULT_PUSHBUTTON_RIGHT_PIN (A4) #define DEFAULT_PUSHBUTTON_STEP (4) // level movement for each pb press #define DEFAULT_PWM_FREQ (0x00FF) // pwm frequency - 31.3KHz #define DEFAULT_PWM_MODE (0) // Fast (1) or Phase Correct (0) #define DEFAULT_PWM_QTY (2) class AudioDspDriver { public: AudioDspDriver(); /* * Initialise controls and ports. */ void init(); /* * Initialise ADC. */ void init_adc(); /* * Initialise PWM. */ void init_pwm(); /* * Reset all settings to defaults. */ void reset(); /* * Scan and update all controls. */ void process_controls(); /* * Turn on the LED if the effect is ON. */ void process_footswitch(); /* * Pushbuttons control the volume up/down */ void process_pushbuttons(); /* * Check the toggle switch state. */ void process_toggle(); /* * Control the LED (on/off) */ void led(bool state); /* * Read ADC value. Sets and returns `current_input`. */ int16_t read(); /* * Write `current_output` value */ void write(); /* * Read/Write input to output with standard transform. * Sets `current_input` and `current_output` as a by-product. */ void transform(); /* * Read/Write input to output with suppplied transformer function. * transformer function takes two parameters: input and pb_level * * int transformer(int input, int pb_level) * * input is 16-bit signed input signal (values from -32768 to +32768, INT16_MIN to INT16_MAX) * pb_level is 0-1024 with midpoint 512 * * Sets `current_input` and `current_output` as a by-product. */ void transform(int16_t (*transformer)(int16_t, int)); /* * Command: set pushbutton level. * pb_level is 0-1024 with midpoint 512 */ void pb_level(int new_level); /* * Return the current pushbutton level. * pb_level is 0-1024 with midpoint 512 */ int pb_level(); /* * Return the current toggle switch state. */ bool toggle_state(); /* * Return the current footswitch switch state. */ bool footswitch_state(); volatile int16_t current_input; volatile int16_t current_output; private: int led_pin; int footswitch_pin; int toggle_pin; int pb_left_pin; int pb_right_pin; int pb_level_value; byte footswitch_value; byte toggle_value; byte pb_step; int pwm_freq; int pwm_mode; int pwm_qty; }; #endif
19.789116
97
0.619801
[ "transform" ]
c75157c99f5f10b8b65c2f9b9365da058498eff6
3,496
h
C
iotcloud/include/tencentcloud/iotcloud/v20180614/model/BatchPublishMessage.h
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
iotcloud/include/tencentcloud/iotcloud/v20180614/model/BatchPublishMessage.h
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
iotcloud/include/tencentcloud/iotcloud/v20180614/model/BatchPublishMessage.h
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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. */ #ifndef TENCENTCLOUD_IOTCLOUD_V20180614_MODEL_BATCHPUBLISHMESSAGE_H_ #define TENCENTCLOUD_IOTCLOUD_V20180614_MODEL_BATCHPUBLISHMESSAGE_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Iotcloud { namespace V20180614 { namespace Model { /** * 批量发消息请求 */ class BatchPublishMessage : public AbstractModel { public: BatchPublishMessage(); ~BatchPublishMessage() = default; void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const; CoreInternalOutcome Deserialize(const rapidjson::Value &value); /** * 获取消息发往的主题。为 Topic 权限中去除 ProductID 和 DeviceName 的部分,如 “event” * @return Topic 消息发往的主题。为 Topic 权限中去除 ProductID 和 DeviceName 的部分,如 “event” */ std::string GetTopic() const; /** * 设置消息发往的主题。为 Topic 权限中去除 ProductID 和 DeviceName 的部分,如 “event” * @param Topic 消息发往的主题。为 Topic 权限中去除 ProductID 和 DeviceName 的部分,如 “event” */ void SetTopic(const std::string& _topic); /** * 判断参数 Topic 是否已赋值 * @return Topic 是否已赋值 */ bool TopicHasBeenSet() const; /** * 获取消息内容 * @return Payload 消息内容 */ std::string GetPayload() const; /** * 设置消息内容 * @param Payload 消息内容 */ void SetPayload(const std::string& _payload); /** * 判断参数 Payload 是否已赋值 * @return Payload 是否已赋值 */ bool PayloadHasBeenSet() const; private: /** * 消息发往的主题。为 Topic 权限中去除 ProductID 和 DeviceName 的部分,如 “event” */ std::string m_topic; bool m_topicHasBeenSet; /** * 消息内容 */ std::string m_payload; bool m_payloadHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_IOTCLOUD_V20180614_MODEL_BATCHPUBLISHMESSAGE_H_
32.981132
116
0.519165
[ "vector", "model" ]
c76ba28607901868220989e1d3d67739f641e5b4
5,944
c
C
adm/daemons/fingerd.c
ttwings/WuXiaAndJiangHu_Godot
a12bb9028d5625ea01de1ea9cb16fef665472275
[ "MIT" ]
34
2019-04-16T03:32:27.000Z
2022-03-29T08:05:25.000Z
adm/daemons/fingerd.c
ttwings/WuXiaAndJiangHu_Godot
a12bb9028d5625ea01de1ea9cb16fef665472275
[ "MIT" ]
null
null
null
adm/daemons/fingerd.c
ttwings/WuXiaAndJiangHu_Godot
a12bb9028d5625ea01de1ea9cb16fef665472275
[ "MIT" ]
12
2019-03-06T05:15:45.000Z
2022-03-17T02:43:48.000Z
// fingerd.c // Modified by Constant Apr 21 2000` #include <net/dns.h> #include <ansi.h> int sort_user(object ob1, object ob2); void create() { seteuid(getuid()); } string age_string(int time) { int month, day, hour, min, sec; sec = time % 60; time /= 60; min = time % 60; time /= 60; hour = time % 24; time /= 24; day = time % 30; month = time / 30; return (month ? month + "m" : "") + (day ? day + "d" : "") + (hour ? hour + "h" : "") + min + "m"; } string finger_all() { object *ob; string msg, fip; int i; // ob = users(); // 输出格式按照ip排序,Modified by Constant ob = sort_array(users(), ( : sort_user:)); msg = ""; if (!wizardp(this_player())) // player finger { for (i = 0; i < sizeof(ob); i++) { if (this_player() && !this_player()->visible(ob[i])) continue; msg = sprintf("%s%-14s%-14s%-14s\n", msg, ob[i]->query("name"), ob[i]->query("id"), query_idle(ob[i]) + "s"); } return "◎ 侠客行一百\n" + "──────────────────\n" + "姓名 帐号 发呆\n" + "──────────────────\n" + msg + "──────────────────\n"; } else // wizard finger { for (i = 0; i < sizeof(ob); i++) { if (this_player() && !this_player()->visible(ob[i])) continue; msg = sprintf("%s%-14s%-14s%-14s%-7s%s\n", msg, ob[i]->query("name"), ob[i]->query("id"), age_string((int)ob[i]->query("mud_age")), query_idle(ob[i]) + "s", query_ip_name(ob[i])); } return "◎ 侠客行\n" + "─────────────────────────────────────\n" + "姓名 帐号 年龄 发呆 连线\n" + "─────────────────────────────────────\n" + msg + "────────────────────────────────────\n"; } } string finger_user(string name) { object ob, body; string msg, mud; int public_flag; int no_wiz; /* if( sscanf(name, "%s@%s", name, mud)==2 ) { GFINGER_Q->send_finger_q(mud, name, this_player(1)); return "网路指令传送过程可能需要一些时间,请稍候。\n"; } */ ob = new (LOGIN_OB); ob->set("id", name); if (!ob->restore()) { destruct(ob); return "没有这个玩家。\n"; } if (!wizardp(this_player())) // player finger { if (objectp(body = find_player(name)) && (geteuid(body) == name || (body->query("id") == name && body->query("no_look_wiz")))) { if (body->query("no_look_wiz")) no_wiz = 1; // public_flag = body->query("env/public")?1:0; public_flag = 1; } else { body = LOGIN_D->make_body(ob); if (!body->restore()) { destruct(ob); destruct(body); return "没有这个玩家。\n"; } // public_flag = body->query("env/public")?1:0; public_flag = 1; destruct(body); } msg = sprintf("\n英文代号:\t%s\n姓 名:\t%s\n权限等级:\t%s\n" "电子邮件地址:\t%s\n上次连线:\t%s\n\n", ob->query("id"), ob->query("name"), SECURITY_D->get_status(name), public_flag ? ob->query("email") : "不告诉你", ctime(ob->query("last_on"))); if (objectp(body = find_player(name)) && (geteuid(body) == name || (body->query("id") == name && body->query("no_look_wiz")))) { if (!wizardp(body) || this_player()->visible(body) || body->query("no_look_wiz")) { msg += sprintf("\n%s目前正在连线中。\n", body->name(1)); if (ob->query("id") != this_player()->query("id")) message("channel:chat", HIC "【闲聊】“啊......嚏!”" + body->name(1) + "打了个大喷嚏,揉了揉鼻子嘟囔道:“一定是我那口子" + this_player()->query("name") + "又在想我了。”\n" NOR, users()); } else tell_object(find_player(name), WHT + this_player()->query("name") + "(" + this_player()->query("id") + ")" + "正在乱捅你。\n" NOR); } } else // wizard finger { msg = sprintf("\n英文代号:\t%s\n姓 名:\t%s\n权限等级:\t%s\n" "电子邮件地址:\t%s\n上次连线地址:\t%s( %s )\n\n", ob->query("id"), ob->query("name"), SECURITY_D->get_status(name), ob->query("email"), ob->query("last_from"), ctime(ob->query("last_on"))); if (objectp(body = find_player(name)) && geteuid(body) == name) { msg += sprintf("\n%s目前正在从 %s 连线中。\n", body->name(1), query_ip_name(body)); } } destruct(ob); return msg; } varargs string remote_finger_user(string name, int chinese_flag) { object ob, body; string msg; ob = new (LOGIN_OB); ob->set("id", name); if (!ob->restore()) { destruct(ob); return chinese_flag ? "没有这个玩家。\n" : "No such user.\n"; } if (chinese_flag) msg = sprintf( "\n英文代号:\t%s\n姓 名:\t%s\n权限等级:\t%s\n" "电子邮件地址:\t%s\n上次连线地址:\t%s( %s )\n\n", ob->query("id"), ob->query("name"), SECURITY_D->get_status(name), ob->query("email"), ob->query("last_from"), ctime(ob->query("last_on"))); else msg = sprintf( "\nName\t: %s\nStatus\t: %s\nEmail\t: %s\nLastOn\t: %s( %s )\n\n", capitalize(ob->query("id")), SECURITY_D->get_status(name), ob->query("email"), ob->query("last_from"), ctime(ob->query("last_on"))); if (body = find_player(name)) { if (!this_player() || this_player()->visible(body)) msg += chinese_flag ? ("\n" + ob->query("name") + "目前正在线上。\n") : ("\n" + capitalize(name) + " is currently connected.\n"); message("channel:chat", HIC "【闲聊】“啊......嚏!”" + body->name(1) + "打了个大喷嚏,揉了揉鼻子嘟囔道:“一定是我那口子" + this_player()->query("name") + "又在想我了。”\n" NOR, users()); } destruct(ob); return msg; } object acquire_login_ob(string id) { object ob; if (ob = find_player(id)) { // Check if the player is linkdead if (ob->query_temp("link_ob")) return ob->query_temp("link_ob"); } ob = new (LOGIN_OB); ob->set("id", id); // return ob->restore() ? ob : 0; if (ob->restore()) return ob; else { destruct(ob); return 0; } } string get_killer() { int i; string msg; object *ob = users(); msg = ""; for (i = 0; i < sizeof(ob); i++) if ((int)ob[i]->query_condition("killer")) msg += (ob[i]->short() + "\n"); if (msg == "") return "本城治安良好。\n"; else return "现在本城正在缉拿以下人犯:\n\n" + msg; } int sort_user(object ob1, object ob2) { return strcmp(query_ip_name(ob1), query_ip_name(ob2)); }
24.766667
155
0.530956
[ "object" ]
c76fa44e7b467a7551e3fd5dfea0396205a19388
1,141
h
C
source-code/particles.h
michael-horansky/magnetic-gas
a48dafa15868ee169d8bdc866cdd457a7bfc88eb
[ "MIT" ]
null
null
null
source-code/particles.h
michael-horansky/magnetic-gas
a48dafa15868ee169d8bdc866cdd457a7bfc88eb
[ "MIT" ]
null
null
null
source-code/particles.h
michael-horansky/magnetic-gas
a48dafa15868ee169d8bdc866cdd457a7bfc88eb
[ "MIT" ]
null
null
null
#ifndef C_PARTICLE #define C_PARTICLE #include "container.h" class Container; class Particle { public: Particle(); Particle(Container *my_parent_container, double start_pos_x, double start_pos_y, double start_pos_z, double start_vel_x, double start_vel_y, double start_vel_z, double start_mass, double start_inertia); ~Particle(); void randomize_particle(double max_vel); virtual std::vector<double> force_imposed_by(Particle *other) {return std::vector<double>(6,0.0);} virtual std::vector<double> force_imposed_by_container() {return std::vector<double>(6,0.0);} virtual void rotate_self() {} double p_x; double p_y; double p_z; double v_x; double v_y; double v_z; double a_x; double a_y; double a_z; double next_a_x; double next_a_y; double next_a_z; double m; double r; double inertia; double omega_x; double omega_y; double omega_z; double eps_x; double eps_y; double eps_z; std::vector<double> cloud_p_x; std::vector<double> cloud_p_y; Container *parent_container; }; #endif // C_PARTICLE
21.528302
206
0.687993
[ "vector" ]
c77295b806855331c5a91b662b6658306a5cdebe
46,316
c
C
BSLDEMO-2.01c/Source/bsldemo.c
gbhug5a/MSP430-BSL
2814466302346fdea27ccb589f6c018a9ed11419
[ "MIT" ]
9
2017-12-27T19:19:32.000Z
2022-03-20T15:15:57.000Z
BSLDEMO-2.01c/Source/bsldemo.c
gbhug5a/MSP430-BSL
2814466302346fdea27ccb589f6c018a9ed11419
[ "MIT" ]
2
2021-01-13T14:32:37.000Z
2021-01-14T09:16:17.000Z
BSLDEMO-2.01c/Source/bsldemo.c
gbhug5a/MSP430-BSL
2814466302346fdea27ccb589f6c018a9ed11419
[ "MIT" ]
2
2019-04-25T10:01:20.000Z
2021-09-06T03:37:47.000Z
/**************************************************************** * * Copyright (C) 1999-2000 Texas Instruments, Inc. * Author: Volker Rzehak * Co-author: FRGR * *---------------------------------------------------------------- * All software and related documentation is provided "AS IS" and * without warranty or support of any kind and Texas Instruments * expressly disclaims all other warranties, express or implied, * including, but not limited to, the implied warranties of * merchantability and fitness for a particular purpose. Under no * circumstances shall Texas Instruments be liable for any * incidental, special or consequential damages that result from * the use or inability to use the software or related * documentation, even if Texas Instruments has been advised of * the liability. * * Unless otherwise stated, software written and copyrighted by * Texas Instruments is distributed as "freeware". You may use * and modify this software without any charge or restriction. * You may distribute to others, as long as the original author * is acknowledged. * **************************************************************** * * Project: MSP430 Bootstrap Loader Demonstration Program * * File:BSLDEMO.C * * Description: * This is the main program of the bootstrap loader * demonstration. * The main function holds the general sequence to access the * bootstrap loader and program/verify a file. * The parsing of the TI TXT file is done in a separate * function. * * A couple of parameters can be passed to the program to * control its functions. For a detailed description see the * appendix of the corresponding application note. * * History: * Version 1.00 (05/2000) * Version 1.10 (08/2000) * - Help screen added. * - Additional mass erase cycles added * (Required for larger flash memories) * Defined with: #define ADD_MERASE_CYCLES 20 * - Possibility to load a completely new BSL into RAM * (supposing there is enough RAM) - Mainly a test feature! * - A new workaround method to cope with the checksum bug * established. Because this workaround is incompatbile with * the former one the required TI TXT file is renamed to * "PATCH.TXT". * Version 1.12 (09/2000) * - Added handling of frames with odd starting address * to BSLCOMM.C. (This is required for loaders with word * programming algorithm! > BSL-Version >= 1.30) * - Changed default number of data bytes within one frame * to 240 bytes (old: 64). Speeds up programming. * - Always read BSL version number (even if new one is loaded * into RAM. * - Fixed setting of warning flag in conjunction with loading * a new BSL into RAM. * - Added a byte counter to the programTIText function. * - Number of mass erase cycles can be changed via command * line option (-m) * Version 1.14 * 11/2000 FRGR: * - Minor text bug fixes and cosmetics (title aso...). * - Read startaddress for loadable BSL from file * 05/2001 FRGR: * - Implementation of "+f" parameter for Fast Erase Check by * File (BSL cmd "0x1C"). Could be speeded up for Mass * Erase (one single command with whole address range). * - Bargraph for displaying progress of read/write activities. * 08/2001 FRGR: * - See test sequences for new features at file end. * - Skip verify if BSL with online verification is used. * - Implementation of "-s{0,1,2}" parameter for Change Baudrate * command (BSL cmd "0x20"). * - Implementation of "+#" parameter for executing test sequences * - Time measurement for "Prog/Verify" and "Over all" (in sec). * Version 1.15 * 01/2004 FRGR * - Test sequence: Wrong password performs a Mass Erase. * - Implementation of "+u" parameter for "User Call" simulation * - Open Help screen also if no cmdline parameter. * UPSF * - Fixed bug in end detection of help * Version 2.00 * 10/2004 FRGR * - added support for 2.xx * 03/2005 UPSF * - added updated support for 2.xx * - added read file function * - added support for higher COM ports ( > COM4 ) * - added Erase Segment function * - added support for Extended Memory (MSP430X) * - added restore function for InfoA Segment * - fixed handling of wait option - it got ignored in +option * - changed parsing of command line so that a parameter without + or - is used as filename * Version 2.01 * - fixed change baud rate for G2xx3 parts (handles device ID starting with 0x25) * * Change by GH: * * Version 2.01b * - added +i Program Flow Specifier to invert DTR line * * Version 2.01c * - deleted +i Program Flow Operator - replaced by -i Option * * - added -i Option to invert DTR line (for use with USB-to-Serial adapters) * - added -j Option to invert RTS line (for parts with dedicated JTAG pins) * ****************************************************************/ #include <string.h> #include <stdio.h> #include <conio.h> #include <windows.h> #include "bslcomm.h" #include "TI_TXT_Files.h" /*--------------------------------------------------------------- * Defines: *--------------------------------------------------------------- */ /* This definition includes code to load a new BSL into RAM: * NOTE: Can only be used with devices with sufficient RAM! * The program flow is changed slightly compared to a version * without "NEW_BSL" defined. * The definition also defines the filename of the TI-TXT file * with the new BSL code. */ #define NEW_BSL /* The "WORKAROUND" definition includes code for a workaround * required by the first version(s) of the bootstrap loader. */ #define WORKAROUND /* If "DEBUGDUMP" is defined, all checked and programmed blocks are * logged on the screen. */ #define DEBUGDUMP /* Additional mass erase cylces required for (some) F149 devices. * If ADD_MERASE_CYCLES is not defined only one mass erase * cycle is executed. * Remove #define for fixed F149 or F11xx devices. */ #define ADD_MERASE_CYCLES 20 /* Error: verification failed: */ #define ERR_VERIFY_FAILED 98 /* Error: erase check failed: */ #define ERR_ERASE_CHECK_FAILED 97 /* Error: unable to open input file: */ #define ERR_FILE_OPEN 96 /* Mask: program data: */ #define ACTION_PROGRAM 0x01 /* Mask: verify data: */ #define ACTION_VERIFY 0x02 /* Mask: erase check: */ #define ACTION_ERASE_CHECK 0x04 /* Mask: transmit password: */ /* Note: Should not be used in conjunction with any other action! */ #define ACTION_PASSWD 0x08 /* Mask: erase check fast: */ #define ACTION_ERASE_CHECK_FAST 0x10 /*--------------------------------------------------------------- * Global Variables: *--------------------------------------------------------------- */ char *programName= "MSP430 Bootstrap Loader Communication Program"; char *programVersion= "Version 2.01c"; /* Max. bytes sent within one frame if parsing a TI TXT file. * ( >= 16 and == n*16 and <= MAX_DATA_BYTES!) */ int maxData= 240; /* Change by GH */ BOOL InvertDTR = FALSE; /* New flag for -i Option to invert DTR */ BOOL InvertRTS = FALSE; /* New flag for -j Option to invert RTS */ /* Buffers used to store data transmitted to and received from BSL: */ BYTE blkin [MAX_DATA_BYTES]; /* Receive buffer */ BYTE blkout[MAX_DATA_BYTES]; /* Transmit buffer */ #ifdef WORKAROUND char *patchFilename = "PATCH.TXT"; char *patchFile = NULL; #endif /* WORKAROUND */ BOOL patchRequired = FALSE; BOOL patchLoaded = FALSE; WORD bslVer = 0; WORD _addr, _len, _err; BYTE speed = 0; /* default 9600 Baud */ DWORD Time_BSL_starts, Time_PRG_starts, Time_BSL_stops; char *newBSLFile= NULL; char newBSLFilename[256]; struct toDoList { unsigned MassErase : 1; unsigned EraseCheck: 1; unsigned FastCheck : 1; unsigned Program : 1; unsigned Verify: 1; unsigned Reset : 1; unsigned Wait : 1; /* Wait for <Enter> at end of program */ /* (0: no; 1: yes): */ unsigned OnePass : 1; /* Do EraseCheck, Program and Verify */ /* in one pass (TI TXT file is read */ /* only once) */ unsigned SpeedUp : 1; /* Change Baudrate */ unsigned UserCalled: 1; /* Second run without entry sequence */ unsigned BSLStart: 1; /* Start BSL */ unsigned Dump2file:1; /* Dump Memory to file */ unsigned EraseSegment:1;/* Erase Segment */ unsigned MSP430X:1; /* Enable MSP430X Ext.Memory support */ unsigned RestoreInfoA:1;/* Save InfoA before mass erase */ } toDo; int error= ERR_NONE; int i, j; char comPortName[20]= "COM1"; // Default setting. char *filename= NULL; char *passwdFile= NULL; char passwdFilename[256]; BYTE bslVerHi, bslVerLo, devTypeHi, devTypeLo, devProcHi, devProcLo; WORD bslerrbuf; #ifdef ADD_MERASE_CYCLES int meraseCycles= ADD_MERASE_CYCLES; #else const int meraseCycles= 1; #endif // ADD_MERASE_CYCLES long readStart = 0; long readLen = 0; char *readfilename = NULL; void *errData= NULL; int byteCtr= 0; /*--------------------------------------------------------------- * Functions: *--------------------------------------------------------------- */ int preparePatch() { int error= ERR_NONE; #ifdef WORKAROUND if (patchLoaded) { /* Load PC with 0x0220. * This will invoke the patched bootstrap loader subroutines. */ error= bslTxRx(BSL_LOADPC, /* Command: Load PC */ 0x0220, /* Address to load into PC */ 0, /* No additional data! */ NULL, blkin); if (error != ERR_NONE) return(error); BSLMemAccessWarning= 0; /* Error is removed within workaround code */ } #endif /* WORKAROUND */ return(error); } void postPatch() { #ifdef WORKAROUND if (patchLoaded) { BSLMemAccessWarning= 1; /* Turn warning back on. */ } #endif /* WORKAROUND */ } int verifyBlk(unsigned long addr, WORD len, unsigned action) { int i= 0; int error= ERR_NONE; if ((action & (ACTION_VERIFY | ACTION_ERASE_CHECK)) != 0) { #ifdef DEBUGDUMP printf("Check starting at %x, %i bytes... ", addr, len); #endif /* DEBUGDUMP */ error= preparePatch(); if (error != ERR_NONE) return(error); if (toDo.MSP430X) { if (error = bslTxRx(BSL_MEMOFFSET, 0, (WORD)(addr>>16), NULL, blkin) !=0) return (error); addr = addr & 0xFFFF; } error= bslTxRx(BSL_RXBLK, addr, len, NULL, blkin); postPatch(); #ifdef DEBUGDUMP printf("Error: %i\n", error); #endif /* DEBUGDUMP */ if (error != ERR_NONE) { return(error); /* Cancel, if read error */ } else { for (i= 0; i < len; i++) { if ((action & ACTION_VERIFY) != 0) { /* Compare data in blkout and blkin: */ if (blkin[i] != blkout[i]) { printf("Verification failed at %x (%x, %x)\n", addr+i, blkin[i], blkout[i]); return(ERR_VERIFY_FAILED); /* Verify failed! */ } continue; } if ((action & ACTION_ERASE_CHECK) != 0) { /* Compare data in blkin with erase pattern: */ if (blkin[i] != 0xff) { printf("Erase Check failed at %x (%x)\n", addr+i, blkin[i]); return(ERR_ERASE_CHECK_FAILED); /* Erase Check failed! */ } continue; } /* if ACTION_ERASE_CHECK */ } /* for (i) */ } /* else */ if (toDo.MSP430X) if (error = bslTxRx(BSL_MEMOFFSET, 0, (WORD)(0),NULL, blkin) !=0) return (error); } /* if ACTION_VERIFY | ACTION_ERASE_CHECK */ else if ((action & ACTION_ERASE_CHECK_FAST) != 0) /* FRGR 02/01 */ { #ifdef DEBUGDUMP printf("Fast Check starting at %x, %i bytes... ", addr, len); #endif /* DEBUGDUMP */ error= preparePatch(); if (error != ERR_NONE) return(error); error= bslTxRx(BSL_ECHECK, addr, len, NULL, blkin); postPatch(); #ifdef DEBUGDUMP printf("Error: %i\n", error); #endif /* DEBUGDUMP */ if (error != ERR_NONE) { return(ERR_ERASE_CHECK_FAILED); /* Erase Check failed! */ } } /* if ACTION_ERASE_CHECK_FAST */ return(error); } int programBlk(unsigned long addr, WORD len, unsigned action) { int i= 0; int error= ERR_NONE; if ((action & ACTION_PASSWD) != 0) { return(bslTxRx(BSL_TXPWORD, /* Command: Transmit Password*/ addr, /* Address of interupt vectors */ len, /* Number of bytes */ blkout, blkin)); } /* if ACTION_PASSWD */ /* Check, if specified range is erased: */ if (action & ACTION_ERASE_CHECK) error= verifyBlk(addr, len, action & ACTION_ERASE_CHECK); else if (action & ACTION_ERASE_CHECK_FAST) error= verifyBlk(addr, len, action & ACTION_ERASE_CHECK_FAST); if (error != ERR_NONE) { return(error); } if ((action & ACTION_PROGRAM) != 0) { #ifdef DEBUGDUMP printf("Program starting at %x, %i bytes... ", addr, len); #endif /* DEBUGDUMP */ error= preparePatch(); if (error != ERR_NONE) return(error); /* Set Offset: */ if (toDo.MSP430X) error= bslTxRx(BSL_MEMOFFSET, 0, (WORD)(addr>>16), blkout, blkin); if (error != ERR_NONE) return(error); /* Program block: */ error= bslTxRx(BSL_TXBLK, addr, len, blkout, blkin); postPatch(); #ifdef DEBUGDUMP printf("Error: %i\n", error); #endif /* DEBUGDUMP */ if (error != ERR_NONE) { return(error); /* Cancel, if error (ACTION_VERIFY is skipped!) */ } if (toDo.MSP430X) if (error = bslTxRx(BSL_MEMOFFSET, 0, (WORD)(0),NULL, blkin) !=0) return (error); } /* if ACTION_PROGRAM */ /* Verify block: */ error= verifyBlk(addr, len, action & ACTION_VERIFY); if (error != ERR_NONE) { return(error); } return(error); } /* programBlk */ unsigned int readStartAddrTIText(char *filename) /* FRGR */ { WORD startAddr=0; char strdata[128]; FILE* infile; if ((infile = fopen(filename, "rb")) == 0) { errData= filename; return(ERR_FILE_OPEN); } /* TXT-File is parsed for first @Addr occurence: */ while (TRUE) { /* Read one line: */ if (fgets(strdata, 127, infile) == 0) /* if End Of File */ { break; } if (strdata[0] == '@') /* if @ => start address */ { sscanf(&strdata[1], "%x\n", &startAddr); break; } } fclose(infile); return(startAddr); } /* readStartAddrTIText */ int programTIText (char *filename, unsigned action) { int next= 1; int error= ERR_NONE; int linelen= 0; int linepos= 0; int i, KBytes, KBytesbefore= -1; WORD dataframelen=0; unsigned long currentAddr; char strdata[128]; FILE* infile; byteCtr= 0; if ((infile = fopen(filename, "rb")) == 0) { errData= filename; return(ERR_FILE_OPEN); } /* Convert data for MSP430, TXT-File is parsed line by line: */ while (TRUE) /* FRGR */ { /* Read one line: */ if ((fgets(strdata, 127, infile) == 0) || /* if End Of File or */ (strdata[0] == 'q')) /* if q (last character in file) */ { /* => send frame and quit */ if (dataframelen > 0) /* Data in frame? */ { error= programBlk(currentAddr, dataframelen, action); byteCtr+= dataframelen; /* Byte Counter */ dataframelen=0; } break; /* FRGR */ } linelen= strlen(strdata); if (strdata[0] == '@') /* if @ => new address => send frame and set new addr. */ { if (dataframelen > 0) { error= programBlk(currentAddr, dataframelen, action); byteCtr+= dataframelen; /* Byte Counter */ dataframelen=0; } sscanf(&strdata[1], "%lx\n", &currentAddr); continue; } /* Transfer data in line into blkout: */ for(linepos= 0; linepos < linelen-3; linepos+= 3, dataframelen++) { sscanf(&strdata[linepos], "%3x", &blkout[dataframelen]); /* (Max 16 bytes per line!) */ } if (dataframelen > maxData-16) /* if frame is getting full => send frame */ { error= programBlk(currentAddr, dataframelen, action); byteCtr+= dataframelen; /* Byte Counter */ currentAddr+= dataframelen; dataframelen=0; /* bargraph: indicates succession, actualize only when changed. FRGR */ KBytes = (byteCtr+512)/1024; if (KBytesbefore != KBytes) { KBytesbefore = KBytes; printf("\r%02d KByte ", KBytes); printf("\xDE"); for (i=0;i<KBytes;i+=1) printf("\xB2"); printf("\xDD"); } } if (error != ERR_NONE) { break; /* FRGR */ } } /* clear bargraph, go to left margin */ printf("\r \r"); fclose(infile); return(error); } /* programTIText */ int txPasswd(char* passwdFile) { int i; if (passwdFile == NULL) { /* Send "standard" password to get access to protected functions. */ printf("Transmit standard password...\n"); /* Fill blkout with 0xff * (Flash is completely erased, the contents of all Flash cells is 0xff) */ for (i= 0; i < 0x20; i++) { blkout[i]= 0xff; } return(bslTxRx(BSL_TXPWORD, /* Command: Transmit Password */ 0xffe0, /* Address of interupt vectors */ 0x0020, /* Number of bytes */ blkout, blkin)); } else { /* Send TI TXT file holding interrupt vector data as password: */ printf("Transmit PSW file \"%s\"...\n", passwdFile); return(programTIText(passwdFile, ACTION_PASSWD)); } } /* txPasswd */ void WaitForKey() /* FRGR */ { printf("----------------------------------------------------------- "); printf("Press any key ... "); getch(); printf("\n"); } int signOff(int error, BOOL passwd) { if (toDo.MSP430X) error= bslTxRx(BSL_MEMOFFSET, 0, (WORD)(0), blkout, blkin); if (toDo.Reset) { bslReset(0); /* Reset MSP430 and start user program. */ } switch (error) { case ERR_NONE: if (toDo.Program) printf("Programming completed."); else if (toDo.Verify)printf("Verification successful."); printf("Prog/Verify: %.1f sec",(float)(Time_BSL_stops-Time_PRG_starts)/1000.0); printf(" - Over all: %.1f sec\n",(float)(Time_BSL_stops-Time_BSL_starts)/1000.0); break; case ERR_BSL_SYNC: printf("ERROR: Synchronization failed!\n"); printf("Device with boot loader connected?\n"); break; case ERR_VERIFY_FAILED: printf("ERROR: Verification failed!\n"); break; case ERR_ERASE_CHECK_FAILED: printf("ERROR: Erase check failed!\n"); break; case ERR_FILE_OPEN: printf("ERROR: Unable to open input file \"%s\"!\n", (char*)errData); break; default: if ((passwd) && (error == ERR_RX_NAK)) /* If last command == transmit password && Error: */ printf("ERROR: Password not accepted!\n"); else printf("ERROR: Communication Error!\n"); } /* switch */ if (toDo.Wait) { WaitForKey(); } comDone(); /* Release serial communication port. */ /* After having released the serial port, * the target is no longer supplied via this port! */ if (error == ERR_NONE) return(0); else return(1); } /* signOff */ void showHelp() { char *help[]= { "BSLDEMO-2.01c [-h][-c{port}][-p{file}][-w][-1][-m{num}][+aecpvruw] {file}", "", /* "The last parameter is required: file name of TI-TXT file to be programmed.", "", */ "Options:", "-h Shows this help screen.", "-c{port} Specifies the communication port to be used (e.g. -cCOM2).", #ifdef WORKAROUND "-a{file} Filename of workaround patch (e.g. -aWAROUND.TXT).", #endif "-b{file} Filename of complete loader to be loaded into RAM (e.g. -bBSL.TXT).", "-e{startnum}", " Erase Segment where address does point to.", /* "-f{num} Max. number of data bytes within one transmitted frame (e.g. -f240).", */ /* Change by GH */ "-i Invert polarity of DTR line.", "-j Invert polarity of RTS line.", #ifdef ADD_MERASE_CYCLES "-m{num} Number of mass erase cycles (e.g. -m20).", #endif /* ADD_MERASE_CYCLES */ "-p{file} Specifies a TI-TXT file with the interrupt vectors that are", " used as password (e.g. -pINT_VECT.TXT).", "-r{startnum} {lennum} {file}", " Read memory from startnum till lennum and write to file as TI.TXT.", " (Values in hex format.) ", "-s{num} Changes the baudrate; num=0:9600, 1:19200, 2:38400 (e.g. -s2).", "-w Waits for <ENTER> before closing serial port.", "-x Enable MSP430X Extended Memory support.", "-1 Programming and verification is done in one pass through the file.", "", "Program Flow Specifiers [+aecipvruw]", " a Restore InfoA after mass erase (only with Mass Erase)", " e Mass Erase", " c Erase Check by file {file}", " p Program file {file}", " v Verify by file {file}", " r Reset connected MSP430. Starts application.", " u User Called - Skip entry Sequence.", " w Wait for <ENTER> before closing serial port.", " Only the specified actions are executed!", "", "Default Program Flow Specifiers (if not explicitly given): +ecpvr", "", "\x1B " /* Marks end of help! <ESC>*/ }; int i= 0; while (*help[i] != 0x1B) printf("%s\n", help[i++]); printf("Press any key to exit... "); getch(); } /*------------------------------------------------------------- * Parse Command Line Parameters ... *------------------------------------------------------------- */ int parseCMDLine(int argc, char *argv[]) { /* Default: all actions turned on: */ toDo.MassErase = 1; toDo.EraseCheck= 1; toDo.FastCheck = 0; toDo.Program = 1; toDo.Verify= 1; toDo.Reset = 1; toDo.SpeedUp = 0; /* Change Baudrate */ toDo.UserCalled= 0; toDo.Wait = 0; /* Do not wait for <Enter> at the end! */ toDo.OnePass = 0; /* Do erase check, program and verify*/ toDo.BSLStart= 1; toDo.Dump2file = 0; toDo.EraseSegment = 0; toDo.MSP430X = 0; toDo.RestoreInfoA = 0; filename = NULL; passwdFile = NULL; patchFile = patchFilename; if (argc > 1) { for (i= 1; i < (argc); i++) { switch (argv[i][0]) { case '-': switch (argv[i][1]) { case 'h': case 'H': showHelp(); /* Show help screen and */ return(1); /* exit program. */ break; case 'c': case 'C': strcpy(comPortName, "\\\\.\\"); /* Required by Windows */ memcpy(&comPortName[4], &argv[i][2], strlen(argv[i])-2); break; case 'p': case 'P': strcpy(passwdFilename, &argv[i][2]); passwdFile = passwdFilename; break; case 'w': case 'W': toDo.Wait= 1; /* Do wait for <Enter> at the end! */ break; case '1': toDo.OnePass= 1; break; /* Change by GH */ case 'i': InvertDTR = TRUE; break; case 'j': InvertRTS = TRUE; break; case 's': case 'S': if ((argv[i][2] >= '0') && (argv[i][2] <= '9')) { speed = argv[i][2] - 0x30; /* convert ASCII to number */ toDo.SpeedUp= 1; } break; case 'f': case 'F': if (argv[i][2] != 0) { sscanf(&argv[i][2], "%i", &maxData); /* Make sure that conditions for maxData are met: * ( >= 16 and == n*16 and <= MAX_DATA_BYTES!) */ maxData= (maxData > MAX_DATA_BYTES) ? MAX_DATA_BYTES : maxData; maxData= (maxData < 16) ? 16 : maxData; maxData= maxData - (maxData % 16); printf("Max. number of data bytes within one frame set to %i.\n", maxData); } break; #ifdef ADD_MERASE_CYCLES case 'm': case 'M': if (argv[i][2] != 0) { sscanf(&argv[i][2], "%i", &meraseCycles); meraseCycles= (meraseCycles < 1) ? 1 : meraseCycles; printf("Number of mass erase cycles set to %i.\n", meraseCycles); } break; #endif /* ADD_MERASE_CYCLES */ #ifdef WORKAROUND case 'a': case 'A': strcpy (patchFilename ,&argv[i][2]); patchFile=patchFilename; break; #endif /* WORKAROUND */ #ifdef NEW_BSL case 'b': case 'B': strcpy (newBSLFilename ,&argv[i][2]); newBSLFile=newBSLFilename; break; #endif /* NEW_BSL */ case 'r': case 'R': toDo.MassErase = 0; toDo.EraseCheck= 0; toDo.FastCheck = 0; toDo.Program = 0; toDo.Verify= 0; toDo.Dump2file = 1; sscanf(&argv[i][2], "%X", &readStart); i++; sscanf(&argv[i][0], "%X", &readLen); i++; readfilename = &argv[i][0]; break; case 'e': case 'E': toDo.MassErase = 0; toDo.EraseCheck= 0; toDo.FastCheck = 0; toDo.Program = 0; toDo.Verify= 0; toDo.Reset = 0; toDo.UserCalled= 0; toDo.BSLStart= 1; toDo.Dump2file = 0; toDo.EraseSegment = 1; sscanf(&argv[i][2], "%X", &readStart); i++; break; case 'x': case 'X': toDo.MSP430X = 1; break; default: printf("ERROR: Illegal command line parameter!\n"); } /* switch argv[i][1] */ break; /* '-' */ case '+': /* Turn all actions off: */ toDo.MassErase = 0; toDo.EraseCheck= 0; toDo.FastCheck = 0; toDo.Program = 0; toDo.Verify= 0; toDo.Reset = 0; toDo.UserCalled= 0; toDo.BSLStart= 1; toDo.RestoreInfoA = 0; /* Turn only specified actions back on: */ for (j= 1; j < (int)(strlen(argv[i])); j++) { switch (argv[i][j]) { case 'a': case 'A': /* Restore InfoA Segment */ toDo.RestoreInfoA = 1; case 'e': case 'E': /* Erase Flash */ toDo.MassErase = 1; break; case 'c': case 'C': /* Erase Check (by file) */ toDo.EraseCheck= 1; break; case 'f': case 'F': /* Fast Erase Check (by file) */ toDo.FastCheck= 1; break; case 'p': case 'P': /* Program file */ toDo.Program = 1; break; case 'r': case 'R': /* Reset MSP430 before waiting for <Enter> */ toDo.Reset = 1; break; case 'u': case 'U': /* Second run without entry sequence */ toDo.UserCalled= 1; break; case 'v': case 'V': /* Verify file */ toDo.Verify= 1; break; case 'w': case 'W': /* Wait for <Enter> before closing serial port */ toDo.Wait = 1; break; case 'x': case 'X': /* Start BSL ??? */ toDo.BSLStart = 0; break; default: printf("ERROR: Illegal action specified!\n"); } /* switch */ } /* for (j) */ break; /* '+' */ default: filename= argv[i]; } /* switch argv[i][0] */ } /* for (i) */ } else { showHelp(); return(1); } return(0); } /*--------------------------------------------------------------- * Main: *--------------------------------------------------------------- */ int main(int argc, char *argv[]) { const WORD SMALL_RAM_model = 0; const WORD LARGE_RAM_model = 1; const WORD ROM_model = 0x4567; WORD loadedModel = ROM_model; int stat = 0; unsigned char infoA[0x40]; #ifdef NEW_BSL newBSLFile= NULL; #endif // NEW_BSL #ifdef WORKAROUND /* Show memory access warning, if working with bootstrap * loader version(s) requiring the workaround patch. * Turn warning on by default until we can determine the * actual version of the bootstrap loader. */ BSLMemAccessWarning= 1; #endif /* WORKAROUND */ printf("%s (%s)\n", programName, programVersion); stat = parseCMDLine(argc, argv); if (stat != 0) return(stat); /*------------------------------------------------------- * Communication with Bootstrap Loader ... *------------------------------------------------------- */ /* Open COMx port (Change COM-port name to your needs!): */ if (comInit(comPortName, DEFAULT_TIMEOUT, 4) != 0) { printf("ERROR: Opening COM-Port failed!\n"); if (toDo.Wait) { WaitForKey(); /* FRGR */ } return(0); } if (toDo.UserCalled) { } else { bslReset(toDo.BSLStart); /* Invoke the boot loader. */ //delay(2000); Time_BSL_starts = GetTickCount(); } Repeat: #ifdef NEW_BSL if ((newBSLFile == NULL) || (passwdFile == NULL)) { /* If a password file is specified the "new" bootstrap loader can be loaded * (if also specified) before the mass erase is performed. Then the mass * erase can be done using the "new" BSL. Otherwise the mass erase is done * now! */ #endif /* NEW_BSL */ if (toDo.RestoreInfoA && toDo.MassErase) { /* Read actual InfoA segment Content. */ printf("Read InfoA Segment...\n"); /* Transmit password to get access to protected BSL functions. */ if ((error= txPasswd(passwdFile)) != ERR_NONE) { return(signOff(error, TRUE)); /* Password was transmitted! */ } if (toDo.MSP430X) if (bslTxRx(BSL_MEMOFFSET, 0, 0, NULL, blkin) !=0) return (signOff(error, TRUE)); if ((error= bslTxRx(BSL_RXBLK, /* Command: Read/Receive Block */ 0x010C0, /* Start address */ 0x40, /* No. of bytes to read */ NULL, infoA)) != ERR_NONE) { return(signOff(error, FALSE)); } } else { toDo.RestoreInfoA = 0; } if (toDo.MassErase) { int i; /* Erase the flash memory completely (with mass erase command): */ printf("Mass Erase...\n"); for (i= 0; i < meraseCycles; i++) { if (i == 1) { printf("Additional mass erase cycles...\n"); } if ((error= bslTxRx(BSL_MERAS, /* Command: Mass Erase */ 0xff00, /* Any address within flash memory. */ 0xa506, /* Required setting for mass erase! */ NULL, blkin)) != ERR_NONE) { return(signOff(error, FALSE)); } } passwdFile= NULL; /* No password file required! */ } #ifdef NEW_BSL } /* if ((newBSLFile == NULL) || (passwdFile == NULL)) */ #endif /* NEW_BSL */ /* Transmit password to get access to protected BSL functions. */ if (!(toDo.UserCalled)) if ((error= txPasswd(passwdFile)) != ERR_NONE) { return(signOff(error, TRUE)); /* Password was transmitted! */ } /* Read actual bootstrap loader version (FRGR: complete Chip ID). */ if (toDo.MSP430X) if (bslTxRx(BSL_MEMOFFSET, 0, 0, NULL, blkin) !=0) return (signOff(error, TRUE)); if ((error= bslTxRx(BSL_RXBLK, /* Command: Read/Receive Block */ 0x0ff0, /* Start address */ 14, /* No. of bytes to read */ NULL, blkin)) == ERR_NONE) { memcpy(&devTypeHi,&blkin[0x00], 1); memcpy(&devTypeLo,&blkin[0x01], 1); memcpy(&devProcHi,&blkin[0x02], 1); memcpy(&devProcLo,&blkin[0x03], 1); memcpy(&bslVerHi, &blkin[0x0A], 1); memcpy(&bslVerLo, &blkin[0x0B], 1); printf("BSL version: %X.%02X", bslVerHi,bslVerLo); printf(" - Family member: %02X%02X", devTypeHi, devTypeLo); printf(" - Process: %02X%02X\n", devProcHi, devProcLo); bslVer= (bslVerHi << 8) | bslVerLo; if (bslVer < 0x0150) bslerrbuf = 0x021E; else bslerrbuf = 0x0200; if (bslVer <= 0x0110) { #ifdef WORKAROUND #ifdef NEW_BSL if (newBSLFile == NULL) { #endif /* NEW_BSL */ printf("Patch for flash programming required!\n"); patchRequired= TRUE; #ifdef NEW_BSL } #endif /* NEW_BSL */ #endif /* WORKAROUND */ BSLMemAccessWarning= 1; } else { BSLMemAccessWarning= 0; /* Fixed in newer versions of BSL. */ } } if (patchRequired || ((newBSLFile != NULL) && (bslVer <= 0x0110))) { /* Execute function within bootstrap loader * to prepare stack pointer for the following patch. * This function will lock the protected functions again. */ printf("Load PC with 0x0C22...\n"); if ((error= bslTxRx(BSL_LOADPC, /* Command: Load PC */ 0x0C22, /* Address to load into PC */ 0, /* No additional data! */ NULL, blkin)) != ERR_NONE) { return(signOff(error, FALSE)); } /* Re-send password to re-gain access to protected functions. */ if ((error= txPasswd(passwdFile)) != ERR_NONE) { return(signOff(error, TRUE)); /* Password was transmitted! */ } } #ifdef NEW_BSL if (newBSLFile != NULL) { WORD startaddr; /* used twice: vector or start address */ startaddr = readStartAddrTIText(newBSLFile); if (startaddr == 0) { startaddr = 0x0300; } printf("Load"); if (bslVer >= 0x0140) printf("/Verify"); printf(" new BSL \"%s\" into RAM at 0x%04X...\n", newBSLFile, startaddr); if ((error= programTIText(newBSLFile, /* File to program */ ACTION_PROGRAM)) != ERR_NONE) { return(signOff(error, FALSE)); } if (bslVer < 0x0140) { printf("Verify new BSL \"%s\"...\n", newBSLFile); if ((error= programTIText(newBSLFile, /* File to verify */ ACTION_VERIFY)) != ERR_NONE) { return(signOff(error, FALSE)); } } /* Read startvector/loaded model of NEW bootstrap loader: */ if ((error= bslTxRx(BSL_RXBLK, startaddr, 4, NULL, blkin)) == ERR_NONE) { memcpy(&startaddr, &blkin[0], 2); memcpy(&loadedModel, &blkin[2], 2); if (loadedModel != SMALL_RAM_model) { loadedModel= LARGE_RAM_model; bslerrbuf = 0x0200; printf("Start new BSL (LARGE model > 1K Bytes) at 0x%04X...\n", startaddr); } else printf("Start new BSL (SMALL model < 512 Bytes) at 0x%04X...\n", startaddr); error= bslTxRx(BSL_LOADPC, /* Command: Load PC */ startaddr,/* Address to load into PC */ 0, /* No additional data! */ NULL, blkin); } if (error != ERR_NONE) { return(signOff(error, FALSE)); } /* BSL-Bugs should be fixed within "new" BSL: */ BSLMemAccessWarning= 0; patchRequired= FALSE; patchLoaded= FALSE; if (loadedModel != SMALL_RAM_model) { /* Re-send password to re-gain access to protected functions. */ if ((error= txPasswd(passwdFile)) != ERR_NONE) { return(signOff(error, TRUE)); /* Password was transmitted! */ } } } #endif/* NEW_BSL */ #ifdef WORKAROUND if (patchRequired) { printf("Load and verify patch \"%s\"...\n", patchFile); /* Programming and verification is done in one pass. * The patch file is only read and parsed once. */ if ((error= programTIText(patchFile, /* File to program */ ACTION_PROGRAM | ACTION_VERIFY)) != ERR_NONE) { return(signOff(error, FALSE)); } patchLoaded= TRUE; } #endif /* WORKAROUND */ #ifdef NEW_BSL if ((newBSLFile != NULL) && (passwdFile != NULL) && toDo.MassErase) { /* Erase the flash memory completely (with mass erase command): */ printf("Mass Erase...\n"); if ((error= bslTxRx(BSL_MERAS, /* Command: Mass Erase */ 0xff00, /* Any address within flash memory. */ 0xa506, /* Required setting for mass erase! */ NULL, blkin)) != ERR_NONE) { return(signOff(error, FALSE)); } passwdFile= NULL; /* No password file required! */ } #endif /* NEW_BSL*/ /* FRGR */ if (toDo.SpeedUp) // 0:9600, 1:19200, 2:38400 (3:56000 not applicable) { DWORD BR; // Baudrate if ((devTypeHi == 0xF1) || (devTypeHi == 0x12)) // F1232 / F1xx { BYTE BCSCTL1, DCOCTL; // Basic Clock Module Registers switch (speed) // for F148, F149, F169 { //Rsel DCO case 0: BR = CBR_9600; BCSCTL1 = 0x85; DCOCTL = 0x80; break;// 5 4 case 1: BR = CBR_19200; BCSCTL1 = 0x86; DCOCTL = 0xE0; break;// 6 7 case 2: BR = CBR_38400; BCSCTL1 = 0x87; DCOCTL = 0xE0; break;// 7 7 default: BR = CBR_9600; BCSCTL1 = 0x85; DCOCTL = 0x80; speed = 0; } _addr = (BCSCTL1 << 8) + DCOCTL;// D2, D1: values for CPU frequency } else if (devTypeHi == 0xF4) { BYTE SCFI0, SCFI1; // FLL+ Registers switch (speed) // for F448, F449 { //NDCO FN_x case 0: BR = CBR_9600; SCFI1 = 0x98; SCFI0= 0x00; break;// 19 0 case 1: BR = CBR_19200; SCFI1 = 0xB0; SCFI0= 0x00; break;// 22 0 case 2: BR = CBR_38400; SCFI1 = 0xC8; SCFI0= 0x00; break;// 25 0 default: BR = CBR_9600; SCFI1 = 0x98; SCFI0= 0x00; speed = 0; } _addr = (SCFI1 << 8) + SCFI0; // D2, D1: values for CPU frequency } else if (devTypeHi == 0xF2 || devTypeHi == 0x25) { BYTE BCSCTL1, DCOCTL; // Basic Clock Module Registers switch (speed) // for F2xx { //Rsel DCO case 0: BR = CBR_9600; BCSCTL1 = 0x88; DCOCTL = 0x80; break;// 5 4 case 1: BR = CBR_19200; BCSCTL1 = 0x8B; DCOCTL = 0x80; break;// 6 7 case 2: BR = CBR_38400; BCSCTL1 = 0x8C; DCOCTL = 0x80; break;// 7 7 default: BR = CBR_9600; BCSCTL1 = 0x88; DCOCTL = 0x80; speed = 0; } _addr = (BCSCTL1 << 8) + DCOCTL;// D2, D1: values for CPU frequency } _len = speed; // D3: index for baudrate (speed) if (BR != comGetBaudrate()) // change only if not same speed { printf("Change Baudrate "); error= bslTxRx(BSL_SPEED, // Command: Change Speed _addr, // Mandatory code _len, // Mandatory code NULL, blkin); if (error == ERR_NONE) { printf("from %d ", comGetBaudrate()); comChangeBaudrate(BR); delay(10); printf("to %d Baud (Mode: %d)\n", comGetBaudrate(),speed); } else { printf("command not accepted. Baudrate remains at %d Baud\n", comGetBaudrate()); } } } Time_PRG_starts = GetTickCount(); //printf("Start time measurement for pure Prog/Verify cycle...\n"); if (!toDo.OnePass) { if (toDo.EraseCheck) { /* Parse file in TXT-Format and check the erasure of required flash cells. */ printf("Erase Check by file \"%s\"...\n", filename); if ((error= programTIText(filename, ACTION_ERASE_CHECK)) != ERR_NONE) { return(signOff(error, FALSE)); } } if (toDo.FastCheck) { /* Parse file in TXT-Format and check the erasure of required flash cells. */ printf("Fast E-Check by file \"%s\"...\n", filename); if ((error= programTIText(filename, ACTION_ERASE_CHECK_FAST)) != ERR_NONE) { return(signOff(error, FALSE)); } } if (toDo.Program) { /* Parse file in TXT-Format and program data into flash memory. */ printf("Program \"%s\"...\n", filename); if ((error= programTIText(filename, ACTION_PROGRAM)) != ERR_NONE) { if (newBSLFile == NULL) return(signOff(ERR_VERIFY_FAILED, FALSE)); else { // read out error address+3 from RAM (error address buffer) if ((loadedModel == LARGE_RAM_model) || (loadedModel == SMALL_RAM_model)) { if (toDo.MSP430X) if (bslTxRx(BSL_MEMOFFSET, 0, 0, NULL, blkin) !=0) signOff(error, TRUE); if ((error= bslTxRx(BSL_RXBLK, bslerrbuf, 2, NULL, blkin)) == ERR_NONE) { _err = (blkin[1] << 8) + blkin[0]; printf("Verification Error at 0x%04X\n", _err-3); } else return(signOff(error, FALSE)); } else return(signOff(ERR_VERIFY_FAILED, FALSE)); } } else { printf("%i bytes programmed.\n", byteCtr); } } if (toDo.Verify) { if ((toDo.Program) && ((bslVer >= 0x0140) || (newBSLFile != NULL))) { printf("Verify... already done during programming.\n"); } else { /* Verify programmed data: */ printf("Verify\"%s\"...\n", filename); if ((error= programTIText(filename, ACTION_VERIFY)) != ERR_NONE) { return(signOff(error, FALSE)); } } } } else { unsigned action= 0; if (toDo.EraseCheck) { action |= ACTION_ERASE_CHECK; printf("EraseCheck "); } if (toDo.FastCheck) { action |= ACTION_ERASE_CHECK_FAST; printf("EraseCheckFast "); } if (toDo.Program) { action |= ACTION_PROGRAM; printf("Program "); } if (toDo.Verify) { action |= ACTION_VERIFY; printf("Verify "); } if (action != 0) { printf("\"%s\" ...\n", filename); error= programTIText(filename, action); if (error != ERR_NONE) { return(signOff(error, FALSE)); } else { printf("%i bytes programmed.\n", byteCtr); } } } if (toDo.RestoreInfoA) { unsigned long startaddr = 0x10C0; WORD len = 0x40; printf("Restore InfoA Segment...\n"); /* Restore actual InfoA segment Content. */ if (toDo.MSP430X) if (bslTxRx(BSL_MEMOFFSET, 0, 0, NULL, blkin) !=0) return (signOff(error, TRUE)); while ((len > 0) && (infoA[0x40-len] == 0xff)) { len --; startaddr++; } if (len > 0) { memcpy(blkout, &infoA[startaddr - 0x10C0], len); if (error= programBlk(startaddr, len, ACTION_PROGRAM)) { return(signOff(error, FALSE)); } } } if (toDo.Dump2file) { BYTE* DataPtr = NULL; BYTE* BytesPtr = NULL; long byteCount = readLen; long addrCount = readStart; BytesPtr = DataPtr = (BYTE*) malloc(sizeof(BYTE) * readLen); printf("Read memory to file: %s Start: 0x%-4X Length 0x%-4X\n", readfilename, readStart, readLen); if (toDo.MSP430X) { if (error = bslTxRx(BSL_MEMOFFSET, 0, (WORD)(addrCount>>16), NULL, blkin) !=ERR_NONE) return(signOff(error, FALSE)); addrCount = addrCount & 0xFFFF; } while (byteCount > 0) { if (byteCount > maxData) { /* Read data. */ printf(" Read memory Start: 0x%-4X Length %d\n", (readStart & 0xFFFF0000)+addrCount, maxData); if ((error= bslTxRx(BSL_RXBLK, /* Command: Read/Receive Block */ (WORD)addrCount, /* Start address */ (WORD)maxData, /* No. of bytes to read */ NULL, BytesPtr)) != ERR_NONE) return(signOff(error, FALSE)); } else { /* Read data. */ printf(" Read memory Start: 0x%-4X Length %d\n", (readStart & 0xFFFF0000)+addrCount, byteCount); if ((error= bslTxRx(BSL_RXBLK, /* Command: Read/Receive Block */ (WORD)addrCount, /* Start address */ (WORD)byteCount, /* No. of bytes to read */ NULL, BytesPtr)) != ERR_NONE) return(signOff(error, FALSE)); } byteCount -= maxData; addrCount += maxData; BytesPtr += maxData; } StartTITextOutput(readfilename); WriteTITextBytes((unsigned long) readStart, (WORD) (readLen/2), DataPtr); FinishTITextOutput(); if (DataPtr != NULL) free (DataPtr); if (toDo.MSP430X) if (error = bslTxRx(BSL_MEMOFFSET, 0, (WORD)(0),NULL, blkin) !=0) return (error); } if (toDo.EraseSegment) { long addrCount = readStart; printf("Erase Segment: 0x%-4X\n", readStart); if (toDo.MSP430X) { if (error = bslTxRx(BSL_MEMOFFSET, 0, (WORD)(addrCount>>16), NULL, blkin) !=ERR_NONE) return(signOff(error, FALSE)); addrCount = addrCount & 0xFFFF; } if (error = bslTxRx(BSL_ERASE, addrCount, 0xA502, NULL, blkin) !=ERR_NONE) return(signOff(error, FALSE)); if (toDo.MSP430X) if (error = bslTxRx(BSL_MEMOFFSET, 0, (WORD)(0),NULL, blkin) !=0) return (error); } if (toDo.UserCalled) { toDo.UserCalled = 0; //bslReset(0); /* Reset MSP430 and start user program. */ printf("No Device reset - BSL called from user program ---------------------\n"); //delay(100); goto Repeat; } Time_BSL_stops = GetTickCount(); return(signOff(ERR_NONE, FALSE)); } /* EOF */
29.823567
120
0.545816
[ "vector", "model" ]
c776d4e812004672960fc8d45bf3ecef81c9e571
6,691
h
C
third_party/gecko-15/win32/include/DeviceManagerD3D9.h
bwp/SeleniumWebDriver
58221fbe59fcbbde9d9a033a95d45d576b422747
[ "Apache-2.0" ]
1
2018-02-05T04:23:18.000Z
2018-02-05T04:23:18.000Z
third_party/gecko-16/win32/include/DeviceManagerD3D9.h
bwp/SeleniumWebDriver
58221fbe59fcbbde9d9a033a95d45d576b422747
[ "Apache-2.0" ]
null
null
null
third_party/gecko-16/win32/include/DeviceManagerD3D9.h
bwp/SeleniumWebDriver
58221fbe59fcbbde9d9a033a95d45d576b422747
[ "Apache-2.0" ]
null
null
null
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef GFX_DEVICEMANAGERD3D9_H #define GFX_DEVICEMANAGERD3D9_H #include "gfxTypes.h" #include "nsRect.h" #include "nsAutoPtr.h" #include "d3d9.h" #include "nsTArray.h" namespace mozilla { namespace layers { class DeviceManagerD3D9; class LayerD3D9; class Nv3DVUtils; class Layer; // Shader Constant locations const int CBmLayerTransform = 0; const int CBmProjection = 4; const int CBvRenderTargetOffset = 8; const int CBvTextureCoords = 9; const int CBvLayerQuad = 10; const int CBfLayerOpacity = 0; /** * SwapChain class, this class manages the swap chain belonging to a * LayerManagerD3D9. */ class THEBES_API SwapChainD3D9 { NS_INLINE_DECL_REFCOUNTING(SwapChainD3D9) public: ~SwapChainD3D9(); /** * This function will prepare the device this swap chain belongs to for * rendering to this swap chain. Only after calling this function can the * swap chain be drawn to, and only until this function is called on another * swap chain belonging to this device will the device draw to it. Passed in * is the size of the swap chain. If the window size differs from the size * during the last call to this function the swap chain will resize. Note that * in no case does this function guarantee the backbuffer to still have its * old content. */ bool PrepareForRendering(); /** * This function will present the selected rectangle of the swap chain to * its associated window. */ void Present(const nsIntRect &aRect); private: friend class DeviceManagerD3D9; SwapChainD3D9(DeviceManagerD3D9 *aDeviceManager); bool Init(HWND hWnd); /** * This causes us to release our swap chain, clearing out our resource usage * so the master device may reset. */ void Reset(); nsRefPtr<IDirect3DSwapChain9> mSwapChain; nsRefPtr<DeviceManagerD3D9> mDeviceManager; HWND mWnd; }; /** * Device manager, this class is used by the layer managers to share the D3D9 * device and create swap chains for the individual windows the layer managers * belong to. */ class THEBES_API DeviceManagerD3D9 { public: DeviceManagerD3D9(); NS_IMETHOD_(nsrefcnt) AddRef(void); NS_IMETHOD_(nsrefcnt) Release(void); protected: nsAutoRefCnt mRefCnt; NS_DECL_OWNINGTHREAD public: bool Init(); /** * Sets up the render state for the device for layer rendering. */ void SetupRenderState(); /** * Create a swap chain setup to work with the specified window. */ already_AddRefed<SwapChainD3D9> CreateSwapChain(HWND hWnd); IDirect3DDevice9 *device() { return mDevice; } bool IsD3D9Ex() { return mDeviceEx; } bool HasDynamicTextures() { return mHasDynamicTextures; } enum ShaderMode { RGBLAYER, RGBALAYER, COMPONENTLAYERPASS1, COMPONENTLAYERPASS2, YCBCRLAYER, SOLIDCOLORLAYER }; void SetShaderMode(ShaderMode aMode, Layer* aMask, bool aIs2D); /** * Return pointer to the Nv3DVUtils instance */ Nv3DVUtils *GetNv3DVUtils() { return mNv3DVUtils; } /** * Returns true if this device was removed. */ bool DeviceWasRemoved() { return mDeviceWasRemoved; } PRUint32 GetDeviceResetCount() { return mDeviceResetCount; } /** * We keep a list of all layers here that may have hardware resource allocated * so we can clean their resources on reset. */ nsTArray<LayerD3D9*> mLayersWithResources; PRInt32 GetMaxTextureSize() { return mMaxTextureSize; } private: friend class SwapChainD3D9; ~DeviceManagerD3D9(); /** * This function verifies the device is ready for rendering, internally this * will test the cooperative level of the device and reset the device if * needed. If this returns false subsequent rendering calls may return errors. */ bool VerifyReadyForRendering(); /** * This will fill our vertex buffer with the data of our quad, it may be * called when the vertex buffer is recreated. */ bool CreateVertexBuffer(); /* Array used to store all swap chains for device resets */ nsTArray<SwapChainD3D9*> mSwapChains; /* The D3D device we use */ nsRefPtr<IDirect3DDevice9> mDevice; /* The D3D9Ex device - only valid on Vista+ with WDDM */ nsRefPtr<IDirect3DDevice9Ex> mDeviceEx; /* An instance of the D3D9 object */ nsRefPtr<IDirect3D9> mD3D9; /* An instance of the D3D9Ex object - only valid on Vista+ with WDDM */ nsRefPtr<IDirect3D9Ex> mD3D9Ex; /* Vertex shader used for layer quads */ nsRefPtr<IDirect3DVertexShader9> mLayerVS; /* Pixel shader used for RGB textures */ nsRefPtr<IDirect3DPixelShader9> mRGBPS; /* Pixel shader used for RGBA textures */ nsRefPtr<IDirect3DPixelShader9> mRGBAPS; /* Pixel shader used for component alpha textures (pass 1) */ nsRefPtr<IDirect3DPixelShader9> mComponentPass1PS; /* Pixel shader used for component alpha textures (pass 2) */ nsRefPtr<IDirect3DPixelShader9> mComponentPass2PS; /* Pixel shader used for RGB textures */ nsRefPtr<IDirect3DPixelShader9> mYCbCrPS; /* Pixel shader used for solid colors */ nsRefPtr<IDirect3DPixelShader9> mSolidColorPS; /* As above, but using a mask layer */ nsRefPtr<IDirect3DVertexShader9> mLayerVSMask; nsRefPtr<IDirect3DVertexShader9> mLayerVSMask3D; nsRefPtr<IDirect3DPixelShader9> mRGBPSMask; nsRefPtr<IDirect3DPixelShader9> mRGBAPSMask; nsRefPtr<IDirect3DPixelShader9> mRGBAPSMask3D; nsRefPtr<IDirect3DPixelShader9> mComponentPass1PSMask; nsRefPtr<IDirect3DPixelShader9> mComponentPass2PSMask; nsRefPtr<IDirect3DPixelShader9> mYCbCrPSMask; nsRefPtr<IDirect3DPixelShader9> mSolidColorPSMask; /* Vertex buffer containing our basic vertex structure */ nsRefPtr<IDirect3DVertexBuffer9> mVB; /* Our vertex declaration */ nsRefPtr<IDirect3DVertexDeclaration9> mVD; /* Our focus window - this is really a dummy window we can associate our * device with. */ HWND mFocusWnd; /* we use this to help track if our device temporarily or permanently lost */ HMONITOR mDeviceMonitor; PRUint32 mDeviceResetCount; PRUint32 mMaxTextureSize; /* If this device supports dynamic textures */ bool mHasDynamicTextures; /* If this device was removed */ bool mDeviceWasRemoved; /* Nv3DVUtils instance */ nsAutoPtr<Nv3DVUtils> mNv3DVUtils; /** * Verifies all required device capabilities are present. */ bool VerifyCaps(); }; } /* namespace layers */ } /* namespace mozilla */ #endif /* GFX_DEVICEMANAGERD3D9_H */
27.422131
80
0.735017
[ "render", "object", "solid" ]
c77d37c600bd37273f06b7570527b0745d6794a1
2,002
h
C
kubernetes/model/io_k8s_api_storage_v1_csi_node.h
zouxiaoliang/nerv-kubernetes-client-c
07528948c643270fd757d38edc68da8c9628ee7a
[ "Apache-2.0" ]
null
null
null
kubernetes/model/io_k8s_api_storage_v1_csi_node.h
zouxiaoliang/nerv-kubernetes-client-c
07528948c643270fd757d38edc68da8c9628ee7a
[ "Apache-2.0" ]
null
null
null
kubernetes/model/io_k8s_api_storage_v1_csi_node.h
zouxiaoliang/nerv-kubernetes-client-c
07528948c643270fd757d38edc68da8c9628ee7a
[ "Apache-2.0" ]
null
null
null
/* * io_k8s_api_storage_v1_csi_node.h * * CSINode holds information about all CSI drivers installed on a node. CSI drivers do not need to create the CSINode object directly. As long as they use the node-driver-registrar sidecar container, the kubelet will automatically populate the CSINode object for the CSI driver as part of kubelet plugin registration. CSINode has the same name as a node. If the object is missing, it means either there are no CSI Drivers available on the node, or the Kubelet version is low enough that it doesn&#39;t create this object. CSINode has an OwnerReference that points to the corresponding node object. */ #ifndef _io_k8s_api_storage_v1_csi_node_H_ #define _io_k8s_api_storage_v1_csi_node_H_ #include <string.h> #include "../external/cJSON.h" #include "../include/list.h" #include "../include/keyValuePair.h" #include "../include/binary.h" typedef struct io_k8s_api_storage_v1_csi_node_t io_k8s_api_storage_v1_csi_node_t; #include "io_k8s_api_storage_v1_csi_node_spec.h" #include "io_k8s_apimachinery_pkg_apis_meta_v1_object_meta.h" typedef struct io_k8s_api_storage_v1_csi_node_t { char *api_version; // string char *kind; // string struct io_k8s_apimachinery_pkg_apis_meta_v1_object_meta_t *metadata; //model struct io_k8s_api_storage_v1_csi_node_spec_t *spec; //model } io_k8s_api_storage_v1_csi_node_t; io_k8s_api_storage_v1_csi_node_t *io_k8s_api_storage_v1_csi_node_create( char *api_version, char *kind, io_k8s_apimachinery_pkg_apis_meta_v1_object_meta_t *metadata, io_k8s_api_storage_v1_csi_node_spec_t *spec ); void io_k8s_api_storage_v1_csi_node_free(io_k8s_api_storage_v1_csi_node_t *io_k8s_api_storage_v1_csi_node); io_k8s_api_storage_v1_csi_node_t *io_k8s_api_storage_v1_csi_node_parseFromJSON(cJSON *io_k8s_api_storage_v1_csi_nodeJSON); cJSON *io_k8s_api_storage_v1_csi_node_convertToJSON(io_k8s_api_storage_v1_csi_node_t *io_k8s_api_storage_v1_csi_node); #endif /* _io_k8s_api_storage_v1_csi_node_H_ */
43.521739
597
0.83017
[ "object", "model" ]
c77daff5e3f74df8673a84c7a87a6a86b75b9e18
471
h
C
islands/include/AssetArchive.h
mosmeh/islands
b9076c491e8c0d88be634a295ca4a81ba335b7ff
[ "BSD-2-Clause", "MIT" ]
null
null
null
islands/include/AssetArchive.h
mosmeh/islands
b9076c491e8c0d88be634a295ca4a81ba335b7ff
[ "BSD-2-Clause", "MIT" ]
null
null
null
islands/include/AssetArchive.h
mosmeh/islands
b9076c491e8c0d88be634a295ca4a81ba335b7ff
[ "BSD-2-Clause", "MIT" ]
null
null
null
#pragma once #define ENABLE_ASSET_ARCHIVE #ifdef ENABLE_ASSET_ARCHIVE namespace islands { class AssetArchive { public: AssetArchive(const AssetArchive&) = delete; AssetArchive& operator=(const AssetArchive&) = delete; virtual ~AssetArchive(); static AssetArchive& getInstance(); std::vector<char> readFile(const std::string& filename) const; std::string readTextFile(const std::string& filename) const; private: zip_t* zip_; AssetArchive(); }; } #endif
16.241379
63
0.753715
[ "vector" ]
c7837d9455003643c3a47dcc416c1dfb1b39b3c6
1,625
h
C
src/SurfaceControl.h
jackthgu/K-AR_HYU_Deform_Simulation
e7c275c8948e1fe3e800ab37b17aa8406b147277
[ "MIT" ]
null
null
null
src/SurfaceControl.h
jackthgu/K-AR_HYU_Deform_Simulation
e7c275c8948e1fe3e800ab37b17aa8406b147277
[ "MIT" ]
null
null
null
src/SurfaceControl.h
jackthgu/K-AR_HYU_Deform_Simulation
e7c275c8948e1fe3e800ab37b17aa8406b147277
[ "MIT" ]
null
null
null
#ifndef SURFACECONTROL_H_ #define SURFACECONTROL_H_ #include <MainLib/OgreFltk/OgreMotionLoader.h> #include <BaseLib/motion/FullbodyIK_MotionDOF.h> class SurfaceControl { double entityScale_per_skinScale; SkinnedMeshLoader mOrigLoader; VRMLloader* mLoader; // for IK OBJloader::Mesh mMesh; SkinnedMeshFromVertexInfo *mSkinningInfo; std::vector<SkinnedMeshFromVertexInfo::VertexInfo > info; vector3 mOrigOffset; Posture mPose0; vectorn mPose; std::vector<MotionUtil::Effector> mEffectors; // unused MotionUtil::FullbodyIK_MotionDOF* solver; public: SurfaceControl( const char* fbxFile, double _entityScale_per_skinScale, const vector3& initialRootPos); virtual ~SurfaceControl( ); inline OBJloader::Mesh & getCurrMesh() { return mMesh;} inline const OBJloader::Mesh & getCurrMesh() const { return mMesh;} // step 1 void clearConstraints() { info.resize(0);} int numCon() const { return (int)info.size();} // step 2 // utility functions void addConstraints( int vertexIndex) { info.resize(info.size()+1); auto& i=info.back(); i.treeIndices=mSkinningInfo->treeIndices(vertexIndex); i.localpos=mSkinningInfo->localPos(vertexIndex); i.weights=mSkinningInfo->weights(vertexIndex); } void addConstraints( int v1, int v2, int v3, vector3 const & baryCoeffs) { info.resize(info.size()+1); auto& i=info.back(); mSkinningInfo->getVertexInfo(v1, v2, v3, baryCoeffs, i.treeIndices, i.localpos, i.weights); } vector3 getConPos(int conIndex) const; // updates currMesh from surface constraints stored in info. void solveIK(vector3N const& desired_pos); }; #endif
30.660377
153
0.748923
[ "mesh", "vector" ]
c788e5b73cf8845e6777cc140b738bb646ffaa86
1,102
h
C
code/engine.vc2008/xrSound/XAudioTarget.h
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
7
2018-03-27T12:36:07.000Z
2020-06-26T11:31:52.000Z
code/engine.vc2008/xrSound/XAudioTarget.h
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
2
2018-05-26T23:17:14.000Z
2019-04-14T18:33:27.000Z
code/engine.vc2008/xrSound/XAudioTarget.h
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
5
2020-10-18T11:55:26.000Z
2022-03-28T07:21:35.000Z
/********************************************************* * Copyright (C) X-Ray Oxygen, 2018. All rights reserved. * X-Ray Oxygen - open-source X-Ray fork * Apache License ********************************************************** * Module Name: XAudio Target ********************************************************** * XAudioTarget.h * Main methods for XAudio implementation *********************************************************/ #pragma once #include "stdafx.h" class CSoundRender_TargetB : public CSoundRender_Target { typedef CSoundRender_Target inherited; // XAudio2 LPVOID pSource; LPVOID pBuffers[sdef_target_count]; float GainCache; u32 BufBlock; private: void fill_block(u32 BufferID); public: CSoundRender_TargetB(); virtual ~CSoundRender_TargetB(); //void source_changed(); virtual bool _initialize(); virtual void _destroy(); virtual void _restart(); virtual void start(CSoundRender_Emitter* E); virtual void render(); virtual void rewind(); virtual void stop(); virtual void update(); virtual void fill_parameters(); virtual void alAuxInit(u32 slot); };
23.446809
58
0.594374
[ "render" ]
c78ebcacb015dfe5b38104bf4976a537015c47a2
7,682
h
C
src/thingboard.h
tjorim/bomberboy-qt
76b888b40ab41647d7247555f053a008599c83b4
[ "MIT" ]
null
null
null
src/thingboard.h
tjorim/bomberboy-qt
76b888b40ab41647d7247555f053a008599c83b4
[ "MIT" ]
null
null
null
src/thingboard.h
tjorim/bomberboy-qt
76b888b40ab41647d7247555f053a008599c83b4
[ "MIT" ]
null
null
null
#ifndef THINGBOARD_H #define THINGBOARD_H #include <QList> #include <QGraphicsItem> #include "thing.h" #include "powerup.h" /** * class ThingBoard * * @author Jorim Tielemans * @version 09/01/2017 */ class ThingBoard { public: // constructors ThingBoard(); QList<QList<Thing *> > getBoard() const; void createBoard(int width, int height); void placeThing(int x, int y, Thing *thing); Thing *getThing(int x, int y); /** * Constructor voor objects van class Level * * @param m het Model. */ void load(int levelNr); /** * Dit is level 1: Old Boring Level. Hier zitten 181 dozen in, * nog een bepaald percentage moet gevuld worden met PowerUps. * * Voorbeeld: x x x x x x x x x x x x x x x x x x x x x x b d d d d d d d d d d d d d d d x x x d x d x d x d x d x d x d x d x x x d d d d d d d d d d d d d d d d d d d x x d x d x d x d x d x d x d x d x d x d x x d d d d d d d d d d d d d d d d d d d x x d x d x d x d x d x d x d x d x d x d x x d d d d d d d d d d d d d d d d d d d x x d x d x d x d x d x d x d x d x d x d x x d d d d d d d d d d d d d d d d d d d x x d x d x d x d x d x d x d x d x d x d x x d d d d d d d d d d d d d d d d d d d x x x d x d x d x d x d x d x d x d x x x d d d d d d d d d d d d d d d r x x x x x x x x x x x x x x x x x x x x x x */ void level1(); /** * Dit is level 2: FIRE EVERYWHERE!!! Xoxo. Hier zijn geen PowerUps aanwezig. * In het midden bevind zich een cirkel van kruit (eigenlijk een rechthoek), * dit ontploft mee als vuur van een explosie het raakt. * * Voorbeeld: x x x x x x x x x x x x x x x x x x x x x x d d d d d d x x d x x x x x x x x x d x x d k k k k k k k k k k k d x x x x k x x d x d x x k x x x x k d d d k x x x x k x x x x x k x x d x x b k k r x x d x x k x x x x x k x x x x k d d d k x x x x k x x d x d x x k x x x x d k k k k k k k k k k k d x x d x x x x x x x x x d x x d d d d d d x x x x x x x x x x x x x x x x x x x x x x */ void level2(); /** * Dit is level 3: Let's teleport! Hier zitten 149 dozen in, * nog een bepaald percentage moet gevuld worden met PowerUps. * In de hoeken (niet echt helemaal uiterst in de hoeken) bevinden zich portalen, * hier kan men doorgaan en men komt bij de andere poort (de overkant van het veld) uit. * * Voorbeeld: x x x x x x x x x x x x x x x x x x x x x x b d d d d d d d d d x x x x d x d x d x d x d x d x x x x p d d d d d d d d d d d d d p x x x d x d x d x d x d x d x d x d x x x d d d d d d d d d d d d d d d d d d d x x d x d x d x d x d x d x d x d x d x d x x d d d d d d d d d d d d d d d d d d d x x d x d x d x d x d x d x d x d x d x d x x d d d d d d d d d d d d d d d d d d d x x x d x d x d x d x d x d x d x d x x x p d d d d d d d d d d d d d p x x x x d x d x d x d x d x d x x x x d d d d d d d d d r x x x x x x x x x x x x x x x x x x x x x x */ void level3(); /** * Dit is level 4: Just go kill yourself >:(. Hier zijn geen PowerUps aanwezig, * maar ook geen kratten of kruit. Just plain simple Grond everywhere. * Men kan zich nergens verbergen, dus ze moeten elkaar gewoon afmaken, of toch proberen. * * ToDo: De spelers krijgen direct het maximale aantal bommen, * de maximale vuurkracht en ze lopen op hun snelst. Levens krijgen ze maar 3. * * Voorbeeld: x x x x x x x x x x x x x x x x x x x x x x b x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x r x x x x x x x x x x x x x x x x x x x x x x */ void level4(); /** * Selecteert een willekeurige powerup uit een enum. * Source: http://stackoverflow.com/questions/18145766/generating-a-random-enum-value-continuously-without-getting-the-same-value-twice * * @return Een willekeurige powerup. */ PowerUp::Power getRandomPower(); /** * Nu staat er dus wel een javadocding bij. * Deze functie gaat, afhankelijk van hoeveel powerups er moeten worden verstopt, op bepaalde plaatsen een krat vervangen door een powerup. */ void verdeelPowerUp(int aantalPowerUps); private: QList<QList<Thing *> > board; }; #endif // THINGBOARD_H
50.539474
143
0.331034
[ "model" ]
c7a4f90cb1c36e15a6831c7202da144d7601db81
1,741
h
C
wrappers/8.1.1/vtkInteractorStyleRubberBandPickWrap.h
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
6
2016-02-03T12:48:36.000Z
2020-09-16T15:07:51.000Z
wrappers/8.1.1/vtkInteractorStyleRubberBandPickWrap.h
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
4
2016-02-13T01:30:43.000Z
2020-03-30T16:59:32.000Z
wrappers/8.1.1/vtkInteractorStyleRubberBandPickWrap.h
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
null
null
null
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #ifndef NATIVE_EXTENSION_VTK_VTKINTERACTORSTYLERUBBERBANDPICKWRAP_H #define NATIVE_EXTENSION_VTK_VTKINTERACTORSTYLERUBBERBANDPICKWRAP_H #include <nan.h> #include <vtkSmartPointer.h> #include <vtkInteractorStyleRubberBandPick.h> #include "vtkInteractorStyleTrackballCameraWrap.h" #include "../../plus/plus.h" class VtkInteractorStyleRubberBandPickWrap : public VtkInteractorStyleTrackballCameraWrap { public: using Nan::ObjectWrap::Wrap; static void Init(v8::Local<v8::Object> exports); static void InitPtpl(); static void ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info); VtkInteractorStyleRubberBandPickWrap(vtkSmartPointer<vtkInteractorStyleRubberBandPick>); VtkInteractorStyleRubberBandPickWrap(); ~VtkInteractorStyleRubberBandPickWrap( ); static Nan::Persistent<v8::FunctionTemplate> ptpl; private: static void New(const Nan::FunctionCallbackInfo<v8::Value>& info); static void NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info); static void OnChar(const Nan::FunctionCallbackInfo<v8::Value>& info); static void OnLeftButtonDown(const Nan::FunctionCallbackInfo<v8::Value>& info); static void OnLeftButtonUp(const Nan::FunctionCallbackInfo<v8::Value>& info); static void OnMouseMove(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info); static void StartSelect(const Nan::FunctionCallbackInfo<v8::Value>& info); #ifdef VTK_NODE_PLUS_VTKINTERACTORSTYLERUBBERBANDPICKWRAP_CLASSDEF VTK_NODE_PLUS_VTKINTERACTORSTYLERUBBERBANDPICKWRAP_CLASSDEF #endif }; #endif
37.042553
90
0.805284
[ "object" ]
c7acb4fe44510fe10c1cd2179777b938bcd0b3b4
3,246
h
C
include/HMM/Model.h
Jamagas/HMM
7a9fc3446c28be79da36e7b567ad3b18cdf5c185
[ "MIT" ]
1
2021-03-07T15:51:12.000Z
2021-03-07T15:51:12.000Z
include/HMM/Model.h
Jamagas/HMM
7a9fc3446c28be79da36e7b567ad3b18cdf5c185
[ "MIT" ]
null
null
null
include/HMM/Model.h
Jamagas/HMM
7a9fc3446c28be79da36e7b567ad3b18cdf5c185
[ "MIT" ]
null
null
null
#ifndef __HMM__Model__ #define __HMM__Model__ #include <string> #include "StateTransitionProbabilityDistributionMatrix.h" #include "StateEmissionProbabilityDistributionMatrix.h" #include "InitialStateProbabilityDistribution.h" template<std::size_t numberOfStates, std::size_t numberOfObservationSymbols> class Model { private: StateTransitionProbabilityDistributionMatrix<numberOfStates> transitionDistribution; StateEmissionProbabilityDistributionMatrix<numberOfStates, numberOfObservationSymbols> emissionDistribution; InitialStateProbabilityDistribution<numberOfStates> initialStateDistribution; std::array<std::string, numberOfObservationSymbols> observationSymbols; Model() { } public: Model(const StateTransitionProbabilityDistributionMatrix<numberOfStates> &transitionDistribution, const StateEmissionProbabilityDistributionMatrix<numberOfStates, numberOfObservationSymbols> &emissionDistribution, const InitialStateProbabilityDistribution<numberOfStates> &initialStateDistribution, const std::array<std::string, numberOfObservationSymbols> &observationSymbols) : transitionDistribution(transitionDistribution), emissionDistribution(emissionDistribution), initialStateDistribution(initialStateDistribution) { this->transitionDistribution = transitionDistribution; this->emissionDistribution = emissionDistribution; this->initialStateDistribution = initialStateDistribution; this->observationSymbols = observationSymbols; } StateTransitionProbabilityDistributionMatrix<numberOfStates> getTransitionDistribution() { return this->transitionDistribution; } StateEmissionProbabilityDistributionMatrix<numberOfStates, numberOfObservationSymbols> getEmissionDistribution() { return this->emissionDistribution; } InitialStateProbabilityDistribution<numberOfStates> getInitialStateDistribution() { return this->initialStateDistribution; } std::array<std::string, numberOfObservationSymbols> getObservationSymbols() { return this->observationSymbols; } template<std::size_t numberOfObservationSymbolsInSequence> std::array<int, numberOfObservationSymbolsInSequence> getObservationSymbolsIndexes(std::array<std::string, numberOfObservationSymbolsInSequence> observationSymbolsSequence) { std::array<int, numberOfObservationSymbolsInSequence> observationSymbolsIndexesArray = {}; observationSymbolsIndexesArray.fill(-1); for (int observationSymbolIndexInSequence = 0; observationSymbolIndexInSequence < numberOfObservationSymbolsInSequence; observationSymbolIndexInSequence++) { for (int observationSymbolIndex = 0; observationSymbolIndex < numberOfObservationSymbols; observationSymbolIndex++) { if (observationSymbols[observationSymbolIndex].compare(observationSymbolsSequence[observationSymbolIndexInSequence]) == 0) { observationSymbolsIndexesArray[observationSymbolIndexInSequence] = observationSymbolIndex; break; } } } return observationSymbolsIndexesArray; } }; #endif
45.083333
178
0.773876
[ "model" ]
c7b97a62f45cd3de3abf9fbb446d1e9508e0f70f
6,503
h
C
source/common/2d/drawparms.h
bisk89/Raze
1a2663f7ac84d4e4f472e0796b937447ee6fab6b
[ "RSA-MD" ]
2
2020-03-26T10:11:17.000Z
2021-01-19T08:16:48.000Z
source/common/2d/drawparms.h
bisk89/Raze
1a2663f7ac84d4e4f472e0796b937447ee6fab6b
[ "RSA-MD" ]
null
null
null
source/common/2d/drawparms.h
bisk89/Raze
1a2663f7ac84d4e4f472e0796b937447ee6fab6b
[ "RSA-MD" ]
null
null
null
#pragma once /* ** v_video.h ** **--------------------------------------------------------------------------- ** Copyright 1998-2008 Randy Heit ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** 2. Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** 3. The name of the author may not be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **--------------------------------------------------------------------------- ** */ #include "palentry.h" #include "renderstyle.h" #include "c_cvars.h" #include "v_2ddrawer.h" #define TAG_DONE (0) /* Used to indicate the end of the Tag list */ #define TAG_END (0) /* Ditto */ /* list pointed to in ti_Data */ enum { DTA_Base = 1, DTA_DestWidth, // width of area to draw to DTA_DestHeight, // height of area to draw to DTA_Alpha, // alpha value for translucency DTA_FillColor, // color to stencil onto the destination DTA_TranslationIndex, // translation table to recolor the source DTA_AlphaChannel, // bool: the source is an alpha channel; used with DTA_FillColor DTA_Clean, // bool: scale texture size and position by CleanXfac and CleanYfac DTA_320x200, // bool: scale texture size and position to fit on a virtual 320x200 screen DTA_Bottom320x200, // bool: same as DTA_320x200 but centers virtual screen on bottom for 1280x1024 targets DTA_CleanNoMove, // bool: like DTA_Clean but does not reposition output position DTA_CleanNoMove_1, // bool: like DTA_CleanNoMove, but uses Clean[XY]fac_1 instead DTA_FlipX, // bool: flip image horizontally //FIXME: Does not work with DTA_Window(Left|Right) DTA_ShadowColor, // color of shadow DTA_ShadowAlpha, // alpha of shadow DTA_Shadow, // set shadow color and alphas to defaults DTA_VirtualWidth, // pretend the canvas is this wide DTA_VirtualHeight, // pretend the canvas is this tall DTA_TopOffset, // override texture's top offset DTA_LeftOffset, // override texture's left offset DTA_CenterOffset, // bool: override texture's left and top offsets and set them for the texture's middle DTA_CenterBottomOffset,// bool: override texture's left and top offsets and set them for the texture's bottom middle DTA_WindowLeft, // don't draw anything left of this column (on source, not dest) DTA_WindowRight, // don't draw anything at or to the right of this column (on source, not dest) DTA_ClipTop, // don't draw anything above this row (on dest, not source) DTA_ClipBottom, // don't draw anything at or below this row (on dest, not source) DTA_ClipLeft, // don't draw anything to the left of this column (on dest, not source) DTA_ClipRight, // don't draw anything at or to the right of this column (on dest, not source) DTA_Masked, // true(default)=use masks from texture, false=ignore masks DTA_HUDRules, // use fullscreen HUD rules to position and size textures DTA_HUDRulesC, // only used internally for marking HUD_HorizCenter DTA_KeepRatio, // doesn't adjust screen size for DTA_Virtual* if the aspect ratio is not 4:3 DTA_RenderStyle, // same as render style for actors DTA_ColorOverlay, // uint32_t: ARGB to overlay on top of image; limited to black for software DTA_BilinearFilter, // bool: apply bilinear filtering to the image DTA_SpecialColormap,// pointer to FSpecialColormapParameters DTA_Desaturate, // explicit desaturation factor (does not do anything in Legacy OpenGL) DTA_Fullscreen, // Draw image fullscreen (same as DTA_VirtualWidth/Height with graphics size.) // floating point duplicates of some of the above: DTA_DestWidthF, DTA_DestHeightF, DTA_TopOffsetF, DTA_LeftOffsetF, DTA_VirtualWidthF, DTA_VirtualHeightF, DTA_WindowLeftF, DTA_WindowRightF, // For DrawText calls: DTA_TextLen, // stop after this many characters, even if \0 not hit DTA_CellX, // horizontal size of character cell DTA_CellY, // vertical size of character cell // New additions. DTA_Color, DTA_FlipY, // bool: flip image vertically DTA_SrcX, // specify a source rectangle (this supersedes the poorly implemented DTA_WindowLeft/Right DTA_SrcY, DTA_SrcWidth, DTA_SrcHeight, DTA_LegacyRenderStyle, // takes an old-style STYLE_* constant instead of an FRenderStyle DTA_Burn, // activates the burn shader for this element DTA_Spacing, // Strings only: Additional spacing between characters DTA_Monospace, // Fonts only: Use a fixed distance between characters. }; enum EMonospacing : int { Off = 0, CellLeft = 1, CellCenter = 2, CellRight = 3 }; enum { HUD_Normal, HUD_HorizCenter }; class FFont; struct DrawParms { double x, y; double texwidth; double texheight; double destwidth; double destheight; double virtWidth; double virtHeight; double windowleft; double windowright; int cleanmode; int dclip; int uclip; int lclip; int rclip; double top; double left; float Alpha; int remap; PalEntry fillcolor; PalEntry colorOverlay; PalEntry color; int alphaChannel; int flipX; int flipY; //float shadowAlpha; int shadowColor; int keepratio; int masked; int bilinear; FRenderStyle style; int desaturate; int scalex, scaley; int cellx, celly; int monospace; int spacing; int maxstrlen; bool fortext; bool virtBottom; double srcx, srcy; double srcwidth, srcheight; bool burn; }; struct Va_List { va_list list; };
35.928177
117
0.736429
[ "render" ]
c7bfdbb57c110b46ce751675425741dfc12ca060
804
h
C
compat/hkbHandle_1.h
BlazesRus/hkxcmd
e00a554225234e40e111e808b095156ac1d4b1fe
[ "Intel" ]
38
2015-03-24T00:41:59.000Z
2022-03-23T09:18:29.000Z
compat/hkbHandle_1.h
BlazesRus/hkxcmd
e00a554225234e40e111e808b095156ac1d4b1fe
[ "Intel" ]
2
2015-10-14T07:41:48.000Z
2015-12-14T02:19:05.000Z
compat/hkbHandle_1.h
BlazesRus/hkxcmd
e00a554225234e40e111e808b095156ac1d4b1fe
[ "Intel" ]
24
2015-08-03T20:41:07.000Z
2022-03-27T03:58:37.000Z
#pragma once #include <Common/Base/hkBase.h> #include <Common/Base/Object/hkReferencedObject.h> #include <Common/Base/Types/Geometry/LocalFrame/hkLocalFrame.h> #include <Physics/Dynamics/Entity/hkpRigidBody.h> #include "hkbCharacter_2.h" class hkbHandle : public hkReferencedObject { public: HK_DECLARE_CLASS_ALLOCATOR( HK_MEMORY_CLASS_BEHAVIOR_RUNTIME ); HK_DECLARE_REFLECTION(); public: HK_FORCE_INLINE hkbHandle(void) {} HK_FORCE_INLINE hkbHandle( hkFinishLoadedObjectFlag flag ) : hkReferencedObject(flag) , m_frame(flag) , m_rigidBody(flag) , m_character(flag) {} // Properties hkRefPtr<hkLocalFrame> m_frame; hkRefPtr<hkpRigidBody> m_rigidBody; hkRefPtr<hkbCharacter> m_character; hkInt16 m_animationBoneIndex; }; extern const hkClass hkbHandleClass;
26.8
89
0.773632
[ "geometry", "object" ]
c7c7f2a77f9d715835190433a25da3dd2ba68422
1,636
h
C
src/cmake/cmakefile.h
fredsson/cmakegen
ff06db45236220f44fb11ad8363a52d7fbbb82b9
[ "MIT" ]
1
2019-11-16T09:57:41.000Z
2019-11-16T09:57:41.000Z
src/cmake/cmakefile.h
fredsson/cmakegen
ff06db45236220f44fb11ad8363a52d7fbbb82b9
[ "MIT" ]
17
2019-02-09T12:45:13.000Z
2021-11-14T15:13:21.000Z
src/cmake/cmakefile.h
fredsson/cmakegen
ff06db45236220f44fb11ad8363a52d7fbbb82b9
[ "MIT" ]
null
null
null
#ifndef CMAKE_CMAKEFILE_H #define CMAKE_CMAKEFILE_H #include "cmakefunction.h" #include <memory> #include <string> #include <vector> class IoHandler; namespace cmake { struct Token; class CmakeScanner; class ICmakeFunctionCriteria; class CmakeFile { public: static std::shared_ptr<CmakeFile> parse(const std::string& directoryPath, const std::string& filePath, IoHandler& ioHandler); CmakeFile(const std::string& path); const std::string& path() const; const std::vector<CmakeFunction*> functions() const; bool hasPositions() const; int includeFilesOffsetAdded() const; CmakeFunction* getFunction(const ICmakeFunctionCriteria& criteria) const; void addFunction(const std::shared_ptr<CmakeFunction>& func); void replaceIncludeFiles(const std::vector<std::string>& includeFiles); void replaceSourceFiles(const std::vector<std::string>& sourceFiles); void removeIncludeFiles(); void write(); private: static std::shared_ptr<CmakeFunction> parseFunction(const Token& parentToken, CmakeScanner& scanner); void addIncludeFunction(const std::vector<std::string>& includeFiles); void moveFunctions(std::vector<std::shared_ptr<CmakeFunction>>::iterator startItr, const int lineOffset); std::shared_ptr<CmakeFunction> createReplacementFunction( const std::string& functionName, const std::string& setArgumentName, const FilePosition& startPosition, const std::vector<std::string>& files ); std::string path_; std::vector<std::string> includeFiles_; std::vector<std::string> sourceFiles_; std::vector<std::shared_ptr<CmakeFunction>> functions_; bool hasPositions_; }; } #endif
30.296296
127
0.765281
[ "vector" ]
c7d92885ee8ce87101a85f980165704682dc2e9e
2,063
h
C
sem2/oop/Laboratoare/LAB6-7/Exercitiu/Exercitiu/Exercitiu/ListaVD.h
itsbratu/bachelor
b3bcae07fc8297fb0557a4bf752b20c6104c2563
[ "MIT" ]
null
null
null
sem2/oop/Laboratoare/LAB6-7/Exercitiu/Exercitiu/Exercitiu/ListaVD.h
itsbratu/bachelor
b3bcae07fc8297fb0557a4bf752b20c6104c2563
[ "MIT" ]
null
null
null
sem2/oop/Laboratoare/LAB6-7/Exercitiu/Exercitiu/Exercitiu/ListaVD.h
itsbratu/bachelor
b3bcae07fc8297fb0557a4bf752b20c6104c2563
[ "MIT" ]
null
null
null
#pragma once template <class T> class ListVD { class iterator { public: typedef iterator self_type; typedef T value_type; typedef T& reference; typedef T* pointer; typedef std::forward_iterator_tag iterator_category; typedef int difference_type; iterator(pointer ptr) : ptr_(ptr) { } self_type operator++() { self_type i = *this; ptr_++; return i; } self_type operator++(int junk) { ptr_++; return *this; } reference operator*() { return *ptr_; } pointer operator->() { return ptr_; } bool operator==(const self_type& rhs) { return ptr_ == rhs.ptr_; } bool operator!=(const self_type& rhs) { return ptr_ != rhs.ptr_; } private: pointer ptr_; }; private: int cap; int lg; T* elems; public: int size() const { return lg; } //constructor default pentru vector dinamic ListVD() : cap{ 1 }, lg{ 0 }, elems{ new Activity[cap] }{ } //constructor copiere ListVD(const ListVD& ot) : cap{ ot.cap }, lg{ ot.lg }, elems{ new Activity[ot.lg] }{ for (int i = 0; i < ot.lg; ++i) elems[i] = ot.elems[i]; } //operator assignment void operator =(const ListVD& ot) { delete[] elems; elems = new Activity[ot.lg]; lg = ot.lg; cap = ot.cap; for (int i = 0; i < lg; ++i) elems[i] = ot.elems[i]; } //destructor ~ListVD() { delete[] elems; } ListVD(std::vector <T> acts) { for (const auto& a : acts) push_back(a); } std::vector<T> toStdVector() const { std::vector<T> rez; for (int i = 0; i < lg; ++i) rez.push_back(elems[i]); return rez; } //Aduagare vector dinamic void push_back(const T& a) { if (cap == lg) { T* aux = new T[cap * 2]; for (int i = 0; i < lg; ++i) { aux[i] = elems[i]; } delete[] elems; elems = aux; cap = cap * 2; } elems[lg++] = a; } iterator begin() const { return iterator(&elems[0]); } iterator end() const { return iterator(&elems[lg]); } T back() const { return elems[lg - 1]; } void pop_back() { lg--; } T operator [](size_t i) const { return elems[i]; } T& operator [](size_t i) { return elems[i]; } };
19.101852
85
0.601551
[ "vector" ]
c7de3359b20a87981b1085a1ecffb78975ac01d2
889
h
C
ex19_prototype_system/object.h
thlorenz/learn-c-the-hard-way
686c20949f150c6149fe35d12ee7d8d8290ea8c0
[ "MIT" ]
8
2015-05-29T05:42:10.000Z
2019-09-23T19:47:11.000Z
ex19_prototype_system/object.h
thlorenz/learn-c-the-hard-way
686c20949f150c6149fe35d12ee7d8d8290ea8c0
[ "MIT" ]
null
null
null
ex19_prototype_system/object.h
thlorenz/learn-c-the-hard-way
686c20949f150c6149fe35d12ee7d8d8290ea8c0
[ "MIT" ]
3
2016-10-14T02:03:13.000Z
2020-03-04T11:26:42.000Z
#ifndef _OBJECT_H #define _OBJECT_H #include <stdlib.h> typedef enum { NORTH, SOUTH, EAST, WEST } Direction; // all proto structs will have Object as first field // that way they all can pe treated as just an Object struct typedef struct { char *description; int (*init)(void *self); void (*describe)(void *self); void (*destroy)(void *self); void *(*move)(void *self, Direction direction); int (*attack)(void *self, int damage); } Object; int Object_init(void *self); void Object_describe(void *self); void Object_destroy(void *self); void *Object_move(void *self, Direction direction); int Object_attack(void *self, int damage); void *Object_new(size_t size, Object proto, char *description); // T##Object - concat Object to T // Example: new(Room, "Hello) => Object_new(sizeof(Room), RoomProto, "Hello") #define NEW(T, N) Object_new(sizeof(T), T##Proto, N) #endif
26.147059
77
0.709786
[ "object" ]
c7e0dcc2bffce0827d6b615d31095b2a92ec28b4
1,361
c
C
Validation/Performance/bin/SparseCompRow.c
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
Validation/Performance/bin/SparseCompRow.c
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
Validation/Performance/bin/SparseCompRow.c
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
/* multiple iterations used to make kernel have roughly same granulairty as other Scimark kernels. */ double SparseCompRow_num_flops(int N, int nz, int num_iterations) { /* Note that if nz does not divide N evenly, then the actual number of nonzeros used is adjusted slightly. */ int actual_nz = (nz/N) * N; return ((double)actual_nz) * 2.0 * ((double) num_iterations); } /* computes a matrix-vector multiply with a sparse matrix held in compress-row format. If the size of the matrix in MxN with nz nonzeros, then the val[] is the nz nonzeros, with its ith entry in column col[i]. The integer vector row[] is of size M+1 and row[i] points to the begining of the ith row in col[]. */ void SparseCompRow_matmult( int M, double *y, double *val, int *row, int *col, double *x, int NUM_ITERATIONS) { int reps; int r; int i; for (reps=0; reps<NUM_ITERATIONS; reps++) { for (r=0; r<M; r++) { double sum = 0.0; int rowR = row[r]; int rowRp1 = row[r+1]; for (i=rowR; i<rowRp1; i++) sum += x[ col[i] ] * val[i]; y[r] = sum; } } }
30.931818
72
0.523145
[ "vector" ]
c7e3334b72c396f889f1cd65716823e220abbc4a
1,925
h
C
tensorflow/dtensor/mlir/shape_utils.h
TheRakeshPurohit/tensorflow
bee6d5a268122df99e1e55a7b92517e84ad25bab
[ "Apache-2.0" ]
3
2022-03-09T01:39:56.000Z
2022-03-30T23:17:58.000Z
tensorflow/dtensor/mlir/shape_utils.h
TheRakeshPurohit/tensorflow
bee6d5a268122df99e1e55a7b92517e84ad25bab
[ "Apache-2.0" ]
1
2020-08-01T05:40:12.000Z
2020-08-01T05:40:12.000Z
tensorflow/dtensor/mlir/shape_utils.h
TheRakeshPurohit/tensorflow
bee6d5a268122df99e1e55a7b92517e84ad25bab
[ "Apache-2.0" ]
1
2022-01-29T04:25:16.000Z
2022-01-29T04:25:16.000Z
/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless 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. ==============================================================================*/ #ifndef TENSORFLOW_DTENSOR_MLIR_SHAPE_UTILS_H_ #define TENSORFLOW_DTENSOR_MLIR_SHAPE_UTILS_H_ #include "llvm/ADT/ArrayRef.h" #include "mlir/IR/Operation.h" // from @llvm-project #include "mlir/IR/Value.h" // from @llvm-project #include "tensorflow/dtensor/cc/dstatus.h" namespace tensorflow { namespace dtensor { StatusOr<llvm::ArrayRef<int64_t>> ExtractGlobalInputShape( mlir::OpOperand& input_value); StatusOr<llvm::ArrayRef<int64_t>> ExtractGlobalOutputShape( mlir::OpResult result_value); // Returns op with recalculated local shape of `op` given all it's operands. mlir::Operation* InferSPMDExpandedLocalShape(mlir::Operation* op); // Gets the shape of a Value if the type is a RankedTensorType, otherwise // returns an error. StatusOr<llvm::ArrayRef<int64_t>> GetShapeOfValue(const mlir::Value& value, bool fail_on_dynamic = false); // If the producer or consumer of this value is a DTensorLayout, retrieves // the global shape from that layout, otherwise returns an error. StatusOr<llvm::ArrayRef<int64_t>> GetGlobalShapeOfValueFromDTensorLayout( const mlir::Value& value); } // namespace dtensor } // namespace tensorflow #endif // TENSORFLOW_DTENSOR_MLIR_SHAPE_UTILS_H_
38.5
80
0.731429
[ "shape" ]
c7ecc1dcbc06d8820ce056b68568a5fe72b29e64
1,572
h
C
Header/UMProtocolData.h
titer18/umengCommunity
87953c7b0968e3ac1a24a41dc45fd974fd88eac6
[ "MIT" ]
1
2018-11-05T06:36:55.000Z
2018-11-05T06:36:55.000Z
shishi/Library/UMCommunitySDK/UMCommunitySDK/UMComFoundation.framework/Headers/UMProtocolData.h
myandy/shi_ios
b7afd208de6a1eb2bdf37e25d1d7c4fd29cae258
[ "Apache-2.0" ]
null
null
null
shishi/Library/UMCommunitySDK/UMCommunitySDK/UMComFoundation.framework/Headers/UMProtocolData.h
myandy/shi_ios
b7afd208de6a1eb2bdf37e25d1d7c4fd29cae258
[ "Apache-2.0" ]
1
2018-11-05T06:36:56.000Z
2018-11-05T06:36:56.000Z
// // Created by ming on 08/28/13. // // #import <Foundation/Foundation.h> #define UM_SAFE_STR(Object) (Object==nil?@"":Object) @interface UMProtocolData : NSObject #pragma mark dateTime info + (NSString *)dateString; + (NSString *)timeString; + (NSString *)timeMSString; + (NSString *)latString; + (NSString *)lngString; #pragma mark deviceAndOS info //just for iOS 6.0 or later,please test in device //+ (NSString *)deviceIDAdverString; //just for iOS 6.0 or later + (NSString *)deviceIDVendorString; //mac_adress + (NSString *)deviceMacString; //mac_adress_md5 //+ (NSString *)deviceMacMD5String; + (NSString *)openUDIDString; + (NSString *)UUIDString; + (NSString *)UUIDMD5String; //device_model + (NSString *)deviceModelString; //resolution + (NSString *)resolutionString; //os + (NSString *)osString; //os_version + (NSString *)osVersionString; //cpu + (NSString *)cpuString; + (NSString *)orientationString; //is_jailbroken + (BOOL)isDeviceJailBreak; + (NSString *)deviceJailBreakString; + (BOOL)isPad; //country + (NSString *)countryString; //language + (NSString *)languageString; //timezone + (NSString *)timezoneString; #pragma mark network info //access + (NSString *)accessString; //carrier + (NSString *)carrierString; #pragma mark ipa info //is_pirated + (BOOL)isAppPirate; + (NSString *)appPirateString; //package_name + (NSString *)appPackageNameString; //display_name + (NSString *)appDisplayNameString; //app_version + (NSString *)appBundleVersionString; //appShortversion + (NSString *)appShortVersionString; @end
15.411765
52
0.721374
[ "object" ]
c7efc3b8362e7c92c18408b787ab3bd6326f9bf8
7,651
h
C
linux_packages/source/hypre-2.9.0b/src/babel-runtime/sidl/sidl_DFinder_Impl.h
pangkeji/warp3d
8b273b337e557f734298940a63291697cd561d02
[ "NCSA" ]
75
2015-07-06T18:14:20.000Z
2022-01-24T02:54:32.000Z
linux_packages/source/hypre-2.9.0b/src/babel-runtime/sidl/sidl_DFinder_Impl.h
pangkeji/warp3d
8b273b337e557f734298940a63291697cd561d02
[ "NCSA" ]
15
2017-04-07T18:09:58.000Z
2022-02-28T01:48:33.000Z
linux_packages/source/hypre-2.9.0b/src/babel-runtime/sidl/sidl_DFinder_Impl.h
pangkeji/warp3d
8b273b337e557f734298940a63291697cd561d02
[ "NCSA" ]
41
2015-05-24T23:24:54.000Z
2021-12-13T22:07:45.000Z
/* * File: sidl_DFinder_Impl.h * Symbol: sidl.DFinder-v0.9.15 * Symbol Type: class * Babel Version: 1.0.4 * Release: $Name: V2-9-0b $ * Revision: @(#) $Id: sidl_DFinder_Impl.h,v 1.6 2007/09/27 19:35:43 painter Exp $ * Description: Server-side implementation for sidl.DFinder * * Copyright (c) 2000-2002, The Regents of the University of California. * Produced at the Lawrence Livermore National Laboratory. * Written by the Components Team <components@llnl.gov> * All rights reserved. * * This file is part of Babel. For more information, see * http://www.llnl.gov/CASC/components/. Please read the COPYRIGHT file * for Our Notice and the LICENSE file for the GNU Lesser General Public * License. * * 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 dated 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 recieved 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 * * WARNING: Automatically generated; only changes within splicers preserved * */ #ifndef included_sidl_DFinder_Impl_h #define included_sidl_DFinder_Impl_h #ifndef included_sidl_header_h #include "sidl_header.h" #endif #ifndef included_sidl_BaseClass_h #include "sidl_BaseClass.h" #endif #ifndef included_sidl_BaseInterface_h #include "sidl_BaseInterface.h" #endif #ifndef included_sidl_ClassInfo_h #include "sidl_ClassInfo.h" #endif #ifndef included_sidl_DFinder_h #include "sidl_DFinder.h" #endif #ifndef included_sidl_DLL_h #include "sidl_DLL.h" #endif #ifndef included_sidl_Finder_h #include "sidl_Finder.h" #endif #ifndef included_sidl_RuntimeException_h #include "sidl_RuntimeException.h" #endif /* DO-NOT-DELETE splicer.begin(sidl.DFinder._includes) */ /* Put additional include files here... */ /* DO-NOT-DELETE splicer.end(sidl.DFinder._includes) */ /* * Private data for class sidl.DFinder */ struct sidl_DFinder__data { /* DO-NOT-DELETE splicer.begin(sidl.DFinder._data) */ /* Put private data members here... */ char* d_search_path; /* DO-NOT-DELETE splicer.end(sidl.DFinder._data) */ }; #ifdef __cplusplus extern "C" { #endif /* * Access functions for class private data and built-in methods */ extern struct sidl_DFinder__data* sidl_DFinder__get_data( sidl_DFinder); extern void sidl_DFinder__set_data( sidl_DFinder, struct sidl_DFinder__data*); extern void impl_sidl_DFinder__load( /* out */ sidl_BaseInterface *_ex); extern void impl_sidl_DFinder__ctor( /* in */ sidl_DFinder self, /* out */ sidl_BaseInterface *_ex); extern void impl_sidl_DFinder__ctor2( /* in */ sidl_DFinder self, /* in */ void* private_data, /* out */ sidl_BaseInterface *_ex); extern void impl_sidl_DFinder__dtor( /* in */ sidl_DFinder self, /* out */ sidl_BaseInterface *_ex); /* * User-defined object methods */ extern struct sidl_BaseClass__object* impl_sidl_DFinder_fconnect_sidl_BaseClass( const char* url, sidl_bool ar, sidl_BaseInterface *_ex); extern struct sidl_BaseClass__object* impl_sidl_DFinder_fcast_sidl_BaseClass( void* bi, sidl_BaseInterface* _ex); extern struct sidl_BaseInterface__object* impl_sidl_DFinder_fconnect_sidl_BaseInterface(const char* url, sidl_bool ar, sidl_BaseInterface *_ex); extern struct sidl_BaseInterface__object* impl_sidl_DFinder_fcast_sidl_BaseInterface(void* bi, sidl_BaseInterface* _ex); extern struct sidl_ClassInfo__object* impl_sidl_DFinder_fconnect_sidl_ClassInfo( const char* url, sidl_bool ar, sidl_BaseInterface *_ex); extern struct sidl_ClassInfo__object* impl_sidl_DFinder_fcast_sidl_ClassInfo( void* bi, sidl_BaseInterface* _ex); extern struct sidl_DFinder__object* impl_sidl_DFinder_fconnect_sidl_DFinder( const char* url, sidl_bool ar, sidl_BaseInterface *_ex); extern struct sidl_DFinder__object* impl_sidl_DFinder_fcast_sidl_DFinder(void* bi, sidl_BaseInterface* _ex); extern struct sidl_DLL__object* impl_sidl_DFinder_fconnect_sidl_DLL(const char* url, sidl_bool ar, sidl_BaseInterface *_ex); extern struct sidl_DLL__object* impl_sidl_DFinder_fcast_sidl_DLL(void* bi, sidl_BaseInterface* _ex); extern struct sidl_Finder__object* impl_sidl_DFinder_fconnect_sidl_Finder(const char* url, sidl_bool ar, sidl_BaseInterface *_ex); extern struct sidl_Finder__object* impl_sidl_DFinder_fcast_sidl_Finder(void* bi, sidl_BaseInterface* _ex); extern struct sidl_RuntimeException__object* impl_sidl_DFinder_fconnect_sidl_RuntimeException(const char* url, sidl_bool ar, sidl_BaseInterface *_ex); extern struct sidl_RuntimeException__object* impl_sidl_DFinder_fcast_sidl_RuntimeException(void* bi, sidl_BaseInterface* _ex); extern sidl_DLL impl_sidl_DFinder_findLibrary( /* in */ sidl_DFinder self, /* in */ const char* sidl_name, /* in */ const char* target, /* in */ enum sidl_Scope__enum lScope, /* in */ enum sidl_Resolve__enum lResolve, /* out */ sidl_BaseInterface *_ex); extern void impl_sidl_DFinder_setSearchPath( /* in */ sidl_DFinder self, /* in */ const char* path_name, /* out */ sidl_BaseInterface *_ex); extern char* impl_sidl_DFinder_getSearchPath( /* in */ sidl_DFinder self, /* out */ sidl_BaseInterface *_ex); extern void impl_sidl_DFinder_addSearchPath( /* in */ sidl_DFinder self, /* in */ const char* path_fragment, /* out */ sidl_BaseInterface *_ex); extern struct sidl_BaseClass__object* impl_sidl_DFinder_fconnect_sidl_BaseClass( const char* url, sidl_bool ar, sidl_BaseInterface *_ex); extern struct sidl_BaseClass__object* impl_sidl_DFinder_fcast_sidl_BaseClass( void* bi, sidl_BaseInterface* _ex); extern struct sidl_BaseInterface__object* impl_sidl_DFinder_fconnect_sidl_BaseInterface(const char* url, sidl_bool ar, sidl_BaseInterface *_ex); extern struct sidl_BaseInterface__object* impl_sidl_DFinder_fcast_sidl_BaseInterface(void* bi, sidl_BaseInterface* _ex); extern struct sidl_ClassInfo__object* impl_sidl_DFinder_fconnect_sidl_ClassInfo( const char* url, sidl_bool ar, sidl_BaseInterface *_ex); extern struct sidl_ClassInfo__object* impl_sidl_DFinder_fcast_sidl_ClassInfo( void* bi, sidl_BaseInterface* _ex); extern struct sidl_DFinder__object* impl_sidl_DFinder_fconnect_sidl_DFinder( const char* url, sidl_bool ar, sidl_BaseInterface *_ex); extern struct sidl_DFinder__object* impl_sidl_DFinder_fcast_sidl_DFinder(void* bi, sidl_BaseInterface* _ex); extern struct sidl_DLL__object* impl_sidl_DFinder_fconnect_sidl_DLL(const char* url, sidl_bool ar, sidl_BaseInterface *_ex); extern struct sidl_DLL__object* impl_sidl_DFinder_fcast_sidl_DLL(void* bi, sidl_BaseInterface* _ex); extern struct sidl_Finder__object* impl_sidl_DFinder_fconnect_sidl_Finder(const char* url, sidl_bool ar, sidl_BaseInterface *_ex); extern struct sidl_Finder__object* impl_sidl_DFinder_fcast_sidl_Finder(void* bi, sidl_BaseInterface* _ex); extern struct sidl_RuntimeException__object* impl_sidl_DFinder_fconnect_sidl_RuntimeException(const char* url, sidl_bool ar, sidl_BaseInterface *_ex); extern struct sidl_RuntimeException__object* impl_sidl_DFinder_fcast_sidl_RuntimeException(void* bi, sidl_BaseInterface* _ex); #ifdef __cplusplus } #endif #endif
34.61991
87
0.788132
[ "object" ]
c7f178d4f3d727c6213f870708a75754de213217
4,395
h
C
include/organism.h
jamesbut/NeuroEvo
96a2e952e93c280e6018a7f55b2c66264cd47206
[ "MIT" ]
8
2019-07-23T13:05:35.000Z
2020-07-09T03:42:27.000Z
include/organism.h
jamesbut/NeuroEvo
96a2e952e93c280e6018a7f55b2c66264cd47206
[ "MIT" ]
null
null
null
include/organism.h
jamesbut/NeuroEvo
96a2e952e93c280e6018a7f55b2c66264cd47206
[ "MIT" ]
null
null
null
#ifndef _ORGANISM_H_ #define _ORGANISM_H_ /* This class contains everything that constitutes an Organism, including its genotype, phenotype and genotype-phenotype map. */ #include <genotype/genotype.h> #include <phenotype/phenotype_specs/phenotype_spec.h> #include <memory> #include <iostream> #include <iomanip> #include <fstream> #include <gp_map/gp_map.h> namespace NeuroEvo { template <typename G, typename T> class Organism { public: Organism(const Genotype<G>& genotype, GPMap<G, T>& gp_map) : _genotype(genotype.clone()), _gp_map(gp_map.clone()), _phenotype(gp_map.map(*_genotype)), _fitness(std::nullopt), _domain_winner(false) {} Organism(GPMap<G, T>& gp_map, const std::string file_name) : _genotype(new Genotype<G>(file_name)), _gp_map(gp_map.clone()), _phenotype(gp_map.map(*_genotype)), _fitness(std::nullopt), _domain_winner(false) {} Organism(const Organism& organism) : _genotype(organism.get_genotype().clone()), _gp_map(organism._gp_map->clone()), _phenotype(organism.get_phenotype().clone_phenotype()), _fitness(organism.get_fitness()), _domain_winner(organism._domain_winner) {} Organism& operator=(const Organism& organism) { _genotype = organism.get_genotype().clone(); _gp_map = organism._gp_map->clone(); _phenotype = organism.get_phenotype().clone_phenotype(); _fitness = organism.get_fitness(); _domain_winner = organism._domain_winner; return *this; } ~Organism() = default; Organism(Organism&& organism) = default; Organism& operator=(Organism&& organism) = default; //Pass in domain completion fitness too in order to determine whether the //organism is a domain winner void set_fitness(const double fitness, const double domain_completion_fitness) { if(fitness >= domain_completion_fitness) _domain_winner = true; _fitness = fitness; } const std::optional<const double> get_fitness() const { return _fitness; } Genotype<G>& get_genotype() const { return *_genotype; } GPMap<G, T>& get_gp_map() const { return *_gp_map; } Phenotype<T>& get_phenotype() const { return *_phenotype; } bool is_domain_winner() const { return _domain_winner; } void set_domain_winner(const bool winner) { _domain_winner = winner; } //Creates new phenotype out of modified genotype void genesis() { _phenotype.reset(_gp_map->map(*_genotype)); } void save_org_to_file( const std::string& file_name, const std::optional<std::vector<double>>& domain_hyperparams = std::nullopt) const { //Print fitness and then the genotype std::ofstream org_file; org_file.open(file_name); org_file << _fitness.value(); org_file << std::setprecision(std::numeric_limits<double>::max_digits10); org_file << "," << *_genotype; //if(_gp_map) // _gp_map.get()->print(org_file); //If domain hyperparams are given write them to a new line if(domain_hyperparams.has_value()) { org_file << "\n"; for(std::size_t i = 0; i < domain_hyperparams.value().size(); i++) { org_file << domain_hyperparams.value()[i]; if(i != domain_hyperparams.value().size()-1) org_file << ","; } } org_file.close(); } friend std::ostream& operator<<(std::ostream& os, const Organism& organism) { //Just print genotype for now os << "Genotype: " << std::endl << "[" << *organism._genotype << "]" << std::endl << "Phenotype: " << std::endl << *organism._phenotype << std::endl << "Fitness: "; if(organism._fitness.has_value()) os << organism._fitness.value(); else os << "N/A"; return os; } private: std::unique_ptr<Genotype<G>> _genotype; std::unique_ptr<GPMap<G, T>> _gp_map; std::unique_ptr<Phenotype<T>> _phenotype; std::optional<double> _fitness; bool _domain_winner; }; } // namespace NeuroEvo #endif
25.552326
84
0.602958
[ "vector" ]
c7f68881c8abb3f675304b039adf5b5983949f9c
6,103
h
C
code/SDK/include/Max_16/Graphics/IViewportViewSetting.h
porames25/xray-oxygen
1f3f46a7a1ffc2be1de04a1ec665862127894ef7
[ "Apache-2.0" ]
7
2018-03-27T12:36:07.000Z
2020-06-26T11:31:52.000Z
code/SDK/include/Max_16/Graphics/IViewportViewSetting.h
porames25/xray-oxygen
1f3f46a7a1ffc2be1de04a1ec665862127894ef7
[ "Apache-2.0" ]
2
2018-05-26T23:17:14.000Z
2019-04-14T18:33:27.000Z
code/SDK/include/Max_16/Graphics/IViewportViewSetting.h
Graff46/xray-oxygen
543e79929c0e8debe57f5c567eaf11e5fe08216f
[ "Apache-2.0" ]
6
2015-03-24T06:40:20.000Z
2019-03-18T13:56:13.000Z
// // Copyright 2012 Autodesk, Inc. All rights reserved. // // Use of this software is subject to the terms of the Autodesk license // agreement provided at the time of installation or download, or which // otherwise accompanies this software in either electronic or hard copy form. // // #pragma once #include "../maxapi.h" #include "GraphicsEnums.h" #define IVIEWPORT_SETTINGS_INTERFACE_ID Interface_ID(0x761840a9, 0x437f4090) namespace MaxSDK { namespace Graphics { /** \brief Viewport Setting For The Nitrous Graphics Viewport \note To access this interface from a ViewExp object, please call ViewExp::GetInterface(IVIEWPORT_SETTINGS_INTERFACE_ID). */ class IViewportViewSetting : public FPMixinInterface { public: /** Enable/Disable progressive rendering. */ virtual void SetProgressiveRenderingEnabled(bool enabled) = 0; /** Get the enable state of progressive rendering \return true if enabled or false otherwise */ virtual bool GetProgressiveRenderingEnabled() const = 0; /** Enable/Disable show edged faces. */ virtual void SetShowEdgedFaces(bool bShowEdgeFaces) = 0; /** Get the state of showing edged faces \return true if edged faces is on or false otherwise */ virtual bool GetShowEdgedFaces() const = 0; /** Enable/Disable use texture. */ virtual void SetUseTexture(bool bUseTexture) = 0; /** Get the state of 'use texture' \return true if use texture or false otherwise */ virtual bool GetUseTexture() const = 0; /** Enable/Disable display selected with edged faces. */ virtual void SetSelectedEdgedFaces(bool bSelEdgedFaces) = 0; /** Get the state of 'display selected with edged faces' \return true if this option is on or false otherwise */ virtual bool GetSelectedEdgedFaces() const = 0; /** Enable/Disable use selection brackets. */ virtual void SetShowSelectionBrackets(bool bShowSelectionBrackets) = 0; /** Get the state of show selection brackets. \return true if this option is on or false otherwise */ virtual bool GetShowSelectionBrackets() const = 0; /** Enable/Disable shade selected faces. */ virtual void SetShadeSelectedFaces(bool bShadeSelFaces) = 0; /** Get the state of shade selected edged faces. \return true if this option is on or false otherwise */ virtual bool GetShadeSelectedFaces() const = 0; /** Set true to disable viewport or false otherwise. */ virtual void SetViewportDisable(bool bViewportDisable) = 0; /** Get the state of viewport disable \return true if viewport is currently disabled or false otherwise */ virtual bool GetViewportDisable() const = 0; /** Enable/Disable viewport clipping. */ virtual void SetViewportClipping(bool bVptClipping) = 0; /** Get the state of viewport clipping \return true if this option is on or false otherwise */ virtual bool GetViewportClipping() const = 0; /** Enable/Disable use environment background color. */ virtual void SetUseEnvironmentBackgroundColor(bool bUseEnvColor) = 0; /** Get the state of use environment background color \return true if this option is on or false otherwise */ virtual bool GetUseEnvironmentBackgroundColor() const = 0; /** Enable/Disable use viewport background. */ virtual void SetUseViewportBackground(bool bValue) = 0; /** Get the state of use viewport background \return true if this option is on or false otherwise */ virtual bool GetUseViewportBackground() const = 0; /** Enable/Disable show highlight. */ virtual void SetShowHighLight(bool bShowHighLight) = 0; /** Get the state of show highlight \return true if this option is on or false otherwise */ virtual bool GetShowHighlight() const = 0; /** Set the current view style. */ virtual void SetViewportVisualStyle(VisualStyle visualStyle) = 0; /** Get the viewport visual style of current viewport \return the visual style */ virtual VisualStyle GetViewportVisualStyle() const = 0; /** Enable/Disable shade selected objects. */ virtual void SetShadeSelectedObjects(bool bShadeSelObj) = 0; /** Get the state of shade selected objects \return true if this option is on or false otherwise */ virtual bool GetShadeSelectedObjects() const = 0; /** Enable/Disable auto display selected light. */ virtual void SetAutoDisplaySelectedLight(bool bAutoDisSelLight) = 0; /** Get the state of auto display selected light \return true if this option is on or false otherwise */ virtual bool GetAutoDisplaySelectedLight() const = 0; /** Enable/Disable ambient occlusion. */ virtual void SetAmbientOcclusionEnabled(bool bAmbientOcclusionEnabled) = 0; /** Get the enabled state of ambient occlusion \return true if ambient occlusion is enabled or false otherwise */ virtual bool GetAmbientOcclusionEnabled() const = 0; /** Enable/Disable shadow. */ virtual void SetShadowsEnabled(bool bShadowsEnabled) = 0; /** Get the state of display shadow \return true if shadow is on or false otherwise */ virtual bool GetShadowsEnabled() const = 0; /** Enable/Disable degrade to default lights. */ virtual void SetAdaptiveDegradeAlwaysDegradeLights(bool bDegradeLights) = 0; /** Get the state of degrade to default lights \return true if this option is on or false otherwise */ virtual bool GetAdaptiveDegradeAlwaysDegradeLights() const = 0; /** Enable/Disable draw back faces for wireframe mesh in adaptive degradation. */ virtual void SetAdaptiveDegradeDrawBackfaces(bool bDrawBackfaces) = 0; /** Get the state of draw backfaces \return true if this option is on or false otherwise */ virtual bool GetAdaptiveDegradeDrawBackfaces() const = 0; /** Set true to never degrade geometry or false otherwise. */ virtual void SetAdaptiveDegradeNeverDegradeGeometry(bool bNeverDegradeGeometry) = 0; /** Get the state of never degrade geometry \return true if this option is on or false otherwise */ virtual bool GetAdaptiveDegradeNeverDegradeGeometry() const = 0; protected: virtual ~IViewportViewSetting(){} }; } }// namespaces
33.168478
86
0.736687
[ "mesh", "geometry", "object" ]
2a01acf128eb96452c46ce9a6af6f15df538c65c
3,713
h
C
Ouroboros/Include/oBasis/oCppParsing.h
jiangzhu1212/oooii
fc00ff81e74adaafd9c98ba7c055f55d95a36e3b
[ "MIT" ]
null
null
null
Ouroboros/Include/oBasis/oCppParsing.h
jiangzhu1212/oooii
fc00ff81e74adaafd9c98ba7c055f55d95a36e3b
[ "MIT" ]
null
null
null
Ouroboros/Include/oBasis/oCppParsing.h
jiangzhu1212/oooii
fc00ff81e74adaafd9c98ba7c055f55d95a36e3b
[ "MIT" ]
null
null
null
// Copyright (c) 2014 Antony Arciuolo. See License.txt regarding use. // Very basic C++ parsing intended to handle trival cases to // build simple compilers such as for reflection systems or // pre-process HLSL source before compiling. #pragma once #ifndef oCppParsing_h #define oCppParsing_h #include <ctype.h> // isalnum // returns true for [A-Za-z0-9_] inline bool oIsCppID(char c) { return isalnum(c) || c == '_'; } // Move to the next id character, or one of the stop chars, whichever is first const char* oMoveToNextID(const char* _pCurrent, const char* _Stop = ""); char* oMoveToNextID(char* _pCurrent, const char* _Stop = ""); // Walks through from start counting lines up until the specified line. size_t oGetLineNumber(const char* _Start, const char* _Line); // Given the string that is returned from typeid(someStdVec).name(), return the // string that represents the typename held in the vector. Returns dst char* oGetStdVectorType(char* _StrDestination, size_t _SizeofStrDestination, const char* _TypeinfoName); // Fills strDestination with the file name of the next found include path // context should be the address of the pointer to a string of C++ source // code, and it will be updated to point just after the found header. This // returns false, when there are no more matches. bool oGetNextInclude(char* _StrDestination, size_t _SizeofStrDestination, const char** _ppContext); // Given a buffer of source that uses #include statements, replace those // statements with the contents of the specified include files by using // a user callback. The buffer must be large enough to accommodate all // merged includes. If this returns false, oErrorGetLst() will be std::errc::io_error to // indicate a problem in the specified Load function or std::errc::invalid_argument // if the specified buffer is too small to hold the results of the merge. bool oMergeIncludes(char* _StrSourceCode, size_t _SizeofStrSourceCode, const char* _SourceFullPath, const std::function<bool(void* _pDestination, size_t _SizeofDestination, const char* _Path)>& _Load); // _____________________________________________________________________________ // Templated-on-size versions of the above API template<size_t size> inline char* oGetStdVectorType(char (&_StrDestination)[size], const char* _TypeinfoName) { return oGetStdVectorType(_StrDestination, size, _TypeinfoName); } template<size_t size> inline bool oGetNextInclude(char (&_StrDestination)[size], const char** _ppContext) { return oGetNextInclude(_StrDestination, size, _ppContext); } template<size_t size> inline errno_t oMergeIncludes(char (&_StrSourceCode)[size], const char* _SourceFullPath, const std::function<bool(void* _pDestination, size_t _SizeofDestination, const char* _Path)>& _Load, char* _StrErrorMessage, size_t _SizeofStrErrorMessage) { return oMergeIncludes(_StrSourceCode, size, _SourceFullPath, Load, _StrErrorMessage, _SizeofStrErrorMessage); } template<size_t size> inline errno_t oMergeIncludes(char* _StrSourceCode, size_t _SizeofStrSourceCode, const char* _SourceFullPath, const std::function<bool(void* _pDestination, size_t _SizeofDestination, const char* _Path)>& Load, char (&_StrErrorMessage)[size]) { return oMergeIncludes(_StrSourceCode, size, _SourceFullPath, Load, _StrErrorMessage, size); } template<size_t size, size_t errSize> inline errno_t oMergeIncludes(char (&_StrSourceCode)[size], const char* _SourceFullPath, const std::function<bool(void* _pDestination, size_t _SizeofDestination, const char* _Path)>& Load, char (&_StrErrorMessage)[errSize]) { return oMergeIncludes(_StrSourceCode, size, _SourceFullPath, Load, _StrErrorMessage, errSize); } #endif
75.77551
381
0.778616
[ "vector" ]
2a1585dc1f54e40920ad0f9583ac7e900fe00bea
2,342
h
C
include/Graph.h
asardaes/dijkstra-shortest-path
4cda25c4c7973699261956fdd883f8ca0ff1a95e
[ "MIT" ]
null
null
null
include/Graph.h
asardaes/dijkstra-shortest-path
4cda25c4c7973699261956fdd883f8ca0ff1a95e
[ "MIT" ]
null
null
null
include/Graph.h
asardaes/dijkstra-shortest-path
4cda25c4c7973699261956fdd883f8ca0ff1a95e
[ "MIT" ]
null
null
null
#ifndef GRAPH_H #define GRAPH_H #include <algorithm> // std::find_if #include <iostream> // std::cout #include <limits> // std::numeric_limits<>::max #include <map> // std::map #include <set> // std::set #include <utility> // std::pair #include <vector> // std::vector // ============================================================================================================================= // Graph class template // ============================================================================================================================= template <typename vertex_t, typename weight_t> class Graph { public: typedef int id_t; protected: private: template <typename w_t> struct Vertex { Vertex(); Vertex(const id_t& id, const vertex_t& name); id_t id; vertex_t name; std::vector< std::pair<id_t, w_t> > edges; }; id_t ids = id_t(0); bool directed; std::vector< Vertex<weight_t> > vertices; std::map< vertex_t, id_t > names_to_ids; public: enum class EXCEPTIONS { VERTEX_REPEATED }; Graph(const int& num_vert = 1, const bool& directed = true); Graph(const std::vector<vertex_t>& vert_names, const bool& directed = true); unsigned int size(); bool is_directed(); void print(); id_t get_vertex_id(const vertex_t& name); bool add_vertex_by_name(const vertex_t& name); bool add_edge_by_id(const id_t& id_1, const id_t& id_2, const weight_t& weight = weight_t(0)); bool add_edge_by_name(const vertex_t& vert_1, const vertex_t& vert_2, const weight_t& weight = weight_t(0)); bool add_edge_by_name(const vertex_t& vert_1, const std::vector<vertex_t>& verts_2, const std::vector<weight_t>& weights); weight_t shortest_path_by_id(const id_t& start, const id_t& target); weight_t shortest_path_by_name(const vertex_t& start, const vertex_t& target); }; // ============================================================================================================================= // Implementation // ============================================================================================================================= #include "Graph.hpp" #endif // GRAPH_H
33.942029
130
0.494876
[ "vector" ]
2a1b02b40eebff7ed08910eab27570639908b42a
4,317
h
C
llvm/include/llvm/Transforms/Scalar/TLSVariableHoist.h
lxbndr/llvm-project
2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34
[ "Apache-2.0" ]
null
null
null
llvm/include/llvm/Transforms/Scalar/TLSVariableHoist.h
lxbndr/llvm-project
2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34
[ "Apache-2.0" ]
null
null
null
llvm/include/llvm/Transforms/Scalar/TLSVariableHoist.h
lxbndr/llvm-project
2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34
[ "Apache-2.0" ]
null
null
null
//==- TLSVariableHoist.h ------ Remove Redundant TLS Loads -------*- C++ -*-==// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This pass identifies/eliminates Redundant TLS Loads if related option is set. // For example: // static __thread int x; // int g(); // int f(int c) { // int *px = &x; // while (c--) // *px += g(); // return *px; // } // // will generate Redundant TLS Loads by compiling it with // clang++ -fPIC -ftls-model=global-dynamic -O2 -S // // .LBB0_2: # %while.body // # =>This Inner Loop Header: Depth=1 // callq _Z1gv@PLT // movl %eax, %ebp // leaq _ZL1x@TLSLD(%rip), %rdi // callq __tls_get_addr@PLT // addl _ZL1x@DTPOFF(%rax), %ebp // movl %ebp, _ZL1x@DTPOFF(%rax) // addl $-1, %ebx // jne .LBB0_2 // jmp .LBB0_3 // .LBB0_4: # %entry.while.end_crit_edge // leaq _ZL1x@TLSLD(%rip), %rdi // callq __tls_get_addr@PLT // movl _ZL1x@DTPOFF(%rax), %ebp // // The Redundant TLS Loads will hurt the performance, especially in loops. // So we try to eliminate/move them if required by customers, let it be: // // # %bb.0: # %entry // ... // movl %edi, %ebx // leaq _ZL1x@TLSLD(%rip), %rdi // callq __tls_get_addr@PLT // leaq _ZL1x@DTPOFF(%rax), %r14 // testl %ebx, %ebx // je .LBB0_1 // .LBB0_2: # %while.body // # =>This Inner Loop Header: Depth=1 // callq _Z1gv@PLT // addl (%r14), %eax // movl %eax, (%r14) // addl $-1, %ebx // jne .LBB0_2 // jmp .LBB0_3 // //===----------------------------------------------------------------------===// #ifndef LLVM_TRANSFORMS_SCALAR_TLSVARIABLEHOIST_H #define LLVM_TRANSFORMS_SCALAR_TLSVARIABLEHOIST_H #include "llvm/ADT/MapVector.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/IR/PassManager.h" namespace llvm { class BasicBlock; class DominatorTree; class Function; class GlobalVariable; class Instruction; /// A private "module" namespace for types and utilities used by /// TLSVariableHoist. These are implementation details and should /// not be used by clients. namespace tlshoist { /// Keeps track of the user of a TLS variable and the operand index /// where the variable is used. struct TLSUser { Instruction *Inst; unsigned OpndIdx; TLSUser(Instruction *Inst, unsigned Idx) : Inst(Inst), OpndIdx(Idx) {} }; /// Keeps track of a TLS variable candidate and its users. struct TLSCandidate { SmallVector<TLSUser, 8> Users; /// Add the user to the use list and update the cost. void addUser(Instruction *Inst, unsigned Idx) { Users.push_back(TLSUser(Inst, Idx)); } }; } // end namespace tlshoist class TLSVariableHoistPass : public PassInfoMixin<TLSVariableHoistPass> { public: PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM); // Glue for old PM. bool runImpl(Function &F, DominatorTree &DT, LoopInfo &LI); private: DominatorTree *DT; LoopInfo *LI; /// Keeps track of TLS variable candidates found in the function. using TLSCandMapType = MapVector<GlobalVariable *, tlshoist::TLSCandidate>; TLSCandMapType TLSCandMap; void collectTLSCandidates(Function &Fn); void collectTLSCandidate(Instruction *Inst); Instruction *getNearestLoopDomInst(BasicBlock *BB, Loop *L); Instruction *getDomInst(Instruction *I1, Instruction *I2); BasicBlock::iterator findInsertPos(Function &Fn, GlobalVariable *GV, BasicBlock *&PosBB); Instruction *genBitCastInst(Function &Fn, GlobalVariable *GV); bool tryReplaceTLSCandidates(Function &Fn); bool tryReplaceTLSCandidate(Function &Fn, GlobalVariable *GV); }; } // end namespace llvm #endif // LLVM_TRANSFORMS_SCALAR_TLSVARIABLEHOIST_H
32.704545
80
0.596942
[ "model" ]
b5111e28bdc056f751691380790683a57f330cd5
890
h
C
include/video/mesh.h
rayment/sticky
ee4f41284477710623bff92a62472c029f1d5990
[ "BSD-3-Clause" ]
null
null
null
include/video/mesh.h
rayment/sticky
ee4f41284477710623bff92a62472c029f1d5990
[ "BSD-3-Clause" ]
null
null
null
include/video/mesh.h
rayment/sticky
ee4f41284477710623bff92a62472c029f1d5990
[ "BSD-3-Clause" ]
null
null
null
/* * mesh.h * GL mesh header. * * Author : Finn Rayment <finn@rayment.fr> * Date created : 11/04/2021 */ #ifndef _FR_RAYMENT_STICKY_MESH_H #define _FR_RAYMENT_STICKY_MESH_H 1 #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #include "common/macros.h" #include "common/types.h" STICKY_PUBLIC ( typedef struct Smesh_s { Suint32 vbo, vao, ebo, normals, uv; Ssize_t vlen, ilen, uvlen; Sbool use_indices; } Smesh; void S_mesh_init(void); void S_mesh_free(void); Smesh *S_mesh_create(Sfloat *, Ssize_t, Suint32 *, Ssize_t, Sfloat *, Ssize_t, Sfloat *, Ssize_t); void S_mesh_draw(Smesh *); void S_mesh_destroy(Smesh *); Smesh *S_mesh_get_cube_mesh(void); Smesh *S_mesh_get_sprite_mesh(void); ) /* STICKY_PUBLIC */ #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* _FR_RAYMENT_STICKY_MESH_H */
17.45098
48
0.666292
[ "mesh" ]
b513f18ddf65634d57bc5c225e27cf3787b3b184
2,440
h
C
AlfrescoSDK/CMIS/ObjectiveCMIS/CMISPagedResult.h
tmughal/alfresco-ios-sdk
ee8010ac55b90bb039370175eaacdc422a68e984
[ "Apache-2.0" ]
10
2015-01-12T16:42:25.000Z
2021-05-25T13:37:51.000Z
AlfrescoSDK/CMIS/ObjectiveCMIS/CMISPagedResult.h
tmughal/alfresco-ios-sdk
ee8010ac55b90bb039370175eaacdc422a68e984
[ "Apache-2.0" ]
10
2015-01-12T16:14:20.000Z
2020-08-05T14:42:35.000Z
AlfrescoSDK/CMIS/ObjectiveCMIS/CMISPagedResult.h
tmughal/alfresco-ios-sdk
ee8010ac55b90bb039370175eaacdc422a68e984
[ "Apache-2.0" ]
12
2015-02-13T07:43:03.000Z
2021-05-25T13:37:53.000Z
/* 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 <Foundation/Foundation.h> /** * Wrapper class for the results of fetching a new page using the block below. */ @interface CMISFetchNextPageBlockResult : NSObject @property (nonatomic, strong) NSArray *resultArray; @property BOOL hasMoreItems; @property int numItems; @end typedef void (^CMISFetchNextPageBlockCompletionBlock)(CMISFetchNextPageBlockResult *result, NSError *error); typedef void (^CMISFetchNextPageBlock)(int skipCount, int maxItems, CMISFetchNextPageBlockCompletionBlock completionBlock); @class CMISObject; /** * The result of executing an operation which has potentially more results than returned in once. */ @interface CMISPagedResult : NSObject @property (nonatomic, strong, readonly) NSArray *resultArray; @property (readonly) BOOL hasMoreItems; @property (readonly) int numItems; /** * completionBlock returns paged results or nil if unsuccessful */ + (void)pagedResultUsingFetchBlock:(CMISFetchNextPageBlock)fetchNextPageBlock limitToMaxItems:(int)maxItems startFromSkipCount:(int)skipCount completionBlock:(void (^)(CMISPagedResult *result, NSError *error))completionBlock; /** * fetches the next page * completionBlock returns paged result or nil if unsuccessful */ - (void)fetchNextPageWithCompletionBlock:(void (^)(CMISPagedResult *result, NSError *error))completionBlock; /** * enumerates through the items in a page * completionBlock returns NSError nil if successful */ - (void)enumerateItemsUsingBlock:(void (^)(id object, BOOL *stop))enumerationBlock completionBlock:(void (^)(NSError *error))completionBlock; @end
35.882353
123
0.760656
[ "object" ]
b52778c8e2f829924523e54b44805a16b31ca2ab
950
h
C
Generators/NDB_RandomizedOldGenerator.h
GrzegorzNieuzyla/Negative-Database-Authentication-System
020ee8f48470349ba3377a6980506e0a8a0ef845
[ "MIT" ]
null
null
null
Generators/NDB_RandomizedOldGenerator.h
GrzegorzNieuzyla/Negative-Database-Authentication-System
020ee8f48470349ba3377a6980506e0a8a0ef845
[ "MIT" ]
null
null
null
Generators/NDB_RandomizedOldGenerator.h
GrzegorzNieuzyla/Negative-Database-Authentication-System
020ee8f48470349ba3377a6980506e0a8a0ef845
[ "MIT" ]
null
null
null
#pragma once #include "NDB_Generator.h" #include "../Utils/RandomValuesGenerator.h" #include <set> class NDB_RandomizedOldGenerator : public NDB_Generator { public: NDB_RandomizedOldGenerator(const std::set<DBRecord>& db, int length); void PrintParameters() const override; FileUtils::CsvFileData GetCsvData() const override; std::size_t Generate(Stream& output) override; static std::string GetName() { return "RandomizedOld"; } private: [[nodiscard]] bool DoesNDBRecordMatchesAny(std::vector<NDBChar> record) const; [[nodiscard]] NDBRecord PatternGenerate(const DBRecord& record) const; static bool Matches(VectorView<NDBChar> ndbRecord, VectorView<bool> dbRecord); static bool Matches(const std::vector<NDBChar>& ndbRecord, const std::vector<bool>& dbRecord, std::vector<int> indices); static bool Matches(const std::vector<NDBChar>& ndbRecord, const std::vector<bool>& dbRecord); };
31.666667
124
0.733684
[ "vector" ]
b528f37b4ce07b6199151e3bd813b8e454f44f9d
2,734
h
C
include/physics/detector.h
JmirY/Playground
39f567842a7c319608fc83932dd4c41604bc246c
[ "MIT" ]
3
2021-06-04T06:38:00.000Z
2021-06-04T06:57:08.000Z
include/physics/detector.h
JmirY/Playground
39f567842a7c319608fc83932dd4c41604bc246c
[ "MIT" ]
null
null
null
include/physics/detector.h
JmirY/Playground
39f567842a7c319608fc83932dd4c41604bc246c
[ "MIT" ]
1
2021-06-04T07:22:22.000Z
2021-06-04T07:22:22.000Z
#ifndef DETECTOR_H #define DETECTOR_H #include "collider.h" #include <vector> #include <unordered_map> namespace physics { class CollisionDetector { friend class Simulator; private: float friction; float objectRestitution; float groundRestitution; public: CollisionDetector() : friction(0.6f), objectRestitution(0.3f), groundRestitution(0.2f) {} /* 충돌을 검출하고 충돌 정보를 contacts 에 저장한다 */ void detectCollision( std::vector<Contact*>& contacts, std::unordered_map<unsigned int, Collider*>& colliders, PlaneCollider& groundCollider ); private: /* 충돌 검사 함수들. 충돌이 있다면 충돌 정보 구조체를 생성하고 contacts 에 푸쉬하고 true 를 반환한다. 총돌이 없다면 false 를 반환한다 */ bool sphereAndBox( std::vector<Contact*>& contacts, const SphereCollider&, const BoxCollider& ); bool sphereAndSphere( std::vector<Contact*>& contacts, const SphereCollider&, const SphereCollider& ); bool sphereAndPlane( std::vector<Contact*>& contacts, const SphereCollider&, const PlaneCollider& ); /* Seperating Axis Theorem 사용 */ bool boxAndBox( std::vector<Contact*>& contacts, const BoxCollider&, const BoxCollider& ); bool boxAndPlane( std::vector<Contact*>& contacts, const BoxCollider&, const PlaneCollider& ); /* 선이 도형을 통과하는지 검사한다 카메라로부터 hit point 까지의 거리를 반환한다 hit 하지 않는다면 음수를 반환한다 */ float rayAndSphere( const Vector3& origin, const Vector3& direction, const SphereCollider& ); float rayAndBox( const Vector3& origin, const Vector3& direction, const BoxCollider& ); private: /* 두 박스가 주어진 축에 대해 어느정도 겹치는지 반환한다 */ float calcPenetration( const BoxCollider& box1, const BoxCollider& box2, const Vector3& axis ); /* 직육면체의 면-점 접촉일 때 충돌점을 찾는다 */ void calcContactPointOnPlane( const BoxCollider& box1, const BoxCollider& box2, int minPenetrationAxisIdx, Contact* contact ); /* 직육면체의 선-선 접촉일 때 충돌점을 찾는다 */ void calcContactPointOnLine( const BoxCollider& box1, const BoxCollider& box2, int minPenetrationAxisIdx, Contact* contact ); }; } // namespace physics #endif // DETECTOR_H
26.543689
81
0.536211
[ "vector" ]
b5460ee5877f459d32b4fa1b2108fc9fb015358e
2,243
h
C
internal/SceneOCL.h
MrApfel1994/Ray
31ae807ee6a0406c30c08fa0d38b3a44224f86b6
[ "WTFPL" ]
60
2018-10-24T08:31:22.000Z
2019-04-28T20:14:04.000Z
internal/SceneOCL.h
MrApfel1994/Ray
31ae807ee6a0406c30c08fa0d38b3a44224f86b6
[ "WTFPL" ]
1
2018-12-17T16:18:00.000Z
2018-12-18T15:32:52.000Z
internal/SceneOCL.h
MrApfel1994/Ray
31ae807ee6a0406c30c08fa0d38b3a44224f86b6
[ "WTFPL" ]
5
2020-01-22T08:54:00.000Z
2021-11-21T16:23:46.000Z
#pragma once #include "TextureAtlasOCL.h" #include "VectorOCL.h" #include "../SceneBase.h" namespace Ray { namespace Ocl { class Renderer; class Scene : public SceneBase { protected: friend class Ocl::Renderer; const cl::Context &context_; const cl::CommandQueue &queue_; size_t max_img_buf_size_; Ocl::Vector<bvh_node_t> nodes_; Ocl::Vector<tri_accel_t> tris_; Ocl::Vector<uint32_t> tri_indices_; Ocl::Vector<transform_t> transforms_; Ocl::Vector<mesh_t> meshes_; Ocl::Vector<mesh_instance_t> mesh_instances_; Ocl::Vector<uint32_t> mi_indices_; Ocl::Vector<vertex_t> vertices_; Ocl::Vector<uint32_t> vtx_indices_; Ocl::Vector<material_t> materials_; Ocl::Vector<texture_t> textures_; Ocl::TextureAtlas texture_atlas_; Ocl::Vector<light_t> lights_; Ocl::Vector<uint32_t> li_indices_; Ocl::environment_t env_; uint32_t macro_nodes_start_ = 0xffffffff, macro_nodes_count_ = 0; uint32_t light_nodes_start_ = 0xffffffff, light_nodes_count_ = 0; uint32_t default_env_texture_; uint32_t default_normals_texture_; void RemoveNodes(uint32_t node_index, uint32_t node_count); void RebuildMacroBVH(); void RebuildLightBVH(); public: Scene(const cl::Context &context, const cl::CommandQueue &queue, size_t max_img_buffer_size); void GetEnvironment(environment_desc_t &env) override; void SetEnvironment(const environment_desc_t &env) override; uint32_t AddTexture(const tex_desc_t &t) override; void RemoveTexture(uint32_t) override {} uint32_t AddMaterial(const mat_desc_t &m) override; void RemoveMaterial(uint32_t) override {} uint32_t AddMesh(const mesh_desc_t &m) override; void RemoveMesh(uint32_t) override; uint32_t AddLight(const light_desc_t &l) override; void RemoveLight(uint32_t i) override; uint32_t AddMeshInstance(uint32_t m_index, const float *xform) override; void SetMeshInstanceTransform(uint32_t mi_index, const float *xform) override; void RemoveMeshInstance(uint32_t) override; uint32_t triangle_count() override { return (uint32_t)tris_.size(); } uint32_t node_count() override { return (uint32_t)nodes_.size(); } }; } }
29.12987
97
0.732947
[ "vector" ]
b5473b35482f22b5f52b530bf4a8cb2de1d28d7d
470,715
c
C
PyMaSC/core/readlen_2.c
ronin-gw/PyMaSC
70c32b647017e162e0b004cadcf4f59a2d4012b6
[ "MIT" ]
2
2018-04-20T13:34:16.000Z
2021-07-13T16:20:28.000Z
PyMaSC/core/readlen_2.c
ronin-gw/PyMaSC
70c32b647017e162e0b004cadcf4f59a2d4012b6
[ "MIT" ]
1
2021-03-16T11:08:46.000Z
2021-03-16T17:26:15.000Z
PyMaSC/core/readlen_2.c
ronin-gw/PyMaSC
70c32b647017e162e0b004cadcf4f59a2d4012b6
[ "MIT" ]
null
null
null
/* Generated by Cython 0.29.2 */ /* BEGIN: Cython Metadata { "distutils": { "depends": [ "/usr/local/lib/python2.7/site-packages/pysam/htslib_util.h", "/usr/local/lib/python2.7/site-packages/pysam/include/htslib/htslib/bgzf.h", "/usr/local/lib/python2.7/site-packages/pysam/include/htslib/htslib/cram.h", "/usr/local/lib/python2.7/site-packages/pysam/include/htslib/htslib/faidx.h", "/usr/local/lib/python2.7/site-packages/pysam/include/htslib/htslib/hfile.h", "/usr/local/lib/python2.7/site-packages/pysam/include/htslib/htslib/hts.h", "/usr/local/lib/python2.7/site-packages/pysam/include/htslib/htslib/kstring.h", "/usr/local/lib/python2.7/site-packages/pysam/include/htslib/htslib/sam.h", "/usr/local/lib/python2.7/site-packages/pysam/include/htslib/htslib/tbx.h", "/usr/local/lib/python2.7/site-packages/pysam/include/htslib/htslib/vcf.h", "/usr/local/lib/python2.7/site-packages/pysam/include/htslib/htslib/vcfutils.h", "/usr/local/lib/python2.7/site-packages/pysam/pysam_stream.h" ], "extra_compile_args": [ "-O3", "-ffast-math" ], "include_dirs": [ "/usr/local/lib/python2.7/site-packages/pysam", "/usr/local/lib/python2.7/site-packages/pysam/include/htslib" ], "name": "PyMaSC.core.readlen", "sources": [ "/PyMaSC/PyMaSC/core/readlen.pyx" ] }, "module_name": "PyMaSC.core.readlen" } END: Cython Metadata */ #define PY_SSIZE_T_CLEAN #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. #elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03030000) #error Cython requires Python 2.6+ or Python 3.3+. #else #define CYTHON_ABI "0_29_2" #define CYTHON_HEX_VERSION 0x001D02F0 #define CYTHON_FUTURE_DIVISION 0 #include <stddef.h> #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall #endif #ifndef __cdecl #define __cdecl #endif #ifndef __fastcall #define __fastcall #endif #endif #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif #define __PYX_COMMA , #ifndef HAVE_LONG_LONG #if PY_VERSION_HEX >= 0x02070000 #define HAVE_LONG_LONG #endif #endif #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif #ifndef Py_HUGE_VAL #define Py_HUGE_VAL HUGE_VAL #endif #ifdef PYPY_VERSION #define CYTHON_COMPILING_IN_PYPY 1 #define CYTHON_COMPILING_IN_PYSTON 0 #define CYTHON_COMPILING_IN_CPYTHON 0 #undef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 0 #undef CYTHON_USE_PYTYPE_LOOKUP #define CYTHON_USE_PYTYPE_LOOKUP 0 #if PY_VERSION_HEX < 0x03050000 #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #elif !defined(CYTHON_USE_ASYNC_SLOTS) #define CYTHON_USE_ASYNC_SLOTS 1 #endif #undef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 0 #undef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 0 #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #undef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 1 #undef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 0 #undef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 0 #undef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 0 #undef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 0 #undef CYTHON_PEP489_MULTI_PHASE_INIT #define CYTHON_PEP489_MULTI_PHASE_INIT 0 #undef CYTHON_USE_TP_FINALIZE #define CYTHON_USE_TP_FINALIZE 0 #undef CYTHON_USE_DICT_VERSIONS #define CYTHON_USE_DICT_VERSIONS 0 #undef CYTHON_USE_EXC_INFO_STACK #define CYTHON_USE_EXC_INFO_STACK 0 #elif defined(PYSTON_VERSION) #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_PYSTON 1 #define CYTHON_COMPILING_IN_CPYTHON 0 #ifndef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 1 #endif #undef CYTHON_USE_PYTYPE_LOOKUP #define CYTHON_USE_PYTYPE_LOOKUP 0 #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #undef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 0 #ifndef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 1 #endif #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #ifndef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 0 #endif #ifndef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 1 #endif #ifndef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 1 #endif #undef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 0 #undef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 0 #undef CYTHON_PEP489_MULTI_PHASE_INIT #define CYTHON_PEP489_MULTI_PHASE_INIT 0 #undef CYTHON_USE_TP_FINALIZE #define CYTHON_USE_TP_FINALIZE 0 #undef CYTHON_USE_DICT_VERSIONS #define CYTHON_USE_DICT_VERSIONS 0 #undef CYTHON_USE_EXC_INFO_STACK #define CYTHON_USE_EXC_INFO_STACK 0 #else #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_PYSTON 0 #define CYTHON_COMPILING_IN_CPYTHON 1 #ifndef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 1 #endif #if PY_VERSION_HEX < 0x02070000 #undef CYTHON_USE_PYTYPE_LOOKUP #define CYTHON_USE_PYTYPE_LOOKUP 0 #elif !defined(CYTHON_USE_PYTYPE_LOOKUP) #define CYTHON_USE_PYTYPE_LOOKUP 1 #endif #if PY_MAJOR_VERSION < 3 #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #elif !defined(CYTHON_USE_ASYNC_SLOTS) #define CYTHON_USE_ASYNC_SLOTS 1 #endif #if PY_VERSION_HEX < 0x02070000 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #elif !defined(CYTHON_USE_PYLONG_INTERNALS) #define CYTHON_USE_PYLONG_INTERNALS 1 #endif #ifndef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 1 #endif #ifndef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 1 #endif #if PY_VERSION_HEX < 0x030300F0 #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #elif !defined(CYTHON_USE_UNICODE_WRITER) #define CYTHON_USE_UNICODE_WRITER 1 #endif #ifndef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 0 #endif #ifndef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 1 #endif #ifndef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 1 #endif #ifndef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 1 #endif #ifndef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 1 #endif #ifndef CYTHON_PEP489_MULTI_PHASE_INIT #define CYTHON_PEP489_MULTI_PHASE_INIT (PY_VERSION_HEX >= 0x03050000) #endif #ifndef CYTHON_USE_TP_FINALIZE #define CYTHON_USE_TP_FINALIZE (PY_VERSION_HEX >= 0x030400a1) #endif #ifndef CYTHON_USE_DICT_VERSIONS #define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX >= 0x030600B1) #endif #ifndef CYTHON_USE_EXC_INFO_STACK #define CYTHON_USE_EXC_INFO_STACK (PY_VERSION_HEX >= 0x030700A3) #endif #endif #if !defined(CYTHON_FAST_PYCCALL) #define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1) #endif #if CYTHON_USE_PYLONG_INTERNALS #include "longintrepr.h" #undef SHIFT #undef BASE #undef MASK #ifdef SIZEOF_VOID_P enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) }; #endif #endif #ifndef __has_attribute #define __has_attribute(x) 0 #endif #ifndef __has_cpp_attribute #define __has_cpp_attribute(x) 0 #endif #ifndef CYTHON_RESTRICT #if defined(__GNUC__) #define CYTHON_RESTRICT __restrict__ #elif defined(_MSC_VER) && _MSC_VER >= 1400 #define CYTHON_RESTRICT __restrict #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define CYTHON_RESTRICT restrict #else #define CYTHON_RESTRICT #endif #endif #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif # elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif #endif #ifndef CYTHON_MAYBE_UNUSED_VAR # if defined(__cplusplus) template<class T> void CYTHON_MAYBE_UNUSED_VAR( const T& ) { } # else # define CYTHON_MAYBE_UNUSED_VAR(x) (void)(x) # endif #endif #ifndef CYTHON_NCP_UNUSED # if CYTHON_COMPILING_IN_CPYTHON # define CYTHON_NCP_UNUSED # else # define CYTHON_NCP_UNUSED CYTHON_UNUSED # endif #endif #define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) #ifdef _MSC_VER #ifndef _MSC_STDINT_H_ #if _MSC_VER < 1300 typedef unsigned char uint8_t; typedef unsigned int uint32_t; #else typedef unsigned __int8 uint8_t; typedef unsigned __int32 uint32_t; #endif #endif #else #include <stdint.h> #endif #ifndef CYTHON_FALLTHROUGH #if defined(__cplusplus) && __cplusplus >= 201103L #if __has_cpp_attribute(fallthrough) #define CYTHON_FALLTHROUGH [[fallthrough]] #elif __has_cpp_attribute(clang::fallthrough) #define CYTHON_FALLTHROUGH [[clang::fallthrough]] #elif __has_cpp_attribute(gnu::fallthrough) #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] #endif #endif #ifndef CYTHON_FALLTHROUGH #if __has_attribute(fallthrough) #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) #else #define CYTHON_FALLTHROUGH #endif #endif #if defined(__clang__ ) && defined(__apple_build_version__) #if __apple_build_version__ < 7000000 #undef CYTHON_FALLTHROUGH #define CYTHON_FALLTHROUGH #endif #endif #endif #ifndef CYTHON_INLINE #if defined(__clang__) #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) #elif defined(__GNUC__) #define CYTHON_INLINE __inline__ #elif defined(_MSC_VER) #define CYTHON_INLINE __inline #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define CYTHON_INLINE inline #else #define CYTHON_INLINE #endif #endif #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag) #define Py_OptimizeFlag 0 #endif #define __PYX_BUILD_PY_SSIZE_T "n" #define CYTHON_FORMAT_SSIZE_T "z" #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #define __Pyx_DefaultClassType PyClass_Type #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #define __Pyx_DefaultClassType PyType_Type #endif #ifndef Py_TPFLAGS_CHECKTYPES #define Py_TPFLAGS_CHECKTYPES 0 #endif #ifndef Py_TPFLAGS_HAVE_INDEX #define Py_TPFLAGS_HAVE_INDEX 0 #endif #ifndef Py_TPFLAGS_HAVE_NEWBUFFER #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif #ifndef Py_TPFLAGS_HAVE_FINALIZE #define Py_TPFLAGS_HAVE_FINALIZE 0 #endif #ifndef METH_STACKLESS #define METH_STACKLESS 0 #endif #if PY_VERSION_HEX <= 0x030700A3 || !defined(METH_FASTCALL) #ifndef METH_FASTCALL #define METH_FASTCALL 0x80 #endif typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs); typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames); #else #define __Pyx_PyCFunctionFast _PyCFunctionFast #define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords #endif #if CYTHON_FAST_PYCCALL #define __Pyx_PyFastCFunction_Check(func)\ ((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))))) #else #define __Pyx_PyFastCFunction_Check(func) 0 #endif #if CYTHON_USE_DICT_VERSIONS #define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag) #define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\ (version_var) = __PYX_GET_DICT_VERSION(dict);\ (cache_var) = (value); #define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\ static PY_UINT64_T __pyx_dict_version = 0;\ static PyObject *__pyx_dict_cached_value = NULL;\ if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\ (VAR) = __pyx_dict_cached_value;\ } else {\ (VAR) = __pyx_dict_cached_value = (LOOKUP);\ __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\ }\ } #else #define __PYX_GET_DICT_VERSION(dict) (0) #define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var) #define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP); #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) #define PyObject_Malloc(s) PyMem_Malloc(s) #define PyObject_Free(p) PyMem_Free(p) #define PyObject_Realloc(p) PyMem_Realloc(p) #endif #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030400A1 #define PyMem_RawMalloc(n) PyMem_Malloc(n) #define PyMem_RawRealloc(p, n) PyMem_Realloc(p, n) #define PyMem_RawFree(p) PyMem_Free(p) #endif #if CYTHON_COMPILING_IN_PYSTON #define __Pyx_PyCode_HasFreeVars(co) PyCode_HasFreeVars(co) #define __Pyx_PyFrame_SetLineNumber(frame, lineno) PyFrame_SetLineNumber(frame, lineno) #else #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) #endif #if !CYTHON_FAST_THREAD_STATE || PY_VERSION_HEX < 0x02070000 #define __Pyx_PyThreadState_Current PyThreadState_GET() #elif PY_VERSION_HEX >= 0x03060000 #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() #elif PY_VERSION_HEX >= 0x03000000 #define __Pyx_PyThreadState_Current PyThreadState_GET() #else #define __Pyx_PyThreadState_Current _PyThreadState_Current #endif #if PY_VERSION_HEX < 0x030700A2 && !defined(PyThread_tss_create) && !defined(Py_tss_NEEDS_INIT) #include "pythread.h" #define Py_tss_NEEDS_INIT 0 typedef int Py_tss_t; static CYTHON_INLINE int PyThread_tss_create(Py_tss_t *key) { *key = PyThread_create_key(); return 0; // PyThread_create_key reports success always } static CYTHON_INLINE Py_tss_t * PyThread_tss_alloc(void) { Py_tss_t *key = (Py_tss_t *)PyObject_Malloc(sizeof(Py_tss_t)); *key = Py_tss_NEEDS_INIT; return key; } static CYTHON_INLINE void PyThread_tss_free(Py_tss_t *key) { PyObject_Free(key); } static CYTHON_INLINE int PyThread_tss_is_created(Py_tss_t *key) { return *key != Py_tss_NEEDS_INIT; } static CYTHON_INLINE void PyThread_tss_delete(Py_tss_t *key) { PyThread_delete_key(*key); *key = Py_tss_NEEDS_INIT; } static CYTHON_INLINE int PyThread_tss_set(Py_tss_t *key, void *value) { return PyThread_set_key_value(*key, value); } static CYTHON_INLINE void * PyThread_tss_get(Py_tss_t *key) { return PyThread_get_key_value(*key); } #endif // TSS (Thread Specific Storage) API #if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized) #define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) #else #define __Pyx_PyDict_NewPresized(n) PyDict_New() #endif #if PY_MAJOR_VERSION >= 3 || CYTHON_FUTURE_DIVISION #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) #else #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) #endif #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 && CYTHON_USE_UNICODE_INTERNALS #define __Pyx_PyDict_GetItemStr(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash) #else #define __Pyx_PyDict_GetItemStr(dict, name) PyDict_GetItem(dict, name) #endif #if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) #define CYTHON_PEP393_ENABLED 1 #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ 0 : _PyUnicode_Ready((PyObject *)(op))) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, ch) #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) #else #define CYTHON_PEP393_ENABLED 0 #define PyUnicode_1BYTE_KIND 1 #define PyUnicode_2BYTE_KIND 2 #define PyUnicode_4BYTE_KIND 4 #define __Pyx_PyUnicode_READY(op) (0) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111) #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) #define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = ch) #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u)) #endif #if CYTHON_COMPILING_IN_PYPY #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) #else #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains) #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check) #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format) #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) #endif #define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyString_Check(b) && !PyString_CheckExact(b)))) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) #define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) #else #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) #endif #if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII) #define PyObject_ASCII(o) PyObject_Repr(o) #endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject #define PyString_Type PyUnicode_Type #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #define PyObject_Unicode PyObject_Str #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) #else #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) #endif #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif #if CYTHON_ASSUME_SAFE_MACROS #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq) #else #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) #endif #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type #define PyInt_Check(op) PyLong_Check(op) #define PyInt_CheckExact(op) PyLong_CheckExact(op) #define PyInt_FromString PyLong_FromString #define PyInt_FromUnicode PyLong_FromUnicode #define PyInt_FromLong PyLong_FromLong #define PyInt_FromSize_t PyLong_FromSize_t #define PyInt_FromSsize_t PyLong_FromSsize_t #define PyInt_AsLong PyLong_AsLong #define PyInt_AS_LONG PyLong_AS_LONG #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask #define PyNumber_Int PyNumber_Long #endif #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif #if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY #ifndef PyUnicode_InternFromString #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) #endif #endif #if PY_VERSION_HEX < 0x030200A4 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong #define __Pyx_PyInt_AsHash_t PyInt_AsLong #else #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : (Py_INCREF(func), func)) #else #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) #endif #if CYTHON_USE_ASYNC_SLOTS #if PY_VERSION_HEX >= 0x030500B1 #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods #define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async) #else #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved)) #endif #else #define __Pyx_PyType_AsAsync(obj) NULL #endif #ifndef __Pyx_PyAsyncMethodsStruct typedef struct { unaryfunc am_await; unaryfunc am_aiter; unaryfunc am_anext; } __Pyx_PyAsyncMethodsStruct; #endif #if defined(WIN32) || defined(MS_WINDOWS) #define _USE_MATH_DEFINES #endif #include <math.h> #ifdef NAN #define __PYX_NAN() ((float) NAN) #else static CYTHON_INLINE float __PYX_NAN() { float value; memset(&value, 0xFF, sizeof(value)); return value; } #endif #if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) #define __Pyx_truncl trunc #else #define __Pyx_truncl truncl #endif #define __PYX_ERR(f_index, lineno, Ln_error) \ { \ __pyx_filename = __pyx_f[f_index]; __pyx_lineno = lineno; __pyx_clineno = __LINE__; goto Ln_error; \ } #ifndef __PYX_EXTERN_C #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" #else #define __PYX_EXTERN_C extern #endif #endif #define __PYX_HAVE__PyMaSC__core__readlen #define __PYX_HAVE_API__PyMaSC__core__readlen /* Early includes */ #include <stdint.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include "pythread.h" #include <sys/types.h> #include "stdarg.h" #include "htslib/kstring.h" #include "htslib_util.h" #include "htslib/hfile.h" #include "htslib/bgzf.h" #include "htslib/hts.h" #include "htslib/sam.h" #include "htslib/faidx.h" #include "htslib/tbx.h" #include "htslib/vcf.h" #include "htslib/vcfutils.h" #include "htslib/cram.h" #include "pysam_stream.h" #ifdef _OPENMP #include <omp.h> #endif /* _OPENMP */ #if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) #define CYTHON_WITHOUT_ASSERTIONS #endif typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; #define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 #define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 #define __PYX_DEFAULT_STRING_ENCODING "" #define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString #define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #define __Pyx_uchar_cast(c) ((unsigned char)c) #define __Pyx_long_cast(x) ((long)x) #define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ (sizeof(type) < sizeof(Py_ssize_t)) ||\ (sizeof(type) > sizeof(Py_ssize_t) &&\ likely(v < (type)PY_SSIZE_T_MAX ||\ v == (type)PY_SSIZE_T_MAX) &&\ (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ v == (type)PY_SSIZE_T_MIN))) ||\ (sizeof(type) == sizeof(Py_ssize_t) &&\ (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ v == (type)PY_SSIZE_T_MAX))) ) static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { return (size_t) i < (size_t) limit; } #if defined (__cplusplus) && __cplusplus >= 201103L #include <cstdlib> #define __Pyx_sst_abs(value) std::abs(value) #elif SIZEOF_INT >= SIZEOF_SIZE_T #define __Pyx_sst_abs(value) abs(value) #elif SIZEOF_LONG >= SIZEOF_SIZE_T #define __Pyx_sst_abs(value) labs(value) #elif defined (_MSC_VER) #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define __Pyx_sst_abs(value) llabs(value) #elif defined (__GNUC__) #define __Pyx_sst_abs(value) __builtin_llabs(value) #else #define __Pyx_sst_abs(value) ((value<0) ? -value : value) #endif static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); #define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) #define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) #define __Pyx_PyBytes_FromString PyBytes_FromString #define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); #if PY_MAJOR_VERSION < 3 #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #else #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize #endif #define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) #define __Pyx_PyObject_AsWritableString(s) ((char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsWritableSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) #define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) #define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) #define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) #define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) { const Py_UNICODE *u_end = u; while (*u_end++) ; return (size_t)(u_end - u - 1); } #define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) #define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode #define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) #define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x); #define __Pyx_PySequence_Tuple(obj)\ (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); #if CYTHON_ASSUME_SAFE_MACROS #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) #else #define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) #endif #define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) #else #define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x)) #endif #define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(x)) #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII static int __Pyx_sys_getdefaultencoding_not_ascii; static int __Pyx_init_sys_getdefaultencoding_params(void) { PyObject* sys; PyObject* default_encoding = NULL; PyObject* ascii_chars_u = NULL; PyObject* ascii_chars_b = NULL; const char* default_encoding_c; sys = PyImport_ImportModule("sys"); if (!sys) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); Py_DECREF(sys); if (!default_encoding) goto bad; default_encoding_c = PyBytes_AsString(default_encoding); if (!default_encoding_c) goto bad; if (strcmp(default_encoding_c, "ascii") == 0) { __Pyx_sys_getdefaultencoding_not_ascii = 0; } else { char ascii_chars[128]; int c; for (c = 0; c < 128; c++) { ascii_chars[c] = c; } __Pyx_sys_getdefaultencoding_not_ascii = 1; ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); if (!ascii_chars_u) goto bad; ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { PyErr_Format( PyExc_ValueError, "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", default_encoding_c); goto bad; } Py_DECREF(ascii_chars_u); Py_DECREF(ascii_chars_b); } Py_DECREF(default_encoding); return 0; bad: Py_XDECREF(default_encoding); Py_XDECREF(ascii_chars_u); Py_XDECREF(ascii_chars_b); return -1; } #endif #if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) #else #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) #if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT static char* __PYX_DEFAULT_STRING_ENCODING; static int __Pyx_init_sys_getdefaultencoding_params(void) { PyObject* sys; PyObject* default_encoding = NULL; char* default_encoding_c; sys = PyImport_ImportModule("sys"); if (!sys) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); Py_DECREF(sys); if (!default_encoding) goto bad; default_encoding_c = PyBytes_AsString(default_encoding); if (!default_encoding_c) goto bad; __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c) + 1); if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); Py_DECREF(default_encoding); return 0; bad: Py_XDECREF(default_encoding); return -1; } #endif #endif /* Test for GCC > 2.95 */ #if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #else /* !__GNUC__ or GCC < 2.95 */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } static PyObject *__pyx_m = NULL; static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_cython_runtime = NULL; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; static PyObject *__pyx_empty_unicode; static int __pyx_lineno; static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; static const char *__pyx_f[] = { "PyMaSC/core/readlen.pyx", "array.pxd", "type.pxd", "bool.pxd", "complex.pxd", "libchtslib.pxd", "libcfaidx.pxd", "libcalignedsegment.pxd", "libcalignmentfile.pxd", }; /*--- Type declarations ---*/ #ifndef _ARRAYARRAY_H struct arrayobject; typedef struct arrayobject arrayobject; #endif struct __pyx_obj_5pysam_10libchtslib_HTSFile; struct __pyx_obj_5pysam_9libcfaidx_FastaFile; struct __pyx_obj_5pysam_9libcfaidx_FastqProxy; struct __pyx_obj_5pysam_9libcfaidx_FastxRecord; struct __pyx_obj_5pysam_9libcfaidx_FastxFile; struct __pyx_obj_5pysam_9libcfaidx_FastqFile; struct __pyx_obj_5pysam_9libcfaidx_Fastafile; struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment; struct __pyx_obj_5pysam_18libcalignedsegment_PileupColumn; struct __pyx_obj_5pysam_18libcalignedsegment_PileupRead; struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader; struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile; struct __pyx_obj_5pysam_17libcalignmentfile_PileupColumn; struct __pyx_obj_5pysam_17libcalignmentfile_PileupRead; struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow; struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion; struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead; struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll; struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs; struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection; struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn; struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnRegion; struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAllRefs; struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads; struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct___mean; struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr; struct __pyx_opt_args_5pysam_9libcfaidx_10FastqProxy_get_quality_array; struct __pyx_opt_args_5pysam_9libcfaidx_11FastxRecord_get_quality_array; /* "pysam/libcfaidx.pxd":49 * cdef cython.str to_string(self) * cdef cython.str tostring(self) * cpdef array.array get_quality_array(self, int offset=*) # <<<<<<<<<<<<<< * * */ struct __pyx_opt_args_5pysam_9libcfaidx_10FastqProxy_get_quality_array { int __pyx_n; int offset; }; /* "pysam/libcfaidx.pxd":59 * cdef cython.str to_string(self) * cdef cython.str tostring(self) * cpdef array.array get_quality_array(self, int offset=*) # <<<<<<<<<<<<<< * * cdef class FastxFile: */ struct __pyx_opt_args_5pysam_9libcfaidx_11FastxRecord_get_quality_array { int __pyx_n; int offset; }; struct __pyx_opt_args_5pysam_18libcalignedsegment_14AlignedSegment_set_tag; struct __pyx_opt_args_5pysam_18libcalignedsegment_14AlignedSegment_get_tag; struct __pyx_opt_args_5pysam_18libcalignedsegment_14AlignedSegment_tostring; /* "pysam/libcalignedsegment.pxd":30 * * from pysam.libcalignmentfile cimport AlignmentFile, AlignmentHeader * ctypedef AlignmentFile AlignmentFile_t # <<<<<<<<<<<<<< * * */ typedef struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_t_5pysam_18libcalignedsegment_AlignmentFile_t; /* "pysam/libcalignedsegment.pxd":50 * # add an alignment tag with value to the AlignedSegment * # an existing tag of the same name will be replaced. * cpdef set_tag(self, tag, value, value_type=?, replace=?) # <<<<<<<<<<<<<< * * # add an alignment tag with value to the AlignedSegment */ struct __pyx_opt_args_5pysam_18libcalignedsegment_14AlignedSegment_set_tag { int __pyx_n; PyObject *value_type; PyObject *replace; }; /* "pysam/libcalignedsegment.pxd":54 * # add an alignment tag with value to the AlignedSegment * # an existing tag of the same name will be replaced. * cpdef get_tag(self, tag, with_value_type=?) # <<<<<<<<<<<<<< * * # return true if tag exists */ struct __pyx_opt_args_5pysam_18libcalignedsegment_14AlignedSegment_get_tag { int __pyx_n; PyObject *with_value_type; }; /* "pysam/libcalignedsegment.pxd":63 * * # returns a valid sam alignment string (deprecated) * cpdef tostring(self, htsfile=*) # <<<<<<<<<<<<<< * * */ struct __pyx_opt_args_5pysam_18libcalignedsegment_14AlignedSegment_tostring { int __pyx_n; PyObject *htsfile; }; struct __pyx_t_5pysam_17libcalignmentfile___iterdata; typedef struct __pyx_t_5pysam_17libcalignmentfile___iterdata __pyx_t_5pysam_17libcalignmentfile___iterdata; struct __pyx_opt_args_5pysam_17libcalignmentfile_14IteratorColumn__setup_iterator; /* "pysam/libcalignmentfile.pxd":24 * # Utility types * * ctypedef struct __iterdata: # <<<<<<<<<<<<<< * htsFile * htsfile * bam_hdr_t * header */ struct __pyx_t_5pysam_17libcalignmentfile___iterdata { htsFile *htsfile; bam_hdr_t *header; hts_itr_t *iter; faidx_t *fastafile; int tid; char *seq; int seq_len; int min_mapping_quality; int flag_require; int flag_filter; int compute_baq; int redo_baq; int ignore_orphans; int adjust_capq_threshold; }; /* "pysam/libcalignmentfile.pxd":138 * cdef int cnext(self) * cdef char * get_sequence(self) * cdef _setup_iterator(self, # <<<<<<<<<<<<<< * int tid, * int start, */ struct __pyx_opt_args_5pysam_17libcalignmentfile_14IteratorColumn__setup_iterator { int __pyx_n; int multiple_iterators; }; /* "pysam/libchtslib.pxd":2590 * * * cdef class HTSFile(object): # <<<<<<<<<<<<<< * cdef htsFile *htsfile # pointer to htsFile structure * cdef int64_t start_offset # BGZF offset of first record */ struct __pyx_obj_5pysam_10libchtslib_HTSFile { PyObject_HEAD struct __pyx_vtabstruct_5pysam_10libchtslib_HTSFile *__pyx_vtab; htsFile *htsfile; int64_t start_offset; PyObject *filename; PyObject *mode; PyObject *threads; PyObject *index_filename; int is_stream; int is_remote; int duplicate_filehandle; }; /* "pysam/libcfaidx.pxd":37 * int * dret) * * cdef class FastaFile: # <<<<<<<<<<<<<< * cdef bint is_remote * cdef object _filename, _references, _lengths, reference2length */ struct __pyx_obj_5pysam_9libcfaidx_FastaFile { PyObject_HEAD struct __pyx_vtabstruct_5pysam_9libcfaidx_FastaFile *__pyx_vtab; int is_remote; PyObject *_filename; PyObject *_references; PyObject *_lengths; PyObject *reference2length; faidx_t *fastafile; }; /* "pysam/libcfaidx.pxd":45 * * * cdef class FastqProxy: # <<<<<<<<<<<<<< * cdef kseq_t * _delegate * cdef cython.str to_string(self) */ struct __pyx_obj_5pysam_9libcfaidx_FastqProxy { PyObject_HEAD struct __pyx_vtabstruct_5pysam_9libcfaidx_FastqProxy *__pyx_vtab; kseq_t *_delegate; }; /* "pysam/libcfaidx.pxd":52 * * * cdef class FastxRecord: # <<<<<<<<<<<<<< * """ * Python container for pysam.libcfaidx.FastqProxy with persistence. */ struct __pyx_obj_5pysam_9libcfaidx_FastxRecord { PyObject_HEAD struct __pyx_vtabstruct_5pysam_9libcfaidx_FastxRecord *__pyx_vtab; PyObject *comment; PyObject *quality; PyObject *sequence; PyObject *name; }; /* "pysam/libcfaidx.pxd":61 * cpdef array.array get_quality_array(self, int offset=*) * * cdef class FastxFile: # <<<<<<<<<<<<<< * cdef object _filename * cdef BGZF * fastqfile */ struct __pyx_obj_5pysam_9libcfaidx_FastxFile { PyObject_HEAD struct __pyx_vtabstruct_5pysam_9libcfaidx_FastxFile *__pyx_vtab; PyObject *_filename; BGZF *fastqfile; kseq_t *entry; int persist; int is_remote; }; /* "pysam/libcfaidx.pxd":73 * * # Compatibility Layer for pysam 0.8.1 * cdef class FastqFile(FastxFile): # <<<<<<<<<<<<<< * pass * */ struct __pyx_obj_5pysam_9libcfaidx_FastqFile { struct __pyx_obj_5pysam_9libcfaidx_FastxFile __pyx_base; }; /* "pysam/libcfaidx.pxd":78 * * # Compatibility Layer for pysam < 0.8 * cdef class Fastafile(FastaFile): # <<<<<<<<<<<<<< * pass * */ struct __pyx_obj_5pysam_9libcfaidx_Fastafile { struct __pyx_obj_5pysam_9libcfaidx_FastaFile __pyx_base; }; /* "pysam/libcalignedsegment.pxd":34 * * # Note: need to declare all C fields and methods here * cdef class AlignedSegment: # <<<<<<<<<<<<<< * * # object that this AlignedSegment represents */ struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment { PyObject_HEAD struct __pyx_vtabstruct_5pysam_18libcalignedsegment_AlignedSegment *__pyx_vtab; bam1_t *_delegate; struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *header; PyObject *cache_query_qualities; PyObject *cache_query_alignment_qualities; PyObject *cache_query_sequence; PyObject *cache_query_alignment_sequence; }; /* "pysam/libcalignedsegment.pxd":66 * * * cdef class PileupColumn: # <<<<<<<<<<<<<< * cdef bam_pileup1_t ** plp * cdef int tid */ struct __pyx_obj_5pysam_18libcalignedsegment_PileupColumn { PyObject_HEAD bam_pileup1_t **plp; int tid; int pos; int n_pu; struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *header; uint32_t min_base_quality; uint8_t *buf; char *reference_sequence; }; /* "pysam/libcalignedsegment.pxd":76 * cdef char * reference_sequence * * cdef class PileupRead: # <<<<<<<<<<<<<< * cdef int32_t _qpos * cdef AlignedSegment _alignment */ struct __pyx_obj_5pysam_18libcalignedsegment_PileupRead { PyObject_HEAD int32_t _qpos; struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *_alignment; int _indel; int _level; uint32_t _is_del; uint32_t _is_head; uint32_t _is_tail; uint32_t _is_refskip; }; /* "pysam/libcalignmentfile.pxd":41 * * * cdef class AlignmentHeader(object): # <<<<<<<<<<<<<< * cdef bam_hdr_t *ptr * */ struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader { PyObject_HEAD bam_hdr_t *ptr; }; /* "pysam/libcalignmentfile.pxd":44 * cdef bam_hdr_t *ptr * * cdef class AlignmentFile(HTSFile): # <<<<<<<<<<<<<< * cdef readonly object reference_filename * cdef readonly AlignmentHeader header */ struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile { struct __pyx_obj_5pysam_10libchtslib_HTSFile __pyx_base; PyObject *reference_filename; struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *header; hts_idx_t *index; bam1_t *b; }; /* "pysam/libcalignmentfile.pxd":61 * * * cdef class PileupColumn: # <<<<<<<<<<<<<< * cdef bam_pileup1_t ** plp * cdef int tid */ struct __pyx_obj_5pysam_17libcalignmentfile_PileupColumn { PyObject_HEAD bam_pileup1_t **plp; int tid; int pos; int n_pu; }; /* "pysam/libcalignmentfile.pxd":68 * * * cdef class PileupRead: # <<<<<<<<<<<<<< * cdef AlignedSegment _alignment * cdef int32_t _qpos */ struct __pyx_obj_5pysam_17libcalignmentfile_PileupRead { PyObject_HEAD struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *_alignment; int32_t _qpos; int _indel; int _level; uint32_t _is_del; uint32_t _is_head; uint32_t _is_tail; uint32_t _is_refskip; }; /* "pysam/libcalignmentfile.pxd":79 * * * cdef class IteratorRow: # <<<<<<<<<<<<<< * cdef int retval * cdef bam1_t * b */ struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow { PyObject_HEAD int retval; bam1_t *b; struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *samfile; htsFile *htsfile; hts_idx_t *index; struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *header; int owns_samfile; }; /* "pysam/libcalignmentfile.pxd":89 * * * cdef class IteratorRowRegion(IteratorRow): # <<<<<<<<<<<<<< * cdef hts_itr_t * iter * cdef bam1_t * getCurrent(self) */ struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion { struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow __pyx_base; struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowRegion *__pyx_vtab; hts_itr_t *iter; }; /* "pysam/libcalignmentfile.pxd":95 * * * cdef class IteratorRowHead(IteratorRow): # <<<<<<<<<<<<<< * cdef int max_rows * cdef int current_row */ struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead { struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow __pyx_base; struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowHead *__pyx_vtab; int max_rows; int current_row; }; /* "pysam/libcalignmentfile.pxd":102 * * * cdef class IteratorRowAll(IteratorRow): # <<<<<<<<<<<<<< * cdef bam1_t * getCurrent(self) * cdef int cnext(self) */ struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll { struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow __pyx_base; struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowAll *__pyx_vtab; }; /* "pysam/libcalignmentfile.pxd":107 * * * cdef class IteratorRowAllRefs(IteratorRow): # <<<<<<<<<<<<<< * cdef int tid * cdef IteratorRowRegion rowiter */ struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs { struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow __pyx_base; int tid; struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *rowiter; }; /* "pysam/libcalignmentfile.pxd":112 * * * cdef class IteratorRowSelection(IteratorRow): # <<<<<<<<<<<<<< * cdef int current_pos * cdef positions */ struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection { struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow __pyx_base; struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowSelection *__pyx_vtab; int current_pos; PyObject *positions; }; /* "pysam/libcalignmentfile.pxd":119 * * * cdef class IteratorColumn: # <<<<<<<<<<<<<< * * # result of the last plbuf_push */ struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn { PyObject_HEAD struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumn *__pyx_vtab; struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *iter; int tid; int pos; int n_plp; uint32_t min_base_quality; bam_pileup1_t *plp; bam_mplp_t pileup_iter; __pyx_t_5pysam_17libcalignmentfile___iterdata iterdata; struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *samfile; struct __pyx_obj_5pysam_9libcfaidx_FastaFile *fastafile; PyObject *stepper; int max_depth; int ignore_overlaps; }; /* "pysam/libcalignmentfile.pxd":150 * * * cdef class IteratorColumnRegion(IteratorColumn): # <<<<<<<<<<<<<< * cdef int start * cdef int stop */ struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnRegion { struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn __pyx_base; int start; int stop; int truncate; }; /* "pysam/libcalignmentfile.pxd":156 * * * cdef class IteratorColumnAllRefs(IteratorColumn): # <<<<<<<<<<<<<< * pass * */ struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAllRefs { struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn __pyx_base; }; /* "pysam/libcalignmentfile.pxd":160 * * * cdef class IndexedReads: # <<<<<<<<<<<<<< * cdef AlignmentFile samfile * cdef htsFile * htsfile */ struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads { PyObject_HEAD struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *samfile; htsFile *htsfile; PyObject *index; int owns_samfile; struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *header; }; /* "PyMaSC/core/readlen.pyx":11 * * * def _mean(c): # <<<<<<<<<<<<<< * return int(round( * sum(length * freq for length, freq in c.items()) / float(sum(c.values())) */ struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct___mean { PyObject_HEAD PyObject *__pyx_v_c; }; /* "PyMaSC/core/readlen.pyx":13 * def _mean(c): * return int(round( * sum(length * freq for length, freq in c.items()) / float(sum(c.values())) # <<<<<<<<<<<<<< * )) * */ struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr { PyObject_HEAD struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct___mean *__pyx_outer_scope; PyObject *__pyx_v_freq; PyObject *__pyx_v_length; PyObject *__pyx_t_0; Py_ssize_t __pyx_t_1; PyObject *(*__pyx_t_2)(PyObject *); }; /* "pysam/libchtslib.pxd":2590 * * * cdef class HTSFile(object): # <<<<<<<<<<<<<< * cdef htsFile *htsfile # pointer to htsFile structure * cdef int64_t start_offset # BGZF offset of first record */ struct __pyx_vtabstruct_5pysam_10libchtslib_HTSFile { htsFile *(*_open_htsfile)(struct __pyx_obj_5pysam_10libchtslib_HTSFile *); }; static struct __pyx_vtabstruct_5pysam_10libchtslib_HTSFile *__pyx_vtabptr_5pysam_10libchtslib_HTSFile; /* "pysam/libcfaidx.pxd":37 * int * dret) * * cdef class FastaFile: # <<<<<<<<<<<<<< * cdef bint is_remote * cdef object _filename, _references, _lengths, reference2length */ struct __pyx_vtabstruct_5pysam_9libcfaidx_FastaFile { char *(*_fetch)(struct __pyx_obj_5pysam_9libcfaidx_FastaFile *, char *, int, int, int *); }; static struct __pyx_vtabstruct_5pysam_9libcfaidx_FastaFile *__pyx_vtabptr_5pysam_9libcfaidx_FastaFile; /* "pysam/libcfaidx.pxd":45 * * * cdef class FastqProxy: # <<<<<<<<<<<<<< * cdef kseq_t * _delegate * cdef cython.str to_string(self) */ struct __pyx_vtabstruct_5pysam_9libcfaidx_FastqProxy { PyObject *(*to_string)(struct __pyx_obj_5pysam_9libcfaidx_FastqProxy *); PyObject *(*tostring)(struct __pyx_obj_5pysam_9libcfaidx_FastqProxy *); arrayobject *(*get_quality_array)(struct __pyx_obj_5pysam_9libcfaidx_FastqProxy *, int __pyx_skip_dispatch, struct __pyx_opt_args_5pysam_9libcfaidx_10FastqProxy_get_quality_array *__pyx_optional_args); }; static struct __pyx_vtabstruct_5pysam_9libcfaidx_FastqProxy *__pyx_vtabptr_5pysam_9libcfaidx_FastqProxy; /* "pysam/libcfaidx.pxd":52 * * * cdef class FastxRecord: # <<<<<<<<<<<<<< * """ * Python container for pysam.libcfaidx.FastqProxy with persistence. */ struct __pyx_vtabstruct_5pysam_9libcfaidx_FastxRecord { PyObject *(*to_string)(struct __pyx_obj_5pysam_9libcfaidx_FastxRecord *); PyObject *(*tostring)(struct __pyx_obj_5pysam_9libcfaidx_FastxRecord *); arrayobject *(*get_quality_array)(struct __pyx_obj_5pysam_9libcfaidx_FastxRecord *, int __pyx_skip_dispatch, struct __pyx_opt_args_5pysam_9libcfaidx_11FastxRecord_get_quality_array *__pyx_optional_args); }; static struct __pyx_vtabstruct_5pysam_9libcfaidx_FastxRecord *__pyx_vtabptr_5pysam_9libcfaidx_FastxRecord; /* "pysam/libcfaidx.pxd":61 * cpdef array.array get_quality_array(self, int offset=*) * * cdef class FastxFile: # <<<<<<<<<<<<<< * cdef object _filename * cdef BGZF * fastqfile */ struct __pyx_vtabstruct_5pysam_9libcfaidx_FastxFile { kseq_t *(*getCurrent)(struct __pyx_obj_5pysam_9libcfaidx_FastxFile *); int (*cnext)(struct __pyx_obj_5pysam_9libcfaidx_FastxFile *); }; static struct __pyx_vtabstruct_5pysam_9libcfaidx_FastxFile *__pyx_vtabptr_5pysam_9libcfaidx_FastxFile; /* "pysam/libcfaidx.pxd":73 * * # Compatibility Layer for pysam 0.8.1 * cdef class FastqFile(FastxFile): # <<<<<<<<<<<<<< * pass * */ struct __pyx_vtabstruct_5pysam_9libcfaidx_FastqFile { struct __pyx_vtabstruct_5pysam_9libcfaidx_FastxFile __pyx_base; }; static struct __pyx_vtabstruct_5pysam_9libcfaidx_FastqFile *__pyx_vtabptr_5pysam_9libcfaidx_FastqFile; /* "pysam/libcfaidx.pxd":78 * * # Compatibility Layer for pysam < 0.8 * cdef class Fastafile(FastaFile): # <<<<<<<<<<<<<< * pass * */ struct __pyx_vtabstruct_5pysam_9libcfaidx_Fastafile { struct __pyx_vtabstruct_5pysam_9libcfaidx_FastaFile __pyx_base; }; static struct __pyx_vtabstruct_5pysam_9libcfaidx_Fastafile *__pyx_vtabptr_5pysam_9libcfaidx_Fastafile; /* "pysam/libcalignedsegment.pxd":34 * * # Note: need to declare all C fields and methods here * cdef class AlignedSegment: # <<<<<<<<<<<<<< * * # object that this AlignedSegment represents */ struct __pyx_vtabstruct_5pysam_18libcalignedsegment_AlignedSegment { PyObject *(*set_tag)(struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *, PyObject *, PyObject *, int __pyx_skip_dispatch, struct __pyx_opt_args_5pysam_18libcalignedsegment_14AlignedSegment_set_tag *__pyx_optional_args); PyObject *(*get_tag)(struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *, PyObject *, int __pyx_skip_dispatch, struct __pyx_opt_args_5pysam_18libcalignedsegment_14AlignedSegment_get_tag *__pyx_optional_args); PyObject *(*has_tag)(struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *, PyObject *, int __pyx_skip_dispatch); PyObject *(*to_string)(struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *, int __pyx_skip_dispatch); PyObject *(*tostring)(struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *, int __pyx_skip_dispatch, struct __pyx_opt_args_5pysam_18libcalignedsegment_14AlignedSegment_tostring *__pyx_optional_args); }; static struct __pyx_vtabstruct_5pysam_18libcalignedsegment_AlignedSegment *__pyx_vtabptr_5pysam_18libcalignedsegment_AlignedSegment; /* "pysam/libcalignmentfile.pxd":44 * cdef bam_hdr_t *ptr * * cdef class AlignmentFile(HTSFile): # <<<<<<<<<<<<<< * cdef readonly object reference_filename * cdef readonly AlignmentHeader header */ struct __pyx_vtabstruct_5pysam_17libcalignmentfile_AlignmentFile { struct __pyx_vtabstruct_5pysam_10libchtslib_HTSFile __pyx_base; bam1_t *(*getCurrent)(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *); int (*cnext)(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *); int (*write)(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *, struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *, int __pyx_skip_dispatch); }; static struct __pyx_vtabstruct_5pysam_17libcalignmentfile_AlignmentFile *__pyx_vtabptr_5pysam_17libcalignmentfile_AlignmentFile; /* "pysam/libcalignmentfile.pxd":89 * * * cdef class IteratorRowRegion(IteratorRow): # <<<<<<<<<<<<<< * cdef hts_itr_t * iter * cdef bam1_t * getCurrent(self) */ struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowRegion { bam1_t *(*getCurrent)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *); int (*cnext)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *); }; static struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowRegion *__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowRegion; /* "pysam/libcalignmentfile.pxd":95 * * * cdef class IteratorRowHead(IteratorRow): # <<<<<<<<<<<<<< * cdef int max_rows * cdef int current_row */ struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowHead { bam1_t *(*getCurrent)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead *); int (*cnext)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead *); }; static struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowHead *__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowHead; /* "pysam/libcalignmentfile.pxd":102 * * * cdef class IteratorRowAll(IteratorRow): # <<<<<<<<<<<<<< * cdef bam1_t * getCurrent(self) * cdef int cnext(self) */ struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowAll { bam1_t *(*getCurrent)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll *); int (*cnext)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll *); }; static struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowAll *__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowAll; /* "pysam/libcalignmentfile.pxd":112 * * * cdef class IteratorRowSelection(IteratorRow): # <<<<<<<<<<<<<< * cdef int current_pos * cdef positions */ struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowSelection { bam1_t *(*getCurrent)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *); int (*cnext)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *); }; static struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowSelection *__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowSelection; /* "pysam/libcalignmentfile.pxd":119 * * * cdef class IteratorColumn: # <<<<<<<<<<<<<< * * # result of the last plbuf_push */ struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumn { int (*cnext)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *); char *(*get_sequence)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *); PyObject *(*_setup_iterator)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *, int, int, int, struct __pyx_opt_args_5pysam_17libcalignmentfile_14IteratorColumn__setup_iterator *__pyx_optional_args); PyObject *(*reset)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *, PyObject *, PyObject *, PyObject *); PyObject *(*_free_pileup_iter)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *); char *(*getSequence)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *); }; static struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumn *__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumn; /* "pysam/libcalignmentfile.pxd":150 * * * cdef class IteratorColumnRegion(IteratorColumn): # <<<<<<<<<<<<<< * cdef int start * cdef int stop */ struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumnRegion { struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumn __pyx_base; }; static struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumnRegion *__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumnRegion; /* "pysam/libcalignmentfile.pxd":156 * * * cdef class IteratorColumnAllRefs(IteratorColumn): # <<<<<<<<<<<<<< * pass * */ struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumnAllRefs { struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumn __pyx_base; }; static struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumnAllRefs *__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumnAllRefs; /* --- Runtime support code (head) --- */ /* Refnanny.proto */ #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif #if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, int); void (*DECREF)(void*, PyObject*, int); void (*GOTREF)(void*, PyObject*, int); void (*GIVEREF)(void*, PyObject*, int); void* (*SetupContext)(const char*, int, const char*); void (*FinishContext)(void**); } __Pyx_RefNannyAPIStruct; static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; #ifdef WITH_THREAD #define __Pyx_RefNannySetupContext(name, acquire_gil)\ if (acquire_gil) {\ PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ PyGILState_Release(__pyx_gilstate_save);\ } else {\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ } #else #define __Pyx_RefNannySetupContext(name, acquire_gil)\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) #endif #define __Pyx_RefNannyFinishContext()\ __Pyx_RefNanny->FinishContext(&__pyx_refnanny) #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) #else #define __Pyx_RefNannyDeclarations #define __Pyx_RefNannySetupContext(name, acquire_gil) #define __Pyx_RefNannyFinishContext() #define __Pyx_INCREF(r) Py_INCREF(r) #define __Pyx_DECREF(r) Py_DECREF(r) #define __Pyx_GOTREF(r) #define __Pyx_GIVEREF(r) #define __Pyx_XINCREF(r) Py_XINCREF(r) #define __Pyx_XDECREF(r) Py_XDECREF(r) #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) #endif #define __Pyx_XDECREF_SET(r, v) do {\ PyObject *tmp = (PyObject *) r;\ r = v; __Pyx_XDECREF(tmp);\ } while (0) #define __Pyx_DECREF_SET(r, v) do {\ PyObject *tmp = (PyObject *) r;\ r = v; __Pyx_DECREF(tmp);\ } while (0) #define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) #define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) /* PyObjectGetAttrStr.proto */ #if CYTHON_USE_TYPE_SLOTS static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name); #else #define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) #endif /* GetBuiltinName.proto */ static PyObject *__Pyx_GetBuiltinName(PyObject *name); /* None.proto */ static CYTHON_INLINE void __Pyx_RaiseClosureNameError(const char *varname); /* PyFunctionFastCall.proto */ #if CYTHON_FAST_PYCALL #define __Pyx_PyFunction_FastCall(func, args, nargs)\ __Pyx_PyFunction_FastCallDict((func), (args), (nargs), NULL) #if 1 || PY_VERSION_HEX < 0x030600B1 static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, int nargs, PyObject *kwargs); #else #define __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs) _PyFunction_FastCallDict(func, args, nargs, kwargs) #endif #define __Pyx_BUILD_ASSERT_EXPR(cond)\ (sizeof(char [1 - 2*!(cond)]) - 1) #ifndef Py_MEMBER_SIZE #define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member) #endif static size_t __pyx_pyframe_localsplus_offset = 0; #include "frameobject.h" #define __Pxy_PyFrame_Initialize_Offsets()\ ((void)__Pyx_BUILD_ASSERT_EXPR(sizeof(PyFrameObject) == offsetof(PyFrameObject, f_localsplus) + Py_MEMBER_SIZE(PyFrameObject, f_localsplus)),\ (void)(__pyx_pyframe_localsplus_offset = ((size_t)PyFrame_Type.tp_basicsize) - Py_MEMBER_SIZE(PyFrameObject, f_localsplus))) #define __Pyx_PyFrame_GetLocalsplus(frame)\ (assert(__pyx_pyframe_localsplus_offset), (PyObject **)(((char *)(frame)) + __pyx_pyframe_localsplus_offset)) #endif /* PyObjectCall.proto */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); #else #define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) #endif /* PyObjectCallMethO.proto */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); #endif /* PyObjectCallNoArg.proto */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); #else #define __Pyx_PyObject_CallNoArg(func) __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL) #endif /* PyCFunctionFastCall.proto */ #if CYTHON_FAST_PYCCALL static CYTHON_INLINE PyObject *__Pyx_PyCFunction_FastCall(PyObject *func, PyObject **args, Py_ssize_t nargs); #else #define __Pyx_PyCFunction_FastCall(func, args, nargs) (assert(0), NULL) #endif /* PyObjectCallOneArg.proto */ static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); /* RaiseTooManyValuesToUnpack.proto */ static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); /* RaiseNeedMoreValuesToUnpack.proto */ static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); /* IterFinish.proto */ static CYTHON_INLINE int __Pyx_IterFinish(void); /* UnpackItemEndCheck.proto */ static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); /* PyIntBinop.proto */ #if !CYTHON_COMPILING_IN_PYPY static PyObject* __Pyx_PyInt_RemainderObjC(PyObject *op1, PyObject *op2, long intval, int inplace); #else #define __Pyx_PyInt_RemainderObjC(op1, op2, intval, inplace)\ (inplace ? PyNumber_InPlaceRemainder(op1, op2) : PyNumber_Remainder(op1, op2)) #endif /* GetItemInt.proto */ #define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) :\ (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) :\ __Pyx_GetItemInt_Generic(o, to_py_func(i)))) #define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, int wraparound, int boundscheck); #define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, int wraparound, int boundscheck); static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, int wraparound, int boundscheck); /* ObjectGetItem.proto */ #if CYTHON_USE_TYPE_SLOTS static CYTHON_INLINE PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject* key); #else #define __Pyx_PyObject_GetItem(obj, key) PyObject_GetItem(obj, key) #endif /* PyIntBinop.proto */ #if !CYTHON_COMPILING_IN_PYPY static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, long intval, int inplace); #else #define __Pyx_PyInt_AddObjC(op1, op2, intval, inplace)\ (inplace ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2)) #endif /* FetchCommonType.proto */ static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type); /* CythonFunction.proto */ #define __Pyx_CyFunction_USED 1 #define __Pyx_CYFUNCTION_STATICMETHOD 0x01 #define __Pyx_CYFUNCTION_CLASSMETHOD 0x02 #define __Pyx_CYFUNCTION_CCLASS 0x04 #define __Pyx_CyFunction_GetClosure(f)\ (((__pyx_CyFunctionObject *) (f))->func_closure) #define __Pyx_CyFunction_GetClassObj(f)\ (((__pyx_CyFunctionObject *) (f))->func_classobj) #define __Pyx_CyFunction_Defaults(type, f)\ ((type *)(((__pyx_CyFunctionObject *) (f))->defaults)) #define __Pyx_CyFunction_SetDefaultsGetter(f, g)\ ((__pyx_CyFunctionObject *) (f))->defaults_getter = (g) typedef struct { PyCFunctionObject func; #if PY_VERSION_HEX < 0x030500A0 PyObject *func_weakreflist; #endif PyObject *func_dict; PyObject *func_name; PyObject *func_qualname; PyObject *func_doc; PyObject *func_globals; PyObject *func_code; PyObject *func_closure; PyObject *func_classobj; void *defaults; int defaults_pyobjects; int flags; PyObject *defaults_tuple; PyObject *defaults_kwdict; PyObject *(*defaults_getter)(PyObject *); PyObject *func_annotations; } __pyx_CyFunctionObject; static PyTypeObject *__pyx_CyFunctionType = 0; #define __Pyx_CyFunction_Check(obj) (__Pyx_TypeCheck(obj, __pyx_CyFunctionType)) #define __Pyx_CyFunction_NewEx(ml, flags, qualname, self, module, globals, code)\ __Pyx_CyFunction_New(__pyx_CyFunctionType, ml, flags, qualname, self, module, globals, code) static PyObject *__Pyx_CyFunction_New(PyTypeObject *, PyMethodDef *ml, int flags, PyObject* qualname, PyObject *self, PyObject *module, PyObject *globals, PyObject* code); static CYTHON_INLINE void *__Pyx_CyFunction_InitDefaults(PyObject *m, size_t size, int pyobjects); static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *m, PyObject *tuple); static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *m, PyObject *dict); static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *m, PyObject *dict); static int __pyx_CyFunction_init(void); /* ListCompAppend.proto */ #if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { PyListObject* L = (PyListObject*) list; Py_ssize_t len = Py_SIZE(list); if (likely(L->allocated > len)) { Py_INCREF(x); PyList_SET_ITEM(list, len, x); Py_SIZE(list) = len+1; return 0; } return PyList_Append(list, x); } #else #define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) #endif /* RaiseArgTupleInvalid.proto */ static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /* RaiseDoubleKeywords.proto */ static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /* ParseKeywords.proto */ static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\ PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\ const char* function_name); /* GetModuleGlobalName.proto */ #if CYTHON_USE_DICT_VERSIONS #define __Pyx_GetModuleGlobalName(var, name) {\ static PY_UINT64_T __pyx_dict_version = 0;\ static PyObject *__pyx_dict_cached_value = NULL;\ (var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_d))) ?\ (likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\ __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ } #define __Pyx_GetModuleGlobalNameUncached(var, name) {\ PY_UINT64_T __pyx_dict_version;\ PyObject *__pyx_dict_cached_value;\ (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ } static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value); #else #define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name) #define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name) static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name); #endif /* PyObjectLookupSpecial.proto */ #if CYTHON_USE_PYTYPE_LOOKUP && CYTHON_USE_TYPE_SLOTS static CYTHON_INLINE PyObject* __Pyx_PyObject_LookupSpecial(PyObject* obj, PyObject* attr_name) { PyObject *res; PyTypeObject *tp = Py_TYPE(obj); #if PY_MAJOR_VERSION < 3 if (unlikely(PyInstance_Check(obj))) return __Pyx_PyObject_GetAttrStr(obj, attr_name); #endif res = _PyType_Lookup(tp, attr_name); if (likely(res)) { descrgetfunc f = Py_TYPE(res)->tp_descr_get; if (!f) { Py_INCREF(res); } else { res = f(res, obj, (PyObject *)tp); } } else { PyErr_SetObject(PyExc_AttributeError, attr_name); } return res; } #else #define __Pyx_PyObject_LookupSpecial(o,n) __Pyx_PyObject_GetAttrStr(o,n) #endif /* py_dict_values.proto */ static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d); /* UnpackUnboundCMethod.proto */ typedef struct { PyObject *type; PyObject **method_name; PyCFunction func; PyObject *method; int flag; } __Pyx_CachedCFunction; /* CallUnboundCMethod0.proto */ static PyObject* __Pyx__CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self); #if CYTHON_COMPILING_IN_CPYTHON #define __Pyx_CallUnboundCMethod0(cfunc, self)\ (likely((cfunc)->func) ?\ (likely((cfunc)->flag == METH_NOARGS) ? (*((cfunc)->func))(self, NULL) :\ (PY_VERSION_HEX >= 0x030600B1 && likely((cfunc)->flag == METH_FASTCALL) ?\ (PY_VERSION_HEX >= 0x030700A0 ?\ (*(__Pyx_PyCFunctionFast)(void*)(PyCFunction)(cfunc)->func)(self, &__pyx_empty_tuple, 0) :\ (*(__Pyx_PyCFunctionFastWithKeywords)(void*)(PyCFunction)(cfunc)->func)(self, &__pyx_empty_tuple, 0, NULL)) :\ (PY_VERSION_HEX >= 0x030700A0 && (cfunc)->flag == (METH_FASTCALL | METH_KEYWORDS) ?\ (*(__Pyx_PyCFunctionFastWithKeywords)(void*)(PyCFunction)(cfunc)->func)(self, &__pyx_empty_tuple, 0, NULL) :\ (likely((cfunc)->flag == (METH_VARARGS | METH_KEYWORDS)) ? ((*(PyCFunctionWithKeywords)(void*)(PyCFunction)(cfunc)->func)(self, __pyx_empty_tuple, NULL)) :\ ((cfunc)->flag == METH_VARARGS ? (*((cfunc)->func))(self, __pyx_empty_tuple) :\ __Pyx__CallUnboundCMethod0(cfunc, self)))))) :\ __Pyx__CallUnboundCMethod0(cfunc, self)) #else #define __Pyx_CallUnboundCMethod0(cfunc, self) __Pyx__CallUnboundCMethod0(cfunc, self) #endif /* PyObjectCall2Args.proto */ static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2); /* ExtTypeTest.proto */ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /* IncludeStringH.proto */ #include <string.h> /* BytesEquals.proto */ static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); /* UnicodeEquals.proto */ static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); /* StrEquals.proto */ #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals #else #define __Pyx_PyString_Equals __Pyx_PyBytes_Equals #endif /* DictGetItem.proto */ #if PY_MAJOR_VERSION >= 3 && !CYTHON_COMPILING_IN_PYPY static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key); #define __Pyx_PyObject_Dict_GetItem(obj, name)\ (likely(PyDict_CheckExact(obj)) ?\ __Pyx_PyDict_GetItem(obj, name) : PyObject_GetItem(obj, name)) #else #define __Pyx_PyDict_GetItem(d, key) PyObject_GetItem(d, key) #define __Pyx_PyObject_Dict_GetItem(obj, name) PyObject_GetItem(obj, name) #endif /* PyDictContains.proto */ static CYTHON_INLINE int __Pyx_PyDict_ContainsTF(PyObject* item, PyObject* dict, int eq) { int result = PyDict_Contains(dict, item); return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); } /* GetTopmostException.proto */ #if CYTHON_USE_EXC_INFO_STACK static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate); #endif /* PyThreadStateGet.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; #define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; #define __Pyx_PyErr_Occurred() __pyx_tstate->curexc_type #else #define __Pyx_PyThreadState_declare #define __Pyx_PyThreadState_assign #define __Pyx_PyErr_Occurred() PyErr_Occurred() #endif /* SaveResetException.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); #else #define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) #define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) #endif /* GetException.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb) static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #else static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); #endif /* PyErrFetchRestore.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) #define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) #define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) #define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) #define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #if CYTHON_COMPILING_IN_CPYTHON #define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) #else #define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) #endif #else #define __Pyx_PyErr_Clear() PyErr_Clear() #define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) #define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) #define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) #define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) #endif /* None.proto */ static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname); /* PyObject_GenericGetAttrNoDict.proto */ #if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name); #else #define __Pyx_PyObject_GenericGetAttrNoDict PyObject_GenericGetAttr #endif /* TypeImport.proto */ #ifndef __PYX_HAVE_RT_ImportType_proto #define __PYX_HAVE_RT_ImportType_proto enum __Pyx_ImportType_CheckSize { __Pyx_ImportType_CheckSize_Error = 0, __Pyx_ImportType_CheckSize_Warn = 1, __Pyx_ImportType_CheckSize_Ignore = 2 }; static PyTypeObject *__Pyx_ImportType(PyObject* module, const char *module_name, const char *class_name, size_t size, enum __Pyx_ImportType_CheckSize check_size); #endif /* GetVTable.proto */ static void* __Pyx_GetVtable(PyObject *dict); /* Import.proto */ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /* ImportFrom.proto */ static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); /* CLineInTraceback.proto */ #ifdef CYTHON_CLINE_IN_TRACEBACK #define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) #else static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); #endif /* CodeObjectCache.proto */ typedef struct { PyCodeObject* code_object; int code_line; } __Pyx_CodeObjectCacheEntry; struct __Pyx_CodeObjectCache { int count; int max_count; __Pyx_CodeObjectCacheEntry* entries; }; static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); static PyCodeObject *__pyx_find_code_object(int code_line); static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); /* AddTraceback.proto */ static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_unsigned_long(unsigned long value); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_unsigned_int(unsigned int value); /* ArrayAPI.proto */ #ifndef _ARRAYARRAY_H #define _ARRAYARRAY_H typedef struct arraydescr { int typecode; int itemsize; PyObject * (*getitem)(struct arrayobject *, Py_ssize_t); int (*setitem)(struct arrayobject *, Py_ssize_t, PyObject *); #if PY_MAJOR_VERSION >= 3 char *formats; #endif } arraydescr; struct arrayobject { PyObject_HEAD Py_ssize_t ob_size; union { char *ob_item; float *as_floats; double *as_doubles; int *as_ints; unsigned int *as_uints; unsigned char *as_uchars; signed char *as_schars; char *as_chars; unsigned long *as_ulongs; long *as_longs; #if PY_MAJOR_VERSION >= 3 unsigned long long *as_ulonglongs; long long *as_longlongs; #endif short *as_shorts; unsigned short *as_ushorts; Py_UNICODE *as_pyunicodes; void *as_voidptr; } data; Py_ssize_t allocated; struct arraydescr *ob_descr; PyObject *weakreflist; #if PY_MAJOR_VERSION >= 3 int ob_exports; #endif }; #ifndef NO_NEWARRAY_INLINE static CYTHON_INLINE PyObject * newarrayobject(PyTypeObject *type, Py_ssize_t size, struct arraydescr *descr) { arrayobject *op; size_t nbytes; if (size < 0) { PyErr_BadInternalCall(); return NULL; } nbytes = size * descr->itemsize; if (nbytes / descr->itemsize != (size_t)size) { return PyErr_NoMemory(); } op = (arrayobject *) type->tp_alloc(type, 0); if (op == NULL) { return NULL; } op->ob_descr = descr; op->allocated = size; op->weakreflist = NULL; op->ob_size = size; if (size <= 0) { op->data.ob_item = NULL; } else { op->data.ob_item = PyMem_NEW(char, nbytes); if (op->data.ob_item == NULL) { Py_DECREF(op); return PyErr_NoMemory(); } } return (PyObject *) op; } #else PyObject* newarrayobject(PyTypeObject *type, Py_ssize_t size, struct arraydescr *descr); #endif static CYTHON_INLINE int resize(arrayobject *self, Py_ssize_t n) { void *items = (void*) self->data.ob_item; PyMem_Resize(items, char, (size_t)(n * self->ob_descr->itemsize)); if (items == NULL) { PyErr_NoMemory(); return -1; } self->data.ob_item = (char*) items; self->ob_size = n; self->allocated = n; return 0; } static CYTHON_INLINE int resize_smart(arrayobject *self, Py_ssize_t n) { void *items = (void*) self->data.ob_item; Py_ssize_t newsize; if (n < self->allocated && n*4 > self->allocated) { self->ob_size = n; return 0; } newsize = n + (n / 2) + 1; if (newsize <= n) { PyErr_NoMemory(); return -1; } PyMem_Resize(items, char, (size_t)(newsize * self->ob_descr->itemsize)); if (items == NULL) { PyErr_NoMemory(); return -1; } self->data.ob_item = (char*) items; self->ob_size = n; self->allocated = newsize; return 0; } #endif /* CIntFromPy.proto */ static CYTHON_INLINE unsigned int __Pyx_PyInt_As_unsigned_int(PyObject *); /* CIntFromPy.proto */ static CYTHON_INLINE unsigned long __Pyx_PyInt_As_unsigned_long(PyObject *); /* CIntFromPy.proto */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); /* CIntFromPy.proto */ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); /* FastTypeChecks.proto */ #if CYTHON_COMPILING_IN_CPYTHON #define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); #else #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) #define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) #define __Pyx_PyErr_GivenExceptionMatches2(err, type1, type2) (PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2)) #endif #define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) /* RaiseException.proto */ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /* SwapException.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_ExceptionSwap(type, value, tb) __Pyx__ExceptionSwap(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #else static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); #endif /* PyObjectGetMethod.proto */ static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method); /* PyObjectCallMethod1.proto */ static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg); /* CoroutineBase.proto */ typedef PyObject *(*__pyx_coroutine_body_t)(PyObject *, PyThreadState *, PyObject *); #if CYTHON_USE_EXC_INFO_STACK #define __Pyx_ExcInfoStruct _PyErr_StackItem #else typedef struct { PyObject *exc_type; PyObject *exc_value; PyObject *exc_traceback; } __Pyx_ExcInfoStruct; #endif typedef struct { PyObject_HEAD __pyx_coroutine_body_t body; PyObject *closure; __Pyx_ExcInfoStruct gi_exc_state; PyObject *gi_weakreflist; PyObject *classobj; PyObject *yieldfrom; PyObject *gi_name; PyObject *gi_qualname; PyObject *gi_modulename; PyObject *gi_code; int resume_label; char is_running; } __pyx_CoroutineObject; static __pyx_CoroutineObject *__Pyx__Coroutine_New( PyTypeObject *type, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, PyObject *name, PyObject *qualname, PyObject *module_name); static __pyx_CoroutineObject *__Pyx__Coroutine_NewInit( __pyx_CoroutineObject *gen, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, PyObject *name, PyObject *qualname, PyObject *module_name); static CYTHON_INLINE void __Pyx_Coroutine_ExceptionClear(__Pyx_ExcInfoStruct *self); static int __Pyx_Coroutine_clear(PyObject *self); static PyObject *__Pyx_Coroutine_Send(PyObject *self, PyObject *value); static PyObject *__Pyx_Coroutine_Close(PyObject *self); static PyObject *__Pyx_Coroutine_Throw(PyObject *gen, PyObject *args); #if CYTHON_USE_EXC_INFO_STACK #define __Pyx_Coroutine_SwapException(self) #define __Pyx_Coroutine_ResetAndClearException(self) __Pyx_Coroutine_ExceptionClear(&(self)->gi_exc_state) #else #define __Pyx_Coroutine_SwapException(self) {\ __Pyx_ExceptionSwap(&(self)->gi_exc_state.exc_type, &(self)->gi_exc_state.exc_value, &(self)->gi_exc_state.exc_traceback);\ __Pyx_Coroutine_ResetFrameBackpointer(&(self)->gi_exc_state);\ } #define __Pyx_Coroutine_ResetAndClearException(self) {\ __Pyx_ExceptionReset((self)->gi_exc_state.exc_type, (self)->gi_exc_state.exc_value, (self)->gi_exc_state.exc_traceback);\ (self)->gi_exc_state.exc_type = (self)->gi_exc_state.exc_value = (self)->gi_exc_state.exc_traceback = NULL;\ } #endif #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyGen_FetchStopIterationValue(pvalue)\ __Pyx_PyGen__FetchStopIterationValue(__pyx_tstate, pvalue) #else #define __Pyx_PyGen_FetchStopIterationValue(pvalue)\ __Pyx_PyGen__FetchStopIterationValue(__Pyx_PyThreadState_Current, pvalue) #endif static int __Pyx_PyGen__FetchStopIterationValue(PyThreadState *tstate, PyObject **pvalue); static CYTHON_INLINE void __Pyx_Coroutine_ResetFrameBackpointer(__Pyx_ExcInfoStruct *exc_state); /* PatchModuleWithCoroutine.proto */ static PyObject* __Pyx_Coroutine_patch_module(PyObject* module, const char* py_code); /* PatchGeneratorABC.proto */ static int __Pyx_patch_abc(void); /* Generator.proto */ #define __Pyx_Generator_USED static PyTypeObject *__pyx_GeneratorType = 0; #define __Pyx_Generator_CheckExact(obj) (Py_TYPE(obj) == __pyx_GeneratorType) #define __Pyx_Generator_New(body, code, closure, name, qualname, module_name)\ __Pyx__Coroutine_New(__pyx_GeneratorType, body, code, closure, name, qualname, module_name) static PyObject *__Pyx_Generator_Next(PyObject *self); static int __pyx_Generator_init(void); /* CheckBinaryVersion.proto */ static int __Pyx_check_binary_version(void); /* InitStrings.proto */ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /* Module declarations from 'libc.stdint' */ /* Module declarations from 'libc.string' */ /* Module declarations from 'libc.stdlib' */ /* Module declarations from 'libc.stdio' */ /* Module declarations from 'cython' */ /* Module declarations from 'cpython.version' */ /* Module declarations from '__builtin__' */ /* Module declarations from 'cpython.type' */ static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; /* Module declarations from 'cpython.object' */ /* Module declarations from 'cpython.ref' */ /* Module declarations from 'cpython.exc' */ /* Module declarations from 'cpython.module' */ /* Module declarations from 'cpython.mem' */ /* Module declarations from 'cpython.tuple' */ /* Module declarations from 'cpython.list' */ /* Module declarations from 'cpython.sequence' */ /* Module declarations from 'cpython.mapping' */ /* Module declarations from 'cpython.iterator' */ /* Module declarations from 'cpython.number' */ /* Module declarations from 'cpython.int' */ /* Module declarations from '__builtin__' */ /* Module declarations from 'cpython.bool' */ static PyTypeObject *__pyx_ptype_7cpython_4bool_bool = 0; /* Module declarations from 'cpython.long' */ /* Module declarations from 'cpython.float' */ /* Module declarations from '__builtin__' */ /* Module declarations from 'cpython.complex' */ static PyTypeObject *__pyx_ptype_7cpython_7complex_complex = 0; /* Module declarations from 'cpython.string' */ /* Module declarations from 'cpython.unicode' */ /* Module declarations from 'cpython.dict' */ /* Module declarations from 'cpython.instance' */ /* Module declarations from 'cpython.function' */ /* Module declarations from 'cpython.method' */ /* Module declarations from 'cpython.weakref' */ /* Module declarations from 'cpython.getargs' */ /* Module declarations from 'cpython.pythread' */ /* Module declarations from 'cpython.pystate' */ /* Module declarations from 'cpython.cobject' */ /* Module declarations from 'cpython.oldbuffer' */ /* Module declarations from 'cpython.set' */ /* Module declarations from 'cpython.buffer' */ /* Module declarations from 'cpython.bytes' */ /* Module declarations from 'cpython.pycapsule' */ /* Module declarations from 'cpython' */ /* Module declarations from 'array' */ /* Module declarations from 'cpython.array' */ static PyTypeObject *__pyx_ptype_7cpython_5array_array = 0; static CYTHON_INLINE int __pyx_f_7cpython_5array_extend_buffer(arrayobject *, char *, Py_ssize_t); /*proto*/ /* Module declarations from 'posix.types' */ /* Module declarations from 'pysam.libchtslib' */ static PyTypeObject *__pyx_ptype_5pysam_10libchtslib_HTSFile = 0; /* Module declarations from 'pysam.libcfaidx' */ static PyTypeObject *__pyx_ptype_5pysam_9libcfaidx_FastaFile = 0; static PyTypeObject *__pyx_ptype_5pysam_9libcfaidx_FastqProxy = 0; static PyTypeObject *__pyx_ptype_5pysam_9libcfaidx_FastxRecord = 0; static PyTypeObject *__pyx_ptype_5pysam_9libcfaidx_FastxFile = 0; static PyTypeObject *__pyx_ptype_5pysam_9libcfaidx_FastqFile = 0; static PyTypeObject *__pyx_ptype_5pysam_9libcfaidx_Fastafile = 0; /* Module declarations from 'pysam.libcalignedsegment' */ static PyTypeObject *__pyx_ptype_5pysam_18libcalignedsegment_AlignedSegment = 0; static PyTypeObject *__pyx_ptype_5pysam_18libcalignedsegment_PileupColumn = 0; static PyTypeObject *__pyx_ptype_5pysam_18libcalignedsegment_PileupRead = 0; /* Module declarations from 'pysam.libcalignmentfile' */ static PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader = 0; static PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile = 0; static PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_PileupColumn = 0; static PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_PileupRead = 0; static PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_IteratorRow = 0; static PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion = 0; static PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowHead = 0; static PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAll = 0; static PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAllRefs = 0; static PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowSelection = 0; static PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn = 0; static PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnRegion = 0; static PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAllRefs = 0; static PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_IndexedReads = 0; /* Module declarations from 'PyMaSC.core.readlen' */ static PyTypeObject *__pyx_ptype_6PyMaSC_4core_7readlen___pyx_scope_struct___mean = 0; static PyTypeObject *__pyx_ptype_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr = 0; #define __Pyx_MODULE_NAME "PyMaSC.core.readlen" extern int __pyx_module_is_main_PyMaSC__core__readlen; int __pyx_module_is_main_PyMaSC__core__readlen = 0; /* Implementation of 'PyMaSC.core.readlen' */ static PyObject *__pyx_builtin_min; static PyObject *__pyx_builtin_max; static PyObject *__pyx_builtin_round; static PyObject *__pyx_builtin_sum; static PyObject *__pyx_builtin_enumerate; static PyObject *__pyx_builtin_sorted; static PyObject *__pyx_builtin_zip; static PyObject *__pyx_builtin_MemoryError; static const char __pyx_k_c[] = "c"; static const char __pyx_k_i[] = "i"; static const char __pyx_k_k[] = "k"; static const char __pyx_k_l[] = "l"; static const char __pyx_k_v[] = "v"; static const char __pyx_k_MAX[] = "MAX"; static const char __pyx_k_MIN[] = "MIN"; static const char __pyx_k_key[] = "key"; static const char __pyx_k_max[] = "max"; static const char __pyx_k_min[] = "min"; static const char __pyx_k_num[] = "num"; static const char __pyx_k_pos[] = "pos"; static const char __pyx_k_sum[] = "sum"; static const char __pyx_k_zip[] = "zip"; static const char __pyx_k_MEAN[] = "MEAN"; static const char __pyx_k_MODE[] = "MODE"; static const char __pyx_k_args[] = "args"; static const char __pyx_k_exit[] = "__exit__"; static const char __pyx_k_info[] = "info"; static const char __pyx_k_main[] = "__main__"; static const char __pyx_k_mapq[] = "mapq"; static const char __pyx_k_mean[] = "_mean"; static const char __pyx_k_mode[] = "_mode"; static const char __pyx_k_name[] = "__name__"; static const char __pyx_k_path[] = "path"; static const char __pyx_k_read[] = "read"; static const char __pyx_k_send[] = "send"; static const char __pyx_k_test[] = "__test__"; static const char __pyx_k_chrom[] = "chrom"; static const char __pyx_k_close[] = "close"; static const char __pyx_k_enter[] = "__enter__"; static const char __pyx_k_items[] = "items"; static const char __pyx_k_round[] = "round"; static const char __pyx_k_sum_2[] = "_sum"; static const char __pyx_k_throw[] = "throw"; static const char __pyx_k_MEDIAN[] = "MEDIAN"; static const char __pyx_k_finish[] = "finish"; static const char __pyx_k_format[] = "format"; static const char __pyx_k_import[] = "__import__"; static const char __pyx_k_length[] = "length"; static const char __pyx_k_logger[] = "logger"; static const char __pyx_k_median[] = "_median"; static const char __pyx_k_nread2[] = "nread2"; static const char __pyx_k_nreads[] = "nreads"; static const char __pyx_k_sorted[] = "sorted"; static const char __pyx_k_stream[] = "stream"; static const char __pyx_k_target[] = "target"; static const char __pyx_k_update[] = "update"; static const char __pyx_k_values[] = "values"; static const char __pyx_k_chrom_2[] = "_chrom"; static const char __pyx_k_counter[] = "counter"; static const char __pyx_k_estfunc[] = "estfunc"; static const char __pyx_k_esttype[] = "esttype"; static const char __pyx_k_genexpr[] = "genexpr"; static const char __pyx_k_lengths[] = "lengths"; static const char __pyx_k_logging[] = "logging"; static const char __pyx_k_npaired[] = "npaired"; static const char __pyx_k_readlen[] = "readlen"; static const char __pyx_k_is_read2[] = "is_read2"; static const char __pyx_k_progress[] = "progress"; static const char __pyx_k_enumerate[] = "enumerate"; static const char __pyx_k_getLogger[] = "getLogger"; static const char __pyx_k_has_index[] = "has_index"; static const char __pyx_k_is_paired[] = "is_paired"; static const char __pyx_k_nunmapped[] = "nunmapped"; static const char __pyx_k_set_chrom[] = "set_chrom"; static const char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; static const char __pyx_k_references[] = "references"; static const char __pyx_k_set_genome[] = "set_genome"; static const char __pyx_k_MemoryError[] = "MemoryError"; static const char __pyx_k_disable_bar[] = "disable_bar"; static const char __pyx_k_is_unmapped[] = "is_unmapped"; static const char __pyx_k_ESTFUNCTIONS[] = "ESTFUNCTIONS"; static const char __pyx_k_chrom2length[] = "chrom2length"; static const char __pyx_k_is_duplicate[] = "is_duplicate"; static const char __pyx_k_mapq_criteria[] = "mapq_criteria"; static const char __pyx_k_reference_name[] = "reference_name"; static const char __pyx_k_mapping_quality[] = "mapping_quality"; static const char __pyx_k_reference_start[] = "reference_start"; static const char __pyx_k_estimate_readlen[] = "estimate_readlen"; static const char __pyx_k_cline_in_traceback[] = "cline_in_traceback"; static const char __pyx_k_infer_query_length[] = "infer_query_length"; static const char __pyx_k_mode_locals_lambda[] = "_mode.<locals>.<lambda>"; static const char __pyx_k_PyMaSC_core_readlen[] = "PyMaSC.core.readlen"; static const char __pyx_k_mean_locals_genexpr[] = "_mean.<locals>.genexpr"; static const char __pyx_k_ReadCountProgressBar[] = "ReadCountProgressBar"; static const char __pyx_k_Estimated_read_length[] = "Estimated read length = {:,}"; static const char __pyx_k_PyMaSC_utils_progress[] = "PyMaSC.utils.progress"; static const char __pyx_k_PyMaSC_core_readlen_pyx[] = "PyMaSC/core/readlen.pyx"; static const char __pyx_k_All_reads_were_single_ended[] = "All reads were single-ended."; static const char __pyx_k_Note_that_only_1st_reads_in_the[] = "Note that only 1st reads in the templates will be used for calculation."; static const char __pyx_k_reads_were_paired_reads_were_1s[] = "{:,} reads were paired: {:,} reads were 1st and {:,} reads were last segment."; static const char __pyx_k_Scan_reads_reads_were_unmapped_a[] = "Scan {:,} reads, {:,} reads were unmapped and {:,} reads >= MAPQ {}."; static PyObject *__pyx_kp_s_All_reads_were_single_ended; static PyObject *__pyx_n_s_ESTFUNCTIONS; static PyObject *__pyx_kp_s_Estimated_read_length; static PyObject *__pyx_n_s_MAX; static PyObject *__pyx_n_s_MEAN; static PyObject *__pyx_n_s_MEDIAN; static PyObject *__pyx_n_s_MIN; static PyObject *__pyx_n_s_MODE; static PyObject *__pyx_n_s_MemoryError; static PyObject *__pyx_kp_s_Note_that_only_1st_reads_in_the; static PyObject *__pyx_n_s_PyMaSC_core_readlen; static PyObject *__pyx_kp_s_PyMaSC_core_readlen_pyx; static PyObject *__pyx_n_s_PyMaSC_utils_progress; static PyObject *__pyx_n_s_ReadCountProgressBar; static PyObject *__pyx_kp_s_Scan_reads_reads_were_unmapped_a; static PyObject *__pyx_n_s_args; static PyObject *__pyx_n_s_c; static PyObject *__pyx_n_s_chrom; static PyObject *__pyx_n_s_chrom2length; static PyObject *__pyx_n_s_chrom_2; static PyObject *__pyx_n_s_cline_in_traceback; static PyObject *__pyx_n_s_close; static PyObject *__pyx_n_s_counter; static PyObject *__pyx_n_s_disable_bar; static PyObject *__pyx_n_s_enter; static PyObject *__pyx_n_s_enumerate; static PyObject *__pyx_n_s_estfunc; static PyObject *__pyx_n_s_estimate_readlen; static PyObject *__pyx_n_s_esttype; static PyObject *__pyx_n_s_exit; static PyObject *__pyx_n_s_finish; static PyObject *__pyx_n_s_format; static PyObject *__pyx_n_s_genexpr; static PyObject *__pyx_n_s_getLogger; static PyObject *__pyx_n_s_has_index; static PyObject *__pyx_n_s_i; static PyObject *__pyx_n_s_import; static PyObject *__pyx_n_s_infer_query_length; static PyObject *__pyx_n_s_info; static PyObject *__pyx_n_s_is_duplicate; static PyObject *__pyx_n_s_is_paired; static PyObject *__pyx_n_s_is_read2; static PyObject *__pyx_n_s_is_unmapped; static PyObject *__pyx_n_s_items; static PyObject *__pyx_n_s_k; static PyObject *__pyx_n_s_key; static PyObject *__pyx_n_s_l; static PyObject *__pyx_n_s_length; static PyObject *__pyx_n_s_lengths; static PyObject *__pyx_n_s_logger; static PyObject *__pyx_n_s_logging; static PyObject *__pyx_n_s_main; static PyObject *__pyx_n_s_mapping_quality; static PyObject *__pyx_n_s_mapq; static PyObject *__pyx_n_s_mapq_criteria; static PyObject *__pyx_n_s_max; static PyObject *__pyx_n_s_mean; static PyObject *__pyx_n_s_mean_locals_genexpr; static PyObject *__pyx_n_s_median; static PyObject *__pyx_n_s_min; static PyObject *__pyx_n_s_mode; static PyObject *__pyx_n_s_mode_locals_lambda; static PyObject *__pyx_n_s_name; static PyObject *__pyx_n_s_npaired; static PyObject *__pyx_n_s_nread2; static PyObject *__pyx_n_s_nreads; static PyObject *__pyx_n_s_num; static PyObject *__pyx_n_s_nunmapped; static PyObject *__pyx_n_s_path; static PyObject *__pyx_n_s_pos; static PyObject *__pyx_n_s_progress; static PyObject *__pyx_n_s_pyx_vtable; static PyObject *__pyx_n_s_read; static PyObject *__pyx_n_s_readlen; static PyObject *__pyx_kp_s_reads_were_paired_reads_were_1s; static PyObject *__pyx_n_s_reference_name; static PyObject *__pyx_n_s_reference_start; static PyObject *__pyx_n_s_references; static PyObject *__pyx_n_s_round; static PyObject *__pyx_n_s_send; static PyObject *__pyx_n_s_set_chrom; static PyObject *__pyx_n_s_set_genome; static PyObject *__pyx_n_s_sorted; static PyObject *__pyx_n_s_stream; static PyObject *__pyx_n_s_sum; static PyObject *__pyx_n_s_sum_2; static PyObject *__pyx_n_s_target; static PyObject *__pyx_n_s_test; static PyObject *__pyx_n_s_throw; static PyObject *__pyx_n_s_update; static PyObject *__pyx_n_s_v; static PyObject *__pyx_n_s_values; static PyObject *__pyx_n_s_zip; static PyObject *__pyx_pf_6PyMaSC_4core_7readlen_5_mean_genexpr(PyObject *__pyx_self); /* proto */ static PyObject *__pyx_pf_6PyMaSC_4core_7readlen__mean(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_c); /* proto */ static PyObject *__pyx_pf_6PyMaSC_4core_7readlen_2_median(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_c); /* proto */ static PyObject *__pyx_lambda_funcdef_lambda1(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_x); /* proto */ static PyObject *__pyx_pf_6PyMaSC_4core_7readlen_4_mode(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_c); /* proto */ static PyObject *__pyx_pf_6PyMaSC_4core_7readlen_6estimate_readlen(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_path, PyObject *__pyx_v_esttype, unsigned int __pyx_v_mapq_criteria); /* proto */ static int __pyx_pf_7cpython_5array_5array___getbuffer__(arrayobject *__pyx_v_self, Py_buffer *__pyx_v_info, CYTHON_UNUSED int __pyx_v_flags); /* proto */ static void __pyx_pf_7cpython_5array_5array_2__releasebuffer__(CYTHON_UNUSED arrayobject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ static PyObject *__pyx_tp_new_6PyMaSC_4core_7readlen___pyx_scope_struct___mean(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static PyObject *__pyx_tp_new_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_values = {0, &__pyx_n_s_values, 0, 0, 0}; static PyObject *__pyx_int_0; static PyObject *__pyx_int_1; static PyObject *__pyx_int_2; static PyObject *__pyx_tuple_; static PyObject *__pyx_tuple__2; static PyObject *__pyx_tuple__4; static PyObject *__pyx_tuple__6; static PyObject *__pyx_tuple__8; static PyObject *__pyx_codeobj__3; static PyObject *__pyx_codeobj__5; static PyObject *__pyx_codeobj__7; static PyObject *__pyx_codeobj__9; /* Late includes */ /* "PyMaSC/core/readlen.pyx":11 * * * def _mean(c): # <<<<<<<<<<<<<< * return int(round( * sum(length * freq for length, freq in c.items()) / float(sum(c.values())) */ /* Python wrapper */ static PyObject *__pyx_pw_6PyMaSC_4core_7readlen_1_mean(PyObject *__pyx_self, PyObject *__pyx_v_c); /*proto*/ static PyMethodDef __pyx_mdef_6PyMaSC_4core_7readlen_1_mean = {"_mean", (PyCFunction)__pyx_pw_6PyMaSC_4core_7readlen_1_mean, METH_O, 0}; static PyObject *__pyx_pw_6PyMaSC_4core_7readlen_1_mean(PyObject *__pyx_self, PyObject *__pyx_v_c) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("_mean (wrapper)", 0); __pyx_r = __pyx_pf_6PyMaSC_4core_7readlen__mean(__pyx_self, ((PyObject *)__pyx_v_c)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_gb_6PyMaSC_4core_7readlen_5_mean_2generator(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value); /* proto */ /* "PyMaSC/core/readlen.pyx":13 * def _mean(c): * return int(round( * sum(length * freq for length, freq in c.items()) / float(sum(c.values())) # <<<<<<<<<<<<<< * )) * */ static PyObject *__pyx_pf_6PyMaSC_4core_7readlen_5_mean_genexpr(PyObject *__pyx_self) { struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr *__pyx_cur_scope; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("genexpr", 0); __pyx_cur_scope = (struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr *)__pyx_tp_new_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr(__pyx_ptype_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr, __pyx_empty_tuple, NULL); if (unlikely(!__pyx_cur_scope)) { __pyx_cur_scope = ((struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr *)Py_None); __Pyx_INCREF(Py_None); __PYX_ERR(0, 13, __pyx_L1_error) } else { __Pyx_GOTREF(__pyx_cur_scope); } __pyx_cur_scope->__pyx_outer_scope = (struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct___mean *) __pyx_self; __Pyx_INCREF(((PyObject *)__pyx_cur_scope->__pyx_outer_scope)); __Pyx_GIVEREF(__pyx_cur_scope->__pyx_outer_scope); { __pyx_CoroutineObject *gen = __Pyx_Generator_New((__pyx_coroutine_body_t) __pyx_gb_6PyMaSC_4core_7readlen_5_mean_2generator, NULL, (PyObject *) __pyx_cur_scope, __pyx_n_s_genexpr, __pyx_n_s_mean_locals_genexpr, __pyx_n_s_PyMaSC_core_readlen); if (unlikely(!gen)) __PYX_ERR(0, 13, __pyx_L1_error) __Pyx_DECREF(__pyx_cur_scope); __Pyx_RefNannyFinishContext(); return (PyObject *) gen; } /* function exit code */ __pyx_L1_error:; __Pyx_AddTraceback("PyMaSC.core.readlen._mean.genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __Pyx_DECREF(((PyObject *)__pyx_cur_scope)); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_gb_6PyMaSC_4core_7readlen_5_mean_2generator(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value) /* generator body */ { struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr *__pyx_cur_scope = ((struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr *)__pyx_generator->closure); PyObject *__pyx_r = NULL; PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; Py_ssize_t __pyx_t_4; PyObject *(*__pyx_t_5)(PyObject *); PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *(*__pyx_t_8)(PyObject *); __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("genexpr", 0); switch (__pyx_generator->resume_label) { case 0: goto __pyx_L3_first_run; case 1: goto __pyx_L8_resume_from_yield; default: /* CPython raises the right error here */ __Pyx_RefNannyFinishContext(); return NULL; } __pyx_L3_first_run:; if (unlikely(!__pyx_sent_value)) __PYX_ERR(0, 13, __pyx_L1_error) if (unlikely(!__pyx_cur_scope->__pyx_outer_scope->__pyx_v_c)) { __Pyx_RaiseClosureNameError("c"); __PYX_ERR(0, 13, __pyx_L1_error) } __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_cur_scope->__pyx_outer_scope->__pyx_v_c, __pyx_n_s_items); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_2))) { __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); if (likely(__pyx_t_3)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_2, function); } } __pyx_t_1 = (__pyx_t_3) ? __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3) : __Pyx_PyObject_CallNoArg(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (likely(PyList_CheckExact(__pyx_t_1)) || PyTuple_CheckExact(__pyx_t_1)) { __pyx_t_2 = __pyx_t_1; __Pyx_INCREF(__pyx_t_2); __pyx_t_4 = 0; __pyx_t_5 = NULL; } else { __pyx_t_4 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_5 = Py_TYPE(__pyx_t_2)->tp_iternext; if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 13, __pyx_L1_error) } __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; for (;;) { if (likely(!__pyx_t_5)) { if (likely(PyList_CheckExact(__pyx_t_2))) { if (__pyx_t_4 >= PyList_GET_SIZE(__pyx_t_2)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_1 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_4); __Pyx_INCREF(__pyx_t_1); __pyx_t_4++; if (unlikely(0 < 0)) __PYX_ERR(0, 13, __pyx_L1_error) #else __pyx_t_1 = PySequence_ITEM(__pyx_t_2, __pyx_t_4); __pyx_t_4++; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); #endif } else { if (__pyx_t_4 >= PyTuple_GET_SIZE(__pyx_t_2)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_1 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_4); __Pyx_INCREF(__pyx_t_1); __pyx_t_4++; if (unlikely(0 < 0)) __PYX_ERR(0, 13, __pyx_L1_error) #else __pyx_t_1 = PySequence_ITEM(__pyx_t_2, __pyx_t_4); __pyx_t_4++; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); #endif } } else { __pyx_t_1 = __pyx_t_5(__pyx_t_2); if (unlikely(!__pyx_t_1)) { PyObject* exc_type = PyErr_Occurred(); if (exc_type) { if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else __PYX_ERR(0, 13, __pyx_L1_error) } break; } __Pyx_GOTREF(__pyx_t_1); } if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { PyObject* sequence = __pyx_t_1; Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); __PYX_ERR(0, 13, __pyx_L1_error) } #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS if (likely(PyTuple_CheckExact(sequence))) { __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_6 = PyTuple_GET_ITEM(sequence, 1); } else { __pyx_t_3 = PyList_GET_ITEM(sequence, 0); __pyx_t_6 = PyList_GET_ITEM(sequence, 1); } __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx_t_6); #else __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_6 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); #endif __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } else { Py_ssize_t index = -1; __pyx_t_7 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_8 = Py_TYPE(__pyx_t_7)->tp_iternext; index = 0; __pyx_t_3 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_3)) goto __pyx_L6_unpacking_failed; __Pyx_GOTREF(__pyx_t_3); index = 1; __pyx_t_6 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_6)) goto __pyx_L6_unpacking_failed; __Pyx_GOTREF(__pyx_t_6); if (__Pyx_IternextUnpackEndCheck(__pyx_t_8(__pyx_t_7), 2) < 0) __PYX_ERR(0, 13, __pyx_L1_error) __pyx_t_8 = NULL; __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; goto __pyx_L7_unpacking_done; __pyx_L6_unpacking_failed:; __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __pyx_t_8 = NULL; if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); __PYX_ERR(0, 13, __pyx_L1_error) __pyx_L7_unpacking_done:; } __Pyx_XGOTREF(__pyx_cur_scope->__pyx_v_length); __Pyx_XDECREF_SET(__pyx_cur_scope->__pyx_v_length, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_XGOTREF(__pyx_cur_scope->__pyx_v_freq); __Pyx_XDECREF_SET(__pyx_cur_scope->__pyx_v_freq, __pyx_t_6); __Pyx_GIVEREF(__pyx_t_6); __pyx_t_6 = 0; __pyx_t_1 = PyNumber_Multiply(__pyx_cur_scope->__pyx_v_length, __pyx_cur_scope->__pyx_v_freq); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; __Pyx_XGIVEREF(__pyx_t_2); __pyx_cur_scope->__pyx_t_0 = __pyx_t_2; __pyx_cur_scope->__pyx_t_1 = __pyx_t_4; __pyx_cur_scope->__pyx_t_2 = __pyx_t_5; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); __Pyx_Coroutine_ResetAndClearException(__pyx_generator); /* return from generator, yielding value */ __pyx_generator->resume_label = 1; return __pyx_r; __pyx_L8_resume_from_yield:; __pyx_t_2 = __pyx_cur_scope->__pyx_t_0; __pyx_cur_scope->__pyx_t_0 = 0; __Pyx_XGOTREF(__pyx_t_2); __pyx_t_4 = __pyx_cur_scope->__pyx_t_1; __pyx_t_5 = __pyx_cur_scope->__pyx_t_2; if (unlikely(!__pyx_sent_value)) __PYX_ERR(0, 13, __pyx_L1_error) } __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; CYTHON_MAYBE_UNUSED_VAR(__pyx_cur_scope); /* function exit code */ PyErr_SetNone(PyExc_StopIteration); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_AddTraceback("genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_L0:; __Pyx_XDECREF(__pyx_r); __pyx_r = 0; #if !CYTHON_USE_EXC_INFO_STACK __Pyx_Coroutine_ResetAndClearException(__pyx_generator); #endif __pyx_generator->resume_label = -1; __Pyx_Coroutine_clear((PyObject*)__pyx_generator); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "PyMaSC/core/readlen.pyx":11 * * * def _mean(c): # <<<<<<<<<<<<<< * return int(round( * sum(length * freq for length, freq in c.items()) / float(sum(c.values())) */ static PyObject *__pyx_pf_6PyMaSC_4core_7readlen__mean(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_c) { struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct___mean *__pyx_cur_scope; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; __Pyx_RefNannySetupContext("_mean", 0); __pyx_cur_scope = (struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct___mean *)__pyx_tp_new_6PyMaSC_4core_7readlen___pyx_scope_struct___mean(__pyx_ptype_6PyMaSC_4core_7readlen___pyx_scope_struct___mean, __pyx_empty_tuple, NULL); if (unlikely(!__pyx_cur_scope)) { __pyx_cur_scope = ((struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct___mean *)Py_None); __Pyx_INCREF(Py_None); __PYX_ERR(0, 11, __pyx_L1_error) } else { __Pyx_GOTREF(__pyx_cur_scope); } __pyx_cur_scope->__pyx_v_c = __pyx_v_c; __Pyx_INCREF(__pyx_cur_scope->__pyx_v_c); __Pyx_GIVEREF(__pyx_cur_scope->__pyx_v_c); /* "PyMaSC/core/readlen.pyx":12 * * def _mean(c): * return int(round( # <<<<<<<<<<<<<< * sum(length * freq for length, freq in c.items()) / float(sum(c.values())) * )) */ __Pyx_XDECREF(__pyx_r); /* "PyMaSC/core/readlen.pyx":13 * def _mean(c): * return int(round( * sum(length * freq for length, freq in c.items()) / float(sum(c.values())) # <<<<<<<<<<<<<< * )) * */ __pyx_t_1 = __pyx_pf_6PyMaSC_4core_7readlen_5_mean_genexpr(((PyObject*)__pyx_cur_scope)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_builtin_sum, __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_cur_scope->__pyx_v_c, __pyx_n_s_values); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_3))) { __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); if (likely(__pyx_t_4)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_3, function); } } __pyx_t_1 = (__pyx_t_4) ? __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4) : __Pyx_PyObject_CallNoArg(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_builtin_sum, __pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyNumber_Float(__pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyNumber_Divide(__pyx_t_2, __pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "PyMaSC/core/readlen.pyx":12 * * def _mean(c): * return int(round( # <<<<<<<<<<<<<< * sum(length * freq for length, freq in c.items()) / float(sum(c.values())) * )) */ __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_builtin_round, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 12, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyNumber_Int(__pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 12, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; /* "PyMaSC/core/readlen.pyx":11 * * * def _mean(c): # <<<<<<<<<<<<<< * return int(round( * sum(length * freq for length, freq in c.items()) / float(sum(c.values())) */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("PyMaSC.core.readlen._mean", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_DECREF(((PyObject *)__pyx_cur_scope)); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "PyMaSC/core/readlen.pyx":17 * * * def _median(c): # <<<<<<<<<<<<<< * num = sum(c.values()) * target = num / 2 */ /* Python wrapper */ static PyObject *__pyx_pw_6PyMaSC_4core_7readlen_3_median(PyObject *__pyx_self, PyObject *__pyx_v_c); /*proto*/ static PyMethodDef __pyx_mdef_6PyMaSC_4core_7readlen_3_median = {"_median", (PyCFunction)__pyx_pw_6PyMaSC_4core_7readlen_3_median, METH_O, 0}; static PyObject *__pyx_pw_6PyMaSC_4core_7readlen_3_median(PyObject *__pyx_self, PyObject *__pyx_v_c) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("_median (wrapper)", 0); __pyx_r = __pyx_pf_6PyMaSC_4core_7readlen_2_median(__pyx_self, ((PyObject *)__pyx_v_c)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_6PyMaSC_4core_7readlen_2_median(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_c) { PyObject *__pyx_v_num = NULL; PyObject *__pyx_v_target = NULL; PyObject *__pyx_v__sum = NULL; PyObject *__pyx_v_l = NULL; PyObject *__pyx_v_length = NULL; PyObject *__pyx_v_i = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; int __pyx_t_5; Py_ssize_t __pyx_t_6; PyObject *__pyx_t_7 = NULL; __Pyx_RefNannySetupContext("_median", 0); /* "PyMaSC/core/readlen.pyx":18 * * def _median(c): * num = sum(c.values()) # <<<<<<<<<<<<<< * target = num / 2 * _sum = 0 */ __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_c, __pyx_n_s_values); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 18, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_2))) { __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); if (likely(__pyx_t_3)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_2, function); } } __pyx_t_1 = (__pyx_t_3) ? __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3) : __Pyx_PyObject_CallNoArg(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 18, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_builtin_sum, __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 18, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_v_num = __pyx_t_2; __pyx_t_2 = 0; /* "PyMaSC/core/readlen.pyx":19 * def _median(c): * num = sum(c.values()) * target = num / 2 # <<<<<<<<<<<<<< * _sum = 0 * */ __pyx_t_2 = __Pyx_PyNumber_Divide(__pyx_v_num, __pyx_int_2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 19, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_v_target = __pyx_t_2; __pyx_t_2 = 0; /* "PyMaSC/core/readlen.pyx":20 * num = sum(c.values()) * target = num / 2 * _sum = 0 # <<<<<<<<<<<<<< * * if num % 2: */ __Pyx_INCREF(__pyx_int_0); __pyx_v__sum = __pyx_int_0; /* "PyMaSC/core/readlen.pyx":22 * _sum = 0 * * if num % 2: # <<<<<<<<<<<<<< * for l in sorted(c): * _sum += c[l] */ __pyx_t_2 = __Pyx_PyInt_RemainderObjC(__pyx_v_num, __pyx_int_2, 2, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 22, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(0, 22, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_4) { /* "PyMaSC/core/readlen.pyx":23 * * if num % 2: * for l in sorted(c): # <<<<<<<<<<<<<< * _sum += c[l] * if target <= _sum: */ __pyx_t_1 = PySequence_List(__pyx_v_c); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 23, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = ((PyObject*)__pyx_t_1); __pyx_t_1 = 0; __pyx_t_5 = PyList_Sort(__pyx_t_2); if (unlikely(__pyx_t_5 == ((int)-1))) __PYX_ERR(0, 23, __pyx_L1_error) if (unlikely(__pyx_t_2 == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); __PYX_ERR(0, 23, __pyx_L1_error) } __pyx_t_1 = __pyx_t_2; __Pyx_INCREF(__pyx_t_1); __pyx_t_6 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; for (;;) { if (__pyx_t_6 >= PyList_GET_SIZE(__pyx_t_1)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_2 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_6); __Pyx_INCREF(__pyx_t_2); __pyx_t_6++; if (unlikely(0 < 0)) __PYX_ERR(0, 23, __pyx_L1_error) #else __pyx_t_2 = PySequence_ITEM(__pyx_t_1, __pyx_t_6); __pyx_t_6++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 23, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); #endif __Pyx_XDECREF_SET(__pyx_v_l, __pyx_t_2); __pyx_t_2 = 0; /* "PyMaSC/core/readlen.pyx":24 * if num % 2: * for l in sorted(c): * _sum += c[l] # <<<<<<<<<<<<<< * if target <= _sum: * return l */ __pyx_t_2 = __Pyx_PyObject_GetItem(__pyx_v_c, __pyx_v_l); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 24, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyNumber_InPlaceAdd(__pyx_v__sum, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 24, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF_SET(__pyx_v__sum, __pyx_t_3); __pyx_t_3 = 0; /* "PyMaSC/core/readlen.pyx":25 * for l in sorted(c): * _sum += c[l] * if target <= _sum: # <<<<<<<<<<<<<< * return l * else: */ __pyx_t_3 = PyObject_RichCompare(__pyx_v_target, __pyx_v__sum, Py_LE); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 25, __pyx_L1_error) __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(0, 25, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_4) { /* "PyMaSC/core/readlen.pyx":26 * _sum += c[l] * if target <= _sum: * return l # <<<<<<<<<<<<<< * else: * length = sorted(c) */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_l); __pyx_r = __pyx_v_l; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; goto __pyx_L0; /* "PyMaSC/core/readlen.pyx":25 * for l in sorted(c): * _sum += c[l] * if target <= _sum: # <<<<<<<<<<<<<< * return l * else: */ } /* "PyMaSC/core/readlen.pyx":23 * * if num % 2: * for l in sorted(c): # <<<<<<<<<<<<<< * _sum += c[l] * if target <= _sum: */ } __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "PyMaSC/core/readlen.pyx":22 * _sum = 0 * * if num % 2: # <<<<<<<<<<<<<< * for l in sorted(c): * _sum += c[l] */ goto __pyx_L3; } /* "PyMaSC/core/readlen.pyx":28 * return l * else: * length = sorted(c) # <<<<<<<<<<<<<< * for i, l in enumerate(length): * _sum += c[l] */ /*else*/ { __pyx_t_3 = PySequence_List(__pyx_v_c); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 28, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_1 = ((PyObject*)__pyx_t_3); __pyx_t_3 = 0; __pyx_t_5 = PyList_Sort(__pyx_t_1); if (unlikely(__pyx_t_5 == ((int)-1))) __PYX_ERR(0, 28, __pyx_L1_error) __pyx_v_length = ((PyObject*)__pyx_t_1); __pyx_t_1 = 0; /* "PyMaSC/core/readlen.pyx":29 * else: * length = sorted(c) * for i, l in enumerate(length): # <<<<<<<<<<<<<< * _sum += c[l] * if target < _sum: */ __Pyx_INCREF(__pyx_int_0); __pyx_t_1 = __pyx_int_0; __pyx_t_3 = __pyx_v_length; __Pyx_INCREF(__pyx_t_3); __pyx_t_6 = 0; for (;;) { if (__pyx_t_6 >= PyList_GET_SIZE(__pyx_t_3)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_2 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_6); __Pyx_INCREF(__pyx_t_2); __pyx_t_6++; if (unlikely(0 < 0)) __PYX_ERR(0, 29, __pyx_L1_error) #else __pyx_t_2 = PySequence_ITEM(__pyx_t_3, __pyx_t_6); __pyx_t_6++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 29, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); #endif __Pyx_XDECREF_SET(__pyx_v_l, __pyx_t_2); __pyx_t_2 = 0; __Pyx_INCREF(__pyx_t_1); __Pyx_XDECREF_SET(__pyx_v_i, __pyx_t_1); __pyx_t_2 = __Pyx_PyInt_AddObjC(__pyx_t_1, __pyx_int_1, 1, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 29, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = __pyx_t_2; __pyx_t_2 = 0; /* "PyMaSC/core/readlen.pyx":30 * length = sorted(c) * for i, l in enumerate(length): * _sum += c[l] # <<<<<<<<<<<<<< * if target < _sum: * return l */ __pyx_t_2 = __Pyx_PyObject_GetItem(__pyx_v_c, __pyx_v_l); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 30, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_7 = PyNumber_InPlaceAdd(__pyx_v__sum, __pyx_t_2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 30, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF_SET(__pyx_v__sum, __pyx_t_7); __pyx_t_7 = 0; /* "PyMaSC/core/readlen.pyx":31 * for i, l in enumerate(length): * _sum += c[l] * if target < _sum: # <<<<<<<<<<<<<< * return l * elif target == _sum: */ __pyx_t_7 = PyObject_RichCompare(__pyx_v_target, __pyx_v__sum, Py_LT); __Pyx_XGOTREF(__pyx_t_7); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 31, __pyx_L1_error) __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_7); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(0, 31, __pyx_L1_error) __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; if (__pyx_t_4) { /* "PyMaSC/core/readlen.pyx":32 * _sum += c[l] * if target < _sum: * return l # <<<<<<<<<<<<<< * elif target == _sum: * return int(round((l + float(length[i+1])) / 2)) */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_l); __pyx_r = __pyx_v_l; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L0; /* "PyMaSC/core/readlen.pyx":31 * for i, l in enumerate(length): * _sum += c[l] * if target < _sum: # <<<<<<<<<<<<<< * return l * elif target == _sum: */ } /* "PyMaSC/core/readlen.pyx":33 * if target < _sum: * return l * elif target == _sum: # <<<<<<<<<<<<<< * return int(round((l + float(length[i+1])) / 2)) * */ __pyx_t_7 = PyObject_RichCompare(__pyx_v_target, __pyx_v__sum, Py_EQ); __Pyx_XGOTREF(__pyx_t_7); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 33, __pyx_L1_error) __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_7); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; if (__pyx_t_4) { /* "PyMaSC/core/readlen.pyx":34 * return l * elif target == _sum: * return int(round((l + float(length[i+1])) / 2)) # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); if (unlikely(__pyx_v_length == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); __PYX_ERR(0, 34, __pyx_L1_error) } __pyx_t_7 = __Pyx_PyInt_AddObjC(__pyx_v_i, __pyx_int_1, 1, 0); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 34, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __pyx_t_2 = __Pyx_PyObject_GetItem(__pyx_v_length, __pyx_t_7); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 34, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __pyx_t_7 = __Pyx_PyNumber_Float(__pyx_t_2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 34, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyNumber_Add(__pyx_v_l, __pyx_t_7); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 34, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __pyx_t_7 = __Pyx_PyNumber_Divide(__pyx_t_2, __pyx_int_2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 34, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_builtin_round, __pyx_t_7); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 34, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __pyx_t_7 = __Pyx_PyNumber_Int(__pyx_t_2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 34, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_r = __pyx_t_7; __pyx_t_7 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L0; /* "PyMaSC/core/readlen.pyx":33 * if target < _sum: * return l * elif target == _sum: # <<<<<<<<<<<<<< * return int(round((l + float(length[i+1])) / 2)) * */ } /* "PyMaSC/core/readlen.pyx":29 * else: * length = sorted(c) * for i, l in enumerate(length): # <<<<<<<<<<<<<< * _sum += c[l] * if target < _sum: */ } __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } __pyx_L3:; /* "PyMaSC/core/readlen.pyx":17 * * * def _median(c): # <<<<<<<<<<<<<< * num = sum(c.values()) * target = num / 2 */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_7); __Pyx_AddTraceback("PyMaSC.core.readlen._median", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_num); __Pyx_XDECREF(__pyx_v_target); __Pyx_XDECREF(__pyx_v__sum); __Pyx_XDECREF(__pyx_v_l); __Pyx_XDECREF(__pyx_v_length); __Pyx_XDECREF(__pyx_v_i); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "PyMaSC/core/readlen.pyx":37 * * * def _mode(c): # <<<<<<<<<<<<<< * return [k for k, v in sorted(c.items(), key=lambda x: x[1])][-1] * */ /* Python wrapper */ static PyObject *__pyx_pw_6PyMaSC_4core_7readlen_5_mode(PyObject *__pyx_self, PyObject *__pyx_v_c); /*proto*/ static PyMethodDef __pyx_mdef_6PyMaSC_4core_7readlen_5_mode = {"_mode", (PyCFunction)__pyx_pw_6PyMaSC_4core_7readlen_5_mode, METH_O, 0}; static PyObject *__pyx_pw_6PyMaSC_4core_7readlen_5_mode(PyObject *__pyx_self, PyObject *__pyx_v_c) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("_mode (wrapper)", 0); __pyx_r = __pyx_pf_6PyMaSC_4core_7readlen_4_mode(__pyx_self, ((PyObject *)__pyx_v_c)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "PyMaSC/core/readlen.pyx":38 * * def _mode(c): * return [k for k, v in sorted(c.items(), key=lambda x: x[1])][-1] # <<<<<<<<<<<<<< * * */ /* Python wrapper */ static PyObject *__pyx_pw_6PyMaSC_4core_7readlen_5_mode_lambda1(PyObject *__pyx_self, PyObject *__pyx_v_x); /*proto*/ static PyMethodDef __pyx_mdef_6PyMaSC_4core_7readlen_5_mode_lambda1 = {"lambda1", (PyCFunction)__pyx_pw_6PyMaSC_4core_7readlen_5_mode_lambda1, METH_O, 0}; static PyObject *__pyx_pw_6PyMaSC_4core_7readlen_5_mode_lambda1(PyObject *__pyx_self, PyObject *__pyx_v_x) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("lambda1 (wrapper)", 0); __pyx_r = __pyx_lambda_funcdef_lambda1(__pyx_self, ((PyObject *)__pyx_v_x)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_lambda_funcdef_lambda1(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_x) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("lambda1", 0); __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_x, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 38, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("PyMaSC.core.readlen._mode.lambda1", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "PyMaSC/core/readlen.pyx":37 * * * def _mode(c): # <<<<<<<<<<<<<< * return [k for k, v in sorted(c.items(), key=lambda x: x[1])][-1] * */ static PyObject *__pyx_pf_6PyMaSC_4core_7readlen_4_mode(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_c) { PyObject *__pyx_v_k = NULL; CYTHON_UNUSED PyObject *__pyx_v_v = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; Py_ssize_t __pyx_t_5; PyObject *(*__pyx_t_6)(PyObject *); PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; PyObject *(*__pyx_t_9)(PyObject *); __Pyx_RefNannySetupContext("_mode", 0); /* "PyMaSC/core/readlen.pyx":38 * * def _mode(c): * return [k for k, v in sorted(c.items(), key=lambda x: x[1])][-1] # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 38, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_c, __pyx_n_s_items); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 38, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_3))) { __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); if (likely(__pyx_t_4)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_3, function); } } __pyx_t_2 = (__pyx_t_4) ? __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4) : __Pyx_PyObject_CallNoArg(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 38, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 38, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 38, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = __Pyx_CyFunction_NewEx(&__pyx_mdef_6PyMaSC_4core_7readlen_5_mode_lambda1, 0, __pyx_n_s_mode_locals_lambda, NULL, __pyx_n_s_PyMaSC_core_readlen, __pyx_d, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 38, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_key, __pyx_t_4) < 0) __PYX_ERR(0, 38, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_sorted, __pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 38, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (likely(PyList_CheckExact(__pyx_t_4)) || PyTuple_CheckExact(__pyx_t_4)) { __pyx_t_2 = __pyx_t_4; __Pyx_INCREF(__pyx_t_2); __pyx_t_5 = 0; __pyx_t_6 = NULL; } else { __pyx_t_5 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_t_4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 38, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_6 = Py_TYPE(__pyx_t_2)->tp_iternext; if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 38, __pyx_L1_error) } __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; for (;;) { if (likely(!__pyx_t_6)) { if (likely(PyList_CheckExact(__pyx_t_2))) { if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_2)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_4 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_5); __Pyx_INCREF(__pyx_t_4); __pyx_t_5++; if (unlikely(0 < 0)) __PYX_ERR(0, 38, __pyx_L1_error) #else __pyx_t_4 = PySequence_ITEM(__pyx_t_2, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 38, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); #endif } else { if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_2)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_4 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_5); __Pyx_INCREF(__pyx_t_4); __pyx_t_5++; if (unlikely(0 < 0)) __PYX_ERR(0, 38, __pyx_L1_error) #else __pyx_t_4 = PySequence_ITEM(__pyx_t_2, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 38, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); #endif } } else { __pyx_t_4 = __pyx_t_6(__pyx_t_2); if (unlikely(!__pyx_t_4)) { PyObject* exc_type = PyErr_Occurred(); if (exc_type) { if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else __PYX_ERR(0, 38, __pyx_L1_error) } break; } __Pyx_GOTREF(__pyx_t_4); } if ((likely(PyTuple_CheckExact(__pyx_t_4))) || (PyList_CheckExact(__pyx_t_4))) { PyObject* sequence = __pyx_t_4; Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); __PYX_ERR(0, 38, __pyx_L1_error) } #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS if (likely(PyTuple_CheckExact(sequence))) { __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_7 = PyTuple_GET_ITEM(sequence, 1); } else { __pyx_t_3 = PyList_GET_ITEM(sequence, 0); __pyx_t_7 = PyList_GET_ITEM(sequence, 1); } __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx_t_7); #else __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 38, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_7 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 38, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); #endif __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; } else { Py_ssize_t index = -1; __pyx_t_8 = PyObject_GetIter(__pyx_t_4); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 38, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_9 = Py_TYPE(__pyx_t_8)->tp_iternext; index = 0; __pyx_t_3 = __pyx_t_9(__pyx_t_8); if (unlikely(!__pyx_t_3)) goto __pyx_L5_unpacking_failed; __Pyx_GOTREF(__pyx_t_3); index = 1; __pyx_t_7 = __pyx_t_9(__pyx_t_8); if (unlikely(!__pyx_t_7)) goto __pyx_L5_unpacking_failed; __Pyx_GOTREF(__pyx_t_7); if (__Pyx_IternextUnpackEndCheck(__pyx_t_9(__pyx_t_8), 2) < 0) __PYX_ERR(0, 38, __pyx_L1_error) __pyx_t_9 = NULL; __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; goto __pyx_L6_unpacking_done; __pyx_L5_unpacking_failed:; __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __pyx_t_9 = NULL; if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); __PYX_ERR(0, 38, __pyx_L1_error) __pyx_L6_unpacking_done:; } __Pyx_XDECREF_SET(__pyx_v_k, __pyx_t_3); __pyx_t_3 = 0; __Pyx_XDECREF_SET(__pyx_v_v, __pyx_t_7); __pyx_t_7 = 0; if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_v_k))) __PYX_ERR(0, 38, __pyx_L1_error) } __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_GetItemInt_List(__pyx_t_1, -1L, long, 1, __Pyx_PyInt_From_long, 1, 1, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 38, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "PyMaSC/core/readlen.pyx":37 * * * def _mode(c): # <<<<<<<<<<<<<< * return [k for k, v in sorted(c.items(), key=lambda x: x[1])][-1] * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("PyMaSC.core.readlen._mode", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_k); __Pyx_XDECREF(__pyx_v_v); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "PyMaSC/core/readlen.pyx":46 * * * def estimate_readlen(path, esttype, unsigned int mapq_criteria): # <<<<<<<<<<<<<< * estfunc = ESTFUNCTIONS[esttype] * */ /* Python wrapper */ static PyObject *__pyx_pw_6PyMaSC_4core_7readlen_7estimate_readlen(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyMethodDef __pyx_mdef_6PyMaSC_4core_7readlen_7estimate_readlen = {"estimate_readlen", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_6PyMaSC_4core_7readlen_7estimate_readlen, METH_VARARGS|METH_KEYWORDS, 0}; static PyObject *__pyx_pw_6PyMaSC_4core_7readlen_7estimate_readlen(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_path = 0; PyObject *__pyx_v_esttype = 0; unsigned int __pyx_v_mapq_criteria; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("estimate_readlen (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_path,&__pyx_n_s_esttype,&__pyx_n_s_mapq_criteria,0}; PyObject* values[3] = {0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_path)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_esttype)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("estimate_readlen", 1, 3, 3, 1); __PYX_ERR(0, 46, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_mapq_criteria)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("estimate_readlen", 1, 3, 3, 2); __PYX_ERR(0, 46, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "estimate_readlen") < 0)) __PYX_ERR(0, 46, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); } __pyx_v_path = values[0]; __pyx_v_esttype = values[1]; __pyx_v_mapq_criteria = __Pyx_PyInt_As_unsigned_int(values[2]); if (unlikely((__pyx_v_mapq_criteria == (unsigned int)-1) && PyErr_Occurred())) __PYX_ERR(0, 46, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("estimate_readlen", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 46, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("PyMaSC.core.readlen.estimate_readlen", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_6PyMaSC_4core_7readlen_6estimate_readlen(__pyx_self, __pyx_v_path, __pyx_v_esttype, __pyx_v_mapq_criteria); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_6PyMaSC_4core_7readlen_6estimate_readlen(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_path, PyObject *__pyx_v_esttype, unsigned int __pyx_v_mapq_criteria) { PyObject *__pyx_v_estfunc = NULL; PyObject *__pyx_v_chrom = 0; PyObject *__pyx_v__chrom = 0; unsigned long __pyx_v_readlen; PyObject *__pyx_v_counter = 0; PyObject *__pyx_v_chrom2length = 0; unsigned long __pyx_v_length; struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *__pyx_v_read = 0; unsigned long __pyx_v_nreads; unsigned long __pyx_v_nunmapped; unsigned long __pyx_v_npaired; unsigned long __pyx_v_nread2; PyObject *__pyx_v_stream = NULL; PyObject *__pyx_v_progress = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; unsigned long __pyx_t_9; int __pyx_t_10; int __pyx_t_11; Py_ssize_t __pyx_t_12; PyObject *(*__pyx_t_13)(PyObject *); PyObject *__pyx_t_14 = NULL; int __pyx_t_15; PyObject *__pyx_t_16 = NULL; int __pyx_t_17; PyObject *__pyx_t_18 = NULL; PyObject *__pyx_t_19 = NULL; PyObject *__pyx_t_20 = NULL; PyObject *__pyx_t_21 = NULL; PyObject *__pyx_t_22 = NULL; __Pyx_RefNannySetupContext("estimate_readlen", 0); /* "PyMaSC/core/readlen.pyx":47 * * def estimate_readlen(path, esttype, unsigned int mapq_criteria): * estfunc = ESTFUNCTIONS[esttype] # <<<<<<<<<<<<<< * * cdef bint is_duplicate */ __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_ESTFUNCTIONS); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 47, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_GetItem(__pyx_t_1, __pyx_v_esttype); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 47, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_v_estfunc = __pyx_t_2; __pyx_t_2 = 0; /* "PyMaSC/core/readlen.pyx":54 * cdef unsigned long pos, readlen * * cdef dict counter = {} # <<<<<<<<<<<<<< * * cdef dict chrom2length */ __pyx_t_2 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 54, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_v_counter = ((PyObject*)__pyx_t_2); __pyx_t_2 = 0; /* "PyMaSC/core/readlen.pyx":60 * cdef AlignedSegment read * * cdef unsigned long nreads = 0 # <<<<<<<<<<<<<< * cdef unsigned long nunmapped = 0 * cdef unsigned long npaired = 0 */ __pyx_v_nreads = 0; /* "PyMaSC/core/readlen.pyx":61 * * cdef unsigned long nreads = 0 * cdef unsigned long nunmapped = 0 # <<<<<<<<<<<<<< * cdef unsigned long npaired = 0 * cdef unsigned long nread2 = 0 */ __pyx_v_nunmapped = 0; /* "PyMaSC/core/readlen.pyx":62 * cdef unsigned long nreads = 0 * cdef unsigned long nunmapped = 0 * cdef unsigned long npaired = 0 # <<<<<<<<<<<<<< * cdef unsigned long nread2 = 0 * */ __pyx_v_npaired = 0; /* "PyMaSC/core/readlen.pyx":63 * cdef unsigned long nunmapped = 0 * cdef unsigned long npaired = 0 * cdef unsigned long nread2 = 0 # <<<<<<<<<<<<<< * * with AlignmentFile(path) as stream: */ __pyx_v_nread2 = 0; /* "PyMaSC/core/readlen.pyx":65 * cdef unsigned long nread2 = 0 * * with AlignmentFile(path) as stream: # <<<<<<<<<<<<<< * chrom = None * chrom2length = dict(zip(stream.references, stream.lengths)) */ /*with:*/ { __pyx_t_2 = __Pyx_PyObject_CallOneArg(((PyObject *)__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile), __pyx_v_path); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 65, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_LookupSpecial(__pyx_t_2, __pyx_n_s_exit); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 65, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = __Pyx_PyObject_LookupSpecial(__pyx_t_2, __pyx_n_s_enter); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 65, __pyx_L3_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_4))) { __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_4); if (likely(__pyx_t_5)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); __Pyx_INCREF(__pyx_t_5); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_4, function); } } __pyx_t_1 = (__pyx_t_5) ? __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_5) : __Pyx_PyObject_CallNoArg(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 65, __pyx_L3_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = __pyx_t_1; __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /*try:*/ { { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ExceptionSave(&__pyx_t_6, &__pyx_t_7, &__pyx_t_8); __Pyx_XGOTREF(__pyx_t_6); __Pyx_XGOTREF(__pyx_t_7); __Pyx_XGOTREF(__pyx_t_8); /*try:*/ { __pyx_v_stream = __pyx_t_4; __pyx_t_4 = 0; /* "PyMaSC/core/readlen.pyx":66 * * with AlignmentFile(path) as stream: * chrom = None # <<<<<<<<<<<<<< * chrom2length = dict(zip(stream.references, stream.lengths)) * length = sum(chrom2length.values()) */ __Pyx_INCREF(Py_None); __pyx_v_chrom = ((PyObject*)Py_None); /* "PyMaSC/core/readlen.pyx":67 * with AlignmentFile(path) as stream: * chrom = None * chrom2length = dict(zip(stream.references, stream.lengths)) # <<<<<<<<<<<<<< * length = sum(chrom2length.values()) * */ __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_stream, __pyx_n_s_references); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 67, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_stream, __pyx_n_s_lengths); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 67, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 67, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_2); __pyx_t_4 = 0; __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_1, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 67, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyObject_CallOneArg(((PyObject *)(&PyDict_Type)), __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 67, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_v_chrom2length = ((PyObject*)__pyx_t_1); __pyx_t_1 = 0; /* "PyMaSC/core/readlen.pyx":68 * chrom = None * chrom2length = dict(zip(stream.references, stream.lengths)) * length = sum(chrom2length.values()) # <<<<<<<<<<<<<< * * progress = ReadCountProgressBar() */ __pyx_t_1 = __Pyx_PyDict_Values(__pyx_v_chrom2length); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 68, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_builtin_sum, __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 68, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_9 = __Pyx_PyInt_As_unsigned_long(__pyx_t_2); if (unlikely((__pyx_t_9 == (unsigned long)-1) && PyErr_Occurred())) __PYX_ERR(0, 68, __pyx_L7_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_v_length = __pyx_t_9; /* "PyMaSC/core/readlen.pyx":70 * length = sum(chrom2length.values()) * * progress = ReadCountProgressBar() # <<<<<<<<<<<<<< * if not stream.has_index(): * progress.disable_bar() */ __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_ReadCountProgressBar); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 70, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_4 = NULL; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_1))) { __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_1); if (likely(__pyx_t_4)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_1, function); } } __pyx_t_2 = (__pyx_t_4) ? __Pyx_PyObject_CallOneArg(__pyx_t_1, __pyx_t_4) : __Pyx_PyObject_CallNoArg(__pyx_t_1); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 70, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_v_progress = __pyx_t_2; __pyx_t_2 = 0; /* "PyMaSC/core/readlen.pyx":71 * * progress = ReadCountProgressBar() * if not stream.has_index(): # <<<<<<<<<<<<<< * progress.disable_bar() * progress.set_genome(length) */ __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_stream, __pyx_n_s_has_index); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 71, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_4 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_1))) { __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_1); if (likely(__pyx_t_4)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_1, function); } } __pyx_t_2 = (__pyx_t_4) ? __Pyx_PyObject_CallOneArg(__pyx_t_1, __pyx_t_4) : __Pyx_PyObject_CallNoArg(__pyx_t_1); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 71, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_10 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_10 < 0)) __PYX_ERR(0, 71, __pyx_L7_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_11 = ((!__pyx_t_10) != 0); if (__pyx_t_11) { /* "PyMaSC/core/readlen.pyx":72 * progress = ReadCountProgressBar() * if not stream.has_index(): * progress.disable_bar() # <<<<<<<<<<<<<< * progress.set_genome(length) * */ __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_progress, __pyx_n_s_disable_bar); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 72, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_4 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_1))) { __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_1); if (likely(__pyx_t_4)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_1, function); } } __pyx_t_2 = (__pyx_t_4) ? __Pyx_PyObject_CallOneArg(__pyx_t_1, __pyx_t_4) : __Pyx_PyObject_CallNoArg(__pyx_t_1); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 72, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "PyMaSC/core/readlen.pyx":71 * * progress = ReadCountProgressBar() * if not stream.has_index(): # <<<<<<<<<<<<<< * progress.disable_bar() * progress.set_genome(length) */ } /* "PyMaSC/core/readlen.pyx":73 * if not stream.has_index(): * progress.disable_bar() * progress.set_genome(length) # <<<<<<<<<<<<<< * * for read in stream: */ __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_progress, __pyx_n_s_set_genome); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 73, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_4 = __Pyx_PyInt_From_unsigned_long(__pyx_v_length); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 73, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_1))) { __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_1); if (likely(__pyx_t_5)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); __Pyx_INCREF(__pyx_t_5); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_1, function); } } __pyx_t_2 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_1, __pyx_t_5, __pyx_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_1, __pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 73, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "PyMaSC/core/readlen.pyx":75 * progress.set_genome(length) * * for read in stream: # <<<<<<<<<<<<<< * _chrom = read.reference_name * if _chrom is None: */ if (likely(PyList_CheckExact(__pyx_v_stream)) || PyTuple_CheckExact(__pyx_v_stream)) { __pyx_t_2 = __pyx_v_stream; __Pyx_INCREF(__pyx_t_2); __pyx_t_12 = 0; __pyx_t_13 = NULL; } else { __pyx_t_12 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_v_stream); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 75, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_13 = Py_TYPE(__pyx_t_2)->tp_iternext; if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 75, __pyx_L7_error) } for (;;) { if (likely(!__pyx_t_13)) { if (likely(PyList_CheckExact(__pyx_t_2))) { if (__pyx_t_12 >= PyList_GET_SIZE(__pyx_t_2)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_1 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_12); __Pyx_INCREF(__pyx_t_1); __pyx_t_12++; if (unlikely(0 < 0)) __PYX_ERR(0, 75, __pyx_L7_error) #else __pyx_t_1 = PySequence_ITEM(__pyx_t_2, __pyx_t_12); __pyx_t_12++; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 75, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_1); #endif } else { if (__pyx_t_12 >= PyTuple_GET_SIZE(__pyx_t_2)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_1 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_12); __Pyx_INCREF(__pyx_t_1); __pyx_t_12++; if (unlikely(0 < 0)) __PYX_ERR(0, 75, __pyx_L7_error) #else __pyx_t_1 = PySequence_ITEM(__pyx_t_2, __pyx_t_12); __pyx_t_12++; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 75, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_1); #endif } } else { __pyx_t_1 = __pyx_t_13(__pyx_t_2); if (unlikely(!__pyx_t_1)) { PyObject* exc_type = PyErr_Occurred(); if (exc_type) { if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else __PYX_ERR(0, 75, __pyx_L7_error) } break; } __Pyx_GOTREF(__pyx_t_1); } if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5pysam_18libcalignedsegment_AlignedSegment))))) __PYX_ERR(0, 75, __pyx_L7_error) __Pyx_XDECREF_SET(__pyx_v_read, ((struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *)__pyx_t_1)); __pyx_t_1 = 0; /* "PyMaSC/core/readlen.pyx":76 * * for read in stream: * _chrom = read.reference_name # <<<<<<<<<<<<<< * if _chrom is None: * continue */ __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_read), __pyx_n_s_reference_name); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 76, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_1); if (!(likely(PyString_CheckExact(__pyx_t_1))||((__pyx_t_1) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "str", Py_TYPE(__pyx_t_1)->tp_name), 0))) __PYX_ERR(0, 76, __pyx_L7_error) __Pyx_XDECREF_SET(__pyx_v__chrom, ((PyObject*)__pyx_t_1)); __pyx_t_1 = 0; /* "PyMaSC/core/readlen.pyx":77 * for read in stream: * _chrom = read.reference_name * if _chrom is None: # <<<<<<<<<<<<<< * continue * */ __pyx_t_11 = (__pyx_v__chrom == ((PyObject*)Py_None)); __pyx_t_10 = (__pyx_t_11 != 0); if (__pyx_t_10) { /* "PyMaSC/core/readlen.pyx":78 * _chrom = read.reference_name * if _chrom is None: * continue # <<<<<<<<<<<<<< * * nreads += 1 */ goto __pyx_L14_continue; /* "PyMaSC/core/readlen.pyx":77 * for read in stream: * _chrom = read.reference_name * if _chrom is None: # <<<<<<<<<<<<<< * continue * */ } /* "PyMaSC/core/readlen.pyx":80 * continue * * nreads += 1 # <<<<<<<<<<<<<< * if read.is_paired: * npaired += 1 */ __pyx_v_nreads = (__pyx_v_nreads + 1); /* "PyMaSC/core/readlen.pyx":81 * * nreads += 1 * if read.is_paired: # <<<<<<<<<<<<<< * npaired += 1 * if read.is_read2: */ __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_read), __pyx_n_s_is_paired); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 81, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_10 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_10 < 0)) __PYX_ERR(0, 81, __pyx_L7_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (__pyx_t_10) { /* "PyMaSC/core/readlen.pyx":82 * nreads += 1 * if read.is_paired: * npaired += 1 # <<<<<<<<<<<<<< * if read.is_read2: * nread2 += 1 */ __pyx_v_npaired = (__pyx_v_npaired + 1); /* "PyMaSC/core/readlen.pyx":83 * if read.is_paired: * npaired += 1 * if read.is_read2: # <<<<<<<<<<<<<< * nread2 += 1 * */ __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_read), __pyx_n_s_is_read2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 83, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_10 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_10 < 0)) __PYX_ERR(0, 83, __pyx_L7_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (__pyx_t_10) { /* "PyMaSC/core/readlen.pyx":84 * npaired += 1 * if read.is_read2: * nread2 += 1 # <<<<<<<<<<<<<< * * if chrom != _chrom: */ __pyx_v_nread2 = (__pyx_v_nread2 + 1); /* "PyMaSC/core/readlen.pyx":83 * if read.is_paired: * npaired += 1 * if read.is_read2: # <<<<<<<<<<<<<< * nread2 += 1 * */ } /* "PyMaSC/core/readlen.pyx":81 * * nreads += 1 * if read.is_paired: # <<<<<<<<<<<<<< * npaired += 1 * if read.is_read2: */ } /* "PyMaSC/core/readlen.pyx":86 * nread2 += 1 * * if chrom != _chrom: # <<<<<<<<<<<<<< * chrom = _chrom * progress.set_chrom(chrom2length[chrom], chrom) */ __pyx_t_10 = (__Pyx_PyString_Equals(__pyx_v_chrom, __pyx_v__chrom, Py_NE)); if (unlikely(__pyx_t_10 < 0)) __PYX_ERR(0, 86, __pyx_L7_error) __pyx_t_11 = (__pyx_t_10 != 0); if (__pyx_t_11) { /* "PyMaSC/core/readlen.pyx":87 * * if chrom != _chrom: * chrom = _chrom # <<<<<<<<<<<<<< * progress.set_chrom(chrom2length[chrom], chrom) * progress.update(read.reference_start) */ __Pyx_INCREF(__pyx_v__chrom); __Pyx_DECREF_SET(__pyx_v_chrom, __pyx_v__chrom); /* "PyMaSC/core/readlen.pyx":88 * if chrom != _chrom: * chrom = _chrom * progress.set_chrom(chrom2length[chrom], chrom) # <<<<<<<<<<<<<< * progress.update(read.reference_start) * */ __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_progress, __pyx_n_s_set_chrom); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 88, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = __Pyx_PyDict_GetItem(__pyx_v_chrom2length, __pyx_v_chrom); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 88, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_14 = NULL; __pyx_t_15 = 0; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_4))) { __pyx_t_14 = PyMethod_GET_SELF(__pyx_t_4); if (likely(__pyx_t_14)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); __Pyx_INCREF(__pyx_t_14); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_4, function); __pyx_t_15 = 1; } } #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_4)) { PyObject *__pyx_temp[3] = {__pyx_t_14, __pyx_t_5, __pyx_v_chrom}; __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_15, 2+__pyx_t_15); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 88, __pyx_L7_error) __Pyx_XDECREF(__pyx_t_14); __pyx_t_14 = 0; __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_4)) { PyObject *__pyx_temp[3] = {__pyx_t_14, __pyx_t_5, __pyx_v_chrom}; __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_15, 2+__pyx_t_15); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 88, __pyx_L7_error) __Pyx_XDECREF(__pyx_t_14); __pyx_t_14 = 0; __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; } else #endif { __pyx_t_16 = PyTuple_New(2+__pyx_t_15); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 88, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_16); if (__pyx_t_14) { __Pyx_GIVEREF(__pyx_t_14); PyTuple_SET_ITEM(__pyx_t_16, 0, __pyx_t_14); __pyx_t_14 = NULL; } __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_16, 0+__pyx_t_15, __pyx_t_5); __Pyx_INCREF(__pyx_v_chrom); __Pyx_GIVEREF(__pyx_v_chrom); PyTuple_SET_ITEM(__pyx_t_16, 1+__pyx_t_15, __pyx_v_chrom); __pyx_t_5 = 0; __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_16, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 88, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; } __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "PyMaSC/core/readlen.pyx":86 * nread2 += 1 * * if chrom != _chrom: # <<<<<<<<<<<<<< * chrom = _chrom * progress.set_chrom(chrom2length[chrom], chrom) */ } /* "PyMaSC/core/readlen.pyx":89 * chrom = _chrom * progress.set_chrom(chrom2length[chrom], chrom) * progress.update(read.reference_start) # <<<<<<<<<<<<<< * * if read.is_unmapped: */ __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_progress, __pyx_n_s_update); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 89, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_16 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_read), __pyx_n_s_reference_start); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 89, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_16); __pyx_t_5 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_4))) { __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_4); if (likely(__pyx_t_5)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); __Pyx_INCREF(__pyx_t_5); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_4, function); } } __pyx_t_1 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_4, __pyx_t_5, __pyx_t_16) : __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_16); __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 89, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "PyMaSC/core/readlen.pyx":91 * progress.update(read.reference_start) * * if read.is_unmapped: # <<<<<<<<<<<<<< * nunmapped += 1 * elif not read.is_duplicate and read.mapping_quality >= mapq_criteria: */ __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_read), __pyx_n_s_is_unmapped); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 91, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_11 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_11 < 0)) __PYX_ERR(0, 91, __pyx_L7_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (__pyx_t_11) { /* "PyMaSC/core/readlen.pyx":92 * * if read.is_unmapped: * nunmapped += 1 # <<<<<<<<<<<<<< * elif not read.is_duplicate and read.mapping_quality >= mapq_criteria: * readlen = read.infer_query_length() */ __pyx_v_nunmapped = (__pyx_v_nunmapped + 1); /* "PyMaSC/core/readlen.pyx":91 * progress.update(read.reference_start) * * if read.is_unmapped: # <<<<<<<<<<<<<< * nunmapped += 1 * elif not read.is_duplicate and read.mapping_quality >= mapq_criteria: */ goto __pyx_L20; } /* "PyMaSC/core/readlen.pyx":93 * if read.is_unmapped: * nunmapped += 1 * elif not read.is_duplicate and read.mapping_quality >= mapq_criteria: # <<<<<<<<<<<<<< * readlen = read.infer_query_length() * if readlen in counter: */ __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_read), __pyx_n_s_is_duplicate); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 93, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_10 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_10 < 0)) __PYX_ERR(0, 93, __pyx_L7_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_17 = ((!__pyx_t_10) != 0); if (__pyx_t_17) { } else { __pyx_t_11 = __pyx_t_17; goto __pyx_L21_bool_binop_done; } __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_read), __pyx_n_s_mapping_quality); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 93, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_4 = __Pyx_PyInt_From_unsigned_int(__pyx_v_mapq_criteria); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 93, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_16 = PyObject_RichCompare(__pyx_t_1, __pyx_t_4, Py_GE); __Pyx_XGOTREF(__pyx_t_16); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 93, __pyx_L7_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_17 = __Pyx_PyObject_IsTrue(__pyx_t_16); if (unlikely(__pyx_t_17 < 0)) __PYX_ERR(0, 93, __pyx_L7_error) __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; __pyx_t_11 = __pyx_t_17; __pyx_L21_bool_binop_done:; if (__pyx_t_11) { /* "PyMaSC/core/readlen.pyx":94 * nunmapped += 1 * elif not read.is_duplicate and read.mapping_quality >= mapq_criteria: * readlen = read.infer_query_length() # <<<<<<<<<<<<<< * if readlen in counter: * counter[readlen] += 1 */ __pyx_t_4 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_read), __pyx_n_s_infer_query_length); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 94, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_1 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_4))) { __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_4); if (likely(__pyx_t_1)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); __Pyx_INCREF(__pyx_t_1); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_4, function); } } __pyx_t_16 = (__pyx_t_1) ? __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_1) : __Pyx_PyObject_CallNoArg(__pyx_t_4); __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 94, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_16); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_9 = __Pyx_PyInt_As_unsigned_long(__pyx_t_16); if (unlikely((__pyx_t_9 == (unsigned long)-1) && PyErr_Occurred())) __PYX_ERR(0, 94, __pyx_L7_error) __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; __pyx_v_readlen = __pyx_t_9; /* "PyMaSC/core/readlen.pyx":95 * elif not read.is_duplicate and read.mapping_quality >= mapq_criteria: * readlen = read.infer_query_length() * if readlen in counter: # <<<<<<<<<<<<<< * counter[readlen] += 1 * else: */ __pyx_t_16 = __Pyx_PyInt_From_unsigned_long(__pyx_v_readlen); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 95, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_16); __pyx_t_11 = (__Pyx_PyDict_ContainsTF(__pyx_t_16, __pyx_v_counter, Py_EQ)); if (unlikely(__pyx_t_11 < 0)) __PYX_ERR(0, 95, __pyx_L7_error) __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; __pyx_t_17 = (__pyx_t_11 != 0); if (__pyx_t_17) { /* "PyMaSC/core/readlen.pyx":96 * readlen = read.infer_query_length() * if readlen in counter: * counter[readlen] += 1 # <<<<<<<<<<<<<< * else: * counter[readlen] = 1 */ __pyx_t_16 = __Pyx_PyInt_From_unsigned_long(__pyx_v_readlen); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 96, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_16); __pyx_t_4 = __Pyx_PyDict_GetItem(__pyx_v_counter, __pyx_t_16); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 96, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_1 = __Pyx_PyInt_AddObjC(__pyx_t_4, __pyx_int_1, 1, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 96, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(PyDict_SetItem(__pyx_v_counter, __pyx_t_16, __pyx_t_1) < 0)) __PYX_ERR(0, 96, __pyx_L7_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; /* "PyMaSC/core/readlen.pyx":95 * elif not read.is_duplicate and read.mapping_quality >= mapq_criteria: * readlen = read.infer_query_length() * if readlen in counter: # <<<<<<<<<<<<<< * counter[readlen] += 1 * else: */ goto __pyx_L23; } /* "PyMaSC/core/readlen.pyx":98 * counter[readlen] += 1 * else: * counter[readlen] = 1 # <<<<<<<<<<<<<< * progress.finish() * */ /*else*/ { __pyx_t_16 = __Pyx_PyInt_From_unsigned_long(__pyx_v_readlen); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 98, __pyx_L7_error) __Pyx_GOTREF(__pyx_t_16); if (unlikely(PyDict_SetItem(__pyx_v_counter, __pyx_t_16, __pyx_int_1) < 0)) __PYX_ERR(0, 98, __pyx_L7_error) __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; } __pyx_L23:; /* "PyMaSC/core/readlen.pyx":93 * if read.is_unmapped: * nunmapped += 1 * elif not read.is_duplicate and read.mapping_quality >= mapq_criteria: # <<<<<<<<<<<<<< * readlen = read.infer_query_length() * if readlen in counter: */ } __pyx_L20:; /* "PyMaSC/core/readlen.pyx":75 * progress.set_genome(length) * * for read in stream: # <<<<<<<<<<<<<< * _chrom = read.reference_name * if _chrom is None: */ __pyx_L14_continue:; } __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "PyMaSC/core/readlen.pyx":65 * cdef unsigned long nread2 = 0 * * with AlignmentFile(path) as stream: # <<<<<<<<<<<<<< * chrom = None * chrom2length = dict(zip(stream.references, stream.lengths)) */ } __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; goto __pyx_L12_try_end; __pyx_L7_error:; __Pyx_XDECREF(__pyx_t_14); __pyx_t_14 = 0; __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_XDECREF(__pyx_t_16); __pyx_t_16 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; /*except:*/ { __Pyx_AddTraceback("PyMaSC.core.readlen.estimate_readlen", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_2, &__pyx_t_16, &__pyx_t_1) < 0) __PYX_ERR(0, 65, __pyx_L9_except_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_GOTREF(__pyx_t_16); __Pyx_GOTREF(__pyx_t_1); __pyx_t_4 = PyTuple_Pack(3, __pyx_t_2, __pyx_t_16, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 65, __pyx_L9_except_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_18 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, NULL); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_18)) __PYX_ERR(0, 65, __pyx_L9_except_error) __Pyx_GOTREF(__pyx_t_18); __pyx_t_17 = __Pyx_PyObject_IsTrue(__pyx_t_18); __Pyx_DECREF(__pyx_t_18); __pyx_t_18 = 0; if (__pyx_t_17 < 0) __PYX_ERR(0, 65, __pyx_L9_except_error) __pyx_t_11 = ((!(__pyx_t_17 != 0)) != 0); if (__pyx_t_11) { __Pyx_GIVEREF(__pyx_t_2); __Pyx_GIVEREF(__pyx_t_16); __Pyx_XGIVEREF(__pyx_t_1); __Pyx_ErrRestoreWithState(__pyx_t_2, __pyx_t_16, __pyx_t_1); __pyx_t_2 = 0; __pyx_t_16 = 0; __pyx_t_1 = 0; __PYX_ERR(0, 65, __pyx_L9_except_error) } __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_XDECREF(__pyx_t_16); __pyx_t_16 = 0; __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; goto __pyx_L8_exception_handled; } __pyx_L9_except_error:; __Pyx_XGIVEREF(__pyx_t_6); __Pyx_XGIVEREF(__pyx_t_7); __Pyx_XGIVEREF(__pyx_t_8); __Pyx_ExceptionReset(__pyx_t_6, __pyx_t_7, __pyx_t_8); goto __pyx_L1_error; __pyx_L8_exception_handled:; __Pyx_XGIVEREF(__pyx_t_6); __Pyx_XGIVEREF(__pyx_t_7); __Pyx_XGIVEREF(__pyx_t_8); __Pyx_ExceptionReset(__pyx_t_6, __pyx_t_7, __pyx_t_8); __pyx_L12_try_end:; } } /*finally:*/ { /*normal exit:*/{ if (__pyx_t_3) { __pyx_t_8 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_tuple_, NULL); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 65, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; } goto __pyx_L6; } __pyx_L6:; } goto __pyx_L27; __pyx_L3_error:; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L1_error; __pyx_L27:; } /* "PyMaSC/core/readlen.pyx":99 * else: * counter[readlen] = 1 * progress.finish() # <<<<<<<<<<<<<< * * length = estfunc(counter) */ if (unlikely(!__pyx_v_progress)) { __Pyx_RaiseUnboundLocalError("progress"); __PYX_ERR(0, 99, __pyx_L1_error) } __pyx_t_16 = __Pyx_PyObject_GetAttrStr(__pyx_v_progress, __pyx_n_s_finish); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 99, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_16); __pyx_t_2 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_16))) { __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_16); if (likely(__pyx_t_2)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_16); __Pyx_INCREF(__pyx_t_2); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_16, function); } } __pyx_t_1 = (__pyx_t_2) ? __Pyx_PyObject_CallOneArg(__pyx_t_16, __pyx_t_2) : __Pyx_PyObject_CallNoArg(__pyx_t_16); __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 99, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "PyMaSC/core/readlen.pyx":101 * progress.finish() * * length = estfunc(counter) # <<<<<<<<<<<<<< * * logger.info("Scan {:,} reads, {:,} reads were unmapped and {:,} reads >= MAPQ {}." */ __Pyx_INCREF(__pyx_v_estfunc); __pyx_t_16 = __pyx_v_estfunc; __pyx_t_2 = NULL; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_16))) { __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_16); if (likely(__pyx_t_2)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_16); __Pyx_INCREF(__pyx_t_2); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_16, function); } } __pyx_t_1 = (__pyx_t_2) ? __Pyx_PyObject_Call2Args(__pyx_t_16, __pyx_t_2, __pyx_v_counter) : __Pyx_PyObject_CallOneArg(__pyx_t_16, __pyx_v_counter); __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 101, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; __pyx_t_9 = __Pyx_PyInt_As_unsigned_long(__pyx_t_1); if (unlikely((__pyx_t_9 == (unsigned long)-1) && PyErr_Occurred())) __PYX_ERR(0, 101, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_v_length = __pyx_t_9; /* "PyMaSC/core/readlen.pyx":103 * length = estfunc(counter) * * logger.info("Scan {:,} reads, {:,} reads were unmapped and {:,} reads >= MAPQ {}." # <<<<<<<<<<<<<< * "".format(nreads, nunmapped, sum(counter.values()), mapq_criteria)) * if npaired > 0: */ __Pyx_GetModuleGlobalName(__pyx_t_16, __pyx_n_s_logger); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 103, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_16); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_16, __pyx_n_s_info); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 103, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; /* "PyMaSC/core/readlen.pyx":104 * * logger.info("Scan {:,} reads, {:,} reads were unmapped and {:,} reads >= MAPQ {}." * "".format(nreads, nunmapped, sum(counter.values()), mapq_criteria)) # <<<<<<<<<<<<<< * if npaired > 0: * logger.info("{:,} reads were paired: {:,} reads were 1st and {:,} reads were last segment." */ __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_kp_s_Scan_reads_reads_were_unmapped_a, __pyx_n_s_format); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 104, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = __Pyx_PyInt_From_unsigned_long(__pyx_v_nreads); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 104, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_14 = __Pyx_PyInt_From_unsigned_long(__pyx_v_nunmapped); if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 104, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_14); __pyx_t_19 = __Pyx_PyDict_Values(__pyx_v_counter); if (unlikely(!__pyx_t_19)) __PYX_ERR(0, 104, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_19); __pyx_t_20 = __Pyx_PyObject_CallOneArg(__pyx_builtin_sum, __pyx_t_19); if (unlikely(!__pyx_t_20)) __PYX_ERR(0, 104, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_20); __Pyx_DECREF(__pyx_t_19); __pyx_t_19 = 0; __pyx_t_19 = __Pyx_PyInt_From_unsigned_int(__pyx_v_mapq_criteria); if (unlikely(!__pyx_t_19)) __PYX_ERR(0, 104, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_19); __pyx_t_21 = NULL; __pyx_t_15 = 0; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_4))) { __pyx_t_21 = PyMethod_GET_SELF(__pyx_t_4); if (likely(__pyx_t_21)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); __Pyx_INCREF(__pyx_t_21); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_4, function); __pyx_t_15 = 1; } } #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_4)) { PyObject *__pyx_temp[5] = {__pyx_t_21, __pyx_t_5, __pyx_t_14, __pyx_t_20, __pyx_t_19}; __pyx_t_16 = __Pyx_PyFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_15, 4+__pyx_t_15); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 104, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_21); __pyx_t_21 = 0; __Pyx_GOTREF(__pyx_t_16); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; __Pyx_DECREF(__pyx_t_20); __pyx_t_20 = 0; __Pyx_DECREF(__pyx_t_19); __pyx_t_19 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_4)) { PyObject *__pyx_temp[5] = {__pyx_t_21, __pyx_t_5, __pyx_t_14, __pyx_t_20, __pyx_t_19}; __pyx_t_16 = __Pyx_PyCFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_15, 4+__pyx_t_15); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 104, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_21); __pyx_t_21 = 0; __Pyx_GOTREF(__pyx_t_16); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; __Pyx_DECREF(__pyx_t_20); __pyx_t_20 = 0; __Pyx_DECREF(__pyx_t_19); __pyx_t_19 = 0; } else #endif { __pyx_t_22 = PyTuple_New(4+__pyx_t_15); if (unlikely(!__pyx_t_22)) __PYX_ERR(0, 104, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_22); if (__pyx_t_21) { __Pyx_GIVEREF(__pyx_t_21); PyTuple_SET_ITEM(__pyx_t_22, 0, __pyx_t_21); __pyx_t_21 = NULL; } __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_22, 0+__pyx_t_15, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_14); PyTuple_SET_ITEM(__pyx_t_22, 1+__pyx_t_15, __pyx_t_14); __Pyx_GIVEREF(__pyx_t_20); PyTuple_SET_ITEM(__pyx_t_22, 2+__pyx_t_15, __pyx_t_20); __Pyx_GIVEREF(__pyx_t_19); PyTuple_SET_ITEM(__pyx_t_22, 3+__pyx_t_15, __pyx_t_19); __pyx_t_5 = 0; __pyx_t_14 = 0; __pyx_t_20 = 0; __pyx_t_19 = 0; __pyx_t_16 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_22, NULL); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 104, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_16); __Pyx_DECREF(__pyx_t_22); __pyx_t_22 = 0; } __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = NULL; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_2); if (likely(__pyx_t_4)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_2, function); } } __pyx_t_1 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_4, __pyx_t_16) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_16); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 103, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "PyMaSC/core/readlen.pyx":105 * logger.info("Scan {:,} reads, {:,} reads were unmapped and {:,} reads >= MAPQ {}." * "".format(nreads, nunmapped, sum(counter.values()), mapq_criteria)) * if npaired > 0: # <<<<<<<<<<<<<< * logger.info("{:,} reads were paired: {:,} reads were 1st and {:,} reads were last segment." * "".format(npaired, npaired - nread2, nread2)) */ __pyx_t_11 = ((__pyx_v_npaired > 0) != 0); if (__pyx_t_11) { /* "PyMaSC/core/readlen.pyx":106 * "".format(nreads, nunmapped, sum(counter.values()), mapq_criteria)) * if npaired > 0: * logger.info("{:,} reads were paired: {:,} reads were 1st and {:,} reads were last segment." # <<<<<<<<<<<<<< * "".format(npaired, npaired - nread2, nread2)) * logger.info("Note that only 1st reads in the templates will be used for calculation.") */ __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_logger); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 106, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_16 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_info); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 106, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_16); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "PyMaSC/core/readlen.pyx":107 * if npaired > 0: * logger.info("{:,} reads were paired: {:,} reads were 1st and {:,} reads were last segment." * "".format(npaired, npaired - nread2, nread2)) # <<<<<<<<<<<<<< * logger.info("Note that only 1st reads in the templates will be used for calculation.") * else: */ __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_kp_s_reads_were_paired_reads_were_1s, __pyx_n_s_format); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 107, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_22 = __Pyx_PyInt_From_unsigned_long(__pyx_v_npaired); if (unlikely(!__pyx_t_22)) __PYX_ERR(0, 107, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_22); __pyx_t_19 = __Pyx_PyInt_From_unsigned_long((__pyx_v_npaired - __pyx_v_nread2)); if (unlikely(!__pyx_t_19)) __PYX_ERR(0, 107, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_19); __pyx_t_20 = __Pyx_PyInt_From_unsigned_long(__pyx_v_nread2); if (unlikely(!__pyx_t_20)) __PYX_ERR(0, 107, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_20); __pyx_t_14 = NULL; __pyx_t_15 = 0; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_4))) { __pyx_t_14 = PyMethod_GET_SELF(__pyx_t_4); if (likely(__pyx_t_14)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); __Pyx_INCREF(__pyx_t_14); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_4, function); __pyx_t_15 = 1; } } #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_4)) { PyObject *__pyx_temp[4] = {__pyx_t_14, __pyx_t_22, __pyx_t_19, __pyx_t_20}; __pyx_t_2 = __Pyx_PyFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_15, 3+__pyx_t_15); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 107, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_14); __pyx_t_14 = 0; __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_22); __pyx_t_22 = 0; __Pyx_DECREF(__pyx_t_19); __pyx_t_19 = 0; __Pyx_DECREF(__pyx_t_20); __pyx_t_20 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_4)) { PyObject *__pyx_temp[4] = {__pyx_t_14, __pyx_t_22, __pyx_t_19, __pyx_t_20}; __pyx_t_2 = __Pyx_PyCFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_15, 3+__pyx_t_15); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 107, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_14); __pyx_t_14 = 0; __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_22); __pyx_t_22 = 0; __Pyx_DECREF(__pyx_t_19); __pyx_t_19 = 0; __Pyx_DECREF(__pyx_t_20); __pyx_t_20 = 0; } else #endif { __pyx_t_5 = PyTuple_New(3+__pyx_t_15); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 107, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); if (__pyx_t_14) { __Pyx_GIVEREF(__pyx_t_14); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_14); __pyx_t_14 = NULL; } __Pyx_GIVEREF(__pyx_t_22); PyTuple_SET_ITEM(__pyx_t_5, 0+__pyx_t_15, __pyx_t_22); __Pyx_GIVEREF(__pyx_t_19); PyTuple_SET_ITEM(__pyx_t_5, 1+__pyx_t_15, __pyx_t_19); __Pyx_GIVEREF(__pyx_t_20); PyTuple_SET_ITEM(__pyx_t_5, 2+__pyx_t_15, __pyx_t_20); __pyx_t_22 = 0; __pyx_t_19 = 0; __pyx_t_20 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_5, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 107, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; } __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = NULL; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_16))) { __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_16); if (likely(__pyx_t_4)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_16); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_16, function); } } __pyx_t_1 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_16, __pyx_t_4, __pyx_t_2) : __Pyx_PyObject_CallOneArg(__pyx_t_16, __pyx_t_2); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 106, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "PyMaSC/core/readlen.pyx":108 * logger.info("{:,} reads were paired: {:,} reads were 1st and {:,} reads were last segment." * "".format(npaired, npaired - nread2, nread2)) * logger.info("Note that only 1st reads in the templates will be used for calculation.") # <<<<<<<<<<<<<< * else: * logger.info("All reads were single-ended.") */ __Pyx_GetModuleGlobalName(__pyx_t_16, __pyx_n_s_logger); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 108, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_16); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_16, __pyx_n_s_info); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 108, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; __pyx_t_16 = NULL; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { __pyx_t_16 = PyMethod_GET_SELF(__pyx_t_2); if (likely(__pyx_t_16)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); __Pyx_INCREF(__pyx_t_16); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_2, function); } } __pyx_t_1 = (__pyx_t_16) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_16, __pyx_kp_s_Note_that_only_1st_reads_in_the) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_kp_s_Note_that_only_1st_reads_in_the); __Pyx_XDECREF(__pyx_t_16); __pyx_t_16 = 0; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 108, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "PyMaSC/core/readlen.pyx":105 * logger.info("Scan {:,} reads, {:,} reads were unmapped and {:,} reads >= MAPQ {}." * "".format(nreads, nunmapped, sum(counter.values()), mapq_criteria)) * if npaired > 0: # <<<<<<<<<<<<<< * logger.info("{:,} reads were paired: {:,} reads were 1st and {:,} reads were last segment." * "".format(npaired, npaired - nread2, nread2)) */ goto __pyx_L28; } /* "PyMaSC/core/readlen.pyx":110 * logger.info("Note that only 1st reads in the templates will be used for calculation.") * else: * logger.info("All reads were single-ended.") # <<<<<<<<<<<<<< * logger.info("Estimated read length = {:,}".format(length)) * */ /*else*/ { __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_logger); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 110, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_16 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_info); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 110, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_16); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = NULL; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_16))) { __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_16); if (likely(__pyx_t_2)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_16); __Pyx_INCREF(__pyx_t_2); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_16, function); } } __pyx_t_1 = (__pyx_t_2) ? __Pyx_PyObject_Call2Args(__pyx_t_16, __pyx_t_2, __pyx_kp_s_All_reads_were_single_ended) : __Pyx_PyObject_CallOneArg(__pyx_t_16, __pyx_kp_s_All_reads_were_single_ended); __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 110, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } __pyx_L28:; /* "PyMaSC/core/readlen.pyx":111 * else: * logger.info("All reads were single-ended.") * logger.info("Estimated read length = {:,}".format(length)) # <<<<<<<<<<<<<< * * return length */ __Pyx_GetModuleGlobalName(__pyx_t_16, __pyx_n_s_logger); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 111, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_16); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_16, __pyx_n_s_info); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 111, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_kp_s_Estimated_read_length, __pyx_n_s_format); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 111, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = __Pyx_PyInt_From_unsigned_long(__pyx_v_length); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 111, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_20 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_4))) { __pyx_t_20 = PyMethod_GET_SELF(__pyx_t_4); if (likely(__pyx_t_20)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); __Pyx_INCREF(__pyx_t_20); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_4, function); } } __pyx_t_16 = (__pyx_t_20) ? __Pyx_PyObject_Call2Args(__pyx_t_4, __pyx_t_20, __pyx_t_5) : __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_5); __Pyx_XDECREF(__pyx_t_20); __pyx_t_20 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 111, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_16); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = NULL; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_2); if (likely(__pyx_t_4)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_2, function); } } __pyx_t_1 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_4, __pyx_t_16) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_16); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 111, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "PyMaSC/core/readlen.pyx":113 * logger.info("Estimated read length = {:,}".format(length)) * * return length # <<<<<<<<<<<<<< */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyInt_From_unsigned_long(__pyx_v_length); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 113, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "PyMaSC/core/readlen.pyx":46 * * * def estimate_readlen(path, esttype, unsigned int mapq_criteria): # <<<<<<<<<<<<<< * estfunc = ESTFUNCTIONS[esttype] * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_14); __Pyx_XDECREF(__pyx_t_16); __Pyx_XDECREF(__pyx_t_19); __Pyx_XDECREF(__pyx_t_20); __Pyx_XDECREF(__pyx_t_21); __Pyx_XDECREF(__pyx_t_22); __Pyx_AddTraceback("PyMaSC.core.readlen.estimate_readlen", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_estfunc); __Pyx_XDECREF(__pyx_v_chrom); __Pyx_XDECREF(__pyx_v__chrom); __Pyx_XDECREF(__pyx_v_counter); __Pyx_XDECREF(__pyx_v_chrom2length); __Pyx_XDECREF((PyObject *)__pyx_v_read); __Pyx_XDECREF(__pyx_v_stream); __Pyx_XDECREF(__pyx_v_progress); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "array.pxd":93 * __data_union data * * def __getbuffer__(self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< * # This implementation of getbuffer is geared towards Cython * # requirements, and does not yet fulfill the PEP. */ /* Python wrapper */ static CYTHON_UNUSED int __pyx_pw_7cpython_5array_5array_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ static CYTHON_UNUSED int __pyx_pw_7cpython_5array_5array_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); __pyx_r = __pyx_pf_7cpython_5array_5array___getbuffer__(((arrayobject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_7cpython_5array_5array___getbuffer__(arrayobject *__pyx_v_self, Py_buffer *__pyx_v_info, CYTHON_UNUSED int __pyx_v_flags) { PyObject *__pyx_v_item_count = NULL; int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; char *__pyx_t_2; int __pyx_t_3; PyObject *__pyx_t_4 = NULL; Py_ssize_t __pyx_t_5; int __pyx_t_6; char __pyx_t_7; if (__pyx_v_info == NULL) { PyErr_SetString(PyExc_BufferError, "PyObject_GetBuffer: view==NULL argument is obsolete"); return -1; } __Pyx_RefNannySetupContext("__getbuffer__", 0); __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); /* "array.pxd":98 * # In particular strided access is always provided regardless * # of flags * item_count = Py_SIZE(self) # <<<<<<<<<<<<<< * * info.suboffsets = NULL */ __pyx_t_1 = PyInt_FromSsize_t(Py_SIZE(((PyObject *)__pyx_v_self))); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 98, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_item_count = __pyx_t_1; __pyx_t_1 = 0; /* "array.pxd":100 * item_count = Py_SIZE(self) * * info.suboffsets = NULL # <<<<<<<<<<<<<< * info.buf = self.data.as_chars * info.readonly = 0 */ __pyx_v_info->suboffsets = NULL; /* "array.pxd":101 * * info.suboffsets = NULL * info.buf = self.data.as_chars # <<<<<<<<<<<<<< * info.readonly = 0 * info.ndim = 1 */ __pyx_t_2 = __pyx_v_self->data.as_chars; __pyx_v_info->buf = __pyx_t_2; /* "array.pxd":102 * info.suboffsets = NULL * info.buf = self.data.as_chars * info.readonly = 0 # <<<<<<<<<<<<<< * info.ndim = 1 * info.itemsize = self.ob_descr.itemsize # e.g. sizeof(float) */ __pyx_v_info->readonly = 0; /* "array.pxd":103 * info.buf = self.data.as_chars * info.readonly = 0 * info.ndim = 1 # <<<<<<<<<<<<<< * info.itemsize = self.ob_descr.itemsize # e.g. sizeof(float) * info.len = info.itemsize * item_count */ __pyx_v_info->ndim = 1; /* "array.pxd":104 * info.readonly = 0 * info.ndim = 1 * info.itemsize = self.ob_descr.itemsize # e.g. sizeof(float) # <<<<<<<<<<<<<< * info.len = info.itemsize * item_count * */ __pyx_t_3 = __pyx_v_self->ob_descr->itemsize; __pyx_v_info->itemsize = __pyx_t_3; /* "array.pxd":105 * info.ndim = 1 * info.itemsize = self.ob_descr.itemsize # e.g. sizeof(float) * info.len = info.itemsize * item_count # <<<<<<<<<<<<<< * * info.shape = <Py_ssize_t*> PyObject_Malloc(sizeof(Py_ssize_t) + 2) */ __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_info->itemsize); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 105, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_4 = PyNumber_Multiply(__pyx_t_1, __pyx_v_item_count); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 105, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_t_4); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 105, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_v_info->len = __pyx_t_5; /* "array.pxd":107 * info.len = info.itemsize * item_count * * info.shape = <Py_ssize_t*> PyObject_Malloc(sizeof(Py_ssize_t) + 2) # <<<<<<<<<<<<<< * if not info.shape: * raise MemoryError() */ __pyx_v_info->shape = ((Py_ssize_t *)PyObject_Malloc(((sizeof(Py_ssize_t)) + 2))); /* "array.pxd":108 * * info.shape = <Py_ssize_t*> PyObject_Malloc(sizeof(Py_ssize_t) + 2) * if not info.shape: # <<<<<<<<<<<<<< * raise MemoryError() * info.shape[0] = item_count # constant regardless of resizing */ __pyx_t_6 = ((!(__pyx_v_info->shape != 0)) != 0); if (unlikely(__pyx_t_6)) { /* "array.pxd":109 * info.shape = <Py_ssize_t*> PyObject_Malloc(sizeof(Py_ssize_t) + 2) * if not info.shape: * raise MemoryError() # <<<<<<<<<<<<<< * info.shape[0] = item_count # constant regardless of resizing * info.strides = &info.itemsize */ PyErr_NoMemory(); __PYX_ERR(1, 109, __pyx_L1_error) /* "array.pxd":108 * * info.shape = <Py_ssize_t*> PyObject_Malloc(sizeof(Py_ssize_t) + 2) * if not info.shape: # <<<<<<<<<<<<<< * raise MemoryError() * info.shape[0] = item_count # constant regardless of resizing */ } /* "array.pxd":110 * if not info.shape: * raise MemoryError() * info.shape[0] = item_count # constant regardless of resizing # <<<<<<<<<<<<<< * info.strides = &info.itemsize * */ __pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_v_item_count); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 110, __pyx_L1_error) (__pyx_v_info->shape[0]) = __pyx_t_5; /* "array.pxd":111 * raise MemoryError() * info.shape[0] = item_count # constant regardless of resizing * info.strides = &info.itemsize # <<<<<<<<<<<<<< * * info.format = <char*> (info.shape + 1) */ __pyx_v_info->strides = (&__pyx_v_info->itemsize); /* "array.pxd":113 * info.strides = &info.itemsize * * info.format = <char*> (info.shape + 1) # <<<<<<<<<<<<<< * info.format[0] = self.ob_descr.typecode * info.format[1] = 0 */ __pyx_v_info->format = ((char *)(__pyx_v_info->shape + 1)); /* "array.pxd":114 * * info.format = <char*> (info.shape + 1) * info.format[0] = self.ob_descr.typecode # <<<<<<<<<<<<<< * info.format[1] = 0 * info.obj = self */ __pyx_t_7 = __pyx_v_self->ob_descr->typecode; (__pyx_v_info->format[0]) = __pyx_t_7; /* "array.pxd":115 * info.format = <char*> (info.shape + 1) * info.format[0] = self.ob_descr.typecode * info.format[1] = 0 # <<<<<<<<<<<<<< * info.obj = self * */ (__pyx_v_info->format[1]) = 0; /* "array.pxd":116 * info.format[0] = self.ob_descr.typecode * info.format[1] = 0 * info.obj = self # <<<<<<<<<<<<<< * * def __releasebuffer__(self, Py_buffer* info): */ __Pyx_INCREF(((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = ((PyObject *)__pyx_v_self); /* "array.pxd":93 * __data_union data * * def __getbuffer__(self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< * # This implementation of getbuffer is geared towards Cython * # requirements, and does not yet fulfill the PEP. */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("cpython.array.array.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; if (__pyx_v_info->obj != NULL) { __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; } goto __pyx_L2; __pyx_L0:; if (__pyx_v_info->obj == Py_None) { __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; } __pyx_L2:; __Pyx_XDECREF(__pyx_v_item_count); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "array.pxd":118 * info.obj = self * * def __releasebuffer__(self, Py_buffer* info): # <<<<<<<<<<<<<< * PyObject_Free(info.shape) * */ /* Python wrapper */ static CYTHON_UNUSED void __pyx_pw_7cpython_5array_5array_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ static CYTHON_UNUSED void __pyx_pw_7cpython_5array_5array_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); __pyx_pf_7cpython_5array_5array_2__releasebuffer__(((arrayobject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); /* function exit code */ __Pyx_RefNannyFinishContext(); } static void __pyx_pf_7cpython_5array_5array_2__releasebuffer__(CYTHON_UNUSED arrayobject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__releasebuffer__", 0); /* "array.pxd":119 * * def __releasebuffer__(self, Py_buffer* info): * PyObject_Free(info.shape) # <<<<<<<<<<<<<< * * array newarrayobject(PyTypeObject* type, Py_ssize_t size, arraydescr *descr) */ PyObject_Free(__pyx_v_info->shape); /* "array.pxd":118 * info.obj = self * * def __releasebuffer__(self, Py_buffer* info): # <<<<<<<<<<<<<< * PyObject_Free(info.shape) * */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "array.pxd":130 * * * cdef inline array clone(array template, Py_ssize_t length, bint zero): # <<<<<<<<<<<<<< * """ fast creation of a new array, given a template array. * type will be same as template. */ static CYTHON_INLINE arrayobject *__pyx_f_7cpython_5array_clone(arrayobject *__pyx_v_template, Py_ssize_t __pyx_v_length, int __pyx_v_zero) { arrayobject *__pyx_v_op = NULL; arrayobject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_t_2; int __pyx_t_3; int __pyx_t_4; __Pyx_RefNannySetupContext("clone", 0); /* "array.pxd":134 * type will be same as template. * if zero is true, new array will be initialized with zeroes.""" * op = newarrayobject(Py_TYPE(template), length, template.ob_descr) # <<<<<<<<<<<<<< * if zero and op is not None: * memset(op.data.as_chars, 0, length * op.ob_descr.itemsize) */ __pyx_t_1 = ((PyObject *)newarrayobject(Py_TYPE(((PyObject *)__pyx_v_template)), __pyx_v_length, __pyx_v_template->ob_descr)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 134, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_op = ((arrayobject *)__pyx_t_1); __pyx_t_1 = 0; /* "array.pxd":135 * if zero is true, new array will be initialized with zeroes.""" * op = newarrayobject(Py_TYPE(template), length, template.ob_descr) * if zero and op is not None: # <<<<<<<<<<<<<< * memset(op.data.as_chars, 0, length * op.ob_descr.itemsize) * return op */ __pyx_t_3 = (__pyx_v_zero != 0); if (__pyx_t_3) { } else { __pyx_t_2 = __pyx_t_3; goto __pyx_L4_bool_binop_done; } __pyx_t_3 = (((PyObject *)__pyx_v_op) != Py_None); __pyx_t_4 = (__pyx_t_3 != 0); __pyx_t_2 = __pyx_t_4; __pyx_L4_bool_binop_done:; if (__pyx_t_2) { /* "array.pxd":136 * op = newarrayobject(Py_TYPE(template), length, template.ob_descr) * if zero and op is not None: * memset(op.data.as_chars, 0, length * op.ob_descr.itemsize) # <<<<<<<<<<<<<< * return op * */ (void)(memset(__pyx_v_op->data.as_chars, 0, (__pyx_v_length * __pyx_v_op->ob_descr->itemsize))); /* "array.pxd":135 * if zero is true, new array will be initialized with zeroes.""" * op = newarrayobject(Py_TYPE(template), length, template.ob_descr) * if zero and op is not None: # <<<<<<<<<<<<<< * memset(op.data.as_chars, 0, length * op.ob_descr.itemsize) * return op */ } /* "array.pxd":137 * if zero and op is not None: * memset(op.data.as_chars, 0, length * op.ob_descr.itemsize) * return op # <<<<<<<<<<<<<< * * cdef inline array copy(array self): */ __Pyx_XDECREF(((PyObject *)__pyx_r)); __Pyx_INCREF(((PyObject *)__pyx_v_op)); __pyx_r = __pyx_v_op; goto __pyx_L0; /* "array.pxd":130 * * * cdef inline array clone(array template, Py_ssize_t length, bint zero): # <<<<<<<<<<<<<< * """ fast creation of a new array, given a template array. * type will be same as template. */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("cpython.array.clone", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_op); __Pyx_XGIVEREF((PyObject *)__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "array.pxd":139 * return op * * cdef inline array copy(array self): # <<<<<<<<<<<<<< * """ make a copy of an array. """ * op = newarrayobject(Py_TYPE(self), Py_SIZE(self), self.ob_descr) */ static CYTHON_INLINE arrayobject *__pyx_f_7cpython_5array_copy(arrayobject *__pyx_v_self) { arrayobject *__pyx_v_op = NULL; arrayobject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("copy", 0); /* "array.pxd":141 * cdef inline array copy(array self): * """ make a copy of an array. """ * op = newarrayobject(Py_TYPE(self), Py_SIZE(self), self.ob_descr) # <<<<<<<<<<<<<< * memcpy(op.data.as_chars, self.data.as_chars, Py_SIZE(op) * op.ob_descr.itemsize) * return op */ __pyx_t_1 = ((PyObject *)newarrayobject(Py_TYPE(((PyObject *)__pyx_v_self)), Py_SIZE(((PyObject *)__pyx_v_self)), __pyx_v_self->ob_descr)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 141, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_op = ((arrayobject *)__pyx_t_1); __pyx_t_1 = 0; /* "array.pxd":142 * """ make a copy of an array. """ * op = newarrayobject(Py_TYPE(self), Py_SIZE(self), self.ob_descr) * memcpy(op.data.as_chars, self.data.as_chars, Py_SIZE(op) * op.ob_descr.itemsize) # <<<<<<<<<<<<<< * return op * */ (void)(memcpy(__pyx_v_op->data.as_chars, __pyx_v_self->data.as_chars, (Py_SIZE(((PyObject *)__pyx_v_op)) * __pyx_v_op->ob_descr->itemsize))); /* "array.pxd":143 * op = newarrayobject(Py_TYPE(self), Py_SIZE(self), self.ob_descr) * memcpy(op.data.as_chars, self.data.as_chars, Py_SIZE(op) * op.ob_descr.itemsize) * return op # <<<<<<<<<<<<<< * * cdef inline int extend_buffer(array self, char* stuff, Py_ssize_t n) except -1: */ __Pyx_XDECREF(((PyObject *)__pyx_r)); __Pyx_INCREF(((PyObject *)__pyx_v_op)); __pyx_r = __pyx_v_op; goto __pyx_L0; /* "array.pxd":139 * return op * * cdef inline array copy(array self): # <<<<<<<<<<<<<< * """ make a copy of an array. """ * op = newarrayobject(Py_TYPE(self), Py_SIZE(self), self.ob_descr) */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("cpython.array.copy", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_op); __Pyx_XGIVEREF((PyObject *)__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "array.pxd":145 * return op * * cdef inline int extend_buffer(array self, char* stuff, Py_ssize_t n) except -1: # <<<<<<<<<<<<<< * """ efficient appending of new stuff of same type * (e.g. of same array type) */ static CYTHON_INLINE int __pyx_f_7cpython_5array_extend_buffer(arrayobject *__pyx_v_self, char *__pyx_v_stuff, Py_ssize_t __pyx_v_n) { Py_ssize_t __pyx_v_itemsize; Py_ssize_t __pyx_v_origsize; int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("extend_buffer", 0); /* "array.pxd":149 * (e.g. of same array type) * n: number of elements (not number of bytes!) """ * cdef Py_ssize_t itemsize = self.ob_descr.itemsize # <<<<<<<<<<<<<< * cdef Py_ssize_t origsize = Py_SIZE(self) * resize_smart(self, origsize + n) */ __pyx_t_1 = __pyx_v_self->ob_descr->itemsize; __pyx_v_itemsize = __pyx_t_1; /* "array.pxd":150 * n: number of elements (not number of bytes!) """ * cdef Py_ssize_t itemsize = self.ob_descr.itemsize * cdef Py_ssize_t origsize = Py_SIZE(self) # <<<<<<<<<<<<<< * resize_smart(self, origsize + n) * memcpy(self.data.as_chars + origsize * itemsize, stuff, n * itemsize) */ __pyx_v_origsize = Py_SIZE(((PyObject *)__pyx_v_self)); /* "array.pxd":151 * cdef Py_ssize_t itemsize = self.ob_descr.itemsize * cdef Py_ssize_t origsize = Py_SIZE(self) * resize_smart(self, origsize + n) # <<<<<<<<<<<<<< * memcpy(self.data.as_chars + origsize * itemsize, stuff, n * itemsize) * return 0 */ __pyx_t_1 = resize_smart(__pyx_v_self, (__pyx_v_origsize + __pyx_v_n)); if (unlikely(__pyx_t_1 == ((int)-1))) __PYX_ERR(1, 151, __pyx_L1_error) /* "array.pxd":152 * cdef Py_ssize_t origsize = Py_SIZE(self) * resize_smart(self, origsize + n) * memcpy(self.data.as_chars + origsize * itemsize, stuff, n * itemsize) # <<<<<<<<<<<<<< * return 0 * */ (void)(memcpy((__pyx_v_self->data.as_chars + (__pyx_v_origsize * __pyx_v_itemsize)), __pyx_v_stuff, (__pyx_v_n * __pyx_v_itemsize))); /* "array.pxd":153 * resize_smart(self, origsize + n) * memcpy(self.data.as_chars + origsize * itemsize, stuff, n * itemsize) * return 0 # <<<<<<<<<<<<<< * * cdef inline int extend(array self, array other) except -1: */ __pyx_r = 0; goto __pyx_L0; /* "array.pxd":145 * return op * * cdef inline int extend_buffer(array self, char* stuff, Py_ssize_t n) except -1: # <<<<<<<<<<<<<< * """ efficient appending of new stuff of same type * (e.g. of same array type) */ /* function exit code */ __pyx_L1_error:; __Pyx_AddTraceback("cpython.array.extend_buffer", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "array.pxd":155 * return 0 * * cdef inline int extend(array self, array other) except -1: # <<<<<<<<<<<<<< * """ extend array with data from another array; types must match. """ * if self.ob_descr.typecode != other.ob_descr.typecode: */ static CYTHON_INLINE int __pyx_f_7cpython_5array_extend(arrayobject *__pyx_v_self, arrayobject *__pyx_v_other) { int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; __Pyx_RefNannySetupContext("extend", 0); /* "array.pxd":157 * cdef inline int extend(array self, array other) except -1: * """ extend array with data from another array; types must match. """ * if self.ob_descr.typecode != other.ob_descr.typecode: # <<<<<<<<<<<<<< * PyErr_BadArgument() * return extend_buffer(self, other.data.as_chars, Py_SIZE(other)) */ __pyx_t_1 = ((__pyx_v_self->ob_descr->typecode != __pyx_v_other->ob_descr->typecode) != 0); if (__pyx_t_1) { /* "array.pxd":158 * """ extend array with data from another array; types must match. """ * if self.ob_descr.typecode != other.ob_descr.typecode: * PyErr_BadArgument() # <<<<<<<<<<<<<< * return extend_buffer(self, other.data.as_chars, Py_SIZE(other)) * */ __pyx_t_2 = PyErr_BadArgument(); if (unlikely(__pyx_t_2 == ((int)0))) __PYX_ERR(1, 158, __pyx_L1_error) /* "array.pxd":157 * cdef inline int extend(array self, array other) except -1: * """ extend array with data from another array; types must match. """ * if self.ob_descr.typecode != other.ob_descr.typecode: # <<<<<<<<<<<<<< * PyErr_BadArgument() * return extend_buffer(self, other.data.as_chars, Py_SIZE(other)) */ } /* "array.pxd":159 * if self.ob_descr.typecode != other.ob_descr.typecode: * PyErr_BadArgument() * return extend_buffer(self, other.data.as_chars, Py_SIZE(other)) # <<<<<<<<<<<<<< * * cdef inline void zero(array self): */ __pyx_t_2 = __pyx_f_7cpython_5array_extend_buffer(__pyx_v_self, __pyx_v_other->data.as_chars, Py_SIZE(((PyObject *)__pyx_v_other))); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(1, 159, __pyx_L1_error) __pyx_r = __pyx_t_2; goto __pyx_L0; /* "array.pxd":155 * return 0 * * cdef inline int extend(array self, array other) except -1: # <<<<<<<<<<<<<< * """ extend array with data from another array; types must match. """ * if self.ob_descr.typecode != other.ob_descr.typecode: */ /* function exit code */ __pyx_L1_error:; __Pyx_AddTraceback("cpython.array.extend", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "array.pxd":161 * return extend_buffer(self, other.data.as_chars, Py_SIZE(other)) * * cdef inline void zero(array self): # <<<<<<<<<<<<<< * """ set all elements of array to zero. """ * memset(self.data.as_chars, 0, Py_SIZE(self) * self.ob_descr.itemsize) */ static CYTHON_INLINE void __pyx_f_7cpython_5array_zero(arrayobject *__pyx_v_self) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("zero", 0); /* "array.pxd":163 * cdef inline void zero(array self): * """ set all elements of array to zero. """ * memset(self.data.as_chars, 0, Py_SIZE(self) * self.ob_descr.itemsize) # <<<<<<<<<<<<<< */ (void)(memset(__pyx_v_self->data.as_chars, 0, (Py_SIZE(((PyObject *)__pyx_v_self)) * __pyx_v_self->ob_descr->itemsize))); /* "array.pxd":161 * return extend_buffer(self, other.data.as_chars, Py_SIZE(other)) * * cdef inline void zero(array self): # <<<<<<<<<<<<<< * """ set all elements of array to zero. """ * memset(self.data.as_chars, 0, Py_SIZE(self) * self.ob_descr.itemsize) */ /* function exit code */ __Pyx_RefNannyFinishContext(); } static struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct___mean *__pyx_freelist_6PyMaSC_4core_7readlen___pyx_scope_struct___mean[8]; static int __pyx_freecount_6PyMaSC_4core_7readlen___pyx_scope_struct___mean = 0; static PyObject *__pyx_tp_new_6PyMaSC_4core_7readlen___pyx_scope_struct___mean(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { PyObject *o; if (CYTHON_COMPILING_IN_CPYTHON && likely((__pyx_freecount_6PyMaSC_4core_7readlen___pyx_scope_struct___mean > 0) & (t->tp_basicsize == sizeof(struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct___mean)))) { o = (PyObject*)__pyx_freelist_6PyMaSC_4core_7readlen___pyx_scope_struct___mean[--__pyx_freecount_6PyMaSC_4core_7readlen___pyx_scope_struct___mean]; memset(o, 0, sizeof(struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct___mean)); (void) PyObject_INIT(o, t); PyObject_GC_Track(o); } else { o = (*t->tp_alloc)(t, 0); if (unlikely(!o)) return 0; } return o; } static void __pyx_tp_dealloc_6PyMaSC_4core_7readlen___pyx_scope_struct___mean(PyObject *o) { struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct___mean *p = (struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct___mean *)o; PyObject_GC_UnTrack(o); Py_CLEAR(p->__pyx_v_c); if (CYTHON_COMPILING_IN_CPYTHON && ((__pyx_freecount_6PyMaSC_4core_7readlen___pyx_scope_struct___mean < 8) & (Py_TYPE(o)->tp_basicsize == sizeof(struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct___mean)))) { __pyx_freelist_6PyMaSC_4core_7readlen___pyx_scope_struct___mean[__pyx_freecount_6PyMaSC_4core_7readlen___pyx_scope_struct___mean++] = ((struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct___mean *)o); } else { (*Py_TYPE(o)->tp_free)(o); } } static int __pyx_tp_traverse_6PyMaSC_4core_7readlen___pyx_scope_struct___mean(PyObject *o, visitproc v, void *a) { int e; struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct___mean *p = (struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct___mean *)o; if (p->__pyx_v_c) { e = (*v)(p->__pyx_v_c, a); if (e) return e; } return 0; } static int __pyx_tp_clear_6PyMaSC_4core_7readlen___pyx_scope_struct___mean(PyObject *o) { PyObject* tmp; struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct___mean *p = (struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct___mean *)o; tmp = ((PyObject*)p->__pyx_v_c); p->__pyx_v_c = Py_None; Py_INCREF(Py_None); Py_XDECREF(tmp); return 0; } static PyTypeObject __pyx_type_6PyMaSC_4core_7readlen___pyx_scope_struct___mean = { PyVarObject_HEAD_INIT(0, 0) "PyMaSC.core.readlen.__pyx_scope_struct___mean", /*tp_name*/ sizeof(struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct___mean), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_6PyMaSC_4core_7readlen___pyx_scope_struct___mean, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ #endif #if PY_MAJOR_VERSION >= 3 0, /*tp_as_async*/ #endif 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ 0, /*tp_doc*/ __pyx_tp_traverse_6PyMaSC_4core_7readlen___pyx_scope_struct___mean, /*tp_traverse*/ __pyx_tp_clear_6PyMaSC_4core_7readlen___pyx_scope_struct___mean, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ 0, /*tp_methods*/ 0, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new_6PyMaSC_4core_7readlen___pyx_scope_struct___mean, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ 0, /*tp_version_tag*/ #if PY_VERSION_HEX >= 0x030400a1 0, /*tp_finalize*/ #endif }; static struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr *__pyx_freelist_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr[8]; static int __pyx_freecount_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr = 0; static PyObject *__pyx_tp_new_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { PyObject *o; if (CYTHON_COMPILING_IN_CPYTHON && likely((__pyx_freecount_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr > 0) & (t->tp_basicsize == sizeof(struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr)))) { o = (PyObject*)__pyx_freelist_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr[--__pyx_freecount_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr]; memset(o, 0, sizeof(struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr)); (void) PyObject_INIT(o, t); PyObject_GC_Track(o); } else { o = (*t->tp_alloc)(t, 0); if (unlikely(!o)) return 0; } return o; } static void __pyx_tp_dealloc_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr(PyObject *o) { struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr *p = (struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr *)o; PyObject_GC_UnTrack(o); Py_CLEAR(p->__pyx_outer_scope); Py_CLEAR(p->__pyx_v_freq); Py_CLEAR(p->__pyx_v_length); Py_CLEAR(p->__pyx_t_0); if (CYTHON_COMPILING_IN_CPYTHON && ((__pyx_freecount_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr < 8) & (Py_TYPE(o)->tp_basicsize == sizeof(struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr)))) { __pyx_freelist_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr[__pyx_freecount_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr++] = ((struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr *)o); } else { (*Py_TYPE(o)->tp_free)(o); } } static int __pyx_tp_traverse_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr(PyObject *o, visitproc v, void *a) { int e; struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr *p = (struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr *)o; if (p->__pyx_outer_scope) { e = (*v)(((PyObject *)p->__pyx_outer_scope), a); if (e) return e; } if (p->__pyx_v_freq) { e = (*v)(p->__pyx_v_freq, a); if (e) return e; } if (p->__pyx_v_length) { e = (*v)(p->__pyx_v_length, a); if (e) return e; } if (p->__pyx_t_0) { e = (*v)(p->__pyx_t_0, a); if (e) return e; } return 0; } static PyTypeObject __pyx_type_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr = { PyVarObject_HEAD_INIT(0, 0) "PyMaSC.core.readlen.__pyx_scope_struct_1_genexpr", /*tp_name*/ sizeof(struct __pyx_obj_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ #endif #if PY_MAJOR_VERSION >= 3 0, /*tp_as_async*/ #endif 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ 0, /*tp_doc*/ __pyx_tp_traverse_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ 0, /*tp_methods*/ 0, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ 0, /*tp_version_tag*/ #if PY_VERSION_HEX >= 0x030400a1 0, /*tp_finalize*/ #endif }; static PyMethodDef __pyx_methods[] = { {0, 0, 0, 0} }; #if PY_MAJOR_VERSION >= 3 #if CYTHON_PEP489_MULTI_PHASE_INIT static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ static int __pyx_pymod_exec_readlen(PyObject* module); /*proto*/ static PyModuleDef_Slot __pyx_moduledef_slots[] = { {Py_mod_create, (void*)__pyx_pymod_create}, {Py_mod_exec, (void*)__pyx_pymod_exec_readlen}, {0, NULL} }; #endif static struct PyModuleDef __pyx_moduledef = { PyModuleDef_HEAD_INIT, "readlen", 0, /* m_doc */ #if CYTHON_PEP489_MULTI_PHASE_INIT 0, /* m_size */ #else -1, /* m_size */ #endif __pyx_methods /* m_methods */, #if CYTHON_PEP489_MULTI_PHASE_INIT __pyx_moduledef_slots, /* m_slots */ #else NULL, /* m_reload */ #endif NULL, /* m_traverse */ NULL, /* m_clear */ NULL /* m_free */ }; #endif #ifndef CYTHON_SMALL_CODE #if defined(__clang__) #define CYTHON_SMALL_CODE #elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) #define CYTHON_SMALL_CODE __attribute__((cold)) #else #define CYTHON_SMALL_CODE #endif #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_kp_s_All_reads_were_single_ended, __pyx_k_All_reads_were_single_ended, sizeof(__pyx_k_All_reads_were_single_ended), 0, 0, 1, 0}, {&__pyx_n_s_ESTFUNCTIONS, __pyx_k_ESTFUNCTIONS, sizeof(__pyx_k_ESTFUNCTIONS), 0, 0, 1, 1}, {&__pyx_kp_s_Estimated_read_length, __pyx_k_Estimated_read_length, sizeof(__pyx_k_Estimated_read_length), 0, 0, 1, 0}, {&__pyx_n_s_MAX, __pyx_k_MAX, sizeof(__pyx_k_MAX), 0, 0, 1, 1}, {&__pyx_n_s_MEAN, __pyx_k_MEAN, sizeof(__pyx_k_MEAN), 0, 0, 1, 1}, {&__pyx_n_s_MEDIAN, __pyx_k_MEDIAN, sizeof(__pyx_k_MEDIAN), 0, 0, 1, 1}, {&__pyx_n_s_MIN, __pyx_k_MIN, sizeof(__pyx_k_MIN), 0, 0, 1, 1}, {&__pyx_n_s_MODE, __pyx_k_MODE, sizeof(__pyx_k_MODE), 0, 0, 1, 1}, {&__pyx_n_s_MemoryError, __pyx_k_MemoryError, sizeof(__pyx_k_MemoryError), 0, 0, 1, 1}, {&__pyx_kp_s_Note_that_only_1st_reads_in_the, __pyx_k_Note_that_only_1st_reads_in_the, sizeof(__pyx_k_Note_that_only_1st_reads_in_the), 0, 0, 1, 0}, {&__pyx_n_s_PyMaSC_core_readlen, __pyx_k_PyMaSC_core_readlen, sizeof(__pyx_k_PyMaSC_core_readlen), 0, 0, 1, 1}, {&__pyx_kp_s_PyMaSC_core_readlen_pyx, __pyx_k_PyMaSC_core_readlen_pyx, sizeof(__pyx_k_PyMaSC_core_readlen_pyx), 0, 0, 1, 0}, {&__pyx_n_s_PyMaSC_utils_progress, __pyx_k_PyMaSC_utils_progress, sizeof(__pyx_k_PyMaSC_utils_progress), 0, 0, 1, 1}, {&__pyx_n_s_ReadCountProgressBar, __pyx_k_ReadCountProgressBar, sizeof(__pyx_k_ReadCountProgressBar), 0, 0, 1, 1}, {&__pyx_kp_s_Scan_reads_reads_were_unmapped_a, __pyx_k_Scan_reads_reads_were_unmapped_a, sizeof(__pyx_k_Scan_reads_reads_were_unmapped_a), 0, 0, 1, 0}, {&__pyx_n_s_args, __pyx_k_args, sizeof(__pyx_k_args), 0, 0, 1, 1}, {&__pyx_n_s_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 0, 1, 1}, {&__pyx_n_s_chrom, __pyx_k_chrom, sizeof(__pyx_k_chrom), 0, 0, 1, 1}, {&__pyx_n_s_chrom2length, __pyx_k_chrom2length, sizeof(__pyx_k_chrom2length), 0, 0, 1, 1}, {&__pyx_n_s_chrom_2, __pyx_k_chrom_2, sizeof(__pyx_k_chrom_2), 0, 0, 1, 1}, {&__pyx_n_s_cline_in_traceback, __pyx_k_cline_in_traceback, sizeof(__pyx_k_cline_in_traceback), 0, 0, 1, 1}, {&__pyx_n_s_close, __pyx_k_close, sizeof(__pyx_k_close), 0, 0, 1, 1}, {&__pyx_n_s_counter, __pyx_k_counter, sizeof(__pyx_k_counter), 0, 0, 1, 1}, {&__pyx_n_s_disable_bar, __pyx_k_disable_bar, sizeof(__pyx_k_disable_bar), 0, 0, 1, 1}, {&__pyx_n_s_enter, __pyx_k_enter, sizeof(__pyx_k_enter), 0, 0, 1, 1}, {&__pyx_n_s_enumerate, __pyx_k_enumerate, sizeof(__pyx_k_enumerate), 0, 0, 1, 1}, {&__pyx_n_s_estfunc, __pyx_k_estfunc, sizeof(__pyx_k_estfunc), 0, 0, 1, 1}, {&__pyx_n_s_estimate_readlen, __pyx_k_estimate_readlen, sizeof(__pyx_k_estimate_readlen), 0, 0, 1, 1}, {&__pyx_n_s_esttype, __pyx_k_esttype, sizeof(__pyx_k_esttype), 0, 0, 1, 1}, {&__pyx_n_s_exit, __pyx_k_exit, sizeof(__pyx_k_exit), 0, 0, 1, 1}, {&__pyx_n_s_finish, __pyx_k_finish, sizeof(__pyx_k_finish), 0, 0, 1, 1}, {&__pyx_n_s_format, __pyx_k_format, sizeof(__pyx_k_format), 0, 0, 1, 1}, {&__pyx_n_s_genexpr, __pyx_k_genexpr, sizeof(__pyx_k_genexpr), 0, 0, 1, 1}, {&__pyx_n_s_getLogger, __pyx_k_getLogger, sizeof(__pyx_k_getLogger), 0, 0, 1, 1}, {&__pyx_n_s_has_index, __pyx_k_has_index, sizeof(__pyx_k_has_index), 0, 0, 1, 1}, {&__pyx_n_s_i, __pyx_k_i, sizeof(__pyx_k_i), 0, 0, 1, 1}, {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, {&__pyx_n_s_infer_query_length, __pyx_k_infer_query_length, sizeof(__pyx_k_infer_query_length), 0, 0, 1, 1}, {&__pyx_n_s_info, __pyx_k_info, sizeof(__pyx_k_info), 0, 0, 1, 1}, {&__pyx_n_s_is_duplicate, __pyx_k_is_duplicate, sizeof(__pyx_k_is_duplicate), 0, 0, 1, 1}, {&__pyx_n_s_is_paired, __pyx_k_is_paired, sizeof(__pyx_k_is_paired), 0, 0, 1, 1}, {&__pyx_n_s_is_read2, __pyx_k_is_read2, sizeof(__pyx_k_is_read2), 0, 0, 1, 1}, {&__pyx_n_s_is_unmapped, __pyx_k_is_unmapped, sizeof(__pyx_k_is_unmapped), 0, 0, 1, 1}, {&__pyx_n_s_items, __pyx_k_items, sizeof(__pyx_k_items), 0, 0, 1, 1}, {&__pyx_n_s_k, __pyx_k_k, sizeof(__pyx_k_k), 0, 0, 1, 1}, {&__pyx_n_s_key, __pyx_k_key, sizeof(__pyx_k_key), 0, 0, 1, 1}, {&__pyx_n_s_l, __pyx_k_l, sizeof(__pyx_k_l), 0, 0, 1, 1}, {&__pyx_n_s_length, __pyx_k_length, sizeof(__pyx_k_length), 0, 0, 1, 1}, {&__pyx_n_s_lengths, __pyx_k_lengths, sizeof(__pyx_k_lengths), 0, 0, 1, 1}, {&__pyx_n_s_logger, __pyx_k_logger, sizeof(__pyx_k_logger), 0, 0, 1, 1}, {&__pyx_n_s_logging, __pyx_k_logging, sizeof(__pyx_k_logging), 0, 0, 1, 1}, {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, {&__pyx_n_s_mapping_quality, __pyx_k_mapping_quality, sizeof(__pyx_k_mapping_quality), 0, 0, 1, 1}, {&__pyx_n_s_mapq, __pyx_k_mapq, sizeof(__pyx_k_mapq), 0, 0, 1, 1}, {&__pyx_n_s_mapq_criteria, __pyx_k_mapq_criteria, sizeof(__pyx_k_mapq_criteria), 0, 0, 1, 1}, {&__pyx_n_s_max, __pyx_k_max, sizeof(__pyx_k_max), 0, 0, 1, 1}, {&__pyx_n_s_mean, __pyx_k_mean, sizeof(__pyx_k_mean), 0, 0, 1, 1}, {&__pyx_n_s_mean_locals_genexpr, __pyx_k_mean_locals_genexpr, sizeof(__pyx_k_mean_locals_genexpr), 0, 0, 1, 1}, {&__pyx_n_s_median, __pyx_k_median, sizeof(__pyx_k_median), 0, 0, 1, 1}, {&__pyx_n_s_min, __pyx_k_min, sizeof(__pyx_k_min), 0, 0, 1, 1}, {&__pyx_n_s_mode, __pyx_k_mode, sizeof(__pyx_k_mode), 0, 0, 1, 1}, {&__pyx_n_s_mode_locals_lambda, __pyx_k_mode_locals_lambda, sizeof(__pyx_k_mode_locals_lambda), 0, 0, 1, 1}, {&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1}, {&__pyx_n_s_npaired, __pyx_k_npaired, sizeof(__pyx_k_npaired), 0, 0, 1, 1}, {&__pyx_n_s_nread2, __pyx_k_nread2, sizeof(__pyx_k_nread2), 0, 0, 1, 1}, {&__pyx_n_s_nreads, __pyx_k_nreads, sizeof(__pyx_k_nreads), 0, 0, 1, 1}, {&__pyx_n_s_num, __pyx_k_num, sizeof(__pyx_k_num), 0, 0, 1, 1}, {&__pyx_n_s_nunmapped, __pyx_k_nunmapped, sizeof(__pyx_k_nunmapped), 0, 0, 1, 1}, {&__pyx_n_s_path, __pyx_k_path, sizeof(__pyx_k_path), 0, 0, 1, 1}, {&__pyx_n_s_pos, __pyx_k_pos, sizeof(__pyx_k_pos), 0, 0, 1, 1}, {&__pyx_n_s_progress, __pyx_k_progress, sizeof(__pyx_k_progress), 0, 0, 1, 1}, {&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1}, {&__pyx_n_s_read, __pyx_k_read, sizeof(__pyx_k_read), 0, 0, 1, 1}, {&__pyx_n_s_readlen, __pyx_k_readlen, sizeof(__pyx_k_readlen), 0, 0, 1, 1}, {&__pyx_kp_s_reads_were_paired_reads_were_1s, __pyx_k_reads_were_paired_reads_were_1s, sizeof(__pyx_k_reads_were_paired_reads_were_1s), 0, 0, 1, 0}, {&__pyx_n_s_reference_name, __pyx_k_reference_name, sizeof(__pyx_k_reference_name), 0, 0, 1, 1}, {&__pyx_n_s_reference_start, __pyx_k_reference_start, sizeof(__pyx_k_reference_start), 0, 0, 1, 1}, {&__pyx_n_s_references, __pyx_k_references, sizeof(__pyx_k_references), 0, 0, 1, 1}, {&__pyx_n_s_round, __pyx_k_round, sizeof(__pyx_k_round), 0, 0, 1, 1}, {&__pyx_n_s_send, __pyx_k_send, sizeof(__pyx_k_send), 0, 0, 1, 1}, {&__pyx_n_s_set_chrom, __pyx_k_set_chrom, sizeof(__pyx_k_set_chrom), 0, 0, 1, 1}, {&__pyx_n_s_set_genome, __pyx_k_set_genome, sizeof(__pyx_k_set_genome), 0, 0, 1, 1}, {&__pyx_n_s_sorted, __pyx_k_sorted, sizeof(__pyx_k_sorted), 0, 0, 1, 1}, {&__pyx_n_s_stream, __pyx_k_stream, sizeof(__pyx_k_stream), 0, 0, 1, 1}, {&__pyx_n_s_sum, __pyx_k_sum, sizeof(__pyx_k_sum), 0, 0, 1, 1}, {&__pyx_n_s_sum_2, __pyx_k_sum_2, sizeof(__pyx_k_sum_2), 0, 0, 1, 1}, {&__pyx_n_s_target, __pyx_k_target, sizeof(__pyx_k_target), 0, 0, 1, 1}, {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, {&__pyx_n_s_throw, __pyx_k_throw, sizeof(__pyx_k_throw), 0, 0, 1, 1}, {&__pyx_n_s_update, __pyx_k_update, sizeof(__pyx_k_update), 0, 0, 1, 1}, {&__pyx_n_s_v, __pyx_k_v, sizeof(__pyx_k_v), 0, 0, 1, 1}, {&__pyx_n_s_values, __pyx_k_values, sizeof(__pyx_k_values), 0, 0, 1, 1}, {&__pyx_n_s_zip, __pyx_k_zip, sizeof(__pyx_k_zip), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) { __pyx_builtin_min = __Pyx_GetBuiltinName(__pyx_n_s_min); if (!__pyx_builtin_min) __PYX_ERR(0, 42, __pyx_L1_error) __pyx_builtin_max = __Pyx_GetBuiltinName(__pyx_n_s_max); if (!__pyx_builtin_max) __PYX_ERR(0, 42, __pyx_L1_error) __pyx_builtin_round = __Pyx_GetBuiltinName(__pyx_n_s_round); if (!__pyx_builtin_round) __PYX_ERR(0, 12, __pyx_L1_error) __pyx_builtin_sum = __Pyx_GetBuiltinName(__pyx_n_s_sum); if (!__pyx_builtin_sum) __PYX_ERR(0, 13, __pyx_L1_error) __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s_enumerate); if (!__pyx_builtin_enumerate) __PYX_ERR(0, 29, __pyx_L1_error) __pyx_builtin_sorted = __Pyx_GetBuiltinName(__pyx_n_s_sorted); if (!__pyx_builtin_sorted) __PYX_ERR(0, 38, __pyx_L1_error) __pyx_builtin_zip = __Pyx_GetBuiltinName(__pyx_n_s_zip); if (!__pyx_builtin_zip) __PYX_ERR(0, 67, __pyx_L1_error) __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) __PYX_ERR(1, 109, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; } static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); /* "PyMaSC/core/readlen.pyx":65 * cdef unsigned long nread2 = 0 * * with AlignmentFile(path) as stream: # <<<<<<<<<<<<<< * chrom = None * chrom2length = dict(zip(stream.references, stream.lengths)) */ __pyx_tuple_ = PyTuple_Pack(3, Py_None, Py_None, Py_None); if (unlikely(!__pyx_tuple_)) __PYX_ERR(0, 65, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple_); __Pyx_GIVEREF(__pyx_tuple_); /* "PyMaSC/core/readlen.pyx":11 * * * def _mean(c): # <<<<<<<<<<<<<< * return int(round( * sum(length * freq for length, freq in c.items()) / float(sum(c.values())) */ __pyx_tuple__2 = PyTuple_Pack(3, __pyx_n_s_c, __pyx_n_s_genexpr, __pyx_n_s_genexpr); if (unlikely(!__pyx_tuple__2)) __PYX_ERR(0, 11, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__2); __Pyx_GIVEREF(__pyx_tuple__2); __pyx_codeobj__3 = (PyObject*)__Pyx_PyCode_New(1, 0, 3, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__2, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_PyMaSC_core_readlen_pyx, __pyx_n_s_mean, 11, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__3)) __PYX_ERR(0, 11, __pyx_L1_error) /* "PyMaSC/core/readlen.pyx":17 * * * def _median(c): # <<<<<<<<<<<<<< * num = sum(c.values()) * target = num / 2 */ __pyx_tuple__4 = PyTuple_Pack(7, __pyx_n_s_c, __pyx_n_s_num, __pyx_n_s_target, __pyx_n_s_sum_2, __pyx_n_s_l, __pyx_n_s_length, __pyx_n_s_i); if (unlikely(!__pyx_tuple__4)) __PYX_ERR(0, 17, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__4); __Pyx_GIVEREF(__pyx_tuple__4); __pyx_codeobj__5 = (PyObject*)__Pyx_PyCode_New(1, 0, 7, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__4, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_PyMaSC_core_readlen_pyx, __pyx_n_s_median, 17, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__5)) __PYX_ERR(0, 17, __pyx_L1_error) /* "PyMaSC/core/readlen.pyx":37 * * * def _mode(c): # <<<<<<<<<<<<<< * return [k for k, v in sorted(c.items(), key=lambda x: x[1])][-1] * */ __pyx_tuple__6 = PyTuple_Pack(3, __pyx_n_s_c, __pyx_n_s_k, __pyx_n_s_v); if (unlikely(!__pyx_tuple__6)) __PYX_ERR(0, 37, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__6); __Pyx_GIVEREF(__pyx_tuple__6); __pyx_codeobj__7 = (PyObject*)__Pyx_PyCode_New(1, 0, 3, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__6, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_PyMaSC_core_readlen_pyx, __pyx_n_s_mode, 37, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__7)) __PYX_ERR(0, 37, __pyx_L1_error) /* "PyMaSC/core/readlen.pyx":46 * * * def estimate_readlen(path, esttype, unsigned int mapq_criteria): # <<<<<<<<<<<<<< * estfunc = ESTFUNCTIONS[esttype] * */ __pyx_tuple__8 = PyTuple_Pack(20, __pyx_n_s_path, __pyx_n_s_esttype, __pyx_n_s_mapq_criteria, __pyx_n_s_estfunc, __pyx_n_s_is_duplicate, __pyx_n_s_chrom, __pyx_n_s_chrom_2, __pyx_n_s_mapq, __pyx_n_s_pos, __pyx_n_s_readlen, __pyx_n_s_counter, __pyx_n_s_chrom2length, __pyx_n_s_length, __pyx_n_s_read, __pyx_n_s_nreads, __pyx_n_s_nunmapped, __pyx_n_s_npaired, __pyx_n_s_nread2, __pyx_n_s_stream, __pyx_n_s_progress); if (unlikely(!__pyx_tuple__8)) __PYX_ERR(0, 46, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__8); __Pyx_GIVEREF(__pyx_tuple__8); __pyx_codeobj__9 = (PyObject*)__Pyx_PyCode_New(3, 0, 20, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__8, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_PyMaSC_core_readlen_pyx, __pyx_n_s_estimate_readlen, 46, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__9)) __PYX_ERR(0, 46, __pyx_L1_error) __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_RefNannyFinishContext(); return -1; } static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void) { __pyx_umethod_PyDict_Type_values.type = (PyObject*)&PyDict_Type; if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error); __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_int_2 = PyInt_FromLong(2); if (unlikely(!__pyx_int_2)) __PYX_ERR(0, 1, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; } static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(void); /*proto*/ static int __Pyx_modinit_global_init_code(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0); /*--- Global init code ---*/ __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_modinit_variable_export_code(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0); /*--- Variable export code ---*/ __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_modinit_function_export_code(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0); /*--- Function export code ---*/ __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_modinit_type_init_code(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0); /*--- Type init code ---*/ if (PyType_Ready(&__pyx_type_6PyMaSC_4core_7readlen___pyx_scope_struct___mean) < 0) __PYX_ERR(0, 11, __pyx_L1_error) __pyx_type_6PyMaSC_4core_7readlen___pyx_scope_struct___mean.tp_print = 0; if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_6PyMaSC_4core_7readlen___pyx_scope_struct___mean.tp_dictoffset && __pyx_type_6PyMaSC_4core_7readlen___pyx_scope_struct___mean.tp_getattro == PyObject_GenericGetAttr)) { __pyx_type_6PyMaSC_4core_7readlen___pyx_scope_struct___mean.tp_getattro = __Pyx_PyObject_GenericGetAttrNoDict; } __pyx_ptype_6PyMaSC_4core_7readlen___pyx_scope_struct___mean = &__pyx_type_6PyMaSC_4core_7readlen___pyx_scope_struct___mean; if (PyType_Ready(&__pyx_type_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr) < 0) __PYX_ERR(0, 13, __pyx_L1_error) __pyx_type_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr.tp_print = 0; if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr.tp_dictoffset && __pyx_type_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr.tp_getattro == PyObject_GenericGetAttr)) { __pyx_type_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr.tp_getattro = __Pyx_PyObject_GenericGetAttrNoDict; } __pyx_ptype_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr = &__pyx_type_6PyMaSC_4core_7readlen___pyx_scope_struct_1_genexpr; __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_RefNannyFinishContext(); return -1; } static int __Pyx_modinit_type_import_code(void) { __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); /*--- Type import code ---*/ __pyx_t_1 = PyImport_ImportModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 9, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__pyx_t_1, __Pyx_BUILTIN_MODULE_NAME, "type", #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 sizeof(PyTypeObject), #else sizeof(PyHeapTypeObject), #endif __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_7cpython_4type_type) __PYX_ERR(2, 9, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = PyImport_ImportModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 8, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_ptype_7cpython_4bool_bool = __Pyx_ImportType(__pyx_t_1, __Pyx_BUILTIN_MODULE_NAME, "bool", sizeof(PyBoolObject), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_7cpython_4bool_bool) __PYX_ERR(3, 8, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = PyImport_ImportModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_t_1)) __PYX_ERR(4, 15, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_ptype_7cpython_7complex_complex = __Pyx_ImportType(__pyx_t_1, __Pyx_BUILTIN_MODULE_NAME, "complex", sizeof(PyComplexObject), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_7cpython_7complex_complex) __PYX_ERR(4, 15, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = PyImport_ImportModule("array"); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 58, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_ptype_7cpython_5array_array = __Pyx_ImportType(__pyx_t_1, "array", "array", sizeof(arrayobject), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_7cpython_5array_array) __PYX_ERR(1, 58, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = PyImport_ImportModule("pysam.libchtslib"); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 2590, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_ptype_5pysam_10libchtslib_HTSFile = __Pyx_ImportType(__pyx_t_1, "pysam.libchtslib", "HTSFile", sizeof(struct __pyx_obj_5pysam_10libchtslib_HTSFile), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5pysam_10libchtslib_HTSFile) __PYX_ERR(5, 2590, __pyx_L1_error) __pyx_vtabptr_5pysam_10libchtslib_HTSFile = (struct __pyx_vtabstruct_5pysam_10libchtslib_HTSFile*)__Pyx_GetVtable(__pyx_ptype_5pysam_10libchtslib_HTSFile->tp_dict); if (unlikely(!__pyx_vtabptr_5pysam_10libchtslib_HTSFile)) __PYX_ERR(5, 2590, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = PyImport_ImportModule("pysam.libcfaidx"); if (unlikely(!__pyx_t_1)) __PYX_ERR(6, 37, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_ptype_5pysam_9libcfaidx_FastaFile = __Pyx_ImportType(__pyx_t_1, "pysam.libcfaidx", "FastaFile", sizeof(struct __pyx_obj_5pysam_9libcfaidx_FastaFile), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5pysam_9libcfaidx_FastaFile) __PYX_ERR(6, 37, __pyx_L1_error) __pyx_vtabptr_5pysam_9libcfaidx_FastaFile = (struct __pyx_vtabstruct_5pysam_9libcfaidx_FastaFile*)__Pyx_GetVtable(__pyx_ptype_5pysam_9libcfaidx_FastaFile->tp_dict); if (unlikely(!__pyx_vtabptr_5pysam_9libcfaidx_FastaFile)) __PYX_ERR(6, 37, __pyx_L1_error) __pyx_ptype_5pysam_9libcfaidx_FastqProxy = __Pyx_ImportType(__pyx_t_1, "pysam.libcfaidx", "FastqProxy", sizeof(struct __pyx_obj_5pysam_9libcfaidx_FastqProxy), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5pysam_9libcfaidx_FastqProxy) __PYX_ERR(6, 45, __pyx_L1_error) __pyx_vtabptr_5pysam_9libcfaidx_FastqProxy = (struct __pyx_vtabstruct_5pysam_9libcfaidx_FastqProxy*)__Pyx_GetVtable(__pyx_ptype_5pysam_9libcfaidx_FastqProxy->tp_dict); if (unlikely(!__pyx_vtabptr_5pysam_9libcfaidx_FastqProxy)) __PYX_ERR(6, 45, __pyx_L1_error) __pyx_ptype_5pysam_9libcfaidx_FastxRecord = __Pyx_ImportType(__pyx_t_1, "pysam.libcfaidx", "FastxRecord", sizeof(struct __pyx_obj_5pysam_9libcfaidx_FastxRecord), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5pysam_9libcfaidx_FastxRecord) __PYX_ERR(6, 52, __pyx_L1_error) __pyx_vtabptr_5pysam_9libcfaidx_FastxRecord = (struct __pyx_vtabstruct_5pysam_9libcfaidx_FastxRecord*)__Pyx_GetVtable(__pyx_ptype_5pysam_9libcfaidx_FastxRecord->tp_dict); if (unlikely(!__pyx_vtabptr_5pysam_9libcfaidx_FastxRecord)) __PYX_ERR(6, 52, __pyx_L1_error) __pyx_ptype_5pysam_9libcfaidx_FastxFile = __Pyx_ImportType(__pyx_t_1, "pysam.libcfaidx", "FastxFile", sizeof(struct __pyx_obj_5pysam_9libcfaidx_FastxFile), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5pysam_9libcfaidx_FastxFile) __PYX_ERR(6, 61, __pyx_L1_error) __pyx_vtabptr_5pysam_9libcfaidx_FastxFile = (struct __pyx_vtabstruct_5pysam_9libcfaidx_FastxFile*)__Pyx_GetVtable(__pyx_ptype_5pysam_9libcfaidx_FastxFile->tp_dict); if (unlikely(!__pyx_vtabptr_5pysam_9libcfaidx_FastxFile)) __PYX_ERR(6, 61, __pyx_L1_error) __pyx_ptype_5pysam_9libcfaidx_FastqFile = __Pyx_ImportType(__pyx_t_1, "pysam.libcfaidx", "FastqFile", sizeof(struct __pyx_obj_5pysam_9libcfaidx_FastqFile), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5pysam_9libcfaidx_FastqFile) __PYX_ERR(6, 73, __pyx_L1_error) __pyx_vtabptr_5pysam_9libcfaidx_FastqFile = (struct __pyx_vtabstruct_5pysam_9libcfaidx_FastqFile*)__Pyx_GetVtable(__pyx_ptype_5pysam_9libcfaidx_FastqFile->tp_dict); if (unlikely(!__pyx_vtabptr_5pysam_9libcfaidx_FastqFile)) __PYX_ERR(6, 73, __pyx_L1_error) __pyx_ptype_5pysam_9libcfaidx_Fastafile = __Pyx_ImportType(__pyx_t_1, "pysam.libcfaidx", "Fastafile", sizeof(struct __pyx_obj_5pysam_9libcfaidx_Fastafile), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5pysam_9libcfaidx_Fastafile) __PYX_ERR(6, 78, __pyx_L1_error) __pyx_vtabptr_5pysam_9libcfaidx_Fastafile = (struct __pyx_vtabstruct_5pysam_9libcfaidx_Fastafile*)__Pyx_GetVtable(__pyx_ptype_5pysam_9libcfaidx_Fastafile->tp_dict); if (unlikely(!__pyx_vtabptr_5pysam_9libcfaidx_Fastafile)) __PYX_ERR(6, 78, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = PyImport_ImportModule("pysam.libcalignedsegment"); if (unlikely(!__pyx_t_1)) __PYX_ERR(7, 34, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_ptype_5pysam_18libcalignedsegment_AlignedSegment = __Pyx_ImportType(__pyx_t_1, "pysam.libcalignedsegment", "AlignedSegment", sizeof(struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5pysam_18libcalignedsegment_AlignedSegment) __PYX_ERR(7, 34, __pyx_L1_error) __pyx_vtabptr_5pysam_18libcalignedsegment_AlignedSegment = (struct __pyx_vtabstruct_5pysam_18libcalignedsegment_AlignedSegment*)__Pyx_GetVtable(__pyx_ptype_5pysam_18libcalignedsegment_AlignedSegment->tp_dict); if (unlikely(!__pyx_vtabptr_5pysam_18libcalignedsegment_AlignedSegment)) __PYX_ERR(7, 34, __pyx_L1_error) __pyx_ptype_5pysam_18libcalignedsegment_PileupColumn = __Pyx_ImportType(__pyx_t_1, "pysam.libcalignedsegment", "PileupColumn", sizeof(struct __pyx_obj_5pysam_18libcalignedsegment_PileupColumn), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5pysam_18libcalignedsegment_PileupColumn) __PYX_ERR(7, 66, __pyx_L1_error) __pyx_ptype_5pysam_18libcalignedsegment_PileupRead = __Pyx_ImportType(__pyx_t_1, "pysam.libcalignedsegment", "PileupRead", sizeof(struct __pyx_obj_5pysam_18libcalignedsegment_PileupRead), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5pysam_18libcalignedsegment_PileupRead) __PYX_ERR(7, 76, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = PyImport_ImportModule("pysam.libcalignmentfile"); if (unlikely(!__pyx_t_1)) __PYX_ERR(8, 41, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader = __Pyx_ImportType(__pyx_t_1, "pysam.libcalignmentfile", "AlignmentHeader", sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader) __PYX_ERR(8, 41, __pyx_L1_error) __pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile = __Pyx_ImportType(__pyx_t_1, "pysam.libcalignmentfile", "AlignmentFile", sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile) __PYX_ERR(8, 44, __pyx_L1_error) __pyx_vtabptr_5pysam_17libcalignmentfile_AlignmentFile = (struct __pyx_vtabstruct_5pysam_17libcalignmentfile_AlignmentFile*)__Pyx_GetVtable(__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile->tp_dict); if (unlikely(!__pyx_vtabptr_5pysam_17libcalignmentfile_AlignmentFile)) __PYX_ERR(8, 44, __pyx_L1_error) __pyx_ptype_5pysam_17libcalignmentfile_PileupColumn = __Pyx_ImportType(__pyx_t_1, "pysam.libcalignmentfile", "PileupColumn", sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_PileupColumn), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5pysam_17libcalignmentfile_PileupColumn) __PYX_ERR(8, 61, __pyx_L1_error) __pyx_ptype_5pysam_17libcalignmentfile_PileupRead = __Pyx_ImportType(__pyx_t_1, "pysam.libcalignmentfile", "PileupRead", sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_PileupRead), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5pysam_17libcalignmentfile_PileupRead) __PYX_ERR(8, 68, __pyx_L1_error) __pyx_ptype_5pysam_17libcalignmentfile_IteratorRow = __Pyx_ImportType(__pyx_t_1, "pysam.libcalignmentfile", "IteratorRow", sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5pysam_17libcalignmentfile_IteratorRow) __PYX_ERR(8, 79, __pyx_L1_error) __pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion = __Pyx_ImportType(__pyx_t_1, "pysam.libcalignmentfile", "IteratorRowRegion", sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion) __PYX_ERR(8, 89, __pyx_L1_error) __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowRegion = (struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowRegion*)__Pyx_GetVtable(__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion->tp_dict); if (unlikely(!__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowRegion)) __PYX_ERR(8, 89, __pyx_L1_error) __pyx_ptype_5pysam_17libcalignmentfile_IteratorRowHead = __Pyx_ImportType(__pyx_t_1, "pysam.libcalignmentfile", "IteratorRowHead", sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowHead) __PYX_ERR(8, 95, __pyx_L1_error) __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowHead = (struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowHead*)__Pyx_GetVtable(__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowHead->tp_dict); if (unlikely(!__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowHead)) __PYX_ERR(8, 95, __pyx_L1_error) __pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAll = __Pyx_ImportType(__pyx_t_1, "pysam.libcalignmentfile", "IteratorRowAll", sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAll) __PYX_ERR(8, 102, __pyx_L1_error) __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowAll = (struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowAll*)__Pyx_GetVtable(__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAll->tp_dict); if (unlikely(!__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowAll)) __PYX_ERR(8, 102, __pyx_L1_error) __pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAllRefs = __Pyx_ImportType(__pyx_t_1, "pysam.libcalignmentfile", "IteratorRowAllRefs", sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAllRefs) __PYX_ERR(8, 107, __pyx_L1_error) __pyx_ptype_5pysam_17libcalignmentfile_IteratorRowSelection = __Pyx_ImportType(__pyx_t_1, "pysam.libcalignmentfile", "IteratorRowSelection", sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowSelection) __PYX_ERR(8, 112, __pyx_L1_error) __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowSelection = (struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowSelection*)__Pyx_GetVtable(__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowSelection->tp_dict); if (unlikely(!__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowSelection)) __PYX_ERR(8, 112, __pyx_L1_error) __pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn = __Pyx_ImportType(__pyx_t_1, "pysam.libcalignmentfile", "IteratorColumn", sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn) __PYX_ERR(8, 119, __pyx_L1_error) __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumn = (struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumn*)__Pyx_GetVtable(__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn->tp_dict); if (unlikely(!__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumn)) __PYX_ERR(8, 119, __pyx_L1_error) __pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnRegion = __Pyx_ImportType(__pyx_t_1, "pysam.libcalignmentfile", "IteratorColumnRegion", sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnRegion), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnRegion) __PYX_ERR(8, 150, __pyx_L1_error) __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumnRegion = (struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumnRegion*)__Pyx_GetVtable(__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnRegion->tp_dict); if (unlikely(!__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumnRegion)) __PYX_ERR(8, 150, __pyx_L1_error) __pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAllRefs = __Pyx_ImportType(__pyx_t_1, "pysam.libcalignmentfile", "IteratorColumnAllRefs", sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAllRefs), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAllRefs) __PYX_ERR(8, 156, __pyx_L1_error) __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumnAllRefs = (struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumnAllRefs*)__Pyx_GetVtable(__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAllRefs->tp_dict); if (unlikely(!__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumnAllRefs)) __PYX_ERR(8, 156, __pyx_L1_error) __pyx_ptype_5pysam_17libcalignmentfile_IndexedReads = __Pyx_ImportType(__pyx_t_1, "pysam.libcalignmentfile", "IndexedReads", sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5pysam_17libcalignmentfile_IndexedReads) __PYX_ERR(8, 160, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_RefNannyFinishContext(); return -1; } static int __Pyx_modinit_variable_import_code(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0); /*--- Variable import code ---*/ __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_modinit_function_import_code(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0); /*--- Function import code ---*/ __Pyx_RefNannyFinishContext(); return 0; } #if PY_MAJOR_VERSION < 3 #ifdef CYTHON_NO_PYINIT_EXPORT #define __Pyx_PyMODINIT_FUNC void #else #define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC #endif #else #ifdef CYTHON_NO_PYINIT_EXPORT #define __Pyx_PyMODINIT_FUNC PyObject * #else #define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC #endif #endif #if PY_MAJOR_VERSION < 3 __Pyx_PyMODINIT_FUNC initreadlen(void) CYTHON_SMALL_CODE; /*proto*/ __Pyx_PyMODINIT_FUNC initreadlen(void) #else __Pyx_PyMODINIT_FUNC PyInit_readlen(void) CYTHON_SMALL_CODE; /*proto*/ __Pyx_PyMODINIT_FUNC PyInit_readlen(void) #if CYTHON_PEP489_MULTI_PHASE_INIT { return PyModuleDef_Init(&__pyx_moduledef); } static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) { #if PY_VERSION_HEX >= 0x030700A1 static PY_INT64_T main_interpreter_id = -1; PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp); if (main_interpreter_id == -1) { main_interpreter_id = current_id; return (unlikely(current_id == -1)) ? -1 : 0; } else if (unlikely(main_interpreter_id != current_id)) #else static PyInterpreterState *main_interpreter = NULL; PyInterpreterState *current_interpreter = PyThreadState_Get()->interp; if (!main_interpreter) { main_interpreter = current_interpreter; } else if (unlikely(main_interpreter != current_interpreter)) #endif { PyErr_SetString( PyExc_ImportError, "Interpreter change detected - this module can only be loaded into one interpreter per process."); return -1; } return 0; } static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) { PyObject *value = PyObject_GetAttrString(spec, from_name); int result = 0; if (likely(value)) { if (allow_none || value != Py_None) { result = PyDict_SetItemString(moddict, to_name, value); } Py_DECREF(value); } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); } else { result = -1; } return result; } static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, CYTHON_UNUSED PyModuleDef *def) { PyObject *module = NULL, *moddict, *modname; if (__Pyx_check_single_interpreter()) return NULL; if (__pyx_m) return __Pyx_NewRef(__pyx_m); modname = PyObject_GetAttrString(spec, "name"); if (unlikely(!modname)) goto bad; module = PyModule_NewObject(modname); Py_DECREF(modname); if (unlikely(!module)) goto bad; moddict = PyModule_GetDict(module); if (unlikely(!moddict)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad; return module; bad: Py_XDECREF(module); return NULL; } static CYTHON_SMALL_CODE int __pyx_pymod_exec_readlen(PyObject *__pyx_pyinit_module) #endif #endif { PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; __Pyx_RefNannyDeclarations #if CYTHON_PEP489_MULTI_PHASE_INIT if (__pyx_m) { if (__pyx_m == __pyx_pyinit_module) return 0; PyErr_SetString(PyExc_RuntimeError, "Module 'readlen' has already been imported. Re-initialisation is not supported."); return -1; } #elif PY_MAJOR_VERSION >= 3 if (__pyx_m) return __Pyx_NewRef(__pyx_m); #endif #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); if (!__Pyx_RefNanny) { PyErr_Clear(); __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); if (!__Pyx_RefNanny) Py_FatalError("failed to import 'refnanny' module"); } #endif __Pyx_RefNannySetupContext("__Pyx_PyMODINIT_FUNC PyInit_readlen(void)", 0); if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #ifdef __Pxy_PyFrame_Initialize_Offsets __Pxy_PyFrame_Initialize_Offsets(); #endif __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) #ifdef __Pyx_CyFunction_USED if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_FusedFunction_USED if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_Coroutine_USED if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_Generator_USED if (__pyx_Generator_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_AsyncGen_USED if (__pyx_AsyncGen_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_StopAsyncIteration_USED if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif /*--- Library function declarations ---*/ /*--- Threads initialization code ---*/ #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS #ifdef WITH_THREAD /* Python build with threading support? */ PyEval_InitThreads(); #endif #endif /*--- Module creation code ---*/ #if CYTHON_PEP489_MULTI_PHASE_INIT __pyx_m = __pyx_pyinit_module; Py_INCREF(__pyx_m); #else #if PY_MAJOR_VERSION < 3 __pyx_m = Py_InitModule4("readlen", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) #endif __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) Py_INCREF(__pyx_d); __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_cython_runtime = PyImport_AddModule((char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) #if CYTHON_COMPILING_IN_PYPY Py_INCREF(__pyx_b); #endif if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error); /*--- Initialize various global constants etc. ---*/ if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif if (__pyx_module_is_main_PyMaSC__core__readlen) { if (PyObject_SetAttr(__pyx_m, __pyx_n_s_name, __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) } #if PY_MAJOR_VERSION >= 3 { PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) if (!PyDict_GetItemString(modules, "PyMaSC.core.readlen")) { if (unlikely(PyDict_SetItemString(modules, "PyMaSC.core.readlen", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error) } } #endif /*--- Builtin init code ---*/ if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Constants init code ---*/ if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Global type/function init code ---*/ (void)__Pyx_modinit_global_init_code(); (void)__Pyx_modinit_variable_export_code(); (void)__Pyx_modinit_function_export_code(); if (unlikely(__Pyx_modinit_type_init_code() != 0)) goto __pyx_L1_error; if (unlikely(__Pyx_modinit_type_import_code() != 0)) goto __pyx_L1_error; (void)__Pyx_modinit_variable_import_code(); (void)__Pyx_modinit_function_import_code(); /*--- Execution code ---*/ #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif /* "PyMaSC/core/readlen.pyx":1 * import logging # <<<<<<<<<<<<<< * * from pysam.libcalignmentfile cimport AlignmentFile */ __pyx_t_1 = __Pyx_Import(__pyx_n_s_logging, 0, -1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_logging, __pyx_t_1) < 0) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "PyMaSC/core/readlen.pyx":6 * from pysam.libcalignedsegment cimport AlignedSegment * * from PyMaSC.utils.progress import ReadCountProgressBar # <<<<<<<<<<<<<< * * logger = logging.getLogger(__name__) */ __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 6, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(__pyx_n_s_ReadCountProgressBar); __Pyx_GIVEREF(__pyx_n_s_ReadCountProgressBar); PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_ReadCountProgressBar); __pyx_t_2 = __Pyx_Import(__pyx_n_s_PyMaSC_utils_progress, __pyx_t_1, -1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 6, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_ReadCountProgressBar); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 6, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_ReadCountProgressBar, __pyx_t_1) < 0) __PYX_ERR(0, 6, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "PyMaSC/core/readlen.pyx":8 * from PyMaSC.utils.progress import ReadCountProgressBar * * logger = logging.getLogger(__name__) # <<<<<<<<<<<<<< * * */ __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_logging); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 8, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_getLogger); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 8, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_name); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 8, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 8, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (PyDict_SetItem(__pyx_d, __pyx_n_s_logger, __pyx_t_3) < 0) __PYX_ERR(0, 8, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "PyMaSC/core/readlen.pyx":11 * * * def _mean(c): # <<<<<<<<<<<<<< * return int(round( * sum(length * freq for length, freq in c.items()) / float(sum(c.values())) */ __pyx_t_3 = PyCFunction_NewEx(&__pyx_mdef_6PyMaSC_4core_7readlen_1_mean, NULL, __pyx_n_s_PyMaSC_core_readlen); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 11, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_d, __pyx_n_s_mean, __pyx_t_3) < 0) __PYX_ERR(0, 11, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "PyMaSC/core/readlen.pyx":17 * * * def _median(c): # <<<<<<<<<<<<<< * num = sum(c.values()) * target = num / 2 */ __pyx_t_3 = PyCFunction_NewEx(&__pyx_mdef_6PyMaSC_4core_7readlen_3_median, NULL, __pyx_n_s_PyMaSC_core_readlen); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 17, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_d, __pyx_n_s_median, __pyx_t_3) < 0) __PYX_ERR(0, 17, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "PyMaSC/core/readlen.pyx":37 * * * def _mode(c): # <<<<<<<<<<<<<< * return [k for k, v in sorted(c.items(), key=lambda x: x[1])][-1] * */ __pyx_t_3 = PyCFunction_NewEx(&__pyx_mdef_6PyMaSC_4core_7readlen_5_mode, NULL, __pyx_n_s_PyMaSC_core_readlen); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 37, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_d, __pyx_n_s_mode, __pyx_t_3) < 0) __PYX_ERR(0, 37, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "PyMaSC/core/readlen.pyx":42 * * ESTFUNCTIONS = dict( * MEAN=_mean, MEDIAN=_median, MODE=_mode, MIN=min, MAX=max # <<<<<<<<<<<<<< * ) * */ __pyx_t_3 = __Pyx_PyDict_NewPresized(5); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 42, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_mean); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 42, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_MEAN, __pyx_t_2) < 0) __PYX_ERR(0, 42, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_median); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 42, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_MEDIAN, __pyx_t_2) < 0) __PYX_ERR(0, 42, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_mode); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 42, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_MODE, __pyx_t_2) < 0) __PYX_ERR(0, 42, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_MIN, __pyx_builtin_min) < 0) __PYX_ERR(0, 42, __pyx_L1_error) if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_MAX, __pyx_builtin_max) < 0) __PYX_ERR(0, 42, __pyx_L1_error) if (PyDict_SetItem(__pyx_d, __pyx_n_s_ESTFUNCTIONS, __pyx_t_3) < 0) __PYX_ERR(0, 41, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "PyMaSC/core/readlen.pyx":46 * * * def estimate_readlen(path, esttype, unsigned int mapq_criteria): # <<<<<<<<<<<<<< * estfunc = ESTFUNCTIONS[esttype] * */ __pyx_t_3 = PyCFunction_NewEx(&__pyx_mdef_6PyMaSC_4core_7readlen_7estimate_readlen, NULL, __pyx_n_s_PyMaSC_core_readlen); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 46, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_d, __pyx_n_s_estimate_readlen, __pyx_t_3) < 0) __PYX_ERR(0, 46, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "PyMaSC/core/readlen.pyx":1 * import logging # <<<<<<<<<<<<<< * * from pysam.libcalignmentfile cimport AlignmentFile */ __pyx_t_3 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_3) < 0) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "array.pxd":161 * return extend_buffer(self, other.data.as_chars, Py_SIZE(other)) * * cdef inline void zero(array self): # <<<<<<<<<<<<<< * """ set all elements of array to zero. """ * memset(self.data.as_chars, 0, Py_SIZE(self) * self.ob_descr.itemsize) */ /*--- Wrapped vars code ---*/ goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); if (__pyx_m) { if (__pyx_d) { __Pyx_AddTraceback("init PyMaSC.core.readlen", __pyx_clineno, __pyx_lineno, __pyx_filename); } Py_CLEAR(__pyx_m); } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "init PyMaSC.core.readlen"); } __pyx_L0:; __Pyx_RefNannyFinishContext(); #if CYTHON_PEP489_MULTI_PHASE_INIT return (__pyx_m != NULL) ? 0 : -1; #elif PY_MAJOR_VERSION >= 3 return __pyx_m; #else return; #endif } /* --- Runtime support code --- */ /* Refnanny */ #if CYTHON_REFNANNY static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; void *r = NULL; m = PyImport_ImportModule(modname); if (!m) goto end; p = PyObject_GetAttrString(m, "RefNannyAPI"); if (!p) goto end; r = PyLong_AsVoidPtr(p); end: Py_XDECREF(p); Py_XDECREF(m); return (__Pyx_RefNannyAPIStruct *)r; } #endif /* PyObjectGetAttrStr */ #if CYTHON_USE_TYPE_SLOTS static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { PyTypeObject* tp = Py_TYPE(obj); if (likely(tp->tp_getattro)) return tp->tp_getattro(obj, attr_name); #if PY_MAJOR_VERSION < 3 if (likely(tp->tp_getattr)) return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); #endif return PyObject_GetAttr(obj, attr_name); } #endif /* GetBuiltinName */ static PyObject *__Pyx_GetBuiltinName(PyObject *name) { PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); if (unlikely(!result)) { PyErr_Format(PyExc_NameError, #if PY_MAJOR_VERSION >= 3 "name '%U' is not defined", name); #else "name '%.200s' is not defined", PyString_AS_STRING(name)); #endif } return result; } /* None */ static CYTHON_INLINE void __Pyx_RaiseClosureNameError(const char *varname) { PyErr_Format(PyExc_NameError, "free variable '%s' referenced before assignment in enclosing scope", varname); } /* PyFunctionFastCall */ #if CYTHON_FAST_PYCALL static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args, Py_ssize_t na, PyObject *globals) { PyFrameObject *f; PyThreadState *tstate = __Pyx_PyThreadState_Current; PyObject **fastlocals; Py_ssize_t i; PyObject *result; assert(globals != NULL); /* XXX Perhaps we should create a specialized PyFrame_New() that doesn't take locals, but does take builtins without sanity checking them. */ assert(tstate != NULL); f = PyFrame_New(tstate, co, globals, NULL); if (f == NULL) { return NULL; } fastlocals = __Pyx_PyFrame_GetLocalsplus(f); for (i = 0; i < na; i++) { Py_INCREF(*args); fastlocals[i] = *args++; } result = PyEval_EvalFrameEx(f,0); ++tstate->recursion_depth; Py_DECREF(f); --tstate->recursion_depth; return result; } #if 1 || PY_VERSION_HEX < 0x030600B1 static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, int nargs, PyObject *kwargs) { PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); PyObject *globals = PyFunction_GET_GLOBALS(func); PyObject *argdefs = PyFunction_GET_DEFAULTS(func); PyObject *closure; #if PY_MAJOR_VERSION >= 3 PyObject *kwdefs; #endif PyObject *kwtuple, **k; PyObject **d; Py_ssize_t nd; Py_ssize_t nk; PyObject *result; assert(kwargs == NULL || PyDict_Check(kwargs)); nk = kwargs ? PyDict_Size(kwargs) : 0; if (Py_EnterRecursiveCall((char*)" while calling a Python object")) { return NULL; } if ( #if PY_MAJOR_VERSION >= 3 co->co_kwonlyargcount == 0 && #endif likely(kwargs == NULL || nk == 0) && co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { if (argdefs == NULL && co->co_argcount == nargs) { result = __Pyx_PyFunction_FastCallNoKw(co, args, nargs, globals); goto done; } else if (nargs == 0 && argdefs != NULL && co->co_argcount == Py_SIZE(argdefs)) { /* function called with no arguments, but all parameters have a default value: use default values as arguments .*/ args = &PyTuple_GET_ITEM(argdefs, 0); result =__Pyx_PyFunction_FastCallNoKw(co, args, Py_SIZE(argdefs), globals); goto done; } } if (kwargs != NULL) { Py_ssize_t pos, i; kwtuple = PyTuple_New(2 * nk); if (kwtuple == NULL) { result = NULL; goto done; } k = &PyTuple_GET_ITEM(kwtuple, 0); pos = i = 0; while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) { Py_INCREF(k[i]); Py_INCREF(k[i+1]); i += 2; } nk = i / 2; } else { kwtuple = NULL; k = NULL; } closure = PyFunction_GET_CLOSURE(func); #if PY_MAJOR_VERSION >= 3 kwdefs = PyFunction_GET_KW_DEFAULTS(func); #endif if (argdefs != NULL) { d = &PyTuple_GET_ITEM(argdefs, 0); nd = Py_SIZE(argdefs); } else { d = NULL; nd = 0; } #if PY_MAJOR_VERSION >= 3 result = PyEval_EvalCodeEx((PyObject*)co, globals, (PyObject *)NULL, args, nargs, k, (int)nk, d, (int)nd, kwdefs, closure); #else result = PyEval_EvalCodeEx(co, globals, (PyObject *)NULL, args, nargs, k, (int)nk, d, (int)nd, closure); #endif Py_XDECREF(kwtuple); done: Py_LeaveRecursiveCall(); return result; } #endif #endif /* PyObjectCall */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { PyObject *result; ternaryfunc call = func->ob_type->tp_call; if (unlikely(!call)) return PyObject_Call(func, arg, kw); if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) return NULL; result = (*call)(func, arg, kw); Py_LeaveRecursiveCall(); if (unlikely(!result) && unlikely(!PyErr_Occurred())) { PyErr_SetString( PyExc_SystemError, "NULL result without error in PyObject_Call"); } return result; } #endif /* PyObjectCallMethO */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { PyObject *self, *result; PyCFunction cfunc; cfunc = PyCFunction_GET_FUNCTION(func); self = PyCFunction_GET_SELF(func); if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) return NULL; result = cfunc(self, arg); Py_LeaveRecursiveCall(); if (unlikely(!result) && unlikely(!PyErr_Occurred())) { PyErr_SetString( PyExc_SystemError, "NULL result without error in PyObject_Call"); } return result; } #endif /* PyObjectCallNoArg */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { #if CYTHON_FAST_PYCALL if (PyFunction_Check(func)) { return __Pyx_PyFunction_FastCall(func, NULL, 0); } #endif #ifdef __Pyx_CyFunction_USED if (likely(PyCFunction_Check(func) || __Pyx_CyFunction_Check(func))) #else if (likely(PyCFunction_Check(func))) #endif { if (likely(PyCFunction_GET_FLAGS(func) & METH_NOARGS)) { return __Pyx_PyObject_CallMethO(func, NULL); } } return __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL); } #endif /* PyCFunctionFastCall */ #if CYTHON_FAST_PYCCALL static CYTHON_INLINE PyObject * __Pyx_PyCFunction_FastCall(PyObject *func_obj, PyObject **args, Py_ssize_t nargs) { PyCFunctionObject *func = (PyCFunctionObject*)func_obj; PyCFunction meth = PyCFunction_GET_FUNCTION(func); PyObject *self = PyCFunction_GET_SELF(func); int flags = PyCFunction_GET_FLAGS(func); assert(PyCFunction_Check(func)); assert(METH_FASTCALL == (flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))); assert(nargs >= 0); assert(nargs == 0 || args != NULL); /* _PyCFunction_FastCallDict() must not be called with an exception set, because it may clear it (directly or indirectly) and so the caller loses its exception */ assert(!PyErr_Occurred()); if ((PY_VERSION_HEX < 0x030700A0) || unlikely(flags & METH_KEYWORDS)) { return (*((__Pyx_PyCFunctionFastWithKeywords)(void*)meth)) (self, args, nargs, NULL); } else { return (*((__Pyx_PyCFunctionFast)(void*)meth)) (self, args, nargs); } } #endif /* PyObjectCallOneArg */ #if CYTHON_COMPILING_IN_CPYTHON static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { PyObject *result; PyObject *args = PyTuple_New(1); if (unlikely(!args)) return NULL; Py_INCREF(arg); PyTuple_SET_ITEM(args, 0, arg); result = __Pyx_PyObject_Call(func, args, NULL); Py_DECREF(args); return result; } static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { #if CYTHON_FAST_PYCALL if (PyFunction_Check(func)) { return __Pyx_PyFunction_FastCall(func, &arg, 1); } #endif if (likely(PyCFunction_Check(func))) { if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { return __Pyx_PyObject_CallMethO(func, arg); #if CYTHON_FAST_PYCCALL } else if (PyCFunction_GET_FLAGS(func) & METH_FASTCALL) { return __Pyx_PyCFunction_FastCall(func, &arg, 1); #endif } } return __Pyx__PyObject_CallOneArg(func, arg); } #else static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { PyObject *result; PyObject *args = PyTuple_Pack(1, arg); if (unlikely(!args)) return NULL; result = __Pyx_PyObject_Call(func, args, NULL); Py_DECREF(args); return result; } #endif /* RaiseTooManyValuesToUnpack */ static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { PyErr_Format(PyExc_ValueError, "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); } /* RaiseNeedMoreValuesToUnpack */ static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { PyErr_Format(PyExc_ValueError, "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", index, (index == 1) ? "" : "s"); } /* IterFinish */ static CYTHON_INLINE int __Pyx_IterFinish(void) { #if CYTHON_FAST_THREAD_STATE PyThreadState *tstate = __Pyx_PyThreadState_Current; PyObject* exc_type = tstate->curexc_type; if (unlikely(exc_type)) { if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) { PyObject *exc_value, *exc_tb; exc_value = tstate->curexc_value; exc_tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; Py_DECREF(exc_type); Py_XDECREF(exc_value); Py_XDECREF(exc_tb); return 0; } else { return -1; } } return 0; #else if (unlikely(PyErr_Occurred())) { if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { PyErr_Clear(); return 0; } else { return -1; } } return 0; #endif } /* UnpackItemEndCheck */ static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { if (unlikely(retval)) { Py_DECREF(retval); __Pyx_RaiseTooManyValuesError(expected); return -1; } else { return __Pyx_IterFinish(); } return 0; } /* PyIntBinop */ #if !CYTHON_COMPILING_IN_PYPY static PyObject* __Pyx_PyInt_RemainderObjC(PyObject *op1, PyObject *op2, CYTHON_UNUSED long intval, CYTHON_UNUSED int inplace) { #if PY_MAJOR_VERSION < 3 if (likely(PyInt_CheckExact(op1))) { const long b = intval; long x; long a = PyInt_AS_LONG(op1); x = a % b; x += ((x != 0) & ((x ^ b) < 0)) * b; return PyInt_FromLong(x); } #endif #if CYTHON_USE_PYLONG_INTERNALS if (likely(PyLong_CheckExact(op1))) { const long b = intval; long a, x; #ifdef HAVE_LONG_LONG const PY_LONG_LONG llb = intval; PY_LONG_LONG lla, llx; #endif const digit* digits = ((PyLongObject*)op1)->ob_digit; const Py_ssize_t size = Py_SIZE(op1); if (likely(__Pyx_sst_abs(size) <= 1)) { a = likely(size) ? digits[0] : 0; if (size == -1) a = -a; } else { switch (size) { case -2: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { a = -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { lla = -(PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; case 2: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { lla = (PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; case -3: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { a = -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { lla = -(PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; case 3: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { lla = (PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; case -4: if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { a = -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { lla = -(PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; case 4: if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { a = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { lla = (PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; default: return PyLong_Type.tp_as_number->nb_remainder(op1, op2); } } x = a % b; x += ((x != 0) & ((x ^ b) < 0)) * b; return PyLong_FromLong(x); #ifdef HAVE_LONG_LONG long_long: llx = lla % llb; llx += ((llx != 0) & ((llx ^ llb) < 0)) * llb; return PyLong_FromLongLong(llx); #endif } #endif return (inplace ? PyNumber_InPlaceRemainder : PyNumber_Remainder)(op1, op2); } #endif /* GetItemInt */ static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { PyObject *r; if (!j) return NULL; r = PyObject_GetItem(o, j); Py_DECREF(j); return r; } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS Py_ssize_t wrapped_i = i; if (wraparound & unlikely(i < 0)) { wrapped_i += PyList_GET_SIZE(o); } if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyList_GET_SIZE(o)))) { PyObject *r = PyList_GET_ITEM(o, wrapped_i); Py_INCREF(r); return r; } return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); #else return PySequence_GetItem(o, i); #endif } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS Py_ssize_t wrapped_i = i; if (wraparound & unlikely(i < 0)) { wrapped_i += PyTuple_GET_SIZE(o); } if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyTuple_GET_SIZE(o)))) { PyObject *r = PyTuple_GET_ITEM(o, wrapped_i); Py_INCREF(r); return r; } return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); #else return PySequence_GetItem(o, i); #endif } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS && CYTHON_USE_TYPE_SLOTS if (is_list || PyList_CheckExact(o)) { Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); if ((!boundscheck) || (likely(__Pyx_is_valid_index(n, PyList_GET_SIZE(o))))) { PyObject *r = PyList_GET_ITEM(o, n); Py_INCREF(r); return r; } } else if (PyTuple_CheckExact(o)) { Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); if ((!boundscheck) || likely(__Pyx_is_valid_index(n, PyTuple_GET_SIZE(o)))) { PyObject *r = PyTuple_GET_ITEM(o, n); Py_INCREF(r); return r; } } else { PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; if (likely(m && m->sq_item)) { if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { Py_ssize_t l = m->sq_length(o); if (likely(l >= 0)) { i += l; } else { if (!PyErr_ExceptionMatches(PyExc_OverflowError)) return NULL; PyErr_Clear(); } } return m->sq_item(o, i); } } #else if (is_list || PySequence_Check(o)) { return PySequence_GetItem(o, i); } #endif return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); } /* ObjectGetItem */ #if CYTHON_USE_TYPE_SLOTS static PyObject *__Pyx_PyObject_GetIndex(PyObject *obj, PyObject* index) { PyObject *runerr; Py_ssize_t key_value; PySequenceMethods *m = Py_TYPE(obj)->tp_as_sequence; if (unlikely(!(m && m->sq_item))) { PyErr_Format(PyExc_TypeError, "'%.200s' object is not subscriptable", Py_TYPE(obj)->tp_name); return NULL; } key_value = __Pyx_PyIndex_AsSsize_t(index); if (likely(key_value != -1 || !(runerr = PyErr_Occurred()))) { return __Pyx_GetItemInt_Fast(obj, key_value, 0, 1, 1); } if (PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) { PyErr_Clear(); PyErr_Format(PyExc_IndexError, "cannot fit '%.200s' into an index-sized integer", Py_TYPE(index)->tp_name); } return NULL; } static PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject* key) { PyMappingMethods *m = Py_TYPE(obj)->tp_as_mapping; if (likely(m && m->mp_subscript)) { return m->mp_subscript(obj, key); } return __Pyx_PyObject_GetIndex(obj, key); } #endif /* PyIntBinop */ #if !CYTHON_COMPILING_IN_PYPY static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, CYTHON_UNUSED long intval, CYTHON_UNUSED int inplace) { #if PY_MAJOR_VERSION < 3 if (likely(PyInt_CheckExact(op1))) { const long b = intval; long x; long a = PyInt_AS_LONG(op1); x = (long)((unsigned long)a + b); if (likely((x^a) >= 0 || (x^b) >= 0)) return PyInt_FromLong(x); return PyLong_Type.tp_as_number->nb_add(op1, op2); } #endif #if CYTHON_USE_PYLONG_INTERNALS if (likely(PyLong_CheckExact(op1))) { const long b = intval; long a, x; #ifdef HAVE_LONG_LONG const PY_LONG_LONG llb = intval; PY_LONG_LONG lla, llx; #endif const digit* digits = ((PyLongObject*)op1)->ob_digit; const Py_ssize_t size = Py_SIZE(op1); if (likely(__Pyx_sst_abs(size) <= 1)) { a = likely(size) ? digits[0] : 0; if (size == -1) a = -a; } else { switch (size) { case -2: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { a = -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { lla = -(PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; case 2: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { lla = (PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; case -3: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { a = -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { lla = -(PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; case 3: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { lla = (PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; case -4: if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { a = -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { lla = -(PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; case 4: if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { a = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { lla = (PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; default: return PyLong_Type.tp_as_number->nb_add(op1, op2); } } x = a + b; return PyLong_FromLong(x); #ifdef HAVE_LONG_LONG long_long: llx = lla + llb; return PyLong_FromLongLong(llx); #endif } #endif if (PyFloat_CheckExact(op1)) { const long b = intval; double a = PyFloat_AS_DOUBLE(op1); double result; PyFPE_START_PROTECT("add", return NULL) result = ((double)a) + (double)b; PyFPE_END_PROTECT(result) return PyFloat_FromDouble(result); } return (inplace ? PyNumber_InPlaceAdd : PyNumber_Add)(op1, op2); } #endif /* FetchCommonType */ static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type) { PyObject* fake_module; PyTypeObject* cached_type = NULL; fake_module = PyImport_AddModule((char*) "_cython_" CYTHON_ABI); if (!fake_module) return NULL; Py_INCREF(fake_module); cached_type = (PyTypeObject*) PyObject_GetAttrString(fake_module, type->tp_name); if (cached_type) { if (!PyType_Check((PyObject*)cached_type)) { PyErr_Format(PyExc_TypeError, "Shared Cython type %.200s is not a type object", type->tp_name); goto bad; } if (cached_type->tp_basicsize != type->tp_basicsize) { PyErr_Format(PyExc_TypeError, "Shared Cython type %.200s has the wrong size, try recompiling", type->tp_name); goto bad; } } else { if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto bad; PyErr_Clear(); if (PyType_Ready(type) < 0) goto bad; if (PyObject_SetAttrString(fake_module, type->tp_name, (PyObject*) type) < 0) goto bad; Py_INCREF(type); cached_type = type; } done: Py_DECREF(fake_module); return cached_type; bad: Py_XDECREF(cached_type); cached_type = NULL; goto done; } /* CythonFunction */ #include <structmember.h> static PyObject * __Pyx_CyFunction_get_doc(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *closure) { if (unlikely(op->func_doc == NULL)) { if (op->func.m_ml->ml_doc) { #if PY_MAJOR_VERSION >= 3 op->func_doc = PyUnicode_FromString(op->func.m_ml->ml_doc); #else op->func_doc = PyString_FromString(op->func.m_ml->ml_doc); #endif if (unlikely(op->func_doc == NULL)) return NULL; } else { Py_INCREF(Py_None); return Py_None; } } Py_INCREF(op->func_doc); return op->func_doc; } static int __Pyx_CyFunction_set_doc(__pyx_CyFunctionObject *op, PyObject *value, CYTHON_UNUSED void *context) { PyObject *tmp = op->func_doc; if (value == NULL) { value = Py_None; } Py_INCREF(value); op->func_doc = value; Py_XDECREF(tmp); return 0; } static PyObject * __Pyx_CyFunction_get_name(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) { if (unlikely(op->func_name == NULL)) { #if PY_MAJOR_VERSION >= 3 op->func_name = PyUnicode_InternFromString(op->func.m_ml->ml_name); #else op->func_name = PyString_InternFromString(op->func.m_ml->ml_name); #endif if (unlikely(op->func_name == NULL)) return NULL; } Py_INCREF(op->func_name); return op->func_name; } static int __Pyx_CyFunction_set_name(__pyx_CyFunctionObject *op, PyObject *value, CYTHON_UNUSED void *context) { PyObject *tmp; #if PY_MAJOR_VERSION >= 3 if (unlikely(value == NULL || !PyUnicode_Check(value))) #else if (unlikely(value == NULL || !PyString_Check(value))) #endif { PyErr_SetString(PyExc_TypeError, "__name__ must be set to a string object"); return -1; } tmp = op->func_name; Py_INCREF(value); op->func_name = value; Py_XDECREF(tmp); return 0; } static PyObject * __Pyx_CyFunction_get_qualname(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) { Py_INCREF(op->func_qualname); return op->func_qualname; } static int __Pyx_CyFunction_set_qualname(__pyx_CyFunctionObject *op, PyObject *value, CYTHON_UNUSED void *context) { PyObject *tmp; #if PY_MAJOR_VERSION >= 3 if (unlikely(value == NULL || !PyUnicode_Check(value))) #else if (unlikely(value == NULL || !PyString_Check(value))) #endif { PyErr_SetString(PyExc_TypeError, "__qualname__ must be set to a string object"); return -1; } tmp = op->func_qualname; Py_INCREF(value); op->func_qualname = value; Py_XDECREF(tmp); return 0; } static PyObject * __Pyx_CyFunction_get_self(__pyx_CyFunctionObject *m, CYTHON_UNUSED void *closure) { PyObject *self; self = m->func_closure; if (self == NULL) self = Py_None; Py_INCREF(self); return self; } static PyObject * __Pyx_CyFunction_get_dict(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) { if (unlikely(op->func_dict == NULL)) { op->func_dict = PyDict_New(); if (unlikely(op->func_dict == NULL)) return NULL; } Py_INCREF(op->func_dict); return op->func_dict; } static int __Pyx_CyFunction_set_dict(__pyx_CyFunctionObject *op, PyObject *value, CYTHON_UNUSED void *context) { PyObject *tmp; if (unlikely(value == NULL)) { PyErr_SetString(PyExc_TypeError, "function's dictionary may not be deleted"); return -1; } if (unlikely(!PyDict_Check(value))) { PyErr_SetString(PyExc_TypeError, "setting function's dictionary to a non-dict"); return -1; } tmp = op->func_dict; Py_INCREF(value); op->func_dict = value; Py_XDECREF(tmp); return 0; } static PyObject * __Pyx_CyFunction_get_globals(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) { Py_INCREF(op->func_globals); return op->func_globals; } static PyObject * __Pyx_CyFunction_get_closure(CYTHON_UNUSED __pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) { Py_INCREF(Py_None); return Py_None; } static PyObject * __Pyx_CyFunction_get_code(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) { PyObject* result = (op->func_code) ? op->func_code : Py_None; Py_INCREF(result); return result; } static int __Pyx_CyFunction_init_defaults(__pyx_CyFunctionObject *op) { int result = 0; PyObject *res = op->defaults_getter((PyObject *) op); if (unlikely(!res)) return -1; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS op->defaults_tuple = PyTuple_GET_ITEM(res, 0); Py_INCREF(op->defaults_tuple); op->defaults_kwdict = PyTuple_GET_ITEM(res, 1); Py_INCREF(op->defaults_kwdict); #else op->defaults_tuple = PySequence_ITEM(res, 0); if (unlikely(!op->defaults_tuple)) result = -1; else { op->defaults_kwdict = PySequence_ITEM(res, 1); if (unlikely(!op->defaults_kwdict)) result = -1; } #endif Py_DECREF(res); return result; } static int __Pyx_CyFunction_set_defaults(__pyx_CyFunctionObject *op, PyObject* value, CYTHON_UNUSED void *context) { PyObject* tmp; if (!value) { value = Py_None; } else if (value != Py_None && !PyTuple_Check(value)) { PyErr_SetString(PyExc_TypeError, "__defaults__ must be set to a tuple object"); return -1; } Py_INCREF(value); tmp = op->defaults_tuple; op->defaults_tuple = value; Py_XDECREF(tmp); return 0; } static PyObject * __Pyx_CyFunction_get_defaults(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) { PyObject* result = op->defaults_tuple; if (unlikely(!result)) { if (op->defaults_getter) { if (__Pyx_CyFunction_init_defaults(op) < 0) return NULL; result = op->defaults_tuple; } else { result = Py_None; } } Py_INCREF(result); return result; } static int __Pyx_CyFunction_set_kwdefaults(__pyx_CyFunctionObject *op, PyObject* value, CYTHON_UNUSED void *context) { PyObject* tmp; if (!value) { value = Py_None; } else if (value != Py_None && !PyDict_Check(value)) { PyErr_SetString(PyExc_TypeError, "__kwdefaults__ must be set to a dict object"); return -1; } Py_INCREF(value); tmp = op->defaults_kwdict; op->defaults_kwdict = value; Py_XDECREF(tmp); return 0; } static PyObject * __Pyx_CyFunction_get_kwdefaults(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) { PyObject* result = op->defaults_kwdict; if (unlikely(!result)) { if (op->defaults_getter) { if (__Pyx_CyFunction_init_defaults(op) < 0) return NULL; result = op->defaults_kwdict; } else { result = Py_None; } } Py_INCREF(result); return result; } static int __Pyx_CyFunction_set_annotations(__pyx_CyFunctionObject *op, PyObject* value, CYTHON_UNUSED void *context) { PyObject* tmp; if (!value || value == Py_None) { value = NULL; } else if (!PyDict_Check(value)) { PyErr_SetString(PyExc_TypeError, "__annotations__ must be set to a dict object"); return -1; } Py_XINCREF(value); tmp = op->func_annotations; op->func_annotations = value; Py_XDECREF(tmp); return 0; } static PyObject * __Pyx_CyFunction_get_annotations(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) { PyObject* result = op->func_annotations; if (unlikely(!result)) { result = PyDict_New(); if (unlikely(!result)) return NULL; op->func_annotations = result; } Py_INCREF(result); return result; } static PyGetSetDef __pyx_CyFunction_getsets[] = { {(char *) "func_doc", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, {(char *) "__doc__", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, {(char *) "func_name", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, {(char *) "__name__", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, {(char *) "__qualname__", (getter)__Pyx_CyFunction_get_qualname, (setter)__Pyx_CyFunction_set_qualname, 0, 0}, {(char *) "__self__", (getter)__Pyx_CyFunction_get_self, 0, 0, 0}, {(char *) "func_dict", (getter)__Pyx_CyFunction_get_dict, (setter)__Pyx_CyFunction_set_dict, 0, 0}, {(char *) "__dict__", (getter)__Pyx_CyFunction_get_dict, (setter)__Pyx_CyFunction_set_dict, 0, 0}, {(char *) "func_globals", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, {(char *) "__globals__", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, {(char *) "func_closure", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, {(char *) "__closure__", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, {(char *) "func_code", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, {(char *) "__code__", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, {(char *) "func_defaults", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, {(char *) "__defaults__", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, {(char *) "__kwdefaults__", (getter)__Pyx_CyFunction_get_kwdefaults, (setter)__Pyx_CyFunction_set_kwdefaults, 0, 0}, {(char *) "__annotations__", (getter)__Pyx_CyFunction_get_annotations, (setter)__Pyx_CyFunction_set_annotations, 0, 0}, {0, 0, 0, 0, 0} }; static PyMemberDef __pyx_CyFunction_members[] = { {(char *) "__module__", T_OBJECT, offsetof(PyCFunctionObject, m_module), PY_WRITE_RESTRICTED, 0}, {0, 0, 0, 0, 0} }; static PyObject * __Pyx_CyFunction_reduce(__pyx_CyFunctionObject *m, CYTHON_UNUSED PyObject *args) { #if PY_MAJOR_VERSION >= 3 return PyUnicode_FromString(m->func.m_ml->ml_name); #else return PyString_FromString(m->func.m_ml->ml_name); #endif } static PyMethodDef __pyx_CyFunction_methods[] = { {"__reduce__", (PyCFunction)__Pyx_CyFunction_reduce, METH_VARARGS, 0}, {0, 0, 0, 0} }; #if PY_VERSION_HEX < 0x030500A0 #define __Pyx_CyFunction_weakreflist(cyfunc) ((cyfunc)->func_weakreflist) #else #define __Pyx_CyFunction_weakreflist(cyfunc) ((cyfunc)->func.m_weakreflist) #endif static PyObject *__Pyx_CyFunction_New(PyTypeObject *type, PyMethodDef *ml, int flags, PyObject* qualname, PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { __pyx_CyFunctionObject *op = PyObject_GC_New(__pyx_CyFunctionObject, type); if (op == NULL) return NULL; op->flags = flags; __Pyx_CyFunction_weakreflist(op) = NULL; op->func.m_ml = ml; op->func.m_self = (PyObject *) op; Py_XINCREF(closure); op->func_closure = closure; Py_XINCREF(module); op->func.m_module = module; op->func_dict = NULL; op->func_name = NULL; Py_INCREF(qualname); op->func_qualname = qualname; op->func_doc = NULL; op->func_classobj = NULL; op->func_globals = globals; Py_INCREF(op->func_globals); Py_XINCREF(code); op->func_code = code; op->defaults_pyobjects = 0; op->defaults = NULL; op->defaults_tuple = NULL; op->defaults_kwdict = NULL; op->defaults_getter = NULL; op->func_annotations = NULL; PyObject_GC_Track(op); return (PyObject *) op; } static int __Pyx_CyFunction_clear(__pyx_CyFunctionObject *m) { Py_CLEAR(m->func_closure); Py_CLEAR(m->func.m_module); Py_CLEAR(m->func_dict); Py_CLEAR(m->func_name); Py_CLEAR(m->func_qualname); Py_CLEAR(m->func_doc); Py_CLEAR(m->func_globals); Py_CLEAR(m->func_code); Py_CLEAR(m->func_classobj); Py_CLEAR(m->defaults_tuple); Py_CLEAR(m->defaults_kwdict); Py_CLEAR(m->func_annotations); if (m->defaults) { PyObject **pydefaults = __Pyx_CyFunction_Defaults(PyObject *, m); int i; for (i = 0; i < m->defaults_pyobjects; i++) Py_XDECREF(pydefaults[i]); PyObject_Free(m->defaults); m->defaults = NULL; } return 0; } static void __Pyx__CyFunction_dealloc(__pyx_CyFunctionObject *m) { if (__Pyx_CyFunction_weakreflist(m) != NULL) PyObject_ClearWeakRefs((PyObject *) m); __Pyx_CyFunction_clear(m); PyObject_GC_Del(m); } static void __Pyx_CyFunction_dealloc(__pyx_CyFunctionObject *m) { PyObject_GC_UnTrack(m); __Pyx__CyFunction_dealloc(m); } static int __Pyx_CyFunction_traverse(__pyx_CyFunctionObject *m, visitproc visit, void *arg) { Py_VISIT(m->func_closure); Py_VISIT(m->func.m_module); Py_VISIT(m->func_dict); Py_VISIT(m->func_name); Py_VISIT(m->func_qualname); Py_VISIT(m->func_doc); Py_VISIT(m->func_globals); Py_VISIT(m->func_code); Py_VISIT(m->func_classobj); Py_VISIT(m->defaults_tuple); Py_VISIT(m->defaults_kwdict); if (m->defaults) { PyObject **pydefaults = __Pyx_CyFunction_Defaults(PyObject *, m); int i; for (i = 0; i < m->defaults_pyobjects; i++) Py_VISIT(pydefaults[i]); } return 0; } static PyObject *__Pyx_CyFunction_descr_get(PyObject *func, PyObject *obj, PyObject *type) { __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; if (m->flags & __Pyx_CYFUNCTION_STATICMETHOD) { Py_INCREF(func); return func; } if (m->flags & __Pyx_CYFUNCTION_CLASSMETHOD) { if (type == NULL) type = (PyObject *)(Py_TYPE(obj)); return __Pyx_PyMethod_New(func, type, (PyObject *)(Py_TYPE(type))); } if (obj == Py_None) obj = NULL; return __Pyx_PyMethod_New(func, obj, type); } static PyObject* __Pyx_CyFunction_repr(__pyx_CyFunctionObject *op) { #if PY_MAJOR_VERSION >= 3 return PyUnicode_FromFormat("<cyfunction %U at %p>", op->func_qualname, (void *)op); #else return PyString_FromFormat("<cyfunction %s at %p>", PyString_AsString(op->func_qualname), (void *)op); #endif } static PyObject * __Pyx_CyFunction_CallMethod(PyObject *func, PyObject *self, PyObject *arg, PyObject *kw) { PyCFunctionObject* f = (PyCFunctionObject*)func; PyCFunction meth = f->m_ml->ml_meth; Py_ssize_t size; switch (f->m_ml->ml_flags & (METH_VARARGS | METH_KEYWORDS | METH_NOARGS | METH_O)) { case METH_VARARGS: if (likely(kw == NULL || PyDict_Size(kw) == 0)) return (*meth)(self, arg); break; case METH_VARARGS | METH_KEYWORDS: return (*(PyCFunctionWithKeywords)(void*)meth)(self, arg, kw); case METH_NOARGS: if (likely(kw == NULL || PyDict_Size(kw) == 0)) { size = PyTuple_GET_SIZE(arg); if (likely(size == 0)) return (*meth)(self, NULL); PyErr_Format(PyExc_TypeError, "%.200s() takes no arguments (%" CYTHON_FORMAT_SSIZE_T "d given)", f->m_ml->ml_name, size); return NULL; } break; case METH_O: if (likely(kw == NULL || PyDict_Size(kw) == 0)) { size = PyTuple_GET_SIZE(arg); if (likely(size == 1)) { PyObject *result, *arg0; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS arg0 = PyTuple_GET_ITEM(arg, 0); #else arg0 = PySequence_ITEM(arg, 0); if (unlikely(!arg0)) return NULL; #endif result = (*meth)(self, arg0); #if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) Py_DECREF(arg0); #endif return result; } PyErr_Format(PyExc_TypeError, "%.200s() takes exactly one argument (%" CYTHON_FORMAT_SSIZE_T "d given)", f->m_ml->ml_name, size); return NULL; } break; default: PyErr_SetString(PyExc_SystemError, "Bad call flags in " "__Pyx_CyFunction_Call. METH_OLDARGS is no " "longer supported!"); return NULL; } PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments", f->m_ml->ml_name); return NULL; } static CYTHON_INLINE PyObject *__Pyx_CyFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { return __Pyx_CyFunction_CallMethod(func, ((PyCFunctionObject*)func)->m_self, arg, kw); } static PyObject *__Pyx_CyFunction_CallAsMethod(PyObject *func, PyObject *args, PyObject *kw) { PyObject *result; __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *) func; if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { Py_ssize_t argc; PyObject *new_args; PyObject *self; argc = PyTuple_GET_SIZE(args); new_args = PyTuple_GetSlice(args, 1, argc); if (unlikely(!new_args)) return NULL; self = PyTuple_GetItem(args, 0); if (unlikely(!self)) { Py_DECREF(new_args); return NULL; } result = __Pyx_CyFunction_CallMethod(func, self, new_args, kw); Py_DECREF(new_args); } else { result = __Pyx_CyFunction_Call(func, args, kw); } return result; } static PyTypeObject __pyx_CyFunctionType_type = { PyVarObject_HEAD_INIT(0, 0) "cython_function_or_method", sizeof(__pyx_CyFunctionObject), 0, (destructor) __Pyx_CyFunction_dealloc, 0, 0, 0, #if PY_MAJOR_VERSION < 3 0, #else 0, #endif (reprfunc) __Pyx_CyFunction_repr, 0, 0, 0, 0, __Pyx_CyFunction_CallAsMethod, 0, 0, 0, 0, Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, 0, (traverseproc) __Pyx_CyFunction_traverse, (inquiry) __Pyx_CyFunction_clear, 0, #if PY_VERSION_HEX < 0x030500A0 offsetof(__pyx_CyFunctionObject, func_weakreflist), #else offsetof(PyCFunctionObject, m_weakreflist), #endif 0, 0, __pyx_CyFunction_methods, __pyx_CyFunction_members, __pyx_CyFunction_getsets, 0, 0, __Pyx_CyFunction_descr_get, 0, offsetof(__pyx_CyFunctionObject, func_dict), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, #if PY_VERSION_HEX >= 0x030400a1 0, #endif }; static int __pyx_CyFunction_init(void) { __pyx_CyFunctionType = __Pyx_FetchCommonType(&__pyx_CyFunctionType_type); if (unlikely(__pyx_CyFunctionType == NULL)) { return -1; } return 0; } static CYTHON_INLINE void *__Pyx_CyFunction_InitDefaults(PyObject *func, size_t size, int pyobjects) { __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; m->defaults = PyObject_Malloc(size); if (unlikely(!m->defaults)) return PyErr_NoMemory(); memset(m->defaults, 0, size); m->defaults_pyobjects = pyobjects; return m->defaults; } static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *func, PyObject *tuple) { __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; m->defaults_tuple = tuple; Py_INCREF(tuple); } static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *func, PyObject *dict) { __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; m->defaults_kwdict = dict; Py_INCREF(dict); } static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *func, PyObject *dict) { __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; m->func_annotations = dict; Py_INCREF(dict); } /* RaiseArgTupleInvalid */ static void __Pyx_RaiseArgtupleInvalid( const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found) { Py_ssize_t num_expected; const char *more_or_less; if (num_found < num_min) { num_expected = num_min; more_or_less = "at least"; } else { num_expected = num_max; more_or_less = "at most"; } if (exact) { more_or_less = "exactly"; } PyErr_Format(PyExc_TypeError, "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", func_name, more_or_less, num_expected, (num_expected == 1) ? "" : "s", num_found); } /* RaiseDoubleKeywords */ static void __Pyx_RaiseDoubleKeywordsError( const char* func_name, PyObject* kw_name) { PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION >= 3 "%s() got multiple values for keyword argument '%U'", func_name, kw_name); #else "%s() got multiple values for keyword argument '%s'", func_name, PyString_AsString(kw_name)); #endif } /* ParseKeywords */ static int __Pyx_ParseOptionalKeywords( PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name) { PyObject *key = 0, *value = 0; Py_ssize_t pos = 0; PyObject*** name; PyObject*** first_kw_arg = argnames + num_pos_args; while (PyDict_Next(kwds, &pos, &key, &value)) { name = first_kw_arg; while (*name && (**name != key)) name++; if (*name) { values[name-argnames] = value; continue; } name = first_kw_arg; #if PY_MAJOR_VERSION < 3 if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { while (*name) { if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) && _PyString_Eq(**name, key)) { values[name-argnames] = value; break; } name++; } if (*name) continue; else { PyObject*** argname = argnames; while (argname != first_kw_arg) { if ((**argname == key) || ( (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) && _PyString_Eq(**argname, key))) { goto arg_passed_twice; } argname++; } } } else #endif if (likely(PyUnicode_Check(key))) { while (*name) { int cmp = (**name == key) ? 0 : #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : #endif PyUnicode_Compare(**name, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) { values[name-argnames] = value; break; } name++; } if (*name) continue; else { PyObject*** argname = argnames; while (argname != first_kw_arg) { int cmp = (**argname == key) ? 0 : #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : #endif PyUnicode_Compare(**argname, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) goto arg_passed_twice; argname++; } } } else goto invalid_keyword_type; if (kwds2) { if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; } else { goto invalid_keyword; } } return 0; arg_passed_twice: __Pyx_RaiseDoubleKeywordsError(function_name, key); goto bad; invalid_keyword_type: PyErr_Format(PyExc_TypeError, "%.200s() keywords must be strings", function_name); goto bad; invalid_keyword: PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION < 3 "%.200s() got an unexpected keyword argument '%.200s'", function_name, PyString_AsString(key)); #else "%s() got an unexpected keyword argument '%U'", function_name, key); #endif bad: return -1; } /* GetModuleGlobalName */ #if CYTHON_USE_DICT_VERSIONS static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value) #else static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) #endif { PyObject *result; #if !CYTHON_AVOID_BORROWED_REFS #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 result = _PyDict_GetItem_KnownHash(__pyx_d, name, ((PyASCIIObject *) name)->hash); __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) if (likely(result)) { return __Pyx_NewRef(result); } else if (unlikely(PyErr_Occurred())) { return NULL; } #else result = PyDict_GetItem(__pyx_d, name); __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) if (likely(result)) { return __Pyx_NewRef(result); } #endif #else result = PyObject_GetItem(__pyx_d, name); __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) if (likely(result)) { return __Pyx_NewRef(result); } PyErr_Clear(); #endif return __Pyx_GetBuiltinName(name); } /* UnpackUnboundCMethod */ static int __Pyx_TryUnpackUnboundCMethod(__Pyx_CachedCFunction* target) { PyObject *method; method = __Pyx_PyObject_GetAttrStr(target->type, *target->method_name); if (unlikely(!method)) return -1; target->method = method; #if CYTHON_COMPILING_IN_CPYTHON #if PY_MAJOR_VERSION >= 3 if (likely(__Pyx_TypeCheck(method, &PyMethodDescr_Type))) #endif { PyMethodDescrObject *descr = (PyMethodDescrObject*) method; target->func = descr->d_method->ml_meth; target->flag = descr->d_method->ml_flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_STACKLESS); } #endif return 0; } /* CallUnboundCMethod0 */ static PyObject* __Pyx__CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self) { PyObject *args, *result = NULL; if (unlikely(!cfunc->method) && unlikely(__Pyx_TryUnpackUnboundCMethod(cfunc) < 0)) return NULL; #if CYTHON_ASSUME_SAFE_MACROS args = PyTuple_New(1); if (unlikely(!args)) goto bad; Py_INCREF(self); PyTuple_SET_ITEM(args, 0, self); #else args = PyTuple_Pack(1, self); if (unlikely(!args)) goto bad; #endif result = __Pyx_PyObject_Call(cfunc->method, args, NULL); Py_DECREF(args); bad: return result; } /* py_dict_values */ static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d) { if (PY_MAJOR_VERSION >= 3) return __Pyx_CallUnboundCMethod0(&__pyx_umethod_PyDict_Type_values, d); else return PyDict_Values(d); } /* PyObjectCall2Args */ static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2) { PyObject *args, *result = NULL; #if CYTHON_FAST_PYCALL if (PyFunction_Check(function)) { PyObject *args[2] = {arg1, arg2}; return __Pyx_PyFunction_FastCall(function, args, 2); } #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(function)) { PyObject *args[2] = {arg1, arg2}; return __Pyx_PyCFunction_FastCall(function, args, 2); } #endif args = PyTuple_New(2); if (unlikely(!args)) goto done; Py_INCREF(arg1); PyTuple_SET_ITEM(args, 0, arg1); Py_INCREF(arg2); PyTuple_SET_ITEM(args, 1, arg2); Py_INCREF(function); result = __Pyx_PyObject_Call(function, args, NULL); Py_DECREF(args); Py_DECREF(function); done: return result; } /* ExtTypeTest */ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { if (unlikely(!type)) { PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (likely(__Pyx_TypeCheck(obj, type))) return 1; PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", Py_TYPE(obj)->tp_name, type->tp_name); return 0; } /* BytesEquals */ static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { #if CYTHON_COMPILING_IN_PYPY return PyObject_RichCompareBool(s1, s2, equals); #else if (s1 == s2) { return (equals == Py_EQ); } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { const char *ps1, *ps2; Py_ssize_t length = PyBytes_GET_SIZE(s1); if (length != PyBytes_GET_SIZE(s2)) return (equals == Py_NE); ps1 = PyBytes_AS_STRING(s1); ps2 = PyBytes_AS_STRING(s2); if (ps1[0] != ps2[0]) { return (equals == Py_NE); } else if (length == 1) { return (equals == Py_EQ); } else { int result; #if CYTHON_USE_UNICODE_INTERNALS Py_hash_t hash1, hash2; hash1 = ((PyBytesObject*)s1)->ob_shash; hash2 = ((PyBytesObject*)s2)->ob_shash; if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { return (equals == Py_NE); } #endif result = memcmp(ps1, ps2, (size_t)length); return (equals == Py_EQ) ? (result == 0) : (result != 0); } } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { return (equals == Py_NE); } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { return (equals == Py_NE); } else { int result; PyObject* py_result = PyObject_RichCompare(s1, s2, equals); if (!py_result) return -1; result = __Pyx_PyObject_IsTrue(py_result); Py_DECREF(py_result); return result; } #endif } /* UnicodeEquals */ static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { #if CYTHON_COMPILING_IN_PYPY return PyObject_RichCompareBool(s1, s2, equals); #else #if PY_MAJOR_VERSION < 3 PyObject* owned_ref = NULL; #endif int s1_is_unicode, s2_is_unicode; if (s1 == s2) { goto return_eq; } s1_is_unicode = PyUnicode_CheckExact(s1); s2_is_unicode = PyUnicode_CheckExact(s2); #if PY_MAJOR_VERSION < 3 if ((s1_is_unicode & (!s2_is_unicode)) && PyString_CheckExact(s2)) { owned_ref = PyUnicode_FromObject(s2); if (unlikely(!owned_ref)) return -1; s2 = owned_ref; s2_is_unicode = 1; } else if ((s2_is_unicode & (!s1_is_unicode)) && PyString_CheckExact(s1)) { owned_ref = PyUnicode_FromObject(s1); if (unlikely(!owned_ref)) return -1; s1 = owned_ref; s1_is_unicode = 1; } else if (((!s2_is_unicode) & (!s1_is_unicode))) { return __Pyx_PyBytes_Equals(s1, s2, equals); } #endif if (s1_is_unicode & s2_is_unicode) { Py_ssize_t length; int kind; void *data1, *data2; if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) return -1; length = __Pyx_PyUnicode_GET_LENGTH(s1); if (length != __Pyx_PyUnicode_GET_LENGTH(s2)) { goto return_ne; } #if CYTHON_USE_UNICODE_INTERNALS { Py_hash_t hash1, hash2; #if CYTHON_PEP393_ENABLED hash1 = ((PyASCIIObject*)s1)->hash; hash2 = ((PyASCIIObject*)s2)->hash; #else hash1 = ((PyUnicodeObject*)s1)->hash; hash2 = ((PyUnicodeObject*)s2)->hash; #endif if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { goto return_ne; } } #endif kind = __Pyx_PyUnicode_KIND(s1); if (kind != __Pyx_PyUnicode_KIND(s2)) { goto return_ne; } data1 = __Pyx_PyUnicode_DATA(s1); data2 = __Pyx_PyUnicode_DATA(s2); if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { goto return_ne; } else if (length == 1) { goto return_eq; } else { int result = memcmp(data1, data2, (size_t)(length * kind)); #if PY_MAJOR_VERSION < 3 Py_XDECREF(owned_ref); #endif return (equals == Py_EQ) ? (result == 0) : (result != 0); } } else if ((s1 == Py_None) & s2_is_unicode) { goto return_ne; } else if ((s2 == Py_None) & s1_is_unicode) { goto return_ne; } else { int result; PyObject* py_result = PyObject_RichCompare(s1, s2, equals); #if PY_MAJOR_VERSION < 3 Py_XDECREF(owned_ref); #endif if (!py_result) return -1; result = __Pyx_PyObject_IsTrue(py_result); Py_DECREF(py_result); return result; } return_eq: #if PY_MAJOR_VERSION < 3 Py_XDECREF(owned_ref); #endif return (equals == Py_EQ); return_ne: #if PY_MAJOR_VERSION < 3 Py_XDECREF(owned_ref); #endif return (equals == Py_NE); #endif } /* DictGetItem */ #if PY_MAJOR_VERSION >= 3 && !CYTHON_COMPILING_IN_PYPY static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) { PyObject *value; value = PyDict_GetItemWithError(d, key); if (unlikely(!value)) { if (!PyErr_Occurred()) { if (unlikely(PyTuple_Check(key))) { PyObject* args = PyTuple_Pack(1, key); if (likely(args)) { PyErr_SetObject(PyExc_KeyError, args); Py_DECREF(args); } } else { PyErr_SetObject(PyExc_KeyError, key); } } return NULL; } Py_INCREF(value); return value; } #endif /* GetTopmostException */ #if CYTHON_USE_EXC_INFO_STACK static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate) { _PyErr_StackItem *exc_info = tstate->exc_info; while ((exc_info->exc_type == NULL || exc_info->exc_type == Py_None) && exc_info->previous_item != NULL) { exc_info = exc_info->previous_item; } return exc_info; } #endif /* SaveResetException */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { #if CYTHON_USE_EXC_INFO_STACK _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); *type = exc_info->exc_type; *value = exc_info->exc_value; *tb = exc_info->exc_traceback; #else *type = tstate->exc_type; *value = tstate->exc_value; *tb = tstate->exc_traceback; #endif Py_XINCREF(*type); Py_XINCREF(*value); Py_XINCREF(*tb); } static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; #if CYTHON_USE_EXC_INFO_STACK _PyErr_StackItem *exc_info = tstate->exc_info; tmp_type = exc_info->exc_type; tmp_value = exc_info->exc_value; tmp_tb = exc_info->exc_traceback; exc_info->exc_type = type; exc_info->exc_value = value; exc_info->exc_traceback = tb; #else tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = type; tstate->exc_value = value; tstate->exc_traceback = tb; #endif Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); } #endif /* GetException */ #if CYTHON_FAST_THREAD_STATE static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) #else static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) #endif { PyObject *local_type, *local_value, *local_tb; #if CYTHON_FAST_THREAD_STATE PyObject *tmp_type, *tmp_value, *tmp_tb; local_type = tstate->curexc_type; local_value = tstate->curexc_value; local_tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; #else PyErr_Fetch(&local_type, &local_value, &local_tb); #endif PyErr_NormalizeException(&local_type, &local_value, &local_tb); #if CYTHON_FAST_THREAD_STATE if (unlikely(tstate->curexc_type)) #else if (unlikely(PyErr_Occurred())) #endif goto bad; #if PY_MAJOR_VERSION >= 3 if (local_tb) { if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) goto bad; } #endif Py_XINCREF(local_tb); Py_XINCREF(local_type); Py_XINCREF(local_value); *type = local_type; *value = local_value; *tb = local_tb; #if CYTHON_FAST_THREAD_STATE #if CYTHON_USE_EXC_INFO_STACK { _PyErr_StackItem *exc_info = tstate->exc_info; tmp_type = exc_info->exc_type; tmp_value = exc_info->exc_value; tmp_tb = exc_info->exc_traceback; exc_info->exc_type = local_type; exc_info->exc_value = local_value; exc_info->exc_traceback = local_tb; } #else tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = local_type; tstate->exc_value = local_value; tstate->exc_traceback = local_tb; #endif Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); #else PyErr_SetExcInfo(local_type, local_value, local_tb); #endif return 0; bad: *type = 0; *value = 0; *tb = 0; Py_XDECREF(local_type); Py_XDECREF(local_value); Py_XDECREF(local_tb); return -1; } /* PyErrFetchRestore */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; tmp_type = tstate->curexc_type; tmp_value = tstate->curexc_value; tmp_tb = tstate->curexc_traceback; tstate->curexc_type = type; tstate->curexc_value = value; tstate->curexc_traceback = tb; Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); } static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { *type = tstate->curexc_type; *value = tstate->curexc_value; *tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; } #endif /* None */ static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname) { PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname); } /* PyObject_GenericGetAttrNoDict */ #if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 static PyObject *__Pyx_RaiseGenericGetAttributeError(PyTypeObject *tp, PyObject *attr_name) { PyErr_Format(PyExc_AttributeError, #if PY_MAJOR_VERSION >= 3 "'%.50s' object has no attribute '%U'", tp->tp_name, attr_name); #else "'%.50s' object has no attribute '%.400s'", tp->tp_name, PyString_AS_STRING(attr_name)); #endif return NULL; } static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name) { PyObject *descr; PyTypeObject *tp = Py_TYPE(obj); if (unlikely(!PyString_Check(attr_name))) { return PyObject_GenericGetAttr(obj, attr_name); } assert(!tp->tp_dictoffset); descr = _PyType_Lookup(tp, attr_name); if (unlikely(!descr)) { return __Pyx_RaiseGenericGetAttributeError(tp, attr_name); } Py_INCREF(descr); #if PY_MAJOR_VERSION < 3 if (likely(PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_HAVE_CLASS))) #endif { descrgetfunc f = Py_TYPE(descr)->tp_descr_get; if (unlikely(f)) { PyObject *res = f(descr, obj, (PyObject *)tp); Py_DECREF(descr); return res; } } return descr; } #endif /* TypeImport */ #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(PyObject *module, const char *module_name, const char *class_name, size_t size, enum __Pyx_ImportType_CheckSize check_size) { PyObject *result = 0; char warning[200]; Py_ssize_t basicsize; #ifdef Py_LIMITED_API PyObject *py_basicsize; #endif result = PyObject_GetAttrString(module, class_name); if (!result) goto bad; if (!PyType_Check(result)) { PyErr_Format(PyExc_TypeError, "%.200s.%.200s is not a type object", module_name, class_name); goto bad; } #ifndef Py_LIMITED_API basicsize = ((PyTypeObject *)result)->tp_basicsize; #else py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); if (!py_basicsize) goto bad; basicsize = PyLong_AsSsize_t(py_basicsize); Py_DECREF(py_basicsize); py_basicsize = 0; if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) goto bad; #endif if ((size_t)basicsize < size) { PyErr_Format(PyExc_ValueError, "%.200s.%.200s size changed, may indicate binary incompatibility. " "Expected %zd from C header, got %zd from PyObject", module_name, class_name, size, basicsize); goto bad; } if (check_size == __Pyx_ImportType_CheckSize_Error && (size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, "%.200s.%.200s size changed, may indicate binary incompatibility. " "Expected %zd from C header, got %zd from PyObject", module_name, class_name, size, basicsize); goto bad; } else if (check_size == __Pyx_ImportType_CheckSize_Warn && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility. " "Expected %zd from C header, got %zd from PyObject", module_name, class_name, size, basicsize); if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; } return (PyTypeObject *)result; bad: Py_XDECREF(result); return NULL; } #endif /* GetVTable */ static void* __Pyx_GetVtable(PyObject *dict) { void* ptr; PyObject *ob = PyObject_GetItem(dict, __pyx_n_s_pyx_vtable); if (!ob) goto bad; #if PY_VERSION_HEX >= 0x02070000 ptr = PyCapsule_GetPointer(ob, 0); #else ptr = PyCObject_AsVoidPtr(ob); #endif if (!ptr && !PyErr_Occurred()) PyErr_SetString(PyExc_RuntimeError, "invalid vtable found for imported type"); Py_DECREF(ob); return ptr; bad: Py_XDECREF(ob); return NULL; } /* Import */ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { PyObject *empty_list = 0; PyObject *module = 0; PyObject *global_dict = 0; PyObject *empty_dict = 0; PyObject *list; #if PY_MAJOR_VERSION < 3 PyObject *py_import; py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); if (!py_import) goto bad; #endif if (from_list) list = from_list; else { empty_list = PyList_New(0); if (!empty_list) goto bad; list = empty_list; } global_dict = PyModule_GetDict(__pyx_m); if (!global_dict) goto bad; empty_dict = PyDict_New(); if (!empty_dict) goto bad; { #if PY_MAJOR_VERSION >= 3 if (level == -1) { if (strchr(__Pyx_MODULE_NAME, '.')) { module = PyImport_ImportModuleLevelObject( name, global_dict, empty_dict, list, 1); if (!module) { if (!PyErr_ExceptionMatches(PyExc_ImportError)) goto bad; PyErr_Clear(); } } level = 0; } #endif if (!module) { #if PY_MAJOR_VERSION < 3 PyObject *py_level = PyInt_FromLong(level); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, (PyObject *)NULL); Py_DECREF(py_level); #else module = PyImport_ImportModuleLevelObject( name, global_dict, empty_dict, list, level); #endif } } bad: #if PY_MAJOR_VERSION < 3 Py_XDECREF(py_import); #endif Py_XDECREF(empty_list); Py_XDECREF(empty_dict); return module; } /* ImportFrom */ static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Format(PyExc_ImportError, #if PY_MAJOR_VERSION < 3 "cannot import name %.230s", PyString_AS_STRING(name)); #else "cannot import name %S", name); #endif } return value; } /* CLineInTraceback */ #ifndef CYTHON_CLINE_IN_TRACEBACK static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line) { PyObject *use_cline; PyObject *ptype, *pvalue, *ptraceback; #if CYTHON_COMPILING_IN_CPYTHON PyObject **cython_runtime_dict; #endif if (unlikely(!__pyx_cython_runtime)) { return c_line; } __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); #if CYTHON_COMPILING_IN_CPYTHON cython_runtime_dict = _PyObject_GetDictPtr(__pyx_cython_runtime); if (likely(cython_runtime_dict)) { __PYX_PY_DICT_LOOKUP_IF_MODIFIED( use_cline, *cython_runtime_dict, __Pyx_PyDict_GetItemStr(*cython_runtime_dict, __pyx_n_s_cline_in_traceback)) } else #endif { PyObject *use_cline_obj = __Pyx_PyObject_GetAttrStr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback); if (use_cline_obj) { use_cline = PyObject_Not(use_cline_obj) ? Py_False : Py_True; Py_DECREF(use_cline_obj); } else { PyErr_Clear(); use_cline = NULL; } } if (!use_cline) { c_line = 0; PyObject_SetAttr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback, Py_False); } else if (use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { c_line = 0; } __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); return c_line; } #endif /* CodeObjectCache */ static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { int start = 0, mid = 0, end = count - 1; if (end >= 0 && code_line > entries[end].code_line) { return count; } while (start < end) { mid = start + (end - start) / 2; if (code_line < entries[mid].code_line) { end = mid; } else if (code_line > entries[mid].code_line) { start = mid + 1; } else { return mid; } } if (code_line <= entries[mid].code_line) { return mid; } else { return mid + 1; } } static PyCodeObject *__pyx_find_code_object(int code_line) { PyCodeObject* code_object; int pos; if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { return NULL; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { return NULL; } code_object = __pyx_code_cache.entries[pos].code_object; Py_INCREF(code_object); return code_object; } static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { int pos, i; __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; if (unlikely(!code_line)) { return; } if (unlikely(!entries)) { entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); if (likely(entries)) { __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = 64; __pyx_code_cache.count = 1; entries[0].code_line = code_line; entries[0].code_object = code_object; Py_INCREF(code_object); } return; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { PyCodeObject* tmp = entries[pos].code_object; entries[pos].code_object = code_object; Py_DECREF(tmp); return; } if (__pyx_code_cache.count == __pyx_code_cache.max_count) { int new_max = __pyx_code_cache.max_count + 64; entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( __pyx_code_cache.entries, (size_t)new_max*sizeof(__Pyx_CodeObjectCacheEntry)); if (unlikely(!entries)) { return; } __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = new_max; } for (i=__pyx_code_cache.count; i>pos; i--) { entries[i] = entries[i-1]; } entries[pos].code_line = code_line; entries[pos].code_object = code_object; __pyx_code_cache.count++; Py_INCREF(code_object); } /* AddTraceback */ #include "compile.h" #include "frameobject.h" #include "traceback.h" static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyObject *py_srcfile = 0; PyObject *py_funcname = 0; #if PY_MAJOR_VERSION < 3 py_srcfile = PyString_FromString(filename); #else py_srcfile = PyUnicode_FromString(filename); #endif if (!py_srcfile) goto bad; if (c_line) { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #else py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #endif } else { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromString(funcname); #else py_funcname = PyUnicode_FromString(funcname); #endif } if (!py_funcname) goto bad; py_code = __Pyx_PyCode_New( 0, 0, 0, 0, 0, __pyx_empty_bytes, /*PyObject *code,*/ __pyx_empty_tuple, /*PyObject *consts,*/ __pyx_empty_tuple, /*PyObject *names,*/ __pyx_empty_tuple, /*PyObject *varnames,*/ __pyx_empty_tuple, /*PyObject *freevars,*/ __pyx_empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ py_line, __pyx_empty_bytes /*PyObject *lnotab*/ ); Py_DECREF(py_srcfile); Py_DECREF(py_funcname); return py_code; bad: Py_XDECREF(py_srcfile); Py_XDECREF(py_funcname); return NULL; } static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyFrameObject *py_frame = 0; PyThreadState *tstate = __Pyx_PyThreadState_Current; if (c_line) { c_line = __Pyx_CLineForTraceback(tstate, c_line); } py_code = __pyx_find_code_object(c_line ? -c_line : py_line); if (!py_code) { py_code = __Pyx_CreateCodeObjectForTraceback( funcname, c_line, py_line, filename); if (!py_code) goto bad; __pyx_insert_code_object(c_line ? -c_line : py_line, py_code); } py_frame = PyFrame_New( tstate, /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ __pyx_d, /*PyObject *globals,*/ 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; __Pyx_PyFrame_SetLineNumber(py_frame, py_line); PyTraceBack_Here(py_frame); bad: Py_XDECREF(py_code); Py_XDECREF(py_frame); } /* CIntFromPyVerify */ #define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) #define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) #define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ {\ func_type value = func_value;\ if (sizeof(target_type) < sizeof(func_type)) {\ if (unlikely(value != (func_type) (target_type) value)) {\ func_type zero = 0;\ if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ return (target_type) -1;\ if (is_unsigned && unlikely(value < zero))\ goto raise_neg_overflow;\ else\ goto raise_overflow;\ }\ }\ return (target_type) value;\ } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(long) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(long) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(long) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(long), little, !is_unsigned); } } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_unsigned_long(unsigned long value) { const unsigned long neg_one = (unsigned long) ((unsigned long) 0 - (unsigned long) 1), const_zero = (unsigned long) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(unsigned long) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(unsigned long) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(unsigned long) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(unsigned long) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(unsigned long) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(unsigned long), little, !is_unsigned); } } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_unsigned_int(unsigned int value) { const unsigned int neg_one = (unsigned int) ((unsigned int) 0 - (unsigned int) 1), const_zero = (unsigned int) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(unsigned int) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(unsigned int) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(unsigned int) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(unsigned int) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(unsigned int) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(unsigned int), little, !is_unsigned); } } /* CIntFromPy */ static CYTHON_INLINE unsigned int __Pyx_PyInt_As_unsigned_int(PyObject *x) { const unsigned int neg_one = (unsigned int) ((unsigned int) 0 - (unsigned int) 1), const_zero = (unsigned int) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(unsigned int) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(unsigned int, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (unsigned int) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (unsigned int) 0; case 1: __PYX_VERIFY_RETURN_INT(unsigned int, digit, digits[0]) case 2: if (8 * sizeof(unsigned int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) >= 2 * PyLong_SHIFT) { return (unsigned int) (((((unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0])); } } break; case 3: if (8 * sizeof(unsigned int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) >= 3 * PyLong_SHIFT) { return (unsigned int) (((((((unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0])); } } break; case 4: if (8 * sizeof(unsigned int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) >= 4 * PyLong_SHIFT) { return (unsigned int) (((((((((unsigned int)digits[3]) << PyLong_SHIFT) | (unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (unsigned int) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(unsigned int) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(unsigned int, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(unsigned int) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(unsigned int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (unsigned int) 0; case -1: __PYX_VERIFY_RETURN_INT(unsigned int, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(unsigned int, digit, +digits[0]) case -2: if (8 * sizeof(unsigned int) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) - 1 > 2 * PyLong_SHIFT) { return (unsigned int) (((unsigned int)-1)*(((((unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0]))); } } break; case 2: if (8 * sizeof(unsigned int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) - 1 > 2 * PyLong_SHIFT) { return (unsigned int) ((((((unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0]))); } } break; case -3: if (8 * sizeof(unsigned int) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) - 1 > 3 * PyLong_SHIFT) { return (unsigned int) (((unsigned int)-1)*(((((((unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0]))); } } break; case 3: if (8 * sizeof(unsigned int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) - 1 > 3 * PyLong_SHIFT) { return (unsigned int) ((((((((unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0]))); } } break; case -4: if (8 * sizeof(unsigned int) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) - 1 > 4 * PyLong_SHIFT) { return (unsigned int) (((unsigned int)-1)*(((((((((unsigned int)digits[3]) << PyLong_SHIFT) | (unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0]))); } } break; case 4: if (8 * sizeof(unsigned int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) - 1 > 4 * PyLong_SHIFT) { return (unsigned int) ((((((((((unsigned int)digits[3]) << PyLong_SHIFT) | (unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0]))); } } break; } #endif if (sizeof(unsigned int) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(unsigned int, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(unsigned int) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(unsigned int, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else unsigned int val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (unsigned int) -1; } } else { unsigned int val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (unsigned int) -1; val = __Pyx_PyInt_As_unsigned_int(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to unsigned int"); return (unsigned int) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned int"); return (unsigned int) -1; } /* CIntFromPy */ static CYTHON_INLINE unsigned long __Pyx_PyInt_As_unsigned_long(PyObject *x) { const unsigned long neg_one = (unsigned long) ((unsigned long) 0 - (unsigned long) 1), const_zero = (unsigned long) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(unsigned long) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(unsigned long, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (unsigned long) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (unsigned long) 0; case 1: __PYX_VERIFY_RETURN_INT(unsigned long, digit, digits[0]) case 2: if (8 * sizeof(unsigned long) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned long) >= 2 * PyLong_SHIFT) { return (unsigned long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); } } break; case 3: if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned long) >= 3 * PyLong_SHIFT) { return (unsigned long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); } } break; case 4: if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned long) >= 4 * PyLong_SHIFT) { return (unsigned long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (unsigned long) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(unsigned long) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(unsigned long, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(unsigned long) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(unsigned long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (unsigned long) 0; case -1: __PYX_VERIFY_RETURN_INT(unsigned long, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(unsigned long, digit, +digits[0]) case -2: if (8 * sizeof(unsigned long) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned long) - 1 > 2 * PyLong_SHIFT) { return (unsigned long) (((unsigned long)-1)*(((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))); } } break; case 2: if (8 * sizeof(unsigned long) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned long) - 1 > 2 * PyLong_SHIFT) { return (unsigned long) ((((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))); } } break; case -3: if (8 * sizeof(unsigned long) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned long) - 1 > 3 * PyLong_SHIFT) { return (unsigned long) (((unsigned long)-1)*(((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))); } } break; case 3: if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned long) - 1 > 3 * PyLong_SHIFT) { return (unsigned long) ((((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))); } } break; case -4: if (8 * sizeof(unsigned long) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned long) - 1 > 4 * PyLong_SHIFT) { return (unsigned long) (((unsigned long)-1)*(((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))); } } break; case 4: if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned long) - 1 > 4 * PyLong_SHIFT) { return (unsigned long) ((((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))); } } break; } #endif if (sizeof(unsigned long) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(unsigned long, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(unsigned long) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(unsigned long, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else unsigned long val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (unsigned long) -1; } } else { unsigned long val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (unsigned long) -1; val = __Pyx_PyInt_As_unsigned_long(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to unsigned long"); return (unsigned long) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned long"); return (unsigned long) -1; } /* CIntFromPy */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(long) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (long) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (long) 0; case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0]) case 2: if (8 * sizeof(long) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) { return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; case 3: if (8 * sizeof(long) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) { return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; case 4: if (8 * sizeof(long) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) { return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (long) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(long) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (long) 0; case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0]) case -2: if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 2: if (8 * sizeof(long) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case -3: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 3: if (8 * sizeof(long) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case -4: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 4: if (8 * sizeof(long) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; } #endif if (sizeof(long) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else long val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (long) -1; } } else { long val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (long) -1; val = __Pyx_PyInt_As_long(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to long"); return (long) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); return (long) -1; } /* CIntFromPy */ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { const int neg_one = (int) ((int) 0 - (int) 1), const_zero = (int) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(int) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (int) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (int) 0; case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0]) case 2: if (8 * sizeof(int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) { return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; case 3: if (8 * sizeof(int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) { return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; case 4: if (8 * sizeof(int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) { return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (int) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(int) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (int) 0; case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0]) case -2: if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 2: if (8 * sizeof(int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case -3: if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 3: if (8 * sizeof(int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case -4: if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 4: if (8 * sizeof(int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; } #endif if (sizeof(int) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else int val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (int) -1; } } else { int val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (int) -1; val = __Pyx_PyInt_As_int(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to int"); return (int) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to int"); return (int) -1; } /* FastTypeChecks */ #if CYTHON_COMPILING_IN_CPYTHON static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { while (a) { a = a->tp_base; if (a == b) return 1; } return b == &PyBaseObject_Type; } static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { PyObject *mro; if (a == b) return 1; mro = a->tp_mro; if (likely(mro)) { Py_ssize_t i, n; n = PyTuple_GET_SIZE(mro); for (i = 0; i < n; i++) { if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) return 1; } return 0; } return __Pyx_InBases(a, b); } #if PY_MAJOR_VERSION == 2 static int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject* exc_type2) { PyObject *exception, *value, *tb; int res; __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ErrFetch(&exception, &value, &tb); res = exc_type1 ? PyObject_IsSubclass(err, exc_type1) : 0; if (unlikely(res == -1)) { PyErr_WriteUnraisable(err); res = 0; } if (!res) { res = PyObject_IsSubclass(err, exc_type2); if (unlikely(res == -1)) { PyErr_WriteUnraisable(err); res = 0; } } __Pyx_ErrRestore(exception, value, tb); return res; } #else static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { int res = exc_type1 ? __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type1) : 0; if (!res) { res = __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); } return res; } #endif static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { Py_ssize_t i, n; assert(PyExceptionClass_Check(exc_type)); n = PyTuple_GET_SIZE(tuple); #if PY_MAJOR_VERSION >= 3 for (i=0; i<n; i++) { if (exc_type == PyTuple_GET_ITEM(tuple, i)) return 1; } #endif for (i=0; i<n; i++) { PyObject *t = PyTuple_GET_ITEM(tuple, i); #if PY_MAJOR_VERSION < 3 if (likely(exc_type == t)) return 1; #endif if (likely(PyExceptionClass_Check(t))) { if (__Pyx_inner_PyErr_GivenExceptionMatches2(exc_type, NULL, t)) return 1; } else { } } return 0; } static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject* exc_type) { if (likely(err == exc_type)) return 1; if (likely(PyExceptionClass_Check(err))) { if (likely(PyExceptionClass_Check(exc_type))) { return __Pyx_inner_PyErr_GivenExceptionMatches2(err, NULL, exc_type); } else if (likely(PyTuple_Check(exc_type))) { return __Pyx_PyErr_GivenExceptionMatchesTuple(err, exc_type); } else { } } return PyErr_GivenExceptionMatches(err, exc_type); } static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *exc_type1, PyObject *exc_type2) { assert(PyExceptionClass_Check(exc_type1)); assert(PyExceptionClass_Check(exc_type2)); if (likely(err == exc_type1 || err == exc_type2)) return 1; if (likely(PyExceptionClass_Check(err))) { return __Pyx_inner_PyErr_GivenExceptionMatches2(err, exc_type1, exc_type2); } return (PyErr_GivenExceptionMatches(err, exc_type1) || PyErr_GivenExceptionMatches(err, exc_type2)); } #endif /* RaiseException */ #if PY_MAJOR_VERSION < 3 static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, CYTHON_UNUSED PyObject *cause) { __Pyx_PyThreadState_declare Py_XINCREF(type); if (!value || value == Py_None) value = NULL; else Py_INCREF(value); if (!tb || tb == Py_None) tb = NULL; else { Py_INCREF(tb); if (!PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto raise_error; } } if (PyType_Check(type)) { #if CYTHON_COMPILING_IN_PYPY if (!value) { Py_INCREF(Py_None); value = Py_None; } #endif PyErr_NormalizeException(&type, &value, &tb); } else { if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } value = type; type = (PyObject*) Py_TYPE(type); Py_INCREF(type); if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto raise_error; } } __Pyx_PyThreadState_assign __Pyx_ErrRestore(type, value, tb); return; raise_error: Py_XDECREF(value); Py_XDECREF(type); Py_XDECREF(tb); return; } #else static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { PyObject* owned_instance = NULL; if (tb == Py_None) { tb = 0; } else if (tb && !PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto bad; } if (value == Py_None) value = 0; if (PyExceptionInstance_Check(type)) { if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto bad; } value = type; type = (PyObject*) Py_TYPE(value); } else if (PyExceptionClass_Check(type)) { PyObject *instance_class = NULL; if (value && PyExceptionInstance_Check(value)) { instance_class = (PyObject*) Py_TYPE(value); if (instance_class != type) { int is_subclass = PyObject_IsSubclass(instance_class, type); if (!is_subclass) { instance_class = NULL; } else if (unlikely(is_subclass == -1)) { goto bad; } else { type = instance_class; } } } if (!instance_class) { PyObject *args; if (!value) args = PyTuple_New(0); else if (PyTuple_Check(value)) { Py_INCREF(value); args = value; } else args = PyTuple_Pack(1, value); if (!args) goto bad; owned_instance = PyObject_Call(type, args, NULL); Py_DECREF(args); if (!owned_instance) goto bad; value = owned_instance; if (!PyExceptionInstance_Check(value)) { PyErr_Format(PyExc_TypeError, "calling %R should have returned an instance of " "BaseException, not %R", type, Py_TYPE(value)); goto bad; } } } else { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto bad; } if (cause) { PyObject *fixed_cause; if (cause == Py_None) { fixed_cause = NULL; } else if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); if (fixed_cause == NULL) goto bad; } else if (PyExceptionInstance_Check(cause)) { fixed_cause = cause; Py_INCREF(fixed_cause); } else { PyErr_SetString(PyExc_TypeError, "exception causes must derive from " "BaseException"); goto bad; } PyException_SetCause(value, fixed_cause); } PyErr_SetObject(type, value); if (tb) { #if CYTHON_COMPILING_IN_PYPY PyObject *tmp_type, *tmp_value, *tmp_tb; PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); Py_INCREF(tb); PyErr_Restore(tmp_type, tmp_value, tb); Py_XDECREF(tmp_tb); #else PyThreadState *tstate = __Pyx_PyThreadState_Current; PyObject* tmp_tb = tstate->curexc_traceback; if (tb != tmp_tb) { Py_INCREF(tb); tstate->curexc_traceback = tb; Py_XDECREF(tmp_tb); } #endif } bad: Py_XDECREF(owned_instance); return; } #endif /* SwapException */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; #if CYTHON_USE_EXC_INFO_STACK _PyErr_StackItem *exc_info = tstate->exc_info; tmp_type = exc_info->exc_type; tmp_value = exc_info->exc_value; tmp_tb = exc_info->exc_traceback; exc_info->exc_type = *type; exc_info->exc_value = *value; exc_info->exc_traceback = *tb; #else tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = *type; tstate->exc_value = *value; tstate->exc_traceback = *tb; #endif *type = tmp_type; *value = tmp_value; *tb = tmp_tb; } #else static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); PyErr_SetExcInfo(*type, *value, *tb); *type = tmp_type; *value = tmp_value; *tb = tmp_tb; } #endif /* PyObjectGetMethod */ static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method) { PyObject *attr; #if CYTHON_UNPACK_METHODS && CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_PYTYPE_LOOKUP PyTypeObject *tp = Py_TYPE(obj); PyObject *descr; descrgetfunc f = NULL; PyObject **dictptr, *dict; int meth_found = 0; assert (*method == NULL); if (unlikely(tp->tp_getattro != PyObject_GenericGetAttr)) { attr = __Pyx_PyObject_GetAttrStr(obj, name); goto try_unpack; } if (unlikely(tp->tp_dict == NULL) && unlikely(PyType_Ready(tp) < 0)) { return 0; } descr = _PyType_Lookup(tp, name); if (likely(descr != NULL)) { Py_INCREF(descr); #if PY_MAJOR_VERSION >= 3 #ifdef __Pyx_CyFunction_USED if (likely(PyFunction_Check(descr) || (Py_TYPE(descr) == &PyMethodDescr_Type) || __Pyx_CyFunction_Check(descr))) #else if (likely(PyFunction_Check(descr) || (Py_TYPE(descr) == &PyMethodDescr_Type))) #endif #else #ifdef __Pyx_CyFunction_USED if (likely(PyFunction_Check(descr) || __Pyx_CyFunction_Check(descr))) #else if (likely(PyFunction_Check(descr))) #endif #endif { meth_found = 1; } else { f = Py_TYPE(descr)->tp_descr_get; if (f != NULL && PyDescr_IsData(descr)) { attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); Py_DECREF(descr); goto try_unpack; } } } dictptr = _PyObject_GetDictPtr(obj); if (dictptr != NULL && (dict = *dictptr) != NULL) { Py_INCREF(dict); attr = __Pyx_PyDict_GetItemStr(dict, name); if (attr != NULL) { Py_INCREF(attr); Py_DECREF(dict); Py_XDECREF(descr); goto try_unpack; } Py_DECREF(dict); } if (meth_found) { *method = descr; return 1; } if (f != NULL) { attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); Py_DECREF(descr); goto try_unpack; } if (descr != NULL) { *method = descr; return 0; } PyErr_Format(PyExc_AttributeError, #if PY_MAJOR_VERSION >= 3 "'%.50s' object has no attribute '%U'", tp->tp_name, name); #else "'%.50s' object has no attribute '%.400s'", tp->tp_name, PyString_AS_STRING(name)); #endif return 0; #else attr = __Pyx_PyObject_GetAttrStr(obj, name); goto try_unpack; #endif try_unpack: #if CYTHON_UNPACK_METHODS if (likely(attr) && PyMethod_Check(attr) && likely(PyMethod_GET_SELF(attr) == obj)) { PyObject *function = PyMethod_GET_FUNCTION(attr); Py_INCREF(function); Py_DECREF(attr); *method = function; return 1; } #endif *method = attr; return 0; } /* PyObjectCallMethod1 */ static PyObject* __Pyx__PyObject_CallMethod1(PyObject* method, PyObject* arg) { PyObject *result = __Pyx_PyObject_CallOneArg(method, arg); Py_DECREF(method); return result; } static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg) { PyObject *method = NULL, *result; int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); if (likely(is_method)) { result = __Pyx_PyObject_Call2Args(method, obj, arg); Py_DECREF(method); return result; } if (unlikely(!method)) return NULL; return __Pyx__PyObject_CallMethod1(method, arg); } /* CoroutineBase */ #include <structmember.h> #include <frameobject.h> #define __Pyx_Coroutine_Undelegate(gen) Py_CLEAR((gen)->yieldfrom) static int __Pyx_PyGen__FetchStopIterationValue(CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject **pvalue) { PyObject *et, *ev, *tb; PyObject *value = NULL; __Pyx_ErrFetch(&et, &ev, &tb); if (!et) { Py_XDECREF(tb); Py_XDECREF(ev); Py_INCREF(Py_None); *pvalue = Py_None; return 0; } if (likely(et == PyExc_StopIteration)) { if (!ev) { Py_INCREF(Py_None); value = Py_None; } #if PY_VERSION_HEX >= 0x030300A0 else if (Py_TYPE(ev) == (PyTypeObject*)PyExc_StopIteration) { value = ((PyStopIterationObject *)ev)->value; Py_INCREF(value); Py_DECREF(ev); } #endif else if (unlikely(PyTuple_Check(ev))) { if (PyTuple_GET_SIZE(ev) >= 1) { #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS value = PyTuple_GET_ITEM(ev, 0); Py_INCREF(value); #else value = PySequence_ITEM(ev, 0); #endif } else { Py_INCREF(Py_None); value = Py_None; } Py_DECREF(ev); } else if (!__Pyx_TypeCheck(ev, (PyTypeObject*)PyExc_StopIteration)) { value = ev; } if (likely(value)) { Py_XDECREF(tb); Py_DECREF(et); *pvalue = value; return 0; } } else if (!__Pyx_PyErr_GivenExceptionMatches(et, PyExc_StopIteration)) { __Pyx_ErrRestore(et, ev, tb); return -1; } PyErr_NormalizeException(&et, &ev, &tb); if (unlikely(!PyObject_TypeCheck(ev, (PyTypeObject*)PyExc_StopIteration))) { __Pyx_ErrRestore(et, ev, tb); return -1; } Py_XDECREF(tb); Py_DECREF(et); #if PY_VERSION_HEX >= 0x030300A0 value = ((PyStopIterationObject *)ev)->value; Py_INCREF(value); Py_DECREF(ev); #else { PyObject* args = __Pyx_PyObject_GetAttrStr(ev, __pyx_n_s_args); Py_DECREF(ev); if (likely(args)) { value = PySequence_GetItem(args, 0); Py_DECREF(args); } if (unlikely(!value)) { __Pyx_ErrRestore(NULL, NULL, NULL); Py_INCREF(Py_None); value = Py_None; } } #endif *pvalue = value; return 0; } static CYTHON_INLINE void __Pyx_Coroutine_ExceptionClear(__Pyx_ExcInfoStruct *exc_state) { PyObject *t, *v, *tb; t = exc_state->exc_type; v = exc_state->exc_value; tb = exc_state->exc_traceback; exc_state->exc_type = NULL; exc_state->exc_value = NULL; exc_state->exc_traceback = NULL; Py_XDECREF(t); Py_XDECREF(v); Py_XDECREF(tb); } #define __Pyx_Coroutine_AlreadyRunningError(gen) (__Pyx__Coroutine_AlreadyRunningError(gen), (PyObject*)NULL) static void __Pyx__Coroutine_AlreadyRunningError(CYTHON_UNUSED __pyx_CoroutineObject *gen) { const char *msg; if ((0)) { #ifdef __Pyx_Coroutine_USED } else if (__Pyx_Coroutine_Check((PyObject*)gen)) { msg = "coroutine already executing"; #endif #ifdef __Pyx_AsyncGen_USED } else if (__Pyx_AsyncGen_CheckExact((PyObject*)gen)) { msg = "async generator already executing"; #endif } else { msg = "generator already executing"; } PyErr_SetString(PyExc_ValueError, msg); } #define __Pyx_Coroutine_NotStartedError(gen) (__Pyx__Coroutine_NotStartedError(gen), (PyObject*)NULL) static void __Pyx__Coroutine_NotStartedError(CYTHON_UNUSED PyObject *gen) { const char *msg; if ((0)) { #ifdef __Pyx_Coroutine_USED } else if (__Pyx_Coroutine_Check(gen)) { msg = "can't send non-None value to a just-started coroutine"; #endif #ifdef __Pyx_AsyncGen_USED } else if (__Pyx_AsyncGen_CheckExact(gen)) { msg = "can't send non-None value to a just-started async generator"; #endif } else { msg = "can't send non-None value to a just-started generator"; } PyErr_SetString(PyExc_TypeError, msg); } #define __Pyx_Coroutine_AlreadyTerminatedError(gen, value, closing) (__Pyx__Coroutine_AlreadyTerminatedError(gen, value, closing), (PyObject*)NULL) static void __Pyx__Coroutine_AlreadyTerminatedError(CYTHON_UNUSED PyObject *gen, PyObject *value, CYTHON_UNUSED int closing) { #ifdef __Pyx_Coroutine_USED if (!closing && __Pyx_Coroutine_Check(gen)) { PyErr_SetString(PyExc_RuntimeError, "cannot reuse already awaited coroutine"); } else #endif if (value) { #ifdef __Pyx_AsyncGen_USED if (__Pyx_AsyncGen_CheckExact(gen)) PyErr_SetNone(__Pyx_PyExc_StopAsyncIteration); else #endif PyErr_SetNone(PyExc_StopIteration); } } static PyObject *__Pyx_Coroutine_SendEx(__pyx_CoroutineObject *self, PyObject *value, int closing) { __Pyx_PyThreadState_declare PyThreadState *tstate; __Pyx_ExcInfoStruct *exc_state; PyObject *retval; assert(!self->is_running); if (unlikely(self->resume_label == 0)) { if (unlikely(value && value != Py_None)) { return __Pyx_Coroutine_NotStartedError((PyObject*)self); } } if (unlikely(self->resume_label == -1)) { return __Pyx_Coroutine_AlreadyTerminatedError((PyObject*)self, value, closing); } #if CYTHON_FAST_THREAD_STATE __Pyx_PyThreadState_assign tstate = __pyx_tstate; #else tstate = __Pyx_PyThreadState_Current; #endif exc_state = &self->gi_exc_state; if (exc_state->exc_type) { #if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_PYSTON #else if (exc_state->exc_traceback) { PyTracebackObject *tb = (PyTracebackObject *) exc_state->exc_traceback; PyFrameObject *f = tb->tb_frame; Py_XINCREF(tstate->frame); assert(f->f_back == NULL); f->f_back = tstate->frame; } #endif } #if CYTHON_USE_EXC_INFO_STACK exc_state->previous_item = tstate->exc_info; tstate->exc_info = exc_state; #else if (exc_state->exc_type) { __Pyx_ExceptionSwap(&exc_state->exc_type, &exc_state->exc_value, &exc_state->exc_traceback); } else { __Pyx_Coroutine_ExceptionClear(exc_state); __Pyx_ExceptionSave(&exc_state->exc_type, &exc_state->exc_value, &exc_state->exc_traceback); } #endif self->is_running = 1; retval = self->body((PyObject *) self, tstate, value); self->is_running = 0; #if CYTHON_USE_EXC_INFO_STACK exc_state = &self->gi_exc_state; tstate->exc_info = exc_state->previous_item; exc_state->previous_item = NULL; __Pyx_Coroutine_ResetFrameBackpointer(exc_state); #endif return retval; } static CYTHON_INLINE void __Pyx_Coroutine_ResetFrameBackpointer(__Pyx_ExcInfoStruct *exc_state) { PyObject *exc_tb = exc_state->exc_traceback; if (likely(exc_tb)) { #if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_PYSTON #else PyTracebackObject *tb = (PyTracebackObject *) exc_tb; PyFrameObject *f = tb->tb_frame; Py_CLEAR(f->f_back); #endif } } static CYTHON_INLINE PyObject *__Pyx_Coroutine_MethodReturn(CYTHON_UNUSED PyObject* gen, PyObject *retval) { if (unlikely(!retval)) { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign if (!__Pyx_PyErr_Occurred()) { PyObject *exc = PyExc_StopIteration; #ifdef __Pyx_AsyncGen_USED if (__Pyx_AsyncGen_CheckExact(gen)) exc = __Pyx_PyExc_StopAsyncIteration; #endif __Pyx_PyErr_SetNone(exc); } } return retval; } static CYTHON_INLINE PyObject *__Pyx_Coroutine_FinishDelegation(__pyx_CoroutineObject *gen) { PyObject *ret; PyObject *val = NULL; __Pyx_Coroutine_Undelegate(gen); __Pyx_PyGen__FetchStopIterationValue(__Pyx_PyThreadState_Current, &val); ret = __Pyx_Coroutine_SendEx(gen, val, 0); Py_XDECREF(val); return ret; } static PyObject *__Pyx_Coroutine_Send(PyObject *self, PyObject *value) { PyObject *retval; __pyx_CoroutineObject *gen = (__pyx_CoroutineObject*) self; PyObject *yf = gen->yieldfrom; if (unlikely(gen->is_running)) return __Pyx_Coroutine_AlreadyRunningError(gen); if (yf) { PyObject *ret; gen->is_running = 1; #ifdef __Pyx_Generator_USED if (__Pyx_Generator_CheckExact(yf)) { ret = __Pyx_Coroutine_Send(yf, value); } else #endif #ifdef __Pyx_Coroutine_USED if (__Pyx_Coroutine_Check(yf)) { ret = __Pyx_Coroutine_Send(yf, value); } else #endif #ifdef __Pyx_AsyncGen_USED if (__pyx_PyAsyncGenASend_CheckExact(yf)) { ret = __Pyx_async_gen_asend_send(yf, value); } else #endif #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03030000 && (defined(__linux__) || PY_VERSION_HEX >= 0x030600B3) if (PyGen_CheckExact(yf)) { ret = _PyGen_Send((PyGenObject*)yf, value == Py_None ? NULL : value); } else #endif #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03050000 && defined(PyCoro_CheckExact) && (defined(__linux__) || PY_VERSION_HEX >= 0x030600B3) if (PyCoro_CheckExact(yf)) { ret = _PyGen_Send((PyGenObject*)yf, value == Py_None ? NULL : value); } else #endif { if (value == Py_None) ret = Py_TYPE(yf)->tp_iternext(yf); else ret = __Pyx_PyObject_CallMethod1(yf, __pyx_n_s_send, value); } gen->is_running = 0; if (likely(ret)) { return ret; } retval = __Pyx_Coroutine_FinishDelegation(gen); } else { retval = __Pyx_Coroutine_SendEx(gen, value, 0); } return __Pyx_Coroutine_MethodReturn(self, retval); } static int __Pyx_Coroutine_CloseIter(__pyx_CoroutineObject *gen, PyObject *yf) { PyObject *retval = NULL; int err = 0; #ifdef __Pyx_Generator_USED if (__Pyx_Generator_CheckExact(yf)) { retval = __Pyx_Coroutine_Close(yf); if (!retval) return -1; } else #endif #ifdef __Pyx_Coroutine_USED if (__Pyx_Coroutine_Check(yf)) { retval = __Pyx_Coroutine_Close(yf); if (!retval) return -1; } else if (__Pyx_CoroutineAwait_CheckExact(yf)) { retval = __Pyx_CoroutineAwait_Close((__pyx_CoroutineAwaitObject*)yf, NULL); if (!retval) return -1; } else #endif #ifdef __Pyx_AsyncGen_USED if (__pyx_PyAsyncGenASend_CheckExact(yf)) { retval = __Pyx_async_gen_asend_close(yf, NULL); } else if (__pyx_PyAsyncGenAThrow_CheckExact(yf)) { retval = __Pyx_async_gen_athrow_close(yf, NULL); } else #endif { PyObject *meth; gen->is_running = 1; meth = __Pyx_PyObject_GetAttrStr(yf, __pyx_n_s_close); if (unlikely(!meth)) { if (!PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_WriteUnraisable(yf); } PyErr_Clear(); } else { retval = PyObject_CallFunction(meth, NULL); Py_DECREF(meth); if (!retval) err = -1; } gen->is_running = 0; } Py_XDECREF(retval); return err; } static PyObject *__Pyx_Generator_Next(PyObject *self) { __pyx_CoroutineObject *gen = (__pyx_CoroutineObject*) self; PyObject *yf = gen->yieldfrom; if (unlikely(gen->is_running)) return __Pyx_Coroutine_AlreadyRunningError(gen); if (yf) { PyObject *ret; gen->is_running = 1; #ifdef __Pyx_Generator_USED if (__Pyx_Generator_CheckExact(yf)) { ret = __Pyx_Generator_Next(yf); } else #endif #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03030000 && (defined(__linux__) || PY_VERSION_HEX >= 0x030600B3) if (PyGen_CheckExact(yf)) { ret = _PyGen_Send((PyGenObject*)yf, NULL); } else #endif #ifdef __Pyx_Coroutine_USED if (__Pyx_Coroutine_Check(yf)) { ret = __Pyx_Coroutine_Send(yf, Py_None); } else #endif ret = Py_TYPE(yf)->tp_iternext(yf); gen->is_running = 0; if (likely(ret)) { return ret; } return __Pyx_Coroutine_FinishDelegation(gen); } return __Pyx_Coroutine_SendEx(gen, Py_None, 0); } static PyObject *__Pyx_Coroutine_Close_Method(PyObject *self, CYTHON_UNUSED PyObject *arg) { return __Pyx_Coroutine_Close(self); } static PyObject *__Pyx_Coroutine_Close(PyObject *self) { __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; PyObject *retval, *raised_exception; PyObject *yf = gen->yieldfrom; int err = 0; if (unlikely(gen->is_running)) return __Pyx_Coroutine_AlreadyRunningError(gen); if (yf) { Py_INCREF(yf); err = __Pyx_Coroutine_CloseIter(gen, yf); __Pyx_Coroutine_Undelegate(gen); Py_DECREF(yf); } if (err == 0) PyErr_SetNone(PyExc_GeneratorExit); retval = __Pyx_Coroutine_SendEx(gen, NULL, 1); if (unlikely(retval)) { const char *msg; Py_DECREF(retval); if ((0)) { #ifdef __Pyx_Coroutine_USED } else if (__Pyx_Coroutine_Check(self)) { msg = "coroutine ignored GeneratorExit"; #endif #ifdef __Pyx_AsyncGen_USED } else if (__Pyx_AsyncGen_CheckExact(self)) { #if PY_VERSION_HEX < 0x03060000 msg = "async generator ignored GeneratorExit - might require Python 3.6+ finalisation (PEP 525)"; #else msg = "async generator ignored GeneratorExit"; #endif #endif } else { msg = "generator ignored GeneratorExit"; } PyErr_SetString(PyExc_RuntimeError, msg); return NULL; } raised_exception = PyErr_Occurred(); if (likely(!raised_exception || __Pyx_PyErr_GivenExceptionMatches2(raised_exception, PyExc_GeneratorExit, PyExc_StopIteration))) { if (raised_exception) PyErr_Clear(); Py_INCREF(Py_None); return Py_None; } return NULL; } static PyObject *__Pyx__Coroutine_Throw(PyObject *self, PyObject *typ, PyObject *val, PyObject *tb, PyObject *args, int close_on_genexit) { __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; PyObject *yf = gen->yieldfrom; if (unlikely(gen->is_running)) return __Pyx_Coroutine_AlreadyRunningError(gen); if (yf) { PyObject *ret; Py_INCREF(yf); if (__Pyx_PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) && close_on_genexit) { int err = __Pyx_Coroutine_CloseIter(gen, yf); Py_DECREF(yf); __Pyx_Coroutine_Undelegate(gen); if (err < 0) return __Pyx_Coroutine_MethodReturn(self, __Pyx_Coroutine_SendEx(gen, NULL, 0)); goto throw_here; } gen->is_running = 1; if (0 #ifdef __Pyx_Generator_USED || __Pyx_Generator_CheckExact(yf) #endif #ifdef __Pyx_Coroutine_USED || __Pyx_Coroutine_Check(yf) #endif ) { ret = __Pyx__Coroutine_Throw(yf, typ, val, tb, args, close_on_genexit); #ifdef __Pyx_Coroutine_USED } else if (__Pyx_CoroutineAwait_CheckExact(yf)) { ret = __Pyx__Coroutine_Throw(((__pyx_CoroutineAwaitObject*)yf)->coroutine, typ, val, tb, args, close_on_genexit); #endif } else { PyObject *meth = __Pyx_PyObject_GetAttrStr(yf, __pyx_n_s_throw); if (unlikely(!meth)) { Py_DECREF(yf); if (!PyErr_ExceptionMatches(PyExc_AttributeError)) { gen->is_running = 0; return NULL; } PyErr_Clear(); __Pyx_Coroutine_Undelegate(gen); gen->is_running = 0; goto throw_here; } if (likely(args)) { ret = PyObject_CallObject(meth, args); } else { ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL); } Py_DECREF(meth); } gen->is_running = 0; Py_DECREF(yf); if (!ret) { ret = __Pyx_Coroutine_FinishDelegation(gen); } return __Pyx_Coroutine_MethodReturn(self, ret); } throw_here: __Pyx_Raise(typ, val, tb, NULL); return __Pyx_Coroutine_MethodReturn(self, __Pyx_Coroutine_SendEx(gen, NULL, 0)); } static PyObject *__Pyx_Coroutine_Throw(PyObject *self, PyObject *args) { PyObject *typ; PyObject *val = NULL; PyObject *tb = NULL; if (!PyArg_UnpackTuple(args, (char *)"throw", 1, 3, &typ, &val, &tb)) return NULL; return __Pyx__Coroutine_Throw(self, typ, val, tb, args, 1); } static CYTHON_INLINE int __Pyx_Coroutine_traverse_excstate(__Pyx_ExcInfoStruct *exc_state, visitproc visit, void *arg) { Py_VISIT(exc_state->exc_type); Py_VISIT(exc_state->exc_value); Py_VISIT(exc_state->exc_traceback); return 0; } static int __Pyx_Coroutine_traverse(__pyx_CoroutineObject *gen, visitproc visit, void *arg) { Py_VISIT(gen->closure); Py_VISIT(gen->classobj); Py_VISIT(gen->yieldfrom); return __Pyx_Coroutine_traverse_excstate(&gen->gi_exc_state, visit, arg); } static int __Pyx_Coroutine_clear(PyObject *self) { __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; Py_CLEAR(gen->closure); Py_CLEAR(gen->classobj); Py_CLEAR(gen->yieldfrom); __Pyx_Coroutine_ExceptionClear(&gen->gi_exc_state); #ifdef __Pyx_AsyncGen_USED if (__Pyx_AsyncGen_CheckExact(self)) { Py_CLEAR(((__pyx_PyAsyncGenObject*)gen)->ag_finalizer); } #endif Py_CLEAR(gen->gi_code); Py_CLEAR(gen->gi_name); Py_CLEAR(gen->gi_qualname); Py_CLEAR(gen->gi_modulename); return 0; } static void __Pyx_Coroutine_dealloc(PyObject *self) { __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; PyObject_GC_UnTrack(gen); if (gen->gi_weakreflist != NULL) PyObject_ClearWeakRefs(self); if (gen->resume_label >= 0) { PyObject_GC_Track(self); #if PY_VERSION_HEX >= 0x030400a1 && CYTHON_USE_TP_FINALIZE if (PyObject_CallFinalizerFromDealloc(self)) #else Py_TYPE(gen)->tp_del(self); if (self->ob_refcnt > 0) #endif { return; } PyObject_GC_UnTrack(self); } #ifdef __Pyx_AsyncGen_USED if (__Pyx_AsyncGen_CheckExact(self)) { /* We have to handle this case for asynchronous generators right here, because this code has to be between UNTRACK and GC_Del. */ Py_CLEAR(((__pyx_PyAsyncGenObject*)self)->ag_finalizer); } #endif __Pyx_Coroutine_clear(self); PyObject_GC_Del(gen); } static void __Pyx_Coroutine_del(PyObject *self) { PyObject *error_type, *error_value, *error_traceback; __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; __Pyx_PyThreadState_declare if (gen->resume_label < 0) { return; } #if !CYTHON_USE_TP_FINALIZE assert(self->ob_refcnt == 0); self->ob_refcnt = 1; #endif __Pyx_PyThreadState_assign __Pyx_ErrFetch(&error_type, &error_value, &error_traceback); #ifdef __Pyx_AsyncGen_USED if (__Pyx_AsyncGen_CheckExact(self)) { __pyx_PyAsyncGenObject *agen = (__pyx_PyAsyncGenObject*)self; PyObject *finalizer = agen->ag_finalizer; if (finalizer && !agen->ag_closed) { PyObject *res = __Pyx_PyObject_CallOneArg(finalizer, self); if (unlikely(!res)) { PyErr_WriteUnraisable(self); } else { Py_DECREF(res); } __Pyx_ErrRestore(error_type, error_value, error_traceback); return; } } #endif if (unlikely(gen->resume_label == 0 && !error_value)) { #ifdef __Pyx_Coroutine_USED #ifdef __Pyx_Generator_USED if (!__Pyx_Generator_CheckExact(self)) #endif { PyObject_GC_UnTrack(self); #if PY_MAJOR_VERSION >= 3 || defined(PyErr_WarnFormat) if (unlikely(PyErr_WarnFormat(PyExc_RuntimeWarning, 1, "coroutine '%.50S' was never awaited", gen->gi_qualname) < 0)) PyErr_WriteUnraisable(self); #else {PyObject *msg; char *cmsg; #if CYTHON_COMPILING_IN_PYPY msg = NULL; cmsg = (char*) "coroutine was never awaited"; #else char *cname; PyObject *qualname; qualname = gen->gi_qualname; cname = PyString_AS_STRING(qualname); msg = PyString_FromFormat("coroutine '%.50s' was never awaited", cname); if (unlikely(!msg)) { PyErr_Clear(); cmsg = (char*) "coroutine was never awaited"; } else { cmsg = PyString_AS_STRING(msg); } #endif if (unlikely(PyErr_WarnEx(PyExc_RuntimeWarning, cmsg, 1) < 0)) PyErr_WriteUnraisable(self); Py_XDECREF(msg);} #endif PyObject_GC_Track(self); } #endif } else { PyObject *res = __Pyx_Coroutine_Close(self); if (unlikely(!res)) { if (PyErr_Occurred()) PyErr_WriteUnraisable(self); } else { Py_DECREF(res); } } __Pyx_ErrRestore(error_type, error_value, error_traceback); #if !CYTHON_USE_TP_FINALIZE assert(self->ob_refcnt > 0); if (--self->ob_refcnt == 0) { return; } { Py_ssize_t refcnt = self->ob_refcnt; _Py_NewReference(self); self->ob_refcnt = refcnt; } #if CYTHON_COMPILING_IN_CPYTHON assert(PyType_IS_GC(self->ob_type) && _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED); _Py_DEC_REFTOTAL; #endif #ifdef COUNT_ALLOCS --Py_TYPE(self)->tp_frees; --Py_TYPE(self)->tp_allocs; #endif #endif } static PyObject * __Pyx_Coroutine_get_name(__pyx_CoroutineObject *self, CYTHON_UNUSED void *context) { PyObject *name = self->gi_name; if (unlikely(!name)) name = Py_None; Py_INCREF(name); return name; } static int __Pyx_Coroutine_set_name(__pyx_CoroutineObject *self, PyObject *value, CYTHON_UNUSED void *context) { PyObject *tmp; #if PY_MAJOR_VERSION >= 3 if (unlikely(value == NULL || !PyUnicode_Check(value))) #else if (unlikely(value == NULL || !PyString_Check(value))) #endif { PyErr_SetString(PyExc_TypeError, "__name__ must be set to a string object"); return -1; } tmp = self->gi_name; Py_INCREF(value); self->gi_name = value; Py_XDECREF(tmp); return 0; } static PyObject * __Pyx_Coroutine_get_qualname(__pyx_CoroutineObject *self, CYTHON_UNUSED void *context) { PyObject *name = self->gi_qualname; if (unlikely(!name)) name = Py_None; Py_INCREF(name); return name; } static int __Pyx_Coroutine_set_qualname(__pyx_CoroutineObject *self, PyObject *value, CYTHON_UNUSED void *context) { PyObject *tmp; #if PY_MAJOR_VERSION >= 3 if (unlikely(value == NULL || !PyUnicode_Check(value))) #else if (unlikely(value == NULL || !PyString_Check(value))) #endif { PyErr_SetString(PyExc_TypeError, "__qualname__ must be set to a string object"); return -1; } tmp = self->gi_qualname; Py_INCREF(value); self->gi_qualname = value; Py_XDECREF(tmp); return 0; } static __pyx_CoroutineObject *__Pyx__Coroutine_New( PyTypeObject* type, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, PyObject *name, PyObject *qualname, PyObject *module_name) { __pyx_CoroutineObject *gen = PyObject_GC_New(__pyx_CoroutineObject, type); if (unlikely(!gen)) return NULL; return __Pyx__Coroutine_NewInit(gen, body, code, closure, name, qualname, module_name); } static __pyx_CoroutineObject *__Pyx__Coroutine_NewInit( __pyx_CoroutineObject *gen, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, PyObject *name, PyObject *qualname, PyObject *module_name) { gen->body = body; gen->closure = closure; Py_XINCREF(closure); gen->is_running = 0; gen->resume_label = 0; gen->classobj = NULL; gen->yieldfrom = NULL; gen->gi_exc_state.exc_type = NULL; gen->gi_exc_state.exc_value = NULL; gen->gi_exc_state.exc_traceback = NULL; #if CYTHON_USE_EXC_INFO_STACK gen->gi_exc_state.previous_item = NULL; #endif gen->gi_weakreflist = NULL; Py_XINCREF(qualname); gen->gi_qualname = qualname; Py_XINCREF(name); gen->gi_name = name; Py_XINCREF(module_name); gen->gi_modulename = module_name; Py_XINCREF(code); gen->gi_code = code; PyObject_GC_Track(gen); return gen; } /* PatchModuleWithCoroutine */ static PyObject* __Pyx_Coroutine_patch_module(PyObject* module, const char* py_code) { #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) int result; PyObject *globals, *result_obj; globals = PyDict_New(); if (unlikely(!globals)) goto ignore; result = PyDict_SetItemString(globals, "_cython_coroutine_type", #ifdef __Pyx_Coroutine_USED (PyObject*)__pyx_CoroutineType); #else Py_None); #endif if (unlikely(result < 0)) goto ignore; result = PyDict_SetItemString(globals, "_cython_generator_type", #ifdef __Pyx_Generator_USED (PyObject*)__pyx_GeneratorType); #else Py_None); #endif if (unlikely(result < 0)) goto ignore; if (unlikely(PyDict_SetItemString(globals, "_module", module) < 0)) goto ignore; if (unlikely(PyDict_SetItemString(globals, "__builtins__", __pyx_b) < 0)) goto ignore; result_obj = PyRun_String(py_code, Py_file_input, globals, globals); if (unlikely(!result_obj)) goto ignore; Py_DECREF(result_obj); Py_DECREF(globals); return module; ignore: Py_XDECREF(globals); PyErr_WriteUnraisable(module); if (unlikely(PyErr_WarnEx(PyExc_RuntimeWarning, "Cython module failed to patch module with custom type", 1) < 0)) { Py_DECREF(module); module = NULL; } #else py_code++; #endif return module; } /* PatchGeneratorABC */ #ifndef CYTHON_REGISTER_ABCS #define CYTHON_REGISTER_ABCS 1 #endif #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) static PyObject* __Pyx_patch_abc_module(PyObject *module); static PyObject* __Pyx_patch_abc_module(PyObject *module) { module = __Pyx_Coroutine_patch_module( module, "" "if _cython_generator_type is not None:\n" " try: Generator = _module.Generator\n" " except AttributeError: pass\n" " else: Generator.register(_cython_generator_type)\n" "if _cython_coroutine_type is not None:\n" " try: Coroutine = _module.Coroutine\n" " except AttributeError: pass\n" " else: Coroutine.register(_cython_coroutine_type)\n" ); return module; } #endif static int __Pyx_patch_abc(void) { #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) static int abc_patched = 0; if (CYTHON_REGISTER_ABCS && !abc_patched) { PyObject *module; module = PyImport_ImportModule((PY_MAJOR_VERSION >= 3) ? "collections.abc" : "collections"); if (!module) { PyErr_WriteUnraisable(NULL); if (unlikely(PyErr_WarnEx(PyExc_RuntimeWarning, ((PY_MAJOR_VERSION >= 3) ? "Cython module failed to register with collections.abc module" : "Cython module failed to register with collections module"), 1) < 0)) { return -1; } } else { module = __Pyx_patch_abc_module(module); abc_patched = 1; if (unlikely(!module)) return -1; Py_DECREF(module); } module = PyImport_ImportModule("backports_abc"); if (module) { module = __Pyx_patch_abc_module(module); Py_XDECREF(module); } if (!module) { PyErr_Clear(); } } #else if ((0)) __Pyx_Coroutine_patch_module(NULL, NULL); #endif return 0; } /* Generator */ static PyMethodDef __pyx_Generator_methods[] = { {"send", (PyCFunction) __Pyx_Coroutine_Send, METH_O, (char*) PyDoc_STR("send(arg) -> send 'arg' into generator,\nreturn next yielded value or raise StopIteration.")}, {"throw", (PyCFunction) __Pyx_Coroutine_Throw, METH_VARARGS, (char*) PyDoc_STR("throw(typ[,val[,tb]]) -> raise exception in generator,\nreturn next yielded value or raise StopIteration.")}, {"close", (PyCFunction) __Pyx_Coroutine_Close_Method, METH_NOARGS, (char*) PyDoc_STR("close() -> raise GeneratorExit inside generator.")}, {0, 0, 0, 0} }; static PyMemberDef __pyx_Generator_memberlist[] = { {(char *) "gi_running", T_BOOL, offsetof(__pyx_CoroutineObject, is_running), READONLY, NULL}, {(char*) "gi_yieldfrom", T_OBJECT, offsetof(__pyx_CoroutineObject, yieldfrom), READONLY, (char*) PyDoc_STR("object being iterated by 'yield from', or None")}, {(char*) "gi_code", T_OBJECT, offsetof(__pyx_CoroutineObject, gi_code), READONLY, NULL}, {0, 0, 0, 0, 0} }; static PyGetSetDef __pyx_Generator_getsets[] = { {(char *) "__name__", (getter)__Pyx_Coroutine_get_name, (setter)__Pyx_Coroutine_set_name, (char*) PyDoc_STR("name of the generator"), 0}, {(char *) "__qualname__", (getter)__Pyx_Coroutine_get_qualname, (setter)__Pyx_Coroutine_set_qualname, (char*) PyDoc_STR("qualified name of the generator"), 0}, {0, 0, 0, 0, 0} }; static PyTypeObject __pyx_GeneratorType_type = { PyVarObject_HEAD_INIT(0, 0) "generator", sizeof(__pyx_CoroutineObject), 0, (destructor) __Pyx_Coroutine_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_FINALIZE, 0, (traverseproc) __Pyx_Coroutine_traverse, 0, 0, offsetof(__pyx_CoroutineObject, gi_weakreflist), 0, (iternextfunc) __Pyx_Generator_Next, __pyx_Generator_methods, __pyx_Generator_memberlist, __pyx_Generator_getsets, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, #if CYTHON_USE_TP_FINALIZE 0, #else __Pyx_Coroutine_del, #endif 0, #if CYTHON_USE_TP_FINALIZE __Pyx_Coroutine_del, #elif PY_VERSION_HEX >= 0x030400a1 0, #endif }; static int __pyx_Generator_init(void) { __pyx_GeneratorType_type.tp_getattro = __Pyx_PyObject_GenericGetAttrNoDict; __pyx_GeneratorType_type.tp_iter = PyObject_SelfIter; __pyx_GeneratorType = __Pyx_FetchCommonType(&__pyx_GeneratorType_type); if (unlikely(!__pyx_GeneratorType)) { return -1; } return 0; } /* CheckBinaryVersion */ static int __Pyx_check_binary_version(void) { char ctversion[4], rtversion[4]; PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { char message[200]; PyOS_snprintf(message, sizeof(message), "compiletime version %s of module '%.100s' " "does not match runtime version %s", ctversion, __Pyx_MODULE_NAME, rtversion); return PyErr_WarnEx(NULL, message, 1); } return 0; } /* InitStrings */ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { while (t->p) { #if PY_MAJOR_VERSION < 3 if (t->is_unicode) { *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); } else if (t->intern) { *t->p = PyString_InternFromString(t->s); } else { *t->p = PyString_FromStringAndSize(t->s, t->n - 1); } #else if (t->is_unicode | t->is_str) { if (t->intern) { *t->p = PyUnicode_InternFromString(t->s); } else if (t->encoding) { *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); } else { *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); } } else { *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); } #endif if (!*t->p) return -1; if (PyObject_Hash(*t->p) == -1) return -1; ++t; } return 0; } static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); } static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { Py_ssize_t ignore; return __Pyx_PyObject_AsStringAndSize(o, &ignore); } #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT #if !CYTHON_PEP393_ENABLED static const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { char* defenc_c; PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); if (!defenc) return NULL; defenc_c = PyBytes_AS_STRING(defenc); #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII { char* end = defenc_c + PyBytes_GET_SIZE(defenc); char* c; for (c = defenc_c; c < end; c++) { if ((unsigned char) (*c) >= 128) { PyUnicode_AsASCIIString(o); return NULL; } } } #endif *length = PyBytes_GET_SIZE(defenc); return defenc_c; } #else static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII if (likely(PyUnicode_IS_ASCII(o))) { *length = PyUnicode_GET_LENGTH(o); return PyUnicode_AsUTF8(o); } else { PyUnicode_AsASCIIString(o); return NULL; } #else return PyUnicode_AsUTF8AndSize(o, length); #endif } #endif #endif static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT if ( #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII __Pyx_sys_getdefaultencoding_not_ascii && #endif PyUnicode_Check(o)) { return __Pyx_PyUnicode_AsStringAndSize(o, length); } else #endif #if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) if (PyByteArray_Check(o)) { *length = PyByteArray_GET_SIZE(o); return PyByteArray_AS_STRING(o); } else #endif { char* result; int r = PyBytes_AsStringAndSize(o, &result, length); if (unlikely(r < 0)) { return NULL; } else { return result; } } } static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { int retval; if (unlikely(!x)) return -1; retval = __Pyx_PyObject_IsTrue(x); Py_DECREF(x); return retval; } static PyObject* __Pyx_PyNumber_IntOrLongWrongResultType(PyObject* result, const char* type_name) { #if PY_MAJOR_VERSION >= 3 if (PyLong_Check(result)) { if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, "__int__ returned non-int (type %.200s). " "The ability to return an instance of a strict subclass of int " "is deprecated, and may be removed in a future version of Python.", Py_TYPE(result)->tp_name)) { Py_DECREF(result); return NULL; } return result; } #endif PyErr_Format(PyExc_TypeError, "__%.4s__ returned non-%.4s (type %.200s)", type_name, type_name, Py_TYPE(result)->tp_name); Py_DECREF(result); return NULL; } static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) { #if CYTHON_USE_TYPE_SLOTS PyNumberMethods *m; #endif const char *name = NULL; PyObject *res = NULL; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x) || PyLong_Check(x))) #else if (likely(PyLong_Check(x))) #endif return __Pyx_NewRef(x); #if CYTHON_USE_TYPE_SLOTS m = Py_TYPE(x)->tp_as_number; #if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = m->nb_int(x); } else if (m && m->nb_long) { name = "long"; res = m->nb_long(x); } #else if (likely(m && m->nb_int)) { name = "int"; res = m->nb_int(x); } #endif #else if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { res = PyNumber_Int(x); } #endif if (likely(res)) { #if PY_MAJOR_VERSION < 3 if (unlikely(!PyInt_Check(res) && !PyLong_Check(res))) { #else if (unlikely(!PyLong_CheckExact(res))) { #endif return __Pyx_PyNumber_IntOrLongWrongResultType(res, name); } } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_TypeError, "an integer is required"); } return res; } static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; PyObject *x; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_CheckExact(b))) { if (sizeof(Py_ssize_t) >= sizeof(long)) return PyInt_AS_LONG(b); else return PyInt_AsSsize_t(b); } #endif if (likely(PyLong_CheckExact(b))) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)b)->ob_digit; const Py_ssize_t size = Py_SIZE(b); if (likely(__Pyx_sst_abs(size) <= 1)) { ival = likely(size) ? digits[0] : 0; if (size == -1) ival = -ival; return ival; } else { switch (size) { case 2: if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -2: if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case 3: if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -3: if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case 4: if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -4: if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; } } #endif return PyLong_AsSsize_t(b); } x = PyNumber_Index(b); if (!x) return -1; ival = PyInt_AsSsize_t(x); Py_DECREF(x); return ival; } static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) { return b ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False); } static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { return PyInt_FromSize_t(ival); } #endif /* Py_PYTHON_H */
40.314748
480
0.663588
[ "object", "shape" ]
b54ab4454dd409c64eb1da9da09300d00fb59c60
1,106
h
C
cpp/BBSort/array_pool_bucket.h
CostaBru/bucketLogSort
324d3e4ca4fd600cb2d1a8f671d9553cf7c49769
[ "MIT" ]
2
2021-08-17T19:39:40.000Z
2021-08-20T03:55:18.000Z
cpp/BBSort/array_pool_bucket.h
CostaBru/BBSort
fc18af25fc25aa65b175c4f461904ee2d8c71451
[ "MIT" ]
null
null
null
cpp/BBSort/array_pool_bucket.h
CostaBru/BBSort
fc18af25fc25aa65b175c4f461904ee2d8c71451
[ "MIT" ]
null
null
null
#ifndef BBSORT_SOLUTION_ARRAY_POOL_BUCKET_H #define BBSORT_SOLUTION_ARRAY_POOL_BUCKET_H #include "object_pool.h" namespace pool { template<typename T> class array_pool_bucket { using array_value_type = T; using array_pointer = T *; private: object_pool<array_value_type> storage; public: int arrayLen; array_pool_bucket() { } ~array_pool_bucket() { clear(); } array_pointer rentArray() { if (storage.empty()) { return static_cast<array_pointer>(::operator new(sizeof(array_value_type) * arrayLen)); } return storage.pop(); } void returnArray(array_pointer object) { storage.push(object); } void clear() { while (true) { array_pointer poolItem = storage.pop(); if (poolItem == nullptr) { break; } free(poolItem); } } }; } #endif //BBSORT_SOLUTION_ARRAY_POOL_BUCKET_H
17.555556
103
0.531646
[ "object" ]
b54c6a6384dc3f05cf5efaa6a9907a39d1faa3c2
726
h
C
Source/RayLib/Triangle.h
yalcinerbora/meturay
cff17b537fd8723af090802dfd17a0a740b404f5
[ "MIT" ]
null
null
null
Source/RayLib/Triangle.h
yalcinerbora/meturay
cff17b537fd8723af090802dfd17a0a740b404f5
[ "MIT" ]
null
null
null
Source/RayLib/Triangle.h
yalcinerbora/meturay
cff17b537fd8723af090802dfd17a0a740b404f5
[ "MIT" ]
null
null
null
#pragma once #include "Vector.h" #include "AABB.h" namespace Triangle { template <class T> __device__ __host__ AABB<3, T> BoundingBox(const Vector<3, T>& p0, const Vector<3, T>& p1, const Vector<3, T>& p2); } template <class T> __device__ __host__ AABB<3, T> Triangle::BoundingBox(const Vector<3, T>& p0, const Vector<3, T>& p1, const Vector<3, T>& p2) { AABB3f aabb(p0, p0); aabb.SetMin(Vector3f::Min(aabb.Min(), p1)); aabb.SetMin(Vector3f::Min(aabb.Min(), p2)); aabb.SetMax(Vector3f::Max(aabb.Max(), p1)); aabb.SetMax(Vector3f::Max(aabb.Max(), p2)); return aabb; }
25.928571
56
0.541322
[ "vector" ]
b54d4927a88d7b9a43b15733ca6df228875ff617
224,908
c
C
dmd/expression.c
cristivlas/dnet
e45ccca24b9a192fc2779d99b8f8e31195606a73
[ "MS-PL" ]
null
null
null
dmd/expression.c
cristivlas/dnet
e45ccca24b9a192fc2779d99b8f8e31195606a73
[ "MS-PL" ]
null
null
null
dmd/expression.c
cristivlas/dnet
e45ccca24b9a192fc2779d99b8f8e31195606a73
[ "MS-PL" ]
null
null
null
// Compiler implementation of the D programming language // Copyright (c) 1999-2009 by Digital Mars // All Rights Reserved // written by Walter Bright // http://www.digitalmars.com // License for redistribution is by either the Artistic License // in artistic.txt, or the GNU General Public License in gnu.txt. // See the included readme.txt for details. #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <math.h> #include <assert.h> #if _MSC_VER #include <complex> #else #include <complex.h> #endif #if _WIN32 && __DMC__ extern "C" char * __cdecl __locale_decpoint; #endif #include "rmem.h" #include "port.h" #include "mtype.h" #include "init.h" #include "expression.h" #include "template.h" #include "utf.h" #include "enum.h" #include "scope.h" #include "statement.h" #include "declaration.h" #include "aggregate.h" #include "import.h" #include "id.h" #include "dsymbol.h" #include "module.h" #include "attrib.h" #include "hdrgen.h" #include "parse.h" Expression *createTypeInfoArray(Scope *sc, Expression *args[], int dim); Expression *expandVar(int result, VarDeclaration *v); #define LOGSEMANTIC 0 /********************************** * Set operator precedence for each operator. */ // Operator precedence - greater values are higher precedence enum PREC { PREC_zero, PREC_expr, PREC_assign, PREC_cond, PREC_oror, PREC_andand, PREC_or, PREC_xor, PREC_and, PREC_equal, PREC_rel, PREC_shift, PREC_add, PREC_mul, PREC_unary, PREC_primary, }; enum PREC precedence[TOKMAX]; void initPrecedence() { precedence[TOKdotvar] = PREC_primary; precedence[TOKimport] = PREC_primary; precedence[TOKidentifier] = PREC_primary; precedence[TOKthis] = PREC_primary; precedence[TOKsuper] = PREC_primary; precedence[TOKint64] = PREC_primary; precedence[TOKfloat64] = PREC_primary; precedence[TOKnull] = PREC_primary; precedence[TOKstring] = PREC_primary; precedence[TOKarrayliteral] = PREC_primary; precedence[TOKtypeid] = PREC_primary; precedence[TOKis] = PREC_primary; precedence[TOKassert] = PREC_primary; precedence[TOKfunction] = PREC_primary; precedence[TOKvar] = PREC_primary; #if DMDV2 precedence[TOKdefault] = PREC_primary; #endif // post precedence[TOKdotti] = PREC_primary; precedence[TOKdot] = PREC_primary; // precedence[TOKarrow] = PREC_primary; precedence[TOKplusplus] = PREC_primary; precedence[TOKminusminus] = PREC_primary; precedence[TOKcall] = PREC_primary; precedence[TOKslice] = PREC_primary; precedence[TOKarray] = PREC_primary; precedence[TOKaddress] = PREC_unary; precedence[TOKstar] = PREC_unary; precedence[TOKneg] = PREC_unary; precedence[TOKuadd] = PREC_unary; precedence[TOKnot] = PREC_unary; precedence[TOKtobool] = PREC_add; precedence[TOKtilde] = PREC_unary; precedence[TOKdelete] = PREC_unary; precedence[TOKnew] = PREC_unary; precedence[TOKcast] = PREC_unary; precedence[TOKmul] = PREC_mul; precedence[TOKdiv] = PREC_mul; precedence[TOKmod] = PREC_mul; precedence[TOKadd] = PREC_add; precedence[TOKmin] = PREC_add; precedence[TOKcat] = PREC_add; precedence[TOKshl] = PREC_shift; precedence[TOKshr] = PREC_shift; precedence[TOKushr] = PREC_shift; precedence[TOKlt] = PREC_rel; precedence[TOKle] = PREC_rel; precedence[TOKgt] = PREC_rel; precedence[TOKge] = PREC_rel; precedence[TOKunord] = PREC_rel; precedence[TOKlg] = PREC_rel; precedence[TOKleg] = PREC_rel; precedence[TOKule] = PREC_rel; precedence[TOKul] = PREC_rel; precedence[TOKuge] = PREC_rel; precedence[TOKug] = PREC_rel; precedence[TOKue] = PREC_rel; precedence[TOKin] = PREC_rel; #if 0 precedence[TOKequal] = PREC_equal; precedence[TOKnotequal] = PREC_equal; precedence[TOKidentity] = PREC_equal; precedence[TOKnotidentity] = PREC_equal; #else /* Note that we changed precedence, so that < and != have the same * precedence. This change is in the parser, too. */ precedence[TOKequal] = PREC_rel; precedence[TOKnotequal] = PREC_rel; precedence[TOKidentity] = PREC_rel; precedence[TOKnotidentity] = PREC_rel; #endif precedence[TOKand] = PREC_and; precedence[TOKxor] = PREC_xor; precedence[TOKor] = PREC_or; precedence[TOKandand] = PREC_andand; precedence[TOKoror] = PREC_oror; precedence[TOKquestion] = PREC_cond; precedence[TOKassign] = PREC_assign; precedence[TOKconstruct] = PREC_assign; precedence[TOKblit] = PREC_assign; precedence[TOKaddass] = PREC_assign; precedence[TOKminass] = PREC_assign; precedence[TOKcatass] = PREC_assign; precedence[TOKmulass] = PREC_assign; precedence[TOKdivass] = PREC_assign; precedence[TOKmodass] = PREC_assign; precedence[TOKshlass] = PREC_assign; precedence[TOKshrass] = PREC_assign; precedence[TOKushrass] = PREC_assign; precedence[TOKandass] = PREC_assign; precedence[TOKorass] = PREC_assign; precedence[TOKxorass] = PREC_assign; precedence[TOKcomma] = PREC_expr; } /************************************************************* * Given var, we need to get the * right 'this' pointer if var is in an outer class, but our * existing 'this' pointer is in an inner class. * Input: * e1 existing 'this' * ad struct or class we need the correct 'this' for * var the specific member of ad we're accessing */ Expression *getRightThis(Loc loc, Scope *sc, AggregateDeclaration *ad, Expression *e1, Declaration *var) { //printf("\ngetRightThis(e1 = %s, ad = %s, var = %s)\n", e1->toChars(), ad->toChars(), var->toChars()); L1: Type *t = e1->type->toBasetype(); //printf("e1->type = %s, var->type = %s\n", e1->type->toChars(), var->type->toChars()); /* If e1 is not the 'this' pointer for ad */ if (ad && !(t->ty == Tpointer && t->nextOf()->ty == Tstruct && ((TypeStruct *)t->nextOf())->sym == ad) && !(t->ty == Tstruct && ((TypeStruct *)t)->sym == ad) ) { ClassDeclaration *cd = ad->isClassDeclaration(); ClassDeclaration *tcd = t->isClassHandle(); /* e1 is the right this if ad is a base class of e1 */ if (!cd || !tcd || !(tcd == cd || cd->isBaseOf(tcd, NULL)) ) { /* Only classes can be inner classes with an 'outer' * member pointing to the enclosing class instance */ if (tcd && tcd->isNested()) { /* e1 is the 'this' pointer for an inner class: tcd. * Rewrite it as the 'this' pointer for the outer class. */ e1 = new DotVarExp(loc, e1, tcd->vthis); e1->type = tcd->vthis->type; // Do not call checkNestedRef() //e1 = e1->semantic(sc); // Skip up over nested functions, and get the enclosing // class type. int n = 0; Dsymbol *s; for (s = tcd->toParent(); s && s->isFuncDeclaration(); s = s->toParent()) { FuncDeclaration *f = s->isFuncDeclaration(); if (f->vthis) { //printf("rewriting e1 to %s's this\n", f->toChars()); n++; e1 = new VarExp(loc, f->vthis); } } if (s && s->isClassDeclaration()) { e1->type = s->isClassDeclaration()->type; if (n > 1) e1 = e1->semantic(sc); } else e1 = e1->semantic(sc); goto L1; } /* Can't find a path from e1 to ad */ e1->error("this for %s needs to be type %s not type %s", var->toChars(), ad->toChars(), t->toChars()); } } return e1; } /***************************************** * Determine if 'this' is available. * If it is, return the FuncDeclaration that has it. */ FuncDeclaration *hasThis(Scope *sc) { FuncDeclaration *fd; FuncDeclaration *fdthis; //printf("hasThis()\n"); fdthis = sc->parent->isFuncDeclaration(); //printf("fdthis = %p, '%s'\n", fdthis, fdthis ? fdthis->toChars() : ""); // Go upwards until we find the enclosing member function fd = fdthis; while (1) { if (!fd) { goto Lno; } if (!fd->isNested()) break; Dsymbol *parent = fd->parent; while (parent) { TemplateInstance *ti = parent->isTemplateInstance(); if (ti) parent = ti->parent; else break; } fd = fd->parent->isFuncDeclaration(); } if (!fd->isThis()) { //printf("test '%s'\n", fd->toChars()); goto Lno; } assert(fd->vthis); return fd; Lno: return NULL; // don't have 'this' available } /*************************************** * Pull out any properties. */ Expression *resolveProperties(Scope *sc, Expression *e) { //printf("resolveProperties(%s)\n", e->toChars()); if (e->type) { Type *t = e->type->toBasetype(); if (t->ty == Tfunction || e->op == TOKoverloadset) { e = new CallExp(e->loc, e); e = e->semantic(sc); } /* Look for e being a lazy parameter; rewrite as delegate call */ else if (e->op == TOKvar) { VarExp *ve = (VarExp *)e; if (ve->var->storage_class & STClazy) { e = new CallExp(e->loc, e); e = e->semantic(sc); } } else if (e->op == TOKdotexp) { e->error("expression has no value"); } } else if (e->op == TOKdottd) { e = new CallExp(e->loc, e); e = e->semantic(sc); } return e; } /****************************** * Perform semantic() on an array of Expressions. */ void arrayExpressionSemantic(Expressions *exps, Scope *sc) { if (exps) { for (size_t i = 0; i < exps->dim; i++) { Expression *e = (Expression *)exps->data[i]; e = e->semantic(sc); exps->data[i] = (void *)e; } } } /****************************** * Perform canThrow() on an array of Expressions. */ #if DMDV2 int arrayExpressionCanThrow(Expressions *exps) { if (exps) { for (size_t i = 0; i < exps->dim; i++) { Expression *e = (Expression *)exps->data[i]; if (e && e->canThrow()) return 1; } } return 0; } #endif /**************************************** * Expand tuples. */ void expandTuples(Expressions *exps) { //printf("expandTuples()\n"); if (exps) { for (size_t i = 0; i < exps->dim; i++) { Expression *arg = (Expression *)exps->data[i]; if (!arg) continue; // Look for tuple with 0 members if (arg->op == TOKtype) { TypeExp *e = (TypeExp *)arg; if (e->type->toBasetype()->ty == Ttuple) { TypeTuple *tt = (TypeTuple *)e->type->toBasetype(); if (!tt->arguments || tt->arguments->dim == 0) { exps->remove(i); if (i == exps->dim) return; i--; continue; } } } // Inline expand all the tuples while (arg->op == TOKtuple) { TupleExp *te = (TupleExp *)arg; exps->remove(i); // remove arg exps->insert(i, te->exps); // replace with tuple contents if (i == exps->dim) return; // empty tuple, no more arguments arg = (Expression *)exps->data[i]; } } } } /**************************************** * Preprocess arguments to function. */ void preFunctionArguments(Loc loc, Scope *sc, Expressions *exps) { if (exps) { expandTuples(exps); for (size_t i = 0; i < exps->dim; i++) { Expression *arg = (Expression *)exps->data[i]; if (!arg->type) { #ifdef DEBUG if (!global.gag) printf("1: \n"); #endif arg->error("%s is not an expression", arg->toChars()); arg = new IntegerExp(arg->loc, 0, Type::tint32); } arg = resolveProperties(sc, arg); exps->data[i] = (void *) arg; //arg->rvalue(); #if 0 if (arg->type->ty == Tfunction) { arg = new AddrExp(arg->loc, arg); arg = arg->semantic(sc); exps->data[i] = (void *) arg; } #endif } } } /********************************************* * Call copy constructor for struct value argument. */ #if DMDV2 Expression *callCpCtor(Loc loc, Scope *sc, Expression *e) { Type *tb = e->type->toBasetype(); assert(tb->ty == Tstruct); StructDeclaration *sd = ((TypeStruct *)tb)->sym; if (sd->cpctor) { /* Create a variable tmp, and replace the argument e with: * (tmp = e),tmp * and let AssignExp() handle the construction. * This is not the most efficent, ideally tmp would be constructed * directly onto the stack. */ Identifier *idtmp = Lexer::uniqueId("__tmp"); VarDeclaration *tmp = new VarDeclaration(loc, tb, idtmp, new ExpInitializer(0, e)); Expression *ae = new DeclarationExp(loc, tmp); e = new CommaExp(loc, ae, new VarExp(loc, tmp)); e = e->semantic(sc); } return e; } #endif /**************************************** * Now that we know the exact type of the function we're calling, * the arguments[] need to be adjusted: * 1. implicitly convert argument to the corresponding parameter type * 2. add default arguments for any missing arguments * 3. do default promotions on arguments corresponding to ... * 4. add hidden _arguments[] argument * 5. call copy constructor for struct value arguments */ void functionArguments(Loc loc, Scope *sc, TypeFunction *tf, Expressions *arguments) { unsigned n; //printf("functionArguments()\n"); assert(arguments); size_t nargs = arguments ? arguments->dim : 0; size_t nparams = Argument::dim(tf->parameters); if (nargs > nparams && tf->varargs == 0) error(loc, "expected %zu arguments, not %zu for non-variadic function type %s", nparams, nargs, tf->toChars()); n = (nargs > nparams) ? nargs : nparams; // n = max(nargs, nparams) int done = 0; for (size_t i = 0; i < n; i++) { Expression *arg; if (i < nargs) arg = (Expression *)arguments->data[i]; else arg = NULL; Type *tb; if (i < nparams) { Argument *p = Argument::getNth(tf->parameters, i); if (!arg) { if (!p->defaultArg) { if (tf->varargs == 2 && i + 1 == nparams) goto L2; error(loc, "expected %zu function arguments, not %zu", nparams, nargs); break; } arg = p->defaultArg; #if DMDV2 if (arg->op == TOKdefault) { DefaultInitExp *de = (DefaultInitExp *)arg; arg = de->resolve(loc, sc); } else #endif arg = arg->copy(); arguments->push(arg); nargs++; } if (tf->varargs == 2 && i + 1 == nparams) { //printf("\t\tvarargs == 2, p->type = '%s'\n", p->type->toChars()); if (arg->implicitConvTo(p->type)) { if (nargs != nparams) error(loc, "expected %zu function arguments, not %zu", nparams, nargs); goto L1; } L2: Type *tb = p->type->toBasetype(); Type *tret = p->isLazyArray(); switch (tb->ty) { case Tsarray: case Tarray: { // Create a static array variable v of type arg->type #ifdef IN_GCC /* GCC 4.0 does not like zero length arrays used like this; pass a null array value instead. Could also just make a one-element array. */ if (nargs - i == 0) { arg = new NullExp(loc); break; } #endif Identifier *id = Lexer::uniqueId("__arrayArg"); Type *t = new TypeSArray(((TypeArray *)tb)->next, new IntegerExp(nargs - i)); t = t->semantic(loc, sc); VarDeclaration *v = new VarDeclaration(loc, t, id, new VoidInitializer(loc)); v->semantic(sc); v->parent = sc->parent; //sc->insert(v); Expression *c = new DeclarationExp(0, v); c->type = v->type; for (size_t u = i; u < nargs; u++) { Expression *a = (Expression *)arguments->data[u]; if (tret && !((TypeArray *)tb)->next->equals(a->type)) a = a->toDelegate(sc, tret); Expression *e = new VarExp(loc, v); e = new IndexExp(loc, e, new IntegerExp(u + 1 - nparams)); AssignExp *ae = new AssignExp(loc, e, a); #if DMDV2 ae->op = TOKconstruct; #endif if (c) c = new CommaExp(loc, c, ae); else c = ae; } arg = new VarExp(loc, v); if (c) arg = new CommaExp(loc, c, arg); break; } case Tclass: { /* Set arg to be: * new Tclass(arg0, arg1, ..., argn) */ Expressions *args = new Expressions(); args->setDim(nargs - i); for (size_t u = i; u < nargs; u++) args->data[u - i] = arguments->data[u]; arg = new NewExp(loc, NULL, NULL, p->type, args); break; } default: if (!arg) { error(loc, "not enough arguments"); return; } break; } arg = arg->semantic(sc); //printf("\targ = '%s'\n", arg->toChars()); arguments->setDim(i + 1); done = 1; } L1: if (!(p->storageClass & STClazy && p->type->ty == Tvoid)) { if (p->type != arg->type) { //printf("arg->type = %s, p->type = %s\n", arg->type->toChars(), p->type->toChars()); arg = arg->implicitCastTo(sc, p->type); arg = arg->optimize(WANTvalue); } } if (p->storageClass & STCref) { arg = arg->toLvalue(sc, arg); } else if (p->storageClass & STCout) { arg = arg->modifiableLvalue(sc, arg); } // Convert static arrays to pointers tb = arg->type->toBasetype(); if (tb->ty == Tsarray) { arg = arg->checkToPointer(); } #if DMDV2 if (tb->ty == Tstruct && !(p->storageClass & (STCref | STCout))) { arg = callCpCtor(loc, sc, arg); } #endif // Convert lazy argument to a delegate if (p->storageClass & STClazy) { arg = arg->toDelegate(sc, p->type); } #if DMDV2 /* Look for arguments that cannot 'escape' from the called * function. */ if (!tf->parameterEscapes(p)) { /* Function literals can only appear once, so if this * appearance was scoped, there cannot be any others. */ if (arg->op == TOKfunction) { FuncExp *fe = (FuncExp *)arg; fe->fd->tookAddressOf = 0; } /* For passing a delegate to a scoped parameter, * this doesn't count as taking the address of it. * We only worry about 'escaping' references to the function. */ else if (arg->op == TOKdelegate) { DelegateExp *de = (DelegateExp *)arg; if (de->e1->op == TOKvar) { VarExp *ve = (VarExp *)de->e1; FuncDeclaration *f = ve->var->isFuncDeclaration(); if (f) { f->tookAddressOf--; //printf("tookAddressOf = %d\n", f->tookAddressOf); } } } } #endif } else { // If not D linkage, do promotions if (tf->linkage != LINKd) { // Promote bytes, words, etc., to ints arg = arg->integralPromotions(sc); // Promote floats to doubles switch (arg->type->ty) { case Tfloat32: arg = arg->castTo(sc, Type::tfloat64); break; case Timaginary32: arg = arg->castTo(sc, Type::timaginary64); break; } } // Convert static arrays to dynamic arrays tb = arg->type->toBasetype(); if (tb->ty == Tsarray) { TypeSArray *ts = (TypeSArray *)tb; Type *ta = ts->next->arrayOf(); if (ts->size(arg->loc) == 0) { arg = new NullExp(arg->loc); arg->type = ta; } else arg = arg->castTo(sc, ta); } #if DMDV2 if (tb->ty == Tstruct) { arg = callCpCtor(loc, sc, arg); } // Give error for overloaded function addresses if (arg->op == TOKsymoff) { SymOffExp *se = (SymOffExp *)arg; if (se->hasOverloads && !se->var->isFuncDeclaration()->isUnique()) arg->error("function %s is overloaded", arg->toChars()); } #endif arg->rvalue(); } arg = arg->optimize(WANTvalue); arguments->data[i] = (void *) arg; if (done) break; } // If D linkage and variadic, add _arguments[] as first argument if (tf->linkage == LINKd && tf->varargs == 1) { Expression *e; e = createTypeInfoArray(sc, (Expression **)&arguments->data[nparams], arguments->dim - nparams); arguments->insert(0, e); } } /************************************************** * Write expression out to buf, but wrap it * in ( ) if its precedence is less than pr. */ void expToCBuffer(OutBuffer *buf, HdrGenState *hgs, Expression *e, enum PREC pr) { //if (precedence[e->op] == 0) e->dump(0); if (precedence[e->op] < pr || /* Despite precedence, we don't allow a<b<c expressions. * They must be parenthesized. */ (pr == PREC_rel && precedence[e->op] == pr)) { buf->writeByte('('); e->toCBuffer(buf, hgs); buf->writeByte(')'); } else e->toCBuffer(buf, hgs); } /************************************************** * Write out argument list to buf. */ void argsToCBuffer(OutBuffer *buf, Expressions *arguments, HdrGenState *hgs) { if (arguments) { for (size_t i = 0; i < arguments->dim; i++) { Expression *arg = (Expression *)arguments->data[i]; if (arg) { if (i) buf->writeByte(','); expToCBuffer(buf, hgs, arg, PREC_assign); } } } } /************************************************** * Write out argument types to buf. */ void argExpTypesToCBuffer(OutBuffer *buf, Expressions *arguments, HdrGenState *hgs) { if (arguments) { OutBuffer argbuf; for (size_t i = 0; i < arguments->dim; i++) { Expression *arg = (Expression *)arguments->data[i]; if (i) buf->writeByte(','); argbuf.reset(); arg->type->toCBuffer2(&argbuf, hgs, 0); buf->write(&argbuf); } } } /******************************** Expression **************************/ Expression::Expression(Loc loc, enum TOK op, int size) : loc(loc) { //printf("Expression::Expression(op = %d) this = %p\n", op, this); this->loc = loc; this->op = op; this->size = size; type = NULL; } Expression *Expression::syntaxCopy() { //printf("Expression::syntaxCopy()\n"); //dump(0); return copy(); } /********************************* * Does *not* do a deep copy. */ Expression *Expression::copy() { Expression *e; if (!size) { #ifdef DEBUG fprintf(stdmsg, "No expression copy for: %s\n", toChars()); printf("op = %d\n", op); dump(0); #endif assert(0); } e = (Expression *)mem.malloc(size); //printf("Expression::copy(op = %d) e = %p\n", op, e); return (Expression *)memcpy(e, this, size); } /************************** * Semantically analyze Expression. * Determine types, fold constants, etc. */ Expression *Expression::semantic(Scope *sc) { #if LOGSEMANTIC printf("Expression::semantic() %s\n", toChars()); #endif if (type) type = type->semantic(loc, sc); else type = Type::tvoid; return this; } /********************************** * Try to run semantic routines. * If they fail, return NULL. */ Expression *Expression::trySemantic(Scope *sc) { unsigned errors = global.errors; global.gag++; Expression *e = semantic(sc); global.gag--; if (errors != global.errors) { global.errors = errors; e = NULL; } return e; } void Expression::print() { fprintf(stdmsg, "%s\n", toChars()); fflush(stdmsg); } char *Expression::toChars() { OutBuffer *buf; HdrGenState hgs; memset(&hgs, 0, sizeof(hgs)); buf = new OutBuffer(); toCBuffer(buf, &hgs); return buf->toChars(); } void Expression::error(const char *format, ...) { va_list ap; va_start(ap, format); ::verror(loc, format, ap); va_end( ap ); } void Expression::warning(const char *format, ...) { if (global.params.warnings && !global.gag) { fprintf(stdmsg, "warning - "); va_list ap; va_start(ap, format); ::verror(loc, format, ap); va_end( ap ); } } void Expression::rvalue() { if (type && type->toBasetype()->ty == Tvoid) { error("expression %s is void and has no value", toChars()); #if 0 dump(0); halt(); #endif type = Type::terror; } } Expression *Expression::combine(Expression *e1, Expression *e2) { if (e1) { if (e2) { e1 = new CommaExp(e1->loc, e1, e2); e1->type = e2->type; } } else e1 = e2; return e1; } dinteger_t Expression::toInteger() { //printf("Expression %s\n", Token::toChars(op)); error("Integer constant expression expected instead of %s", toChars()); return 0; } uinteger_t Expression::toUInteger() { //printf("Expression %s\n", Token::toChars(op)); return (uinteger_t)toInteger(); } real_t Expression::toReal() { error("Floating point constant expression expected instead of %s", toChars()); return 0; } real_t Expression::toImaginary() { error("Floating point constant expression expected instead of %s", toChars()); return 0; } complex_t Expression::toComplex() { error("Floating point constant expression expected instead of %s", toChars()); #ifdef IN_GCC return complex_t(real_t(0)); // %% nicer #else return 0; #endif } void Expression::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { buf->writestring(Token::toChars(op)); } void Expression::toMangleBuffer(OutBuffer *buf) { error("expression %s is not a valid template value argument", toChars()); #ifdef DEBUG dump(0); #endif } /*************************************** * Return !=0 if expression is an lvalue. */ #if DMDV2 int Expression::isLvalue() { return 0; } #endif /******************************* * Give error if we're not an lvalue. * If we can, convert expression to be an lvalue. */ Expression *Expression::toLvalue(Scope *sc, Expression *e) { if (!e) e = this; else if (!loc.filename) loc = e->loc; error("%s is not an lvalue", e->toChars()); return this; } Expression *Expression::modifiableLvalue(Scope *sc, Expression *e) { //printf("Expression::modifiableLvalue() %s, type = %s\n", toChars(), type->toChars()); // See if this expression is a modifiable lvalue (i.e. not const) #if DMDV2 if (type && (!type->isMutable() || !type->isAssignable())) error("%s is not mutable", e->toChars()); #endif return toLvalue(sc, e); } /************************************ * Detect cases where pointers to the stack can 'escape' the * lifetime of the stack frame. */ void Expression::checkEscape() { } void Expression::checkScalar() { if (!type->isscalar()) error("'%s' is not a scalar, it is a %s", toChars(), type->toChars()); rvalue(); } void Expression::checkNoBool() { if (type->toBasetype()->ty == Tbool) error("operation not allowed on bool '%s'", toChars()); } Expression *Expression::checkIntegral() { if (!type->isintegral()) { error("'%s' is not of integral type, it is a %s", toChars(), type->toChars()); return new ErrorExp(); } rvalue(); return this; } Expression *Expression::checkArithmetic() { if (!type->isintegral() && !type->isfloating()) { error("'%s' is not of arithmetic type, it is a %s", toChars(), type->toChars()); return new ErrorExp(); } rvalue(); return this; } void Expression::checkDeprecated(Scope *sc, Dsymbol *s) { s->checkDeprecated(loc, sc); } #if DMDV2 void Expression::checkPurity(Scope *sc, FuncDeclaration *f) { #if 1 if (sc->func) { FuncDeclaration *outerfunc=sc->func; while (outerfunc->toParent2() && outerfunc->toParent2()->isFuncDeclaration()) { outerfunc = outerfunc->toParent2()->isFuncDeclaration(); } if (outerfunc->isPure() && !sc->intypeof && (!f->isNested() && !f->isPure())) error("pure function '%s' cannot call impure function '%s'\n", sc->func->toChars(), f->toChars()); } #else if (sc->func && sc->func->isPure() && !sc->intypeof && !f->isPure()) error("pure function '%s' cannot call impure function '%s'\n", sc->func->toChars(), f->toChars()); #endif } #endif /******************************** * Check for expressions that have no use. * Input: * flag 0 not going to use the result, so issue error message if no * side effects * 1 the result of the expression is used, but still check * for useless subexpressions * 2 do not issue error messages, just return !=0 if expression * has side effects */ int Expression::checkSideEffect(int flag) { if (flag == 0) { if (op == TOKimport) { error("%s has no effect", toChars()); } else error("%s has no effect in expression (%s)", Token::toChars(op), toChars()); } return 0; } /***************************** * Check that expression can be tested for true or false. */ Expression *Expression::checkToBoolean() { // Default is 'yes' - do nothing #ifdef DEBUG if (!type) dump(0); #endif if (!type->checkBoolean()) { error("expression %s of type %s does not have a boolean value", toChars(), type->toChars()); } return this; } /**************************** */ Expression *Expression::checkToPointer() { Expression *e; Type *tb; //printf("Expression::checkToPointer()\n"); e = this; // If C static array, convert to pointer tb = type->toBasetype(); if (tb->ty == Tsarray) { TypeSArray *ts = (TypeSArray *)tb; if (ts->size(loc) == 0) e = new NullExp(loc); else e = new AddrExp(loc, this); e->type = ts->next->pointerTo(); } return e; } /****************************** * Take address of expression. */ Expression *Expression::addressOf(Scope *sc) { Expression *e; //printf("Expression::addressOf()\n"); e = toLvalue(sc, NULL); e = new AddrExp(loc, e); e->type = type->pointerTo(); return e; } /****************************** * If this is a reference, dereference it. */ Expression *Expression::deref() { //printf("Expression::deref()\n"); if (type->ty == Treference) { Expression *e; e = new PtrExp(loc, this); e->type = ((TypeReference *)type)->next; return e; } return this; } /******************************** * Does this expression statically evaluate to a boolean TRUE or FALSE? */ int Expression::isBool(int result) { return FALSE; } /******************************** * Does this expression result in either a 1 or a 0? */ int Expression::isBit() { return FALSE; } /******************************** * Can this expression throw an exception? * Valid only after semantic() pass. */ int Expression::canThrow() { #if DMDV2 return FALSE; #else return TRUE; #endif } Expressions *Expression::arraySyntaxCopy(Expressions *exps) { Expressions *a = NULL; if (exps) { a = new Expressions(); a->setDim(exps->dim); for (int i = 0; i < a->dim; i++) { Expression *e = (Expression *)exps->data[i]; e = e->syntaxCopy(); a->data[i] = e; } } return a; } /******************************** IntegerExp **************************/ IntegerExp::IntegerExp(Loc loc, dinteger_t value, Type *type) : Expression(loc, TOKint64, sizeof(IntegerExp)) { //printf("IntegerExp(value = %lld, type = '%s')\n", value, type ? type->toChars() : ""); if (type && !type->isscalar()) { //printf("%s, loc = %d\n", toChars(), loc.linnum); error("integral constant must be scalar type, not %s", type->toChars()); type = Type::terror; } this->type = type; this->value = value; } IntegerExp::IntegerExp(dinteger_t value) : Expression(0, TOKint64, sizeof(IntegerExp)) { this->type = Type::tint32; this->value = value; } int IntegerExp::equals(Object *o) { IntegerExp *ne; if (this == o || (((Expression *)o)->op == TOKint64 && ((ne = (IntegerExp *)o), type->toHeadMutable()->equals(ne->type->toHeadMutable())) && value == ne->value)) return 1; return 0; } char *IntegerExp::toChars() { #if 1 return Expression::toChars(); #else static char buffer[sizeof(value) * 3 + 1]; sprintf(buffer, "%jd", value); return buffer; #endif } dinteger_t IntegerExp::toInteger() { Type *t; t = type; while (t) { switch (t->ty) { case Tbit: case Tbool: value = (value != 0); break; case Tint8: value = (d_int8) value; break; case Tchar: case Tuns8: value = (d_uns8) value; break; case Tint16: value = (d_int16) value; break; case Twchar: case Tuns16: value = (d_uns16) value; break; case Tint32: value = (d_int32) value; break; case Tdchar: case Tuns32: value = (d_uns32) value; break; case Tint64: value = (d_int64) value; break; case Tuns64: value = (d_uns64) value; break; case Tpointer: if (PTRSIZE == 4) value = (d_uns32) value; else if (PTRSIZE == 8) value = (d_uns64) value; else assert(0); break; case Tenum: { TypeEnum *te = (TypeEnum *)t; t = te->sym->memtype; continue; } case Ttypedef: { TypeTypedef *tt = (TypeTypedef *)t; t = tt->sym->basetype; continue; } default: /* This can happen if errors, such as * the type is painted on like in fromConstInitializer(). */ if (!global.errors) { type->print(); assert(0); } break; } break; } return value; } real_t IntegerExp::toReal() { Type *t; toInteger(); t = type->toBasetype(); if (t->ty == Tuns64) return (real_t)(d_uns64)value; else return (real_t)(d_int64)value; } real_t IntegerExp::toImaginary() { return (real_t) 0; } complex_t IntegerExp::toComplex() { return toReal(); } int IntegerExp::isBool(int result) { return result ? value != 0 : value == 0; } Expression *IntegerExp::semantic(Scope *sc) { if (!type) { // Determine what the type of this number is dinteger_t number = value; if (number & 0x8000000000000000LL) type = Type::tuns64; else if (number & 0xFFFFFFFF80000000LL) type = Type::tint64; else type = Type::tint32; } else { if (!type->deco) type = type->semantic(loc, sc); } return this; } Expression *IntegerExp::toLvalue(Scope *sc, Expression *e) { if (!e) e = this; else if (!loc.filename) loc = e->loc; e->error("constant %s is not an lvalue", e->toChars()); return this; } void IntegerExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { dinteger_t v = toInteger(); if (type) { Type *t = type; L1: switch (t->ty) { case Tenum: { TypeEnum *te = (TypeEnum *)t; buf->printf("cast(%s)", te->sym->toChars()); t = te->sym->memtype; goto L1; } case Ttypedef: { TypeTypedef *tt = (TypeTypedef *)t; buf->printf("cast(%s)", tt->sym->toChars()); t = tt->sym->basetype; goto L1; } case Twchar: // BUG: need to cast(wchar) case Tdchar: // BUG: need to cast(dchar) if ((uinteger_t)v > 0xFF) { buf->printf("'\\U%08x'", v); break; } case Tchar: if (v == '\'') buf->writestring("'\\''"); else if (isprint(v) && v != '\\') buf->printf("'%c'", (int)v); else buf->printf("'\\x%02x'", (int)v); break; case Tint8: buf->writestring("cast(byte)"); goto L2; case Tint16: buf->writestring("cast(short)"); goto L2; case Tint32: L2: buf->printf("%d", (int)v); break; case Tuns8: buf->writestring("cast(ubyte)"); goto L3; case Tuns16: buf->writestring("cast(ushort)"); goto L3; case Tuns32: L3: buf->printf("%du", (unsigned)v); break; case Tint64: buf->printf("%jdL", v); break; case Tuns64: L4: buf->printf("%juLU", v); break; case Tbit: case Tbool: buf->writestring((char *)(v ? "true" : "false")); break; case Tpointer: buf->writestring("cast("); buf->writestring(t->toChars()); buf->writeByte(')'); if (PTRSIZE == 4) goto L3; else if (PTRSIZE == 8) goto L4; else assert(0); default: /* This can happen if errors, such as * the type is painted on like in fromConstInitializer(). */ if (!global.errors) { #ifdef DEBUG t->print(); #endif assert(0); } break; } } else if (v & 0x8000000000000000LL) buf->printf("0x%jx", v); else buf->printf("%jd", v); } void IntegerExp::toMangleBuffer(OutBuffer *buf) { if ((sinteger_t)value < 0) buf->printf("N%jd", -value); else buf->printf("%jd", value); } /******************************** ErrorExp **************************/ /* Use this expression for error recovery. * It should behave as a 'sink' to prevent further cascaded error messages. */ ErrorExp::ErrorExp() : IntegerExp(0, 0, Type::terror) { } void ErrorExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { buf->writestring("__error"); } /******************************** RealExp **************************/ RealExp::RealExp(Loc loc, real_t value, Type *type) : Expression(loc, TOKfloat64, sizeof(RealExp)) { //printf("RealExp::RealExp(%Lg)\n", value); this->value = value; this->type = type; } char *RealExp::toChars() { char buffer[sizeof(value) * 3 + 8 + 1 + 1]; #ifdef IN_GCC value.format(buffer, sizeof(buffer)); if (type->isimaginary()) strcat(buffer, "i"); #else sprintf(buffer, type->isimaginary() ? "%Lgi" : "%Lg", value); #endif assert(strlen(buffer) < sizeof(buffer)); return mem.strdup(buffer); } dinteger_t RealExp::toInteger() { #ifdef IN_GCC return toReal().toInt(); #else return (sinteger_t) toReal(); #endif } uinteger_t RealExp::toUInteger() { #ifdef IN_GCC return (uinteger_t) toReal().toInt(); #else return (uinteger_t) toReal(); #endif } real_t RealExp::toReal() { return type->isreal() ? value : 0; } real_t RealExp::toImaginary() { return type->isreal() ? 0 : value; } complex_t RealExp::toComplex() { #ifdef __DMC__ return toReal() + toImaginary() * I; #else return complex_t(toReal(), toImaginary()); #endif } /******************************** * Test to see if two reals are the same. * Regard NaN's as equivalent. * Regard +0 and -0 as different. */ int RealEquals(real_t x1, real_t x2) { #if 1 return (Port::isNan(x1) && Port::isNan(x2)) || #elif __APPLE__ return (__inline_isnan(x1) && __inline_isnan(x2)) || #else return (isnan(x1) && isnan(x2)) || #endif /* In some cases, the REALPAD bytes get garbage in them, * so be sure and ignore them. */ memcmp(&x1, &x2, REALSIZE - REALPAD) == 0; } int RealExp::equals(Object *o) { RealExp *ne; if (this == o || (((Expression *)o)->op == TOKfloat64 && ((ne = (RealExp *)o), type->toHeadMutable()->equals(ne->type->toHeadMutable())) && RealEquals(value, ne->value) ) ) return 1; return 0; } Expression *RealExp::semantic(Scope *sc) { if (!type) type = Type::tfloat64; else type = type->semantic(loc, sc); return this; } int RealExp::isBool(int result) { #ifdef IN_GCC return result ? (! value.isZero()) : (value.isZero()); #else return result ? (value != 0) : (value == 0); #endif } void floatToBuffer(OutBuffer *buf, Type *type, real_t value) { /* In order to get an exact representation, try converting it * to decimal then back again. If it matches, use it. * If it doesn't, fall back to hex, which is * always exact. */ char buffer[25]; sprintf(buffer, "%Lg", value); assert(strlen(buffer) < sizeof(buffer)); #if _WIN32 && __DMC__ char *save = __locale_decpoint; __locale_decpoint = "."; real_t r = strtold(buffer, NULL); __locale_decpoint = save; #else real_t r = strtold(buffer, NULL); #endif if (r == value) // if exact duplication buf->writestring(buffer); else buf->printf("%La", value); // ensure exact duplication if (type) { Type *t = type->toBasetype(); switch (t->ty) { case Tfloat32: case Timaginary32: case Tcomplex32: buf->writeByte('F'); break; case Tfloat80: case Timaginary80: case Tcomplex80: buf->writeByte('L'); break; default: break; } if (t->isimaginary()) buf->writeByte('i'); } } void RealExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { floatToBuffer(buf, type, value); } void realToMangleBuffer(OutBuffer *buf, real_t value) { /* Rely on %A to get portable mangling. * Must munge result to get only identifier characters. * * Possible values from %A => mangled result * NAN => NAN * -INF => NINF * INF => INF * -0X1.1BC18BA997B95P+79 => N11BC18BA997B95P79 * 0X1.9P+2 => 19P2 */ #if 1 if (Port::isNan(value)) #elif __APPLE__ if (__inline_isnan(value)) #else if (isnan(value)) #endif buf->writestring("NAN"); // no -NAN bugs else { char buffer[32]; int n = sprintf(buffer, "%LA", value); assert(n > 0 && n < sizeof(buffer)); for (int i = 0; i < n; i++) { char c = buffer[i]; switch (c) { case '-': buf->writeByte('N'); break; case '+': case 'X': case '.': break; case '0': if (i < 2) break; // skip leading 0X default: buf->writeByte(c); break; } } } } void RealExp::toMangleBuffer(OutBuffer *buf) { buf->writeByte('e'); realToMangleBuffer(buf, value); } /******************************** ComplexExp **************************/ ComplexExp::ComplexExp(Loc loc, complex_t value, Type *type) : Expression(loc, TOKcomplex80, sizeof(ComplexExp)) { this->value = value; this->type = type; //printf("ComplexExp::ComplexExp(%s)\n", toChars()); } char *ComplexExp::toChars() { char buffer[sizeof(value) * 3 + 8 + 1]; #ifdef IN_GCC char buf1[sizeof(value) * 3 + 8 + 1]; char buf2[sizeof(value) * 3 + 8 + 1]; creall(value).format(buf1, sizeof(buf1)); cimagl(value).format(buf2, sizeof(buf2)); sprintf(buffer, "(%s+%si)", buf1, buf2); #else sprintf(buffer, "(%Lg+%Lgi)", creall(value), cimagl(value)); assert(strlen(buffer) < sizeof(buffer)); #endif return mem.strdup(buffer); } dinteger_t ComplexExp::toInteger() { #ifdef IN_GCC return (sinteger_t) toReal().toInt(); #else return (sinteger_t) toReal(); #endif } uinteger_t ComplexExp::toUInteger() { #ifdef IN_GCC return (uinteger_t) toReal().toInt(); #else return (uinteger_t) toReal(); #endif } real_t ComplexExp::toReal() { return creall(value); } real_t ComplexExp::toImaginary() { return cimagl(value); } complex_t ComplexExp::toComplex() { return value; } int ComplexExp::equals(Object *o) { ComplexExp *ne; if (this == o || (((Expression *)o)->op == TOKcomplex80 && ((ne = (ComplexExp *)o), type->toHeadMutable()->equals(ne->type->toHeadMutable())) && RealEquals(creall(value), creall(ne->value)) && RealEquals(cimagl(value), cimagl(ne->value)) ) ) return 1; return 0; } Expression *ComplexExp::semantic(Scope *sc) { if (!type) type = Type::tcomplex80; else type = type->semantic(loc, sc); return this; } int ComplexExp::isBool(int result) { if (result) return (bool)(value); else return !value; } void ComplexExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { /* Print as: * (re+imi) */ #ifdef IN_GCC char buf1[sizeof(value) * 3 + 8 + 1]; char buf2[sizeof(value) * 3 + 8 + 1]; creall(value).format(buf1, sizeof(buf1)); cimagl(value).format(buf2, sizeof(buf2)); buf->printf("(%s+%si)", buf1, buf2); #else buf->writeByte('('); floatToBuffer(buf, type, creall(value)); buf->writeByte('+'); floatToBuffer(buf, type, cimagl(value)); buf->writestring("i)"); #endif } void ComplexExp::toMangleBuffer(OutBuffer *buf) { buf->writeByte('c'); real_t r = toReal(); realToMangleBuffer(buf, r); buf->writeByte('c'); // separate the two r = toImaginary(); realToMangleBuffer(buf, r); } /******************************** IdentifierExp **************************/ IdentifierExp::IdentifierExp(Loc loc, Identifier *ident) : Expression(loc, TOKidentifier, sizeof(IdentifierExp)) { this->ident = ident; } Expression *IdentifierExp::semantic(Scope *sc) { Dsymbol *s; Dsymbol *scopesym; #if LOGSEMANTIC printf("IdentifierExp::semantic('%s')\n", ident->toChars()); #endif s = sc->search(loc, ident, &scopesym); if (s) { Expression *e; WithScopeSymbol *withsym; /* See if the symbol was a member of an enclosing 'with' */ withsym = scopesym->isWithScopeSymbol(); if (withsym) { #if DMDV2 /* Disallow shadowing */ // First find the scope of the with Scope *scwith = sc; while (scwith->scopesym != scopesym) { scwith = scwith->enclosing; assert(scwith); } // Look at enclosing scopes for symbols with the same name, // in the same function for (Scope *scx = scwith; scx && scx->func == scwith->func; scx = scx->enclosing) { Dsymbol *s2; if (scx->scopesym && scx->scopesym->symtab && (s2 = scx->scopesym->symtab->lookup(s->ident)) != NULL && s != s2) { error("with symbol %s is shadowing local symbol %s", s->toPrettyChars(), s2->toPrettyChars()); } } #endif s = s->toAlias(); // Same as wthis.ident if (s->needThis() || s->isTemplateDeclaration()) { e = new VarExp(loc, withsym->withstate->wthis); e = new DotIdExp(loc, e, ident); } else { Type *t = withsym->withstate->wthis->type; if (t->ty == Tpointer) t = ((TypePointer *)t)->next; e = typeDotIdExp(loc, t, ident); } } else { /* If f is really a function template, * then replace f with the function template declaration. */ FuncDeclaration *f = s->isFuncDeclaration(); if (f && f->parent) { TemplateInstance *ti = f->parent->isTemplateInstance(); if (ti && !ti->isTemplateMixin() && (ti->name == f->ident || ti->toAlias()->ident == f->ident) && ti->tempdecl && ti->tempdecl->onemember) { TemplateDeclaration *tempdecl = ti->tempdecl; if (tempdecl->overroot) // if not start of overloaded list of TemplateDeclaration's tempdecl = tempdecl->overroot; // then get the start e = new TemplateExp(loc, tempdecl); e = e->semantic(sc); return e; } } // Haven't done overload resolution yet, so pass 1 e = new DsymbolExp(loc, s, 1); } return e->semantic(sc); } error("undefined identifier %s", ident->toChars()); type = Type::terror; return this; } char *IdentifierExp::toChars() { return ident->toChars(); } void IdentifierExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { if (hgs->hdrgen) buf->writestring(ident->toHChars2()); else buf->writestring(ident->toChars()); } #if DMDV2 int IdentifierExp::isLvalue() { return 1; } #endif Expression *IdentifierExp::toLvalue(Scope *sc, Expression *e) { #if 0 tym = tybasic(e1->ET->Tty); if (!(tyscalar(tym) || tym == TYstruct || tym == TYarray && e->Eoper == TOKaddr)) synerr(EM_lvalue); // lvalue expected #endif return this; } /******************************** DollarExp **************************/ DollarExp::DollarExp(Loc loc) : IdentifierExp(loc, Id::dollar) { } /******************************** DsymbolExp **************************/ DsymbolExp::DsymbolExp(Loc loc, Dsymbol *s, int hasOverloads) : Expression(loc, TOKdsymbol, sizeof(DsymbolExp)) { this->s = s; this->hasOverloads = hasOverloads; } Expression *DsymbolExp::semantic(Scope *sc) { #if LOGSEMANTIC printf("DsymbolExp::semantic('%s')\n", s->toChars()); #endif Lagain: EnumMember *em; Expression *e; VarDeclaration *v; FuncDeclaration *f; FuncLiteralDeclaration *fld; OverloadSet *o; Declaration *d; ClassDeclaration *cd; ClassDeclaration *thiscd = NULL; Import *imp; Package *pkg; Type *t; //printf("DsymbolExp:: %p '%s' is a symbol\n", this, toChars()); //printf("s = '%s', s->kind = '%s'\n", s->toChars(), s->kind()); if (type) return this; if (!s->isFuncDeclaration()) // functions are checked after overloading checkDeprecated(sc, s); s = s->toAlias(); //printf("s = '%s', s->kind = '%s', s->needThis() = %p\n", s->toChars(), s->kind(), s->needThis()); if (!s->isFuncDeclaration()) checkDeprecated(sc, s); if (sc->func) thiscd = sc->func->parent->isClassDeclaration(); // BUG: This should happen after overload resolution for functions, not before if (s->needThis()) { if (hasThis(sc) #if DMDV2 && !s->isFuncDeclaration() #endif ) { // Supply an implicit 'this', as in // this.ident DotVarExp *de; de = new DotVarExp(loc, new ThisExp(loc), s->isDeclaration()); return de->semantic(sc); } } em = s->isEnumMember(); if (em) { e = em->value; e = e->semantic(sc); return e; } v = s->isVarDeclaration(); if (v) { //printf("Identifier '%s' is a variable, type '%s'\n", toChars(), v->type->toChars()); if (!type) { type = v->type; if (!v->type) { error("forward reference of %s %s", v->kind(), v->toChars()); type = Type::terror; } } e = new VarExp(loc, v); e->type = type; e = e->semantic(sc); return e->deref(); } fld = s->isFuncLiteralDeclaration(); if (fld) { //printf("'%s' is a function literal\n", fld->toChars()); e = new FuncExp(loc, fld); return e->semantic(sc); } f = s->isFuncDeclaration(); if (f) { //printf("'%s' is a function\n", f->toChars()); if (!f->type->deco) { error("forward reference to %s", toChars()); } return new VarExp(loc, f, hasOverloads); } o = s->isOverloadSet(); if (o) { //printf("'%s' is an overload set\n", o->toChars()); return new OverExp(o); } cd = s->isClassDeclaration(); if (cd && thiscd && cd->isBaseOf(thiscd, NULL) && sc->func->needThis()) { // We need to add an implicit 'this' if cd is this class or a base class. DotTypeExp *dte; dte = new DotTypeExp(loc, new ThisExp(loc), s); return dte->semantic(sc); } imp = s->isImport(); if (imp) { if (!imp->pkg) { error("forward reference of import %s", imp->toChars()); return this; } ScopeExp *ie = new ScopeExp(loc, imp->pkg); return ie->semantic(sc); } pkg = s->isPackage(); if (pkg) { ScopeExp *ie; ie = new ScopeExp(loc, pkg); return ie->semantic(sc); } Module *mod = s->isModule(); if (mod) { ScopeExp *ie; ie = new ScopeExp(loc, mod); return ie->semantic(sc); } t = s->getType(); if (t) { return new TypeExp(loc, t); } TupleDeclaration *tup = s->isTupleDeclaration(); if (tup) { e = new TupleExp(loc, tup); e = e->semantic(sc); return e; } TemplateInstance *ti = s->isTemplateInstance(); if (ti && !global.errors) { if (!ti->semanticRun) ti->semantic(sc); s = ti->inst->toAlias(); if (!s->isTemplateInstance()) goto Lagain; e = new ScopeExp(loc, ti); e = e->semantic(sc); return e; } TemplateDeclaration *td = s->isTemplateDeclaration(); if (td) { e = new TemplateExp(loc, td); e = e->semantic(sc); return e; } Lerr: error("%s '%s' is not a variable", s->kind(), s->toChars()); type = Type::terror; return this; } char *DsymbolExp::toChars() { return s->toChars(); } void DsymbolExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { buf->writestring(s->toChars()); } #if DMDV2 int DsymbolExp::isLvalue() { return 1; } #endif Expression *DsymbolExp::toLvalue(Scope *sc, Expression *e) { #if 0 tym = tybasic(e1->ET->Tty); if (!(tyscalar(tym) || tym == TYstruct || tym == TYarray && e->Eoper == TOKaddr)) synerr(EM_lvalue); // lvalue expected #endif return this; } /******************************** ThisExp **************************/ ThisExp::ThisExp(Loc loc) : Expression(loc, TOKthis, sizeof(ThisExp)) { //printf("ThisExp::ThisExp() loc = %d\n", loc.linnum); var = NULL; } Expression *ThisExp::semantic(Scope *sc) { FuncDeclaration *fd; FuncDeclaration *fdthis; int nested = 0; #if LOGSEMANTIC printf("ThisExp::semantic()\n"); #endif if (type) { //assert(global.errors || var); return this; } /* Special case for typeof(this) and typeof(super) since both * should work even if they are not inside a non-static member function */ if (sc->intypeof) { // Find enclosing struct or class for (Dsymbol *s = sc->parent; 1; s = s->parent) { if (!s) { error("%s is not in a class or struct scope", toChars()); goto Lerr; } ClassDeclaration *cd = s->isClassDeclaration(); if (cd) { type = cd->type; return this; } StructDeclaration *sd = s->isStructDeclaration(); if (sd) { #if STRUCTTHISREF type = sd->type; #else type = sd->type->pointerTo(); #endif return this; } } } fdthis = sc->parent->isFuncDeclaration(); fd = hasThis(sc); // fd is the uplevel function with the 'this' variable if (!fd) goto Lerr; assert(fd->vthis); var = fd->vthis; assert(var->parent); type = var->type; var->isVarDeclaration()->checkNestedReference(sc, loc); if (!sc->intypeof) sc->callSuper |= CSXthis; return this; Lerr: error("'this' is only defined in non-static member functions, not %s", sc->parent->toChars()); type = Type::terror; return this; } int ThisExp::isBool(int result) { return result ? TRUE : FALSE; } void ThisExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { buf->writestring("this"); } #if DMDV2 int ThisExp::isLvalue() { return 1; } #endif Expression *ThisExp::toLvalue(Scope *sc, Expression *e) { return this; } /******************************** SuperExp **************************/ SuperExp::SuperExp(Loc loc) : ThisExp(loc) { op = TOKsuper; } Expression *SuperExp::semantic(Scope *sc) { FuncDeclaration *fd; FuncDeclaration *fdthis; ClassDeclaration *cd; Dsymbol *s; #if LOGSEMANTIC printf("SuperExp::semantic('%s')\n", toChars()); #endif if (type) return this; /* Special case for typeof(this) and typeof(super) since both * should work even if they are not inside a non-static member function */ if (sc->intypeof) { // Find enclosing class for (Dsymbol *s = sc->parent; 1; s = s->parent) { ClassDeclaration *cd; if (!s) { error("%s is not in a class scope", toChars()); goto Lerr; } cd = s->isClassDeclaration(); if (cd) { cd = cd->baseClass; if (!cd) { error("class %s has no 'super'", s->toChars()); goto Lerr; } type = cd->type; return this; } } } fdthis = sc->parent->isFuncDeclaration(); fd = hasThis(sc); if (!fd) goto Lerr; assert(fd->vthis); var = fd->vthis; assert(var->parent); s = fd->toParent(); while (s && s->isTemplateInstance()) s = s->toParent(); assert(s); cd = s->isClassDeclaration(); //printf("parent is %s %s\n", fd->toParent()->kind(), fd->toParent()->toChars()); if (!cd) goto Lerr; if (!cd->baseClass) { error("no base class for %s", cd->toChars()); type = fd->vthis->type; } else { type = cd->baseClass->type; } var->isVarDeclaration()->checkNestedReference(sc, loc); if (!sc->intypeof) sc->callSuper |= CSXsuper; return this; Lerr: error("'super' is only allowed in non-static class member functions"); type = Type::tint32; return this; } void SuperExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { buf->writestring("super"); } /******************************** NullExp **************************/ NullExp::NullExp(Loc loc) : Expression(loc, TOKnull, sizeof(NullExp)) { committed = 0; } Expression *NullExp::semantic(Scope *sc) { #if LOGSEMANTIC printf("NullExp::semantic('%s')\n", toChars()); #endif // NULL is the same as (void *)0 if (!type) type = Type::tvoid->pointerTo(); return this; } int NullExp::isBool(int result) { return result ? FALSE : TRUE; } void NullExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { buf->writestring("null"); } void NullExp::toMangleBuffer(OutBuffer *buf) { buf->writeByte('n'); } /******************************** StringExp **************************/ StringExp::StringExp(Loc loc, char *string) : Expression(loc, TOKstring, sizeof(StringExp)) { this->string = string; this->len = strlen(string); this->sz = 1; this->committed = 0; this->postfix = 0; } StringExp::StringExp(Loc loc, void *string, size_t len) : Expression(loc, TOKstring, sizeof(StringExp)) { this->string = string; this->len = len; this->sz = 1; this->committed = 0; this->postfix = 0; } StringExp::StringExp(Loc loc, void *string, size_t len, unsigned char postfix) : Expression(loc, TOKstring, sizeof(StringExp)) { this->string = string; this->len = len; this->sz = 1; this->committed = 0; this->postfix = postfix; } #if 0 Expression *StringExp::syntaxCopy() { printf("StringExp::syntaxCopy() %s\n", toChars()); return copy(); } #endif int StringExp::equals(Object *o) { //printf("StringExp::equals('%s')\n", o->toChars()); if (o && o->dyncast() == DYNCAST_EXPRESSION) { Expression *e = (Expression *)o; if (e->op == TOKstring) { return compare(o) == 0; } } return FALSE; } char *StringExp::toChars() { OutBuffer buf; HdrGenState hgs; char *p; memset(&hgs, 0, sizeof(hgs)); toCBuffer(&buf, &hgs); buf.writeByte(0); p = (char *)buf.data; buf.data = NULL; return p; } Expression *StringExp::semantic(Scope *sc) { #if LOGSEMANTIC printf("StringExp::semantic() %s\n", toChars()); #endif if (!type) { OutBuffer buffer; size_t newlen = 0; const char *p; size_t u; unsigned c; switch (postfix) { case 'd': for (u = 0; u < len;) { p = utf_decodeChar((unsigned char *)string, len, &u, &c); if (p) { error("%s", p); break; } else { buffer.write4(c); newlen++; } } buffer.write4(0); string = buffer.extractData(); len = newlen; sz = 4; //type = new TypeSArray(Type::tdchar, new IntegerExp(loc, len, Type::tindex)); type = new TypeDArray(Type::tdchar->invariantOf()); committed = 1; break; case 'w': for (u = 0; u < len;) { p = utf_decodeChar((unsigned char *)string, len, &u, &c); if (p) { error("%s", p); break; } else { buffer.writeUTF16(c); newlen++; if (c >= 0x10000) newlen++; } } buffer.writeUTF16(0); string = buffer.extractData(); len = newlen; sz = 2; //type = new TypeSArray(Type::twchar, new IntegerExp(loc, len, Type::tindex)); type = new TypeDArray(Type::twchar->invariantOf()); committed = 1; break; case 'c': committed = 1; default: //type = new TypeSArray(Type::tchar, new IntegerExp(loc, len, Type::tindex)); type = new TypeDArray(Type::tchar->invariantOf()); break; } type = type->semantic(loc, sc); //type = type->invariantOf(); //printf("type = %s\n", type->toChars()); } return this; } /********************************** * Return length of string. */ size_t StringExp::length() { size_t result = 0; dchar_t c; const char *p; switch (sz) { case 1: for (size_t u = 0; u < len;) { p = utf_decodeChar((unsigned char *)string, len, &u, &c); if (p) { error("%s", p); break; } else result++; } break; case 2: for (size_t u = 0; u < len;) { p = utf_decodeWchar((unsigned short *)string, len, &u, &c); if (p) { error("%s", p); break; } else result++; } break; case 4: result = len; break; default: assert(0); } return result; } /**************************************** * Convert string to char[]. */ StringExp *StringExp::toUTF8(Scope *sc) { if (sz != 1) { // Convert to UTF-8 string committed = 0; Expression *e = castTo(sc, Type::tchar->arrayOf()); e = e->optimize(WANTvalue); assert(e->op == TOKstring); StringExp *se = (StringExp *)e; assert(se->sz == 1); return se; } return this; } int StringExp::compare(Object *obj) { // Used to sort case statement expressions so we can do an efficient lookup StringExp *se2 = (StringExp *)(obj); // This is a kludge so isExpression() in template.c will return 5 // for StringExp's. if (!se2) return 5; assert(se2->op == TOKstring); int len1 = len; int len2 = se2->len; if (len1 == len2) { switch (sz) { case 1: return strcmp((char *)string, (char *)se2->string); case 2: { unsigned u; d_wchar *s1 = (d_wchar *)string; d_wchar *s2 = (d_wchar *)se2->string; for (u = 0; u < len; u++) { if (s1[u] != s2[u]) return s1[u] - s2[u]; } } case 4: { unsigned u; d_dchar *s1 = (d_dchar *)string; d_dchar *s2 = (d_dchar *)se2->string; for (u = 0; u < len; u++) { if (s1[u] != s2[u]) return s1[u] - s2[u]; } } break; default: assert(0); } } return len1 - len2; } int StringExp::isBool(int result) { return result ? TRUE : FALSE; } unsigned StringExp::charAt(size_t i) { unsigned value; switch (sz) { case 1: value = ((unsigned char *)string)[i]; break; case 2: value = ((unsigned short *)string)[i]; break; case 4: value = ((unsigned int *)string)[i]; break; default: assert(0); break; } return value; } void StringExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { buf->writeByte('"'); for (size_t i = 0; i < len; i++) { unsigned c = charAt(i); switch (c) { case '"': case '\\': if (!hgs->console) buf->writeByte('\\'); default: if (c <= 0xFF) { if (c <= 0x7F && (isprint(c) || hgs->console)) buf->writeByte(c); else buf->printf("\\x%02x", c); } else if (c <= 0xFFFF) buf->printf("\\x%02x\\x%02x", c & 0xFF, c >> 8); else buf->printf("\\x%02x\\x%02x\\x%02x\\x%02x", c & 0xFF, (c >> 8) & 0xFF, (c >> 16) & 0xFF, c >> 24); break; } } buf->writeByte('"'); if (postfix) buf->writeByte(postfix); } void StringExp::toMangleBuffer(OutBuffer *buf) { char m; OutBuffer tmp; const char *p; unsigned c; size_t u; unsigned char *q; unsigned qlen; /* Write string in UTF-8 format */ switch (sz) { case 1: m = 'a'; q = (unsigned char *)string; qlen = len; break; case 2: m = 'w'; for (u = 0; u < len; ) { p = utf_decodeWchar((unsigned short *)string, len, &u, &c); if (p) error("%s", p); else tmp.writeUTF8(c); } q = tmp.data; qlen = tmp.offset; break; case 4: m = 'd'; for (u = 0; u < len; u++) { c = ((unsigned *)string)[u]; if (!utf_isValidDchar(c)) error("invalid UCS-32 char \\U%08x", c); else tmp.writeUTF8(c); } q = tmp.data; qlen = tmp.offset; break; default: assert(0); } buf->writeByte(m); buf->printf("%d_", qlen); for (size_t i = 0; i < qlen; i++) buf->printf("%02x", q[i]); } /************************ ArrayLiteralExp ************************************/ // [ e1, e2, e3, ... ] ArrayLiteralExp::ArrayLiteralExp(Loc loc, Expressions *elements) : Expression(loc, TOKarrayliteral, sizeof(ArrayLiteralExp)) { this->elements = elements; } ArrayLiteralExp::ArrayLiteralExp(Loc loc, Expression *e) : Expression(loc, TOKarrayliteral, sizeof(ArrayLiteralExp)) { elements = new Expressions; elements->push(e); } Expression *ArrayLiteralExp::syntaxCopy() { return new ArrayLiteralExp(loc, arraySyntaxCopy(elements)); } Expression *ArrayLiteralExp::semantic(Scope *sc) { Expression *e; Type *t0 = NULL; #if LOGSEMANTIC printf("ArrayLiteralExp::semantic('%s')\n", toChars()); #endif if (type) return this; // Run semantic() on each element for (int i = 0; i < elements->dim; i++) { e = (Expression *)elements->data[i]; e = e->semantic(sc); assert(e->type); elements->data[i] = (void *)e; } expandTuples(elements); for (int i = 0; i < elements->dim; i++) { e = (Expression *)elements->data[i]; if (!e->type) error("%s has no value", e->toChars()); e = resolveProperties(sc, e); unsigned char committed = 1; if (e->op == TOKstring) committed = ((StringExp *)e)->committed; if (!t0) { t0 = e->type; // Convert any static arrays to dynamic arrays if (t0->ty == Tsarray) { t0 = ((TypeSArray *)t0)->next->arrayOf(); e = e->implicitCastTo(sc, t0); } } else e = e->implicitCastTo(sc, t0); if (!committed && e->op == TOKstring) { StringExp *se = (StringExp *)e; se->committed = 0; } elements->data[i] = (void *)e; } if (!t0) t0 = Type::tvoid; type = new TypeSArray(t0, new IntegerExp(elements->dim)); type = type->semantic(loc, sc); return this; } int ArrayLiteralExp::checkSideEffect(int flag) { int f = 0; for (size_t i = 0; i < elements->dim; i++) { Expression *e = (Expression *)elements->data[i]; f |= e->checkSideEffect(2); } if (flag == 0 && f == 0) Expression::checkSideEffect(0); return f; } int ArrayLiteralExp::isBool(int result) { size_t dim = elements ? elements->dim : 0; return result ? (dim != 0) : (dim == 0); } #if DMDV2 int ArrayLiteralExp::canThrow() { return 1; // because it can fail allocating memory } #endif void ArrayLiteralExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { buf->writeByte('['); argsToCBuffer(buf, elements, hgs); buf->writeByte(']'); } void ArrayLiteralExp::toMangleBuffer(OutBuffer *buf) { size_t dim = elements ? elements->dim : 0; buf->printf("A%u", dim); for (size_t i = 0; i < dim; i++) { Expression *e = (Expression *)elements->data[i]; e->toMangleBuffer(buf); } } /************************ AssocArrayLiteralExp ************************************/ // [ key0 : value0, key1 : value1, ... ] AssocArrayLiteralExp::AssocArrayLiteralExp(Loc loc, Expressions *keys, Expressions *values) : Expression(loc, TOKassocarrayliteral, sizeof(AssocArrayLiteralExp)) { assert(keys->dim == values->dim); this->keys = keys; this->values = values; } Expression *AssocArrayLiteralExp::syntaxCopy() { return new AssocArrayLiteralExp(loc, arraySyntaxCopy(keys), arraySyntaxCopy(values)); } Expression *AssocArrayLiteralExp::semantic(Scope *sc) { Expression *e; Type *tkey = NULL; Type *tvalue = NULL; #if LOGSEMANTIC printf("AssocArrayLiteralExp::semantic('%s')\n", toChars()); #endif // Run semantic() on each element for (size_t i = 0; i < keys->dim; i++) { Expression *key = (Expression *)keys->data[i]; Expression *value = (Expression *)values->data[i]; key = key->semantic(sc); value = value->semantic(sc); keys->data[i] = (void *)key; values->data[i] = (void *)value; } expandTuples(keys); expandTuples(values); if (keys->dim != values->dim) { error("number of keys is %u, must match number of values %u", keys->dim, values->dim); keys->setDim(0); values->setDim(0); } for (size_t i = 0; i < keys->dim; i++) { Expression *key = (Expression *)keys->data[i]; Expression *value = (Expression *)values->data[i]; if (!key->type) error("%s has no value", key->toChars()); if (!value->type) error("%s has no value", value->toChars()); key = resolveProperties(sc, key); value = resolveProperties(sc, value); if (!tkey) tkey = key->type; else key = key->implicitCastTo(sc, tkey); keys->data[i] = (void *)key; if (!tvalue) tvalue = value->type; else value = value->implicitCastTo(sc, tvalue); values->data[i] = (void *)value; } if (!tkey) tkey = Type::tvoid; if (!tvalue) tvalue = Type::tvoid; type = new TypeAArray(tvalue, tkey); type = type->semantic(loc, sc); return this; } int AssocArrayLiteralExp::checkSideEffect(int flag) { int f = 0; for (size_t i = 0; i < keys->dim; i++) { Expression *key = (Expression *)keys->data[i]; Expression *value = (Expression *)values->data[i]; f |= key->checkSideEffect(2); f |= value->checkSideEffect(2); } if (flag == 0 && f == 0) Expression::checkSideEffect(0); return f; } int AssocArrayLiteralExp::isBool(int result) { size_t dim = keys->dim; return result ? (dim != 0) : (dim == 0); } #if DMDV2 int AssocArrayLiteralExp::canThrow() { return 1; } #endif void AssocArrayLiteralExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { buf->writeByte('['); for (size_t i = 0; i < keys->dim; i++) { Expression *key = (Expression *)keys->data[i]; Expression *value = (Expression *)values->data[i]; if (i) buf->writeByte(','); expToCBuffer(buf, hgs, key, PREC_assign); buf->writeByte(':'); expToCBuffer(buf, hgs, value, PREC_assign); } buf->writeByte(']'); } void AssocArrayLiteralExp::toMangleBuffer(OutBuffer *buf) { size_t dim = keys->dim; buf->printf("A%u", dim); for (size_t i = 0; i < dim; i++) { Expression *key = (Expression *)keys->data[i]; Expression *value = (Expression *)values->data[i]; key->toMangleBuffer(buf); value->toMangleBuffer(buf); } } /************************ StructLiteralExp ************************************/ // sd( e1, e2, e3, ... ) StructLiteralExp::StructLiteralExp(Loc loc, StructDeclaration *sd, Expressions *elements) : Expression(loc, TOKstructliteral, sizeof(StructLiteralExp)) { this->sd = sd; this->elements = elements; this->sym = NULL; this->soffset = 0; this->fillHoles = 1; } Expression *StructLiteralExp::syntaxCopy() { return new StructLiteralExp(loc, sd, arraySyntaxCopy(elements)); } Expression *StructLiteralExp::semantic(Scope *sc) { Expression *e; int nfields = sd->fields.dim - sd->isnested; #if LOGSEMANTIC printf("StructLiteralExp::semantic('%s')\n", toChars()); #endif if (type) return this; // Run semantic() on each element for (size_t i = 0; i < elements->dim; i++) { e = (Expression *)elements->data[i]; if (!e) continue; e = e->semantic(sc); elements->data[i] = (void *)e; } expandTuples(elements); size_t offset = 0; for (size_t i = 0; i < elements->dim; i++) { e = (Expression *)elements->data[i]; if (!e) continue; if (!e->type) error("%s has no value", e->toChars()); e = resolveProperties(sc, e); if (i >= nfields) { error("more initializers than fields of %s", sd->toChars()); break; } Dsymbol *s = (Dsymbol *)sd->fields.data[i]; VarDeclaration *v = s->isVarDeclaration(); assert(v); if (v->offset < offset) error("overlapping initialization for %s", v->toChars()); offset = v->offset + v->type->size(); Type *telem = v->type; while (!e->implicitConvTo(telem) && telem->toBasetype()->ty == Tsarray) { /* Static array initialization, as in: * T[3][5] = e; */ telem = telem->toBasetype()->nextOf(); } e = e->implicitCastTo(sc, telem); elements->data[i] = (void *)e; } /* Fill out remainder of elements[] with default initializers for fields[] */ for (size_t i = elements->dim; i < nfields; i++) { Dsymbol *s = (Dsymbol *)sd->fields.data[i]; VarDeclaration *v = s->isVarDeclaration(); assert(v); assert(!v->isThisDeclaration()); if (v->offset < offset) { e = NULL; sd->hasUnions = 1; } else { if (v->init) { e = v->init->toExpression(); if (!e) error("cannot make expression out of initializer for %s", v->toChars()); } else { e = v->type->defaultInit(); e->loc = loc; } offset = v->offset + v->type->size(); } elements->push(e); } type = sd->type; return this; } /************************************** * Gets expression at offset of type. * Returns NULL if not found. */ Expression *StructLiteralExp::getField(Type *type, unsigned offset) { //printf("StructLiteralExp::getField(this = %s, type = %s, offset = %u)\n", // /*toChars()*/"", type->toChars(), offset); Expression *e = NULL; int i = getFieldIndex(type, offset); if (i != -1) { //printf("\ti = %d\n", i); assert(i < elements->dim); e = (Expression *)elements->data[i]; if (e) { e = e->copy(); e->type = type; } } return e; } /************************************ * Get index of field. * Returns -1 if not found. */ int StructLiteralExp::getFieldIndex(Type *type, unsigned offset) { /* Find which field offset is by looking at the field offsets */ if (elements->dim) { for (size_t i = 0; i < sd->fields.dim; i++) { Dsymbol *s = (Dsymbol *)sd->fields.data[i]; VarDeclaration *v = s->isVarDeclaration(); assert(v); if (offset == v->offset && type->size() == v->type->size()) { Expression *e = (Expression *)elements->data[i]; if (e) { return i; } break; } } } return -1; } #if DMDV2 int StructLiteralExp::isLvalue() { return 1; } #endif Expression *StructLiteralExp::toLvalue(Scope *sc, Expression *e) { return this; } int StructLiteralExp::checkSideEffect(int flag) { int f = 0; for (size_t i = 0; i < elements->dim; i++) { Expression *e = (Expression *)elements->data[i]; if (!e) continue; f |= e->checkSideEffect(2); } if (flag == 0 && f == 0) Expression::checkSideEffect(0); return f; } #if DMDV2 int StructLiteralExp::canThrow() { return arrayExpressionCanThrow(elements); } #endif void StructLiteralExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { buf->writestring(sd->toChars()); buf->writeByte('('); argsToCBuffer(buf, elements, hgs); buf->writeByte(')'); } void StructLiteralExp::toMangleBuffer(OutBuffer *buf) { size_t dim = elements ? elements->dim : 0; buf->printf("S%u", dim); for (size_t i = 0; i < dim; i++) { Expression *e = (Expression *)elements->data[i]; if (e) e->toMangleBuffer(buf); else buf->writeByte('v'); // 'v' for void } } /************************ TypeDotIdExp ************************************/ /* Things like: * int.size * foo.size * (foo).size * cast(foo).size */ Expression *typeDotIdExp(Loc loc, Type *type, Identifier *ident) { return new DotIdExp(loc, new TypeExp(loc, type), ident); } /************************************************************/ // Mainly just a placeholder TypeExp::TypeExp(Loc loc, Type *type) : Expression(loc, TOKtype, sizeof(TypeExp)) { //printf("TypeExp::TypeExp(%s)\n", type->toChars()); this->type = type; } Expression *TypeExp::syntaxCopy() { //printf("TypeExp::syntaxCopy()\n"); return new TypeExp(loc, type->syntaxCopy()); } Expression *TypeExp::semantic(Scope *sc) { //printf("TypeExp::semantic(%s)\n", type->toChars()); type = type->semantic(loc, sc); return this; } void TypeExp::rvalue() { error("type %s has no value", toChars()); } void TypeExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { type->toCBuffer(buf, NULL, hgs); } /************************************************************/ // Mainly just a placeholder ScopeExp::ScopeExp(Loc loc, ScopeDsymbol *pkg) : Expression(loc, TOKimport, sizeof(ScopeExp)) { //printf("ScopeExp::ScopeExp(pkg = '%s')\n", pkg->toChars()); //static int count; if (++count == 38) *(char*)0=0; this->sds = pkg; } Expression *ScopeExp::syntaxCopy() { ScopeExp *se = new ScopeExp(loc, (ScopeDsymbol *)sds->syntaxCopy(NULL)); return se; } Expression *ScopeExp::semantic(Scope *sc) { TemplateInstance *ti; ScopeDsymbol *sds2; #if LOGSEMANTIC printf("+ScopeExp::semantic('%s')\n", toChars()); #endif Lagain: ti = sds->isTemplateInstance(); if (ti && !global.errors) { Dsymbol *s; if (!ti->semanticRun) ti->semantic(sc); s = ti->inst->toAlias(); sds2 = s->isScopeDsymbol(); if (!sds2) { Expression *e; //printf("s = %s, '%s'\n", s->kind(), s->toChars()); if (ti->withsym) { // Same as wthis.s e = new VarExp(loc, ti->withsym->withstate->wthis); e = new DotVarExp(loc, e, s->isDeclaration()); } else e = new DsymbolExp(loc, s); e = e->semantic(sc); //printf("-1ScopeExp::semantic()\n"); return e; } if (sds2 != sds) { sds = sds2; goto Lagain; } //printf("sds = %s, '%s'\n", sds->kind(), sds->toChars()); } else { //printf("sds = %s, '%s'\n", sds->kind(), sds->toChars()); //printf("\tparent = '%s'\n", sds->parent->toChars()); sds->semantic(sc); } type = Type::tvoid; //printf("-2ScopeExp::semantic() %s\n", toChars()); return this; } void ScopeExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { if (sds->isTemplateInstance()) { sds->toCBuffer(buf, hgs); } else { buf->writestring(sds->kind()); buf->writestring(" "); buf->writestring(sds->toChars()); } } /********************** TemplateExp **************************************/ // Mainly just a placeholder TemplateExp::TemplateExp(Loc loc, TemplateDeclaration *td) : Expression(loc, TOKtemplate, sizeof(TemplateExp)) { //printf("TemplateExp(): %s\n", td->toChars()); this->td = td; } void TemplateExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { buf->writestring(td->toChars()); } void TemplateExp::rvalue() { error("template %s has no value", toChars()); } /********************** NewExp **************************************/ /* thisexp.new(newargs) newtype(arguments) */ NewExp::NewExp(Loc loc, Expression *thisexp, Expressions *newargs, Type *newtype, Expressions *arguments) : Expression(loc, TOKnew, sizeof(NewExp)) { this->thisexp = thisexp; this->newargs = newargs; this->newtype = newtype; this->arguments = arguments; member = NULL; allocator = NULL; onstack = 0; } Expression *NewExp::syntaxCopy() { return new NewExp(loc, thisexp ? thisexp->syntaxCopy() : NULL, arraySyntaxCopy(newargs), newtype->syntaxCopy(), arraySyntaxCopy(arguments)); } Expression *NewExp::semantic(Scope *sc) { int i; Type *tb; ClassDeclaration *cdthis = NULL; #if LOGSEMANTIC printf("NewExp::semantic() %s\n", toChars()); if (thisexp) printf("\tthisexp = %s\n", thisexp->toChars()); printf("\tnewtype: %s\n", newtype->toChars()); #endif if (type) // if semantic() already run return this; Lagain: if (thisexp) { thisexp = thisexp->semantic(sc); cdthis = thisexp->type->isClassHandle(); if (cdthis) { sc = sc->push(cdthis); type = newtype->semantic(loc, sc); sc = sc->pop(); } else { error("'this' for nested class must be a class type, not %s", thisexp->type->toChars()); type = newtype->semantic(loc, sc); } } else type = newtype->semantic(loc, sc); newtype = type; // in case type gets cast to something else tb = type->toBasetype(); //printf("tb: %s, deco = %s\n", tb->toChars(), tb->deco); arrayExpressionSemantic(newargs, sc); preFunctionArguments(loc, sc, newargs); arrayExpressionSemantic(arguments, sc); preFunctionArguments(loc, sc, arguments); if (thisexp && tb->ty != Tclass) error("e.new is only for allocating nested classes, not %s", tb->toChars()); if (tb->ty == Tclass) { TypeFunction *tf; TypeClass *tc = (TypeClass *)(tb); ClassDeclaration *cd = tc->sym->isClassDeclaration(); if (cd->isInterfaceDeclaration()) error("cannot create instance of interface %s", cd->toChars()); else if (cd->isAbstract()) { error("cannot create instance of abstract class %s", cd->toChars()); for (int i = 0; i < cd->vtbl.dim; i++) { FuncDeclaration *fd = ((Dsymbol *)cd->vtbl.data[i])->isFuncDeclaration(); if (fd && fd->isAbstract()) error("function %s is abstract", fd->toChars()); } } checkDeprecated(sc, cd); if (cd->isNested()) { /* We need a 'this' pointer for the nested class. * Ensure we have the right one. */ Dsymbol *s = cd->toParent2(); ClassDeclaration *cdn = s->isClassDeclaration(); FuncDeclaration *fdn = s->isFuncDeclaration(); //printf("cd isNested, cdn = %s\n", cdn ? cdn->toChars() : "null"); if (cdn) { if (!cdthis) { // Supply an implicit 'this' and try again thisexp = new ThisExp(loc); for (Dsymbol *sp = sc->parent; 1; sp = sp->parent) { if (!sp) { error("outer class %s 'this' needed to 'new' nested class %s", cdn->toChars(), cd->toChars()); break; } ClassDeclaration *cdp = sp->isClassDeclaration(); if (!cdp) continue; if (cdp == cdn || cdn->isBaseOf(cdp, NULL)) break; // Add a '.outer' and try again thisexp = new DotIdExp(loc, thisexp, Id::outer); } if (!global.errors) goto Lagain; } if (cdthis) { //printf("cdthis = %s\n", cdthis->toChars()); if (cdthis != cdn && !cdn->isBaseOf(cdthis, NULL)) error("'this' for nested class must be of type %s, not %s", cdn->toChars(), thisexp->type->toChars()); } #if 0 else { for (Dsymbol *sf = sc->func; 1; sf= sf->toParent2()->isFuncDeclaration()) { if (!sf) { error("outer class %s 'this' needed to 'new' nested class %s", cdn->toChars(), cd->toChars()); break; } printf("sf = %s\n", sf->toChars()); AggregateDeclaration *ad = sf->isThis(); if (ad && (ad == cdn || cdn->isBaseOf(ad->isClassDeclaration(), NULL))) break; } } #endif } #if 1 else if (thisexp) error("e.new is only for allocating nested classes"); else if (fdn) { // make sure the parent context fdn of cd is reachable from sc for (Dsymbol *sp = sc->parent; 1; sp = sp->parent) { if (fdn == sp) break; FuncDeclaration *fsp = sp ? sp->isFuncDeclaration() : NULL; if (!sp || (fsp && fsp->isStatic())) { error("outer function context of %s is needed to 'new' nested class %s", fdn->toPrettyChars(), cd->toPrettyChars()); break; } } } #else else if (fdn) { /* The nested class cd is nested inside a function, * we'll let getEthis() look for errors. */ //printf("nested class %s is nested inside function %s, we're in %s\n", cd->toChars(), fdn->toChars(), sc->func->toChars()); if (thisexp) // Because thisexp cannot be a function frame pointer error("e.new is only for allocating nested classes"); } #endif else assert(0); } else if (thisexp) error("e.new is only for allocating nested classes"); FuncDeclaration *f = NULL; if (cd->ctor) f = resolveFuncCall(sc, loc, cd->ctor, NULL, NULL, arguments, 0); if (f) { checkDeprecated(sc, f); member = f->isCtorDeclaration(); assert(member); cd->accessCheck(loc, sc, member); tf = (TypeFunction *)f->type; if (!arguments) arguments = new Expressions(); functionArguments(loc, sc, tf, arguments); } else { if (arguments && arguments->dim) error("no constructor for %s", cd->toChars()); } if (cd->aggNew) { // Prepend the size argument to newargs[] Expression *e = new IntegerExp(loc, cd->size(loc), Type::tsize_t); if (!newargs) newargs = new Expressions(); newargs->shift(e); f = cd->aggNew->overloadResolve(loc, NULL, newargs); allocator = f->isNewDeclaration(); assert(allocator); tf = (TypeFunction *)f->type; functionArguments(loc, sc, tf, newargs); } else { if (newargs && newargs->dim) error("no allocator for %s", cd->toChars()); } } else if (tb->ty == Tstruct) { TypeStruct *ts = (TypeStruct *)tb; StructDeclaration *sd = ts->sym; TypeFunction *tf; FuncDeclaration *f = NULL; if (sd->ctor) f = resolveFuncCall(sc, loc, sd->ctor, NULL, NULL, arguments, 0); if (f) { checkDeprecated(sc, f); member = f->isCtorDeclaration(); assert(member); sd->accessCheck(loc, sc, member); tf = (TypeFunction *)f->type; // type = tf->next; if (!arguments) arguments = new Expressions(); functionArguments(loc, sc, tf, arguments); } else { if (arguments && arguments->dim) error("no constructor for %s", sd->toChars()); } if (sd->aggNew) { // Prepend the uint size argument to newargs[] Expression *e = new IntegerExp(loc, sd->size(loc), Type::tuns32); if (!newargs) newargs = new Expressions(); newargs->shift(e); f = sd->aggNew->overloadResolve(loc, NULL, newargs); allocator = f->isNewDeclaration(); assert(allocator); tf = (TypeFunction *)f->type; functionArguments(loc, sc, tf, newargs); #if 0 e = new VarExp(loc, f); e = new CallExp(loc, e, newargs); e = e->semantic(sc); e->type = type->pointerTo(); return e; #endif } else { if (newargs && newargs->dim) error("no allocator for %s", sd->toChars()); } type = type->pointerTo(); } else if (tb->ty == Tarray && (arguments && arguments->dim)) { for (size_t i = 0; i < arguments->dim; i++) { if (tb->ty != Tarray) { error("too many arguments for array"); arguments->dim = i; break; } Expression *arg = (Expression *)arguments->data[i]; arg = resolveProperties(sc, arg); arg = arg->implicitCastTo(sc, Type::tsize_t); arg = arg->optimize(WANTvalue); if (arg->op == TOKint64 && (long long)arg->toInteger() < 0) error("negative array index %s", arg->toChars()); arguments->data[i] = (void *) arg; tb = ((TypeDArray *)tb)->next->toBasetype(); } } else if (tb->isscalar()) { if (arguments && arguments->dim) error("no constructor for %s", type->toChars()); type = type->pointerTo(); } else { error("new can only create structs, dynamic arrays or class objects, not %s's", type->toChars()); type = type->pointerTo(); } //printf("NewExp: '%s'\n", toChars()); //printf("NewExp:type '%s'\n", type->toChars()); return this; } int NewExp::checkSideEffect(int flag) { return 1; } #if DMDV2 int NewExp::canThrow() { return 1; } #endif void NewExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { int i; if (thisexp) { expToCBuffer(buf, hgs, thisexp, PREC_primary); buf->writeByte('.'); } buf->writestring("new "); if (newargs && newargs->dim) { buf->writeByte('('); argsToCBuffer(buf, newargs, hgs); buf->writeByte(')'); } newtype->toCBuffer(buf, NULL, hgs); if (arguments && arguments->dim) { buf->writeByte('('); argsToCBuffer(buf, arguments, hgs); buf->writeByte(')'); } } /********************** NewAnonClassExp **************************************/ NewAnonClassExp::NewAnonClassExp(Loc loc, Expression *thisexp, Expressions *newargs, ClassDeclaration *cd, Expressions *arguments) : Expression(loc, TOKnewanonclass, sizeof(NewAnonClassExp)) { this->thisexp = thisexp; this->newargs = newargs; this->cd = cd; this->arguments = arguments; } Expression *NewAnonClassExp::syntaxCopy() { return new NewAnonClassExp(loc, thisexp ? thisexp->syntaxCopy() : NULL, arraySyntaxCopy(newargs), (ClassDeclaration *)cd->syntaxCopy(NULL), arraySyntaxCopy(arguments)); } Expression *NewAnonClassExp::semantic(Scope *sc) { #if LOGSEMANTIC printf("NewAnonClassExp::semantic() %s\n", toChars()); //printf("thisexp = %p\n", thisexp); //printf("type: %s\n", type->toChars()); #endif Expression *d = new DeclarationExp(loc, cd); d = d->semantic(sc); Expression *n = new NewExp(loc, thisexp, newargs, cd->type, arguments); Expression *c = new CommaExp(loc, d, n); return c->semantic(sc); } int NewAnonClassExp::checkSideEffect(int flag) { return 1; } #if DMDV2 int NewAnonClassExp::canThrow() { return 1; } #endif void NewAnonClassExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { int i; if (thisexp) { expToCBuffer(buf, hgs, thisexp, PREC_primary); buf->writeByte('.'); } buf->writestring("new"); if (newargs && newargs->dim) { buf->writeByte('('); argsToCBuffer(buf, newargs, hgs); buf->writeByte(')'); } buf->writestring(" class "); if (arguments && arguments->dim) { buf->writeByte('('); argsToCBuffer(buf, arguments, hgs); buf->writeByte(')'); } //buf->writestring(" { }"); if (cd) { cd->toCBuffer(buf, hgs); } } /********************** SymbolExp **************************************/ #if DMDV2 SymbolExp::SymbolExp(Loc loc, enum TOK op, int size, Declaration *var, int hasOverloads) : Expression(loc, op, size) { assert(var); this->var = var; this->hasOverloads = hasOverloads; } #endif /********************** SymOffExp **************************************/ SymOffExp::SymOffExp(Loc loc, Declaration *var, unsigned offset, int hasOverloads) : SymbolExp(loc, TOKsymoff, sizeof(SymOffExp), var, hasOverloads) { this->offset = offset; VarDeclaration *v = var->isVarDeclaration(); if (v && v->needThis()) error("need 'this' for address of %s", v->toChars()); } Expression *SymOffExp::semantic(Scope *sc) { #if LOGSEMANTIC printf("SymOffExp::semantic('%s')\n", toChars()); #endif //var->semantic(sc); if (!type) type = var->type->pointerTo(); VarDeclaration *v = var->isVarDeclaration(); if (v) v->checkNestedReference(sc, loc); return this; } int SymOffExp::isBool(int result) { return result ? TRUE : FALSE; } void SymOffExp::checkEscape() { VarDeclaration *v = var->isVarDeclaration(); if (v) { if (!v->isDataseg()) error("escaping reference to local variable %s", v->toChars()); } } void SymOffExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { if (offset) buf->printf("(& %s+%u)", var->toChars(), offset); else buf->printf("& %s", var->toChars()); } /******************************** VarExp **************************/ VarExp::VarExp(Loc loc, Declaration *var, int hasOverloads) : SymbolExp(loc, TOKvar, sizeof(VarExp), var, hasOverloads) { //printf("VarExp(this = %p, '%s', loc = %s)\n", this, var->toChars(), loc.toChars()); //if (strcmp(var->ident->toChars(), "func") == 0) halt(); this->type = var->type; } int VarExp::equals(Object *o) { VarExp *ne; if (this == o || (((Expression *)o)->op == TOKvar && ((ne = (VarExp *)o), type->toHeadMutable()->equals(ne->type->toHeadMutable())) && var == ne->var)) return 1; return 0; } Expression *VarExp::semantic(Scope *sc) { FuncLiteralDeclaration *fd; #if LOGSEMANTIC printf("VarExp::semantic(%s)\n", toChars()); #endif if (!type) { type = var->type; #if 0 if (var->storage_class & STClazy) { TypeFunction *tf = new TypeFunction(NULL, type, 0, LINKd); type = new TypeDelegate(tf); type = type->semantic(loc, sc); } #endif } /* Fix for 1161 doesn't work because it causes protection * problems when instantiating imported templates passing private * variables as alias template parameters. */ //accessCheck(loc, sc, NULL, var); VarDeclaration *v = var->isVarDeclaration(); if (v) { #if 0 if ((v->isConst() || v->isInvariant()) && type->toBasetype()->ty != Tsarray && v->init) { ExpInitializer *ei = v->init->isExpInitializer(); if (ei) { //ei->exp->implicitCastTo(sc, type)->print(); return ei->exp->implicitCastTo(sc, type); } } #endif v->checkNestedReference(sc, loc); #if DMDV2 #if 1 if (sc->func) { /* Determine if sc->func is pure or if any function that * encloses it is also pure. */ bool hasPureParent = false; for (FuncDeclaration *outerfunc = sc->func; outerfunc;) { if (outerfunc->isPure()) { hasPureParent = true; break; } Dsymbol *parent = outerfunc->toParent2(); if (!parent) break; outerfunc = parent->isFuncDeclaration(); } /* If ANY of its enclosing functions are pure, * it cannot do anything impure. * If it is pure, it cannot access any mutable variables other * than those inside itself */ if (hasPureParent && !sc->intypeof && v->isDataseg() && !v->isInvariant()) { error("pure function '%s' cannot access mutable static data '%s'", sc->func->toChars(), v->toChars()); } else if (sc->func->isPure() && sc->parent != v->parent && !sc->intypeof && !v->isInvariant() && !(v->storage_class & STCmanifest)) { error("pure nested function '%s' cannot access mutable data '%s'", sc->func->toChars(), v->toChars()); if (v->isEnumDeclaration()) error("enum"); } } #else if (sc->func && sc->func->isPure() && !sc->intypeof) { if (v->isDataseg() && !v->isInvariant()) error("pure function '%s' cannot access mutable static data '%s'", sc->func->toChars(), v->toChars()); } #endif #endif } #if 0 else if ((fd = var->isFuncLiteralDeclaration()) != NULL) { Expression *e; e = new FuncExp(loc, fd); e->type = type; return e; } #endif return this; } char *VarExp::toChars() { return var->toChars(); } void VarExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { buf->writestring(var->toChars()); } void VarExp::checkEscape() { VarDeclaration *v = var->isVarDeclaration(); if (v) { Type *tb = v->type->toBasetype(); // if reference type if (tb->ty == Tarray || tb->ty == Tsarray || tb->ty == Tclass) { if ((v->isAuto() || v->isScope()) && !v->noauto) error("escaping reference to scope local %s", v->toChars()); else if (v->storage_class & STCvariadic) error("escaping reference to variadic parameter %s", v->toChars()); } } } #if DMDV2 int VarExp::isLvalue() { if (var->storage_class & STClazy) return 0; return 1; } #endif Expression *VarExp::toLvalue(Scope *sc, Expression *e) { #if 0 tym = tybasic(e1->ET->Tty); if (!(tyscalar(tym) || tym == TYstruct || tym == TYarray && e->Eoper == TOKaddr)) synerr(EM_lvalue); // lvalue expected #endif if (var->storage_class & STClazy) error("lazy variables cannot be lvalues"); return this; } Expression *VarExp::modifiableLvalue(Scope *sc, Expression *e) { //printf("VarExp::modifiableLvalue('%s')\n", var->toChars()); if (type && type->toBasetype()->ty == Tsarray) error("cannot change reference to static array '%s'", var->toChars()); var->checkModify(loc, sc, type); // See if this expression is a modifiable lvalue (i.e. not const) return toLvalue(sc, e); } /******************************** OverExp **************************/ #if DMDV2 OverExp::OverExp(OverloadSet *s) : Expression(loc, TOKoverloadset, sizeof(OverExp)) { //printf("OverExp(this = %p, '%s')\n", this, var->toChars()); vars = s; type = Type::tvoid; } int OverExp::isLvalue() { return 1; } Expression *OverExp::toLvalue(Scope *sc, Expression *e) { return this; } #endif /******************************** TupleExp **************************/ TupleExp::TupleExp(Loc loc, Expressions *exps) : Expression(loc, TOKtuple, sizeof(TupleExp)) { //printf("TupleExp(this = %p)\n", this); this->exps = exps; this->type = NULL; } TupleExp::TupleExp(Loc loc, TupleDeclaration *tup) : Expression(loc, TOKtuple, sizeof(TupleExp)) { exps = new Expressions(); type = NULL; exps->reserve(tup->objects->dim); for (size_t i = 0; i < tup->objects->dim; i++) { Object *o = (Object *)tup->objects->data[i]; if (o->dyncast() == DYNCAST_EXPRESSION) { Expression *e = (Expression *)o; e = e->syntaxCopy(); exps->push(e); } else if (o->dyncast() == DYNCAST_DSYMBOL) { Dsymbol *s = (Dsymbol *)o; Expression *e = new DsymbolExp(loc, s); exps->push(e); } else if (o->dyncast() == DYNCAST_TYPE) { Type *t = (Type *)o; Expression *e = new TypeExp(loc, t); exps->push(e); } else { error("%s is not an expression", o->toChars()); } } } int TupleExp::equals(Object *o) { TupleExp *ne; if (this == o) return 1; if (((Expression *)o)->op == TOKtuple) { TupleExp *te = (TupleExp *)o; if (exps->dim != te->exps->dim) return 0; for (size_t i = 0; i < exps->dim; i++) { Expression *e1 = (Expression *)exps->data[i]; Expression *e2 = (Expression *)te->exps->data[i]; if (!e1->equals(e2)) return 0; } return 1; } return 0; } Expression *TupleExp::syntaxCopy() { return new TupleExp(loc, arraySyntaxCopy(exps)); } Expression *TupleExp::semantic(Scope *sc) { #if LOGSEMANTIC printf("+TupleExp::semantic(%s)\n", toChars()); #endif if (type) return this; // Run semantic() on each argument for (size_t i = 0; i < exps->dim; i++) { Expression *e = (Expression *)exps->data[i]; e = e->semantic(sc); if (!e->type) { error("%s has no value", e->toChars()); e->type = Type::terror; } exps->data[i] = (void *)e; } expandTuples(exps); if (0 && exps->dim == 1) { return (Expression *)exps->data[0]; } type = new TypeTuple(exps); type = type->semantic(loc, sc); //printf("-TupleExp::semantic(%s)\n", toChars()); return this; } void TupleExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { buf->writestring("tuple("); argsToCBuffer(buf, exps, hgs); buf->writeByte(')'); } int TupleExp::checkSideEffect(int flag) { int f = 0; for (int i = 0; i < exps->dim; i++) { Expression *e = (Expression *)exps->data[i]; f |= e->checkSideEffect(2); } if (flag == 0 && f == 0) Expression::checkSideEffect(0); return f; } #if DMDV2 int TupleExp::canThrow() { return arrayExpressionCanThrow(exps); } #endif void TupleExp::checkEscape() { for (size_t i = 0; i < exps->dim; i++) { Expression *e = (Expression *)exps->data[i]; e->checkEscape(); } } /******************************** FuncExp *********************************/ FuncExp::FuncExp(Loc loc, FuncLiteralDeclaration *fd) : Expression(loc, TOKfunction, sizeof(FuncExp)) { this->fd = fd; } Expression *FuncExp::syntaxCopy() { return new FuncExp(loc, (FuncLiteralDeclaration *)fd->syntaxCopy(NULL)); } Expression *FuncExp::semantic(Scope *sc) { #if LOGSEMANTIC printf("FuncExp::semantic(%s)\n", toChars()); #endif if (!type) { fd->semantic(sc); //fd->parent = sc->parent; if (global.errors) { } else { fd->semantic2(sc); if (!global.errors) { fd->semantic3(sc); if (!global.errors && global.params.useInline) fd->inlineScan(); } } // Type is a "delegate to" or "pointer to" the function literal if (fd->isNested()) { type = new TypeDelegate(fd->type); type = type->semantic(loc, sc); } else { type = fd->type->pointerTo(); } fd->tookAddressOf++; } return this; } char *FuncExp::toChars() { return fd->toChars(); } void FuncExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { fd->toCBuffer(buf, hgs); //buf->writestring(fd->toChars()); } /******************************** DeclarationExp **************************/ DeclarationExp::DeclarationExp(Loc loc, Dsymbol *declaration) : Expression(loc, TOKdeclaration, sizeof(DeclarationExp)) { this->declaration = declaration; } Expression *DeclarationExp::syntaxCopy() { return new DeclarationExp(loc, declaration->syntaxCopy(NULL)); } Expression *DeclarationExp::semantic(Scope *sc) { if (type) return this; #if LOGSEMANTIC printf("DeclarationExp::semantic() %s\n", toChars()); #endif /* This is here to support extern(linkage) declaration, * where the extern(linkage) winds up being an AttribDeclaration * wrapper. */ Dsymbol *s = declaration; AttribDeclaration *ad = declaration->isAttribDeclaration(); if (ad) { if (ad->decl && ad->decl->dim == 1) s = (Dsymbol *)ad->decl->data[0]; } if (s->isVarDeclaration()) { // Do semantic() on initializer first, so: // int a = a; // will be illegal. declaration->semantic(sc); s->parent = sc->parent; } //printf("inserting '%s' %p into sc = %p\n", s->toChars(), s, sc); // Insert into both local scope and function scope. // Must be unique in both. if (s->ident) { if (!sc->insert(s)) error("declaration %s is already defined", s->toPrettyChars()); else if (sc->func) { VarDeclaration *v = s->isVarDeclaration(); if (s->isFuncDeclaration() && !sc->func->localsymtab->insert(s)) error("declaration %s is already defined in another scope in %s", s->toPrettyChars(), sc->func->toChars()); else if (!global.params.useDeprecated) { // Disallow shadowing for (Scope *scx = sc->enclosing; scx && scx->func == sc->func; scx = scx->enclosing) { Dsymbol *s2; if (scx->scopesym && scx->scopesym->symtab && (s2 = scx->scopesym->symtab->lookup(s->ident)) != NULL && s != s2) { error("shadowing declaration %s is deprecated", s->toPrettyChars()); } } } } } if (!s->isVarDeclaration()) { declaration->semantic(sc); s->parent = sc->parent; } if (!global.errors) { declaration->semantic2(sc); if (!global.errors) { declaration->semantic3(sc); if (!global.errors && global.params.useInline) declaration->inlineScan(); } } type = Type::tvoid; return this; } int DeclarationExp::checkSideEffect(int flag) { return 1; } #if DMDV2 int DeclarationExp::canThrow() { VarDeclaration *v = declaration->isVarDeclaration(); if (v && v->init) { ExpInitializer *ie = v->init->isExpInitializer(); return ie && ie->exp->canThrow(); } return 0; } #endif void DeclarationExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { declaration->toCBuffer(buf, hgs); } /************************ TypeidExp ************************************/ /* * typeid(int) */ TypeidExp::TypeidExp(Loc loc, Type *typeidType) : Expression(loc, TOKtypeid, sizeof(TypeidExp)) { this->typeidType = typeidType; } Expression *TypeidExp::syntaxCopy() { return new TypeidExp(loc, typeidType->syntaxCopy()); } Expression *TypeidExp::semantic(Scope *sc) { Expression *e; #if LOGSEMANTIC printf("TypeidExp::semantic()\n"); #endif typeidType = typeidType->semantic(loc, sc); e = typeidType->getTypeInfo(sc); if (e->loc.linnum == 0) e->loc = loc; // so there's at least some line number info return e; } void TypeidExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { buf->writestring("typeid("); typeidType->toCBuffer(buf, NULL, hgs); buf->writeByte(')'); } /************************ TraitsExp ************************************/ #if DMDV2 /* * __traits(identifier, args...) */ TraitsExp::TraitsExp(Loc loc, Identifier *ident, Objects *args) : Expression(loc, TOKtraits, sizeof(TraitsExp)) { this->ident = ident; this->args = args; } Expression *TraitsExp::syntaxCopy() { return new TraitsExp(loc, ident, TemplateInstance::arraySyntaxCopy(args)); } void TraitsExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { buf->writestring("__traits("); buf->writestring(ident->toChars()); if (args) { for (int i = 0; i < args->dim; i++) { buf->writeByte(','); Object *oarg = (Object *)args->data[i]; ObjectToCBuffer(buf, hgs, oarg); } } buf->writeByte(')'); } #endif /************************************************************/ HaltExp::HaltExp(Loc loc) : Expression(loc, TOKhalt, sizeof(HaltExp)) { } Expression *HaltExp::semantic(Scope *sc) { #if LOGSEMANTIC printf("HaltExp::semantic()\n"); #endif type = Type::tvoid; return this; } int HaltExp::checkSideEffect(int flag) { return 1; } void HaltExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { buf->writestring("halt"); } /************************************************************/ IsExp::IsExp(Loc loc, Type *targ, Identifier *id, enum TOK tok, Type *tspec, enum TOK tok2, TemplateParameters *parameters) : Expression(loc, TOKis, sizeof(IsExp)) { this->targ = targ; this->id = id; this->tok = tok; this->tspec = tspec; this->tok2 = tok2; this->parameters = parameters; } Expression *IsExp::syntaxCopy() { // This section is identical to that in TemplateDeclaration::syntaxCopy() TemplateParameters *p = NULL; if (parameters) { p = new TemplateParameters(); p->setDim(parameters->dim); for (int i = 0; i < p->dim; i++) { TemplateParameter *tp = (TemplateParameter *)parameters->data[i]; p->data[i] = (void *)tp->syntaxCopy(); } } return new IsExp(loc, targ->syntaxCopy(), id, tok, tspec ? tspec->syntaxCopy() : NULL, tok2, p); } Expression *IsExp::semantic(Scope *sc) { Type *tded; /* is(targ id tok tspec) * is(targ id == tok2) */ //printf("IsExp::semantic(%s)\n", toChars()); if (id && !(sc->flags & SCOPEstaticif)) error("can only declare type aliases within static if conditionals"); Type *t = targ->trySemantic(loc, sc); if (!t) goto Lno; // errors, so condition is false targ = t; if (tok2 != TOKreserved) { switch (tok2) { case TOKtypedef: if (targ->ty != Ttypedef) goto Lno; tded = ((TypeTypedef *)targ)->sym->basetype; break; case TOKstruct: if (targ->ty != Tstruct) goto Lno; if (((TypeStruct *)targ)->sym->isUnionDeclaration()) goto Lno; tded = targ; break; case TOKunion: if (targ->ty != Tstruct) goto Lno; if (!((TypeStruct *)targ)->sym->isUnionDeclaration()) goto Lno; tded = targ; break; case TOKclass: if (targ->ty != Tclass) goto Lno; if (((TypeClass *)targ)->sym->isInterfaceDeclaration()) goto Lno; tded = targ; break; case TOKinterface: if (targ->ty != Tclass) goto Lno; if (!((TypeClass *)targ)->sym->isInterfaceDeclaration()) goto Lno; tded = targ; break; #if DMDV2 case TOKconst: if (!targ->isConst()) goto Lno; tded = targ; break; case TOKinvariant: case TOKimmutable: if (!targ->isInvariant()) goto Lno; tded = targ; break; #endif case TOKsuper: // If class or interface, get the base class and interfaces if (targ->ty != Tclass) goto Lno; else { ClassDeclaration *cd = ((TypeClass *)targ)->sym; Arguments *args = new Arguments; args->reserve(cd->baseclasses.dim); for (size_t i = 0; i < cd->baseclasses.dim; i++) { BaseClass *b = (BaseClass *)cd->baseclasses.data[i]; args->push(new Argument(STCin, b->type, NULL, NULL)); } tded = new TypeTuple(args); } break; case TOKenum: if (targ->ty != Tenum) goto Lno; tded = ((TypeEnum *)targ)->sym->memtype; break; case TOKdelegate: if (targ->ty != Tdelegate) goto Lno; tded = ((TypeDelegate *)targ)->next; // the underlying function type break; case TOKfunction: { if (targ->ty != Tfunction) goto Lno; tded = targ; /* Generate tuple from function parameter types. */ assert(tded->ty == Tfunction); Arguments *params = ((TypeFunction *)tded)->parameters; size_t dim = Argument::dim(params); Arguments *args = new Arguments; args->reserve(dim); for (size_t i = 0; i < dim; i++) { Argument *arg = Argument::getNth(params, i); assert(arg && arg->type); args->push(new Argument(arg->storageClass, arg->type, NULL, NULL)); } tded = new TypeTuple(args); break; } case TOKreturn: /* Get the 'return type' for the function, * delegate, or pointer to function. */ if (targ->ty == Tfunction) tded = ((TypeFunction *)targ)->next; else if (targ->ty == Tdelegate) { tded = ((TypeDelegate *)targ)->next; tded = ((TypeFunction *)tded)->next; } else if (targ->ty == Tpointer && ((TypePointer *)targ)->next->ty == Tfunction) { tded = ((TypePointer *)targ)->next; tded = ((TypeFunction *)tded)->next; } else goto Lno; break; default: assert(0); } goto Lyes; } else if (id && tspec) { /* Evaluate to TRUE if targ matches tspec. * If TRUE, declare id as an alias for the specialized type. */ MATCH m; assert(parameters && parameters->dim); Objects dedtypes; dedtypes.setDim(parameters->dim); dedtypes.zero(); m = targ->deduceType(NULL, tspec, parameters, &dedtypes); if (m == MATCHnomatch || (m != MATCHexact && tok == TOKequal)) { goto Lno; } else { tded = (Type *)dedtypes.data[0]; if (!tded) tded = targ; Objects tiargs; tiargs.setDim(1); tiargs.data[0] = (void *)targ; /* Declare trailing parameters */ for (int i = 1; i < parameters->dim; i++) { TemplateParameter *tp = (TemplateParameter *)parameters->data[i]; Declaration *s = NULL; m = tp->matchArg(sc, &tiargs, i, parameters, &dedtypes, &s); if (m == MATCHnomatch) goto Lno; s->semantic(sc); if (!sc->insert(s)) error("declaration %s is already defined", s->toChars()); #if 0 Object *o = (Object *)dedtypes.data[i]; Dsymbol *s = TemplateDeclaration::declareParameter(loc, sc, tp, o); #endif if (sc->sd) s->addMember(sc, sc->sd, 1); } goto Lyes; } } else if (id) { /* Declare id as an alias for type targ. Evaluate to TRUE */ tded = targ; goto Lyes; } else if (tspec) { /* Evaluate to TRUE if targ matches tspec * is(targ == tspec) * is(targ : tspec) */ tspec = tspec->semantic(loc, sc); //printf("targ = %s\n", targ->toChars()); //printf("tspec = %s\n", tspec->toChars()); if (tok == TOKcolon) { if (targ->implicitConvTo(tspec)) goto Lyes; else goto Lno; } else /* == */ { if (targ->equals(tspec)) goto Lyes; else goto Lno; } } Lyes: if (id) { Dsymbol *s = new AliasDeclaration(loc, id, tded); s->semantic(sc); if (!sc->insert(s)) error("declaration %s is already defined", s->toChars()); if (sc->sd) s->addMember(sc, sc->sd, 1); } //printf("Lyes\n"); return new IntegerExp(loc, 1, Type::tbool); Lno: //printf("Lno\n"); return new IntegerExp(loc, 0, Type::tbool); } void IsExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { buf->writestring("is("); targ->toCBuffer(buf, id, hgs); if (tok2 != TOKreserved) { buf->printf(" %s %s", Token::toChars(tok), Token::toChars(tok2)); } else if (tspec) { if (tok == TOKcolon) buf->writestring(" : "); else buf->writestring(" == "); tspec->toCBuffer(buf, NULL, hgs); } #if DMDV2 if (parameters) { // First parameter is already output, so start with second for (int i = 1; i < parameters->dim; i++) { buf->writeByte(','); TemplateParameter *tp = (TemplateParameter *)parameters->data[i]; tp->toCBuffer(buf, hgs); } } #endif buf->writeByte(')'); } /************************************************************/ UnaExp::UnaExp(Loc loc, enum TOK op, int size, Expression *e1) : Expression(loc, op, size) { this->e1 = e1; } Expression *UnaExp::syntaxCopy() { UnaExp *e; e = (UnaExp *)copy(); e->type = NULL; e->e1 = e->e1->syntaxCopy(); return e; } Expression *UnaExp::semantic(Scope *sc) { #if LOGSEMANTIC printf("UnaExp::semantic('%s')\n", toChars()); #endif e1 = e1->semantic(sc); // if (!e1->type) // error("%s has no value", e1->toChars()); return this; } #if DMDV2 int UnaExp::canThrow() { return e1->canThrow(); } #endif void UnaExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { buf->writestring(Token::toChars(op)); expToCBuffer(buf, hgs, e1, precedence[op]); } /************************************************************/ BinExp::BinExp(Loc loc, enum TOK op, int size, Expression *e1, Expression *e2) : Expression(loc, op, size) { this->e1 = e1; this->e2 = e2; } Expression *BinExp::syntaxCopy() { BinExp *e; e = (BinExp *)copy(); e->type = NULL; e->e1 = e->e1->syntaxCopy(); e->e2 = e->e2->syntaxCopy(); return e; } Expression *BinExp::semantic(Scope *sc) { #if LOGSEMANTIC printf("BinExp::semantic('%s')\n", toChars()); #endif e1 = e1->semantic(sc); if (!e1->type && !(op == TOKassign && e1->op == TOKdottd)) // a.template = e2 { error("%s has no value", e1->toChars()); e1->type = Type::terror; } e2 = e2->semantic(sc); if (!e2->type) { error("%s has no value", e2->toChars()); e2->type = Type::terror; } return this; } Expression *BinExp::semanticp(Scope *sc) { BinExp::semantic(sc); e1 = resolveProperties(sc, e1); e2 = resolveProperties(sc, e2); return this; } /*************************** * Common semantic routine for some xxxAssignExp's. */ Expression *BinExp::commonSemanticAssign(Scope *sc) { Expression *e; if (!type) { BinExp::semantic(sc); e2 = resolveProperties(sc, e2); e = op_overload(sc); if (e) return e; if (e1->op == TOKslice) { // T[] op= ... typeCombine(sc); type = e1->type; return arrayOp(sc); } e1 = e1->modifiableLvalue(sc, e1); e1->checkScalar(); type = e1->type; if (type->toBasetype()->ty == Tbool) { error("operator not allowed on bool expression %s", toChars()); } typeCombine(sc); e1->checkArithmetic(); e2->checkArithmetic(); if (op == TOKmodass && e2->type->iscomplex()) { error("cannot perform modulo complex arithmetic"); return new ErrorExp(); } } return this; } Expression *BinExp::commonSemanticAssignIntegral(Scope *sc) { Expression *e; if (!type) { BinExp::semantic(sc); e2 = resolveProperties(sc, e2); e = op_overload(sc); if (e) return e; if (e1->op == TOKslice) { // T[] op= ... typeCombine(sc); type = e1->type; return arrayOp(sc); } e1 = e1->modifiableLvalue(sc, e1); e1->checkScalar(); type = e1->type; if (type->toBasetype()->ty == Tbool) { e2 = e2->implicitCastTo(sc, type); } typeCombine(sc); e1->checkIntegral(); e2->checkIntegral(); } return this; } int BinExp::checkSideEffect(int flag) { if (op == TOKplusplus || op == TOKminusminus || op == TOKassign || op == TOKconstruct || op == TOKblit || op == TOKaddass || op == TOKminass || op == TOKcatass || op == TOKmulass || op == TOKdivass || op == TOKmodass || op == TOKshlass || op == TOKshrass || op == TOKushrass || op == TOKandass || op == TOKorass || op == TOKxorass || op == TOKin || op == TOKremove) return 1; return Expression::checkSideEffect(flag); } void BinExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { expToCBuffer(buf, hgs, e1, precedence[op]); buf->writeByte(' '); buf->writestring(Token::toChars(op)); buf->writeByte(' '); expToCBuffer(buf, hgs, e2, (enum PREC)(precedence[op] + 1)); } int BinExp::isunsigned() { return e1->type->isunsigned() || e2->type->isunsigned(); } #if DMDV2 int BinExp::canThrow() { return e1->canThrow() || e2->canThrow(); } #endif void BinExp::incompatibleTypes() { error("incompatible types for ((%s) %s (%s)): '%s' and '%s'", e1->toChars(), Token::toChars(op), e2->toChars(), e1->type->toChars(), e2->type->toChars()); } /************************************************************/ CompileExp::CompileExp(Loc loc, Expression *e) : UnaExp(loc, TOKmixin, sizeof(CompileExp), e) { } Expression *CompileExp::semantic(Scope *sc) { #if LOGSEMANTIC printf("CompileExp::semantic('%s')\n", toChars()); #endif UnaExp::semantic(sc); e1 = resolveProperties(sc, e1); e1 = e1->optimize(WANTvalue | WANTinterpret); if (e1->op != TOKstring) { error("argument to mixin must be a string, not (%s)", e1->toChars()); type = Type::terror; return this; } StringExp *se = (StringExp *)e1; se = se->toUTF8(sc); Parser p(sc->module, (unsigned char *)se->string, se->len, 0); p.loc = loc; p.nextToken(); //printf("p.loc.linnum = %d\n", p.loc.linnum); Expression *e = p.parseExpression(); if (p.token.value != TOKeof) error("incomplete mixin expression (%s)", se->toChars()); return e->semantic(sc); } void CompileExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { buf->writestring("mixin("); expToCBuffer(buf, hgs, e1, PREC_assign); buf->writeByte(')'); } /************************************************************/ FileExp::FileExp(Loc loc, Expression *e) : UnaExp(loc, TOKmixin, sizeof(FileExp), e) { } Expression *FileExp::semantic(Scope *sc) { char *name; StringExp *se; #if LOGSEMANTIC printf("FileExp::semantic('%s')\n", toChars()); #endif UnaExp::semantic(sc); e1 = resolveProperties(sc, e1); e1 = e1->optimize(WANTvalue); if (e1->op != TOKstring) { error("file name argument must be a string, not (%s)", e1->toChars()); goto Lerror; } se = (StringExp *)e1; se = se->toUTF8(sc); name = (char *)se->string; if (!global.params.fileImppath) { error("need -Jpath switch to import text file %s", name); goto Lerror; } if (name != FileName::name(name)) { error("use -Jpath switch to provide path for filename %s", name); goto Lerror; } name = FileName::searchPath(global.filePath, name, 0); if (!name) { error("file %s cannot be found, check -Jpath", se->toChars()); goto Lerror; } if (global.params.verbose) printf("file %s\t(%s)\n", se->string, name); { File f(name); if (f.read()) { error("cannot read file %s", f.toChars()); goto Lerror; } else { f.ref = 1; se = new StringExp(loc, f.buffer, f.len); } } Lret: return se->semantic(sc); Lerror: se = new StringExp(loc, (char *)""); goto Lret; } void FileExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { buf->writestring("import("); expToCBuffer(buf, hgs, e1, PREC_assign); buf->writeByte(')'); } /************************************************************/ AssertExp::AssertExp(Loc loc, Expression *e, Expression *msg) : UnaExp(loc, TOKassert, sizeof(AssertExp), e) { this->msg = msg; } Expression *AssertExp::syntaxCopy() { AssertExp *ae = new AssertExp(loc, e1->syntaxCopy(), msg ? msg->syntaxCopy() : NULL); return ae; } Expression *AssertExp::semantic(Scope *sc) { #if LOGSEMANTIC printf("AssertExp::semantic('%s')\n", toChars()); #endif UnaExp::semantic(sc); e1 = resolveProperties(sc, e1); // BUG: see if we can do compile time elimination of the Assert e1 = e1->optimize(WANTvalue); e1 = e1->checkToBoolean(); if (msg) { msg = msg->semantic(sc); msg = resolveProperties(sc, msg); msg = msg->implicitCastTo(sc, Type::tchar->constOf()->arrayOf()); msg = msg->optimize(WANTvalue); } if (e1->isBool(FALSE)) { FuncDeclaration *fd = sc->parent->isFuncDeclaration(); fd->hasReturnExp |= 4; if (!global.params.useAssert) { Expression *e = new HaltExp(loc); e = e->semantic(sc); return e; } } type = Type::tvoid; return this; } int AssertExp::checkSideEffect(int flag) { return 1; } #if DMDV2 int AssertExp::canThrow() { /* assert()s are non-recoverable errors, so functions that * use them can be considered "nothrow" */ return 0; //(global.params.useAssert != 0); } #endif void AssertExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { buf->writestring("assert("); expToCBuffer(buf, hgs, e1, PREC_assign); if (msg) { buf->writeByte(','); expToCBuffer(buf, hgs, msg, PREC_assign); } buf->writeByte(')'); } /************************************************************/ DotIdExp::DotIdExp(Loc loc, Expression *e, Identifier *ident) : UnaExp(loc, TOKdot, sizeof(DotIdExp), e) { this->ident = ident; } Expression *DotIdExp::semantic(Scope *sc) { Expression *e; Expression *eleft; Expression *eright; #if LOGSEMANTIC printf("DotIdExp::semantic(this = %p, '%s')\n", this, toChars()); //printf("e1->op = %d, '%s'\n", e1->op, Token::toChars(e1->op)); #endif //{ static int z; fflush(stdout); if (++z == 10) *(char*)0=0; } #if 0 /* Don't do semantic analysis if we'll be converting * it to a string. */ if (ident == Id::stringof) { char *s = e1->toChars(); e = new StringExp(loc, s, strlen(s), 'c'); e = e->semantic(sc); return e; } #endif /* Special case: rewrite this.id and super.id * to be classtype.id and baseclasstype.id * if we have no this pointer. */ if ((e1->op == TOKthis || e1->op == TOKsuper) && !hasThis(sc)) { ClassDeclaration *cd; StructDeclaration *sd; AggregateDeclaration *ad; ad = sc->getStructClassScope(); if (ad) { cd = ad->isClassDeclaration(); if (cd) { if (e1->op == TOKthis) { e = typeDotIdExp(loc, cd->type, ident); return e->semantic(sc); } else if (cd->baseClass && e1->op == TOKsuper) { e = typeDotIdExp(loc, cd->baseClass->type, ident); return e->semantic(sc); } } else { sd = ad->isStructDeclaration(); if (sd) { if (e1->op == TOKthis) { e = typeDotIdExp(loc, sd->type, ident); return e->semantic(sc); } } } } } UnaExp::semantic(sc); if (e1->op == TOKdotexp) { DotExp *de = (DotExp *)e1; eleft = de->e1; eright = de->e2; } else { e1 = resolveProperties(sc, e1); eleft = NULL; eright = e1; } #if DMDV2 if (e1->op == TOKtuple && ident == Id::offsetof) { /* 'distribute' the .offsetof to each of the tuple elements. */ TupleExp *te = (TupleExp *)e1; Expressions *exps = new Expressions(); exps->setDim(te->exps->dim); for (int i = 0; i < exps->dim; i++) { Expression *e = (Expression *)te->exps->data[i]; e = e->semantic(sc); e = new DotIdExp(e->loc, e, Id::offsetof); exps->data[i] = (void *)e; } e = new TupleExp(loc, exps); e = e->semantic(sc); return e; } #endif if (e1->op == TOKtuple && ident == Id::length) { TupleExp *te = (TupleExp *)e1; e = new IntegerExp(loc, te->exps->dim, Type::tsize_t); return e; } if (e1->op == TOKdottd) { error("template %s does not have property %s", e1->toChars(), ident->toChars()); return e1; } if (!e1->type) { error("expression %s does not have property %s", e1->toChars(), ident->toChars()); return e1; } Type *t1b = e1->type->toBasetype(); if (eright->op == TOKimport) // also used for template alias's { ScopeExp *ie = (ScopeExp *)eright; /* Disable access to another module's private imports. * The check for 'is sds our current module' is because * the current module should have access to its own imports. */ Dsymbol *s = ie->sds->search(loc, ident, (ie->sds->isModule() && ie->sds != sc->module) ? 1 : 0); if (s) { s = s->toAlias(); checkDeprecated(sc, s); EnumMember *em = s->isEnumMember(); if (em) { e = em->value; e = e->semantic(sc); return e; } VarDeclaration *v = s->isVarDeclaration(); if (v) { //printf("DotIdExp:: Identifier '%s' is a variable, type '%s'\n", toChars(), v->type->toChars()); if (v->inuse) { error("circular reference to '%s'", v->toChars()); type = Type::tint32; return this; } type = v->type; if (v->needThis()) { if (!eleft) eleft = new ThisExp(loc); e = new DotVarExp(loc, eleft, v); e = e->semantic(sc); } else { e = new VarExp(loc, v); if (eleft) { e = new CommaExp(loc, eleft, e); e->type = v->type; } } return e->deref(); } FuncDeclaration *f = s->isFuncDeclaration(); if (f) { //printf("it's a function\n"); if (f->needThis()) { if (!eleft) eleft = new ThisExp(loc); e = new DotVarExp(loc, eleft, f); e = e->semantic(sc); } else { e = new VarExp(loc, f, 1); if (eleft) { e = new CommaExp(loc, eleft, e); e->type = f->type; } } return e; } #if DMDV2 OverloadSet *o = s->isOverloadSet(); if (o) { //printf("'%s' is an overload set\n", o->toChars()); return new OverExp(o); } #endif Type *t = s->getType(); if (t) { return new TypeExp(loc, t); } TupleDeclaration *tup = s->isTupleDeclaration(); if (tup) { if (eleft) error("cannot have e.tuple"); e = new TupleExp(loc, tup); e = e->semantic(sc); return e; } ScopeDsymbol *sds = s->isScopeDsymbol(); if (sds) { //printf("it's a ScopeDsymbol\n"); e = new ScopeExp(loc, sds); e = e->semantic(sc); if (eleft) e = new DotExp(loc, eleft, e); return e; } Import *imp = s->isImport(); if (imp) { ScopeExp *ie; ie = new ScopeExp(loc, imp->pkg); return ie->semantic(sc); } // BUG: handle other cases like in IdentifierExp::semantic() #ifdef DEBUG printf("s = '%s', kind = '%s'\n", s->toChars(), s->kind()); #endif assert(0); } else if (ident == Id::stringof) { char *s = ie->toChars(); e = new StringExp(loc, s, strlen(s), 'c'); e = e->semantic(sc); return e; } error("undefined identifier %s", toChars()); type = Type::tvoid; return this; } else if (t1b->ty == Tpointer && ident != Id::init && ident != Id::__sizeof && ident != Id::alignof && ident != Id::offsetof && ident != Id::mangleof && ident != Id::stringof) { /* Rewrite: * p.ident * as: * (*p).ident */ e = new PtrExp(loc, e1); e->type = ((TypePointer *)t1b)->next; return e->type->dotExp(sc, e, ident); } #if DMDV2 else if (t1b->ty == Tarray || t1b->ty == Tsarray || t1b->ty == Taarray) { /* If ident is not a valid property, rewrite: * e1.ident * as: * .ident(e1) */ unsigned errors = global.errors; global.gag++; e = e1->type->dotExp(sc, e1, ident); global.gag--; if (errors != global.errors) // if failed to find the property { global.errors = errors; e = new DotIdExp(loc, new IdentifierExp(loc, Id::empty), ident); e = new CallExp(loc, e, e1); } e = e->semantic(sc); return e; } #endif else { e = e1->type->dotExp(sc, e1, ident); e = e->semantic(sc); return e; } } void DotIdExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { //printf("DotIdExp::toCBuffer()\n"); expToCBuffer(buf, hgs, e1, PREC_primary); buf->writeByte('.'); buf->writestring(ident->toChars()); } /********************** DotTemplateExp ***********************************/ // Mainly just a placeholder DotTemplateExp::DotTemplateExp(Loc loc, Expression *e, TemplateDeclaration *td) : UnaExp(loc, TOKdottd, sizeof(DotTemplateExp), e) { this->td = td; } void DotTemplateExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { expToCBuffer(buf, hgs, e1, PREC_primary); buf->writeByte('.'); buf->writestring(td->toChars()); } /************************************************************/ DotVarExp::DotVarExp(Loc loc, Expression *e, Declaration *v, int hasOverloads) : UnaExp(loc, TOKdotvar, sizeof(DotVarExp), e) { //printf("DotVarExp()\n"); this->var = v; this->hasOverloads = hasOverloads; } Expression *DotVarExp::semantic(Scope *sc) { #if LOGSEMANTIC printf("DotVarExp::semantic('%s')\n", toChars()); #endif if (!type) { var = var->toAlias()->isDeclaration(); TupleDeclaration *tup = var->isTupleDeclaration(); if (tup) { /* Replace: * e1.tuple(a, b, c) * with: * tuple(e1.a, e1.b, e1.c) */ Expressions *exps = new Expressions; exps->reserve(tup->objects->dim); for (size_t i = 0; i < tup->objects->dim; i++) { Object *o = (Object *)tup->objects->data[i]; if (o->dyncast() != DYNCAST_EXPRESSION) { error("%s is not an expression", o->toChars()); } else { Expression *e = (Expression *)o; if (e->op != TOKdsymbol) error("%s is not a member", e->toChars()); else { DsymbolExp *ve = (DsymbolExp *)e; e = new DotVarExp(loc, e1, ve->s->isDeclaration()); exps->push(e); } } } Expression *e = new TupleExp(loc, exps); e = e->semantic(sc); return e; } e1 = e1->semantic(sc); type = var->type; if (!type && global.errors) { // var is goofed up, just return 0 return new ErrorExp(); } assert(type); if (!var->isFuncDeclaration()) // for functions, do checks after overload resolution { Type *t1 = e1->type; if (t1->ty == Tpointer) t1 = t1->nextOf(); type = type->addMod(t1->mod); Dsymbol *vparent = var->toParent(); AggregateDeclaration *ad = vparent ? vparent->isAggregateDeclaration() : NULL; e1 = getRightThis(loc, sc, ad, e1, var); if (!sc->noaccesscheck) accessCheck(loc, sc, e1, var); VarDeclaration *v = var->isVarDeclaration(); Expression *e = expandVar(WANTvalue, v); if (e) return e; } } //printf("-DotVarExp::semantic('%s')\n", toChars()); return this; } #if DMDV2 int DotVarExp::isLvalue() { return 1; } #endif Expression *DotVarExp::toLvalue(Scope *sc, Expression *e) { //printf("DotVarExp::toLvalue(%s)\n", toChars()); return this; } Expression *DotVarExp::modifiableLvalue(Scope *sc, Expression *e) { #if 0 printf("DotVarExp::modifiableLvalue(%s)\n", toChars()); printf("e1->type = %s\n", e1->type->toChars()); printf("var->type = %s\n", var->type->toChars()); #endif if (var->isCtorinit()) { // It's only modifiable if inside the right constructor Dsymbol *s = sc->func; while (1) { FuncDeclaration *fd = NULL; if (s) fd = s->isFuncDeclaration(); if (fd && ((fd->isCtorDeclaration() && var->storage_class & STCfield) || (fd->isStaticCtorDeclaration() && !(var->storage_class & STCfield))) && fd->toParent() == var->toParent() && e1->op == TOKthis ) { VarDeclaration *v = var->isVarDeclaration(); assert(v); v->ctorinit = 1; //printf("setting ctorinit\n"); } else { if (s) { s = s->toParent2(); continue; } else { const char *p = var->isStatic() ? "static " : ""; error("can only initialize %sconst member %s inside %sconstructor", p, var->toChars(), p); } } break; } } #if DMDV2 else { Type *t1 = e1->type->toBasetype(); if (!t1->isMutable() || (t1->ty == Tpointer && !t1->nextOf()->isMutable()) || !var->type->isMutable() || !var->type->isAssignable() || var->storage_class & STCmanifest ) error("cannot modify const/immutable expression %s", toChars()); } #endif return this; } void DotVarExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { expToCBuffer(buf, hgs, e1, PREC_primary); buf->writeByte('.'); buf->writestring(var->toChars()); } /************************************************************/ /* Things like: * foo.bar!(args) */ DotTemplateInstanceExp::DotTemplateInstanceExp(Loc loc, Expression *e, TemplateInstance *ti) : UnaExp(loc, TOKdotti, sizeof(DotTemplateInstanceExp), e) { //printf("DotTemplateInstanceExp()\n"); this->ti = ti; } Expression *DotTemplateInstanceExp::syntaxCopy() { DotTemplateInstanceExp *de = new DotTemplateInstanceExp(loc, e1->syntaxCopy(), (TemplateInstance *)ti->syntaxCopy(NULL)); return de; } Expression *DotTemplateInstanceExp::semantic(Scope *sc) { Dsymbol *s; Dsymbol *s2; TemplateDeclaration *td; Expression *e; Identifier *id; Type *t1; Expression *eleft = NULL; Expression *eright; #if LOGSEMANTIC printf("DotTemplateInstanceExp::semantic('%s')\n", toChars()); #endif //e1->print(); //print(); e1 = e1->semantic(sc); t1 = e1->type; if (t1) t1 = t1->toBasetype(); //t1->print(); /* Extract the following from e1: * s: the symbol which ti should be a member of * eleft: if not NULL, it is the 'this' pointer for ti */ if (e1->op == TOKdotexp) { DotExp *de = (DotExp *)e1; eleft = de->e1; eright = de->e2; } else { eleft = NULL; eright = e1; } if (eright->op == TOKimport) { s = ((ScopeExp *)eright)->sds; } else if (e1->op == TOKtype) { s = t1->isClassHandle(); if (!s) { if (t1->ty == Tstruct) s = ((TypeStruct *)t1)->sym; else goto L1; } } else if (t1 && (t1->ty == Tstruct || t1->ty == Tclass)) { s = t1->toDsymbol(sc); eleft = e1; } else if (t1 && t1->ty == Tpointer) { t1 = ((TypePointer *)t1)->next->toBasetype(); if (t1->ty != Tstruct) goto L1; s = t1->toDsymbol(sc); eleft = e1; } else { L1: error("template %s is not a member of %s", ti->toChars(), e1->toChars()); goto Lerr; } assert(s); id = ti->name; s2 = s->search(loc, id, 0); if (!s2) { if (!s->ident) error("template identifier %s is not a member of undefined %s", id->toChars(), s->kind()); else error("template identifier %s is not a member of %s %s", id->toChars(), s->kind(), s->ident->toChars()); goto Lerr; } s = s2; s->semantic(sc); s = s->toAlias(); td = s->isTemplateDeclaration(); if (!td) { error("%s is not a template", id->toChars()); goto Lerr; } if (global.errors) goto Lerr; ti->tempdecl = td; if (eleft) { Declaration *v; ti->semantic(sc); s = ti->inst->toAlias(); v = s->isDeclaration(); if (v) { e = new DotVarExp(loc, eleft, v); e = e->semantic(sc); return e; } } e = new ScopeExp(loc, ti); if (eleft) { e = new DotExp(loc, eleft, e); } e = e->semantic(sc); return e; Lerr: return new ErrorExp(); } void DotTemplateInstanceExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { expToCBuffer(buf, hgs, e1, PREC_primary); buf->writeByte('.'); ti->toCBuffer(buf, hgs); } /************************************************************/ DelegateExp::DelegateExp(Loc loc, Expression *e, FuncDeclaration *f, int hasOverloads) : UnaExp(loc, TOKdelegate, sizeof(DelegateExp), e) { this->func = f; this->hasOverloads = hasOverloads; } Expression *DelegateExp::semantic(Scope *sc) { #if LOGSEMANTIC printf("DelegateExp::semantic('%s')\n", toChars()); #endif if (!type) { e1 = e1->semantic(sc); type = new TypeDelegate(func->type); type = type->semantic(loc, sc); AggregateDeclaration *ad = func->toParent()->isAggregateDeclaration(); if (func->needThis()) e1 = getRightThis(loc, sc, ad, e1, func); } return this; } void DelegateExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { buf->writeByte('&'); if (!func->isNested()) { expToCBuffer(buf, hgs, e1, PREC_primary); buf->writeByte('.'); } buf->writestring(func->toChars()); } /************************************************************/ DotTypeExp::DotTypeExp(Loc loc, Expression *e, Dsymbol *s) : UnaExp(loc, TOKdottype, sizeof(DotTypeExp), e) { this->sym = s; this->type = s->getType(); } Expression *DotTypeExp::semantic(Scope *sc) { #if LOGSEMANTIC printf("DotTypeExp::semantic('%s')\n", toChars()); #endif UnaExp::semantic(sc); return this; } void DotTypeExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { expToCBuffer(buf, hgs, e1, PREC_primary); buf->writeByte('.'); buf->writestring(sym->toChars()); } /************************************************************/ CallExp::CallExp(Loc loc, Expression *e, Expressions *exps) : UnaExp(loc, TOKcall, sizeof(CallExp), e) { this->arguments = exps; } CallExp::CallExp(Loc loc, Expression *e) : UnaExp(loc, TOKcall, sizeof(CallExp), e) { this->arguments = NULL; } CallExp::CallExp(Loc loc, Expression *e, Expression *earg1) : UnaExp(loc, TOKcall, sizeof(CallExp), e) { Expressions *arguments = new Expressions(); arguments->setDim(1); arguments->data[0] = (void *)earg1; this->arguments = arguments; } CallExp::CallExp(Loc loc, Expression *e, Expression *earg1, Expression *earg2) : UnaExp(loc, TOKcall, sizeof(CallExp), e) { Expressions *arguments = new Expressions(); arguments->setDim(2); arguments->data[0] = (void *)earg1; arguments->data[1] = (void *)earg2; this->arguments = arguments; } Expression *CallExp::syntaxCopy() { return new CallExp(loc, e1->syntaxCopy(), arraySyntaxCopy(arguments)); } Expression *CallExp::semantic(Scope *sc) { TypeFunction *tf; FuncDeclaration *f; int i; Type *t1; int istemp; Objects *targsi = NULL; // initial list of template arguments TemplateInstance *tierror = NULL; #if LOGSEMANTIC printf("CallExp::semantic() %s\n", toChars()); #endif if (type) return this; // semantic() already run #if 0 if (arguments && arguments->dim) { Expression *earg = (Expression *)arguments->data[0]; earg->print(); if (earg->type) earg->type->print(); } #endif if (e1->op == TOKdelegate) { DelegateExp *de = (DelegateExp *)e1; e1 = new DotVarExp(de->loc, de->e1, de->func); return semantic(sc); } /* Transform: * array.id(args) into .id(array,args) * aa.remove(arg) into delete aa[arg] */ if (e1->op == TOKdot) { // BUG: we should handle array.a.b.c.e(args) too DotIdExp *dotid = (DotIdExp *)(e1); dotid->e1 = dotid->e1->semantic(sc); assert(dotid->e1); if (dotid->e1->type) { TY e1ty = dotid->e1->type->toBasetype()->ty; if (e1ty == Taarray && dotid->ident == Id::remove) { if (!arguments || arguments->dim != 1) { error("expected key as argument to aa.remove()"); goto Lagain; } Expression *key = (Expression *)arguments->data[0]; key = key->semantic(sc); key = resolveProperties(sc, key); key->rvalue(); TypeAArray *taa = (TypeAArray *)dotid->e1->type->toBasetype(); key = key->implicitCastTo(sc, taa->index); return new RemoveExp(loc, dotid->e1, key); } else if (e1ty == Tarray || e1ty == Tsarray || e1ty == Taarray) { if (!arguments) arguments = new Expressions(); arguments->shift(dotid->e1); #if DMDV2 e1 = new DotIdExp(dotid->loc, new IdentifierExp(dotid->loc, Id::empty), dotid->ident); #else e1 = new IdentifierExp(dotid->loc, dotid->ident); #endif } } } #if DMDV2 /* This recognizes: * foo!(tiargs)(funcargs) */ if (e1->op == TOKimport && !e1->type) { ScopeExp *se = (ScopeExp *)e1; TemplateInstance *ti = se->sds->isTemplateInstance(); if (ti && !ti->semanticRun) { /* Attempt to instantiate ti. If that works, go with it. * If not, go with partial explicit specialization. */ ti->semanticTiargs(sc); unsigned errors = global.errors; global.gag++; ti->semantic(sc); global.gag--; if (errors != global.errors) { /* Didn't work, go with partial explicit specialization */ global.errors = errors; targsi = ti->tiargs; tierror = ti; // for error reporting e1 = new IdentifierExp(loc, ti->name); } } } /* This recognizes: * expr.foo!(tiargs)(funcargs) */ if (e1->op == TOKdotti && !e1->type) { DotTemplateInstanceExp *se = (DotTemplateInstanceExp *)e1; TemplateInstance *ti = se->ti; if (!ti->semanticRun) { /* Attempt to instantiate ti. If that works, go with it. * If not, go with partial explicit specialization. */ ti->semanticTiargs(sc); Expression *etmp = e1->trySemantic(sc); if (etmp) e1 = etmp; // it worked else // didn't work { targsi = ti->tiargs; tierror = ti; // for error reporting e1 = new DotIdExp(loc, se->e1, ti->name); } } } #endif istemp = 0; Lagain: //printf("Lagain: %s\n", toChars()); f = NULL; if (e1->op == TOKthis || e1->op == TOKsuper) { // semantic() run later for these } else { UnaExp::semantic(sc); /* Look for e1 being a lazy parameter */ if (e1->op == TOKvar) { VarExp *ve = (VarExp *)e1; if (ve->var->storage_class & STClazy) { TypeFunction *tf = new TypeFunction(NULL, ve->var->type, 0, LINKd); TypeDelegate *t = new TypeDelegate(tf); ve->type = t->semantic(loc, sc); } } if (e1->op == TOKimport) { // Perhaps this should be moved to ScopeExp::semantic() ScopeExp *se = (ScopeExp *)e1; e1 = new DsymbolExp(loc, se->sds); e1 = e1->semantic(sc); } #if 1 // patch for #540 by Oskar Linde else if (e1->op == TOKdotexp) { DotExp *de = (DotExp *) e1; if (de->e2->op == TOKimport) { // This should *really* be moved to ScopeExp::semantic() ScopeExp *se = (ScopeExp *)de->e2; de->e2 = new DsymbolExp(loc, se->sds); de->e2 = de->e2->semantic(sc); } if (de->e2->op == TOKtemplate) { TemplateExp *te = (TemplateExp *) de->e2; e1 = new DotTemplateExp(loc,de->e1,te->td); } } #endif } if (e1->op == TOKcomma) { CommaExp *ce = (CommaExp *)e1; e1 = ce->e2; e1->type = ce->type; ce->e2 = this; ce->type = NULL; return ce->semantic(sc); } t1 = NULL; if (e1->type) t1 = e1->type->toBasetype(); // Check for call operator overload if (t1) { AggregateDeclaration *ad; if (t1->ty == Tstruct) { ad = ((TypeStruct *)t1)->sym; // First look for constructor if (ad->ctor && arguments && arguments->dim) { // Create variable that will get constructed Identifier *idtmp = Lexer::uniqueId("__ctmp"); VarDeclaration *tmp = new VarDeclaration(loc, t1, idtmp, NULL); Expression *av = new DeclarationExp(loc, tmp); av = new CommaExp(loc, av, new VarExp(loc, tmp)); Expression *e; CtorDeclaration *cf = ad->ctor->isCtorDeclaration(); if (cf) e = new DotVarExp(loc, av, cf, 1); else { TemplateDeclaration *td = ad->ctor->isTemplateDeclaration(); assert(td); e = new DotTemplateExp(loc, av, td); } e = new CallExp(loc, e, arguments); #if !STRUCTTHISREF /* Constructors return a pointer to the instance */ e = new PtrExp(loc, e); #endif e = e->semantic(sc); return e; } // No constructor, look for overload of opCall if (search_function(ad, Id::call)) goto L1; // overload of opCall, therefore it's a call if (e1->op != TOKtype) error("%s %s does not overload ()", ad->kind(), ad->toChars()); /* It's a struct literal */ Expression *e = new StructLiteralExp(loc, (StructDeclaration *)ad, arguments); e = e->semantic(sc); e->type = e1->type; // in case e1->type was a typedef return e; } else if (t1->ty == Tclass) { ad = ((TypeClass *)t1)->sym; goto L1; L1: // Rewrite as e1.call(arguments) Expression *e = new DotIdExp(loc, e1, Id::call); e = new CallExp(loc, e, arguments); e = e->semantic(sc); return e; } } arrayExpressionSemantic(arguments, sc); preFunctionArguments(loc, sc, arguments); if (e1->op == TOKdotvar && t1->ty == Tfunction || e1->op == TOKdottd) { DotVarExp *dve; DotTemplateExp *dte; AggregateDeclaration *ad; UnaExp *ue = (UnaExp *)(e1); if (e1->op == TOKdotvar) { // Do overload resolution dve = (DotVarExp *)(e1); f = dve->var->isFuncDeclaration(); assert(f); f = f->overloadResolve(loc, ue->e1, arguments); ad = f->toParent()->isAggregateDeclaration(); } else { dte = (DotTemplateExp *)(e1); TemplateDeclaration *td = dte->td; assert(td); if (!arguments) // Should fix deduceFunctionTemplate() so it works on NULL argument arguments = new Expressions(); f = td->deduceFunctionTemplate(sc, loc, targsi, ue->e1, arguments); if (!f) { type = Type::terror; return this; } ad = td->toParent()->isAggregateDeclaration(); } if (f->needThis()) { ue->e1 = getRightThis(loc, sc, ad, ue->e1, f); } /* Cannot call public functions from inside invariant * (because then the invariant would have infinite recursion) */ if (sc->func && sc->func->isInvariantDeclaration() && ue->e1->op == TOKthis && f->addPostInvariant() ) { error("cannot call public/export function %s from immutable", f->toChars()); } checkDeprecated(sc, f); #if DMDV2 checkPurity(sc, f); #endif accessCheck(loc, sc, ue->e1, f); if (!f->needThis()) { VarExp *ve = new VarExp(loc, f); e1 = new CommaExp(loc, ue->e1, ve); e1->type = f->type; } else { if (e1->op == TOKdotvar) dve->var = f; else e1 = new DotVarExp(loc, dte->e1, f); e1->type = f->type; #if 0 printf("ue->e1 = %s\n", ue->e1->toChars()); printf("f = %s\n", f->toChars()); printf("t = %s\n", t->toChars()); printf("e1 = %s\n", e1->toChars()); printf("e1->type = %s\n", e1->type->toChars()); #endif // Const member function can take const/immutable/mutable this if (!(f->type->isConst())) { // Check for const/immutable compatibility Type *tthis = ue->e1->type->toBasetype(); if (tthis->ty == Tpointer) tthis = tthis->nextOf()->toBasetype(); if (f->type->isInvariant()) { if (tthis->mod != MODinvariant) error("%s can only be called on an invariant object", e1->toChars()); } else { if (tthis->mod != 0) { //printf("mod = %x\n", tthis->mod); error("%s can only be called on a mutable object, not %s", e1->toChars(), tthis->toChars()); } } /* Cannot call mutable method on a final struct */ if (tthis->ty == Tstruct && ue->e1->op == TOKvar) { VarExp *v = (VarExp *)ue->e1; if (v->var->storage_class & STCfinal) error("cannot call mutable method on final struct"); } } // See if we need to adjust the 'this' pointer AggregateDeclaration *ad = f->isThis(); ClassDeclaration *cd = ue->e1->type->isClassHandle(); if (ad && cd && ad->isClassDeclaration() && ad != cd && ue->e1->op != TOKsuper) { ue->e1 = ue->e1->castTo(sc, ad->type); //new CastExp(loc, ue->e1, ad->type); ue->e1 = ue->e1->semantic(sc); } } t1 = e1->type; } else if (e1->op == TOKsuper) { // Base class constructor call ClassDeclaration *cd = NULL; if (sc->func) cd = sc->func->toParent()->isClassDeclaration(); if (!cd || !cd->baseClass || !sc->func->isCtorDeclaration()) { error("super class constructor call must be in a constructor"); type = Type::terror; return this; } else { if (!cd->baseClass->ctor) { error("no super class constructor for %s", cd->baseClass->toChars()); type = Type::terror; return this; } else { if (!sc->intypeof) { #if 0 if (sc->callSuper & (CSXthis | CSXsuper)) error("reference to this before super()"); #endif if (sc->noctor || sc->callSuper & CSXlabel) error("constructor calls not allowed in loops or after labels"); if (sc->callSuper & (CSXsuper_ctor | CSXthis_ctor)) error("multiple constructor calls"); sc->callSuper |= CSXany_ctor | CSXsuper_ctor; } f = resolveFuncCall(sc, loc, cd->baseClass->ctor, NULL, NULL, arguments, 0); checkDeprecated(sc, f); #if DMDV2 checkPurity(sc, f); #endif e1 = new DotVarExp(e1->loc, e1, f); e1 = e1->semantic(sc); t1 = e1->type; } } } else if (e1->op == TOKthis) { // same class constructor call AggregateDeclaration *cd = NULL; if (sc->func) cd = sc->func->toParent()->isAggregateDeclaration(); if (!cd || !sc->func->isCtorDeclaration()) { error("constructor call must be in a constructor"); type = Type::terror; return this; } else { if (!sc->intypeof) { #if 0 if (sc->callSuper & (CSXthis | CSXsuper)) error("reference to this before super()"); #endif if (sc->noctor || sc->callSuper & CSXlabel) error("constructor calls not allowed in loops or after labels"); if (sc->callSuper & (CSXsuper_ctor | CSXthis_ctor)) error("multiple constructor calls"); sc->callSuper |= CSXany_ctor | CSXthis_ctor; } f = resolveFuncCall(sc, loc, cd->ctor, NULL, NULL, arguments, 0); checkDeprecated(sc, f); #if DMDV2 checkPurity(sc, f); #endif e1 = new DotVarExp(e1->loc, e1, f); e1 = e1->semantic(sc); t1 = e1->type; // BUG: this should really be done by checking the static // call graph if (f == sc->func) error("cyclic constructor call"); } } else if (e1->op == TOKoverloadset) { OverExp *eo = (OverExp *)e1; FuncDeclaration *f = NULL; for (int i = 0; i < eo->vars->a.dim; i++) { Dsymbol *s = (Dsymbol *)eo->vars->a.data[i]; FuncDeclaration *f2 = s->isFuncDeclaration(); if (f2) { f2 = f2->overloadResolve(loc, NULL, arguments, 1); } else { TemplateDeclaration *td = s->isTemplateDeclaration(); assert(td); f2 = td->deduceFunctionTemplate(sc, loc, targsi, NULL, arguments, 1); } if (f2) { if (f) /* Error if match in more than one overload set, * even if one is a 'better' match than the other. */ ScopeDsymbol::multiplyDefined(loc, f, f2); else f = f2; } } if (!f) { /* No overload matches, just set f and rely on error * message being generated later. */ f = (FuncDeclaration *)eo->vars->a.data[0]; } e1 = new VarExp(loc, f); goto Lagain; } else if (!t1) { error("function expected before (), not '%s'", e1->toChars()); type = Type::terror; return this; } else if (t1->ty != Tfunction) { if (t1->ty == Tdelegate) { TypeDelegate *td = (TypeDelegate *)t1; assert(td->next->ty == Tfunction); tf = (TypeFunction *)(td->next); if (sc->func && sc->func->isPure() && !tf->ispure) { error("pure function '%s' cannot call impure delegate '%s'", sc->func->toChars(), e1->toChars()); } goto Lcheckargs; } else if (t1->ty == Tpointer && ((TypePointer *)t1)->next->ty == Tfunction) { Expression *e; e = new PtrExp(loc, e1); t1 = ((TypePointer *)t1)->next; if (sc->func && sc->func->isPure() && !((TypeFunction *)t1)->ispure) { error("pure function '%s' cannot call impure function pointer '%s'", sc->func->toChars(), e1->toChars()); } e->type = t1; e1 = e; } else if (e1->op == TOKtemplate) { TemplateExp *te = (TemplateExp *)e1; f = te->td->deduceFunctionTemplate(sc, loc, targsi, NULL, arguments); if (!f) { if (tierror) tierror->error("errors instantiating template"); // give better error message type = Type::terror; return this; } if (f->needThis() && hasThis(sc)) { // Supply an implicit 'this', as in // this.ident e1 = new DotTemplateExp(loc, (new ThisExp(loc))->semantic(sc), te->td); goto Lagain; } e1 = new VarExp(loc, f); goto Lagain; } else { error("function expected before (), not %s of type %s", e1->toChars(), e1->type->toChars()); type = Type::terror; return this; } } else if (e1->op == TOKvar) { // Do overload resolution VarExp *ve = (VarExp *)e1; f = ve->var->isFuncDeclaration(); assert(f); if (ve->hasOverloads) f = f->overloadResolve(loc, NULL, arguments); checkDeprecated(sc, f); #if DMDV2 checkPurity(sc, f); #endif if (f->needThis() && hasThis(sc)) { // Supply an implicit 'this', as in // this.ident e1 = new DotVarExp(loc, new ThisExp(loc), f); goto Lagain; } accessCheck(loc, sc, NULL, f); ve->var = f; // ve->hasOverloads = 0; ve->type = f->type; t1 = f->type; } assert(t1->ty == Tfunction); tf = (TypeFunction *)(t1); Lcheckargs: assert(tf->ty == Tfunction); type = tf->next; if (!arguments) arguments = new Expressions(); functionArguments(loc, sc, tf, arguments); if (!type) { error("forward reference to inferred return type of function call %s", toChars()); type = Type::terror; } if (f && f->tintro) { Type *t = type; int offset = 0; TypeFunction *tf = (TypeFunction *)f->tintro; if (tf->next->isBaseOf(t, &offset) && offset) { type = tf->next; return castTo(sc, t); } } return this; } int CallExp::checkSideEffect(int flag) { #if DMDV2 if (flag != 2) return 1; if (e1->checkSideEffect(2)) return 1; /* If any of the arguments have side effects, this expression does */ for (size_t i = 0; i < arguments->dim; i++) { Expression *e = (Expression *)arguments->data[i]; if (e->checkSideEffect(2)) return 1; } /* If calling a function or delegate that is typed as pure, * then this expression has no side effects. */ Type *t = e1->type->toBasetype(); if (t->ty == Tfunction && ((TypeFunction *)t)->ispure) return 0; if (t->ty == Tdelegate && ((TypeFunction *)((TypeDelegate *)t)->next)->ispure) return 0; #endif return 1; } #if DMDV2 int CallExp::canThrow() { //printf("CallExp::canThrow() %s\n", toChars()); if (e1->canThrow()) return 1; /* If any of the arguments can throw, then this expression can throw */ for (size_t i = 0; i < arguments->dim; i++) { Expression *e = (Expression *)arguments->data[i]; if (e && e->canThrow()) return 1; } if (global.errors && !e1->type) return 0; // error recovery /* If calling a function or delegate that is typed as nothrow, * then this expression cannot throw. * Note that pure functions can throw. */ Type *t = e1->type->toBasetype(); if (t->ty == Tfunction && ((TypeFunction *)t)->isnothrow) return 0; if (t->ty == Tdelegate && ((TypeFunction *)((TypeDelegate *)t)->next)->isnothrow) return 0; return 1; } #endif #if DMDV2 int CallExp::isLvalue() { // if (type->toBasetype()->ty == Tstruct) // return 1; Type *tb = e1->type->toBasetype(); if (tb->ty == Tfunction && ((TypeFunction *)tb)->isref) return 1; // function returns a reference return 0; } #endif Expression *CallExp::toLvalue(Scope *sc, Expression *e) { if (isLvalue()) return this; return Expression::toLvalue(sc, e); } void CallExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { int i; expToCBuffer(buf, hgs, e1, precedence[op]); buf->writeByte('('); argsToCBuffer(buf, arguments, hgs); buf->writeByte(')'); } /************************************************************/ AddrExp::AddrExp(Loc loc, Expression *e) : UnaExp(loc, TOKaddress, sizeof(AddrExp), e) { } Expression *AddrExp::semantic(Scope *sc) { #if LOGSEMANTIC printf("AddrExp::semantic('%s')\n", toChars()); #endif if (!type) { UnaExp::semantic(sc); e1 = e1->toLvalue(sc, NULL); if (!e1->type) { error("cannot take address of %s", e1->toChars()); return new ErrorExp(); } if (!e1->type->deco) { /* No deco means semantic() was not run on the type. * We have to run semantic() on the symbol to get the right type: * auto x = &bar; * pure: int bar() { return 1;} * otherwise the 'pure' is missing from the type assigned to x. */ error("forward reference to %s", e1->toChars()); return new ErrorExp(); } //printf("test3 deco = %p\n", e1->type->deco); type = e1->type->pointerTo(); // See if this should really be a delegate if (e1->op == TOKdotvar) { DotVarExp *dve = (DotVarExp *)e1; FuncDeclaration *f = dve->var->isFuncDeclaration(); if (f) { if (!dve->hasOverloads) f->tookAddressOf++; Expression *e = new DelegateExp(loc, dve->e1, f, dve->hasOverloads); e = e->semantic(sc); return e; } } else if (e1->op == TOKvar) { VarExp *ve = (VarExp *)e1; VarDeclaration *v = ve->var->isVarDeclaration(); if (v && !v->canTakeAddressOf()) error("cannot take address of %s", e1->toChars()); FuncDeclaration *f = ve->var->isFuncDeclaration(); if (f) { if (!ve->hasOverloads || /* Because nested functions cannot be overloaded, * mark here that we took its address because castTo() * may not be called with an exact match. */ f->toParent2()->isFuncDeclaration()) f->tookAddressOf++; if (f->isNested()) { Expression *e = new DelegateExp(loc, e1, f, ve->hasOverloads); e = e->semantic(sc); return e; } if (f->needThis() && hasThis(sc)) { /* Should probably supply 'this' after overload resolution, * not before. */ Expression *ethis = new ThisExp(loc); Expression *e = new DelegateExp(loc, ethis, f, ve->hasOverloads); e = e->semantic(sc); return e; } } } return optimize(WANTvalue); } return this; } /************************************************************/ PtrExp::PtrExp(Loc loc, Expression *e) : UnaExp(loc, TOKstar, sizeof(PtrExp), e) { // if (e->type) // type = ((TypePointer *)e->type)->next; } PtrExp::PtrExp(Loc loc, Expression *e, Type *t) : UnaExp(loc, TOKstar, sizeof(PtrExp), e) { type = t; } Expression *PtrExp::semantic(Scope *sc) { #if LOGSEMANTIC printf("PtrExp::semantic('%s')\n", toChars()); #endif if (!type) { UnaExp::semantic(sc); e1 = resolveProperties(sc, e1); if (!e1->type) printf("PtrExp::semantic('%s')\n", toChars()); Expression *e = op_overload(sc); if (e) return e; Type *tb = e1->type->toBasetype(); switch (tb->ty) { case Tpointer: type = ((TypePointer *)tb)->next; break; case Tsarray: case Tarray: type = ((TypeArray *)tb)->next; e1 = e1->castTo(sc, type->pointerTo()); break; default: error("can only * a pointer, not a '%s'", e1->type->toChars()); return new ErrorExp(); } rvalue(); } return this; } #if DMDV2 int PtrExp::isLvalue() { return 1; } #endif Expression *PtrExp::toLvalue(Scope *sc, Expression *e) { #if 0 tym = tybasic(e1->ET->Tty); if (!(tyscalar(tym) || tym == TYstruct || tym == TYarray && e->Eoper == TOKaddr)) synerr(EM_lvalue); // lvalue expected #endif return this; } #if DMDV2 Expression *PtrExp::modifiableLvalue(Scope *sc, Expression *e) { //printf("PtrExp::modifiableLvalue() %s, type %s\n", toChars(), type->toChars()); if (e1->op == TOKsymoff) { SymOffExp *se = (SymOffExp *)e1; se->var->checkModify(loc, sc, type); //return toLvalue(sc, e); } return Expression::modifiableLvalue(sc, e); } #endif void PtrExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { buf->writeByte('*'); expToCBuffer(buf, hgs, e1, precedence[op]); } /************************************************************/ NegExp::NegExp(Loc loc, Expression *e) : UnaExp(loc, TOKneg, sizeof(NegExp), e) { } Expression *NegExp::semantic(Scope *sc) { Expression *e; #if LOGSEMANTIC printf("NegExp::semantic('%s')\n", toChars()); #endif if (!type) { UnaExp::semantic(sc); e1 = resolveProperties(sc, e1); e = op_overload(sc); if (e) return e; e1->checkNoBool(); if (e1->op != TOKslice) e1->checkArithmetic(); type = e1->type; } return this; } /************************************************************/ UAddExp::UAddExp(Loc loc, Expression *e) : UnaExp(loc, TOKuadd, sizeof(UAddExp), e) { } Expression *UAddExp::semantic(Scope *sc) { Expression *e; #if LOGSEMANTIC printf("UAddExp::semantic('%s')\n", toChars()); #endif assert(!type); UnaExp::semantic(sc); e1 = resolveProperties(sc, e1); e = op_overload(sc); if (e) return e; e1->checkNoBool(); e1->checkArithmetic(); return e1; } /************************************************************/ ComExp::ComExp(Loc loc, Expression *e) : UnaExp(loc, TOKtilde, sizeof(ComExp), e) { } Expression *ComExp::semantic(Scope *sc) { Expression *e; if (!type) { UnaExp::semantic(sc); e1 = resolveProperties(sc, e1); e = op_overload(sc); if (e) return e; e1->checkNoBool(); if (e1->op != TOKslice) e1 = e1->checkIntegral(); type = e1->type; } return this; } /************************************************************/ NotExp::NotExp(Loc loc, Expression *e) : UnaExp(loc, TOKnot, sizeof(NotExp), e) { } Expression *NotExp::semantic(Scope *sc) { UnaExp::semantic(sc); e1 = resolveProperties(sc, e1); e1 = e1->checkToBoolean(); type = Type::tboolean; return this; } int NotExp::isBit() { return TRUE; } /************************************************************/ BoolExp::BoolExp(Loc loc, Expression *e, Type *t) : UnaExp(loc, TOKtobool, sizeof(BoolExp), e) { type = t; } Expression *BoolExp::semantic(Scope *sc) { UnaExp::semantic(sc); e1 = resolveProperties(sc, e1); e1 = e1->checkToBoolean(); type = Type::tboolean; return this; } int BoolExp::isBit() { return TRUE; } /************************************************************/ DeleteExp::DeleteExp(Loc loc, Expression *e) : UnaExp(loc, TOKdelete, sizeof(DeleteExp), e) { } Expression *DeleteExp::semantic(Scope *sc) { Type *tb; UnaExp::semantic(sc); e1 = resolveProperties(sc, e1); e1 = e1->toLvalue(sc, NULL); type = Type::tvoid; tb = e1->type->toBasetype(); switch (tb->ty) { case Tclass: { TypeClass *tc = (TypeClass *)tb; ClassDeclaration *cd = tc->sym; if (cd->isCOMinterface()) { /* Because COM classes are deleted by IUnknown.Release() */ error("cannot delete instance of COM interface %s", cd->toChars()); } break; } case Tpointer: tb = ((TypePointer *)tb)->next->toBasetype(); if (tb->ty == Tstruct) { TypeStruct *ts = (TypeStruct *)tb; StructDeclaration *sd = ts->sym; FuncDeclaration *f = sd->aggDelete; FuncDeclaration *fd = sd->dtor; if (!f && !fd) break; /* Construct: * ea = copy e1 to a tmp to do side effects only once * eb = call destructor * ec = call deallocator */ Expression *ea = NULL; Expression *eb = NULL; Expression *ec = NULL; VarDeclaration *v; if (fd && f) { Identifier *id = Lexer::idPool("__tmp"); v = new VarDeclaration(loc, e1->type, id, new ExpInitializer(loc, e1)); v->semantic(sc); v->parent = sc->parent; ea = new DeclarationExp(loc, v); ea->type = v->type; } if (fd) { Expression *e = ea ? new VarExp(loc, v) : e1; e = new DotVarExp(0, e, fd, 0); eb = new CallExp(loc, e); eb = eb->semantic(sc); } if (f) { Type *tpv = Type::tvoid->pointerTo(); Expression *e = ea ? new VarExp(loc, v) : e1->castTo(sc, tpv); e = new CallExp(loc, new VarExp(loc, f), e); ec = e->semantic(sc); } ea = combine(ea, eb); ea = combine(ea, ec); assert(ea); return ea; } break; case Tarray: /* BUG: look for deleting arrays of structs with dtors. */ break; default: if (e1->op == TOKindex) { IndexExp *ae = (IndexExp *)(e1); Type *tb1 = ae->e1->type->toBasetype(); if (tb1->ty == Taarray) break; } error("cannot delete type %s", e1->type->toChars()); break; } if (e1->op == TOKindex) { IndexExp *ae = (IndexExp *)(e1); Type *tb1 = ae->e1->type->toBasetype(); if (tb1->ty == Taarray) { if (!global.params.useDeprecated) error("delete aa[key] deprecated, use aa.remove(key)"); } } return this; } int DeleteExp::checkSideEffect(int flag) { return 1; } Expression *DeleteExp::checkToBoolean() { error("delete does not give a boolean result"); return this; } void DeleteExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { buf->writestring("delete "); expToCBuffer(buf, hgs, e1, precedence[op]); } /************************************************************/ CastExp::CastExp(Loc loc, Expression *e, Type *t) : UnaExp(loc, TOKcast, sizeof(CastExp), e) { to = t; this->mod = ~0; } #if DMDV2 /* For cast(const) and cast(immutable) */ CastExp::CastExp(Loc loc, Expression *e, unsigned mod) : UnaExp(loc, TOKcast, sizeof(CastExp), e) { to = NULL; this->mod = mod; } #endif Expression *CastExp::syntaxCopy() { return to ? new CastExp(loc, e1->syntaxCopy(), to->syntaxCopy()) : new CastExp(loc, e1->syntaxCopy(), mod); } Expression *CastExp::semantic(Scope *sc) { Expression *e; BinExp *b; UnaExp *u; #if LOGSEMANTIC printf("CastExp::semantic('%s')\n", toChars()); #endif //static int x; assert(++x < 10); if (type) return this; UnaExp::semantic(sc); if (e1->type) // if not a tuple { e1 = resolveProperties(sc, e1); if (!to) { /* Handle cast(const) and cast(immutable), etc. */ to = e1->type->castMod(mod); } else to = to->semantic(loc, sc); if (!to->equals(e1->type)) { e = op_overload(sc); if (e) { return e->implicitCastTo(sc, to); } } Type *t1b = e1->type->toBasetype(); Type *tob = to->toBasetype(); if (tob->ty == Tstruct && !tob->equals(t1b) && ((TypeStruct *)tob)->sym->search(0, Id::call, 0) ) { /* Look to replace: * cast(S)t * with: * S(t) */ // Rewrite as to.call(e1) e = new TypeExp(loc, to); e = new DotIdExp(loc, e, Id::call); e = new CallExp(loc, e, e1); e = e->semantic(sc); return e; } } else if (!to) { error("cannot cast tuple"); to = Type::terror; } if (global.params.safe && !sc->module->safe && !sc->intypeof) { // Disallow unsafe casts Type *tob = to->toBasetype(); Type *t1b = e1->type->toBasetype(); if (!t1b->isMutable() && tob->isMutable()) { // Cast not mutable to mutable Lunsafe: error("cast from %s to %s not allowed in safe mode", e1->type->toChars(), to->toChars()); } else if (t1b->isShared() && !tob->isShared()) // Cast away shared goto Lunsafe; else if (tob->ty == Tpointer) { if (t1b->ty != Tpointer) goto Lunsafe; Type *tobn = tob->nextOf()->toBasetype(); Type *t1bn = t1b->nextOf()->toBasetype(); if (!t1bn->isMutable() && tobn->isMutable()) // Cast away pointer to not mutable goto Lunsafe; if (t1bn->isShared() && !tobn->isShared()) // Cast away pointer to shared goto Lunsafe; if (tobn->isTypeBasic() && tobn->size() < t1bn->size()) // Allow things like casting a long* to an int* ; else if (tobn->ty != Tvoid) // Cast to a pointer other than void* goto Lunsafe; } // BUG: Check for casting array types, such as void[] to int*[] } e = e1->castTo(sc, to); return e; } int CastExp::checkSideEffect(int flag) { /* if not: * cast(void) * cast(classtype)func() */ if (!to->equals(Type::tvoid) && !(to->ty == Tclass && e1->op == TOKcall && e1->type->ty == Tclass)) return Expression::checkSideEffect(flag); return 1; } void CastExp::checkEscape() { Type *tb = type->toBasetype(); if (tb->ty == Tarray && e1->op == TOKvar && e1->type->toBasetype()->ty == Tsarray) { VarExp *ve = (VarExp *)e1; VarDeclaration *v = ve->var->isVarDeclaration(); if (v) { if (!v->isDataseg() && !v->isParameter()) error("escaping reference to local %s", v->toChars()); } } } void CastExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { buf->writestring("cast("); #if DMDV1 to->toCBuffer(buf, NULL, hgs); #else if (to) to->toCBuffer(buf, NULL, hgs); else { switch (mod) { case 0: break; case MODconst: buf->writestring(Token::tochars[TOKconst]); break; case MODinvariant: buf->writestring(Token::tochars[TOKimmutable]); break; case MODshared: buf->writestring(Token::tochars[TOKshared]); break; case MODshared | MODconst: buf->writestring(Token::tochars[TOKshared]); buf->writeByte(' '); buf->writestring(Token::tochars[TOKconst]); break; default: assert(0); } } #endif buf->writeByte(')'); expToCBuffer(buf, hgs, e1, precedence[op]); } /************************************************************/ SliceExp::SliceExp(Loc loc, Expression *e1, Expression *lwr, Expression *upr) : UnaExp(loc, TOKslice, sizeof(SliceExp), e1) { this->upr = upr; this->lwr = lwr; lengthVar = NULL; } Expression *SliceExp::syntaxCopy() { Expression *lwr = NULL; if (this->lwr) lwr = this->lwr->syntaxCopy(); Expression *upr = NULL; if (this->upr) upr = this->upr->syntaxCopy(); return new SliceExp(loc, e1->syntaxCopy(), lwr, upr); } Expression *SliceExp::semantic(Scope *sc) { Expression *e; AggregateDeclaration *ad; //FuncDeclaration *fd; ScopeDsymbol *sym; #if LOGSEMANTIC printf("SliceExp::semantic('%s')\n", toChars()); #endif if (type) return this; UnaExp::semantic(sc); e1 = resolveProperties(sc, e1); e = this; Type *t = e1->type->toBasetype(); if (t->ty == Tpointer) { if (!lwr || !upr) error("need upper and lower bound to slice pointer"); } else if (t->ty == Tarray) { } else if (t->ty == Tsarray) { } else if (t->ty == Tclass) { ad = ((TypeClass *)t)->sym; goto L1; } else if (t->ty == Tstruct) { ad = ((TypeStruct *)t)->sym; L1: if (search_function(ad, Id::slice)) { // Rewrite as e1.slice(lwr, upr) e = new DotIdExp(loc, e1, Id::slice); if (lwr) { assert(upr); e = new CallExp(loc, e, lwr, upr); } else { assert(!upr); e = new CallExp(loc, e); } e = e->semantic(sc); return e; } goto Lerror; } else if (t->ty == Ttuple) { if (!lwr && !upr) return e1; if (!lwr || !upr) { error("need upper and lower bound to slice tuple"); goto Lerror; } } else goto Lerror; if (t->ty == Tsarray || t->ty == Tarray || t->ty == Ttuple) { sym = new ArrayScopeSymbol(sc, this); sym->loc = loc; sym->parent = sc->scopesym; sc = sc->push(sym); } if (lwr) { lwr = lwr->semantic(sc); lwr = resolveProperties(sc, lwr); lwr = lwr->implicitCastTo(sc, Type::tsize_t); } if (upr) { upr = upr->semantic(sc); upr = resolveProperties(sc, upr); upr = upr->implicitCastTo(sc, Type::tsize_t); } if (t->ty == Tsarray || t->ty == Tarray || t->ty == Ttuple) sc->pop(); if (t->ty == Ttuple) { lwr = lwr->optimize(WANTvalue); upr = upr->optimize(WANTvalue); uinteger_t i1 = lwr->toUInteger(); uinteger_t i2 = upr->toUInteger(); size_t length; TupleExp *te; TypeTuple *tup; if (e1->op == TOKtuple) // slicing an expression tuple { te = (TupleExp *)e1; length = te->exps->dim; } else if (e1->op == TOKtype) // slicing a type tuple { tup = (TypeTuple *)t; length = Argument::dim(tup->arguments); } else assert(0); if (i1 <= i2 && i2 <= length) { size_t j1 = (size_t) i1; size_t j2 = (size_t) i2; if (e1->op == TOKtuple) { Expressions *exps = new Expressions; exps->setDim(j2 - j1); for (size_t i = 0; i < j2 - j1; i++) { Expression *e = (Expression *)te->exps->data[j1 + i]; exps->data[i] = (void *)e; } e = new TupleExp(loc, exps); } else { Arguments *args = new Arguments; args->reserve(j2 - j1); for (size_t i = j1; i < j2; i++) { Argument *arg = Argument::getNth(tup->arguments, i); args->push(arg); } e = new TypeExp(e1->loc, new TypeTuple(args)); } e = e->semantic(sc); } else { error("string slice [%ju .. %ju] is out of bounds", i1, i2); e = new ErrorExp(); } return e; } if (t->ty == Tarray) { type = e1->type; } else type = t->nextOf()->arrayOf(); return e; Lerror: char *s; if (t->ty == Tvoid) s = e1->toChars(); else s = t->toChars(); error("%s cannot be sliced with []", s); e = new ErrorExp(); return e; } void SliceExp::checkEscape() { e1->checkEscape(); } #if DMDV2 int SliceExp::isLvalue() { return 1; } #endif Expression *SliceExp::toLvalue(Scope *sc, Expression *e) { return this; } Expression *SliceExp::modifiableLvalue(Scope *sc, Expression *e) { error("slice expression %s is not a modifiable lvalue", toChars()); return this; } void SliceExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { expToCBuffer(buf, hgs, e1, precedence[op]); buf->writeByte('['); if (upr || lwr) { if (lwr) expToCBuffer(buf, hgs, lwr, PREC_assign); else buf->writeByte('0'); buf->writestring(".."); if (upr) expToCBuffer(buf, hgs, upr, PREC_assign); else buf->writestring("length"); // BUG: should be array.length } buf->writeByte(']'); } /********************** ArrayLength **************************************/ ArrayLengthExp::ArrayLengthExp(Loc loc, Expression *e1) : UnaExp(loc, TOKarraylength, sizeof(ArrayLengthExp), e1) { } Expression *ArrayLengthExp::semantic(Scope *sc) { Expression *e; #if LOGSEMANTIC printf("ArrayLengthExp::semantic('%s')\n", toChars()); #endif if (!type) { UnaExp::semantic(sc); e1 = resolveProperties(sc, e1); type = Type::tsize_t; } return this; } void ArrayLengthExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { expToCBuffer(buf, hgs, e1, PREC_primary); buf->writestring(".length"); } /*********************** ArrayExp *************************************/ // e1 [ i1, i2, i3, ... ] ArrayExp::ArrayExp(Loc loc, Expression *e1, Expressions *args) : UnaExp(loc, TOKarray, sizeof(ArrayExp), e1) { arguments = args; } Expression *ArrayExp::syntaxCopy() { return new ArrayExp(loc, e1->syntaxCopy(), arraySyntaxCopy(arguments)); } Expression *ArrayExp::semantic(Scope *sc) { Expression *e; Type *t1; #if LOGSEMANTIC printf("ArrayExp::semantic('%s')\n", toChars()); #endif UnaExp::semantic(sc); e1 = resolveProperties(sc, e1); t1 = e1->type->toBasetype(); if (t1->ty != Tclass && t1->ty != Tstruct) { // Convert to IndexExp if (arguments->dim != 1) error("only one index allowed to index %s", t1->toChars()); e = new IndexExp(loc, e1, (Expression *)arguments->data[0]); return e->semantic(sc); } // Run semantic() on each argument for (size_t i = 0; i < arguments->dim; i++) { e = (Expression *)arguments->data[i]; e = e->semantic(sc); if (!e->type) error("%s has no value", e->toChars()); arguments->data[i] = (void *)e; } expandTuples(arguments); assert(arguments && arguments->dim); e = op_overload(sc); if (!e) { error("no [] operator overload for type %s", e1->type->toChars()); e = e1; } return e; } #if DMDV2 int ArrayExp::isLvalue() { if (type && type->toBasetype()->ty == Tvoid) return 0; return 1; } #endif Expression *ArrayExp::toLvalue(Scope *sc, Expression *e) { if (type && type->toBasetype()->ty == Tvoid) error("voids have no value"); return this; } void ArrayExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { int i; expToCBuffer(buf, hgs, e1, PREC_primary); buf->writeByte('['); argsToCBuffer(buf, arguments, hgs); buf->writeByte(']'); } /************************* DotExp ***********************************/ DotExp::DotExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKdotexp, sizeof(DotExp), e1, e2) { } Expression *DotExp::semantic(Scope *sc) { #if LOGSEMANTIC printf("DotExp::semantic('%s')\n", toChars()); if (type) printf("\ttype = %s\n", type->toChars()); #endif e1 = e1->semantic(sc); e2 = e2->semantic(sc); if (e2->op == TOKimport) { ScopeExp *se = (ScopeExp *)e2; TemplateDeclaration *td = se->sds->isTemplateDeclaration(); if (td) { Expression *e = new DotTemplateExp(loc, e1, td); e = e->semantic(sc); return e; } } if (!type) type = e2->type; return this; } /************************* CommaExp ***********************************/ CommaExp::CommaExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKcomma, sizeof(CommaExp), e1, e2) { } Expression *CommaExp::semantic(Scope *sc) { if (!type) { BinExp::semanticp(sc); type = e2->type; } return this; } void CommaExp::checkEscape() { e2->checkEscape(); } #if DMDV2 int CommaExp::isLvalue() { return e2->isLvalue(); } #endif Expression *CommaExp::toLvalue(Scope *sc, Expression *e) { e2 = e2->toLvalue(sc, NULL); return this; } Expression *CommaExp::modifiableLvalue(Scope *sc, Expression *e) { e2 = e2->modifiableLvalue(sc, e); return this; } int CommaExp::isBool(int result) { return e2->isBool(result); } int CommaExp::checkSideEffect(int flag) { if (flag == 2) return e1->checkSideEffect(2) || e2->checkSideEffect(2); else { // Don't check e1 until we cast(void) the a,b code generation return e2->checkSideEffect(flag); } } /************************** IndexExp **********************************/ // e1 [ e2 ] IndexExp::IndexExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKindex, sizeof(IndexExp), e1, e2) { //printf("IndexExp::IndexExp('%s')\n", toChars()); lengthVar = NULL; modifiable = 0; // assume it is an rvalue } Expression *IndexExp::semantic(Scope *sc) { Expression *e; BinExp *b; UnaExp *u; Type *t1; ScopeDsymbol *sym; #if LOGSEMANTIC printf("IndexExp::semantic('%s')\n", toChars()); #endif if (type) return this; if (!e1->type) e1 = e1->semantic(sc); assert(e1->type); // semantic() should already be run on it e = this; // Note that unlike C we do not implement the int[ptr] t1 = e1->type->toBasetype(); if (t1->ty == Tsarray || t1->ty == Tarray || t1->ty == Ttuple) { // Create scope for 'length' variable sym = new ArrayScopeSymbol(sc, this); sym->loc = loc; sym->parent = sc->scopesym; sc = sc->push(sym); } e2 = e2->semantic(sc); if (!e2->type) { error("%s has no value", e2->toChars()); e2->type = Type::terror; } e2 = resolveProperties(sc, e2); if (t1->ty == Tsarray || t1->ty == Tarray || t1->ty == Ttuple) sc = sc->pop(); switch (t1->ty) { case Tpointer: case Tarray: e2 = e2->implicitCastTo(sc, Type::tsize_t); e->type = ((TypeNext *)t1)->next; break; case Tsarray: { e2 = e2->implicitCastTo(sc, Type::tsize_t); TypeSArray *tsa = (TypeSArray *)t1; #if 0 // Don't do now, because it might be short-circuit evaluated // Do compile time array bounds checking if possible e2 = e2->optimize(WANTvalue); if (e2->op == TOKint64) { dinteger_t index = e2->toInteger(); dinteger_t length = tsa->dim->toInteger(); if (index < 0 || index >= length) error("array index [%lld] is outside array bounds [0 .. %lld]", index, length); } #endif e->type = t1->nextOf(); break; } case Taarray: { TypeAArray *taa = (TypeAArray *)t1; if (!arrayTypeCompatible(e2->loc, e2->type, taa->index)) { e2 = e2->implicitCastTo(sc, taa->index); // type checking } type = taa->next; break; } case Ttuple: { e2 = e2->implicitCastTo(sc, Type::tsize_t); e2 = e2->optimize(WANTvalue | WANTinterpret); uinteger_t index = e2->toUInteger(); size_t length; TupleExp *te; TypeTuple *tup; if (e1->op == TOKtuple) { te = (TupleExp *)e1; length = te->exps->dim; } else if (e1->op == TOKtype) { tup = (TypeTuple *)t1; length = Argument::dim(tup->arguments); } else assert(0); if (index < length) { if (e1->op == TOKtuple) e = (Expression *)te->exps->data[(size_t)index]; else e = new TypeExp(e1->loc, Argument::getNth(tup->arguments, (size_t)index)->type); } else { error("array index [%ju] is outside array bounds [0 .. %zu]", index, length); e = e1; } break; } default: error("%s must be an array or pointer type, not %s", e1->toChars(), e1->type->toChars()); type = Type::tint32; break; } return e; } #if DMDV2 int IndexExp::isLvalue() { return 1; } #endif Expression *IndexExp::toLvalue(Scope *sc, Expression *e) { // if (type && type->toBasetype()->ty == Tvoid) // error("voids have no value"); return this; } Expression *IndexExp::modifiableLvalue(Scope *sc, Expression *e) { //printf("IndexExp::modifiableLvalue(%s)\n", toChars()); modifiable = 1; if (e1->op == TOKstring) error("string literals are immutable"); if (type && !type->isMutable()) error("%s isn't mutable", e->toChars()); if (e1->type->toBasetype()->ty == Taarray) e1 = e1->modifiableLvalue(sc, e1); return toLvalue(sc, e); } void IndexExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { expToCBuffer(buf, hgs, e1, PREC_primary); buf->writeByte('['); expToCBuffer(buf, hgs, e2, PREC_assign); buf->writeByte(']'); } /************************* PostExp ***********************************/ PostExp::PostExp(enum TOK op, Loc loc, Expression *e) : BinExp(loc, op, sizeof(PostExp), e, new IntegerExp(loc, 1, Type::tint32)) { } Expression *PostExp::semantic(Scope *sc) { Expression *e = this; if (!type) { BinExp::semantic(sc); e2 = resolveProperties(sc, e2); e = op_overload(sc); if (e) return e; e = this; e1 = e1->modifiableLvalue(sc, e1); e1->checkScalar(); e1->checkNoBool(); if (e1->type->ty == Tpointer) e = scaleFactor(sc); else e2 = e2->castTo(sc, e1->type); e->type = e1->type; } return e; } void PostExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { expToCBuffer(buf, hgs, e1, precedence[op]); buf->writestring((op == TOKplusplus) ? (char *)"++" : (char *)"--"); } /************************************************************/ /* op can be TOKassign, TOKconstruct, or TOKblit */ AssignExp::AssignExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKassign, sizeof(AssignExp), e1, e2) { ismemset = 0; } Expression *AssignExp::semantic(Scope *sc) { Expression *e1old = e1; #if LOGSEMANTIC printf("AssignExp::semantic('%s')\n", toChars()); #endif //printf("e1->op = %d, '%s'\n", e1->op, Token::toChars(e1->op)); //printf("e2->op = %d, '%s'\n", e2->op, Token::toChars(e2->op)); if (type) return this; if (e2->op == TOKcomma) { /* Rewrite to get rid of the comma from rvalue */ AssignExp *ea = new AssignExp(loc, e1, ((CommaExp *)e2)->e2); ea->op = op; Expression *e = new CommaExp(loc, ((CommaExp *)e2)->e1, ea); return e->semantic(sc); } /* Look for operator overloading of a[i]=value. * Do it before semantic() otherwise the a[i] will have been * converted to a.opIndex() already. */ if (e1->op == TOKarray) { ArrayExp *ae = (ArrayExp *)e1; AggregateDeclaration *ad; Identifier *id = Id::index; ae->e1 = ae->e1->semantic(sc); Type *t1 = ae->e1->type->toBasetype(); if (t1->ty == Tstruct) { ad = ((TypeStruct *)t1)->sym; goto L1; } else if (t1->ty == Tclass) { ad = ((TypeClass *)t1)->sym; L1: // Rewrite (a[i] = value) to (a.opIndexAssign(value, i)) if (search_function(ad, Id::indexass)) { Expression *e = new DotIdExp(loc, ae->e1, Id::indexass); Expressions *a = (Expressions *)ae->arguments->copy(); a->insert(0, e2); e = new CallExp(loc, e, a); e = e->semantic(sc); return e; } else { // Rewrite (a[i] = value) to (a.opIndex(i, value)) if (search_function(ad, id)) { Expression *e = new DotIdExp(loc, ae->e1, id); if (1 || !global.params.useDeprecated) error("operator [] assignment overload with opIndex(i, value) illegal, use opIndexAssign(value, i)"); e = new CallExp(loc, e, (Expression *)ae->arguments->data[0], e2); e = e->semantic(sc); return e; } } } } /* Look for operator overloading of a[i..j]=value. * Do it before semantic() otherwise the a[i..j] will have been * converted to a.opSlice() already. */ if (e1->op == TOKslice) { Type *t1; SliceExp *ae = (SliceExp *)e1; AggregateDeclaration *ad; Identifier *id = Id::index; ae->e1 = ae->e1->semantic(sc); ae->e1 = resolveProperties(sc, ae->e1); t1 = ae->e1->type->toBasetype(); if (t1->ty == Tstruct) { ad = ((TypeStruct *)t1)->sym; goto L2; } else if (t1->ty == Tclass) { ad = ((TypeClass *)t1)->sym; L2: // Rewrite (a[i..j] = value) to (a.opIndexAssign(value, i, j)) if (search_function(ad, Id::sliceass)) { Expression *e = new DotIdExp(loc, ae->e1, Id::sliceass); Expressions *a = new Expressions(); a->push(e2); if (ae->lwr) { a->push(ae->lwr); assert(ae->upr); a->push(ae->upr); } else assert(!ae->upr); e = new CallExp(loc, e, a); e = e->semantic(sc); return e; } } } BinExp::semantic(sc); if (e1->op == TOKdottd) { // Rewrite a.b=e2, when b is a template, as a.b(e2) Expression *e = new CallExp(loc, e1, e2); e = e->semantic(sc); return e; } e2 = resolveProperties(sc, e2); assert(e1->type); /* Rewrite tuple assignment as a tuple of assignments. */ if (e1->op == TOKtuple && e2->op == TOKtuple) { TupleExp *tup1 = (TupleExp *)e1; TupleExp *tup2 = (TupleExp *)e2; size_t dim = tup1->exps->dim; if (dim != tup2->exps->dim) { error("mismatched tuple lengths, %d and %d", (int)dim, (int)tup2->exps->dim); } else { Expressions *exps = new Expressions; exps->setDim(dim); for (int i = 0; i < dim; i++) { Expression *ex1 = (Expression *)tup1->exps->data[i]; Expression *ex2 = (Expression *)tup2->exps->data[i]; exps->data[i] = (void *) new AssignExp(loc, ex1, ex2); } Expression *e = new TupleExp(loc, exps); e = e->semantic(sc); return e; } } Type *t1 = e1->type->toBasetype(); if (t1->ty == Tfunction) { // Rewrite f=value to f(value) Expression *e = new CallExp(loc, e1, e2); e = e->semantic(sc); return e; } /* If it is an assignment from a 'foreign' type, * check for operator overloading. */ if (t1->ty == Tstruct) { StructDeclaration *sd = ((TypeStruct *)t1)->sym; if (op == TOKassign) { Expression *e = op_overload(sc); if (e) return e; } else if (op == TOKconstruct) { Type *t2 = e2->type->toBasetype(); if (t2->ty == Tstruct && sd == ((TypeStruct *)t2)->sym && sd->cpctor) { /* We have a copy constructor for this */ if (e2->op == TOKvar || e2->op == TOKstar) { /* Write as: * e1.cpctor(e2); */ Expression *e = new DotVarExp(loc, e1, sd->cpctor, 0); e = new CallExp(loc, e, e2); return e->semantic(sc); } else if (e2->op == TOKquestion) { /* Write as: * a ? e1 = b : e1 = c; */ CondExp *ec = (CondExp *)e2; AssignExp *ea1 = new AssignExp(ec->e1->loc, e1, ec->e1); ea1->op = op; AssignExp *ea2 = new AssignExp(ec->e1->loc, e1, ec->e2); ea2->op = op; Expression *e = new CondExp(loc, ec->econd, ea1, ea2); return e->semantic(sc); } } } } else if (t1->ty == Tclass) { // Disallow assignment operator overloads for same type if (!e2->type->implicitConvTo(e1->type)) { Expression *e = op_overload(sc); if (e) return e; } } if (t1->ty == Tsarray) { // Convert e1 to e1[] Expression *e = new SliceExp(e1->loc, e1, NULL, NULL); e1 = e->semantic(sc); t1 = e1->type->toBasetype(); } e2->rvalue(); if (e1->op == TOKarraylength) { // e1 is not an lvalue, but we let code generator handle it ArrayLengthExp *ale = (ArrayLengthExp *)e1; ale->e1 = ale->e1->modifiableLvalue(sc, e1); } else if (e1->op == TOKslice) { Type *tn = e1->type->nextOf(); if (tn && !tn->isMutable() && op != TOKconstruct) error("slice %s is not mutable", e1->toChars()); } else { // Try to do a decent error message with the expression // before it got constant folded if (e1->op != TOKvar) e1 = e1->optimize(WANTvalue); if (op != TOKconstruct) e1 = e1->modifiableLvalue(sc, e1old); } Type *t2 = e2->type; if (e1->op == TOKslice && t1->nextOf() && e2->implicitConvTo(t1->nextOf()) ) { // memset ismemset = 1; // make it easy for back end to tell what this is e2 = e2->implicitCastTo(sc, t1->nextOf()); } else if (t1->ty == Tsarray) { /* Should have already converted e1 => e1[] */ assert(0); //error("cannot assign to static array %s", e1->toChars()); } else if (e1->op == TOKslice) { e2 = e2->implicitCastTo(sc, e1->type->constOf()); } else { e2 = e2->implicitCastTo(sc, e1->type); } /* Look for array operations */ if (e1->op == TOKslice && !ismemset && (e2->op == TOKadd || e2->op == TOKmin || e2->op == TOKmul || e2->op == TOKdiv || e2->op == TOKmod || e2->op == TOKxor || e2->op == TOKand || e2->op == TOKor || e2->op == TOKtilde || e2->op == TOKneg)) { type = e1->type; return arrayOp(sc); } type = e1->type; assert(type); return this; } Expression *AssignExp::checkToBoolean() { // Things like: // if (a = b) ... // are usually mistakes. error("'=' does not give a boolean result"); return this; } /************************************************************/ AddAssignExp::AddAssignExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKaddass, sizeof(AddAssignExp), e1, e2) { } Expression *AddAssignExp::semantic(Scope *sc) { Expression *e; if (type) return this; BinExp::semantic(sc); e2 = resolveProperties(sc, e2); e = op_overload(sc); if (e) return e; Type *tb1 = e1->type->toBasetype(); Type *tb2 = e2->type->toBasetype(); if (e1->op == TOKslice) { typeCombine(sc); type = e1->type; return arrayOp(sc); } else { e1 = e1->modifiableLvalue(sc, e1); } if ((tb1->ty == Tarray || tb1->ty == Tsarray) && (tb2->ty == Tarray || tb2->ty == Tsarray) && tb1->nextOf()->equals(tb2->nextOf()) ) { type = e1->type; typeCombine(sc); e = this; } else { e1->checkScalar(); e1->checkNoBool(); if (tb1->ty == Tpointer && tb2->isintegral()) e = scaleFactor(sc); else if (tb1->ty == Tbit || tb1->ty == Tbool) { #if 0 // Need to rethink this if (e1->op != TOKvar) { // Rewrite e1+=e2 to (v=&e1),*v=*v+e2 VarDeclaration *v; Expression *ea; Expression *ex; Identifier *id = Lexer::uniqueId("__name"); v = new VarDeclaration(loc, tb1->pointerTo(), id, NULL); v->semantic(sc); if (!sc->insert(v)) assert(0); v->parent = sc->func; ea = new AddrExp(loc, e1); ea = new AssignExp(loc, new VarExp(loc, v), ea); ex = new VarExp(loc, v); ex = new PtrExp(loc, ex); e = new AddExp(loc, ex, e2); e = new CastExp(loc, e, e1->type); e = new AssignExp(loc, ex->syntaxCopy(), e); e = new CommaExp(loc, ea, e); } else #endif { // Rewrite e1+=e2 to e1=e1+e2 // BUG: doesn't account for side effects in e1 // BUG: other assignment operators for bits aren't handled at all e = new AddExp(loc, e1, e2); e = new CastExp(loc, e, e1->type); e = new AssignExp(loc, e1->syntaxCopy(), e); } e = e->semantic(sc); } else { type = e1->type; typeCombine(sc); e1->checkArithmetic(); e2->checkArithmetic(); if (type->isreal() || type->isimaginary()) { assert(global.errors || e2->type->isfloating()); e2 = e2->castTo(sc, e1->type); } e = this; } } return e; } /************************************************************/ MinAssignExp::MinAssignExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKminass, sizeof(MinAssignExp), e1, e2) { } Expression *MinAssignExp::semantic(Scope *sc) { Expression *e; if (type) return this; BinExp::semantic(sc); e2 = resolveProperties(sc, e2); e = op_overload(sc); if (e) return e; if (e1->op == TOKslice) { // T[] -= ... typeCombine(sc); type = e1->type; return arrayOp(sc); } e1 = e1->modifiableLvalue(sc, e1); e1->checkScalar(); e1->checkNoBool(); if (e1->type->ty == Tpointer && e2->type->isintegral()) e = scaleFactor(sc); else { e1 = e1->checkArithmetic(); e2 = e2->checkArithmetic(); type = e1->type; typeCombine(sc); if (type->isreal() || type->isimaginary()) { assert(e2->type->isfloating()); e2 = e2->castTo(sc, e1->type); } e = this; } return e; } /************************************************************/ CatAssignExp::CatAssignExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKcatass, sizeof(CatAssignExp), e1, e2) { } Expression *CatAssignExp::semantic(Scope *sc) { Expression *e; BinExp::semantic(sc); e2 = resolveProperties(sc, e2); e = op_overload(sc); if (e) return e; if (e1->op == TOKslice) { SliceExp *se = (SliceExp *)e1; if (se->e1->type->toBasetype()->ty == Tsarray) error("cannot append to static array %s", se->e1->type->toChars()); } e1 = e1->modifiableLvalue(sc, e1); Type *tb1 = e1->type->toBasetype(); Type *tb2 = e2->type->toBasetype(); e2->rvalue(); if ((tb1->ty == Tarray) && (tb2->ty == Tarray || tb2->ty == Tsarray) && (e2->implicitConvTo(e1->type) || tb2->nextOf()->implicitConvTo(tb1->nextOf())) ) { // Append array e2 = e2->castTo(sc, e1->type); type = e1->type; e = this; } else if ((tb1->ty == Tarray) && e2->implicitConvTo(tb1->nextOf()) ) { // Append element e2 = e2->castTo(sc, tb1->nextOf()); type = e1->type; e = this; } else { error("cannot append type %s to type %s", tb2->toChars(), tb1->toChars()); type = Type::tint32; e = this; } return e; } /************************************************************/ MulAssignExp::MulAssignExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKmulass, sizeof(MulAssignExp), e1, e2) { } Expression *MulAssignExp::semantic(Scope *sc) { Expression *e; BinExp::semantic(sc); e2 = resolveProperties(sc, e2); e = op_overload(sc); if (e) return e; if (e1->op == TOKslice) { // T[] -= ... typeCombine(sc); type = e1->type; return arrayOp(sc); } e1 = e1->modifiableLvalue(sc, e1); e1->checkScalar(); e1->checkNoBool(); type = e1->type; typeCombine(sc); e1->checkArithmetic(); e2->checkArithmetic(); if (e2->type->isfloating()) { Type *t1; Type *t2; t1 = e1->type; t2 = e2->type; if (t1->isreal()) { if (t2->isimaginary() || t2->iscomplex()) { e2 = e2->castTo(sc, t1); } } else if (t1->isimaginary()) { if (t2->isimaginary() || t2->iscomplex()) { switch (t1->ty) { case Timaginary32: t2 = Type::tfloat32; break; case Timaginary64: t2 = Type::tfloat64; break; case Timaginary80: t2 = Type::tfloat80; break; default: assert(0); } e2 = e2->castTo(sc, t2); } } } return this; } /************************************************************/ DivAssignExp::DivAssignExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKdivass, sizeof(DivAssignExp), e1, e2) { } Expression *DivAssignExp::semantic(Scope *sc) { Expression *e; BinExp::semantic(sc); e2 = resolveProperties(sc, e2); e = op_overload(sc); if (e) return e; if (e1->op == TOKslice) { // T[] -= ... typeCombine(sc); type = e1->type; return arrayOp(sc); } e1 = e1->modifiableLvalue(sc, e1); e1->checkScalar(); e1->checkNoBool(); type = e1->type; typeCombine(sc); e1->checkArithmetic(); e2->checkArithmetic(); if (e2->type->isimaginary()) { Type *t1; Type *t2; t1 = e1->type; if (t1->isreal()) { // x/iv = i(-x/v) // Therefore, the result is 0 e2 = new CommaExp(loc, e2, new RealExp(loc, 0, t1)); e2->type = t1; e = new AssignExp(loc, e1, e2); e->type = t1; return e; } else if (t1->isimaginary()) { Expression *e; switch (t1->ty) { case Timaginary32: t2 = Type::tfloat32; break; case Timaginary64: t2 = Type::tfloat64; break; case Timaginary80: t2 = Type::tfloat80; break; default: assert(0); } e2 = e2->castTo(sc, t2); e = new AssignExp(loc, e1, e2); e->type = t1; return e; } } return this; } /************************************************************/ ModAssignExp::ModAssignExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKmodass, sizeof(ModAssignExp), e1, e2) { } Expression *ModAssignExp::semantic(Scope *sc) { return commonSemanticAssign(sc); } /************************************************************/ ShlAssignExp::ShlAssignExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKshlass, sizeof(ShlAssignExp), e1, e2) { } Expression *ShlAssignExp::semantic(Scope *sc) { Expression *e; //printf("ShlAssignExp::semantic()\n"); BinExp::semantic(sc); e2 = resolveProperties(sc, e2); e = op_overload(sc); if (e) return e; e1 = e1->modifiableLvalue(sc, e1); e1->checkScalar(); e1->checkNoBool(); type = e1->type; typeCombine(sc); e1->checkIntegral(); e2 = e2->checkIntegral(); e2 = e2->castTo(sc, Type::tshiftcnt); return this; } /************************************************************/ ShrAssignExp::ShrAssignExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKshrass, sizeof(ShrAssignExp), e1, e2) { } Expression *ShrAssignExp::semantic(Scope *sc) { Expression *e; BinExp::semantic(sc); e2 = resolveProperties(sc, e2); e = op_overload(sc); if (e) return e; e1 = e1->modifiableLvalue(sc, e1); e1->checkScalar(); e1->checkNoBool(); type = e1->type; typeCombine(sc); e1->checkIntegral(); e2 = e2->checkIntegral(); e2 = e2->castTo(sc, Type::tshiftcnt); return this; } /************************************************************/ UshrAssignExp::UshrAssignExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKushrass, sizeof(UshrAssignExp), e1, e2) { } Expression *UshrAssignExp::semantic(Scope *sc) { Expression *e; BinExp::semantic(sc); e2 = resolveProperties(sc, e2); e = op_overload(sc); if (e) return e; e1 = e1->modifiableLvalue(sc, e1); e1->checkScalar(); e1->checkNoBool(); type = e1->type; typeCombine(sc); e1->checkIntegral(); e2 = e2->checkIntegral(); e2 = e2->castTo(sc, Type::tshiftcnt); return this; } /************************************************************/ AndAssignExp::AndAssignExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKandass, sizeof(AndAssignExp), e1, e2) { } Expression *AndAssignExp::semantic(Scope *sc) { return commonSemanticAssignIntegral(sc); } /************************************************************/ OrAssignExp::OrAssignExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKorass, sizeof(OrAssignExp), e1, e2) { } Expression *OrAssignExp::semantic(Scope *sc) { return commonSemanticAssignIntegral(sc); } /************************************************************/ XorAssignExp::XorAssignExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKxorass, sizeof(XorAssignExp), e1, e2) { } Expression *XorAssignExp::semantic(Scope *sc) { return commonSemanticAssignIntegral(sc); } /************************* AddExp *****************************/ AddExp::AddExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKadd, sizeof(AddExp), e1, e2) { } Expression *AddExp::semantic(Scope *sc) { Expression *e; #if LOGSEMANTIC printf("AddExp::semantic('%s')\n", toChars()); #endif if (!type) { BinExp::semanticp(sc); e = op_overload(sc); if (e) return e; Type *tb1 = e1->type->toBasetype(); Type *tb2 = e2->type->toBasetype(); if ((tb1->ty == Tarray || tb1->ty == Tsarray) && (tb2->ty == Tarray || tb2->ty == Tsarray) && tb1->nextOf()->equals(tb2->nextOf()) ) { type = e1->type; e = this; } else if (tb1->ty == Tpointer && e2->type->isintegral() || tb2->ty == Tpointer && e1->type->isintegral()) e = scaleFactor(sc); else if (tb1->ty == Tpointer && tb2->ty == Tpointer) { incompatibleTypes(); type = e1->type; e = this; } else { typeCombine(sc); if ((e1->type->isreal() && e2->type->isimaginary()) || (e1->type->isimaginary() && e2->type->isreal())) { switch (type->toBasetype()->ty) { case Tfloat32: case Timaginary32: type = Type::tcomplex32; break; case Tfloat64: case Timaginary64: type = Type::tcomplex64; break; case Tfloat80: case Timaginary80: type = Type::tcomplex80; break; default: assert(0); } } e = this; } return e; } return this; } /************************************************************/ MinExp::MinExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKmin, sizeof(MinExp), e1, e2) { } Expression *MinExp::semantic(Scope *sc) { Expression *e; Type *t1; Type *t2; #if LOGSEMANTIC printf("MinExp::semantic('%s')\n", toChars()); #endif if (type) return this; BinExp::semanticp(sc); e = op_overload(sc); if (e) return e; e = this; t1 = e1->type->toBasetype(); t2 = e2->type->toBasetype(); if (t1->ty == Tpointer) { if (t2->ty == Tpointer) { // Need to divide the result by the stride // Replace (ptr - ptr) with (ptr - ptr) / stride d_int64 stride; Expression *e; typeCombine(sc); // make sure pointer types are compatible type = Type::tptrdiff_t; stride = t2->nextOf()->size(); if (stride == 0) { e = new IntegerExp(loc, 0, Type::tptrdiff_t); } else { e = new DivExp(loc, this, new IntegerExp(0, stride, Type::tptrdiff_t)); e->type = Type::tptrdiff_t; } return e; } else if (t2->isintegral()) e = scaleFactor(sc); else { error("incompatible types for minus"); return new ErrorExp(); } } else if (t2->ty == Tpointer) { type = e2->type; error("can't subtract pointer from %s", e1->type->toChars()); return new ErrorExp(); } else { typeCombine(sc); t1 = e1->type->toBasetype(); t2 = e2->type->toBasetype(); if ((t1->isreal() && t2->isimaginary()) || (t1->isimaginary() && t2->isreal())) { switch (type->ty) { case Tfloat32: case Timaginary32: type = Type::tcomplex32; break; case Tfloat64: case Timaginary64: type = Type::tcomplex64; break; case Tfloat80: case Timaginary80: type = Type::tcomplex80; break; default: assert(0); } } } return e; } /************************* CatExp *****************************/ CatExp::CatExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKcat, sizeof(CatExp), e1, e2) { } Expression *CatExp::semantic(Scope *sc) { Expression *e; //printf("CatExp::semantic() %s\n", toChars()); if (!type) { BinExp::semanticp(sc); e = op_overload(sc); if (e) return e; Type *tb1 = e1->type->toBasetype(); Type *tb2 = e2->type->toBasetype(); /* BUG: Should handle things like: * char c; * c ~ ' ' * ' ' ~ c; */ #if 0 e1->type->print(); e2->type->print(); #endif if ((tb1->ty == Tsarray || tb1->ty == Tarray) && e2->type->implicitConvTo(tb1->nextOf()) >= MATCHconst) { type = tb1->nextOf()->arrayOf(); if (tb2->ty == Tarray) { // Make e2 into [e2] e2 = new ArrayLiteralExp(e2->loc, e2); e2->type = type; } return this; } else if ((tb2->ty == Tsarray || tb2->ty == Tarray) && e1->type->implicitConvTo(tb2->nextOf()) >= MATCHconst) { type = tb2->nextOf()->arrayOf(); if (tb1->ty == Tarray) { // Make e1 into [e1] e1 = new ArrayLiteralExp(e1->loc, e1); e1->type = type; } return this; } if ((tb1->ty == Tsarray || tb1->ty == Tarray) && (tb2->ty == Tsarray || tb2->ty == Tarray) && (tb1->nextOf()->mod || tb2->nextOf()->mod) && (tb1->nextOf()->mod != tb2->nextOf()->mod) ) { Type *t1 = tb1->nextOf()->mutableOf()->constOf()->arrayOf(); Type *t2 = tb2->nextOf()->mutableOf()->constOf()->arrayOf(); if (e1->op == TOKstring && !((StringExp *)e1)->committed) e1->type = t1; else e1 = e1->castTo(sc, t1); if (e2->op == TOKstring && !((StringExp *)e2)->committed) e2->type = t2; else e2 = e2->castTo(sc, t2); } typeCombine(sc); type = type->toHeadMutable(); Type *tb = type->toBasetype(); if (tb->ty == Tsarray) type = tb->nextOf()->arrayOf(); if (type->ty == Tarray && tb1->nextOf() && tb2->nextOf() && tb1->nextOf()->mod != tb2->nextOf()->mod) { type = type->nextOf()->toHeadMutable()->arrayOf(); } #if 0 e1->type->print(); e2->type->print(); type->print(); print(); #endif Type *t1 = e1->type->toBasetype(); Type *t2 = e2->type->toBasetype(); if (e1->op == TOKstring && e2->op == TOKstring) e = optimize(WANTvalue); else if ((t1->ty == Tarray || t1->ty == Tsarray) && (t2->ty == Tarray || t2->ty == Tsarray)) { e = this; } else { //printf("(%s) ~ (%s)\n", e1->toChars(), e2->toChars()); error("Can only concatenate arrays, not (%s ~ %s)", e1->type->toChars(), e2->type->toChars()); type = Type::tint32; e = this; } e->type = e->type->semantic(loc, sc); return e; } return this; } /************************************************************/ MulExp::MulExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKmul, sizeof(MulExp), e1, e2) { } Expression *MulExp::semantic(Scope *sc) { Expression *e; #if 0 printf("MulExp::semantic() %s\n", toChars()); #endif if (type) { return this; } BinExp::semanticp(sc); e = op_overload(sc); if (e) return e; typeCombine(sc); if (e1->op != TOKslice && e2->op != TOKslice) { e1->checkArithmetic(); e2->checkArithmetic(); } if (type->isfloating()) { Type *t1 = e1->type; Type *t2 = e2->type; if (t1->isreal()) { type = t2; } else if (t2->isreal()) { type = t1; } else if (t1->isimaginary()) { if (t2->isimaginary()) { Expression *e; switch (t1->ty) { case Timaginary32: type = Type::tfloat32; break; case Timaginary64: type = Type::tfloat64; break; case Timaginary80: type = Type::tfloat80; break; default: assert(0); } // iy * iv = -yv e1->type = type; e2->type = type; e = new NegExp(loc, this); e = e->semantic(sc); return e; } else type = t2; // t2 is complex } else if (t2->isimaginary()) { type = t1; // t1 is complex } } return this; } /************************************************************/ DivExp::DivExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKdiv, sizeof(DivExp), e1, e2) { } Expression *DivExp::semantic(Scope *sc) { Expression *e; if (type) return this; BinExp::semanticp(sc); e = op_overload(sc); if (e) return e; typeCombine(sc); if (e1->op != TOKslice && e2->op != TOKslice) { e1->checkArithmetic(); e2->checkArithmetic(); } if (type->isfloating()) { Type *t1 = e1->type; Type *t2 = e2->type; if (t1->isreal()) { type = t2; if (t2->isimaginary()) { Expression *e; // x/iv = i(-x/v) e2->type = t1; e = new NegExp(loc, this); e = e->semantic(sc); return e; } } else if (t2->isreal()) { type = t1; } else if (t1->isimaginary()) { if (t2->isimaginary()) { switch (t1->ty) { case Timaginary32: type = Type::tfloat32; break; case Timaginary64: type = Type::tfloat64; break; case Timaginary80: type = Type::tfloat80; break; default: assert(0); } } else type = t2; // t2 is complex } else if (t2->isimaginary()) { type = t1; // t1 is complex } } return this; } /************************************************************/ ModExp::ModExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKmod, sizeof(ModExp), e1, e2) { } Expression *ModExp::semantic(Scope *sc) { Expression *e; if (type) return this; BinExp::semanticp(sc); e = op_overload(sc); if (e) return e; typeCombine(sc); if (e1->op != TOKslice && e2->op != TOKslice) { e1->checkArithmetic(); e2->checkArithmetic(); } if (type->isfloating()) { type = e1->type; if (e2->type->iscomplex()) { error("cannot perform modulo complex arithmetic"); return new ErrorExp(); } } return this; } /************************************************************/ ShlExp::ShlExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKshl, sizeof(ShlExp), e1, e2) { } Expression *ShlExp::semantic(Scope *sc) { Expression *e; //printf("ShlExp::semantic(), type = %p\n", type); if (!type) { BinExp::semanticp(sc); e = op_overload(sc); if (e) return e; e1 = e1->checkIntegral(); e2 = e2->checkIntegral(); e1 = e1->integralPromotions(sc); e2 = e2->castTo(sc, Type::tshiftcnt); type = e1->type; } return this; } /************************************************************/ ShrExp::ShrExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKshr, sizeof(ShrExp), e1, e2) { } Expression *ShrExp::semantic(Scope *sc) { Expression *e; if (!type) { BinExp::semanticp(sc); e = op_overload(sc); if (e) return e; e1 = e1->checkIntegral(); e2 = e2->checkIntegral(); e1 = e1->integralPromotions(sc); e2 = e2->castTo(sc, Type::tshiftcnt); type = e1->type; } return this; } /************************************************************/ UshrExp::UshrExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKushr, sizeof(UshrExp), e1, e2) { } Expression *UshrExp::semantic(Scope *sc) { Expression *e; if (!type) { BinExp::semanticp(sc); e = op_overload(sc); if (e) return e; e1 = e1->checkIntegral(); e2 = e2->checkIntegral(); e1 = e1->integralPromotions(sc); e2 = e2->castTo(sc, Type::tshiftcnt); type = e1->type; } return this; } /************************************************************/ AndExp::AndExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKand, sizeof(AndExp), e1, e2) { } Expression *AndExp::semantic(Scope *sc) { Expression *e; if (!type) { BinExp::semanticp(sc); e = op_overload(sc); if (e) return e; if (e1->type->toBasetype()->ty == Tbool && e2->type->toBasetype()->ty == Tbool) { type = e1->type; e = this; } else { typeCombine(sc); if (e1->op != TOKslice && e2->op != TOKslice) { e1->checkIntegral(); e2->checkIntegral(); } } } return this; } /************************************************************/ OrExp::OrExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKor, sizeof(OrExp), e1, e2) { } Expression *OrExp::semantic(Scope *sc) { Expression *e; if (!type) { BinExp::semanticp(sc); e = op_overload(sc); if (e) return e; if (e1->type->toBasetype()->ty == Tbool && e2->type->toBasetype()->ty == Tbool) { type = e1->type; e = this; } else { typeCombine(sc); if (e1->op != TOKslice && e2->op != TOKslice) { e1->checkIntegral(); e2->checkIntegral(); } } } return this; } /************************************************************/ XorExp::XorExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKxor, sizeof(XorExp), e1, e2) { } Expression *XorExp::semantic(Scope *sc) { Expression *e; if (!type) { BinExp::semanticp(sc); e = op_overload(sc); if (e) return e; if (e1->type->toBasetype()->ty == Tbool && e2->type->toBasetype()->ty == Tbool) { type = e1->type; e = this; } else { typeCombine(sc); if (e1->op != TOKslice && e2->op != TOKslice) { e1->checkIntegral(); e2->checkIntegral(); } } } return this; } /************************************************************/ OrOrExp::OrOrExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKoror, sizeof(OrOrExp), e1, e2) { } Expression *OrOrExp::semantic(Scope *sc) { unsigned cs1; // same as for AndAnd e1 = e1->semantic(sc); e1 = resolveProperties(sc, e1); e1 = e1->checkToPointer(); e1 = e1->checkToBoolean(); cs1 = sc->callSuper; if (sc->flags & SCOPEstaticif) { /* If in static if, don't evaluate e2 if we don't have to. */ e1 = e1->optimize(WANTflags); if (e1->isBool(TRUE)) { return new IntegerExp(loc, 1, Type::tboolean); } } e2 = e2->semantic(sc); sc->mergeCallSuper(loc, cs1); e2 = resolveProperties(sc, e2); e2 = e2->checkToPointer(); type = Type::tboolean; if (e2->type->ty == Tvoid) type = Type::tvoid; if (e2->op == TOKtype || e2->op == TOKimport) error("%s is not an expression", e2->toChars()); return this; } Expression *OrOrExp::checkToBoolean() { e2 = e2->checkToBoolean(); return this; } int OrOrExp::isBit() { return TRUE; } int OrOrExp::checkSideEffect(int flag) { if (flag == 2) { return e1->checkSideEffect(2) || e2->checkSideEffect(2); } else { e1->checkSideEffect(1); return e2->checkSideEffect(flag); } } /************************************************************/ AndAndExp::AndAndExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKandand, sizeof(AndAndExp), e1, e2) { } Expression *AndAndExp::semantic(Scope *sc) { unsigned cs1; // same as for OrOr e1 = e1->semantic(sc); e1 = resolveProperties(sc, e1); e1 = e1->checkToPointer(); e1 = e1->checkToBoolean(); cs1 = sc->callSuper; if (sc->flags & SCOPEstaticif) { /* If in static if, don't evaluate e2 if we don't have to. */ e1 = e1->optimize(WANTflags); if (e1->isBool(FALSE)) { return new IntegerExp(loc, 0, Type::tboolean); } } e2 = e2->semantic(sc); sc->mergeCallSuper(loc, cs1); e2 = resolveProperties(sc, e2); e2 = e2->checkToPointer(); type = Type::tboolean; if (e2->type->ty == Tvoid) type = Type::tvoid; if (e2->op == TOKtype || e2->op == TOKimport) error("%s is not an expression", e2->toChars()); return this; } Expression *AndAndExp::checkToBoolean() { e2 = e2->checkToBoolean(); return this; } int AndAndExp::isBit() { return TRUE; } int AndAndExp::checkSideEffect(int flag) { if (flag == 2) { return e1->checkSideEffect(2) || e2->checkSideEffect(2); } else { e1->checkSideEffect(1); return e2->checkSideEffect(flag); } } /************************************************************/ InExp::InExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKin, sizeof(InExp), e1, e2) { } Expression *InExp::semantic(Scope *sc) { Expression *e; if (type) return this; BinExp::semanticp(sc); e = op_overload(sc); if (e) return e; //type = Type::tboolean; Type *t2b = e2->type->toBasetype(); if (t2b->ty != Taarray) { error("rvalue of in expression must be an associative array, not %s", e2->type->toChars()); type = Type::terror; } else { TypeAArray *ta = (TypeAArray *)t2b; // Special handling for array keys if (!arrayTypeCompatible(e1->loc, e1->type, ta->index)) { // Convert key to type of key e1 = e1->implicitCastTo(sc, ta->index); } // Return type is pointer to value type = ta->nextOf()->pointerTo(); } return this; } int InExp::isBit() { return FALSE; } /************************************************************/ /* This deletes the key e1 from the associative array e2 */ RemoveExp::RemoveExp(Loc loc, Expression *e1, Expression *e2) : BinExp(loc, TOKremove, sizeof(RemoveExp), e1, e2) { type = Type::tvoid; } /************************************************************/ CmpExp::CmpExp(enum TOK op, Loc loc, Expression *e1, Expression *e2) : BinExp(loc, op, sizeof(CmpExp), e1, e2) { } Expression *CmpExp::semantic(Scope *sc) { Expression *e; Type *t1; Type *t2; #if LOGSEMANTIC printf("CmpExp::semantic('%s')\n", toChars()); #endif if (type) return this; BinExp::semanticp(sc); if (e1->type->toBasetype()->ty == Tclass && e2->op == TOKnull || e2->type->toBasetype()->ty == Tclass && e1->op == TOKnull) { error("do not use null when comparing class types"); } e = op_overload(sc); if (e) { if (!e->type->isscalar() && e->type->equals(e1->type)) { error("recursive opCmp expansion"); e = new ErrorExp(); } else { e = new CmpExp(op, loc, e, new IntegerExp(loc, 0, Type::tint32)); e = e->semantic(sc); } return e; } typeCombine(sc); type = Type::tboolean; // Special handling for array comparisons t1 = e1->type->toBasetype(); t2 = e2->type->toBasetype(); if ((t1->ty == Tarray || t1->ty == Tsarray || t1->ty == Tpointer) && (t2->ty == Tarray || t2->ty == Tsarray || t2->ty == Tpointer)) { if (t1->nextOf()->implicitConvTo(t2->nextOf()) < MATCHconst && t2->nextOf()->implicitConvTo(t1->nextOf()) < MATCHconst && (t1->nextOf()->ty != Tvoid && t2->nextOf()->ty != Tvoid)) error("array comparison type mismatch, %s vs %s", t1->nextOf()->toChars(), t2->nextOf()->toChars()); e = this; } else if (t1->ty == Tstruct || t2->ty == Tstruct || (t1->ty == Tclass && t2->ty == Tclass)) { if (t2->ty == Tstruct) error("need member function opCmp() for %s %s to compare", t2->toDsymbol(sc)->kind(), t2->toChars()); else error("need member function opCmp() for %s %s to compare", t1->toDsymbol(sc)->kind(), t1->toChars()); e = this; } #if 1 else if (t1->iscomplex() || t2->iscomplex()) { error("compare not defined for complex operands"); e = new ErrorExp(); } #endif else { e1->rvalue(); e2->rvalue(); e = this; } //printf("CmpExp: %s, type = %s\n", e->toChars(), e->type->toChars()); return e; } int CmpExp::isBit() { return TRUE; } /************************************************************/ EqualExp::EqualExp(enum TOK op, Loc loc, Expression *e1, Expression *e2) : BinExp(loc, op, sizeof(EqualExp), e1, e2) { assert(op == TOKequal || op == TOKnotequal); } Expression *EqualExp::semantic(Scope *sc) { Expression *e; Type *t1; Type *t2; //printf("EqualExp::semantic('%s')\n", toChars()); if (type) return this; BinExp::semanticp(sc); /* Before checking for operator overloading, check to see if we're * comparing the addresses of two statics. If so, we can just see * if they are the same symbol. */ if (e1->op == TOKaddress && e2->op == TOKaddress) { AddrExp *ae1 = (AddrExp *)e1; AddrExp *ae2 = (AddrExp *)e2; if (ae1->e1->op == TOKvar && ae2->e1->op == TOKvar) { VarExp *ve1 = (VarExp *)ae1->e1; VarExp *ve2 = (VarExp *)ae2->e1; if (ve1->var == ve2->var /*|| ve1->var->toSymbol() == ve2->var->toSymbol()*/) { // They are the same, result is 'true' for ==, 'false' for != e = new IntegerExp(loc, (op == TOKequal), Type::tboolean); return e; } } } if (e1->type->toBasetype()->ty == Tclass && e2->op == TOKnull || e2->type->toBasetype()->ty == Tclass && e1->op == TOKnull) { error("use '%s' instead of '%s' when comparing with null", Token::toChars(op == TOKequal ? TOKidentity : TOKnotidentity), Token::toChars(op)); } //if (e2->op != TOKnull) { e = op_overload(sc); if (e) { if (op == TOKnotequal) { e = new NotExp(e->loc, e); e = e->semantic(sc); } return e; } } e = typeCombine(sc); type = Type::tboolean; // Special handling for array comparisons if (!arrayTypeCompatible(loc, e1->type, e2->type)) { if (e1->type != e2->type && e1->type->isfloating() && e2->type->isfloating()) { // Cast both to complex e1 = e1->castTo(sc, Type::tcomplex80); e2 = e2->castTo(sc, Type::tcomplex80); } } return e; } int EqualExp::isBit() { return TRUE; } /************************************************************/ IdentityExp::IdentityExp(enum TOK op, Loc loc, Expression *e1, Expression *e2) : BinExp(loc, op, sizeof(IdentityExp), e1, e2) { } Expression *IdentityExp::semantic(Scope *sc) { if (type) return this; BinExp::semanticp(sc); type = Type::tboolean; typeCombine(sc); if (e1->type != e2->type && e1->type->isfloating() && e2->type->isfloating()) { // Cast both to complex e1 = e1->castTo(sc, Type::tcomplex80); e2 = e2->castTo(sc, Type::tcomplex80); } return this; } int IdentityExp::isBit() { return TRUE; } /****************************************************************/ CondExp::CondExp(Loc loc, Expression *econd, Expression *e1, Expression *e2) : BinExp(loc, TOKquestion, sizeof(CondExp), e1, e2) { this->econd = econd; } Expression *CondExp::syntaxCopy() { return new CondExp(loc, econd->syntaxCopy(), e1->syntaxCopy(), e2->syntaxCopy()); } Expression *CondExp::semantic(Scope *sc) { Type *t1; Type *t2; unsigned cs0; unsigned cs1; #if LOGSEMANTIC printf("CondExp::semantic('%s')\n", toChars()); #endif if (type) return this; econd = econd->semantic(sc); econd = resolveProperties(sc, econd); econd = econd->checkToPointer(); econd = econd->checkToBoolean(); #if 0 /* this cannot work right because the types of e1 and e2 * both contribute to the type of the result. */ if (sc->flags & SCOPEstaticif) { /* If in static if, don't evaluate what we don't have to. */ econd = econd->optimize(WANTflags); if (econd->isBool(TRUE)) { e1 = e1->semantic(sc); e1 = resolveProperties(sc, e1); return e1; } else if (econd->isBool(FALSE)) { e2 = e2->semantic(sc); e2 = resolveProperties(sc, e2); return e2; } } #endif cs0 = sc->callSuper; e1 = e1->semantic(sc); e1 = resolveProperties(sc, e1); cs1 = sc->callSuper; sc->callSuper = cs0; e2 = e2->semantic(sc); e2 = resolveProperties(sc, e2); sc->mergeCallSuper(loc, cs1); // If either operand is void, the result is void t1 = e1->type; t2 = e2->type; if (t1->ty == Tvoid || t2->ty == Tvoid) type = Type::tvoid; else if (t1 == t2) type = t1; else { typeCombine(sc); switch (e1->type->toBasetype()->ty) { case Tcomplex32: case Tcomplex64: case Tcomplex80: e2 = e2->castTo(sc, e1->type); break; } switch (e2->type->toBasetype()->ty) { case Tcomplex32: case Tcomplex64: case Tcomplex80: e1 = e1->castTo(sc, e2->type); break; } if (type->toBasetype()->ty == Tarray) { e1 = e1->castTo(sc, type); e2 = e2->castTo(sc, type); } } #if 0 printf("res: %s\n", type->toChars()); printf("e1 : %s\n", e1->type->toChars()); printf("e2 : %s\n", e2->type->toChars()); #endif return this; } #if DMDV2 int CondExp::isLvalue() { return e1->isLvalue() && e2->isLvalue(); } #endif Expression *CondExp::toLvalue(Scope *sc, Expression *ex) { PtrExp *e; // convert (econd ? e1 : e2) to *(econd ? &e1 : &e2) e = new PtrExp(loc, this, type); e1 = e1->addressOf(sc); //e1 = e1->toLvalue(sc, NULL); e2 = e2->addressOf(sc); //e2 = e2->toLvalue(sc, NULL); typeCombine(sc); type = e2->type; return e; } Expression *CondExp::modifiableLvalue(Scope *sc, Expression *e) { error("conditional expression %s is not a modifiable lvalue", toChars()); return this; } void CondExp::checkEscape() { e1->checkEscape(); e2->checkEscape(); } Expression *CondExp::checkToBoolean() { e1 = e1->checkToBoolean(); e2 = e2->checkToBoolean(); return this; } int CondExp::checkSideEffect(int flag) { if (flag == 2) { return econd->checkSideEffect(2) || e1->checkSideEffect(2) || e2->checkSideEffect(2); } else { econd->checkSideEffect(1); e1->checkSideEffect(flag); return e2->checkSideEffect(flag); } } #if DMDV2 int CondExp::canThrow() { return econd->canThrow() || e1->canThrow() || e2->canThrow(); } #endif void CondExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { expToCBuffer(buf, hgs, econd, PREC_oror); buf->writestring(" ? "); expToCBuffer(buf, hgs, e1, PREC_expr); buf->writestring(" : "); expToCBuffer(buf, hgs, e2, PREC_cond); } /****************************************************************/ DefaultInitExp::DefaultInitExp(Loc loc, enum TOK subop, int size) : Expression(loc, TOKdefault, size) { this->subop = subop; } void DefaultInitExp::toCBuffer(OutBuffer *buf, HdrGenState *hgs) { buf->writestring(Token::toChars(subop)); } /****************************************************************/ FileInitExp::FileInitExp(Loc loc) : DefaultInitExp(loc, TOKfile, sizeof(FileInitExp)) { } Expression *FileInitExp::semantic(Scope *sc) { //printf("FileInitExp::semantic()\n"); type = Type::tchar->invariantOf()->arrayOf(); return this; } Expression *FileInitExp::resolve(Loc loc, Scope *sc) { //printf("FileInitExp::resolve() %s\n", toChars()); const char *s = loc.filename ? loc.filename : sc->module->ident->toChars(); Expression *e = new StringExp(loc, (char *)s); e = e->semantic(sc); e = e->castTo(sc, type); return e; } /****************************************************************/ LineInitExp::LineInitExp(Loc loc) : DefaultInitExp(loc, TOKline, sizeof(LineInitExp)) { } Expression *LineInitExp::semantic(Scope *sc) { type = Type::tint32; return this; } Expression *LineInitExp::resolve(Loc loc, Scope *sc) { Expression *e = new IntegerExp(loc, loc.linnum, Type::tint32); e = e->castTo(sc, type); return e; }
22.206556
126
0.572683
[ "object", "transform" ]
b551a73f4f62b5deb4d1cbe661751f467b053302
1,944
h
C
perception_oru-port-kinetic/ndt_map_builder/include/ndt_map_builder/ndt_map_builder.h
lllray/ndt-loam
331867941e0764b40e1a980dd85d2174f861e9c8
[ "BSD-3-Clause" ]
1
2020-11-14T08:21:13.000Z
2020-11-14T08:21:13.000Z
perception_oru-port-kinetic/ndt_map_builder/include/ndt_map_builder/ndt_map_builder.h
lllray/ndt-loam
331867941e0764b40e1a980dd85d2174f861e9c8
[ "BSD-3-Clause" ]
1
2021-07-28T04:47:56.000Z
2021-07-28T04:47:56.000Z
perception_oru-port-kinetic/ndt_map_builder/include/ndt_map_builder/ndt_map_builder.h
lllray/ndt-loam
331867941e0764b40e1a980dd85d2174f861e9c8
[ "BSD-3-Clause" ]
2
2020-12-18T11:25:53.000Z
2022-02-19T12:59:59.000Z
#include <ndt_registration/ndt_matcher_p2d.h> #include <ndt_registration/ndt_matcher_d2d.h> #include <ndt_map/ndt_histogram.h> namespace perception_oru { class MapVertex{ public: Eigen::Transform<double,3,Eigen::Affine,Eigen::ColMajor> pose; pcl::PointCloud<pcl::PointXYZ> scan; int id; NDTHistogram hist; double timeRegistration; public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; class MapEdge{ public: Eigen::Transform<double,3,Eigen::Affine,Eigen::ColMajor> relative_pose; Eigen::Matrix<double,6,6> covariance; int idFirst, idSecond; public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; class NDTMapBuilder{ public: NDTMapBuilder(double res, bool _doHistogram = false):tr(res){ isP2F = false; isF2F=false; doHistogram = _doHistogram; } /* bool setICP(){ */ /* isP2F = false; */ /* isF2F=false; */ /* return true; */ /* } */ bool setMatcherP2F(NDTMatcherP2D *_matcherP2F){ matcherP2F = _matcherP2F; isP2F = true; isF2F=false; return true; } bool setMatcherF2F(NDTMatcherD2D *_matcherF2F){ matcherF2F = _matcherF2F; isP2F = false; isF2F=true; return true; } Eigen::Transform<double,3,Eigen::Affine,Eigen::ColMajor> addScan(pcl::PointCloud<pcl::PointXYZ> scan, int id=-1); void saveG2OlogFile(const char* fname); void saveDatlogFile(const char* fname); void printNodePositions(); perception_oru::LazyGrid tr; private: NDTMatcherP2D *matcherP2F; NDTMatcherD2D *matcherF2F; bool isP2F, isF2F, doHistogram; double resolution; std::vector<MapVertex> vertices; std::vector<MapEdge> edges; /* bool matchICP(pcl::PointCloud<pcl::PointXYZ> &target, pcl::PointCloud<pcl::PointXYZ> &source, */ /* Eigen::Transform<double,3,Eigen::Affine,Eigen::ColMajor> &Tout, double &finalscore); */ }; }
25.246753
116
0.656893
[ "vector", "transform" ]
b552797586ca2a05da20be297cad4808b241e6d8
2,883
c
C
test/testrender2.c
neoaggelos/sdlu
4c916dfed0785c759ba1a69363b9e06fbe3583a3
[ "BSD-1-Clause", "Zlib" ]
2
2020-07-28T16:31:08.000Z
2021-07-17T02:39:58.000Z
test/testrender2.c
neoaggelos/sdlu
4c916dfed0785c759ba1a69363b9e06fbe3583a3
[ "BSD-1-Clause", "Zlib" ]
null
null
null
test/testrender2.c
neoaggelos/sdlu
4c916dfed0785c759ba1a69363b9e06fbe3583a3
[ "BSD-1-Clause", "Zlib" ]
null
null
null
/* * The SDL Utility library * Copyright (c) 2016 Aggelos Kolaitis <neoaggelos@gmail.com> * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ /* * testrender2: A test program for the SDL Utility library */ /* Mix pure OpenGL calls with the SDL2 Render API */ #include "SDLU.h" #include "SDL_opengl.h" #include "common.h" #include <stdio.h> #include <stdlib.h> SDL_Window* window; SDL_Renderer* renderer; SDL_bool done = SDL_FALSE; SDL_Event event; /** called at exit to cleanup **/ void cleanup( void ) { if (renderer) SDL_DestroyRenderer(renderer); if (window) SDL_DestroyWindow(window); SDL_Quit(); } int main(int argc, char** argv) { SDL_Rect sdl_rect = SDLU_CreateRect(100, 75, 120, 90); /** We want OpenGL **/ SDL_SetHintWithPriority("SDL_RENDER_DRIVER", "opengl", SDL_HINT_OVERRIDE); /** Initialize SDL **/ SDL_CHECK( SDL_Init(SDL_INIT_VIDEO) != -1 ); atexit( cleanup ); window = SDL_CreateWindow("testrender2", 100, 100, 320, 240, SDL_WINDOW_OPENGL); SDL_CHECK(window); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); SDL_CHECK(renderer); /** wait for quit event **/ while( done == SDL_FALSE ) { SDL_PollEvent( &event ); if (event.type == SDL_QUIT) done = SDL_TRUE; /** SDL Rendering **/ SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0xff); SDL_RenderClear(renderer); SDL_SetRenderDrawColor(renderer, 0xff, 0x88, 0x00, 0xff); SDL_RenderDrawRect(renderer, &sdl_rect); /** OpenGL Rendering **/ SDLU_GL_RenderCacheState(renderer); glShadeModel(GL_SMOOTH); glBegin(GL_TRIANGLES); glColor3f(1, 0, 0); glVertex2f(160, 75); glColor3f(0, 0, 1); glVertex2f(100, 165); glColor3f(0, 1, 0); glVertex2f(220, 165); glEnd(); glShadeModel(GL_FLAT); /* restore state */ SDLU_GL_RenderRestoreState(renderer); /** Update screen **/ SDL_RenderPresent(renderer); } exit(0); }
28.83
84
0.669442
[ "render" ]
b56bd7b29ac4c78ad11eaf25787013fa3af0b82d
2,723
h
C
mbed-client/mbed-client/mbed-client-classic/mbed-client-classic/m2mtimerpimpl.h
ghsecuritylab/mini-client
955e1d213ec0784101061075932dbbac97d98cd9
[ "Apache-2.0" ]
null
null
null
mbed-client/mbed-client/mbed-client-classic/mbed-client-classic/m2mtimerpimpl.h
ghsecuritylab/mini-client
955e1d213ec0784101061075932dbbac97d98cd9
[ "Apache-2.0" ]
null
null
null
mbed-client/mbed-client/mbed-client-classic/mbed-client-classic/m2mtimerpimpl.h
ghsecuritylab/mini-client
955e1d213ec0784101061075932dbbac97d98cd9
[ "Apache-2.0" ]
1
2020-03-06T22:23:26.000Z
2020-03-06T22:23:26.000Z
/* * Copyright (c) 2015 ARM Limited. All rights reserved. * SPDX-License-Identifier: Apache-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. */ #ifndef M2M_TIMER_PIMPL_H__ #define M2M_TIMER_PIMPL_H__ #include "ns_types.h" #include "mbed-client/m2mtimerobserver.h" #include "mbed-client/m2mcorememory.h" class M2MTimerPimpl : public M2MCoreMemory { private: // Prevents the use of assignment operator M2MTimerPimpl& operator=(const M2MTimerPimpl& other); // Prevents the use of copy constructor M2MTimerPimpl(const M2MTimerPimpl& other); public: /** * Constructor. */ M2MTimerPimpl(M2MTimerObserver& _observer); /** * Destructor. */ virtual ~M2MTimerPimpl(); /** * Starts timer * @param interval Timer's interval in milliseconds * @param single_shot defines if timer is ticked * once or is it restarted everytime timer is expired. */ void start_timer(uint32_t interval, M2MTimerObserver::Type type, bool single_shot = true); /** * Stops timer. * This cancels the ongoing timer. */ void stop_timer(); /** * Callback function for timer completion. */ void timer_expired(); /** * @brief Start long period timer */ void start_still_left_timer(); /** * @brief Get timer id * @return Timer id */ inline int8_t get_timer_id() const; /** * @brief Get still left time * @return Time left in milliseconds */ uint32_t get_still_left_time() const; private: void start(); void cancel(); private: M2MTimerObserver& _observer; uint32_t _interval; uint32_t _still_left; // this is the timer-id of this object, used to map the // timer event callback to the correct object. int8_t _timer_id; static int8_t _tasklet_id; static int8_t _next_timer_id; M2MTimerObserver::Type _type:4; bool _single_shot:1; friend class M2MTimer; friend class Test_M2MTimerPimpl_classic; }; inline int8_t M2MTimerPimpl::get_timer_id() const { return _timer_id; } #endif //M2M_TIMER_PIMPL_H__
24.531532
94
0.661403
[ "object" ]
b570ebc8607d3ead30c07f432940c2d5521490ec
3,893
h
C
src/world/cellshare/TbusCellShare.h
hhucn/tbus-vsimrti
09b0b0b2a256321e4027a30e58d5221d1c92ed34
[ "MIT" ]
2
2015-10-26T13:43:36.000Z
2018-11-17T16:46:24.000Z
src/world/cellshare/TbusCellShare.h
hhucn/tbus-vsimrti
09b0b0b2a256321e4027a30e58d5221d1c92ed34
[ "MIT" ]
null
null
null
src/world/cellshare/TbusCellShare.h
hhucn/tbus-vsimrti
09b0b0b2a256321e4027a30e58d5221d1c92ed34
[ "MIT" ]
1
2018-11-17T16:46:21.000Z
2018-11-17T16:46:21.000Z
/* * TbusCellShare.h * * Created on: 17.02.2015 * Author: bialon */ #ifndef TBUSCELLSHARE_H_ #define TBUSCELLSHARE_H_ #include "omnetpp.h" #include "TbusQueueDatarateValue.h" #include "TbusQueueDelayValue.h" #include "TbusCellShareTypes.h" #include <map> #include <set> /** * Representation of a TBUS cell share module. */ class TbusCellShare { protected: /** * Protected constructor for inheriting. */ TbusCellShare() {}; typedef std::set<TbusHost*> HostSet; ///< Set of hosts in cell typedef struct TbusCell { uint64_t numActiveHosts; HostSet hosts; }; /** * Returns the number of active hosts in the given cell. * @param cellId Cell id of cell * @return Number of active hosts */ uint64_t getActiveHostsInCell(cellid_t cellId) { return idToCell[cellId].numActiveHosts; } /** * Get a set of all hosts currently connected to a cell with cell id cellId. * @param cellId Cell id * @return Host set */ HostSet& getHostsInCell(cellid_t cellId) { return idToCell[cellId].hosts; } private: TbusCellShare(const TbusCellShare&); void operator=(const TbusCellShare&); /** * Maps a cell id to the number of connected hosts. */ std::map<cellid_t, TbusCell> idToCell; /** * Update the number of cell active hosts. * @param cellId */ void updateNumActiveHostsInCell(cellid_t cellId) { uint64_t numActiveHosts = 0; HostSet::iterator it; HostSet& hosts = idToCell[cellId].hosts; for (it = hosts.begin(); it != hosts.end(); ++it) { if ((*it)->callback->getQueueStatus() == CELL_ACTIVE) { numActiveHosts++; } } idToCell[cellId].numActiveHosts = numActiveHosts; } public: /** * Singleton instantiation for every model. * @return A TbusCellShare of model T */ template<class T> static TbusCellShare* getInstance() { static TbusCellShare* instance = new T(); ///< Static local variable used for singleton cleanup return instance; } /** * Update cell model. * Host host changed cells between from and to. * @param from Cell host was in * @param to Cell host is in * @param host Optional host reference */ void hostMoved(cellid_t from, cellid_t to, TbusHost* host) { if (from != TBUS_INVALID_CELLID) { idToCell[from].hosts.erase(host); updateNumActiveHostsInCell(from); } if (to != TBUS_INVALID_CELLID) { idToCell[to].hosts.insert(host); updateNumActiveHostsInCell(to); } } /** * Makes every host in cell cellId adapt its queue values. * @param cellId Cell id */ void cellActivityChanged(cellid_t cellId) { HostSet& hosts = idToCell[cellId].hosts; HostSet::iterator it; // First, update the number of cell active hosts updateNumActiveHostsInCell(cellId); // Second, let all hosts adapt active queue's value for (it = hosts.begin(); it != hosts.end(); ++it) { (*it)->callback->adaptQueueValues(ALL); } } /** * Adapt the given value in a new returned value to the current cell model. * The optional parameter host can be used for additional information. * @param cellId Cell to adapt on * @param value Given TbusQueueDatarateValue * @param host Optional host reference * @return Adapted queue datarate value */ virtual TbusQueueDatarateValue* adaptDatarateValue(cellid_t cellId, TbusQueueDatarateValue* value, TbusHost* host = NULL) = 0; /** * Adapt the given value in a new returned value to the current cell model. * The optional parameter host can be used for additional information. * @param cellId Cell to adapt on * @param value Given TbusQueueDelayValue * @param host Optional host reference * @return Adapted queue delay value */ virtual TbusQueueDelayValue* adaptDelayValue(cellid_t cellId, TbusQueueDelayValue* value, TbusHost* host = NULL) = 0; }; #endif /* TBUSCELLSHARE_H_ */
25.781457
128
0.68559
[ "model" ]
b5908e33b1850ca791b967915315665917f36b0b
1,106
h
C
workflow_registry/websocket_utils.h
cepsdev/rollAut
ba1b014e21f7dfc3d0d5c74fd051e65ae74a6a36
[ "MIT" ]
null
null
null
workflow_registry/websocket_utils.h
cepsdev/rollAut
ba1b014e21f7dfc3d0d5c74fd051e65ae74a6a36
[ "MIT" ]
null
null
null
workflow_registry/websocket_utils.h
cepsdev/rollAut
ba1b014e21f7dfc3d0d5c74fd051e65ae74a6a36
[ "MIT" ]
null
null
null
#ifndef WEBSOCKET_UTILS_H #define WEBSOCKET_UTILS_H #include <sys/types.h> #include <dirent.h> #include <sys/stat.h> #include <unistd.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/epoll.h> #include <fcntl.h> #include <netdb.h> #include <tuple> #include <string> #include <vector> namespace ws_utils{ std::pair<bool,std::string> get_http_attribute_content( std::string attr, std::vector<std::pair<std::string,std::string>> const & http_header); bool field_with_content( std::string attr, std::string value, std::vector<std::pair<std::string,std::string>> const & http_header); std::tuple<bool,std::string,std::vector<std::pair<std::string,std::string>>> read_http_request( int sck, std::string& unconsumed_data); struct websocket_frame{ std::vector<unsigned char> payload; bool fin = false; bool rsv1 = false; bool rsv2 = false; bool rsv3 = false; std::uint8_t opcode = 0; }; std::pair<bool,websocket_frame> read_websocket_frame(int sck); } #endif // WEBSOCKET_UTILS_H
23.531915
99
0.665461
[ "vector" ]
b5938206b386a777383b962dbf0463359680192d
2,681
h
C
rmf_traffic/thirdparty/fcl/include/fcl/math/variance3.h
0to1/rmf_traffic
0e641f779e9c7e6d69c316e905df5a51a2c124e1
[ "Apache-2.0" ]
921
2015-01-27T15:11:44.000Z
2022-03-29T08:39:06.000Z
rmf_traffic/thirdparty/fcl/include/fcl/math/variance3.h
0to1/rmf_traffic
0e641f779e9c7e6d69c316e905df5a51a2c124e1
[ "Apache-2.0" ]
474
2015-01-28T08:08:18.000Z
2022-03-30T13:40:49.000Z
rmf_traffic/thirdparty/fcl/include/fcl/math/variance3.h
0to1/rmf_traffic
0e641f779e9c7e6d69c316e905df5a51a2c124e1
[ "Apache-2.0" ]
370
2015-01-05T07:49:25.000Z
2022-03-27T12:41:28.000Z
/* * Software License Agreement (BSD License) * * Copyright (c) 2011-2014, Willow Garage, Inc. * Copyright (c) 2014-2016, Open Source Robotics Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Open Source Robotics Foundation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** @author Jia Pan */ #ifndef FCL_MATH_VARIANCE3_H #define FCL_MATH_VARIANCE3_H #include <cmath> #include "fcl/common/types.h" #include "fcl/math/geometry.h" namespace fcl { /// @brief Class for variance matrix in 3d template <typename S> class FCL_EXPORT Variance3 { public: /// @brief Variation matrix Matrix3<S> Sigma; /// @brief Variations along the eign axes Vector3<S> sigma; /// @brief Matrix whose columns are eigenvectors of Sigma Matrix3<S> axis; Variance3(); Variance3(const Matrix3<S>& sigma); /// @brief init the Variance void init(); /// @brief Compute the sqrt of Sigma matrix based on the eigen decomposition /// result, this is useful when the uncertainty matrix is initialized as a /// square variation matrix Variance3<S>& sqrt(); }; using Variance3f = Variance3<float>; using Variance3d = Variance3<double>; } // namespace fcl #include "fcl/math/variance3-inl.h" #endif
31.916667
79
0.735173
[ "geometry", "3d" ]
240c4d0d7daba3d8b9d0e731cd176be52ef7afd9
6,199
h
C
src/listener/TCPServer.h
RichaGNigam/MyRepository
7ec8461b73e19b72c8eda38b337737c010b79885
[ "Apache-2.0" ]
8
2018-05-02T09:38:43.000Z
2018-09-03T17:36:13.000Z
src/listener/TCPServer.h
RichaGNigam/MyRepository
7ec8461b73e19b72c8eda38b337737c010b79885
[ "Apache-2.0" ]
2
2018-06-19T07:18:54.000Z
2018-06-19T07:21:51.000Z
src/listener/TCPServer.h
RichaGNigam/MyRepository
7ec8461b73e19b72c8eda38b337737c010b79885
[ "Apache-2.0" ]
1
2018-06-27T01:37:13.000Z
2018-06-27T01:37:13.000Z
/* ********************************************************* This code is a proprietary of Kapil Rana Following may not be used in part or in whole without the prior permission of Kapil Rana Author: Kapil Rana Date: 20/06/2015 Purpose: PUSH FYI RS SSL TCP Server Listener. ********************************************************* */ #ifndef __PLAIN_TCP_SERVER__ #define __PLAIN_TCP_SERVER__ #include <unistd.h> #include <list> #include "Runnable.h" #include "Thread.h" #include "Mutex.h" #include "Event.h" #include "PriorityQueue.h" #include "ServerSocket.h" #include "EpollProxy.h" #define DEFAULT_REPORT_STATS_INTERVAL 5000 class TCPReader; class PubSubRouter; /*! * * Push FYI RS's main SSL TCP Server class. * * This class listens for incoming connections from unsecure clients. * This class performs following key tasks: * * 1. Listen for incoming connections. * 2. Pass the connection to TCPReader for handshake * */ class TCPServer : public Runnable, public ServerSocket, EpollProxy, Pushable<Event> { public: typedef std::map<std::string, int> CommandMap; static const int DEFAULT_EPOLL_TIME_OUT_MILLIS = 1000; private: /*! * Constructor is private as this is a Singleton class */ TCPServer(); /*! * Copy Constructor is private as this is a Singleton class */ TCPServer(const TCPServer&); /*! * Self Instance */ static TCPServer* mInstance; /*! * Process the command sent to the TCP Server. * * This method is called when notification pipe is triggered. It then fetches the * commands present in the command queue and process them. */ void processCmd(); /*! * Initialize the list of commands and corresponding codes. */ void initializeCommandMap(); /*! * This method triggers the notification pipe by writing to it's write end. */ void notify(); /*! * Pushes the command depending upon it's priority. * @see push * @see pushFront */ void submitCmd(Event event, bool isHighPriority = false); /*! * subscribe for TCP Server topic and subtopic to the PubSubRouter */ void subscribe(); /*! * unsubscribe for TCP Server topic and subtopic to the PubSubRouter */ void unsubscribe(); /*! * internal method to generate uuid */ string getUUID(); public: /*! * Interface method to get the class Instance */ static TCPServer* getInstance(); /*! * Destructor * * This must always be virtual. */ virtual ~TCPServer(); /*! * This is a concrete implementation of ServerSocket processNewClientSocket * @see ServerSocket Server Socket wrapper class * * @param socketFd Socket file descriptor returned by call to accept */ //void processNewClientSocket(int socketFd); void processNewClientSocket(int socketFd, char* ip, rxUShort port); /*! * Override this method to implement ServerSocket::Accept yourself */ void Accept(); /*! TCPServer Thread Function * * Implement the TCPServer's main thread. */ void run(); /*! Start the server * * Method to start the TCP Server main thread and start listening */ bool online(); /*! Stop the server * * Method to stop the TCP Server main thread */ bool offline(); void idle(int); /*! * Concrete implementation for Pushable::push * * @param event Request event to be pushed */ virtual void push(Event event); /*! * Concrete implementation for Pushable::pushFront to push high priority messages. * @see Pushable Pushable interface * * @param event Request event to be pushed. * * Do not use this method for pushing events on the TCPServer queue without knowing what might happen. * Unknowing use of this method can lead to starvation of incoming messages and some other control messages. * * Avoid it's use unless you know exactly what you are doing. */ virtual void pushFront(Event event); /** * Set alternate port */ void setAlternatePort(rxInt port); private: /*! Thread object * * TCP Sever's thread object * @see Thread */ Thread* mThread; /*! Synchronization Mutex * * pthread_mutex_t wrapper */ Mutex mMutex; /*! TCP Server Command Queue * * TCP Server can be controlled dynamically by sending command's to this queue. * * Command event must contain the following parameters: * * topic = pushfyirs-tcp-server * subtopic = * * command = <command-to-process> */ PriorityQueue<Event>* mCmdQueue; /*! * TCP Server Topic String */ string mTopic; /*! * TCP Server is notified asynchronously of any commands that have been sent to it. * * This notification is executed to trigger the processing of commands. */ int mPipeFd[2]; /*! TCP Server Command List * * A map of TCP Server command code and corresponding string value */ CommandMap mCommandMap; /*! * Command codes */ enum CommandType { eReaderOnline = 0, eStatus }; /*! * Class to perform Push FYI Handshake and identify the protocol used by client. * * @see PushFYIProtocol Check out the class definition for all the protocols supported. */ //PushFYIProtocol mProtocol; /*! * Event Router Instance * * @see PubSubRouter The main Publish Subscribe Event router. * * Say the words and remember them : "I would not mess with this class" */ PubSubRouter& mRouter; /* * is Alternate Port on */ bool mIsAlternatePort; /* * TCPReader instances */ std::vector<string> mReaders; rxUInt mReaderIndex; /* * Server Diagnostics */ rxULong _StartTime; rxULong _ConnectionAccepts; rxULong _IdleCycles; void processReaderOnline(Event&); }; #endif //__SECURE_TCP_SERVER__
22.959259
112
0.619616
[ "object", "vector" ]
24193ae04e4f2fdf5e5675dd73323735f0a942f1
3,074
h
C
Sourcecode/private/mx/core/elements/Appearance.h
Webern/MxOld
822f5ccc92363ddff118e3aa3a048c63be1e857e
[ "MIT" ]
45
2019-04-16T19:55:08.000Z
2022-02-14T02:06:32.000Z
Sourcecode/private/mx/core/elements/Appearance.h
Webern/MxOld
822f5ccc92363ddff118e3aa3a048c63be1e857e
[ "MIT" ]
70
2019-04-07T22:45:21.000Z
2022-03-03T15:35:59.000Z
Sourcecode/private/mx/core/elements/Appearance.h
Webern/MxOld
822f5ccc92363ddff118e3aa3a048c63be1e857e
[ "MIT" ]
21
2019-05-13T13:59:06.000Z
2022-03-25T02:21:05.000Z
// MusicXML Class Library // Copyright (c) by Matthew James Briggs // Distributed under the MIT License #pragma once #include "mx/core/ForwardDeclare.h" #include "mx/core/ElementInterface.h" #include <iosfwd> #include <memory> #include <vector> namespace mx { namespace core { MX_FORWARD_DECLARE_ELEMENT( Distance ) MX_FORWARD_DECLARE_ELEMENT( LineWidth ) MX_FORWARD_DECLARE_ELEMENT( NoteSize ) MX_FORWARD_DECLARE_ELEMENT( OtherAppearance ) MX_FORWARD_DECLARE_ELEMENT( Appearance ) inline AppearancePtr makeAppearance() { return std::make_shared<Appearance>(); } class Appearance : public ElementInterface { public: Appearance(); virtual bool hasAttributes() const; virtual std::ostream& streamAttributes( std::ostream& os ) const; virtual std::ostream& streamName( std::ostream& os ) const; virtual bool hasContents() const; virtual std::ostream& streamContents( std::ostream& os, const int indentLevel, bool& isOneLineOnly ) const; /* _________ LineWidth minOccurs = 0, maxOccurs = unbounded _________ */ const LineWidthSet& getLineWidthSet() const; void addLineWidth( const LineWidthPtr& value ); void removeLineWidth( const LineWidthSetIterConst& value ); void clearLineWidthSet(); LineWidthPtr getLineWidth( const LineWidthSetIterConst& setIterator ) const; /* _________ NoteSize minOccurs = 0, maxOccurs = unbounded _________ */ const NoteSizeSet& getNoteSizeSet() const; void addNoteSize( const NoteSizePtr& value ); void removeNoteSize( const NoteSizeSetIterConst& value ); void clearNoteSizeSet(); NoteSizePtr getNoteSize( const NoteSizeSetIterConst& setIterator ) const; /* _________ Distance minOccurs = 0, maxOccurs = unbounded _________ */ const DistanceSet& getDistanceSet() const; void addDistance( const DistancePtr& value ); void removeDistance( const DistanceSetIterConst& value ); void clearDistanceSet(); DistancePtr getDistance( const DistanceSetIterConst& setIterator ) const; /* _________ OtherAppearance minOccurs = 0, maxOccurs = unbounded _________ */ const OtherAppearanceSet& getOtherAppearanceSet() const; void addOtherAppearance( const OtherAppearancePtr& value ); void removeOtherAppearance( const OtherAppearanceSetIterConst& value ); void clearOtherAppearanceSet(); OtherAppearancePtr getOtherAppearance( const OtherAppearanceSetIterConst& setIterator ) const; private: virtual bool fromXElementImpl( std::ostream& message, ::ezxml::XElement& xelement ); private: LineWidthSet myLineWidthSet; NoteSizeSet myNoteSizeSet; DistanceSet myDistanceSet; OtherAppearanceSet myOtherAppearanceSet; }; } }
39.922078
119
0.664606
[ "vector" ]
2419a451a3f30fba01041ac51bb10a9e49a3798e
3,093
h
C
engine/ttsbase/datamanage/module_manager.h
syang1993/Crystal
876799000b7f0a14d9ab90fcf84ddba319f295e5
[ "Apache-2.0" ]
162
2020-07-01T13:22:03.000Z
2022-03-20T08:25:32.000Z
engine/ttsbase/datamanage/module_manager.h
arctanx999/Crystal
20ff0d2e625f5e48d3bf1651847638085c5b2ea1
[ "Apache-2.0" ]
1
2020-10-16T10:09:03.000Z
2020-12-17T03:41:00.000Z
engine/ttsbase/datamanage/module_manager.h
arctanx999/Crystal
20ff0d2e625f5e48d3bf1651847638085c5b2ea1
[ "Apache-2.0" ]
56
2020-07-02T02:21:53.000Z
2022-03-25T02:55:35.000Z
// // Crystal Text-to-Speech Engine // // Copyright (c) 2007 THU-CUHK Joint Research Center for // Media Sciences, Technologies and Systems. All rights reserved. // // http://mjrc.sz.tsinghua.edu.cn // // Redistribution and use in source and binary forms, with or without // modification, is not allowed, unless a valid written license is // granted by THU-CUHK Joint Research Center. // // THU-CUHK Joint Research Center has the rights to create, modify, // copy, compile, remove, rename, explain and deliver the source codes. // /// /// @file /// /// @brief Head file for managing modules loaded from dynamic libraries for Text-to-Speech (TTS) engine /// /// <b>History:</b> /// - Version: 0.1.0 /// Author: John (john.zywu@gmail.com) /// Date: 2018/1/20 /// Changed: Implemented the framework and basic interfaces /// #ifndef _CST_TTS_BASE_MODULE_MANAGER_H_ #define _CST_TTS_BASE_MODULE_MANAGER_H_ #include <vector> #include "base_moduleapi.h" namespace cst { namespace tts { namespace base { /// /// @brief The class for managing modules dynamically loaded from dynamic libraries /// class CModuleManager { public: /// /// @brief Constructor /// CModuleManager() {} /// /// @brief Destructor /// virtual ~CModuleManager() {freeModules();} /// /// @brief Load modules from the dynamic libraries specified by the configuration file /// /// @param [in] configFile Configuration file for loading modules /// @param [out] dataConfig Return the configuration data for later module initialization /// /// @return Whether operation is successful /// @retval ERROR_SUCCESS The operation is successful /// virtual int loadModules(const wchar_t *configFile, DataConfig &dataConfig); /// /// @brief Free the modules /// /// @return Whether operation is successful /// @retval ERROR_SUCCESS The operation is successful /// virtual int freeModules(); protected: /// /// @brief Load modules from a dynamic library /// /// @param [in] filename Filename of the dynamic library to be loaded /// /// @return Whether operation is successful /// bool loadLibrary(const wchar_t* filename); protected: /// Loaded modules std::map<std::string, ModuleInfo> modules; /// Loaded dynamic libraries (e.g. "DLL" on Windows, "SO" on Linux) std::vector<void*> dlibs; }; }//namespace base } } #endif//_CST_TTS_BASE_MODULE_MANAGER_H_
31.561224
109
0.542192
[ "vector" ]
241cb5d44f0f42dd8d3142be5a01f388c3dfcb31
34,135
c
C
Mac/Modules/ae/AEmodule.c
1byte2bytes/cpython
7fbaeb819ca7b20dca048217ff585ec195e999ec
[ "Unlicense", "TCL", "DOC", "AAL", "X11" ]
1
2019-10-25T21:41:07.000Z
2019-10-25T21:41:07.000Z
Mac/Modules/ae/AEmodule.c
1byte2bytes/cpython
7fbaeb819ca7b20dca048217ff585ec195e999ec
[ "Unlicense", "TCL", "DOC", "AAL", "X11" ]
null
null
null
Mac/Modules/ae/AEmodule.c
1byte2bytes/cpython
7fbaeb819ca7b20dca048217ff585ec195e999ec
[ "Unlicense", "TCL", "DOC", "AAL", "X11" ]
null
null
null
/* =========================== Module AE ============================ */ #include "Python.h" #define SystemSevenOrLater 1 #include "macglue.h" #include <Memory.h> #include <Dialogs.h> #include <Menus.h> #include <Controls.h> extern PyObject *ResObj_New(Handle); extern int ResObj_Convert(PyObject *, Handle *); extern PyObject *OptResObj_New(Handle); extern int OptResObj_Convert(PyObject *, Handle *); extern PyObject *WinObj_New(WindowPtr); extern int WinObj_Convert(PyObject *, WindowPtr *); extern PyTypeObject Window_Type; #define WinObj_Check(x) ((x)->ob_type == &Window_Type) extern PyObject *DlgObj_New(DialogPtr); extern int DlgObj_Convert(PyObject *, DialogPtr *); extern PyTypeObject Dialog_Type; #define DlgObj_Check(x) ((x)->ob_type == &Dialog_Type) extern PyObject *MenuObj_New(MenuHandle); extern int MenuObj_Convert(PyObject *, MenuHandle *); extern PyObject *CtlObj_New(ControlHandle); extern int CtlObj_Convert(PyObject *, ControlHandle *); extern PyObject *GrafObj_New(GrafPtr); extern int GrafObj_Convert(PyObject *, GrafPtr *); extern PyObject *BMObj_New(BitMapPtr); extern int BMObj_Convert(PyObject *, BitMapPtr *); extern PyObject *WinObj_WhichWindow(WindowPtr); #include <AppleEvents.h> #ifndef HAVE_UNIVERSAL_HEADERS #define AEIdleProcPtr IdleProcPtr #define AEFilterProcPtr EventFilterProcPtr #define AEEventHandlerProcPtr EventHandlerProcPtr #endif #ifndef HAVE_UNIVERSAL_HEADERS /* I'm trying to setup the code here so that is easily automated, ** as follows: ** - Use the UPP in the source ** - for pre-universal headers, #define each UPP as the corresponding ProcPtr ** - for each routine we pass we declare a upp_xxx that ** we initialize to the correct value in the init routine. */ #define AEIdleUPP AEIdleProcPtr #define AEFilterUPP AEFilterProcPtr #define AEEventHandlerUPP AEEventHandlerProcPtr #define NewAEIdleProc(x) (x) #define NewAEFilterProc(x) (x) #define NewAEEventHandlerProc(x) (x) #endif static pascal OSErr GenericEventHandler(); /* Forward */ AEEventHandlerUPP upp_GenericEventHandler; static pascal Boolean AEIdleProc(EventRecord *theEvent, long *sleepTime, RgnHandle *mouseRgn) { if ( PyOS_InterruptOccurred() ) return 1; if ( PyMac_HandleEvent(theEvent) < 0 ) { PySys_WriteStderr("Exception in user event handler during AE processing\n"); PyErr_Clear(); } return 0; } AEIdleUPP upp_AEIdleProc; static PyObject *AE_Error; /* ----------------------- Object type AEDesc ----------------------- */ PyTypeObject AEDesc_Type; #define AEDesc_Check(x) ((x)->ob_type == &AEDesc_Type) typedef struct AEDescObject { PyObject_HEAD AEDesc ob_itself; } AEDescObject; PyObject *AEDesc_New(itself) AEDesc *itself; { AEDescObject *it; it = PyObject_NEW(AEDescObject, &AEDesc_Type); if (it == NULL) return NULL; it->ob_itself = *itself; return (PyObject *)it; } AEDesc_Convert(v, p_itself) PyObject *v; AEDesc *p_itself; { if (!AEDesc_Check(v)) { PyErr_SetString(PyExc_TypeError, "AEDesc required"); return 0; } *p_itself = ((AEDescObject *)v)->ob_itself; return 1; } static void AEDesc_dealloc(self) AEDescObject *self; { AEDisposeDesc(&self->ob_itself); PyMem_DEL(self); } static PyObject *AEDesc_AESend(_self, _args) AEDescObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; AppleEvent reply; AESendMode sendMode; AESendPriority sendPriority; long timeOutInTicks; if (!PyArg_ParseTuple(_args, "lhl", &sendMode, &sendPriority, &timeOutInTicks)) return NULL; _err = AESend(&_self->ob_itself, &reply, sendMode, sendPriority, timeOutInTicks, upp_AEIdleProc, (AEFilterUPP)0); if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("O&", AEDesc_New, &reply); return _res; } static PyObject *AEDesc_AEResetTimer(_self, _args) AEDescObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; if (!PyArg_ParseTuple(_args, "")) return NULL; _err = AEResetTimer(&_self->ob_itself); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *AEDesc_AESuspendTheCurrentEvent(_self, _args) AEDescObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; if (!PyArg_ParseTuple(_args, "")) return NULL; _err = AESuspendTheCurrentEvent(&_self->ob_itself); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *AEDesc_AEResumeTheCurrentEvent(_self, _args) AEDescObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; AppleEvent reply; AEEventHandlerUPP dispatcher__proc__ = upp_GenericEventHandler; PyObject *dispatcher; if (!PyArg_ParseTuple(_args, "O&O", AEDesc_Convert, &reply, &dispatcher)) return NULL; _err = AEResumeTheCurrentEvent(&_self->ob_itself, &reply, dispatcher__proc__, (long)dispatcher); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; Py_INCREF(dispatcher); /* XXX leak, but needed */ return _res; } static PyObject *AEDesc_AEGetTheCurrentEvent(_self, _args) AEDescObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; if (!PyArg_ParseTuple(_args, "")) return NULL; _err = AEGetTheCurrentEvent(&_self->ob_itself); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *AEDesc_AESetTheCurrentEvent(_self, _args) AEDescObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; if (!PyArg_ParseTuple(_args, "")) return NULL; _err = AESetTheCurrentEvent(&_self->ob_itself); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *AEDesc_AECoerceDesc(_self, _args) AEDescObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; DescType toType; AEDesc result; if (!PyArg_ParseTuple(_args, "O&", PyMac_GetOSType, &toType)) return NULL; _err = AECoerceDesc(&_self->ob_itself, toType, &result); if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("O&", AEDesc_New, &result); return _res; } static PyObject *AEDesc_AEDuplicateDesc(_self, _args) AEDescObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; AEDesc result; if (!PyArg_ParseTuple(_args, "")) return NULL; _err = AEDuplicateDesc(&_self->ob_itself, &result); if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("O&", AEDesc_New, &result); return _res; } static PyObject *AEDesc_AECountItems(_self, _args) AEDescObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; long theCount; if (!PyArg_ParseTuple(_args, "")) return NULL; _err = AECountItems(&_self->ob_itself, &theCount); if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("l", theCount); return _res; } static PyObject *AEDesc_AEPutPtr(_self, _args) AEDescObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; long index; DescType typeCode; char *dataPtr__in__; long dataPtr__len__; int dataPtr__in_len__; if (!PyArg_ParseTuple(_args, "lO&s#", &index, PyMac_GetOSType, &typeCode, &dataPtr__in__, &dataPtr__in_len__)) return NULL; dataPtr__len__ = dataPtr__in_len__; _err = AEPutPtr(&_self->ob_itself, index, typeCode, dataPtr__in__, dataPtr__len__); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; dataPtr__error__: ; return _res; } static PyObject *AEDesc_AEPutDesc(_self, _args) AEDescObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; long index; AEDesc theAEDesc; if (!PyArg_ParseTuple(_args, "lO&", &index, AEDesc_Convert, &theAEDesc)) return NULL; _err = AEPutDesc(&_self->ob_itself, index, &theAEDesc); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *AEDesc_AEGetNthPtr(_self, _args) AEDescObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; long index; DescType desiredType; AEKeyword theAEKeyword; DescType typeCode; char *dataPtr__out__; long dataPtr__len__; int dataPtr__in_len__; if (!PyArg_ParseTuple(_args, "lO&i", &index, PyMac_GetOSType, &desiredType, &dataPtr__in_len__)) return NULL; if ((dataPtr__out__ = malloc(dataPtr__in_len__)) == NULL) { PyErr_NoMemory(); goto dataPtr__error__; } dataPtr__len__ = dataPtr__in_len__; _err = AEGetNthPtr(&_self->ob_itself, index, desiredType, &theAEKeyword, &typeCode, dataPtr__out__, dataPtr__len__, &dataPtr__len__); if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("O&O&s#", PyMac_BuildOSType, theAEKeyword, PyMac_BuildOSType, typeCode, dataPtr__out__, (int)dataPtr__len__); free(dataPtr__out__); dataPtr__error__: ; return _res; } static PyObject *AEDesc_AEGetNthDesc(_self, _args) AEDescObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; long index; DescType desiredType; AEKeyword theAEKeyword; AEDesc result; if (!PyArg_ParseTuple(_args, "lO&", &index, PyMac_GetOSType, &desiredType)) return NULL; _err = AEGetNthDesc(&_self->ob_itself, index, desiredType, &theAEKeyword, &result); if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("O&O&", PyMac_BuildOSType, theAEKeyword, AEDesc_New, &result); return _res; } static PyObject *AEDesc_AESizeOfNthItem(_self, _args) AEDescObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; long index; DescType typeCode; Size dataSize; if (!PyArg_ParseTuple(_args, "l", &index)) return NULL; _err = AESizeOfNthItem(&_self->ob_itself, index, &typeCode, &dataSize); if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("O&l", PyMac_BuildOSType, typeCode, dataSize); return _res; } static PyObject *AEDesc_AEDeleteItem(_self, _args) AEDescObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; long index; if (!PyArg_ParseTuple(_args, "l", &index)) return NULL; _err = AEDeleteItem(&_self->ob_itself, index); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *AEDesc_AEPutParamPtr(_self, _args) AEDescObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; AEKeyword theAEKeyword; DescType typeCode; char *dataPtr__in__; long dataPtr__len__; int dataPtr__in_len__; if (!PyArg_ParseTuple(_args, "O&O&s#", PyMac_GetOSType, &theAEKeyword, PyMac_GetOSType, &typeCode, &dataPtr__in__, &dataPtr__in_len__)) return NULL; dataPtr__len__ = dataPtr__in_len__; _err = AEPutParamPtr(&_self->ob_itself, theAEKeyword, typeCode, dataPtr__in__, dataPtr__len__); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; dataPtr__error__: ; return _res; } static PyObject *AEDesc_AEPutParamDesc(_self, _args) AEDescObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; AEKeyword theAEKeyword; AEDesc theAEDesc; if (!PyArg_ParseTuple(_args, "O&O&", PyMac_GetOSType, &theAEKeyword, AEDesc_Convert, &theAEDesc)) return NULL; _err = AEPutParamDesc(&_self->ob_itself, theAEKeyword, &theAEDesc); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *AEDesc_AEGetParamPtr(_self, _args) AEDescObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; AEKeyword theAEKeyword; DescType desiredType; DescType typeCode; char *dataPtr__out__; long dataPtr__len__; int dataPtr__in_len__; if (!PyArg_ParseTuple(_args, "O&O&i", PyMac_GetOSType, &theAEKeyword, PyMac_GetOSType, &desiredType, &dataPtr__in_len__)) return NULL; if ((dataPtr__out__ = malloc(dataPtr__in_len__)) == NULL) { PyErr_NoMemory(); goto dataPtr__error__; } dataPtr__len__ = dataPtr__in_len__; _err = AEGetParamPtr(&_self->ob_itself, theAEKeyword, desiredType, &typeCode, dataPtr__out__, dataPtr__len__, &dataPtr__len__); if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("O&s#", PyMac_BuildOSType, typeCode, dataPtr__out__, (int)dataPtr__len__); free(dataPtr__out__); dataPtr__error__: ; return _res; } static PyObject *AEDesc_AEGetParamDesc(_self, _args) AEDescObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; AEKeyword theAEKeyword; DescType desiredType; AEDesc result; if (!PyArg_ParseTuple(_args, "O&O&", PyMac_GetOSType, &theAEKeyword, PyMac_GetOSType, &desiredType)) return NULL; _err = AEGetParamDesc(&_self->ob_itself, theAEKeyword, desiredType, &result); if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("O&", AEDesc_New, &result); return _res; } static PyObject *AEDesc_AESizeOfParam(_self, _args) AEDescObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; AEKeyword theAEKeyword; DescType typeCode; Size dataSize; if (!PyArg_ParseTuple(_args, "O&", PyMac_GetOSType, &theAEKeyword)) return NULL; _err = AESizeOfParam(&_self->ob_itself, theAEKeyword, &typeCode, &dataSize); if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("O&l", PyMac_BuildOSType, typeCode, dataSize); return _res; } static PyObject *AEDesc_AEDeleteParam(_self, _args) AEDescObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; AEKeyword theAEKeyword; if (!PyArg_ParseTuple(_args, "O&", PyMac_GetOSType, &theAEKeyword)) return NULL; _err = AEDeleteParam(&_self->ob_itself, theAEKeyword); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *AEDesc_AEGetAttributePtr(_self, _args) AEDescObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; AEKeyword theAEKeyword; DescType desiredType; DescType typeCode; char *dataPtr__out__; long dataPtr__len__; int dataPtr__in_len__; if (!PyArg_ParseTuple(_args, "O&O&i", PyMac_GetOSType, &theAEKeyword, PyMac_GetOSType, &desiredType, &dataPtr__in_len__)) return NULL; if ((dataPtr__out__ = malloc(dataPtr__in_len__)) == NULL) { PyErr_NoMemory(); goto dataPtr__error__; } dataPtr__len__ = dataPtr__in_len__; _err = AEGetAttributePtr(&_self->ob_itself, theAEKeyword, desiredType, &typeCode, dataPtr__out__, dataPtr__len__, &dataPtr__len__); if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("O&s#", PyMac_BuildOSType, typeCode, dataPtr__out__, (int)dataPtr__len__); free(dataPtr__out__); dataPtr__error__: ; return _res; } static PyObject *AEDesc_AEGetAttributeDesc(_self, _args) AEDescObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; AEKeyword theAEKeyword; DescType desiredType; AEDesc result; if (!PyArg_ParseTuple(_args, "O&O&", PyMac_GetOSType, &theAEKeyword, PyMac_GetOSType, &desiredType)) return NULL; _err = AEGetAttributeDesc(&_self->ob_itself, theAEKeyword, desiredType, &result); if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("O&", AEDesc_New, &result); return _res; } static PyObject *AEDesc_AESizeOfAttribute(_self, _args) AEDescObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; AEKeyword theAEKeyword; DescType typeCode; Size dataSize; if (!PyArg_ParseTuple(_args, "O&", PyMac_GetOSType, &theAEKeyword)) return NULL; _err = AESizeOfAttribute(&_self->ob_itself, theAEKeyword, &typeCode, &dataSize); if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("O&l", PyMac_BuildOSType, typeCode, dataSize); return _res; } static PyObject *AEDesc_AEPutAttributePtr(_self, _args) AEDescObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; AEKeyword theAEKeyword; DescType typeCode; char *dataPtr__in__; long dataPtr__len__; int dataPtr__in_len__; if (!PyArg_ParseTuple(_args, "O&O&s#", PyMac_GetOSType, &theAEKeyword, PyMac_GetOSType, &typeCode, &dataPtr__in__, &dataPtr__in_len__)) return NULL; dataPtr__len__ = dataPtr__in_len__; _err = AEPutAttributePtr(&_self->ob_itself, theAEKeyword, typeCode, dataPtr__in__, dataPtr__len__); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; dataPtr__error__: ; return _res; } static PyObject *AEDesc_AEPutAttributeDesc(_self, _args) AEDescObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; AEKeyword theAEKeyword; AEDesc theAEDesc; if (!PyArg_ParseTuple(_args, "O&O&", PyMac_GetOSType, &theAEKeyword, AEDesc_Convert, &theAEDesc)) return NULL; _err = AEPutAttributeDesc(&_self->ob_itself, theAEKeyword, &theAEDesc); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyMethodDef AEDesc_methods[] = { {"AESend", (PyCFunction)AEDesc_AESend, 1, "(AESendMode sendMode, AESendPriority sendPriority, long timeOutInTicks) -> (AppleEvent reply)"}, {"AEResetTimer", (PyCFunction)AEDesc_AEResetTimer, 1, "() -> None"}, {"AESuspendTheCurrentEvent", (PyCFunction)AEDesc_AESuspendTheCurrentEvent, 1, "() -> None"}, {"AEResumeTheCurrentEvent", (PyCFunction)AEDesc_AEResumeTheCurrentEvent, 1, "(AppleEvent reply, EventHandler dispatcher) -> None"}, {"AEGetTheCurrentEvent", (PyCFunction)AEDesc_AEGetTheCurrentEvent, 1, "() -> None"}, {"AESetTheCurrentEvent", (PyCFunction)AEDesc_AESetTheCurrentEvent, 1, "() -> None"}, {"AECoerceDesc", (PyCFunction)AEDesc_AECoerceDesc, 1, "(DescType toType) -> (AEDesc result)"}, {"AEDuplicateDesc", (PyCFunction)AEDesc_AEDuplicateDesc, 1, "() -> (AEDesc result)"}, {"AECountItems", (PyCFunction)AEDesc_AECountItems, 1, "() -> (long theCount)"}, {"AEPutPtr", (PyCFunction)AEDesc_AEPutPtr, 1, "(long index, DescType typeCode, Buffer dataPtr) -> None"}, {"AEPutDesc", (PyCFunction)AEDesc_AEPutDesc, 1, "(long index, AEDesc theAEDesc) -> None"}, {"AEGetNthPtr", (PyCFunction)AEDesc_AEGetNthPtr, 1, "(long index, DescType desiredType, Buffer dataPtr) -> (AEKeyword theAEKeyword, DescType typeCode, Buffer dataPtr)"}, {"AEGetNthDesc", (PyCFunction)AEDesc_AEGetNthDesc, 1, "(long index, DescType desiredType) -> (AEKeyword theAEKeyword, AEDesc result)"}, {"AESizeOfNthItem", (PyCFunction)AEDesc_AESizeOfNthItem, 1, "(long index) -> (DescType typeCode, Size dataSize)"}, {"AEDeleteItem", (PyCFunction)AEDesc_AEDeleteItem, 1, "(long index) -> None"}, {"AEPutParamPtr", (PyCFunction)AEDesc_AEPutParamPtr, 1, "(AEKeyword theAEKeyword, DescType typeCode, Buffer dataPtr) -> None"}, {"AEPutParamDesc", (PyCFunction)AEDesc_AEPutParamDesc, 1, "(AEKeyword theAEKeyword, AEDesc theAEDesc) -> None"}, {"AEGetParamPtr", (PyCFunction)AEDesc_AEGetParamPtr, 1, "(AEKeyword theAEKeyword, DescType desiredType, Buffer dataPtr) -> (DescType typeCode, Buffer dataPtr)"}, {"AEGetParamDesc", (PyCFunction)AEDesc_AEGetParamDesc, 1, "(AEKeyword theAEKeyword, DescType desiredType) -> (AEDesc result)"}, {"AESizeOfParam", (PyCFunction)AEDesc_AESizeOfParam, 1, "(AEKeyword theAEKeyword) -> (DescType typeCode, Size dataSize)"}, {"AEDeleteParam", (PyCFunction)AEDesc_AEDeleteParam, 1, "(AEKeyword theAEKeyword) -> None"}, {"AEGetAttributePtr", (PyCFunction)AEDesc_AEGetAttributePtr, 1, "(AEKeyword theAEKeyword, DescType desiredType, Buffer dataPtr) -> (DescType typeCode, Buffer dataPtr)"}, {"AEGetAttributeDesc", (PyCFunction)AEDesc_AEGetAttributeDesc, 1, "(AEKeyword theAEKeyword, DescType desiredType) -> (AEDesc result)"}, {"AESizeOfAttribute", (PyCFunction)AEDesc_AESizeOfAttribute, 1, "(AEKeyword theAEKeyword) -> (DescType typeCode, Size dataSize)"}, {"AEPutAttributePtr", (PyCFunction)AEDesc_AEPutAttributePtr, 1, "(AEKeyword theAEKeyword, DescType typeCode, Buffer dataPtr) -> None"}, {"AEPutAttributeDesc", (PyCFunction)AEDesc_AEPutAttributeDesc, 1, "(AEKeyword theAEKeyword, AEDesc theAEDesc) -> None"}, {NULL, NULL, 0} }; PyMethodChain AEDesc_chain = { AEDesc_methods, NULL }; static PyObject *AEDesc_getattr(self, name) AEDescObject *self; char *name; { if (strcmp(name, "type") == 0) return PyMac_BuildOSType(self->ob_itself.descriptorType); if (strcmp(name, "data") == 0) { PyObject *res; char state; state = HGetState(self->ob_itself.dataHandle); HLock(self->ob_itself.dataHandle); res = PyString_FromStringAndSize( *self->ob_itself.dataHandle, GetHandleSize(self->ob_itself.dataHandle)); HUnlock(self->ob_itself.dataHandle); HSetState(self->ob_itself.dataHandle, state); return res; } if (strcmp(name, "__members__") == 0) return Py_BuildValue("[ss]", "data", "type"); return Py_FindMethodInChain(&AEDesc_chain, (PyObject *)self, name); } #define AEDesc_setattr NULL PyTypeObject AEDesc_Type = { PyObject_HEAD_INIT(&PyType_Type) 0, /*ob_size*/ "AEDesc", /*tp_name*/ sizeof(AEDescObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ /* methods */ (destructor) AEDesc_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ (getattrfunc) AEDesc_getattr, /*tp_getattr*/ (setattrfunc) AEDesc_setattr, /*tp_setattr*/ }; /* --------------------- End object type AEDesc --------------------- */ static PyObject *AE_AEProcessAppleEvent(_self, _args) PyObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; EventRecord theEventRecord; if (!PyArg_ParseTuple(_args, "O&", PyMac_GetEventRecord, &theEventRecord)) return NULL; _err = AEProcessAppleEvent(&theEventRecord); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *AE_AEGetInteractionAllowed(_self, _args) PyObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; AEInteractAllowed level; if (!PyArg_ParseTuple(_args, "")) return NULL; _err = AEGetInteractionAllowed(&level); if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("b", level); return _res; } static PyObject *AE_AESetInteractionAllowed(_self, _args) PyObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; AEInteractAllowed level; if (!PyArg_ParseTuple(_args, "b", &level)) return NULL; _err = AESetInteractionAllowed(level); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *AE_AEInteractWithUser(_self, _args) PyObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; long timeOutInTicks; if (!PyArg_ParseTuple(_args, "l", &timeOutInTicks)) return NULL; _err = AEInteractWithUser(timeOutInTicks, (NMRecPtr)0, upp_AEIdleProc); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *AE_AEInstallEventHandler(_self, _args) PyObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; AEEventClass theAEEventClass; AEEventID theAEEventID; AEEventHandlerUPP handler__proc__ = upp_GenericEventHandler; PyObject *handler; if (!PyArg_ParseTuple(_args, "O&O&O", PyMac_GetOSType, &theAEEventClass, PyMac_GetOSType, &theAEEventID, &handler)) return NULL; _err = AEInstallEventHandler(theAEEventClass, theAEEventID, handler__proc__, (long)handler, 0); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; Py_INCREF(handler); /* XXX leak, but needed */ return _res; } static PyObject *AE_AERemoveEventHandler(_self, _args) PyObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; AEEventClass theAEEventClass; AEEventID theAEEventID; if (!PyArg_ParseTuple(_args, "O&O&", PyMac_GetOSType, &theAEEventClass, PyMac_GetOSType, &theAEEventID)) return NULL; _err = AERemoveEventHandler(theAEEventClass, theAEEventID, upp_GenericEventHandler, 0); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *AE_AEGetEventHandler(_self, _args) PyObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; AEEventClass theAEEventClass; AEEventID theAEEventID; AEEventHandlerUPP handler__proc__ = upp_GenericEventHandler; PyObject *handler; if (!PyArg_ParseTuple(_args, "O&O&", PyMac_GetOSType, &theAEEventClass, PyMac_GetOSType, &theAEEventID)) return NULL; _err = AEGetEventHandler(theAEEventClass, theAEEventID, &handler__proc__, (long *)&handler, 0); if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("O", handler); Py_INCREF(handler); /* XXX leak, but needed */ return _res; } static PyObject *AE_AEManagerInfo(_self, _args) PyObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; AEKeyword keyWord; long result; if (!PyArg_ParseTuple(_args, "O&", PyMac_GetOSType, &keyWord)) return NULL; _err = AEManagerInfo(keyWord, &result); if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("l", result); return _res; } static PyObject *AE_AECoercePtr(_self, _args) PyObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; DescType typeCode; char *dataPtr__in__; long dataPtr__len__; int dataPtr__in_len__; DescType toType; AEDesc result; if (!PyArg_ParseTuple(_args, "O&s#O&", PyMac_GetOSType, &typeCode, &dataPtr__in__, &dataPtr__in_len__, PyMac_GetOSType, &toType)) return NULL; dataPtr__len__ = dataPtr__in_len__; _err = AECoercePtr(typeCode, dataPtr__in__, dataPtr__len__, toType, &result); if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("O&", AEDesc_New, &result); dataPtr__error__: ; return _res; } static PyObject *AE_AECreateDesc(_self, _args) PyObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; DescType typeCode; char *dataPtr__in__; long dataPtr__len__; int dataPtr__in_len__; AEDesc result; if (!PyArg_ParseTuple(_args, "O&s#", PyMac_GetOSType, &typeCode, &dataPtr__in__, &dataPtr__in_len__)) return NULL; dataPtr__len__ = dataPtr__in_len__; _err = AECreateDesc(typeCode, dataPtr__in__, dataPtr__len__, &result); if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("O&", AEDesc_New, &result); dataPtr__error__: ; return _res; } static PyObject *AE_AECreateList(_self, _args) PyObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; char *factoringPtr__in__; long factoringPtr__len__; int factoringPtr__in_len__; Boolean isRecord; AEDescList resultList; if (!PyArg_ParseTuple(_args, "s#b", &factoringPtr__in__, &factoringPtr__in_len__, &isRecord)) return NULL; factoringPtr__len__ = factoringPtr__in_len__; _err = AECreateList(factoringPtr__in__, factoringPtr__len__, isRecord, &resultList); if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("O&", AEDesc_New, &resultList); factoringPtr__error__: ; return _res; } static PyObject *AE_AECreateAppleEvent(_self, _args) PyObject *_self; PyObject *_args; { PyObject *_res = NULL; OSErr _err; AEEventClass theAEEventClass; AEEventID theAEEventID; AEAddressDesc target; AEReturnID returnID; AETransactionID transactionID; AppleEvent result; if (!PyArg_ParseTuple(_args, "O&O&O&hh", PyMac_GetOSType, &theAEEventClass, PyMac_GetOSType, &theAEEventID, AEDesc_Convert, &target, &returnID, &transactionID)) return NULL; _err = AECreateAppleEvent(theAEEventClass, theAEEventID, &target, returnID, transactionID, &result); if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("O&", AEDesc_New, &result); return _res; } static PyMethodDef AE_methods[] = { {"AEProcessAppleEvent", (PyCFunction)AE_AEProcessAppleEvent, 1, "(EventRecord theEventRecord) -> None"}, {"AEGetInteractionAllowed", (PyCFunction)AE_AEGetInteractionAllowed, 1, "() -> (AEInteractAllowed level)"}, {"AESetInteractionAllowed", (PyCFunction)AE_AESetInteractionAllowed, 1, "(AEInteractAllowed level) -> None"}, {"AEInteractWithUser", (PyCFunction)AE_AEInteractWithUser, 1, "(long timeOutInTicks) -> None"}, {"AEInstallEventHandler", (PyCFunction)AE_AEInstallEventHandler, 1, "(AEEventClass theAEEventClass, AEEventID theAEEventID, EventHandler handler) -> None"}, {"AERemoveEventHandler", (PyCFunction)AE_AERemoveEventHandler, 1, "(AEEventClass theAEEventClass, AEEventID theAEEventID) -> None"}, {"AEGetEventHandler", (PyCFunction)AE_AEGetEventHandler, 1, "(AEEventClass theAEEventClass, AEEventID theAEEventID) -> (EventHandler handler)"}, {"AEManagerInfo", (PyCFunction)AE_AEManagerInfo, 1, "(AEKeyword keyWord) -> (long result)"}, {"AECoercePtr", (PyCFunction)AE_AECoercePtr, 1, "(DescType typeCode, Buffer dataPtr, DescType toType) -> (AEDesc result)"}, {"AECreateDesc", (PyCFunction)AE_AECreateDesc, 1, "(DescType typeCode, Buffer dataPtr) -> (AEDesc result)"}, {"AECreateList", (PyCFunction)AE_AECreateList, 1, "(Buffer factoringPtr, Boolean isRecord) -> (AEDescList resultList)"}, {"AECreateAppleEvent", (PyCFunction)AE_AECreateAppleEvent, 1, "(AEEventClass theAEEventClass, AEEventID theAEEventID, AEAddressDesc target, AEReturnID returnID, AETransactionID transactionID) -> (AppleEvent result)"}, {NULL, NULL, 0} }; static pascal OSErr GenericEventHandler(AppleEvent *request, AppleEvent *reply, long refcon) { PyObject *handler = (PyObject *)refcon; AEDescObject *requestObject, *replyObject; PyObject *args, *res; if ((requestObject = (AEDescObject *)AEDesc_New(request)) == NULL) { return -1; } if ((replyObject = (AEDescObject *)AEDesc_New(reply)) == NULL) { Py_DECREF(requestObject); return -1; } if ((args = Py_BuildValue("OO", requestObject, replyObject)) == NULL) { Py_DECREF(requestObject); Py_DECREF(replyObject); return -1; } res = PyEval_CallObject(handler, args); requestObject->ob_itself.descriptorType = 'null'; requestObject->ob_itself.dataHandle = NULL; replyObject->ob_itself.descriptorType = 'null'; replyObject->ob_itself.dataHandle = NULL; Py_DECREF(args); if (res == NULL) return -1; Py_DECREF(res); return noErr; } void initAE() { PyObject *m; PyObject *d; upp_AEIdleProc = NewAEIdleProc(AEIdleProc); upp_GenericEventHandler = NewAEEventHandlerProc(GenericEventHandler); m = Py_InitModule("AE", AE_methods); d = PyModule_GetDict(m); AE_Error = PyMac_GetOSErrException(); if (AE_Error == NULL || PyDict_SetItemString(d, "Error", AE_Error) != 0) Py_FatalError("can't initialize AE.Error"); AEDesc_Type.ob_type = &PyType_Type; Py_INCREF(&AEDesc_Type); if (PyDict_SetItemString(d, "AEDescType", (PyObject *)&AEDesc_Type) != 0) Py_FatalError("can't initialize AEDescType"); } /* ========================= End module AE ========================== */
28.660789
157
0.653933
[ "object" ]
2429e9e44e95de0609f789a2ee174e57483639c2
3,964
c
C
ConfProfile/jni/strongswan/src/libcharon/plugins/uci/uci_parser.c
Infoss/conf-profile-4-android
619bd63095bb0f5a67616436d5510d24a233a339
[ "MIT" ]
2
2017-10-16T07:51:18.000Z
2019-06-16T12:07:52.000Z
strongswan/strongswan-5.3.2/src/libcharon/plugins/uci/uci_parser.c
SECURED-FP7/secured-mobility-ned
36fdbfee58a31d42f7047f7a7eaa1b2b70246151
[ "Apache-2.0" ]
5
2016-01-25T18:04:42.000Z
2016-02-25T08:54:56.000Z
strongswan/strongswan-5.3.2/src/libcharon/plugins/uci/uci_parser.c
SECURED-FP7/secured-mobility-ned
36fdbfee58a31d42f7047f7a7eaa1b2b70246151
[ "Apache-2.0" ]
2
2016-01-25T17:14:17.000Z
2016-02-13T20:14:09.000Z
/* * Copyright (C) 2008 Martin Willi * Copyright (C) 2008 Thomas Kallenberg * Hochschule fuer Technik Rapperswil * * 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 2 of the License, or (at your * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>. * * 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. */ #include "uci_parser.h" #include <stdarg.h> #include <library.h> #include <uci.h> typedef struct private_uci_parser_t private_uci_parser_t; /** * Private data of an uci_parser_t object */ struct private_uci_parser_t { /** * Public part */ uci_parser_t public; /** * UCI package name this parser reads */ char *package; }; /** * enumerator implementation create_section_enumerator */ typedef struct { /** implements enumerator */ enumerator_t public; /** currently enumerated uci section */ struct uci_element *current; /** all uci ipsec config sections */ struct uci_list *list; /** uci conntext */ struct uci_context *ctx; /** ipsec uci package */ struct uci_package *package; /** NULL terminated list of keywords */ char *keywords[]; } section_enumerator_t; METHOD(enumerator_t, section_enumerator_enumerate, bool, section_enumerator_t *this, ...) { struct uci_element *element; char **value; va_list args; int i; if (&this->current->list == this->list) { return FALSE; } va_start(args, this); value = va_arg(args, char**); if (value) { if (uci_lookup(this->ctx, &element, this->package, this->current->name, "name") == UCI_OK) { /* use "name" attribute as config name if available ... */ *value = uci_to_option(element)->value; } else { /* ... or the section name becomes config name */ *value = uci_to_section(this->current)->type; } } /* followed by keyword parameters */ for (i = 0; this->keywords[i]; i++) { value = va_arg(args, char**); if (value && uci_lookup(this->ctx, &element, this->package, this->current->name, this->keywords[i]) == UCI_OK) { *value = uci_to_option(element)->value; } } va_end(args); this->current = list_to_element(this->current->list.next); return TRUE; } METHOD(enumerator_t, section_enumerator_destroy, void, section_enumerator_t *this) { uci_free_context(this->ctx); free(this); } METHOD(uci_parser_t, create_section_enumerator, enumerator_t*, private_uci_parser_t *this, ...) { section_enumerator_t *e; va_list args; int i; /* allocate enumerator large enought to hold keyword pointers */ i = 1; va_start(args, this); while (va_arg(args, char*)) { i++; } va_end(args); e = malloc(sizeof(section_enumerator_t) + sizeof(char*) * i); i = 0; va_start(args, this); do { e->keywords[i] = va_arg(args, char*); } while (e->keywords[i++]); va_end(args); e->public.enumerate = (void*)_section_enumerator_enumerate; e->public.destroy = _section_enumerator_destroy; /* load uci context */ e->ctx = uci_alloc_context(); if (uci_load(e->ctx, this->package, &e->package) != UCI_OK) { section_enumerator_destroy(e); return NULL; } e->list = &e->package->sections; e->current = list_to_element(e->list->next); if (e->current->type != UCI_TYPE_SECTION) { section_enumerator_destroy(e); return NULL; } return &e->public; } METHOD(uci_parser_t, destroy, void, private_uci_parser_t *this) { free(this->package); free(this); } /** * Described in header. */ uci_parser_t *uci_parser_create(char *package) { private_uci_parser_t *this; INIT(this, .public = { .create_section_enumerator = _create_section_enumerator, .destroy = _destroy, }, .package = strdup(package), ); return &this->public; }
21.78022
77
0.690716
[ "object" ]
242de2c3582f2383df231d6b7e37806c1ad7733f
1,751
c
C
platform/lpc/lpc11exx/flash_base.c
stxent/lpclib
d1190bbacd68d72d9f04b71a1e208702aa838986
[ "MIT" ]
3
2015-06-06T18:37:13.000Z
2021-01-29T15:51:45.000Z
platform/lpc/lpc11exx/flash_base.c
stxent/lpclib
d1190bbacd68d72d9f04b71a1e208702aa838986
[ "MIT" ]
null
null
null
platform/lpc/lpc11exx/flash_base.c
stxent/lpclib
d1190bbacd68d72d9f04b71a1e208702aa838986
[ "MIT" ]
null
null
null
/* * flash_base.c * Copyright (C) 2020 xent * Project is distributed under the terms of the MIT License */ #include <halm/platform/lpc/flash_base.h> #include <halm/platform/lpc/flash_defs.h> #include <halm/platform/lpc/iap.h> /*----------------------------------------------------------------------------*/ static enum Result flashInit(void *, const void *); /*----------------------------------------------------------------------------*/ const struct EntityClass * const FlashBase = &(const struct EntityClass){ .size = sizeof(struct FlashBase), .init = flashInit, .deinit = 0 /* Default destructor */ }; /*----------------------------------------------------------------------------*/ static enum Result flashInit(void *object, const void *configBase __attribute__((unused))) { struct FlashBase * const interface = object; const uint32_t id = flashReadId(); switch (id) { case CODE_LPC11E11_101: interface->size = 8 * 1024; break; case CODE_LPC11E12_201: interface->size = 16 * 1024; break; case CODE_LPC11E13_301: interface->size = 24 * 1024; break; case CODE_LPC11E14_401: interface->size = 32 * 1024; break; case CODE_LPC11E66: case CODE_LPC11U66: interface->size = 64 * 1024; break; case CODE_LPC11E36_501: interface->size = 96 * 1024; break; case CODE_LPC11E37_401: case CODE_LPC11E37_501: case CODE_LPC11E67: case CODE_LPC11U67_1: case CODE_LPC11U67_2: interface->size = 128 * 1024; break; case CODE_LPC11E68: case CODE_LPC11U68_1: case CODE_LPC11U68_2: interface->size = 256 * 1024; break; default: return E_ERROR; } return E_OK; }
24.319444
80
0.561393
[ "object" ]
2433eda0092b4ace6ba2a0c6e00a14145043898e
1,536
h
C
Gems/Terrain/Code/Source/EditorComponents/EditorTerrainHeightGradientListComponent.h
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
1
2021-08-11T02:20:46.000Z
2021-08-11T02:20:46.000Z
Gems/Terrain/Code/Source/EditorComponents/EditorTerrainHeightGradientListComponent.h
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
3
2021-09-08T03:41:27.000Z
2022-03-12T01:01:29.000Z
Gems/Terrain/Code/Source/EditorComponents/EditorTerrainHeightGradientListComponent.h
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #pragma once #include <Components/TerrainHeightGradientListComponent.h> #include <AzToolsFramework/ToolsComponents/EditorComponentBase.h> #include <LmbrCentral/Component/EditorWrappedComponentBase.h> namespace Terrain { class EditorTerrainHeightGradientListComponent : public LmbrCentral::EditorWrappedComponentBase<TerrainHeightGradientListComponent, TerrainHeightGradientListConfig> { public: using BaseClassType = LmbrCentral::EditorWrappedComponentBase<TerrainHeightGradientListComponent, TerrainHeightGradientListConfig>; AZ_EDITOR_COMPONENT(EditorTerrainHeightGradientListComponent, "{2D945B90-ADAB-4F9A-A113-39E714708068}", BaseClassType); static void Reflect(AZ::ReflectContext* context); static constexpr const char* const s_categoryName = "Terrain"; static constexpr const char* const s_componentName = "Terrain Height Gradient List"; static constexpr const char* const s_componentDescription = "Provides height data for a region to the terrain system"; static constexpr const char* const s_icon = "Editor/Icons/Components/TerrainHeight.svg"; static constexpr const char* const s_viewportIcon = "Editor/Icons/Components/Viewport/TerrainHeight.svg"; static constexpr const char* const s_helpUrl = ""; }; }
46.545455
139
0.773438
[ "3d" ]
243b995ed76e4952183d55030c589307b086a879
31,998
c
C
usr/src/uts/common/io/usb/usb_ia/usb_ia.c
AsahiOS/gate
283d47da4e17a5871d9d575e7ffb81e8f6c52e51
[ "MIT" ]
null
null
null
usr/src/uts/common/io/usb/usb_ia/usb_ia.c
AsahiOS/gate
283d47da4e17a5871d9d575e7ffb81e8f6c52e51
[ "MIT" ]
null
null
null
usr/src/uts/common/io/usb/usb_ia/usb_ia.c
AsahiOS/gate
283d47da4e17a5871d9d575e7ffb81e8f6c52e51
[ "MIT" ]
1
2020-12-30T00:04:16.000Z
2020-12-30T00:04:16.000Z
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ /* * Copyright 2012 Garrett D'Amore <garrett@damore.org>. All rights reserved. */ /* * usb interface association driver * * this driver attempts to the interface association node and * creates/manages child nodes for the included interfaces. */ #if defined(lint) && !defined(DEBUG) #define DEBUG 1 #endif #include <sys/usb/usba/usbai_version.h> #include <sys/usb/usba.h> #include <sys/usb/usba/usba_types.h> #include <sys/usb/usba/usba_impl.h> #include <sys/usb/usb_ia/usb_iavar.h> /* Debugging support */ uint_t usb_ia_errlevel = USB_LOG_L4; uint_t usb_ia_errmask = (uint_t)DPRINT_MASK_ALL; uint_t usb_ia_instance_debug = (uint_t)-1; uint_t usb_ia_bus_config_debug = 0; _NOTE(DATA_READABLE_WITHOUT_LOCK(usb_ia_errlevel)) _NOTE(DATA_READABLE_WITHOUT_LOCK(usb_ia_errmask)) _NOTE(DATA_READABLE_WITHOUT_LOCK(usb_ia_instance_debug)) _NOTE(SCHEME_PROTECTS_DATA("unique", msgb)) _NOTE(SCHEME_PROTECTS_DATA("unique", dev_info)) _NOTE(SCHEME_PROTECTS_DATA("unique", usb_pipe_policy)) static struct cb_ops usb_ia_cb_ops = { nodev, /* open */ nodev, /* close */ nodev, /* strategy */ nodev, /* print */ nodev, /* dump */ nodev, /* read */ nodev, /* write */ nodev, /* ioctl */ nodev, /* devmap */ nodev, /* mmap */ nodev, /* segmap */ nochpoll, /* poll */ ddi_prop_op, /* prop_op */ NULL, /* aread */ D_MP }; static int usb_ia_busop_get_eventcookie(dev_info_t *dip, dev_info_t *rdip, char *eventname, ddi_eventcookie_t *cookie); static int usb_ia_busop_add_eventcall(dev_info_t *dip, dev_info_t *rdip, ddi_eventcookie_t cookie, void (*callback)(dev_info_t *dip, ddi_eventcookie_t cookie, void *arg, void *bus_impldata), void *arg, ddi_callback_id_t *cb_id); static int usb_ia_busop_remove_eventcall(dev_info_t *dip, ddi_callback_id_t cb_id); static int usb_ia_busop_post_event(dev_info_t *dip, dev_info_t *rdip, ddi_eventcookie_t cookie, void *bus_impldata); static int usb_ia_bus_config(dev_info_t *dip, uint_t flag, ddi_bus_config_op_t op, void *arg, dev_info_t **child); static int usb_ia_bus_unconfig(dev_info_t *dip, uint_t flag, ddi_bus_config_op_t op, void *arg); /* * autoconfiguration data and routines. */ static int usb_ia_info(dev_info_t *, ddi_info_cmd_t, void *, void **); static int usb_ia_attach(dev_info_t *, ddi_attach_cmd_t); static int usb_ia_detach(dev_info_t *, ddi_detach_cmd_t); /* other routines */ static void usb_ia_create_pm_components(dev_info_t *, usb_ia_t *); static int usb_ia_bus_ctl(dev_info_t *, dev_info_t *, ddi_ctl_enum_t, void *, void *); static int usb_ia_power(dev_info_t *, int, int); static int usb_ia_restore_device_state(dev_info_t *, usb_ia_t *); static usb_ia_t *usb_ia_obtain_state(dev_info_t *); static void usb_ia_event_cb(dev_info_t *, ddi_eventcookie_t, void *, void *); /* prototypes */ static void usb_ia_create_children(usb_ia_t *); static int usb_ia_cleanup(usb_ia_t *); /* * Busops vector */ static struct bus_ops usb_ia_busops = { BUSO_REV, nullbusmap, /* bus_map */ NULL, /* bus_get_intrspec */ NULL, /* bus_add_intrspec */ NULL, /* bus_remove_intrspec */ NULL, /* XXXX bus_map_fault */ NULL, /* bus_dma_map */ ddi_dma_allochdl, ddi_dma_freehdl, ddi_dma_bindhdl, ddi_dma_unbindhdl, ddi_dma_flush, ddi_dma_win, ddi_dma_mctl, /* bus_dma_ctl */ usb_ia_bus_ctl, /* bus_ctl */ ddi_bus_prop_op, /* bus_prop_op */ usb_ia_busop_get_eventcookie, usb_ia_busop_add_eventcall, usb_ia_busop_remove_eventcall, usb_ia_busop_post_event, /* bus_post_event */ NULL, /* bus_intr_ctl */ usb_ia_bus_config, /* bus_config */ usb_ia_bus_unconfig, /* bus_unconfig */ NULL, /* bus_fm_init */ NULL, /* bus_fm_fini */ NULL, /* bus_fm_access_enter */ NULL, /* bus_fm_access_exit */ NULL /* bus_power */ }; static struct dev_ops usb_ia_ops = { DEVO_REV, /* devo_rev, */ 0, /* refcnt */ usb_ia_info, /* info */ nulldev, /* identify */ nulldev, /* probe */ usb_ia_attach, /* attach */ usb_ia_detach, /* detach */ nodev, /* reset */ &usb_ia_cb_ops, /* driver operations */ &usb_ia_busops, /* bus operations */ usb_ia_power, /* power */ ddi_quiesce_not_needed, /* devo_quiesce */ }; static struct modldrv modldrv = { &mod_driverops, /* Type of module. This one is a driver */ "USB Interface Association Driver", /* Name of the module. */ &usb_ia_ops, /* driver ops */ }; static struct modlinkage modlinkage = { MODREV_1, (void *)&modldrv, NULL }; #define USB_IA_INITIAL_SOFT_SPACE 4 static void *usb_ia_statep; /* * event definition */ static ndi_event_definition_t usb_ia_ndi_event_defs[] = { {USBA_EVENT_TAG_HOT_REMOVAL, DDI_DEVI_REMOVE_EVENT, EPL_KERNEL, NDI_EVENT_POST_TO_ALL}, {USBA_EVENT_TAG_HOT_INSERTION, DDI_DEVI_INSERT_EVENT, EPL_KERNEL, NDI_EVENT_POST_TO_ALL}, {USBA_EVENT_TAG_POST_RESUME, USBA_POST_RESUME_EVENT, EPL_KERNEL, NDI_EVENT_POST_TO_ALL}, {USBA_EVENT_TAG_PRE_SUSPEND, USBA_PRE_SUSPEND_EVENT, EPL_KERNEL, NDI_EVENT_POST_TO_ALL} }; #define USB_IA_N_NDI_EVENTS \ (sizeof (usb_ia_ndi_event_defs) / sizeof (ndi_event_definition_t)) static ndi_event_set_t usb_ia_ndi_events = { NDI_EVENTS_REV1, USB_IA_N_NDI_EVENTS, usb_ia_ndi_event_defs}; /* * standard driver entry points */ int _init(void) { int rval; rval = ddi_soft_state_init(&usb_ia_statep, sizeof (struct usb_ia), USB_IA_INITIAL_SOFT_SPACE); if (rval != 0) { return (rval); } if ((rval = mod_install(&modlinkage)) != 0) { ddi_soft_state_fini(&usb_ia_statep); return (rval); } return (rval); } int _fini(void) { int rval; rval = mod_remove(&modlinkage); if (rval) { return (rval); } ddi_soft_state_fini(&usb_ia_statep); return (rval); } int _info(struct modinfo *modinfop) { return (mod_info(&modlinkage, modinfop)); } /*ARGSUSED*/ static int usb_ia_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result) { usb_ia_t *usb_ia; int instance = getminor((dev_t)arg); int error = DDI_FAILURE; switch (infocmd) { case DDI_INFO_DEVT2DEVINFO: if ((usb_ia = ddi_get_soft_state(usb_ia_statep, instance)) != NULL) { *result = (void *)usb_ia->ia_dip; if (*result != NULL) { error = DDI_SUCCESS; } } else { *result = NULL; } break; case DDI_INFO_DEVT2INSTANCE: *result = (void *)(intptr_t)instance; error = DDI_SUCCESS; break; default: break; } return (error); } /* * child post attach/detach notification */ static void usb_ia_post_attach(usb_ia_t *usb_ia, uint8_t ifno, struct attachspec *as) { USB_DPRINTF_L4(DPRINT_MASK_PM, usb_ia->ia_log_handle, "usb_ia_post_attach: ifno = %d result = %d", ifno, as->result); } static void usb_ia_post_detach(usb_ia_t *usb_ia, uint8_t ifno, struct detachspec *ds) { USB_DPRINTF_L4(DPRINT_MASK_PM, usb_ia->ia_log_handle, "usb_ia_post_detach: ifno = %d result = %d", ifno, ds->result); } /* * bus ctl support. we handle notifications here and the * rest goes up to root hub/hcd */ /*ARGSUSED*/ static int usb_ia_bus_ctl(dev_info_t *dip, dev_info_t *rdip, ddi_ctl_enum_t op, void *arg, void *result) { usba_device_t *hub_usba_device = usba_get_usba_device(rdip); dev_info_t *root_hub_dip = hub_usba_device->usb_root_hub_dip; usb_ia_t *usb_ia; struct attachspec *as; struct detachspec *ds; usb_ia = usb_ia_obtain_state(dip); USB_DPRINTF_L4(DPRINT_MASK_PM, usb_ia->ia_log_handle, "usb_ia_bus_ctl:\n\t" "dip = 0x%p, rdip = 0x%p, op = 0x%x, arg = 0x%p", (void *)dip, (void *)rdip, op, arg); switch (op) { case DDI_CTLOPS_ATTACH: as = (struct attachspec *)arg; switch (as->when) { case DDI_PRE : /* nothing to do basically */ USB_DPRINTF_L2(DPRINT_MASK_PM, usb_ia->ia_log_handle, "DDI_PRE DDI_CTLOPS_ATTACH"); break; case DDI_POST : usb_ia_post_attach(usb_ia, usba_get_ifno(rdip), (struct attachspec *)arg); break; } break; case DDI_CTLOPS_DETACH: ds = (struct detachspec *)arg; switch (ds->when) { case DDI_PRE : /* nothing to do basically */ USB_DPRINTF_L2(DPRINT_MASK_PM, usb_ia->ia_log_handle, "DDI_PRE DDI_CTLOPS_DETACH"); break; case DDI_POST : usb_ia_post_detach(usb_ia, usba_get_ifno(rdip), (struct detachspec *)arg); break; } break; default: /* pass to root hub to handle */ return (usba_bus_ctl(root_hub_dip, rdip, op, arg, result)); } return (DDI_SUCCESS); } /* * bus enumeration entry points */ static int usb_ia_bus_config(dev_info_t *dip, uint_t flag, ddi_bus_config_op_t op, void *arg, dev_info_t **child) { int rval, circ; usb_ia_t *usb_ia = usb_ia_obtain_state(dip); USB_DPRINTF_L4(DPRINT_MASK_ALL, usb_ia->ia_log_handle, "usb_ia_bus_config: op=%d", op); if (usb_ia_bus_config_debug) { flag |= NDI_DEVI_DEBUG; } ndi_devi_enter(dip, &circ); /* enumerate each interface below us */ mutex_enter(&usb_ia->ia_mutex); usb_ia_create_children(usb_ia); mutex_exit(&usb_ia->ia_mutex); rval = ndi_busop_bus_config(dip, flag, op, arg, child, 0); ndi_devi_exit(dip, circ); return (rval); } static int usb_ia_bus_unconfig(dev_info_t *dip, uint_t flag, ddi_bus_config_op_t op, void *arg) { usb_ia_t *usb_ia = usb_ia_obtain_state(dip); dev_info_t *cdip, *mdip; int interface, circular_count; int rval = NDI_SUCCESS; USB_DPRINTF_L4(DPRINT_MASK_ALL, usb_ia->ia_log_handle, "usb_ia_bus_unconfig: op=%d", op); if (usb_ia_bus_config_debug) { flag |= NDI_DEVI_DEBUG; } /* * first offline and if offlining successful, then * remove children */ if (op == BUS_UNCONFIG_ALL) { flag &= ~(NDI_DEVI_REMOVE | NDI_UNCONFIG); } ndi_devi_enter(dip, &circular_count); rval = ndi_busop_bus_unconfig(dip, flag, op, arg); if (op == BUS_UNCONFIG_ALL && rval == NDI_SUCCESS && (flag & NDI_AUTODETACH) == 0) { flag |= NDI_DEVI_REMOVE; rval = ndi_busop_bus_unconfig(dip, flag, op, arg); } /* update children's list */ mutex_enter(&usb_ia->ia_mutex); for (interface = 0; usb_ia->ia_children_dips && (interface < usb_ia->ia_n_ifs); interface++) { mdip = usb_ia->ia_children_dips[interface]; /* now search if this dip still exists */ for (cdip = ddi_get_child(dip); cdip && (cdip != mdip); ) cdip = ddi_get_next_sibling(cdip); if (cdip != mdip) { /* we lost the dip on this interface */ usb_ia->ia_children_dips[interface] = NULL; } else if (cdip) { /* * keep in DS_INITALIZED to prevent parent * from detaching */ (void) ddi_initchild(ddi_get_parent(cdip), cdip); } } mutex_exit(&usb_ia->ia_mutex); ndi_devi_exit(dip, circular_count); USB_DPRINTF_L4(DPRINT_MASK_ALL, usb_ia->ia_log_handle, "usb_ia_bus_config: rval=%d", rval); return (rval); } /* power entry point */ /* ARGSUSED */ static int usb_ia_power(dev_info_t *dip, int comp, int level) { usb_ia_t *usb_ia; usb_common_power_t *pm; int rval = DDI_FAILURE; usb_ia = usb_ia_obtain_state(dip); USB_DPRINTF_L4(DPRINT_MASK_PM, usb_ia->ia_log_handle, "usb_ia_power: Begin: usb_ia = %p, level = %d", (void *)usb_ia, level); mutex_enter(&usb_ia->ia_mutex); pm = usb_ia->ia_pm; /* check if we are transitioning to a legal power level */ if (USB_DEV_PWRSTATE_OK(pm->uc_pwr_states, level)) { USB_DPRINTF_L2(DPRINT_MASK_PM, usb_ia->ia_log_handle, "usb_ia_power: illegal power level = %d " "uc_pwr_states = %x", level, pm->uc_pwr_states); mutex_exit(&usb_ia->ia_mutex); return (rval); } rval = usba_common_power(dip, &(pm->uc_current_power), &(usb_ia->ia_dev_state), level); mutex_exit(&usb_ia->ia_mutex); return (rval); } /* * attach/resume entry point */ static int usb_ia_attach(dev_info_t *dip, ddi_attach_cmd_t cmd) { int instance = ddi_get_instance(dip); usb_ia_t *usb_ia = NULL; uint_t n_ifs; size_t size; switch (cmd) { case DDI_ATTACH: break; case DDI_RESUME: usb_ia = ddi_get_soft_state(usb_ia_statep, instance); (void) usb_ia_restore_device_state(dip, usb_ia); return (DDI_SUCCESS); default: return (DDI_FAILURE); } /* * Attach: * * Allocate soft state and initialize */ if (ddi_soft_state_zalloc(usb_ia_statep, instance) != DDI_SUCCESS) { goto fail; } usb_ia = ddi_get_soft_state(usb_ia_statep, instance); if (usb_ia == NULL) { goto fail; } /* allocate handle for logging of messages */ usb_ia->ia_log_handle = usb_alloc_log_hdl(dip, "ia", &usb_ia_errlevel, &usb_ia_errmask, &usb_ia_instance_debug, 0); usb_ia->ia_dip = dip; usb_ia->ia_instance = instance; usb_ia->ia_first_if = ddi_prop_get_int(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS, "interface", -1); usb_ia->ia_n_ifs = ddi_prop_get_int(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS, "interface-count", -1); if (usb_ia->ia_first_if < 0 || usb_ia->ia_n_ifs < 0) { USB_DPRINTF_L2(DPRINT_MASK_ATTA, usb_ia->ia_log_handle, "interface-association property failed"); goto fail; } /* attach client driver to USBA */ if (usb_client_attach(dip, USBDRV_VERSION, 0) != USB_SUCCESS) { USB_DPRINTF_L2(DPRINT_MASK_ATTA, usb_ia->ia_log_handle, "usb_client_attach failed"); goto fail; } if (usb_get_dev_data(dip, &usb_ia->ia_dev_data, USB_PARSE_LVL_NONE, 0) != USB_SUCCESS) { USB_DPRINTF_L2(DPRINT_MASK_ATTA, usb_ia->ia_log_handle, "usb_get_dev_data failed"); goto fail; } mutex_init(&usb_ia->ia_mutex, NULL, MUTEX_DRIVER, usb_ia->ia_dev_data->dev_iblock_cookie); usb_free_dev_data(dip, usb_ia->ia_dev_data); usb_ia->ia_dev_data = NULL; usb_ia->ia_init_state |= USB_IA_LOCK_INIT; if (ddi_create_minor_node(dip, "usb_ia", S_IFCHR, instance, DDI_NT_NEXUS, 0) != DDI_SUCCESS) { USB_DPRINTF_L2(DPRINT_MASK_ATTA, usb_ia->ia_log_handle, "cannot create devctl minor node"); goto fail; } usb_ia->ia_init_state |= USB_IA_MINOR_NODE_CREATED; /* * allocate array for keeping track of child dips */ n_ifs = usb_ia->ia_n_ifs; usb_ia->ia_cd_list_length = size = (sizeof (dev_info_t *)) * n_ifs; usb_ia->ia_children_dips = kmem_zalloc(size, KM_SLEEP); usb_ia->ia_child_events = kmem_zalloc(sizeof (uint8_t) * n_ifs, KM_SLEEP); /* * Event handling: definition and registration * get event handle for events that we have defined */ (void) ndi_event_alloc_hdl(dip, 0, &usb_ia->ia_ndi_event_hdl, NDI_SLEEP); /* bind event set to the handle */ if (ndi_event_bind_set(usb_ia->ia_ndi_event_hdl, &usb_ia_ndi_events, NDI_SLEEP)) { USB_DPRINTF_L2(DPRINT_MASK_ATTA, usb_ia->ia_log_handle, "usb_ia_attach: binding event set failed"); goto fail; } usb_ia->ia_dev_state = USB_DEV_ONLINE; /* * now create components to power manage this device * before attaching children */ usb_ia_create_pm_components(dip, usb_ia); /* event registration for events from our parent */ usba_common_register_events(dip, n_ifs, usb_ia_event_cb); usb_ia->ia_init_state |= USB_IA_EVENTS_REGISTERED; ddi_report_dev(dip); return (DDI_SUCCESS); fail: USB_DPRINTF_L2(DPRINT_MASK_ATTA, NULL, "usb_ia%d cannot attach", instance); if (usb_ia) { (void) usb_ia_cleanup(usb_ia); } return (DDI_FAILURE); } /* detach or suspend this instance */ static int usb_ia_detach(dev_info_t *dip, ddi_detach_cmd_t cmd) { usb_ia_t *usb_ia = usb_ia_obtain_state(dip); USB_DPRINTF_L4(DPRINT_MASK_ATTA, usb_ia->ia_log_handle, "usb_ia_detach: cmd = 0x%x", cmd); switch (cmd) { case DDI_DETACH: return (usb_ia_cleanup(usb_ia)); case DDI_SUSPEND: /* nothing to do */ mutex_enter(&usb_ia->ia_mutex); usb_ia->ia_dev_state = USB_DEV_SUSPENDED; mutex_exit(&usb_ia->ia_mutex); return (DDI_SUCCESS); default: return (DDI_FAILURE); } _NOTE(NOT_REACHED) /* NOTREACHED */ } /* * usb_ia_cleanup: * cleanup usb_ia and deallocate. this function is called for * handling attach failures and detaching including dynamic * reconfiguration */ /*ARGSUSED*/ static int usb_ia_cleanup(usb_ia_t *usb_ia) { usb_common_power_t *iapm; int rval; dev_info_t *dip = usb_ia->ia_dip; USB_DPRINTF_L4(DPRINT_MASK_ATTA, usb_ia->ia_log_handle, "usb_ia_cleanup:"); if ((usb_ia->ia_init_state & USB_IA_LOCK_INIT) == 0) { goto done; } /* * deallocate events, if events are still registered * (ie. children still attached) then we have to fail the detach */ if (usb_ia->ia_ndi_event_hdl && (ndi_event_free_hdl(usb_ia->ia_ndi_event_hdl) != NDI_SUCCESS)) { USB_DPRINTF_L2(DPRINT_MASK_ATTA, usb_ia->ia_log_handle, "usb_ia_cleanup: ndi_event_free_hdl failed"); return (DDI_FAILURE); } /* * Disable the event callbacks, after this point, event * callbacks will never get called. Note we shouldn't hold * mutex while unregistering events because there may be a * competing event callback thread. Event callbacks are done * with ndi mutex held and this can cause a potential deadlock. * Note that cleanup can't fail after deregistration of events. */ if (usb_ia->ia_init_state & USB_IA_EVENTS_REGISTERED) { usba_common_unregister_events(usb_ia->ia_dip, usb_ia->ia_n_ifs); } iapm = usb_ia->ia_pm; mutex_enter(&usb_ia->ia_mutex); if ((iapm) && (usb_ia->ia_dev_state != USB_DEV_DISCONNECTED)) { mutex_exit(&usb_ia->ia_mutex); (void) pm_busy_component(dip, 0); if (iapm->uc_wakeup_enabled) { /* First bring the device to full power */ (void) pm_raise_power(dip, 0, USB_DEV_OS_FULL_PWR); rval = usb_handle_remote_wakeup(dip, USB_REMOTE_WAKEUP_DISABLE); if (rval != DDI_SUCCESS) { USB_DPRINTF_L2(DPRINT_MASK_EVENTS, usb_ia->ia_log_handle, "usb_cleanup: disable remote " "wakeup failed, rval=%d", rval); } } (void) pm_lower_power(usb_ia->ia_dip, 0, USB_DEV_OS_PWR_OFF); (void) pm_idle_component(dip, 0); } else { mutex_exit(&usb_ia->ia_mutex); } if (iapm) { kmem_free(iapm, sizeof (usb_common_power_t)); } /* free children list */ if (usb_ia->ia_children_dips) { kmem_free(usb_ia->ia_children_dips, usb_ia->ia_cd_list_length); } if (usb_ia->ia_child_events) { kmem_free(usb_ia->ia_child_events, sizeof (uint8_t) * usb_ia->ia_n_ifs); } if (usb_ia->ia_init_state & USB_IA_MINOR_NODE_CREATED) { ddi_remove_minor_node(dip, NULL); } mutex_destroy(&usb_ia->ia_mutex); done: usb_client_detach(dip, usb_ia->ia_dev_data); usb_free_log_hdl(usb_ia->ia_log_handle); ddi_soft_state_free(usb_ia_statep, ddi_get_instance(dip)); ddi_prop_remove_all(dip); return (DDI_SUCCESS); } /* * usb_ia_create_children: */ static void usb_ia_create_children(usb_ia_t *usb_ia) { usba_device_t *usba_device; uint_t n_ifs, first_if; uint_t i; dev_info_t *cdip; usba_device = usba_get_usba_device(usb_ia->ia_dip); USB_DPRINTF_L4(DPRINT_MASK_ATTA, usb_ia->ia_log_handle, "usb_ia_attach_child_drivers: port = %d, address = %d", usba_device->usb_port, usba_device->usb_addr); n_ifs = usb_ia->ia_n_ifs; first_if = usb_ia->ia_first_if; /* * create all children if not already present */ for (i = 0; i < n_ifs; i++) { if (usb_ia->ia_children_dips[i] != NULL) { continue; } mutex_exit(&usb_ia->ia_mutex); cdip = usba_ready_interface_node(usb_ia->ia_dip, first_if + i); mutex_enter(&usb_ia->ia_mutex); if (cdip != NULL) { (void) usba_bind_driver(cdip); usb_ia->ia_children_dips[i] = cdip; } } } /* * event support */ static int usb_ia_busop_get_eventcookie(dev_info_t *dip, dev_info_t *rdip, char *eventname, ddi_eventcookie_t *cookie) { usb_ia_t *usb_ia = usb_ia_obtain_state(dip); USB_DPRINTF_L4(DPRINT_MASK_EVENTS, usb_ia->ia_log_handle, "usb_ia_busop_get_eventcookie: dip=0x%p, rdip=0x%p, " "event=%s", (void *)dip, (void *)rdip, eventname); USB_DPRINTF_L3(DPRINT_MASK_EVENTS, usb_ia->ia_log_handle, "(dip=%s%d rdip=%s%d)", ddi_driver_name(dip), ddi_get_instance(dip), ddi_driver_name(rdip), ddi_get_instance(rdip)); /* return event cookie, iblock cookie, and level */ return (ndi_event_retrieve_cookie(usb_ia->ia_ndi_event_hdl, rdip, eventname, cookie, NDI_EVENT_NOPASS)); } static int usb_ia_busop_add_eventcall(dev_info_t *dip, dev_info_t *rdip, ddi_eventcookie_t cookie, void (*callback)(dev_info_t *dip, ddi_eventcookie_t cookie, void *arg, void *bus_impldata), void *arg, ddi_callback_id_t *cb_id) { int ifno; usb_ia_t *usb_ia = usb_ia_obtain_state(dip); mutex_enter(&usb_ia->ia_mutex); ifno = usba_get_ifno(rdip)- usb_ia->ia_first_if; mutex_exit(&usb_ia->ia_mutex); if (ifno < 0) { ifno = 0; } USB_DPRINTF_L4(DPRINT_MASK_EVENTS, usb_ia->ia_log_handle, "usb_ia_busop_add_eventcall: dip=0x%p, rdip=0x%p " "cookie=0x%p, cb=0x%p, arg=0x%p", (void *)dip, (void *)rdip, (void *)cookie, (void *)callback, arg); USB_DPRINTF_L3(DPRINT_MASK_EVENTS, usb_ia->ia_log_handle, "(dip=%s%d rdip=%s%d event=%s)", ddi_driver_name(dip), ddi_get_instance(dip), ddi_driver_name(rdip), ddi_get_instance(rdip), ndi_event_cookie_to_name(usb_ia->ia_ndi_event_hdl, cookie)); /* Set flag on children registering events */ switch (ndi_event_cookie_to_tag(usb_ia->ia_ndi_event_hdl, cookie)) { case USBA_EVENT_TAG_HOT_REMOVAL: mutex_enter(&usb_ia->ia_mutex); usb_ia->ia_child_events[ifno] |= USB_IA_CHILD_EVENT_DISCONNECT; mutex_exit(&usb_ia->ia_mutex); break; case USBA_EVENT_TAG_PRE_SUSPEND: mutex_enter(&usb_ia->ia_mutex); usb_ia->ia_child_events[ifno] |= USB_IA_CHILD_EVENT_PRESUSPEND; mutex_exit(&usb_ia->ia_mutex); break; default: break; } /* add callback (perform registration) */ return (ndi_event_add_callback(usb_ia->ia_ndi_event_hdl, rdip, cookie, callback, arg, NDI_SLEEP, cb_id)); } static int usb_ia_busop_remove_eventcall(dev_info_t *dip, ddi_callback_id_t cb_id) { usb_ia_t *usb_ia = usb_ia_obtain_state(dip); ndi_event_callbacks_t *cb = (ndi_event_callbacks_t *)cb_id; ASSERT(cb); USB_DPRINTF_L4(DPRINT_MASK_EVENTS, usb_ia->ia_log_handle, "usb_ia_busop_remove_eventcall: dip=0x%p, rdip=0x%p " "cookie=0x%p", (void *)dip, (void *)cb->ndi_evtcb_dip, (void *)cb->ndi_evtcb_cookie); USB_DPRINTF_L3(DPRINT_MASK_EVENTS, usb_ia->ia_log_handle, "(dip=%s%d rdip=%s%d event=%s)", ddi_driver_name(dip), ddi_get_instance(dip), ddi_driver_name(cb->ndi_evtcb_dip), ddi_get_instance(cb->ndi_evtcb_dip), ndi_event_cookie_to_name(usb_ia->ia_ndi_event_hdl, cb->ndi_evtcb_cookie)); /* remove event registration from our event set */ return (ndi_event_remove_callback(usb_ia->ia_ndi_event_hdl, cb_id)); } static int usb_ia_busop_post_event(dev_info_t *dip, dev_info_t *rdip, ddi_eventcookie_t cookie, void *bus_impldata) { usb_ia_t *usb_ia = usb_ia_obtain_state(dip); USB_DPRINTF_L4(DPRINT_MASK_EVENTS, usb_ia->ia_log_handle, "usb_ia_busop_post_event: dip=0x%p, rdip=0x%p " "cookie=0x%p, impl=0x%p", (void *)dip, (void *)rdip, (void *)cookie, bus_impldata); USB_DPRINTF_L3(DPRINT_MASK_EVENTS, usb_ia->ia_log_handle, "(dip=%s%d rdip=%s%d event=%s)", ddi_driver_name(dip), ddi_get_instance(dip), ddi_driver_name(rdip), ddi_get_instance(rdip), ndi_event_cookie_to_name(usb_ia->ia_ndi_event_hdl, cookie)); /* post event to all children registered for this event */ return (ndi_event_run_callbacks(usb_ia->ia_ndi_event_hdl, rdip, cookie, bus_impldata)); } /* * usb_ia_restore_device_state * set the original configuration of the device */ static int usb_ia_restore_device_state(dev_info_t *dip, usb_ia_t *usb_ia) { usb_common_power_t *iapm; USB_DPRINTF_L4(DPRINT_MASK_EVENTS, usb_ia->ia_log_handle, "usb_ia_restore_device_state: usb_ia = %p", (void *)usb_ia); mutex_enter(&usb_ia->ia_mutex); iapm = usb_ia->ia_pm; mutex_exit(&usb_ia->ia_mutex); /* First bring the device to full power */ (void) pm_busy_component(dip, 0); (void) pm_raise_power(dip, 0, USB_DEV_OS_FULL_PWR); if (usb_check_same_device(dip, usb_ia->ia_log_handle, USB_LOG_L0, DPRINT_MASK_EVENTS, USB_CHK_VIDPID, NULL) != USB_SUCCESS) { /* change the device state from suspended to disconnected */ mutex_enter(&usb_ia->ia_mutex); usb_ia->ia_dev_state = USB_DEV_DISCONNECTED; mutex_exit(&usb_ia->ia_mutex); (void) pm_idle_component(dip, 0); return (USB_FAILURE); } /* * if the device had remote wakeup earlier, * enable it again */ if (iapm->uc_wakeup_enabled) { (void) usb_handle_remote_wakeup(usb_ia->ia_dip, USB_REMOTE_WAKEUP_ENABLE); } mutex_enter(&usb_ia->ia_mutex); usb_ia->ia_dev_state = USB_DEV_ONLINE; mutex_exit(&usb_ia->ia_mutex); (void) pm_idle_component(dip, 0); return (USB_SUCCESS); } /* * usb_ia_event_cb() * handle disconnect and connect events */ static void usb_ia_event_cb(dev_info_t *dip, ddi_eventcookie_t cookie, void *arg, void *bus_impldata) { int i, tag; usb_ia_t *usb_ia = usb_ia_obtain_state(dip); dev_info_t *child_dip; ddi_eventcookie_t rm_cookie, ins_cookie, suspend_cookie, resume_cookie; USB_DPRINTF_L4(DPRINT_MASK_EVENTS, usb_ia->ia_log_handle, "usb_ia_event_cb: dip=0x%p, cookie=0x%p, " "arg=0x%p, impl=0x%p", (void *)dip, (void *)cookie, arg, bus_impldata); USB_DPRINTF_L4(DPRINT_MASK_EVENTS, usb_ia->ia_log_handle, "(dip=%s%d event=%s)", ddi_driver_name(dip), ddi_get_instance(dip), ndi_event_cookie_to_name(usb_ia->ia_ndi_event_hdl, cookie)); tag = NDI_EVENT_TAG(cookie); rm_cookie = ndi_event_tag_to_cookie( usb_ia->ia_ndi_event_hdl, USBA_EVENT_TAG_HOT_REMOVAL); suspend_cookie = ndi_event_tag_to_cookie( usb_ia->ia_ndi_event_hdl, USBA_EVENT_TAG_PRE_SUSPEND); ins_cookie = ndi_event_tag_to_cookie( usb_ia->ia_ndi_event_hdl, USBA_EVENT_TAG_HOT_INSERTION); resume_cookie = ndi_event_tag_to_cookie( usb_ia->ia_ndi_event_hdl, USBA_EVENT_TAG_POST_RESUME); mutex_enter(&usb_ia->ia_mutex); switch (tag) { case USBA_EVENT_TAG_HOT_REMOVAL: if (usb_ia->ia_dev_state == USB_DEV_DISCONNECTED) { USB_DPRINTF_L2(DPRINT_MASK_EVENTS, usb_ia->ia_log_handle, "usb_ia_event_cb: Device already disconnected"); } else { /* we are disconnected so set our state now */ usb_ia->ia_dev_state = USB_DEV_DISCONNECTED; for (i = 0; i < usb_ia->ia_n_ifs; i++) { usb_ia->ia_child_events[i] &= ~ USB_IA_CHILD_EVENT_DISCONNECT; } mutex_exit(&usb_ia->ia_mutex); /* pass disconnect event to all the children */ (void) ndi_event_run_callbacks( usb_ia->ia_ndi_event_hdl, NULL, rm_cookie, bus_impldata); mutex_enter(&usb_ia->ia_mutex); } break; case USBA_EVENT_TAG_PRE_SUSPEND: /* set our state *after* suspending children */ mutex_exit(&usb_ia->ia_mutex); /* pass pre_suspend event to all the children */ (void) ndi_event_run_callbacks(usb_ia->ia_ndi_event_hdl, NULL, suspend_cookie, bus_impldata); mutex_enter(&usb_ia->ia_mutex); for (i = 0; i < usb_ia->ia_n_ifs; i++) { usb_ia->ia_child_events[i] &= ~ USB_IA_CHILD_EVENT_PRESUSPEND; } break; case USBA_EVENT_TAG_HOT_INSERTION: mutex_exit(&usb_ia->ia_mutex); if (usb_ia_restore_device_state(dip, usb_ia) == USB_SUCCESS) { /* * Check to see if this child has missed the disconnect * event before it registered for event cb */ mutex_enter(&usb_ia->ia_mutex); for (i = 0; i < usb_ia->ia_n_ifs; i++) { if (usb_ia->ia_child_events[i] & USB_IA_CHILD_EVENT_DISCONNECT) { usb_ia->ia_child_events[i] &= ~USB_IA_CHILD_EVENT_DISCONNECT; child_dip = usb_ia->ia_children_dips[i]; mutex_exit(&usb_ia->ia_mutex); /* post the missed disconnect */ (void) ndi_event_do_callback( usb_ia->ia_ndi_event_hdl, child_dip, rm_cookie, bus_impldata); mutex_enter(&usb_ia->ia_mutex); } } mutex_exit(&usb_ia->ia_mutex); /* pass reconnect event to all the children */ (void) ndi_event_run_callbacks( usb_ia->ia_ndi_event_hdl, NULL, ins_cookie, bus_impldata); } mutex_enter(&usb_ia->ia_mutex); break; case USBA_EVENT_TAG_POST_RESUME: /* * Check to see if this child has missed the pre-suspend * event before it registered for event cb */ for (i = 0; i < usb_ia->ia_n_ifs; i++) { if (usb_ia->ia_child_events[i] & USB_IA_CHILD_EVENT_PRESUSPEND) { usb_ia->ia_child_events[i] &= ~USB_IA_CHILD_EVENT_PRESUSPEND; child_dip = usb_ia->ia_children_dips[i]; mutex_exit(&usb_ia->ia_mutex); /* post the missed pre-suspend event */ (void) ndi_event_do_callback( usb_ia->ia_ndi_event_hdl, child_dip, suspend_cookie, bus_impldata); mutex_enter(&usb_ia->ia_mutex); } } mutex_exit(&usb_ia->ia_mutex); /* pass post_resume event to all the children */ (void) ndi_event_run_callbacks(usb_ia->ia_ndi_event_hdl, NULL, resume_cookie, bus_impldata); mutex_enter(&usb_ia->ia_mutex); break; } mutex_exit(&usb_ia->ia_mutex); } /* * create the pm components required for power management */ static void usb_ia_create_pm_components(dev_info_t *dip, usb_ia_t *usb_ia) { usb_common_power_t *iapm; uint_t pwr_states; USB_DPRINTF_L4(DPRINT_MASK_PM, usb_ia->ia_log_handle, "usb_ia_create_pm_components: Begin"); /* Allocate the PM state structure */ iapm = kmem_zalloc(sizeof (usb_common_power_t), KM_SLEEP); mutex_enter(&usb_ia->ia_mutex); usb_ia->ia_pm = iapm; iapm->uc_usb_statep = usb_ia; iapm->uc_pm_capabilities = 0; /* XXXX should this be 0?? */ iapm->uc_current_power = USB_DEV_OS_FULL_PWR; mutex_exit(&usb_ia->ia_mutex); /* * By not enabling parental notification, PM enforces * "strict parental dependency" meaning, usb_ia won't * power off until any of its children are in full power. */ /* * there are 3 scenarios: * 1. a well behaved device should have remote wakeup * at interface and device level. If the interface * wakes up, usb_ia will wake up * 2. if the device doesn't have remote wake up and * the interface has, PM will still work, ie. * the interfaces wakes up and usb_ia wakes up * 3. if neither the interface nor device has remote * wakeup, the interface will wake up when it is opened * and goes to sleep after being closed for a while * In this case usb_ia should also go to sleep shortly * thereafter * In all scenarios it doesn't really matter whether * remote wakeup at the device level is enabled or not * but we do it anyways */ if (usb_handle_remote_wakeup(dip, USB_REMOTE_WAKEUP_ENABLE) == USB_SUCCESS) { USB_DPRINTF_L3(DPRINT_MASK_PM, usb_ia->ia_log_handle, "usb_ia_create_pm_components: " "Remote Wakeup Enabled"); iapm->uc_wakeup_enabled = 1; } if (usb_create_pm_components(dip, &pwr_states) == USB_SUCCESS) { iapm->uc_pwr_states = (uint8_t)pwr_states; (void) pm_raise_power(dip, 0, USB_DEV_OS_FULL_PWR); } USB_DPRINTF_L4(DPRINT_MASK_PM, usb_ia->ia_log_handle, "usb_ia_create_pm_components: End"); } /* * usb_ia_obtain_state: */ static usb_ia_t * usb_ia_obtain_state(dev_info_t *dip) { int instance = ddi_get_instance(dip); usb_ia_t *statep = ddi_get_soft_state(usb_ia_statep, instance); ASSERT(statep != NULL); return (statep); }
25.88835
78
0.715232
[ "vector" ]
243d15b83fdde219fbff630517b45b556f3d8901
975
c
C
C/Non_Blocking/fixed_memory_parameter.c
WarwickRSE/Intermediate_MPI
ae1587e84e9239fb47629a75cce1bfb416e92136
[ "BSD-3-Clause" ]
2
2020-02-27T18:51:55.000Z
2021-09-16T16:33:21.000Z
C/Non_Blocking/fixed_memory_parameter.c
WarwickRSE/Intermediate_MPI
ae1587e84e9239fb47629a75cce1bfb416e92136
[ "BSD-3-Clause" ]
null
null
null
C/Non_Blocking/fixed_memory_parameter.c
WarwickRSE/Intermediate_MPI
ae1587e84e9239fb47629a75cce1bfb416e92136
[ "BSD-3-Clause" ]
null
null
null
#include <stdio.h> #include <mpi.h> #define TAG 100 void send_vals(int dest, int *val, MPI_Request *request){ /*This works because val is a pointer so the original value still exists outside this function*/ MPI_Isend(val, 1, MPI_INT, dest, TAG, MPI_COMM_WORLD, request); } int main(int argc, char ** argv) { int rank, nproc, left, right; int recv_val, send_val; MPI_Request requests[2]; MPI_Status statuses[2]; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &nproc); MPI_Comm_rank(MPI_COMM_WORLD, &rank); //Set up periodic domain left = rank - 1; if (left < 0) left = nproc - 1; right = rank + 1; if (right > nproc - 1) right = 0; send_val = 25; send_vals(right, &send_val, &requests[0]); MPI_Irecv(&recv_val, 1, MPI_INT, left, TAG, MPI_COMM_WORLD, &requests[1]); MPI_Waitall(2, requests, statuses); printf("Rank %3d got message from rank %3d of %3d\n", rank, left, recv_val); MPI_Finalize(); }
21.666667
68
0.664615
[ "3d" ]
244e77282e3a61a8cbe40f1fb93e2fdfe0dc9ec4
10,136
c
C
KEEN/SRC/static/makeobj.c
pdpdds/DOSDev
5f81c5f94a55b866461f019e9ba8fe27c74039fa
[ "BSD-3-Clause" ]
null
null
null
KEEN/SRC/static/makeobj.c
pdpdds/DOSDev
5f81c5f94a55b866461f019e9ba8fe27c74039fa
[ "BSD-3-Clause" ]
null
null
null
KEEN/SRC/static/makeobj.c
pdpdds/DOSDev
5f81c5f94a55b866461f019e9ba8fe27c74039fa
[ "BSD-3-Clause" ]
null
null
null
/* ** makeobj.c ** **--------------------------------------------------------------------------- ** Copyright 2014 Braden Obrzut ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** 2. Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** 3. The name of the author may not be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **--------------------------------------------------------------------------- ** ** This is a throwaway program to create OMF object files for DOS. It also ** extracts the object files. It should be compatible with MakeOBJ by John ** Romero except where we calculate the checksum correctly. ** */ #include <stdio.h> #include <malloc.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #pragma pack(1) typedef struct { unsigned char type; unsigned short len; } SegHeader; typedef struct { unsigned short len; unsigned char name; unsigned char classname; unsigned char overlayname; } SegDef; #pragma pack() const char* ReadFile(const char* fn, int *size) { char* out; FILE* f = fopen(fn, "rb"); fseek(f, 0, SEEK_END); *size = ftell(f); out = (char*)malloc(*size); fseek(f, 0, SEEK_SET); fread(out, *size, 1, f); fclose(f); return out; } void WriteFile(const char* fn, const char *data, int size) { FILE* f = fopen(fn, "wb"); fwrite(data, size, 1, f); fclose(f); } void Extract(const char* infn) { const char* in; const char* start; const char* p; char outfn[16]; char str[256]; char *outdata; int outsize; int insize; SegHeader head; outdata = NULL; start = in = ReadFile(infn, &insize); while(in < start + insize) { head = *(SegHeader*)in; switch(head.type) { case 0x80: /* THEADR */ memcpy(outfn, in+4, in[3]); outfn[in[3]] = 0; printf("Output: %s\n", outfn); { int i; for(i = 0;i < 16;++i) { if(outfn[i] == ' ') outfn[i] = 0; } } break; case 0x88: /* COMENT */ switch(in[3]) { case 0: memcpy(str, in+5, head.len-2); str[head.len-3] = 0; printf("Comment: %s\n", str); break; default: printf("Unknown comment type %X @ %x ignored.\n", (unsigned char)in[3], (unsigned int)(in - start)); break; } break; case 0x96: /* LNAMES */ p = in+3; while(p < in+head.len+2) { memcpy(str, p+1, (unsigned char)*p); str[(unsigned char)*p] = 0; printf("Name: %s\n", str); p += (unsigned char)*p+1; } break; case 0x98: /* SEGDEF */ { SegDef *sd; sd = *(in+3) ? (SegDef*)(in+4) : (SegDef*)(in+7); printf("Segment Length: %d\n", sd->len); outdata = (char*)malloc(sd->len); outsize = sd->len; break; } case 0x90: /* PUBDEF */ p = in+5; if(in[5] == 0) p += 2; while(p < in+head.len+2) { memcpy(str, p+1, (unsigned char)*p); str[(unsigned char)*p] = 0; printf("Public Name: %s\n", str); p += (unsigned char)*p+4; } break; case 0xA0: /* LEDATA */ printf("Writing data at %d (%d)\n", *(unsigned short*)(in+4), head.len-4); memcpy(outdata+*(unsigned short*)(in+4), in+6, head.len-4); break; case 0x8A: /* MODEND */ /* Ignore */ break; default: printf("Unknown header type %X @ %x ignored.\n", head.type, (unsigned int)(in - start)); break; } in += 3 + head.len; } WriteFile(outfn, outdata, outsize); free((char*)start); free(outdata); } void CheckSum(char *s, unsigned short len) { int sum; len += 3; sum = 0; while(len > 1) { sum += *(unsigned char*)s; ++s; --len; } *s = (unsigned char)(0x100-(sum&0xFF)); } void MakeDataObj(const char* infn, const char* outfn, const char* segname, const char* symname, int altmode) { #define Flush() fwrite(d.buf, d.head.len+3, 1, f) union { char buf[4096]; SegHeader head; } d; int i; FILE *f; int insize; const char *in; const char *infn_stripped = strrchr(infn, '/'); if(strrchr(infn, '\\') > infn_stripped) infn_stripped = strrchr(infn, '\\'); if(infn_stripped == NULL) infn_stripped = infn; else ++infn_stripped; f = fopen(outfn, "wb"); in = ReadFile(infn, &insize); d.head.type = 0x80; d.head.len = 14; d.buf[3] = 12; if(d.buf[3] > 12) d.buf[3] = 12; sprintf(&d.buf[4], "%-12s", infn_stripped); for(i = 0;i < strlen(infn_stripped) && i < 12;++i) d.buf[4+i] = toupper(d.buf[4+i]); /* CheckSum(d.buf, d.head.len); */ d.buf[17] = 0; /* For some reason this one isn't checksummed by MakeOBJ */ Flush(); d.head.type = 0x88; d.head.len = 15; d.buf[3] = 0; d.buf[4] = 0; /* We're not really MakeOBJ v1.1, but to allow us to verify with md5sums */ memcpy(&d.buf[5], "MakeOBJ v1.1", 12); CheckSum(d.buf, d.head.len); Flush(); d.head.type = 0x96; d.head.len = strlen(infn_stripped)+40; d.buf[3] = 6; memcpy(&d.buf[4], "DGROUP", 6); d.buf[10] = 5; memcpy(&d.buf[11], "_DATA", 5); d.buf[16] = 4; memcpy(&d.buf[17], "DATA", 4); d.buf[21] = 0; d.buf[22] = 5; memcpy(&d.buf[23], "_TEXT", 5); d.buf[28] = 4; memcpy(&d.buf[29], "CODE", 4); d.buf[33] = 8; memcpy(&d.buf[34], "FAR_DATA", 8); if(!segname) { if(!altmode) { d.buf[42] = strlen(infn_stripped)-1; for(i = 0;i < strlen(infn_stripped)-4;++i) { if(i == 0) d.buf[43] = toupper(infn_stripped[0]); else d.buf[43+i] = tolower(infn_stripped[i]); } memcpy(&d.buf[43+i], "Seg", 3); } else { d.head.len = 40; } } else { d.head.len = strlen(segname)+41; d.buf[42] = strlen(segname); strcpy(&d.buf[43], segname); } CheckSum(d.buf, d.head.len); Flush(); d.head.type = 0x98; d.head.len = 7; *(unsigned short*)(d.buf+4) = insize; if(altmode == 0) { d.buf[3] = (char)((unsigned char)0x60); d.buf[6] = 8; d.buf[7] = 7; d.buf[8] = 4; } else { d.buf[3] = (char)((unsigned char)0x48); d.buf[6] = 2; d.buf[7] = 3; d.buf[8] = 4; } CheckSum(d.buf, d.head.len); Flush(); if(altmode) { d.head.type = 0x9A; d.head.len = 4; d.buf[3] = 1; d.buf[4] = (char)((unsigned char)0xFF); d.buf[5] = 1; CheckSum(d.buf, d.head.len); Flush(); } d.head.type = 0x90; d.head.len = strlen(infn_stripped)+4; d.buf[3] = 1; d.buf[4] = 1; if(!symname) { d.buf[5] = strlen(infn_stripped)-3; d.buf[6] = '_'; for(i = 0;i < strlen(infn_stripped)-4;++i) d.buf[7+i] = tolower(infn_stripped[i]); } else { d.head.len = strlen(symname)+7; d.buf[5] = strlen(symname); strcpy(&d.buf[6], symname); i = strlen(symname)-1; } d.buf[7+i] = 0; d.buf[8+i] = 0; d.buf[9+i] = 0; /* This checksum is calculated wrong in MakeOBJ, although I don't know in what way. */ CheckSum(d.buf, d.head.len); Flush(); #define LEDATA_LEN 1024 for(i = 0;i < insize;i += LEDATA_LEN) { d.head.type = 0xA0; d.head.len = insize - i > LEDATA_LEN ? LEDATA_LEN+4 : insize - i + 4; d.buf[3] = 1; *(unsigned short*)(d.buf+4) = i; memcpy(&d.buf[6], &in[i], d.head.len-4); CheckSum(d.buf, d.head.len); Flush(); } d.head.type = 0x8A; d.head.len = 2; d.buf[3] = 0; d.buf[4] = 0; CheckSum(d.buf, d.head.len); Flush(); fclose(f); free((char*)in); } void DumpData(const char* infn, const char* outfn, int skip) { FILE *f; int i; int insize; char symname[9]; const char *in; const char *infn_stripped = strrchr(infn, '/'); if(strrchr(infn, '\\') > infn_stripped) infn_stripped = strrchr(infn, '\\'); if(infn_stripped == NULL) infn_stripped = infn; else ++infn_stripped; f = fopen(outfn, "wb"); memset(symname, 0, 9); memcpy(symname, infn_stripped, strlen(infn_stripped)-4); fprintf(f, "char far %s[] ={\r\n", symname); in = ReadFile(infn, &insize); for(i = skip;i < insize;++i) { fprintf(f, "%d", (unsigned char)in[i]); if(i != insize-1) fprintf(f, ",\r\n"); } fprintf(f, " };\r\n"); fclose(f); free((char*)in); } int main(int argc, char* argv[]) { if(argc < 3) { printf("Converts file to OMF.\nUseage:\n ./makeobj [fx] <input> ...\n"); return 0; } switch(argv[1][0]) { case 'c': if(argc < 4) { printf("Need an output location. (Extra parms: <output> [<symbol>])\n"); return 0; } else { const char *symname = NULL; if(argc >= 5) symname = argv[4]; MakeDataObj(argv[2], argv[3], NULL, symname, 1); } break; default: case 'f': if(argc < 4) { printf("Need an output location. (Extra parms: <output> [<segname> <symbol>])\n"); return 0; } else { const char *segname = NULL, *symname = NULL; if(argc >= 6) { segname = argv[4]; symname = argv[5]; } MakeDataObj(argv[2], argv[3], segname, symname, 0); } break; case 'x': Extract(argv[2]); break; case 's': if(argc < 4) { printf("Need an output location. (Extra parms: <output> [<skip>])\n"); return 0; } else { int skip = 0; if(argc >= 5) { skip = atoi(argv[4]); } DumpData(argv[2], argv[3], skip); } break; break; } return 0; }
21.52017
108
0.585043
[ "object" ]
24550edbe7ae143ee78d2914341d38038c75cb9d
7,770
h
C
algorithm/windows.h
germinolegrand/fys
40c05485be835d03b4c9b2ffaf010bffa7ec8832
[ "Unlicense" ]
5
2015-03-22T00:24:31.000Z
2021-05-24T21:31:28.000Z
algorithm/windows.h
germinolegrand/fys
40c05485be835d03b4c9b2ffaf010bffa7ec8832
[ "Unlicense" ]
2
2018-01-04T15:16:08.000Z
2018-05-17T23:45:06.000Z
algorithm/windows.h
germinolegrand/fys
40c05485be835d03b4c9b2ffaf010bffa7ec8832
[ "Unlicense" ]
null
null
null
#pragma once #include <algorithm> #include <iterator> namespace fys { template<class ForwardIt, class Function> Function for_each_incomplete_window(ForwardIt first, ForwardIt last, Function f, typename std::iterator_traits<ForwardIt>::difference_type windowSize, typename std::iterator_traits<ForwardIt>::difference_type windowOffset = 1) { for(; first != last; std::advance(first, std::min(windowOffset, std::distance(first, last)))) f(first, std::next(first, std::min(windowSize, std::distance(first, last)))); return std::move(f); } template<class ForwardIt, class Function> Function for_each_complete_window(ForwardIt first, ForwardIt last, Function f, typename std::iterator_traits<ForwardIt>::difference_type windowSize, typename std::iterator_traits<ForwardIt>::difference_type windowOffset = 1) { for(; std::distance(first, last) >= windowSize; std::advance(first, std::min(windowOffset, std::distance(first, last)))) f(first, std::next(first, std::min(windowSize, std::distance(first, last)))); return std::move(f); } template<class ForwardIt, class OutputIt> OutputIt incomplete_windows_copy(ForwardIt first, ForwardIt last, OutputIt d_first, typename std::iterator_traits<ForwardIt>::difference_type windowSize, typename std::iterator_traits<ForwardIt>::difference_type windowOffset = 1) { for(; first != last; std::advance(first, std::min(windowOffset, std::distance(first, last)))) d_first = std::copy(first, std::next(first, std::min(windowSize, std::distance(first, last))), d_first); return d_first; } template<class ForwardIt, class OutputIt> OutputIt complete_windows_copy(ForwardIt first, ForwardIt last, OutputIt d_first, typename std::iterator_traits<ForwardIt>::difference_type windowSize, typename std::iterator_traits<ForwardIt>::difference_type windowOffset = 1) { for(; std::distance(first, last) >= windowSize; std::advance(first, std::min(windowOffset, std::distance(first, last)))) d_first = std::copy(first, std::next(first, std::min(windowSize, std::distance(first, last))), d_first); return d_first; } namespace priv { template<bool Complete> struct Windows { template<class ForwardIt, class Function> static inline Function for_each_window(ForwardIt first, ForwardIt last, Function f, typename std::iterator_traits<ForwardIt>::difference_type windowSize, typename std::iterator_traits<ForwardIt>::difference_type windowOffset = 1) { return for_each_complete_window(first, last, f, windowSize, windowOffset); } template<class ForwardIt, class OutputIt> static inline OutputIt windows_copy(ForwardIt first, ForwardIt last, OutputIt d_first, typename std::iterator_traits<ForwardIt>::difference_type windowSize, typename std::iterator_traits<ForwardIt>::difference_type windowOffset = 1) { return complete_windows_copy(first, last, d_first, windowSize, windowOffset); } }; template<> struct Windows<false> { template<class ForwardIt, class Function> static inline Function for_each_window(ForwardIt first, ForwardIt last, Function f, typename std::iterator_traits<ForwardIt>::difference_type windowSize, typename std::iterator_traits<ForwardIt>::difference_type windowOffset = 1) { return for_each_incomplete_window(first, last, f, windowSize, windowOffset); } template<class ForwardIt, class OutputIt> static inline OutputIt windows_copy(ForwardIt first, ForwardIt last, OutputIt d_first, typename std::iterator_traits<ForwardIt>::difference_type windowSize, typename std::iterator_traits<ForwardIt>::difference_type windowOffset = 1) { return incomplete_windows_copy(first, last, d_first, windowSize, windowOffset); } }; } template<bool Complete = true, class ForwardIt, class Function> Function for_each_window(ForwardIt first, ForwardIt last, Function f, typename std::iterator_traits<ForwardIt>::difference_type windowSize, typename std::iterator_traits<ForwardIt>::difference_type windowOffset = 1) { return priv::Windows<Complete>::for_each_window(first, last, f, windowSize, windowOffset); } template<bool Complete = true, class ForwardIt, class OutputIt> OutputIt windows_copy(ForwardIt first, ForwardIt last, OutputIt d_first, typename std::iterator_traits<ForwardIt>::difference_type windowSize, typename std::iterator_traits<ForwardIt>::difference_type windowOffset = 1) { return priv::Windows<Complete>::windows_copy(first, last, d_first, windowSize, windowOffset); } /** Documents: (1) function(incomplete_windows_copy) (2) function(complete_windows_copy) (3) function(for_each_incomplete_window) (4) function(for_each_complete_window) (5) function(windows_copy) (6) function(for_each_window) Effects: Takes successive subsequences [i,j) from the range `[first,last)` and (1)(2) copies the elements of `[i,j)` into the range (1) `[d_first, d_first + ???)`, (2) `[d_first, d_first + ((last - first) < windowsSize ? 0 : (last - first + min(windowsOffset - windowsSize, 0))/windowsOffset*windowsSize))` starting from `first` and proceeding to `last`, (3)(4) applies f to `[i,j)`. For each subsequence, performs (1)(2) `copy(i, j, d_first)`, (3)(4) `f(i, j)`. The first subsequence is `[first,first + windowsSize)`. Therefore, assuming a previous subsequence `[g,h)`, the next subsequence is `[g + windowsOffset,h + windowsOffset)`. If `j > last`, (1)(3) then the subsequence becomes `[i, last)`, (2)(4) then the subsequence becomes `[last, last)`. (5) is an alias of (1) if Complete is false, an alias of (2) by default otherwise. (6) is an alias of (3) if Complete is false, an alias of (4) by default otherwise. Returns: The end of the resulting range. Requires: `windowsOffset` shall not be zero, `d_first` shall not be in the range `[first,last)`, `Function` shall meet the requirements of MoveConstructible. Complexity: (1) Exactly `???` assignements,//TODO calculate complexity (2) Exactly `(last - first) < windowsSize ? 0 : (last - first + min(windowsOffset - windowsSize, 0))/windowsOffset*windowsSize` assignements, (3) Exactly `(last - first)/windowsOffset + min(1, last - first)` applications of `f`, (4) Exactly `(last - first) < windowsSize ? 0 : (last - first + min(windowsOffset - windowsSize, 0))/windowsOffset` applications of `f`. Example: ``` int main() { std::vector<int> v = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19}; std::string s("hello world"); fys::windows_copy(begin(s), end(s), std::ostream_iterator<char>(std::cout, ""), 3, 2); std::cout << std::endl; fys::windows_copy<false>(begin(s), end(s), std::ostream_iterator<char>(std::cout, ""), 3, 2); std::cout << std::endl; fys::for_each_window(begin(v), end(v), [](decltype(v)::iterator first, decltype(v)::iterator last){ std::cout << "["; std::for_each(first, last, [](decltype(v)::value_type& x){ std::cout << " " << x; }); std::cout << " ]"; }, 3, 2); std::cout << std::endl; fys::for_each_window<false>(begin(v), end(v), [](decltype(v)::iterator first, decltype(v)::iterator last){ std::cout << "["; std::for_each(first, last, [](decltype(v)::value_type& x){ std::cout << " " << x; }); std::cout << " ]"; }, 3, 2); } ``` Output: ``` hellloo wworrld hellloo wworrldd [ 0 1 2 ][ 2 3 4 ][ 4 5 6 ][ 6 7 8 ][ 8 9 10 ][ 10 11 12 ][ 12 13 14 ][ 14 15 16 ][ 16 17 18 ] [ 0 1 2 ][ 2 3 4 ][ 4 5 6 ][ 6 7 8 ][ 8 9 10 ][ 10 11 12 ][ 12 13 14 ][ 14 15 16 ][ 16 17 18 ][ 18 19 ] ``` **/ }
46.526946
229
0.688031
[ "vector" ]
24595019f8048c38b49d51c7b522c577f0273749
5,597
h
C
Classes/CollectionScreen.h
Fanfare-ETC/catch-a-play
faa39a693a96365cd1e5bb91e4dabb116d092222
[ "MIT", "Unlicense" ]
3
2017-03-16T09:50:08.000Z
2017-03-18T17:40:47.000Z
Classes/CollectionScreen.h
Fanfare-ETC/playbook
faa39a693a96365cd1e5bb91e4dabb116d092222
[ "MIT", "Unlicense" ]
null
null
null
Classes/CollectionScreen.h
Fanfare-ETC/playbook
faa39a693a96365cd1e5bb91e4dabb116d092222
[ "MIT", "Unlicense" ]
null
null
null
// // Created by ramya on 3/2/17. // #ifndef PLAYBOOK_COLLECTION_SCREEN_H #define PLAYBOOK_COLLECTION_SCREEN_H #include "cocos2d.h" #include "json/rapidjson.h" #include "json/document.h" #include "PlaybookLayer.h" #include "PlaybookEvent.h" #include "PredictionWebSocket.h" class CollectionScreen : public PlaybookLayer { public: static cocos2d::Scene* createScene(); virtual bool init(); virtual void update(float delta); void onEnter(); void onExit(); void onResume(); void onPause(); // implement the "static create()" method manually CREATE_FUNC(CollectionScreen); private: struct Card { Card(PlaybookEvent::Team team, PlaybookEvent::EventType event, cocos2d::Sprite* sprite); PlaybookEvent::Team team; PlaybookEvent::EventType event; cocos2d::Sprite* sprite; bool isDragged; int draggedTouchID; cocos2d::Vec2 draggedOrigPosition; bool draggedDropping; }; struct CardSlot { std::shared_ptr<Card> card; bool present; }; enum GoalType { IDENTICAL_CARDS_3, IDENTICAL_CARDS_4, IDENTICAL_CARDS_5, UNIQUE_OUT_CARDS_3, UNIQUE_OUT_CARDS_4, WALK_OR_HIT_BY_PITCH_3, OUT_3, BASES_RBI_3, EACH_COLOR_1, EACH_COLOR_2, SAME_COLOR_3, SAME_COLOR_4, SAME_COLOR_5, BASE_STEAL_RBI, ON_BASE_STEAL_PICK_OFF, FULL_HOUSE, UNKNOWN }; struct GoalMetadata { std::string name; std::string description; std::string file; int score; bool isHidden; int serverId; }; struct GoalTypeHash { template <typename T> std::size_t operator()(T t) const { return static_cast<std::size_t>(t); } }; static const int NUM_SLOTS; static const std::unordered_map<GoalType, GoalMetadata, GoalTypeHash> GOAL_TYPE_METADATA_MAP; const std::string NODE_NAME_HOLDER = "holder"; const std::string NODE_NAME_WHITE_BANNER = "whiteBanner"; const std::string NODE_NAME_SCORE_BAR = "scoreBar"; const std::string NODE_NAME_SCORE_BAR_SCORE_CARD = "scoreBarScoreCard"; const std::string NODE_NAME_GOAL_BAR = "goalBar"; const std::string NODE_NAME_GOAL_BAR_LABEL = "goalBarLabel"; const std::string NODE_NAME_GOALS_CONTAINER = "goalsContainer"; const std::string NODE_NAME_DRAG_TO_DISCARD = "dragToDiscard"; const std::string NODE_NAME_DRAG_TO_SCORE = "dragToScore"; const std::string NODE_NAME_DRAG_TO_SCORE_SHADOW_BOTTOM = "dragToScoreShadowBottom"; cocos2d::Node* _visibleNode; PredictionWebSocket* _websocket; cocos2d::Sprite* _cardsHolder; cocos2d::DrawNode* _cardSlotDrawNode; std::queue<PlaybookEvent::EventType> _incomingCardQueue; std::vector<CardSlot> _cardSlots; cocos2d::Node* _dragToDiscard; bool _dragToDiscardHovered; cocos2d::EventListener* _dragToDiscardListener; cocos2d::Sprite* _dragToScore; bool _dragToScoreHovered; cocos2d::EventListener* _dragToScoreListener; cocos2d::Sprite* _goalSprite; GoalType _activeGoal; GoalType _selectedGoal; std::vector<std::weak_ptr<Card>> _cardsMatchingSelectedGoal; bool _isCardActive; std::shared_ptr<Card> _activeCard; cocos2d::Action* _activeCardAction; float _activeCardOrigScale; cocos2d::Vec2 _activeCardOrigPosition; float _activeCardOrigRotation; cocos2d::EventListener* _activeEventListener; int _score; void initEventsDragToDiscard(); void initEventsDragToScore(); void invalidateDragToScore(); void connectToServer(); void disconnectFromServer(); void handleServerMessage(const std::string& event, const rapidjson::Value::ConstMemberIterator& data, bool hasData); void handlePlaysCreated(const rapidjson::Value::ConstMemberIterator& data, bool hasData); void reportScore(int score); void reportGoal(GoalType goal); std::weak_ptr<Card> getDraggedCard(cocos2d::Touch* touch); void receiveCard(PlaybookEvent::EventType event); std::shared_ptr<Card> createCard(PlaybookEvent::EventType event); void startDraggingActiveCard(cocos2d::Touch* touch); void stopDraggingActiveCard(cocos2d::Touch* touch); void discardCard(std::weak_ptr<Card> card); void scoreCardSet(GoalType goal, const std::vector<std::weak_ptr<Card>>& cardSet); void updateScore(int score, bool withAnimation = true); float getCardScaleInSlot(cocos2d::Node* card); cocos2d::Vec2 getCardPositionForSlot(cocos2d::Node* cardNode, int slot); cocos2d::Rect getCardBoundingBoxForSlot(cocos2d::Node* cardNode, int slot); void drawBoundingBoxForSlot(cocos2d::Node* cardNode, int slot); int getNearestAvailableCardSlot(cocos2d::Node *card, const cocos2d::Vec2 &position); void assignCardToSlot(std::shared_ptr<Card> card, int slot); void assignActiveCardToSlot(int slot); void createRandomGoal(); void setActiveGoal(GoalType goal); void checkIfGoalMet(); bool cardSetMeetsGoal(const std::vector<std::weak_ptr<Card>>& cardSet, GoalType goal, std::vector<std::weak_ptr<Card>>& outSet); void updateGoals(std::unordered_map<GoalType, std::vector<std::weak_ptr<Card>>, GoalTypeHash> goalSets); void highlightCardsMatchingGoal(); void restoreState(); void saveState(); std::string serialize(); void unserialize(const std::string& data); }; #endif //PLAYBOOK_COLLECTION_SCREEN_H
31.621469
108
0.697874
[ "vector" ]
245c1937f46f431ecab6c5757c4fa6b88a66483e
2,418
h
C
src/GooseDEM/GooseDEM.h
tdegeus/GooseDEM
cde2892f6a6b20509837b237f7153b985c73ea95
[ "MIT" ]
null
null
null
src/GooseDEM/GooseDEM.h
tdegeus/GooseDEM
cde2892f6a6b20509837b237f7153b985c73ea95
[ "MIT" ]
6
2018-05-08T09:11:06.000Z
2019-10-12T21:11:25.000Z
src/GooseDEM/GooseDEM.h
tdegeus/GooseDEM
cde2892f6a6b20509837b237f7153b985c73ea95
[ "MIT" ]
null
null
null
/* ================================================================================================= (c - MIT) T.W.J. de Geus (Tom) | tom@geus.me | www.geus.me | github.com/tdegeus/GooseDEM ================================================================================================= */ #ifndef GOOSEDEM_H #define GOOSEDEM_H // --------------------------------------- include libraries --------------------------------------- // use "M_PI" from "math.h" #define _USE_MATH_DEFINES #include <tuple> #include <fstream> #include <stdexcept> #include <limits> #include <math.h> #include <iso646.h> #include <Eigen/Eigen> #include <cppmat/cppmat.h> // ---------------------------------------- dummy operation ---------------------------------------- // dummy operation that can be use to suppress the "unused parameter" warnings #define UNUSED(p) ( (void)(p) ) // -------------------------------------- version information -------------------------------------- #define GOOSEDEM_WORLD_VERSION 0 #define GOOSEDEM_MAJOR_VERSION 0 #define GOOSEDEM_MINOR_VERSION 3 #define GOOSEDEM_VERSION_AT_LEAST(x,y,z) \ (GOOSEDEM_WORLD_VERSION>x || (GOOSEDEM_WORLD_VERSION>=x && \ (GOOSEDEM_MAJOR_VERSION>y || (GOOSEDEM_MAJOR_VERSION>=y && \ GOOSEDEM_MINOR_VERSION>=z)))) #define GOOSEDEM_VERSION(x,y,z) \ (GOOSEDEM_WORLD_VERSION==x && \ GOOSEDEM_MAJOR_VERSION==y && \ GOOSEDEM_MINOR_VERSION==z) // ------------------------------------------ alias types ------------------------------------------ namespace GooseDEM { typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatD; typedef Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatS; typedef Eigen::Matrix<double, Eigen::Dynamic, 1, Eigen::ColMajor> ColD; typedef Eigen::Matrix<size_t, Eigen::Dynamic, 1, Eigen::ColMajor> ColS; } // ------------------------------------------------------------------------------------------------- #include "Write.h" #include "Spring.h" #include "Dashpot.h" #include "Iterate.h" #include "Vector.h" #include "Geometry.h" #include "TimeIntegration.h" #include "Write.cpp" #include "Spring.cpp" #include "Dashpot.cpp" #include "Iterate.cpp" #include "Vector.cpp" #include "TimeIntegration.cpp" // ------------------------------------------------------------------------------------------------- #endif
31.815789
100
0.492556
[ "geometry", "vector" ]
2468f38976cf5c81a0f395ae7601c83542542a89
1,227
h
C
include/Individual.h
OliverMD/mpev
3aeec57ffff0396dce5d9d36c0f9dd529a4388d9
[ "MIT" ]
null
null
null
include/Individual.h
OliverMD/mpev
3aeec57ffff0396dce5d9d36c0f9dd529a4388d9
[ "MIT" ]
null
null
null
include/Individual.h
OliverMD/mpev
3aeec57ffff0396dce5d9d36c0f9dd529a4388d9
[ "MIT" ]
null
null
null
// // Created by Oliver Downard on 18/12/2017. // #pragma once #include <string> #include <vector> class Context; class IndividualRep { public: virtual std::string name() = 0; virtual std::unique_ptr<IndividualRep> copy() = 0; virtual std::string toString() const = 0; }; class IntIndividualRep : public IndividualRep { public: IntIndividualRep(int val) : value{val} {} std::string name() override { return "int"; } int getValue() { return value; } std::unique_ptr<IndividualRep> copy() override { return std::make_unique<IntIndividualRep>(value); } std::string toString() const override { return std::to_string(value); } private: int value; }; struct Individual { Individual(std::unique_ptr<IndividualRep> rep, float fit) : representation{std::move(rep)}, fitness{fit} {} std::unique_ptr<IndividualRep> representation; float fitness; }; /** * Basic Int individual maker * @return A random Individual with an IntIndividualRep */ Individual makeRandomIntIndivdual(Context &ctx); std::vector<Individual> crossoverIntIndividuals(Context &ctx, Individual &b, Individual &a); Individual mutateIntIndividual(Context &ctx, Individual &a);
25.5625
76
0.693562
[ "vector" ]
ba0f87158b5373b133e652b1eb1f6025a7607ab2
444
h
C
EasyCpp/Database/DatabaseDriver.h
Thalhammer/EasyCpp
6b9886fecf0aa363eaf03741426fd3462306c211
[ "MIT" ]
3
2018-02-06T05:12:41.000Z
2020-05-12T20:57:32.000Z
EasyCpp/Database/DatabaseDriver.h
Thalhammer/EasyCpp
6b9886fecf0aa363eaf03741426fd3462306c211
[ "MIT" ]
41
2016-07-11T12:19:10.000Z
2017-08-08T07:43:12.000Z
EasyCpp/Database/DatabaseDriver.h
Thalhammer/EasyCpp
6b9886fecf0aa363eaf03741426fd3462306c211
[ "MIT" ]
2
2019-08-02T10:24:36.000Z
2020-09-11T01:45:12.000Z
#pragma once #include "Database.h" #include <vector> namespace EasyCpp { namespace Database { class DLL_EXPORT DatabaseDriver { public: virtual ~DatabaseDriver() {} /// <summary>Create a instance of this database type using the provided DSN and options.</summary> virtual DatabasePtr createInstance(const std::string& dsn, const Bundle& options = {}) = 0; }; typedef std::shared_ptr<DatabaseDriver> DatabaseDriverPtr; } }
24.666667
101
0.727477
[ "vector" ]
ba1ae65bebf8bb1ed06c7842d72f7eb26026bdbd
1,857
h
C
Code/Framework/AzCore/AzCore/std/function/function_fwd.h
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
11
2021-07-08T09:58:26.000Z
2022-03-17T17:59:26.000Z
Code/Framework/AzCore/AzCore/std/function/function_fwd.h
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
29
2021-07-06T19:33:52.000Z
2022-03-22T10:27:49.000Z
Code/Framework/AzCore/AzCore/std/function/function_fwd.h
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
4
2021-07-06T19:24:43.000Z
2022-03-31T12:42:27.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ // Based on boost 1.39.0 #ifndef AZSTD_FUNCTION_FWD_H #define AZSTD_FUNCTION_FWD_H #include <AzCore/std/base.h> namespace AZStd { class bad_function_call; // Preferred syntax template<typename Signature> class function; template<typename Signature> inline void swap(function<Signature>& f1, function<Signature>& f2) { f1.swap(f2); } // Portable syntax //template<typename R> class function0; //template<typename R, typename T1> class function1; //template<typename R, typename T1, typename T2> class function2; //template<typename R, typename T1, typename T2, typename T3> class function3; //template<typename R, typename T1, typename T2, typename T3, typename T4> class function4; //template<typename R, typename T1, typename T2, typename T3, typename T4, typename T5> class function5; //template<typename R, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> class function6; //template<typename R, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> class function7; //template<typename R, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> class function8; //template<typename R, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> class function9; //template<typename R, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10> class function10; } #endif // AZSTD_FUNCTION_FWD_H #pragma once
45.292683
175
0.735595
[ "3d" ]
ba263800e4d5a20d300391d1c00f2059922f8e79
13,161
c
C
src/image.c
gamemasterplc/n64game
b4a478fd65aac15f54ce493640c729bab8391a58
[ "MIT" ]
2
2021-11-17T06:14:15.000Z
2021-11-20T00:46:04.000Z
src/image.c
gamemasterplc/n64game
b4a478fd65aac15f54ce493640c729bab8391a58
[ "MIT" ]
null
null
null
src/image.c
gamemasterplc/n64game
b4a478fd65aac15f54ce493640c729bab8391a58
[ "MIT" ]
1
2021-12-09T10:21:45.000Z
2021-12-09T10:21:45.000Z
#include <ultra64.h> #include "fs.h" #include "gfx.h" #include "malloc.h" #include "image.h" N64Image *ImageLoad(char *path) { FSFile file; if(!FSOpen(&file, path)) { //Failed to load file return NULL; } //Read image file u32 length = FSGetLength(&file); N64Image *image = malloc(length); FSRead(&file, image, length); //Fixup header pointers image->data = (void *)((u32)image+(u32)image->data); if(image->pal_data) { image->pal_data = (u16 *)((u32)image+(u32)image->pal_data); } return image; } N64Image *ImageCreate(u16 w, u16 h, u32 fmt) { N64Image *image = malloc(sizeof(N64Image)); image->fmt = fmt; image->w = w; image->h = h; //Allocate image data //4bpp images round up for odd numbers of pixels //CI4 and CI8 allocate a palette switch(fmt) { case IMG_FMT_I4: case IMG_FMT_IA4: image->data = malloc(((w*h)+1)/2); image->pal_data = NULL; break; case IMG_FMT_I8: case IMG_FMT_IA8: image->data = malloc(w*h); image->pal_data = NULL; break; case IMG_FMT_CI4: image->data = malloc(((w*h)+1)/2); image->pal_data = malloc(16*2); break; case IMG_FMT_CI8: image->data = malloc(w*h); image->pal_data = malloc(256*2); break; case IMG_FMT_IA16: case IMG_FMT_RGBA16: image->data = malloc(w*h*2); image->pal_data = NULL; break; case IMG_FMT_RGBA32: image->data = malloc(w*h*4); image->pal_data = NULL; break; default: image->data = NULL; image->pal_data = NULL; break; } return image; } void ImageFlushData(N64Image *image) { switch(image->fmt) { case IMG_FMT_I4: case IMG_FMT_IA4: osWritebackDCache(image->data, ((image->w*image->h)+1)/2); break; case IMG_FMT_I8: case IMG_FMT_IA8: osWritebackDCache(image->data, image->w*image->h); break; case IMG_FMT_CI4: osWritebackDCache(image->data, ((image->w*image->h)+1)/2); osWritebackDCache(image->pal_data, 16*2); break; case IMG_FMT_CI8: osWritebackDCache(image->data, image->w*image->h); osWritebackDCache(image->pal_data, 256*2); break; case IMG_FMT_IA16: case IMG_FMT_RGBA16: osWritebackDCache(image->data, image->w*image->h*2); break; case IMG_FMT_RGBA32: osWritebackDCache(image->data, image->w*image->h*4); break; default: break; } } void ImageDelete(N64Image *image) { if(image->data != (char *)image+16) { //Free image data if not from file free(image->data); if(image->pal_data) { free(image->pal_data); } } free(image); } static int slice_word_count[] = { 512, 512, 512, 512, 512, 256, 256, 512, 512 }; static u8 fmt_tile_bytes[] = { 0, 1, 0, 1, 2, 0, 1, 2, 2 }; static int GetSliceHeight(N64Image *image, int width) { int stride; if(fmt_tile_bytes[image->fmt] != 0) { //Proper Texture Stride Calculation if(image->fmt == IMG_FMT_RGBA32) { stride = ((width*fmt_tile_bytes[image->fmt])+7)>>2; } else { stride = ((width*fmt_tile_bytes[image->fmt])+7)>>3; } } else { //Proper 4-bit Texture Stride Calculation stride = ((width>>1)+7)>>3; } return slice_word_count[image->fmt]/stride; } static void LoadPalette(N64Image *image) { if(image->fmt == IMG_FMT_CI4 || image->fmt == IMG_FMT_CI8) { gDPSetTextureLUT(gfx_dlistp++, G_TT_RGBA16); if(image->fmt == IMG_FMT_CI8) { gDPLoadTLUT_pal256(gfx_dlistp++, image->pal_data); } else { gDPLoadTLUT_pal16(gfx_dlistp++, 0, image->pal_data); } } else { gDPSetTextureLUT(gfx_dlistp++, G_TT_NONE); } } static void LoadTexture(N64Image *image, u16 uls, u16 ult, u16 lrs, u16 lrt) { switch(image->fmt) { case IMG_FMT_I4: gDPLoadTextureTile_4b(gfx_dlistp++, image->data, G_IM_FMT_I, image->w, image->h, uls, ult, lrs, lrt, 0, G_TX_CLAMP, G_TX_CLAMP, G_TX_NOMASK, G_TX_NOMASK, G_TX_NOLOD, G_TX_NOLOD); break; case IMG_FMT_I8: gDPLoadTextureTile(gfx_dlistp++, image->data, G_IM_FMT_I, G_IM_SIZ_8b, image->w, image->h, uls, ult, lrs, lrt, 0, G_TX_CLAMP, G_TX_CLAMP, G_TX_NOMASK, G_TX_NOMASK, G_TX_NOLOD, G_TX_NOLOD); break; case IMG_FMT_IA4: gDPLoadTextureTile_4b(gfx_dlistp++, image->data, G_IM_FMT_IA, image->w, image->h, uls, ult, lrs, lrt, 0, G_TX_CLAMP, G_TX_CLAMP, G_TX_NOMASK, G_TX_NOMASK, G_TX_NOLOD, G_TX_NOLOD); break; case IMG_FMT_IA8: gDPLoadTextureTile(gfx_dlistp++, image->data, G_IM_FMT_IA, G_IM_SIZ_8b, image->w, image->h, uls, ult, lrs, lrt, 0, G_TX_CLAMP, G_TX_CLAMP, G_TX_NOMASK, G_TX_NOMASK, G_TX_NOLOD, G_TX_NOLOD); break; case IMG_FMT_IA16: gDPLoadTextureTile(gfx_dlistp++, image->data, G_IM_FMT_IA, G_IM_SIZ_16b, image->w, image->h, uls, ult, lrs, lrt, 0, G_TX_CLAMP, G_TX_CLAMP, G_TX_NOMASK, G_TX_NOMASK, G_TX_NOLOD, G_TX_NOLOD); break; case IMG_FMT_CI4: gDPLoadTextureTile_4b(gfx_dlistp++, image->data, G_IM_FMT_CI, image->w, image->h, uls, ult, lrs, lrt, 0, G_TX_CLAMP, G_TX_CLAMP, G_TX_NOMASK, G_TX_NOMASK, G_TX_NOLOD, G_TX_NOLOD); break; case IMG_FMT_CI8: gDPLoadTextureTile(gfx_dlistp++, image->data, G_IM_FMT_CI, G_IM_SIZ_8b, image->w, image->h, uls, ult, lrs, lrt, 0, G_TX_CLAMP, G_TX_CLAMP, G_TX_NOMASK, G_TX_NOMASK, G_TX_NOLOD, G_TX_NOLOD); break; case IMG_FMT_RGBA16: gDPLoadTextureTile(gfx_dlistp++, image->data, G_IM_FMT_RGBA, G_IM_SIZ_16b, image->w, image->h, uls, ult, lrs, lrt, 0, G_TX_CLAMP, G_TX_CLAMP, G_TX_NOMASK, G_TX_NOMASK, G_TX_NOLOD, G_TX_NOLOD); break; case IMG_FMT_RGBA32: gDPLoadTextureTile(gfx_dlistp++, image->data, G_IM_FMT_RGBA, G_IM_SIZ_32b, image->w, image->h, uls, ult, lrs, lrt, 0, G_TX_CLAMP, G_TX_CLAMP, G_TX_NOMASK, G_TX_NOMASK, G_TX_NOLOD, G_TX_NOLOD); break; } } static void PutImageNoFlip(N64Image *image, int x, int y, int src_x, int src_y, int src_w, int src_h) { int slice_h = GetSliceHeight(image, src_w); if(src_h <= slice_h) { //Fast one-slice path LoadTexture(image, src_x, src_y, (src_x+src_w)-1, (src_y+src_h)-1); gSPScisTextureRectangle(gfx_dlistp++, x*4, y*4, (x+src_w)*4, (y+src_h)*4, 0, src_x*32, src_y*32, 1024, 1024); gDPPipeSync(gfx_dlistp++); } else { //Multi-slice path int num_slices = src_h/slice_h; int remainder_h = src_h%slice_h; int slice_y = 0; //Render slices for(int i=0; i<num_slices; i++) { if(y+slice_y < -slice_h) { //Skip offscreen slices slice_y += slice_h; continue; } LoadTexture(image, src_x, src_y+slice_y, (src_x+src_w)-1, (src_y+slice_y+slice_h)-1); gSPScisTextureRectangle(gfx_dlistp++, x*4, (y+slice_y)*4, (x+src_w)*4, (y+slice_y+slice_h)*4, 0, src_x*32, (src_y+slice_y)*32, 1024, 1024); gDPPipeSync(gfx_dlistp++); slice_y += slice_h; } if(remainder_h == 0) { return; } //Render remainder LoadTexture(image, src_x, src_y+slice_y, (src_x+src_w)-1, (src_y+slice_y+remainder_h)-1); gSPScisTextureRectangle(gfx_dlistp++, x*4, (y+slice_y)*4, (x+src_w)*4, (y+slice_y+remainder_h)*4, 0, src_x*32, (src_y+slice_y)*32, 1024, 1024); gDPPipeSync(gfx_dlistp++); } } static void PutImageFlipX(N64Image *image, int x, int y, int src_x, int src_y, int src_w, int src_h) { int slice_h = GetSliceHeight(image, src_w); if(src_h <= slice_h) { //Fast one-slice path LoadTexture(image, src_x, src_y, (src_x+src_w)-1, (src_y+src_h)-1); gSPScisTextureRectangle(gfx_dlistp++, x*4, y*4, (x+src_w)*4, (y+src_h)*4, 0, (src_x+src_w-1)*32, src_y*32, -1024, 1024); gDPPipeSync(gfx_dlistp++); } else { //Multi-slice path int num_slices = src_h/slice_h; int remainder_h = src_h%slice_h; int slice_y = 0; //Render slices for(int i=0; i<num_slices; i++) { if(y+slice_y < -slice_h) { //Skip offscreen slices slice_y += slice_h; continue; } LoadTexture(image, src_x, src_y+slice_y, (src_x+src_w)-1, (src_y+slice_y+slice_h)-1); gSPScisTextureRectangle(gfx_dlistp++, x*4, (y+slice_y)*4, (x+src_w)*4, (y+slice_y+slice_h)*4, 0, (src_x+src_w-1)*32, (src_y+slice_y)*32, -1024, 1024); gDPPipeSync(gfx_dlistp++); slice_y += slice_h; } if(remainder_h == 0) { return; } //Render remainder LoadTexture(image, src_x, src_y+slice_y, (src_x+src_w)-1, (src_y+slice_y+remainder_h)-1); gSPScisTextureRectangle(gfx_dlistp++, x*4, (y+slice_y)*4, (x+src_w)*4, (y+slice_y+remainder_h)*4, 0, (src_x+src_w-1)*32, (src_y+slice_y)*32, -1024, 1024); gDPPipeSync(gfx_dlistp++); } } static void PutImageFlipY(N64Image *image, int x, int y, int src_x, int src_y, int src_w, int src_h) { int slice_h = GetSliceHeight(image, src_w); if(src_h <= slice_h) { //Fast one-slice path LoadTexture(image, src_x, src_y, (src_x+src_w)-1, (src_y+src_h)-1); gSPScisTextureRectangle(gfx_dlistp++, x*4, y*4, (x+src_w)*4, (y+src_h)*4, 0, src_x*32, (src_y+src_h-1)*32, 1024, -1024); gDPPipeSync(gfx_dlistp++); } else { //Multi-slice path int num_slices = src_h/slice_h; int remainder_h = src_h%slice_h; int slice_y = 0; //Render slices for(int i=0; i<num_slices; i++) { if(y+slice_y < -slice_h) { //Skip offscreen slices slice_y += slice_h; continue; } LoadTexture(image, src_x, src_y+slice_y, (src_x+src_w)-1, (src_y+slice_y+slice_h)-1); gSPScisTextureRectangle(gfx_dlistp++, x*4, (y+(src_h-(slice_y+slice_h)))*4, (x+src_w)*4, (y+(src_h-slice_y))*4, 0, src_x*32, (src_y+slice_y+slice_h-1)*32, 1024, -1024); gDPPipeSync(gfx_dlistp++); slice_y += slice_h; } if(remainder_h == 0) { return; } //Render remainder LoadTexture(image, src_x, src_y+slice_y, (src_x+src_w)-1, (src_y+slice_y+remainder_h)-1); gSPScisTextureRectangle(gfx_dlistp++, x*4, y*4, (x+src_w)*4, (y+remainder_h)*4, 0, src_x*32, (src_y+slice_y+remainder_h-1)*32, 1024, -1024); gDPPipeSync(gfx_dlistp++); } } static void PutImageFlipXY(N64Image *image, int x, int y, int src_x, int src_y, int src_w, int src_h) { int slice_h = GetSliceHeight(image, src_w); if(src_h <= slice_h) { //Fast one-slice path LoadTexture(image, src_x, src_y, (src_x+src_w)-1, (src_y+src_h)-1); gSPScisTextureRectangle(gfx_dlistp++, x*4, y*4, (x+src_w)*4, (y+src_h)*4, 0, (src_x+src_w-1)*32, (src_y+src_h-1)*32, -1024, -1024); gDPPipeSync(gfx_dlistp++); } else { //Multi-slice path int num_slices = src_h/slice_h; int remainder_h = src_h%slice_h; int slice_y = 0; //Render slices for(int i=0; i<num_slices; i++) { if(y+slice_y < -slice_h) { //Skip offscreen slices slice_y += slice_h; continue; } LoadTexture(image, src_x, src_y+slice_y, (src_x+src_w)-1, (src_y+slice_y+slice_h)-1); gSPScisTextureRectangle(gfx_dlistp++, x*4, (y+(src_h-(slice_y+slice_h)))*4, (x+src_w)*4, (y+(src_h-slice_y))*4, 0, (src_x+src_w-1)*32, (src_y+slice_y+slice_h-1)*32, -1024, -1024); gDPPipeSync(gfx_dlistp++); slice_y += slice_h; } if(remainder_h == 0) { return; } //Render remainder LoadTexture(image, src_x, src_y+slice_y, (src_x+src_w)-1, (src_y+slice_y+remainder_h)-1); gSPScisTextureRectangle(gfx_dlistp++, x*4, y*4, (x+src_w)*4, (y+remainder_h)*4, 0, (src_x+src_w-1)*32, (src_y+slice_y+remainder_h-1)*32, -1024, -1024); gDPPipeSync(gfx_dlistp++); } } void ImagePutTintFlip(N64Image *image, int x, int y, int flip, u32 tint) { //Check for hidden image if(x < -image->w || y < -image->h) { return; } if(tint == GFX_COLOR_WHITE) { //White equals no tint GfxSetRenderMode(GFX_RENDER_IMAGE); } else { //Get tint channels u8 tint_r = (tint >> 24) & 0xFF; u8 tint_g = (tint >> 16) & 0xFF; u8 tint_b = (tint >> 8) & 0xFF; u8 tint_a = tint & 0xFF; GfxSetRenderMode(GFX_RENDER_IMAGETINT); gDPSetPrimColor(gfx_dlistp++, 0, 0, tint_r, tint_g, tint_b, tint_a); } LoadPalette(image); switch(flip) { case IMAGE_FLIP_NONE: PutImageNoFlip(image, x, y, 0, 0, image->w, image->h); break; case IMAGE_FLIP_X: PutImageFlipX(image, x, y, 0, 0, image->w, image->h); break; case IMAGE_FLIP_Y: PutImageFlipY(image, x, y, 0, 0, image->w, image->h); break; case IMAGE_FLIP_XY: PutImageFlipXY(image, x, y, 0, 0, image->w, image->h); break; default: PutImageNoFlip(image, x, y, 0, 0, image->w, image->h); break; } } void ImagePutPartialTintFlip(N64Image *image, int x, int y, int src_x, int src_y, int src_w, int src_h, int flip, u32 tint) { //Check for hidden image if(x < -src_w || y < -src_h) { return; } if(tint == GFX_COLOR_WHITE) { //White equals no tint GfxSetRenderMode(GFX_RENDER_IMAGE); } else { //Get tint channels u8 tint_r = (tint >> 24) & 0xFF; u8 tint_g = (tint >> 16) & 0xFF; u8 tint_b = (tint >> 8) & 0xFF; u8 tint_a = tint & 0xFF; GfxSetRenderMode(GFX_RENDER_IMAGETINT); gDPSetPrimColor(gfx_dlistp++, 0, 0, tint_r, tint_g, tint_b, tint_a); } LoadPalette(image); switch(flip) { case IMAGE_FLIP_NONE: PutImageNoFlip(image, x, y, src_x, src_y, src_w, src_h); break; case IMAGE_FLIP_X: PutImageFlipX(image, x, y, src_x, src_y, src_w, src_h); break; case IMAGE_FLIP_Y: PutImageFlipY(image, x, y, src_x, src_y, src_w, src_h); break; case IMAGE_FLIP_XY: PutImageFlipXY(image, x, y, src_x, src_y, src_w, src_h); break; default: PutImageNoFlip(image, x, y, src_x, src_y, src_w, src_h); break; } }
29.117257
123
0.663627
[ "render" ]
ba2d505155b8684a23e800f1dbd98a2a5e874819
5,108
h
C
include/db/dbtable.h
mamontov-cpp/saddy
f20a0030e18af9e0714fe56c19407fbeacc529a7
[ "BSD-2-Clause" ]
58
2015-08-09T14:56:35.000Z
2022-01-15T22:06:58.000Z
include/db/dbtable.h
mamontov-cpp/saddy-graphics-engine-2d
e25a6637fcc49cb26614bf03b70e5d03a3a436c7
[ "BSD-2-Clause" ]
245
2015-08-08T08:44:22.000Z
2022-01-04T09:18:08.000Z
include/db/dbtable.h
mamontov-cpp/saddy
f20a0030e18af9e0714fe56c19407fbeacc529a7
[ "BSD-2-Clause" ]
23
2015-12-06T03:57:49.000Z
2020-10-12T14:15:50.000Z
/*! \file db/dbtable.h Contains definition of class Table, which represents object table in database. */ #pragma once #include "dbobject.h" #include "../refcountable.h" namespace sad { namespace db { class Database; class ObjectFactory; /*! \class Table A table, which represents objects in database, which could be used to fetch objects dynamically and do some other stuff. */ class Table: public sad::RefCountable { public: /*! Creates new empty table */ Table(); /*! This class can be inherited */ virtual ~Table(); /*! Adds new object to a table \param[in] a an object */ virtual void add(sad::db::Object* a); /*! Removes objects from table \param[in] a an object */ virtual void remove(sad::db::Object* a); /*! Queries a table by full key \param[in] major_id a major id, stored in DB \param[in] minor_id a minor local key \return a found object (nullptr if not found) */ virtual sad::db::Object* queryById(unsigned long long major_id, unsigned long long minor_id); /*! Query table by minor id \param[in] minor_id a minor id \return a found object (nullptr if not found) */ virtual sad::db::Object* queryByMinorId(unsigned long long minor_id); /*! Queries a table by name \param[in] name a name \return a vector of linked object */ virtual sad::Vector<sad::db::Object*> queryByName(const sad::String& name); /*! Queries a table by name \param[in] name a name \return an object or null if not found */ virtual sad::db::Object* objectByName(const sad::String& name); /*! Queries objects from table by major id field \param[in] major_id an id \return an object, or null if not found */ virtual sad::db::Object* queryByMajorId(unsigned long long major_id); /*! Loads table from a value \param[in] v value \param[in] factory a factory \param[in] renderer a renderer, where should resources, linked to objects be stored \param[in] tree_name a name for tree, where should resourced, linked to objects be stored \return whether value was successfull */ virtual bool load( const picojson::value & v, sad::db::ObjectFactory* factory, sad::Renderer* renderer = nullptr, const sad::String& tree_name = "" ); /*! Saves a table to a value \param[out] v a value for table */ virtual void save(picojson::value & v); /*! Returns database, linked with table \return database */ sad::db::Database* database() const; /*! Sets database for a table \param[in] d database */ void setDatabase(sad::db::Database* d); /*! Fills vector with objects from table \param[out] o objects */ virtual void objects(sad::Vector<sad::db::Object*> & o); /*! Returns object list from table \return object list from table */ sad::Vector<sad::db::Object*> objectList(); /*! Returns object list from table with only objects of specified type \param[in] s string \return object list from table */ sad::Vector<sad::db::Object*> objectListOfType(const sad::String& s); /*! Fetches objects of specified type from table \param[out] o objects */ template< typename T > void objectsOfType(sad::Vector<T*> & o) { sad::db::TypeName<T>::init(); const sad::String type_name = (sad::db::TypeName<T>::name()); o.clear(); for(sad::Hash<unsigned long long, sad::db::Object*>::iterator it = m_objects_by_minorid.begin(); it != m_objects_by_minorid.end(); ++it) { if (it.value()->isInstanceOf(type_name)) { o << static_cast<T*>(it.value()); } } } /*! Changes object name in hash table to make container consistent \param[in] o object \param[in] old_name old name of object \param[in] name a name of object */ virtual void changeObjectName( sad::db::Object * o, const sad::String & old_name, const sad::String & name ); /*! Clears a table */ void clear(); /*! Returns, whether table is empty */ bool empty() const; protected: /*! Maximum minor id */ unsigned long long m_max_minor_id; /*! A database, which table is belongs to */ sad::db::Database * m_database; /*! Objects, determined by name */ sad::Hash<sad::String, sad::Vector<sad::db::Object*> > m_object_by_name; /*! A hash, storing objects by minor id */ sad::Hash<unsigned long long, sad::db::Object*> m_objects_by_minorid; /*! A hash, storing objects by major id */ sad::Hash<unsigned long long, sad::db::Object*> m_objects_by_majorid; }; } }
31.337423
106
0.584965
[ "object", "vector" ]
ba3a28c12cc8fea9bce5d60c32d683aed2d2aa5f
4,757
h
C
Computational_Module/Computational_Module_Class_File.h
ValveDigitalHealth/EPlabResearchWorksApp
bfae0b2e5e492bca778e96457738ba316e77b197
[ "MIT" ]
null
null
null
Computational_Module/Computational_Module_Class_File.h
ValveDigitalHealth/EPlabResearchWorksApp
bfae0b2e5e492bca778e96457738ba316e77b197
[ "MIT" ]
null
null
null
Computational_Module/Computational_Module_Class_File.h
ValveDigitalHealth/EPlabResearchWorksApp
bfae0b2e5e492bca778e96457738ba316e77b197
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------- /* MIT LICENSE Copyright (c) 2021 Pawel Kuklik Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the SOFTWARE. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ //--------------------------------------------------------------------------- #ifndef Computational_Module_Class_FileH #define Computational_Module_Class_FileH //--------------------------------------------------------------------------- #include<vector> #include <math.h> #include "Progress_Bar_Form.h" #include "predefined_parameters.h" #include "Numerical_Library.h" //---------------------------------------------------------------------------------------- class Computational_Module_Class { public: Computational_Module_Class(); //--------------------------------------------------------- // Save/load object to/from stream //--------------------------------------------------------- int save_object_to_stream(ofstream* File); int load_object_from_stream(ifstream* File); Numerical_Library Numerical_Library_Obj; //---------------------------------------------------------------------- // ANNOTATION PARAMETERS //---------------------------------------------------------------------- int Deflection_Detection_Alg; bool Individual_Reference_Channel_Annotation; bool Automatic_Annotation_Flag; double Min_Voltage_Threshold_for_LAT_annotation_mV; double Max_Distance_Data_Points_Projection_mm; //---------------------------------------------------------------------- // Left and right distance from the activation in Roving channel around // which activation in the Roving channel is searched. // Now values are the same in all channels (copied from Annotation Setup in Main_form) //---------------------------------------------------------------------- int ROV_LAT_Annotation_Left_Edge_ms; int ROV_LAT_Annotation_Right_Edge_ms; // Sliding SD window annotation parameters double Deflection_SD_WL_ms; double Deflection_SD_Th; //---------------------------------------------------------------------------- // Function finds ACTIVATION in the signal between Begin and // End positions using given algorithm and stores found position in // long *Activation_Ptr. Returns OK_RESULT if ok. //---------------------------------------------------------------------------- template <typename TV> void detect_single_activation(std::vector<TV> *Signal, long Begin, long End, long *Activation_Ptr,double Time_Step_ms); int Sliding_Window_Algorithm; /* void reposition_reference_bar_according_to_V_wave(STUDY_Class *STUDY, TProgress_Form *Progress_Form,vector<double> *V_Wave, int V_Wave_Source); */ //---------------------------------------------------------------------- // microFRACTIONATION //---------------------------------------------------------------------- int Microfractionation_Algorithm; long Window_Check_size_ms; // robimy check zeby byla ciagla??? double Microfractionation_percentile_threshold; //---------------------------------------------------------------------- // AF voltage amplitude //---------------------------------------------------------------------- long Window_Length_For_AF_Voltage_Calculation_ms; //---------------------------------------------------------------------- // Electric dispersion calculation //---------------------------------------------------------------------- long Sliding_Window_Size_for_dispersion_calculation_ms; double Voltage_threshold_for_dispersion_calculation_mV; //---------------------------------------------------------------------- // Fractionation / MPD //---------------------------------------------------------------------- double Window_Size_ms; double PP_Threshold; double Peak_Definition_Range_ms; double MPD_Min_Duration; long MPD_Min_Peak_No; }; #endif
39.641667
90
0.558335
[ "object", "vector" ]
ba4143e7034b7cbdcaee2f7cbeeafddf4eacc41e
7,391
h
C
termsrv/remdsk/server/sessmgr/map.h
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
termsrv/remdsk/server/sessmgr/map.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
termsrv/remdsk/server/sessmgr/map.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1999-2000 Microsoft Corporation Module Name: map.h Abstract: Implementation of MAP<> template based on STL's map<> Author: HueiWang 2/17/2000 --*/ #ifndef __MAP_H__ #define __MAP_H__ #include "tsstl.h" #include "locks.h" class CMAPException { public: DWORD m_ErrorCode; CMAPException(DWORD errorCode = 0) : m_ErrorCode(errorCode) {} }; template<class T> class MAPAllocator : public allocator<T> { public: MAPAllocator() : allocator<T>() {} pointer allocate(size_type n, const void *hint) { T* ptr; ptr = (T *)operator new( (size_t)n * sizeof(T)); if( NULL == ptr ) { throw CMAPException(ERROR_NOT_ENOUGH_MEMORY); } return ptr; } char * _Charalloc(size_type sz) { return (char *)allocate( sz, NULL ); } // // No need to overload construct(), // // void construct(pointer p, const T& val); // // The member function constructs an object of type T at p by evaluating // the placement new expression new ((void *)p) T(val). // }; template<class KEY, class T, class Pred = less<KEY>, class A = MAPAllocator<T> > class MAP : public map<KEY, T, Pred, A> { private: // // Difference between this MAP<> and STL's map<> is that this // template protect data via critical section, refer to STL's map<> // for detail of member function. // // critical section to lock the tree. CCriticalSection m_CriticalSection; // //map<KEY, T, Pred, A>::iterator m_it; public: // LOCK_ITERATOR, derive from STL's map<>::iterator typedef typename map<KEY, T, Pred, A>::iterator Iter_base; struct __Iterator : Iter_base { CCriticalSection& lock; __Iterator( const __Iterator& it ) : lock(it.lock) /*++ --*/ { lock.Lock(); *this = it; } __Iterator( CCriticalSection& m, iterator it ) : lock(m) { lock.Lock(); *(map<KEY, T, Pred, A>::iterator *)this = it; } ~__Iterator() { lock.UnLock(); } __Iterator& operator=(const __Iterator& it ) { if( this != &it ) { // No additional Lock() here since // our constructor already holding a lock *(map<KEY, T, Pred, A>::iterator *)this = (map<KEY, T, Pred, A>::iterator)it; } return *this; } }; typedef __Iterator LOCK_ITERATOR; LOCK_ITERATOR begin() /*++ overload map<>::begin() --*/ { // Double lock is necessary, caller could do // <...>::LOCK_ITERATOR it = <>.find(); // and before LOCK_ITERATOR destructor got call, call might do // it = <>.find() again, that will increase lock count by 1 and // no way to release it. CCriticalSectionLocker lock( m_CriticalSection ); return LOCK_ITERATOR(m_CriticalSection, map<KEY, T, Pred, A>::begin()); } explicit MAP( const Pred& comp = Pred(), const A& al = A() ) : map<KEY, T, Pred, A>( comp, al ) /*++ --*/ { //m_it = end(); } MAP(const map& x) : map(x) { m_it = end(); } MAP( const value_type *first, const value_type *last, const Pred& comp = Pred(), const A& al = A() ) : map( first, last, comp, al ) { //m_it = end(); } //virtual ~MAP() //{ // map<KEY, T, Pred, A>::~map(); //} //--------------------------------------------------------- void Cleanup() { erase_all(); } //--------------------------------------------------------- void Lock() /*++ Explicity lock the data tree --*/ { m_CriticalSection.Lock(); } //--------------------------------------------------------- void Unlock() /*++ lock lock the data tree --*/ { m_CriticalSection.UnLock(); } //--------------------------------------------------------- bool TryLock() /*++ Try locking the tree, same as Win32's TryEnterCriticalSection(). --*/ { return m_CriticalSection.TryLock(); } //--------------------------------------------------------- typename A::reference operator[]( const KEY& key ) /*++ Overload map<>::operator[] to lock tree. --*/ { CCriticalSectionLocker lock( m_CriticalSection ); return map<KEY, T, Pred, A>::operator[](key); } //--------------------------------------------------------- pair<iterator, bool> insert(iterator it, const value_type& x) /*++ overload map<>;;insert() --*/ { CCriticalSectionLocker lock( m_CriticalSection ); return map<KEY, T, Pred, A>::insert(Key); } //--------------------------------------------------------- void insert( const value_type* first, const value_type* last ) /*++ overload map<>::insert(). --*/ { CCriticalSectionLocker lock( m_CriticalSection ); map<KEY, T, Pred, A>::insert(first, lase); } //--------------------------------------------------------- LOCK_ITERATOR erase( iterator it ) /*++ overload map<>::erase() --*/ { CCriticalSectionLocker lock( m_CriticalSection ); return LOCK_ITERATOR(m_CriticalSection, map<KEY, T, Pred, A>::erase(it)); } //--------------------------------------------------------- void erase_all() /*++ delete all data in the tree --*/ { CCriticalSectionLocker lock( m_CriticalSection ); erase( map<KEY, T, Pred, A>::begin(), end() ); return; } //--------------------------------------------------------- LOCK_ITERATOR erase( iterator first, iterator last ) /*++ Overload map<>::erase() --*/ { CCriticalSectionLocker lock( m_CriticalSection ); return LOCK_ITERATOR(m_CriticalSection, map<KEY, T, Pred, A>::erase(first, last)); } //--------------------------------------------------------- size_type erase( const KEY& key ) /*++ overload map<>::erase() --*/ { CCriticalSectionLocker lock( m_CriticalSection ); return map<KEY, T, Pred, A>::erase(key); } LOCK_ITERATOR find( const KEY& key ) /*++ overload map<>::find() --*/ { CCriticalSectionLocker lock( m_CriticalSection ); return LOCK_ITERATOR( m_CriticalSection, map<KEY, T, Pred, A>::find(key) ); } }; #endif
21.17765
94
0.436071
[ "object" ]
ba47726e9d01c543073c0fabc683fb1cd9864c7f
5,162
c
C
private/ntos/ke/ia64/ia32init.c
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/ntos/ke/ia64/ia32init.c
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/ntos/ke/ia64/ia32init.c
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
/*++ Module Name: ia32init.c Abstract: This module contains code to support iA32 resources structures Author: Revision History: --*/ #include "ki.h" #if defined(WX86) VOID KiInitializeGdtEntry ( OUT PKGDTENTRY GdtEntry, IN ULONG Base, IN ULONG Limit, IN USHORT Type, IN USHORT Dpl, IN USHORT Granularity ) /*++ Routine Description: This function initializes a GDT entry. Base, Limit, Type (code, data), and Dpl (0 or 3) are set according to parameters. All other fields of the entry are set to match standard system values. Arguments: GdtEntry - GDT descriptor to be filled in. Base - Linear address of the first byte mapped by the selector. Limit - Size of the selector in pages. Note that 0 is 1 page while 0xffffff is 1 megapage = 4 gigabytes. Type - Code or Data. All code selectors are marked readable, all data selectors are marked writeable. Dpl - User (3) or System (0) Granularity - 0 for byte, 1 for page Return Value: Pointer to the GDT entry. --*/ { GdtEntry->LimitLow = (USHORT)(Limit & 0xffff); GdtEntry->BaseLow = (USHORT)(Base & 0xffff); GdtEntry->HighWord.Bytes.BaseMid = (UCHAR)((Base & 0xff0000) >> 16); GdtEntry->HighWord.Bits.Type = Type; GdtEntry->HighWord.Bits.Dpl = Dpl; GdtEntry->HighWord.Bits.Pres = 1; GdtEntry->HighWord.Bits.LimitHi = (Limit & 0xf0000) >> 16; GdtEntry->HighWord.Bits.Sys = 0; GdtEntry->HighWord.Bits.Reserved_0 = 0; GdtEntry->HighWord.Bits.Default_Big = 1; GdtEntry->HighWord.Bits.Granularity = Granularity; GdtEntry->HighWord.Bytes.BaseHi = (UCHAR)((Base & 0xff000000) >> 24); } VOID KiInitializeXDescriptor ( OUT PKXDESCRIPTOR Descriptor, IN ULONG Base, IN ULONG Limit, IN USHORT Type, IN USHORT Dpl, IN USHORT Granularity ) /*++ Routine Description: This function initializes a unscrambled Descriptor. Base, Limit, Type (code, data), and Dpl (0 or 3) are set according to parameters. All other fields of the entry are set to match standard system values. The Descriptor will be initialized to 0 first, and then setup as requested Arguments: Descriptor - descriptor to be filled in. Base - Linear address of the first byte mapped by the selector. Limit - Size of the selector in pages. Note that 0 is 1 page while 0xffffff is 1 megapage = 4 gigabytes. Type - Code or Data. All code selectors are marked readable, all data selectors are marked writeable. Dpl - User (3) or System (0) Granularity - 0 for byte, 1 for page Return Value: Pointer to the Descriptor --*/ { Descriptor->Words.DescriptorWords = 0; Descriptor->Words.Bits.Base = Base; Descriptor->Words.Bits.Limit = Limit; Descriptor->Words.Bits.Type = Type; Descriptor->Words.Bits.Dpl = Dpl; Descriptor->Words.Bits.Pres = 1; Descriptor->Words.Bits.Default_Big = 1; Descriptor->Words.Bits.Granularity = Granularity; } VOID KeiA32ResourceCreate ( IN PEPROCESS Process, IN PTEB Teb ) /*++ Routine Description: To initial Gdt Table for the target user thread Only called from KiInitializeContextThread() Arguments: Thread - Pointer to KTHREAD object Return value: None --*/ { ULONG i; PUCHAR Gdt; ASSERT (sizeof(KTRAP_FRAME) == sizeof(KIA32_FRAME)); // // Initialize each required Gdt entry // Gdt = (PUCHAR) Teb->Gdt; RtlZeroMemory(Gdt, GDT_TABLE_SIZE); KiInitializeGdtEntry((PKGDTENTRY)(Gdt + KGDT_R3_CODE), 0, (ULONG)-1, TYPE_CODE_USER, DPL_USER, GRAN_PAGE); KiInitializeGdtEntry((PKGDTENTRY)(Gdt + KGDT_R3_DATA), 0, (ULONG)-1, TYPE_DATA_USER, DPL_USER, GRAN_PAGE); // // Set user TEB descriptor // KiInitializeGdtEntry((PKGDTENTRY)(Gdt + KGDT_R3_TEB), Teb, sizeof(TEB)-1, TYPE_DATA_USER, DPL_USER, GRAN_BYTE); // // The FS descriptor for ISA transitions. This needs to be in // unscrambled format // KiInitializeXDescriptor((PKXDESCRIPTOR)&(Teb->FsDescriptor), Teb, sizeof(TEB)-1, TYPE_DATA_USER, DPL_USER, GRAN_BYTE); // Set BIOS descriptor // // Set LDT descriptor, just copy whatever the Proecss has // *(PKGDTENTRY)(Gdt+KGDT_LDT) = (Process->Pcb).LdtDescriptor; // Set Video display buffer descriptor // // Setup ISA transition GdtDescriptor - needs to be unscrambled // But according tot he seamless EAS, only the base and limit // are actually used... // KiInitializeXDescriptor((PKXDESCRIPTOR)&(Teb->GdtDescriptor), (ULONG)Gdt, GDT_TABLE_SIZE-1, TYPE_DATA_USER, DPL_USER, GRAN_BYTE); // // Setup ISA transition LdtDescriptor - needs to be unscrambled // Teb->LdtDescriptor = (ULONGLONG)((Process->Pcb).UnscrambledLdtDescriptor); } #endif // defined(WX86)
24.009302
79
0.639093
[ "object" ]