text
stringlengths
2
1.04M
meta
dict
<?xml version="1.0" encoding="UTF-8" ?> <http-response statusCode="503"> <annotation name="Server unavailable response" host="example.com" port="80" scheme="http" uri-path="/users/u10391" request-method="GET">This is the description for this mock response.</annotation> <headers> <header name="Content-Length" value="0" /> <header name="Retry-After" value="Fri, 04 Nov 2014 23:59:59 GMT" /> </headers> <cookies /> <body /> </http-response>
{ "content_hash": "34e8c74f6b10c861da92cc8aa6709e6b", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 95, "avg_line_length": 35.2, "alnum_prop": 0.5928030303030303, "repo_name": "evanspa/PEHateoas-Client", "id": "e24bc61023acb758051c46d00d7c38a4b4791c17", "size": "528", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "PEHateoas-ClientTests/http-mock-responses/http-response.503.1.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "289721" }, { "name": "Ruby", "bytes": "1418" }, { "name": "Shell", "bytes": "700" } ], "symlink_target": "" }
#include <iterator> #include <string> #include <vector> #include "tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.h" #include "tensorflow/contrib/lite/toco/graph_transformations/quantization_util.h" #include "tensorflow/contrib/lite/toco/model.h" #include "tensorflow/contrib/lite/toco/tooling_util.h" namespace toco { namespace { // The minimum number of elements a weights array must have to be quantized // by this transformation. // TODO(suharshs): Make this minimum size configurable. const int kWeightsMinSize = 1024; // Gets the quantization params from the float array. void GetQuantizationParamsFromArray(const Array& array, QuantizationParams* params) { const std::vector<float>& float_vals = array.GetBuffer<ArrayDataType::kFloat>().data; auto minmax = std::minmax_element(float_vals.begin(), float_vals.end()); MinMax toco_minmax; toco_minmax.min = *minmax.first; toco_minmax.max = *minmax.second; GetQuantizationParams(ArrayDataType::kUint8, toco_minmax, params); } } // namespace bool QuantizeWeights::Run(Model* model, std::size_t op_index) { const auto op_it = model->operators.begin() + op_index; Operator* op = op_it->get(); // Get the weights tensor, if the current operator has one. int weights_index; if (op->type == OperatorType::kConv || op->type == OperatorType::kDepthwiseConv || op->type == OperatorType::kFullyConnected) { weights_index = 1; } else if (op->type == OperatorType::kLstmCell) { weights_index = LstmCellOperator::WEIGHTS_INPUT; } else { return false; } // Return early if the array isn't a constant param, this can happen in early // transformation passes until transpose operations following the weight array // are resolved. const string weights = op->inputs[weights_index]; if (!IsConstantParameterArray(*model, weights)) { return false; } // Return early if the weight tensor is not type float. Array& weights_array = model->GetArray(weights); if (weights_array.data_type != ArrayDataType::kFloat) { return false; } // Return early if the tensor is too small. Small tensors don't take up too // much space and can result in bad quantization results. if (weights_array.GetBuffer<ArrayDataType::kFloat>().data.size() < kWeightsMinSize) { return false; } // Quantize the weight tensor to type kUint8. QuantizationParams params; GetQuantizationParamsFromArray(weights_array, &params); QuantizeArray(this, model, weights, ArrayDataType::kUint8, params); // Insert a Dequantize operation after the quantized weights tensor. auto* dequantize_op = new DequantizeOperator; model->operators.emplace(op_it, dequantize_op); // Create a new intermediate tensor to connect the Dequantize op to the // original op. const string dequantized_output = AvailableArrayName(*model, weights + "_dequantized"); Array& dequantized_output_array = model->GetOrCreateArray(dequantized_output); dequantized_output_array.data_type = ArrayDataType::kFloat; // Connect up the new Dequantize op with the weights and original op. op->inputs[weights_index] = dequantized_output; dequantize_op->inputs = {weights}; dequantize_op->outputs = {dequantized_output}; return true; } } // namespace toco
{ "content_hash": "bce0c446c61e1097adb916dc5ffe7c45", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 85, "avg_line_length": 35.06315789473684, "alnum_prop": 0.7211047733413389, "repo_name": "dendisuhubdy/tensorflow", "id": "88ea0945e7dd15ba325d34ea3fdbf34ff7d91381", "size": "3999", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "tensorflow/contrib/lite/toco/graph_transformations/quantize_weights.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "9258" }, { "name": "C", "bytes": "304178" }, { "name": "C++", "bytes": "43473103" }, { "name": "CMake", "bytes": "202538" }, { "name": "Go", "bytes": "1148824" }, { "name": "HTML", "bytes": "4680032" }, { "name": "Java", "bytes": "755551" }, { "name": "Jupyter Notebook", "bytes": "2211560" }, { "name": "LLVM", "bytes": "6536" }, { "name": "Makefile", "bytes": "48603" }, { "name": "Objective-C", "bytes": "12456" }, { "name": "Objective-C++", "bytes": "94385" }, { "name": "PHP", "bytes": "2140" }, { "name": "Perl", "bytes": "7536" }, { "name": "PureBasic", "bytes": "25356" }, { "name": "Python", "bytes": "36820408" }, { "name": "Ruby", "bytes": "533" }, { "name": "Shell", "bytes": "428510" }, { "name": "Smarty", "bytes": "6870" } ], "symlink_target": "" }
int main(int argc, char **argv) { struct sockaddr_l2 loc_addr = { 0 }, rem_addr = { 0 }; char buf[1024] = { 0 }; int s, client, bytes_read; unsigned int opt = sizeof(rem_addr); // allocate socket s = socket(AF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP); // bind socket to port 0x1001 of the first available // bluetooth adapter loc_addr.l2_family = AF_BLUETOOTH; loc_addr.l2_bdaddr = *BDADDR_ANY; loc_addr.l2_psm = htobs(0x1001); bind(s, (struct sockaddr *)&loc_addr, sizeof(loc_addr)); // put socket into listening mode listen(s, 1); // accept one connection client = accept(s, (struct sockaddr *)&rem_addr, &opt); ba2str( &rem_addr.l2_bdaddr, buf ); fprintf(stderr, "accepted connection from %s\n", buf); // read data from the client memset(buf, 0, sizeof(buf)); bytes_read = recv(client, buf, sizeof(buf), 0); if( bytes_read > 0 ) { printf("received [%s]\n", buf); } // close connection close(client); close(s); return 0; }
{ "content_hash": "ad4a36ca1b12515f8ee31eff0afa4225", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 60, "avg_line_length": 27.225, "alnum_prop": 0.5821854912764004, "repo_name": "bearlin/study_bluetooth_socket", "id": "82c3832cbbe2d44927b4301bbd2dfb932f40a320", "size": "1240", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bluetooth/docs/btessentials/l2cap-server.c", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "104980" }, { "name": "C++", "bytes": "393082" }, { "name": "Groovy", "bytes": "100" }, { "name": "Python", "bytes": "17091" }, { "name": "Shell", "bytes": "23536" } ], "symlink_target": "" }
'''Get columns by name from SQL query''' # sqlite3 import sqlite3 db = sqlite3.connect(':memory:') db.row_factory = sqlite3.Row # psycopg2 import psycopg2 from psycopg2.extras import DictCursor db = psycopg2.connect('my-dbn-string') cur = db.cursor(cursor_factory=DictCursor) # Then cur.execute('select * from people') for row in cur: print(row['name'])
{ "content_hash": "36c74a8242098b66f0d386a8a0857026", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 42, "avg_line_length": 21.235294117647058, "alnum_prop": 0.7285318559556787, "repo_name": "tebeka/pythonwise", "id": "b11593a35df06409b877497022f719e131f10a16", "size": "361", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sql-col-by-name.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "419" }, { "name": "Assembly", "bytes": "130" }, { "name": "Awk", "bytes": "94" }, { "name": "C", "bytes": "3348" }, { "name": "CSS", "bytes": "7156" }, { "name": "Dockerfile", "bytes": "691" }, { "name": "Go", "bytes": "17160" }, { "name": "HTML", "bytes": "28603" }, { "name": "JavaScript", "bytes": "75641" }, { "name": "Jupyter Notebook", "bytes": "542450" }, { "name": "Makefile", "bytes": "2242" }, { "name": "Mako", "bytes": "795" }, { "name": "Python", "bytes": "1039734" }, { "name": "Shell", "bytes": "23126" }, { "name": "TeX", "bytes": "257" }, { "name": "Vim script", "bytes": "785" } ], "symlink_target": "" }
@protocol GMGridViewDataSource; @protocol GMGridViewActionDelegate; @protocol GMGridViewSortingDelegate; @protocol GMGridViewTransformationDelegate; @protocol GMGridViewLayoutStrategy; typedef enum { GMGridViewStylePush = 0, GMGridViewStyleSwap } GMGridViewStyle; ////////////////////////////////////////////////////////////// #pragma mark Interface GMGridView ////////////////////////////////////////////////////////////// @interface GMGridView : UIView <UIGestureRecognizerDelegate, UIScrollViewDelegate> { } // Delegates @property (nonatomic, gm_weak) NSObject<GMGridViewDataSource> *dataSource; // Required @property (nonatomic, gm_weak) NSObject<GMGridViewActionDelegate> *actionDelegate; // Optional - to get taps callback @property (nonatomic, gm_weak) NSObject<GMGridViewSortingDelegate> *sortingDelegate; // Optional - to enable sorting @property (nonatomic, gm_weak) NSObject<GMGridViewTransformationDelegate> *transformDelegate; // Optional - to enable fullsize mode // Layout Strategy @property (nonatomic, strong) id<GMGridViewLayoutStrategy> layoutStrategy; // Default is GMGridViewLayoutVerticalStrategy // Editing Mode @property (nonatomic, getter=isEditing) BOOL editing; // Default is NO - When set to YES, all gestures are disabled and delete buttons shows up on cells // Customizing Options @property (nonatomic, gm_weak) UIView *mainSuperView; // Default is self @property (nonatomic) GMGridViewStyle style; // Default is GMGridViewStyleSwap @property (nonatomic) NSInteger itemSpacing; // Default is 10 @property (nonatomic) BOOL centerGrid; // Default is YES @property (nonatomic) UIEdgeInsets minEdgeInsets; // Default is (5, 5, 5, 5) @property (nonatomic) CFTimeInterval minimumPressDuration; // Default is 0.2; if set to 0, the scrollView will not be scrollable @property (nonatomic) BOOL showFullSizeViewWithAlphaWhenTransforming; // Default is YES - not working right now @property (nonatomic) BOOL showsVerticalScrollIndicator; // Default is YES @property (nonatomic) BOOL showsHorizontalScrollIndicator; // Default is YES // Sorting Gestures @property (nonatomic, readonly) UIPanGestureRecognizer *sortingPanGesture; @property (nonatomic, readonly) UILongPressGestureRecognizer *sortingLongPressGesture; @property (nonatomic, readonly) UILongPressGestureRecognizer *editingModeLongPressGesture; // Moving gestures @property (nonatomic, readonly) UIPinchGestureRecognizer *pinchGesture; @property (nonatomic, readonly) UITapGestureRecognizer *tapGesture; @property (nonatomic, readonly) UITapGestureRecognizer *tapGestureEndEditing; @property (nonatomic, readonly) UIRotationGestureRecognizer *rotationGesture; @property (nonatomic, readonly) UIPanGestureRecognizer *panGesture; @property (nonatomic, readonly) UIScrollView *scrollView; // Messing with the scrollView can lead to unexpected behavior. Avoid changing any properties // or changing its delegate. You have been warned. @property (nonatomic,strong) NSNumber *inEditingMode; // Reusable cells - (GMGridViewCell *)dequeueReusableCell; // Should be called in GMGridView:cellForItemAtIndex: to reuse a cell // Cells - (GMGridViewCell *)cellForItemAtIndex:(NSInteger)position; // Might return nil if cell not loaded for the specific index // Actions - (void)reloadData; - (void)insertObjectAtIndex:(NSInteger)index; - (void)removeObjectAtIndex:(NSInteger)index; - (void)reloadObjectAtIndex:(NSInteger)index; - (void)swapObjectAtIndex:(NSInteger)index1 withObjectAtIndex:(NSInteger)index2; - (void)scrollToObjectAtIndex:(NSInteger)index animated:(BOOL)animated; @end ////////////////////////////////////////////////////////////// #pragma mark Protocol GMGridViewDataSource ////////////////////////////////////////////////////////////// @protocol GMGridViewDataSource <NSObject> @optional // Populating subview items - (NSInteger)numberOfItemsInGMGridView:(GMGridView *)gridView; - (CGSize)sizeForItemsInGMGridView:(GMGridView *)gridView; - (GMGridViewCell *)GMGridView:(GMGridView *)gridView cellForItemAtIndex:(NSInteger)index; // Scroll delegate methods - (void)GMGridView:(GMGridView *)gridView didScrollToItemAtIndex:(NSInteger)index; - (void)GMGridView:(GMGridView *)gridView didScrollToPoint:(CGPoint)point ofWidth:(float)width; // Required to enable editing mode - (void)GMGridView:(GMGridView *)gridView deleteItemAtIndex:(NSInteger)index; @end ////////////////////////////////////////////////////////////// #pragma mark Protocol GMGridViewActionDelegate ////////////////////////////////////////////////////////////// @protocol GMGridViewActionDelegate <NSObject> @optional - (void)GMGridView:(GMGridView *)gridView didTapOnItemAtIndex:(NSInteger)position location:(CGPoint)location; - (void)GMGridView:(GMGridView *)gridView didDoubleTapOnItemAtIndex:(NSInteger)position location:(CGPoint)location; @end ////////////////////////////////////////////////////////////// #pragma mark Protocol GMGridViewSortingDelegate ////////////////////////////////////////////////////////////// @protocol GMGridViewSortingDelegate <NSObject> @optional // Item moved - right place to update the data structure - (void)GMGridView:(GMGridView *)gridView moveItemAtIndex:(NSInteger)oldIndex toIndex:(NSInteger)newIndex; - (void)GMGridView:(GMGridView *)gridView exchangeItemAtIndex:(NSInteger)index1 withItemAtIndex:(NSInteger)index2; // Sorting started/ended - indexes are not specified on purpose (not the right place to update data structure) - (void)GMGridView:(GMGridView *)gridView didStartMovingCell:(GMGridViewCell *)cell; - (void)GMGridView:(GMGridView *)gridView didEndMovingCell:(GMGridViewCell *)cell; // Enable/Disable the shaking behavior of an item being moved - (BOOL)GMGridView:(GMGridView *)gridView shouldAllowShakingBehaviorWhenMovingCell:(GMGridViewCell *)view atIndex:(NSInteger)index; @end ////////////////////////////////////////////////////////////// #pragma mark Protocol GMGridViewTransformationDelegate ////////////////////////////////////////////////////////////// @protocol GMGridViewTransformationDelegate <NSObject> @optional // Fullsize - (CGSize)GMGridView:(GMGridView *)gridView sizeInFullSizeForCell:(GMGridViewCell *)cell atIndex:(NSInteger)index; - (UIView *)GMGridView:(GMGridView *)gridView fullSizeViewForCell:(GMGridViewCell *)cell atIndex:(NSInteger)index; // Transformation (pinch, drag, rotate) of the item - (void)GMGridView:(GMGridView *)gridView didStartTransformingCell:(GMGridViewCell *)cell; - (void)GMGridView:(GMGridView *)gridView didEnterFullSizeForCell:(GMGridViewCell *)cell; - (void)GMGridView:(GMGridView *)gridView didEndTransformingCell:(GMGridViewCell *)cell; @end
{ "content_hash": "b44c9a7c3e5778165955b9b84e8bf2dd", "timestamp": "", "source": "github", "line_count": 150, "max_line_length": 163, "avg_line_length": 45.973333333333336, "alnum_prop": 0.7054814385150812, "repo_name": "111minutes/GMGridView-CSFork", "id": "5ee4fddc3692bca75b0a0c771251801fb687250f", "size": "8284", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "GMGridView/API/GMGridView.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1795" }, { "name": "Objective-C", "bytes": "163939" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">sample2</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> </resources>
{ "content_hash": "881c5a8d998495607f0a98aefa9756ac", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 52, "avg_line_length": 27.125, "alnum_prop": 0.6728110599078341, "repo_name": "rahulpareek2440/AndroidPrograms", "id": "d244be14c24fe75ec911cb0c4529d792522cf704", "size": "217", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sample2/res/values/strings.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1726" }, { "name": "Groff", "bytes": "496" }, { "name": "HTML", "bytes": "104173" }, { "name": "Java", "bytes": "366083" } ], "symlink_target": "" }
// +k8s:defaulter-gen=TypeMeta // +groupName=kubeadm.k8s.io // +k8s:deepcopy-gen=package // +k8s:conversion-gen=k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm // Package v1beta1 defines the v1beta1 version of the kubeadm config file format, that is a big step // forward the objective of graduate kubeadm config to beta. // // //TODO add notes about big changes introduced by this release // // Migration from old kubeadm config versions // // Please convert your v1alpha3 configuration files to v1beta1 using the kubeadm config migrate command of kubeadm v1.13.x // (conversion from older releases of kubeadm config files requires older release of kubeadm as well e.g. // kubeadm v1.11 should be used to migrate v1alpha1 to v1alpha2; kubeadm v1.12 should be used to translate v1alpha2 to v1alpha3) // // Nevertheless, kubeadm v1.13.x will support reading from v1alpha3 version of the kubeadm config file format, but this support // will be dropped in the v1.14 release. // // Basics // // The preferred way to configure kubeadm is to pass an YAML configuration file with the --config option. Some of the // configuration options defined in the kubeadm config file are also available as command line flags, but only // the most common/simple use case are supported with this approach. // // A kubeadm config file could contain multiple configuration types separated using three dashes (“---”). // // The kubeadm config print-defaults command print the default values for all the kubeadm supported configuration types. // // apiVersion: kubeadm.k8s.io/v1beta1 // kind: InitConfiguration // ... // --- // apiVersion: kubeadm.k8s.io/v1beta1 // kind: ClusterConfiguration // ... // --- // apiVersion: kubelet.config.k8s.io/v1beta1 // kind: KubeletConfiguration // ... // --- // apiVersion: kubeproxy.config.k8s.io/v1alpha1 // kind: KubeProxyConfiguration // ... // --- // apiVersion: kubeadm.k8s.io/v1beta1 // kind: JoinConfiguration // ... // // The list of configuration types that must be included in a configuration file depends by the action you are // performing (init or join) and by the configuration options you are going to use (defaults or advanced customization). // // If some configuration types are not provided, or provided only partially, kubeadm will use default values; defaults // provided by kubeadm includes also enforcing consistency of values across components when required (e.g. // cluster-cidr flag on controller manager and clusterCIDR on kube-proxy). // // Users are always allowed to override default values, with the only exception of a small subset of setting with // relevance for security (e.g. enforce authorization-mode Node and RBAC on api server) // // If the user provides a configuration types that is not expected for the action you are performing, kubeadm will // ignore those types and print a warning. // // Kubeadm init configuration types // // When executing kubeadm init with the --config option, the following configuration types could be used: // InitConfiguration, ClusterConfiguration, KubeProxyConfiguration, KubeletConfiguration, but only one // between InitConfiguration and ClusterConfiguration is mandatory. // // apiVersion: kubeadm.k8s.io/v1beta1 // kind: InitConfiguration // bootstrapTokens: // ... // nodeRegistration: // ... // apiEndpoint: // ... // // The InitConfiguration type should be used to configure runtime settings, that in case of kubeadm init // are the configuration of the bootstrap token and all the setting which are specific to the node where kubeadm // is executed, including: // // - NodeRegistration, that holds fields that relate to registering the new node to the cluster; // use it to customize the node name, the CRI socket to use or any other settings that should apply to this // node only (e.g. the node ip). // // - APIEndpoint, that represents the endpoint of the instance of the API server to be deployed on this node; // use it e.g. to customize the API server advertise address. // // apiVersion: kubeadm.k8s.io/v1beta1 // kind: ClusterConfiguration // networking: // ... // etcd: // ... // apiServerExtraArgs: // ... // APIServerExtraVolumes: // ... // ... // // The ClusterConfiguration type should be used to configure cluster-wide settings, // including settings for: // // - Networking, that holds configuration for the networking topology of the cluster; use it e.g. to customize // node subnet or services subnet. // // - Etcd configurations; use it e.g. to customize the local etcd or to configure the API server // for using an external etcd cluster. // // - kube-apiserver, kube-scheduler, kube-controller-manager configurations; use it to customize control-plane // components by adding customized setting or overriding kubeadm default settings. // // apiVersion: kubeproxy.config.k8s.io/v1alpha1 // kind: KubeProxyConfiguration // ... // // The KubeProxyConfiguration type should be used to change the configuration passed to kube-proxy instances deployed // in the cluster. If this object is not provided or provided only partially, kubeadm applies defaults. // // See https://kubernetes.io/docs/reference/command-line-tools-reference/kube-proxy/ or https://godoc.org/k8s.io/kube-proxy/config/v1alpha1#KubeProxyConfiguration // for kube proxy official documentation. // // apiVersion: kubelet.config.k8s.io/v1beta1 // kind: KubeletConfiguration // ... // // The KubeletConfiguration type should be used to change the configurations that will be passed to all kubelet instances // deployed in the cluster. If this object is not provided or provided only partially, kubeadm applies defaults. // // See https://kubernetes.io/docs/reference/command-line-tools-reference/kubelet/ or https://godoc.org/k8s.io/kubelet/config/v1beta1#KubeletConfiguration // for kube proxy official documentation. // // Here is a fully populated example of a single YAML file containing multiple // configuration types to be used during a `kubeadm init` run. // // apiVersion: kubeadm.k8s.io/v1beta1 // kind: InitConfiguration // bootstrapTokens: // - token: "9a08jv.c0izixklcxtmnze7" // description: "kubeadm bootstrap token" // ttl: "24h" // - token: "783bde.3f89s0fje9f38fhf" // description: "another bootstrap token" // usages: // - signing // groups: // - system:anonymous // nodeRegistration: // name: "ec2-10-100-0-1" // criSocket: "/var/run/dockershim.sock" // taints: // - key: "kubeadmNode" // value: "master" // effect: "NoSchedule" // kubeletExtraArgs: // cgroupDriver: "cgroupfs" // apiEndpoint: // advertiseAddress: "10.100.0.1" // bindPort: 6443 // --- // apiVersion: kubeadm.k8s.io/v1beta1 // kind: ClusterConfiguration // etcd: // # one of local or external // local: // image: "k8s.gcr.io/etcd-amd64:3.2.18" // dataDir: "/var/lib/etcd" // extraArgs: // listen-client-urls: "http://10.100.0.1:2379" // serverCertSANs: // - "ec2-10-100-0-1.compute-1.amazonaws.com" // peerCertSANs: // - "10.100.0.1" // external: // endpoints: // - "10.100.0.1:2379" // - "10.100.0.2:2379" // caFile: "/etcd/kubernetes/pki/etcd/etcd-ca.crt" // certFile: "/etcd/kubernetes/pki/etcd/etcd.crt" // certKey: "/etcd/kubernetes/pki/etcd/etcd.key" // networking: // serviceSubnet: "10.96.0.0/12" // podSubnet: "10.100.0.1/24" // dnsDomain: "cluster.local" // kubernetesVersion: "v1.12.0" // controlPlaneEndpoint: "10.100.0.1:6443" // apiServer: // extraArgs: // authorization-mode: "Node,RBAC" // extraVolumes: // - name: "some-volume" // hostPath: "/etc/some-path" // mountPath: "/etc/some-pod-path" // readOnly: false // pathType: File // certSANs: // - "10.100.1.1" // - "ec2-10-100-0-1.compute-1.amazonaws.com" // timeoutForControlPlane: 4m0s // controllerManager: // extraArgs: // node-cidr-mask-size: 20 // extraVolumes: // - name: "some-volume" // hostPath: "/etc/some-path" // mountPath: "/etc/some-pod-path" // readOnly: false // pathType: File // scheduler: // extraArgs: // address: "10.100.0.1" // extraVolumes: // - name: "some-volume" // hostPath: "/etc/some-path" // mountPath: "/etc/some-pod-path" // readOnly: false // pathType: File // certificatesDir: "/etc/kubernetes/pki" // imageRepository: "k8s.gcr.io" // unifiedControlPlaneImage: "k8s.gcr.io/controlplane:v1.12.0" // auditPolicy: // # https://kubernetes.io/docs/tasks/debug-application-cluster/audit/#audit-policy // path: "/var/log/audit/audit.json" // logDir: "/var/log/audit" // logMaxAge: 7 # in days // featureGates: // selfhosting: false // clusterName: "example-cluster" // // Kubeadm join configuration types // // When executing kubeadm join with the --config option, the JoinConfiguration type should be provided. // // apiVersion: kubeadm.k8s.io/v1beta1 // kind: JoinConfiguration // ... // // The JoinConfiguration type should be used to configure runtime settings, that in case of kubeadm join // are the discovery method used for accessing the cluster info and all the setting which are specific // to the node where kubeadm is executed, including: // // - NodeRegistration, that holds fields that relate to registering the new node to the cluster; // use it to customize the node name, the CRI socket to use or any other settings that should apply to this // node only (e.g. the node ip). // // - APIEndpoint, that represents the endpoint of the instance of the API server to be eventually deployed on this node. // package v1beta1 // import "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/v1beta1" //TODO: The BootstrapTokenString object should move out to either k8s.io/client-go or k8s.io/api in the future //(probably as part of Bootstrap Tokens going GA). It should not be staged under the kubeadm API as it is now.
{ "content_hash": "7cf4dccaec8f4f23d36c7e3075600df5", "timestamp": "", "source": "github", "line_count": 253, "max_line_length": 162, "avg_line_length": 39.84189723320158, "alnum_prop": 0.7003968253968254, "repo_name": "clairew/kubernetes", "id": "e9c3843d93c9af9e73c660f6743f8cc7105438bb", "size": "10653", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "cmd/kubeadm/app/apis/kubeadm/v1beta1/doc.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2525" }, { "name": "Go", "bytes": "44604851" }, { "name": "HTML", "bytes": "2714804" }, { "name": "Makefile", "bytes": "74515" }, { "name": "Nginx", "bytes": "595" }, { "name": "PowerShell", "bytes": "4261" }, { "name": "Protocol Buffer", "bytes": "515347" }, { "name": "Python", "bytes": "2308158" }, { "name": "Ruby", "bytes": "1591" }, { "name": "SaltStack", "bytes": "52331" }, { "name": "Shell", "bytes": "1609888" } ], "symlink_target": "" }
from disassemblers.libdisassemble.opcode86 import regs from copy import deepcopy legal_integers = ['rdi', 'rsi', 'rdx', 'rcx', 'r8', 'r9'] legal_sse = ['xmm0', 'xmm1', 'xmm2', 'xmm3', 'xmm4', 'xmm5', 'xmm6', 'xmm7'] legal_other = ['rax'] def reg_normalize(reg): ''' Normalize a register to a form independent of its size. ''' idx = list(map(lambda x: x[0], regs)).index(reg) return regs[idx&0xF][0] class Params: ''' A data structure that holds the current list of parameters used and is able to let you know when it ends using some heuristics. ''' def __init__(self): self.memory = [] self.integers = [] self.sse = [] self.other = [] self.args = [] def add(self, reg, arg): ''' Try to add a register to the list of params. If its the next legal register in a list of parameters, it's added and True is returned. If it isn't, False is returned so that the function can be wrapped. ''' arg = deepcopy(arg) if 'w' in arg: arg['w'] = False arg['r'] = True try: param = reg_normalize(reg) except ValueError: return False try: if legal_integers[len(self.integers)] == param: self.integers.append(reg) self.args.append(arg) return True elif legal_sse[len(self.sse)] == reg: #fix normalization here self.sse.append(reg) self.args.append(arg) return True elif legal_other[len(self.other)] == param: self.other.append(reg) return True else: return False except IndexError: return False def fold(cfg, symbols): ''' Fold as many function calls as its possible, infering arguments lists along the way. ''' for block, depth in cfg.iterblocks(): inside_call = False for n, line in enumerate(reversed(block)): if inside_call: if 'dest' not in line['ins']: continue dest = line['ins']['dest'] param = dest['value'] if call_params.add(param, dest): pass else: apply_ins = {'op': 'apply', 'function': function_name, 'args': call_params.args} eax = {'value': 'eax', 'repr': 'eax', 'r': False, 'w': True} mov_ins = {'op': 'mov', 'src': apply_ins, 'dest': eax} block[len(block)-call_n-1]['ins'] = mov_ins inside_call = False call_params = None if line['ins']['op'] == 'call': inside_call = True call_n = n call_params = Params() function_name = 'unknown_function' if 'repr' in line['ins']['dest']: if type(line['ins']['dest']['repr']) == int: addr = line['loc']+line['length']+line['ins']['dest']['repr'] if addr in symbols: function_name = symbols[addr]
{ "content_hash": "e71d6c13d99c45458564c2ff7fc62909", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 100, "avg_line_length": 35.365591397849464, "alnum_prop": 0.4843417452113104, "repo_name": "drx/ocd", "id": "9bdf7391faee11d28a56157d67d40566ac4a3762", "size": "3289", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/function_calls.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "3306" }, { "name": "Makefile", "bytes": "159" }, { "name": "Python", "bytes": "310636" } ], "symlink_target": "" }
// // STRootViewController.m // Stacks // // Created by Max Luzuriaga on 6/21/11. // Copyright 2011 __MyCompanyName__. All rights reserved. // #import "STRootViewController.h" #import <QuartzCore/QuartzCore.h> #import "STStackDetailViewController.h" #import "StacksAppDelegate.h" #import "STStack.h" #import "STCard.h" #import "STStackCell.h" #import "STButton.h" #import "STEmptyDataSetView.h" #define NEW_STACK_BUTTON_TAG 100 @implementation STRootViewController @synthesize fetchedResultsController = __fetchedResultsController, managedObjectContext = __managedObjectContext, detailViewController = _detailViewController; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { self.title = NSLocalizedString(@"Stacks", nil); id delegate = [[UIApplication sharedApplication] delegate]; self.managedObjectContext = [delegate managedObjectContext]; } return self; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } #pragma mark - View lifecycle - (void)viewDidLoad { [super viewDidLoad]; self.tableView.indicatorStyle = UIScrollViewIndicatorStyleWhite; self.tableView.backgroundColor = [UIColor clearColor]; self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone; self.tableView.rowHeight = 65; self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 8)]; UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 67)]; STButton *button = [[STButton alloc] initWithFrame:CGRectMake(15, 15, 290, 44) buttonColor:STButtonColorBlue disclosureImageEnabled:NO]; [button setTitle:NSLocalizedString(@"+ Add a new Stack", nil) forState:UIControlStateNormal]; [button addTarget:self action:@selector(addNewStack) forControlEvents:UIControlEventTouchUpInside]; [button setEnabled:NO animated:NO]; button.tag = NEW_STACK_BUTTON_TAG; [headerView addSubview:button]; self.tableView.tableHeaderView = headerView; self.navigationItem.rightBarButtonItem = self.editButtonItem; id delegate = [[UIApplication sharedApplication] delegate]; NSArray *toolbarItems = [[NSArray alloc] initWithObjects: [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addNewStack)], [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"settingsIcon"] style:UIBarButtonItemStylePlain target:delegate action:@selector(showSettings)], nil]; [self setToolbarItems:toolbarItems animated:YES]; NSString *text = NSLocalizedString(@"Tap either button to add your first Stack.", nil); emptyDataSetView = [[STEmptyDataSetView alloc] initWithFrame:CGRectMake(0, 0, 320, 261) text:text style:STEmptyDataSetViewStyleOneButton]; } - (void)setEditing:(BOOL)editing animated:(BOOL)animated { [super setEditing:editing animated:animated]; STButton *button = (STButton *)[self.tableView.tableHeaderView viewWithTag:NEW_STACK_BUTTON_TAG]; [button setEnabled:!editing animated:YES]; if (editing) [self.navigationItem.rightBarButtonItem setBackgroundImage:[[UIImage imageNamed:@"barButtonItemHighlightedBackground"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 6, 0, 6)] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault]; else [self.navigationItem.rightBarButtonItem setBackgroundImage:[[UIImage imageNamed:@"barButtonItemBackground"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 6, 0, 6)] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault]; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationPortrait); } #pragma mark - UITableViewDelegate and UITableViewDataSource // Customize the number of sections in the table view. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return [[self.fetchedResultsController sections] count]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section]; return [sectionInfo numberOfObjects]; } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; STStackCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) cell = [[STStackCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; // Configure the cell. [self configureCell:cell atIndexPath:indexPath]; return cell; } // Override to support conditional editing of the table view. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { return YES; } - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete the managed object for the given index path NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext]; [context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]]; // Save the context. NSError *error = nil; if (![context save:&error]) { /* Replace this implementation with code to handle the error appropriately. abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button. */ NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } } } - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { // The table view should not be re-orderable. return NO; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { if (!self.detailViewController) { self.detailViewController = [[STStackDetailViewController alloc] initWithNibName:@"STStackDetailViewController" bundle:nil]; } STStack *selectedStack = (STStack *)[[self fetchedResultsController] objectAtIndexPath:indexPath]; _detailViewController.stack = selectedStack; [self.navigationController pushViewController:_detailViewController animated:YES]; } #pragma mark - Fetched results controller - (NSFetchedResultsController *)fetchedResultsController { if (__fetchedResultsController != nil) { return __fetchedResultsController; } /* Set up the fetched results controller. */ // Create the fetch request for the entity. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; // Edit the entity name as appropriate. NSEntityDescription *entity = [NSEntityDescription entityForName:@"STStack" inManagedObjectContext:self.managedObjectContext]; [fetchRequest setEntity:entity]; // Set the batch size to a suitable number. [fetchRequest setFetchBatchSize:20]; // Edit the sort key as appropriate. NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"createdDate" ascending:NO]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; // Edit the section name key path and cache name if appropriate. // nil for section name key path means "no sections". NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"]; aFetchedResultsController.delegate = self; self.fetchedResultsController = aFetchedResultsController; NSError *error = nil; if (![self.fetchedResultsController performFetch:&error]) { /* Replace this implementation with code to handle the error appropriately. abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button. */ NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } return __fetchedResultsController; } - (void)persistentStoreAdded { // Now that the persistent store has been added asynchronously, perform the fetch on the fetchedResults controller NSError *error = nil; if (![self.fetchedResultsController performFetch:&error]) { /* Replace this implementation with code to handle the error appropriately. abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button. */ NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } [self.tableView reloadData]; STButton *button = (STButton *)[self.tableView.tableHeaderView viewWithTag:NEW_STACK_BUTTON_TAG]; [button setEnabled:YES animated:YES]; [self presentEmptyDataSetViewIfNeeded]; } - (void)controllerWillChangeContent:(NSFetchedResultsController *)controller { [self.tableView beginUpdates]; } - (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type { switch(type) { case NSFetchedResultsChangeInsert: [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]; break; case NSFetchedResultsChangeDelete: [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]; break; } } - (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath { UITableView *tableView = self.tableView; switch(type) { case NSFetchedResultsChangeInsert: [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; break; case NSFetchedResultsChangeDelete: [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; break; case NSFetchedResultsChangeUpdate: [self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath]; break; case NSFetchedResultsChangeMove: [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]withRowAnimation:UITableViewRowAnimationFade]; break; } id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:0]; if ([sectionInfo numberOfObjects] == 0) { [self setEditing:NO animated:YES]; } } - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller { [self.tableView endUpdates]; [self presentEmptyDataSetViewIfNeeded]; } /* // Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed. - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller { // In the simplest, most efficient, case, reload the table view. [self.tableView reloadData]; } */ - (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath { STStack *stack = (STStack *)[self.fetchedResultsController objectAtIndexPath:indexPath]; cell.textLabel.text = stack.name; } #pragma mark - STEmptyDataSetView - (void)presentEmptyDataSetViewIfNeeded { id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:0]; BOOL hasStacks = [sectionInfo numberOfObjects] != 0; BOOL shown = emptyDataSetView.superview != nil; StacksAppDelegate *delegate = (StacksAppDelegate *)[[UIApplication sharedApplication] delegate]; if (!hasStacks && !shown) { emptyDataSetView.alpha = 0.0; [self.view addSubview:emptyDataSetView]; [self.view sendSubviewToBack:emptyDataSetView]; [UIView animateWithDuration:0.5 animations:^(void) { emptyDataSetView.alpha = 1.0; }]; [delegate showToolbarGlow]; [delegate adjustToolbarGlowForYOffset:self.tableView.contentOffset.y]; } else if (hasStacks && shown) { [UIView animateWithDuration:0.5 animations:^(void) { emptyDataSetView.alpha = 0.0; }]; [emptyDataSetView removeFromSuperview]; [delegate hideToolbarGlow]; } } - (void)scrollViewDidScroll:(UIScrollView *)scrollView { if (emptyDataSetView.superview != nil) { StacksAppDelegate *delegate = (StacksAppDelegate *)[[UIApplication sharedApplication] delegate]; [delegate adjustToolbarGlowForYOffset:scrollView.contentOffset.y]; } } #pragma mark - Add new Stack - (void)addNewStack { STNewStackViewController *newStackViewController = [[STNewStackViewController alloc] init]; newStackViewController.delegate = self; UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:newStackViewController]; [self presentModalViewController:navigationController animated:YES]; } - (void)newStackViewController:(STNewStackViewController *)newStackViewController didSaveWithName:(NSString *)name { // Create a new instance of the entity managed by the fetched results controller. // NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext]; STStack *newStack = [NSEntityDescription insertNewObjectForEntityForName:@"STStack" inManagedObjectContext:self.managedObjectContext]; newStack.createdDate = [NSDate date]; newStack.name = name; // Save the context. NSError *error = nil; if (![self.managedObjectContext save:&error]) { /* Replace this implementation with code to handle the error appropriately. abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button. */ NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } if (!self.detailViewController) { self.detailViewController = [[STStackDetailViewController alloc] initWithNibName:@"STStackDetailViewController" bundle:nil]; } STStack *selectedStack = (STStack *)[[self fetchedResultsController] objectAtIndexPath:[self.fetchedResultsController indexPathForObject:newStack]]; _detailViewController.stack = selectedStack; [self.navigationController pushViewController:_detailViewController animated:YES]; } @end
{ "content_hash": "973cef73096287720fd13682ac00b8ce", "timestamp": "", "source": "github", "line_count": 404, "max_line_length": 357, "avg_line_length": 41.881188118811885, "alnum_prop": 0.7314420803782505, "repo_name": "maxluzuriaga/Stacks", "id": "3d023396769bb08ba8c141e4d7e0d6627ee9be85", "size": "16920", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Stacks/Classes/STRootViewController.m", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
namespace IO { class Accelerometer { public: API virtual ~Accelerometer() = default; typedef Toast::Memory::Shared::IO::AccelRange Range; API virtual void set_range(Range range) = 0; API virtual float x() = 0; API virtual float y() = 0; API virtual float z() = 0; }; class BuiltInAccelerometer : public Accelerometer { public: API BuiltInAccelerometer(); API void set_range(Range range) override; API float x() override; API float y() override; API float z() override; }; }
{ "content_hash": "c4f1746a0074eb842a5f4eda091306b3", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 54, "avg_line_length": 22.90909090909091, "alnum_prop": 0.6884920634920635, "repo_name": "JacisNonsense/ToastCPP", "id": "52c4192ae8f3a1657d3c30225ac513b61263c3d2", "size": "576", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Toast-Core/include/io/accel.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "136" }, { "name": "C", "bytes": "459953" }, { "name": "C++", "bytes": "358330" }, { "name": "CSS", "bytes": "1721" }, { "name": "HTML", "bytes": "8530" }, { "name": "JavaScript", "bytes": "36504" } ], "symlink_target": "" }
@implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // // Override point for customization after application launch. // self.window.backgroundColor = [UIColor whiteColor]; // [self.window makeKeyAndVisible]; return YES; } - (void)applicationWillResignActive:(UIApplication *)application { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } - (void)applicationDidEnterBackground:(UIApplication *)application { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } - (void)applicationWillEnterForeground:(UIApplication *)application { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } - (void)applicationDidBecomeActive:(UIApplication *)application { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } - (void)applicationWillTerminate:(UIApplication *)application { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } @end
{ "content_hash": "e1829319d31af78e4aa774c13796923c", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 281, "avg_line_length": 51.87179487179487, "alnum_prop": 0.7800296589223925, "repo_name": "kevinkwon/KKUIKitStudy", "id": "54838b0860946d12c34241732d87b7d33e1ca9f8", "size": "2183", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "KKUIKit/KKUIKit/AppDelegate.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "25819" } ], "symlink_target": "" }
package org.apache.isis.viewer.restfulobjects.tck; import org.junit.Test; import org.apache.isis.viewer.restfulobjects.applib.Rel; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; public class RelTest_matches { @Test public void whenDoes() throws Exception { assertThat(Rel.ACTION.matches(Rel.ACTION), is(true)); } @Test public void whenDoesNot() throws Exception { assertThat(Rel.ACTION.matches(Rel.ACTION_PARAM), is(false)); } @Test public void whenMatchesOnStr() throws Exception { assertThat(Rel.ACTION.matches(Rel.ACTION.getName()), is(true)); } @Test public void whenMatchesOnStrWithParams() throws Exception { assertThat(Rel.ACTION.matches(Rel.ACTION.andParam("foo", "bar")), is(true)); } }
{ "content_hash": "4c142f4b39ea372bb59939f3e64b8831", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 84, "avg_line_length": 24.90909090909091, "alnum_prop": 0.694647201946472, "repo_name": "howepeng/isis", "id": "72808e422303a9e943b3907e536198bf5a8968a3", "size": "1647", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "mothballed/tck/tck-viewer-restfulobjects/src/test/java/org/apache/isis/viewer/restfulobjects/tck/RelTest_matches.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "169367" }, { "name": "Cucumber", "bytes": "8162" }, { "name": "Groovy", "bytes": "28126" }, { "name": "HTML", "bytes": "601255" }, { "name": "Java", "bytes": "17808958" }, { "name": "JavaScript", "bytes": "118425" }, { "name": "Shell", "bytes": "12774" }, { "name": "XSLT", "bytes": "72290" } ], "symlink_target": "" }
require('path-compat') -- imports local class = require("pl.class") local Set = require("pl.Set") local test = require("pl.test") local pretty = require("pl.pretty") local Util = require("Util") -- module local Data = class() function Data:_init(categories, examples) self.categories = categories or {} self.examples = examples or {} self:check() end function Data:check() -- Check examples against declared categories local cats = Set(self.categories) for _, v in ipairs(self.examples) do if not (Set{v[1]} < cats) then error("Example category '" .. v[1] .. "' not declared") end end -- Categories must be unique assert(Set.len(Set(self.categories)) == table.getn(self.categories)) end function Data:write() return pretty.write(self) end function Data:read(t) if not Util.is_table(t) then t = assert(pretty.read(t)) end self.categories = t.categories self.examples = t.examples end function Data:__tostring() return self:write() end -- tests local function tests() -- Data local d = Data() d:check() d:read({categories = {"dog", "cat"}, examples = {{"dog", 1}, {"cat", 2}}}) d:check() d:read({categories = {"dog", "cat"}, examples = {{"flog", 1}, {"cat", 2}}}) test.asserteq(pcall(function() d:check() end), false) d:read({categories = {"dog", "cat", "dog"}, examples = {{"dog", 1}, {"cat", 2}}}) test.asserteq(pcall(function() d:check() end), false) end local m = {} m.Data = Data m.tests = tests return m
{ "content_hash": "ee602f3457f807781bbdc1b3f21cc3e4", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 83, "avg_line_length": 21, "alnum_prop": 0.6411804158283032, "repo_name": "henfredemars/random-forest", "id": "f31d52fffee5b8ee745f3acd1251b4f032181419", "size": "1501", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Data.lua", "mode": "33188", "license": "mit", "language": [ { "name": "Lua", "bytes": "16371" } ], "symlink_target": "" }
Requests for PHP ================ [![Build Status](https://travis-ci.org/rmccue/Requests.svg?branch=master)](https://travis-ci.org/rmccue/Requests) [![codecov.io](http://codecov.io/github/rmccue/Requests/coverage.svg?branch=master)](http://codecov.io/github/rmccue/Requests?branch=master) Requests is a HTTP library written in PHP, for human beings. It is roughly based on the API from the excellent [Requests Python library](http://python-requests.org/). Requests is [ISC Licensed](https://github.com/rmccue/Requests/blob/master/LICENSE) (similar to the new BSD license) and has no dependencies, except for PHP 5.2+. Despite PHP's use as a language for the web, its tools for sending HTTP requests are severely lacking. cURL has an [interesting API](http://php.net/manual/en/function.curl-setopt.php), to say the least, and you can't always rely on it being available. Sockets provide only low level access, and require you to build most of the HTTP response parsing yourself. We all have better things to do. That's why Requests was born. ```php $headers = array('Accept' => 'application/json'); $options = array('auth' => array('user', 'pass')); $request = Requests::get('https://api.github.com/gists', $headers, $options); var_dump($request->status_code); // int(200) var_dump($request->headers['content-type']); // string(31) "application/json; charset=utf-8" var_dump($request->body); // string(26891) "[...]" ``` Requests allows you to send **HEAD**, **GET**, **POST**, **PUT**, **DELETE**, and **PATCH** HTTP requests. You can add headers, form data, multipart files, and parameters with simple arrays, and access the response data in the same way. Requests uses cURL and fsockopen, depending on what your system has available, but abstracts all the nasty stuff out of your way, providing a consistent API. Features -------- - International Domains and URLs - Browser-style SSL Verification - Basic/Digest Authentication - Automatic Decompression - Connection Timeouts Installation ------------ ### Install with Composer If you're using [Composer](https://github.com/composer/composer) to manage dependencies, you can add Requests with it. ```sh composer require rmccue/requests ``` or { "require": { "rmccue/requests": ">=1.0" } } ### Install source from GitHub To install the source code: $ git clone git://github.com/rmccue/Requests.git And include it in your scripts: require_once '/path/to/Requests/library/Requests.php'; You'll probably also want to register an autoloader: Requests::register_autoloader(); ### Install source from zip/tarball Alternatively, you can fetch a [tarball][] or [zipball][]: $ curl -L https://github.com/rmccue/Requests/tarball/master | tar xzv (or) $ wget https://github.com/rmccue/Requests/tarball/master -O - | tar xzv [tarball]: https://github.com/rmccue/Requests/tarball/master [zipball]: https://github.com/rmccue/Requests/zipball/master ### Using a Class Loader If you're using a class loader (e.g., [Symfony Class Loader][]) for [PSR-0][]-style class loading: $loader->registerPrefix('Requests', 'path/to/vendor/Requests/library'); [Symfony Class Loader]: https://github.com/symfony/ClassLoader [PSR-0]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md Documentation ------------- The best place to start is our [prose-based documentation][], which will guide you through using Requests. After that, take a look at [the documentation for `Requests::request()`][request_method], where all the parameters are fully documented. Requests is [100% documented with PHPDoc](http://requests.ryanmccue.info/api/). If you find any problems with it, [create a new issue](https://github.com/rmccue/Requests/issues/new)! [prose-based documentation]: https://github.com/rmccue/Requests/blob/master/docs/README.md [request_method]: http://requests.ryanmccue.info/api/class-Requests.html#_request Testing ------- Requests strives to have 100% code-coverage of the library with an extensive set of tests. We're not quite there yet, but [we're getting close][codecov]. [codecov]: http://codecov.io/github/rmccue/Requests To run the test suite, first check that you have the [PHP JSON extension ](http://php.net/manual/en/book.json.php) enabled. Then simply: $ cd tests $ phpunit If you'd like to run a single set of tests, specify just the name: $ phpunit Transport/cURL Contribute ---------- 1. Check for open issues or open a new issue for a feature request or a bug 2. Fork [the repository][] on Github to start making your changes to the `master` branch (or branch off of it) 3. Write a test which shows that the bug was fixed or that the feature works as expected 4. Send a pull request and bug me until I merge it [the repository]: https://github.com/rmccue/Requests
{ "content_hash": "f9eaa9cdecbb5f4f45e562faf9cf2893", "timestamp": "", "source": "github", "line_count": 152, "max_line_length": 140, "avg_line_length": 32.96052631578947, "alnum_prop": 0.700998003992016, "repo_name": "mwendakith/eid_dashboard", "id": "c4455394e6cadddf0348461d42790d5fd29c13fe", "size": "5010", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/libraries/requests/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "95311" }, { "name": "HTML", "bytes": "8177944" }, { "name": "Hack", "bytes": "758" }, { "name": "JavaScript", "bytes": "5135927" }, { "name": "PHP", "bytes": "6151777" }, { "name": "PLpgSQL", "bytes": "47573" }, { "name": "SQLPL", "bytes": "446896" } ], "symlink_target": "" }
import functools import logbook import math import numpy as np import numpy.linalg as la from six import iteritems import pandas as pd from . import risk from . risk import ( alpha, check_entry, downside_risk, information_ratio, sharpe_ratio, sortino_ratio, ) log = logbook.Logger('Risk Period') choose_treasury = functools.partial(risk.choose_treasury, risk.select_treasury_duration) class RiskMetricsPeriod(object): def __init__(self, start_date, end_date, returns, env, benchmark_returns=None, algorithm_leverages=None): self.env = env treasury_curves = env.treasury_curves if treasury_curves.index[-1] >= start_date: mask = ((treasury_curves.index >= start_date) & (treasury_curves.index <= end_date)) self.treasury_curves = treasury_curves[mask] else: # our test is beyond the treasury curve history # so we'll use the last available treasury curve self.treasury_curves = treasury_curves[-1:] self.start_date = start_date self.end_date = end_date if benchmark_returns is None: br = env.benchmark_returns benchmark_returns = br[(br.index >= returns.index[0]) & (br.index <= returns.index[-1])] self.algorithm_returns = self.mask_returns_to_period(returns, env) self.benchmark_returns = self.mask_returns_to_period(benchmark_returns, env) self.algorithm_leverages = algorithm_leverages self.calculate_metrics() def calculate_metrics(self): self.benchmark_period_returns = \ self.calculate_period_returns(self.benchmark_returns) self.algorithm_period_returns = \ self.calculate_period_returns(self.algorithm_returns) if not self.algorithm_returns.index.equals( self.benchmark_returns.index ): message = "Mismatch between benchmark_returns ({bm_count}) and \ algorithm_returns ({algo_count}) in range {start} : {end}" message = message.format( bm_count=len(self.benchmark_returns), algo_count=len(self.algorithm_returns), start=self.start_date, end=self.end_date ) raise Exception(message) self.num_trading_days = len(self.benchmark_returns) self.trading_day_counts = pd.stats.moments.rolling_count( self.algorithm_returns, self.num_trading_days) self.mean_algorithm_returns = \ self.algorithm_returns.cumsum() / self.trading_day_counts self.benchmark_volatility = self.calculate_volatility( self.benchmark_returns) self.algorithm_volatility = self.calculate_volatility( self.algorithm_returns) self.treasury_period_return = choose_treasury( self.treasury_curves, self.start_date, self.end_date, self.env, ) self.sharpe = self.calculate_sharpe() # The consumer currently expects a 0.0 value for sharpe in period, # this differs from cumulative which was np.nan. # When factoring out the sharpe_ratio, the different return types # were collapsed into `np.nan`. # TODO: Either fix consumer to accept `np.nan` or make the # `sharpe_ratio` return type configurable. # In the meantime, convert nan values to 0.0 if pd.isnull(self.sharpe): self.sharpe = 0.0 self.sortino = self.calculate_sortino() self.information = self.calculate_information() self.beta, self.algorithm_covariance, self.benchmark_variance, \ self.condition_number, self.eigen_values = self.calculate_beta() self.alpha = self.calculate_alpha() self.excess_return = self.algorithm_period_returns - \ self.treasury_period_return self.max_drawdown = self.calculate_max_drawdown() self.max_leverage = self.calculate_max_leverage() def to_dict(self): """ Creates a dictionary representing the state of the risk report. Returns a dict object of the form: """ period_label = self.end_date.strftime("%Y-%m") rval = { 'trading_days': self.num_trading_days, 'benchmark_volatility': self.benchmark_volatility, 'algo_volatility': self.algorithm_volatility, 'treasury_period_return': self.treasury_period_return, 'algorithm_period_return': self.algorithm_period_returns, 'benchmark_period_return': self.benchmark_period_returns, 'sharpe': self.sharpe, 'sortino': self.sortino, 'information': self.information, 'beta': self.beta, 'alpha': self.alpha, 'excess_return': self.excess_return, 'max_drawdown': self.max_drawdown, 'max_leverage': self.max_leverage, 'period_label': period_label } return {k: None if check_entry(k, v) else v for k, v in iteritems(rval)} def __repr__(self): statements = [] metrics = [ "algorithm_period_returns", "benchmark_period_returns", "excess_return", "num_trading_days", "benchmark_volatility", "algorithm_volatility", "sharpe", "sortino", "information", "algorithm_covariance", "benchmark_variance", "beta", "alpha", "max_drawdown", "max_leverage", "algorithm_returns", "benchmark_returns", "condition_number", "eigen_values" ] for metric in metrics: value = getattr(self, metric) statements.append("{m}:{v}".format(m=metric, v=value)) return '\n'.join(statements) def mask_returns_to_period(self, daily_returns, env): if isinstance(daily_returns, list): returns = pd.Series([x.returns for x in daily_returns], index=[x.date for x in daily_returns]) else: # otherwise we're receiving an index already returns = daily_returns trade_days = env.trading_days trade_day_mask = returns.index.normalize().isin(trade_days) mask = ((returns.index >= self.start_date) & (returns.index <= self.end_date) & trade_day_mask) returns = returns[mask] return returns def calculate_period_returns(self, returns): period_returns = (1. + returns).prod() - 1 return period_returns def calculate_volatility(self, daily_returns): return np.std(daily_returns, ddof=1) * math.sqrt(self.num_trading_days) def calculate_sharpe(self): """ http://en.wikipedia.org/wiki/Sharpe_ratio """ return sharpe_ratio(self.algorithm_volatility, self.algorithm_period_returns, self.treasury_period_return) def calculate_sortino(self): """ http://en.wikipedia.org/wiki/Sortino_ratio """ mar = downside_risk(self.algorithm_returns, self.mean_algorithm_returns, self.num_trading_days) # Hold on to downside risk for debugging purposes. self.downside_risk = mar return sortino_ratio(self.algorithm_period_returns, self.treasury_period_return, mar) def calculate_information(self): """ http://en.wikipedia.org/wiki/Information_ratio """ return information_ratio(self.algorithm_returns, self.benchmark_returns) def calculate_beta(self): """ .. math:: \\beta_a = \\frac{\mathrm{Cov}(r_a,r_p)}{\mathrm{Var}(r_p)} http://en.wikipedia.org/wiki/Beta_(finance) """ # it doesn't make much sense to calculate beta for less than two days, # so return nan. if len(self.algorithm_returns) < 2: return np.nan, np.nan, np.nan, np.nan, [] returns_matrix = np.vstack([self.algorithm_returns, self.benchmark_returns]) C = np.cov(returns_matrix, ddof=1) # If there are missing benchmark values, then we can't calculate the # beta. if not np.isfinite(C).all(): return np.nan, np.nan, np.nan, np.nan, [] eigen_values = la.eigvals(C) condition_number = max(eigen_values) / min(eigen_values) algorithm_covariance = C[0][1] benchmark_variance = C[1][1] beta = algorithm_covariance / benchmark_variance return ( beta, algorithm_covariance, benchmark_variance, condition_number, eigen_values ) def calculate_alpha(self): """ http://en.wikipedia.org/wiki/Alpha_(investment) """ return alpha(self.algorithm_period_returns, self.treasury_period_return, self.benchmark_period_returns, self.beta) def calculate_max_drawdown(self): compounded_returns = [] cur_return = 0.0 for r in self.algorithm_returns: try: cur_return += math.log(1.0 + r) # this is a guard for a single day returning -100%, if returns are # greater than -1.0 it will throw an error because you cannot take # the log of a negative number except ValueError: log.debug("{cur} return, zeroing the returns".format( cur=cur_return)) cur_return = 0.0 compounded_returns.append(cur_return) cur_max = None max_drawdown = None for cur in compounded_returns: if cur_max is None or cur > cur_max: cur_max = cur drawdown = (cur - cur_max) if max_drawdown is None or drawdown < max_drawdown: max_drawdown = drawdown if max_drawdown is None: return 0.0 return 1.0 - math.exp(max_drawdown) def calculate_max_leverage(self): if self.algorithm_leverages is None: return 0.0 else: return max(self.algorithm_leverages)
{ "content_hash": "ab1e8d2290ff7dc0a9623ba9778e1dee", "timestamp": "", "source": "github", "line_count": 306, "max_line_length": 79, "avg_line_length": 35.11437908496732, "alnum_prop": 0.5617496510004654, "repo_name": "wilsonkichoi/zipline", "id": "b4af1288984ded1f8d7aca8ee7f7a7f4e7a457c3", "size": "11328", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "zipline/finance/risk/period.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "6778" }, { "name": "Emacs Lisp", "bytes": "138" }, { "name": "Jupyter Notebook", "bytes": "171073" }, { "name": "PowerShell", "bytes": "3260" }, { "name": "Python", "bytes": "2653811" }, { "name": "Shell", "bytes": "6381" } ], "symlink_target": "" }
print("\nExercise 10.11\n") # # Question 1 # 1. Two words are a "reverse pair" if each is the reverse of the other. Write # a program that finds all the reverse pairs in the word list. # import bisect fin = open('words.txt') wlist = [] def word_list(word): for line in fin: word = line.strip() wlist.append(word) return wlist def in_bisect(word_list, word): i = bisect.bisect_left(word_list, word) if i == len(word_list): return False return word_list[i] == word def reverse_pair(wlist): reverse_pair_list = [] for word in wlist: if in_bisect(wlist, word[::-1]): pair = (word, word[::-1]) reverse_pair_list.append(pair) return reverse_pair_list wlist = word_list(fin) print(reverse_pair(wlist))
{ "content_hash": "5e0febdf620398a579206a3ff31d75de", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 79, "avg_line_length": 21.210526315789473, "alnum_prop": 0.609181141439206, "repo_name": "ITSE-1402/git-classworkspace", "id": "add225b50c298df78e7190f3eef22d72e42dc8b9", "size": "912", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Yao_repo/homework-chapter-10/exercise10.11.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "4009" } ], "symlink_target": "" }
package license //go:generate counterfeiter . DirReader type DirReader interface { Read(string) (*License, error) }
{ "content_hash": "1f75dbfcb14f4ae0ac3abcdab957eb12", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 39, "avg_line_length": 17, "alnum_prop": 0.7563025210084033, "repo_name": "cf-platform-eng/aws-pcf-quickstart", "id": "b39fb9624fb5a02ecf3a4377203cde36543531b0", "size": "119", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "vendor/github.com/cloudfoundry/bosh-cli/release/license/interfaces.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "1871" }, { "name": "Go", "bytes": "21969" }, { "name": "Python", "bytes": "25058" }, { "name": "Shell", "bytes": "7277" } ], "symlink_target": "" }
class CreateSites < ActiveRecord::Migration def self.up create_table :spree_sites do |t| t.string :name t.string :domain t.timestamps end end def self.down drop_table :spree_sites end end
{ "content_hash": "8a22743e52d17ffc6e0ddf4ab5a891e2", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 43, "avg_line_length": 16.285714285714285, "alnum_prop": 0.6447368421052632, "repo_name": "qinghe/spree_multi_site", "id": "d1ef0f79b370543dbf5515311cd1f01489c0c730", "size": "228", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/migrate/20120415215214_create_sites.rb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "1657" }, { "name": "Ruby", "bytes": "176363" } ], "symlink_target": "" }
.class Landroid/webkit/WebSelectDialog$1; .super Ljava/lang/Object; .source "WebSelectDialog.java" # interfaces .implements Landroid/view/ViewTreeObserver$OnComputeInternalInsetsListener; # annotations .annotation system Ldalvik/annotation/EnclosingClass; value = Landroid/webkit/WebSelectDialog; .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x0 name = null .end annotation # instance fields .field final synthetic this$0:Landroid/webkit/WebSelectDialog; # direct methods .method constructor <init>(Landroid/webkit/WebSelectDialog;)V .locals 0 .parameter .prologue .line 101 iput-object p1, p0, Landroid/webkit/WebSelectDialog$1;->this$0:Landroid/webkit/WebSelectDialog; invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V return-void .end method # virtual methods .method public onComputeInternalInsets(Landroid/view/ViewTreeObserver$InternalInsetsInfo;)V .locals 2 .parameter "info" .prologue .line 103 iget-object v0, p0, Landroid/webkit/WebSelectDialog$1;->this$0:Landroid/webkit/WebSelectDialog; iget-object v1, p0, Landroid/webkit/WebSelectDialog$1;->this$0:Landroid/webkit/WebSelectDialog; iget-object v1, v1, Landroid/webkit/WebSelectDialog;->mTmpInsets:Landroid/inputmethodservice/InputMethodService$Insets; invoke-virtual {v0, v1}, Landroid/webkit/WebSelectDialog;->onComputeInsets(Landroid/inputmethodservice/InputMethodService$Insets;)V .line 104 iget-object v0, p1, Landroid/view/ViewTreeObserver$InternalInsetsInfo;->contentInsets:Landroid/graphics/Rect; iget-object v1, p0, Landroid/webkit/WebSelectDialog$1;->this$0:Landroid/webkit/WebSelectDialog; iget-object v1, v1, Landroid/webkit/WebSelectDialog;->mTmpInsets:Landroid/inputmethodservice/InputMethodService$Insets; iget v1, v1, Landroid/inputmethodservice/InputMethodService$Insets;->contentTopInsets:I iput v1, v0, Landroid/graphics/Rect;->top:I .line 105 iget-object v0, p1, Landroid/view/ViewTreeObserver$InternalInsetsInfo;->visibleInsets:Landroid/graphics/Rect; iget-object v1, p0, Landroid/webkit/WebSelectDialog$1;->this$0:Landroid/webkit/WebSelectDialog; iget-object v1, v1, Landroid/webkit/WebSelectDialog;->mTmpInsets:Landroid/inputmethodservice/InputMethodService$Insets; iget v1, v1, Landroid/inputmethodservice/InputMethodService$Insets;->visibleTopInsets:I iput v1, v0, Landroid/graphics/Rect;->top:I .line 106 iget-object v0, p0, Landroid/webkit/WebSelectDialog$1;->this$0:Landroid/webkit/WebSelectDialog; iget-object v0, v0, Landroid/webkit/WebSelectDialog;->mTmpInsets:Landroid/inputmethodservice/InputMethodService$Insets; iget v0, v0, Landroid/inputmethodservice/InputMethodService$Insets;->touchableInsets:I invoke-virtual {p1, v0}, Landroid/view/ViewTreeObserver$InternalInsetsInfo;->setTouchableInsets(I)V .line 107 return-void .end method
{ "content_hash": "3b1ddf436ad095cff62c6d24f9b0aab3", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 135, "avg_line_length": 33.98850574712644, "alnum_prop": 0.7747717281028069, "repo_name": "baidurom/devices-n7108", "id": "1f3a1b7ac56f4d636db24e4071f38a1a4881989e", "size": "2957", "binary": false, "copies": "2", "ref": "refs/heads/coron-4.1", "path": "vendor/aosp/framework2.jar.out/smali/android/webkit/WebSelectDialog$1.smali", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "12697" }, { "name": "Shell", "bytes": "1974" } ], "symlink_target": "" }
<?php namespace Lexik\Bundle\CurrencyBundle\Adapter; /** * @author Yoann Aparici <y.aparici@lexik.fr> * @author Cédric Girard <c.girard@lexik.fr> */ class DoctrineCurrencyAdapter extends AbstractCurrencyAdapter { /** * {@inheritdoc} */ public function attachAll() { // nothing here } /** * Return identifier * * @return string */ public function getIdentifier() { return 'doctrine'; } }
{ "content_hash": "48067486595251b458d76c2f02230f42", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 61, "avg_line_length": 16.821428571428573, "alnum_prop": 0.5944798301486199, "repo_name": "marcelohg/NasajonWebTeamplateProject", "id": "067b3ac80fd369180d432a6303cf7ddda1218592", "size": "472", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/lexik/currency-bundle/Lexik/Bundle/CurrencyBundle/Adapter/DoctrineCurrencyAdapter.php", "mode": "33261", "license": "mit", "language": [ { "name": "C#", "bytes": "13930" }, { "name": "CSS", "bytes": "327474" }, { "name": "JavaScript", "bytes": "17359824" }, { "name": "Nu", "bytes": "750" }, { "name": "PHP", "bytes": "58802" }, { "name": "Perl", "bytes": "4224" }, { "name": "Python", "bytes": "113740" }, { "name": "Shell", "bytes": "79" } ], "symlink_target": "" }
#include "lib.h" #include "mail-storage.h" #include "mail-types.h" #include "push-notification-drivers.h" #include "push-notification-events.h" #include "push-notification-event-messageread.h" #include "push-notification-txn-msg.h" #define EVENT_NAME "MessageRead" static void push_notification_event_messageread_debug_msg (struct push_notification_txn_event *event ATTR_UNUSED) { i_debug("%s: Message was flagged as seen", EVENT_NAME); } static void push_notification_event_messageread_event( struct push_notification_txn *ptxn, struct push_notification_event_config *ec, struct push_notification_txn_msg *msg, struct mail *mail, enum mail_flags old_flags) { struct push_notification_event_messageread_data *data; enum mail_flags flags; /* If data struct exists, that means the read flag was changed. */ data = push_notification_txn_msg_get_eventdata(msg, EVENT_NAME); if ((data == NULL) && !(old_flags & MAIL_SEEN)) { flags = mail_get_flags(mail); if (flags & MAIL_SEEN) { data = p_new(ptxn->pool, struct push_notification_event_messageread_data, 1); data->read = TRUE; push_notification_txn_msg_set_eventdata(ptxn, msg, ec, data); } } } /* Event definition */ extern struct push_notification_event push_notification_event_messageread; struct push_notification_event push_notification_event_messageread = { .name = EVENT_NAME, .msg = { .debug_msg = push_notification_event_messageread_debug_msg }, .msg_triggers = { .flagchange = push_notification_event_messageread_event } };
{ "content_hash": "de9ada5a96f2ee311cddb86c9aa87f63", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 77, "avg_line_length": 28.637931034482758, "alnum_prop": 0.6730885009030705, "repo_name": "dscho/dovecot", "id": "870f894d1682d751c124f1d3c3c917f4da6fded7", "size": "1732", "binary": false, "copies": "1", "ref": "refs/heads/default", "path": "src/plugins/push-notification/push-notification-event-messageread.c", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "11118558" }, { "name": "C++", "bytes": "90087" }, { "name": "Logos", "bytes": "3470" }, { "name": "Objective-C", "bytes": "1689" }, { "name": "Perl", "bytes": "9288" }, { "name": "Python", "bytes": "1626" }, { "name": "Shell", "bytes": "7240" } ], "symlink_target": "" }
require 'pavlov' require 'pavlov/alpha_compatibility' require 'pavlov/helpers' module PavlovSupport def stub_classes(*classnames) classnames.each do |classname| stub_const classname, Class.new end end def expect_validating(hash) hash[:pavlov_options] ||= {} hash[:pavlov_options][:ability] ||= double(can?: true) instance = described_class.new(hash) instance.valid? error_messages = instance.errors.map do |attribute, message| "#{attribute} #{message}" end expect(error_messages) end def fail_validation(message) include message end class ExecuteAsUser < Struct.new(:user) include Pavlov::Helpers def pavlov_options Util::PavlovContextSerialization.pavlov_context_by_user user end def execute(&block) yield self end end def as(user, &block) @execute_as_user ||= {} @execute_as_user[user] ||= ExecuteAsUser.new(user) @execute_as_user[user].execute(&block) end end
{ "content_hash": "e16e3f3ca9d3450130808d6676bf2cd8", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 66, "avg_line_length": 22.40909090909091, "alnum_prop": 0.6744421906693712, "repo_name": "Factlink/pavlov", "id": "2cc25fae74ee06746e36074061c3a652b477462d", "size": "986", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/regression/pavlov_helper.rb", "mode": "33261", "license": "mit", "language": [ { "name": "Ruby", "bytes": "44159" } ], "symlink_target": "" }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.resolvePath = exports.default = undefined; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); exports.stringifyPath = stringifyPath; exports.matchPath = matchPath; var _makeJSONError = require('./errorReporting/makeJSONError'); var _makeJSONError2 = _interopRequireDefault(_makeJSONError); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var validIdentifier = /^[$A-Z_][0-9A-Z_$]*$/i; var Validation = function () { function Validation(context, input) { _classCallCheck(this, Validation); this.inputName = ''; this.errors = []; this.context = context; this.input = input; } _createClass(Validation, [{ key: 'hasErrors', value: function hasErrors(path) { if (path) { var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = this.errors[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var _ref = _step.value; var _ref2 = _slicedToArray(_ref, 1); var candidate = _ref2[0]; if (matchPath(path, candidate)) { return true; } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } return false; } else { return this.errors.length > 0; } } }, { key: 'addError', value: function addError(path, expectedType, message) { this.errors.push([path, message, expectedType]); return this; } }, { key: 'clearError', value: function clearError(path) { var didClear = false; if (path) { var _errors = []; var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = this.errors[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var error = _step2.value; if (matchPath(path, error[0])) { didClear = true; } else { _errors.push(error); } } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2.return) { _iterator2.return(); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } this.errors = _errors; } else { didClear = this.errors.length > 0; this.errors = []; } return didClear; } }, { key: 'resolvePath', value: function resolvePath(path) { return _resolvePath(this.input, path); } }, { key: 'toJSON', value: function toJSON() { return (0, _makeJSONError2.default)(this); } }]); return Validation; }(); exports.default = Validation; function stringifyPath(path) { if (!path.length) { return 'Value'; } var length = path.length; var parts = new Array(length); for (var i = 0; i < length; i++) { var part = path[i]; if (part === '[[Return Type]]') { parts[i] = 'Return Type'; } else if (typeof part !== 'string' || !validIdentifier.test(part)) { parts[i] = '[' + String(part) + ']'; } else if (i > 0) { parts[i] = '.' + part; } else { parts[i] = part; } } return parts.join(''); } function _resolvePath(input, path) { var subject = input; var length = path.length; for (var i = 0; i < length; i++) { if (subject == null) { return undefined; } var part = path[i]; if (part === '[[Return Type]]') { continue; } if (subject instanceof Map) { subject = subject.get(part); } else { subject = subject[part]; } } return subject; } exports.resolvePath = _resolvePath; function matchPath(path, candidate) { var length = path.length; if (length > candidate.length) { return false; } for (var i = 0; i < length; i++) { if (candidate[i] !== path[i]) { return false; } } return true; }
{ "content_hash": "f20e44709911080fd156fd5c8eda2d50", "timestamp": "", "source": "github", "line_count": 196, "max_line_length": 664, "avg_line_length": 30.852040816326532, "alnum_prop": 0.5703654704812303, "repo_name": "jakegornall/MeatFestWebsite", "id": "6f556369d49a0a4017263fa8de979feb79af4ef8", "size": "6047", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node_modules/flow-runtime/lib/Validation.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "12501" }, { "name": "HTML", "bytes": "5296" }, { "name": "JavaScript", "bytes": "1147442" }, { "name": "Python", "bytes": "10255" } ], "symlink_target": "" }
package pt.ist.recplay.inspector.util; import pt.utl.ist.rfidtoys.recplay.SerializableSessionObject; import java.io.FileInputStream; import java.io.ObjectInputStream; public class Deserializer { private final String currentPath = System.getProperty("user.dir"); private static Deserializer instance = null; public SerializableSessionObject deserializeSessionObject(String basePath, String path, String extension) { SerializableSessionObject sessionObject; try { FileInputStream fis = new FileInputStream(currentPath + "/src/main/resources/" + basePath + path + extension); ObjectInputStream ois = new ObjectInputStream(fis); sessionObject = (SerializableSessionObject) ois.readObject(); ois.close(); return sessionObject; } catch (Exception e) { e.printStackTrace(); return null; } } public static Deserializer getDeserializer() { if(instance == null) { instance = new Deserializer(); } return instance; } }
{ "content_hash": "080184b3b3a3d9def23100bda30b858b", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 122, "avg_line_length": 28.102564102564102, "alnum_prop": 0.6624087591240876, "repo_name": "mvpgomes/cloud4things", "id": "65483834d11a52956b281e266adfcede8ddecab6", "size": "1096", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rec-play-session-deserializer/src/main/java/pt/ist/recplay/inspector/util/Deserializer.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "75181" }, { "name": "Java", "bytes": "7264" }, { "name": "JavaScript", "bytes": "8642" }, { "name": "PLpgSQL", "bytes": "11057" }, { "name": "Ruby", "bytes": "528870" }, { "name": "Scala", "bytes": "21593" }, { "name": "Shell", "bytes": "24759" } ], "symlink_target": "" }
#import "Base.h" #import "MBGSocialRemoteNotification.h" @interface common_RemoteNotification_base : Base @end
{ "content_hash": "f552eb69b04b4bef6108651bae3eeece", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 48, "avg_line_length": 16.285714285714285, "alnum_prop": 0.7807017543859649, "repo_name": "DeNADev/ANE4MobageNativeSDK", "id": "e98c17acdc579c06c567ee3daa4930781b1531fd", "size": "1259", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ios/src/com.mobage.air.extension/social/common/RemoteNotification/common_RemoteNotification_base.h", "mode": "33261", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "156252" }, { "name": "Java", "bytes": "454615" }, { "name": "Makefile", "bytes": "11245" }, { "name": "Objective-C", "bytes": "475524" }, { "name": "Ruby", "bytes": "1168" } ], "symlink_target": "" }
"use strict" const wrapCPS = (fn, options) => { if (typeof fn !== "function") throw new Error("fn is not a function") return function() { const args = Array.from(arguments) return new Promise((resolve, reject) => { args.push(function() { const resultArgs = Array.from(arguments) const error = options && options.noError ? null : resultArgs.shift() if (error) reject(error) else if (options && options.multi) { const result = {} for (let i = 0; i < options.multi.length; i++) { result[options.multi[i]] = resultArgs[i] } resolve(result) } else resolve(resultArgs[0]) }) fn(...args) }) } } module.exports = { wrapCPS, }
{ "content_hash": "d0c9b6ca8489e7c0761436e77ed135ce", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 76, "avg_line_length": 25.93103448275862, "alnum_prop": 0.5571808510638298, "repo_name": "BenoitZugmeyer/pass-web", "id": "7af27256566ce2eb650fb7ee7f46f91f0eaea506", "size": "752", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/promiseUtil.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "237" }, { "name": "JavaScript", "bytes": "47081" }, { "name": "Shell", "bytes": "892" } ], "symlink_target": "" }
This repository contains the source code of the tools needed for our gradle framework that aims at deriving a multilinear tongue model from a given MRI data set. Have a look at [our paper][1] to learn more about the background. ## Installation You can install each tool individually by using the cmake files in the respective subdirectory. However, you are also able to install them all at once from the root directory. ### Requirements Please make sure that the following libraries and tools are available: - A C++ compiler that can handle C++11 code, *e.g.*, GCC (since version 4.8.1) or Clang (since version 3.3). - [ann](https://www.cs.umd.edu/~mount/ANN) - [armadillo](http://arma.sourceforge.net) - [cmake](https://cmake.org) - [gtkmm-3.0](https://www.gtkmm.org) - [jsoncpp](https://github.com/open-source-parsers/jsoncpp) - [pkg-config](https://www.freedesktop.org/wiki/Software/pkg-config) - [cairomm-1.0](https://www.cairographics.org/cairomm) - [itk](https://itk.org) - [yaml-cpp](https://github.com/jbeder/yaml-cpp) On Ubuntu, for example, you can install all dependencies by executing the following command: ```sh apt-get install \ build-essential \ libann-dev \ libarmadillo-dev \ cmake \ libjsoncpp-dev \ pkg-config \ libgtkmm-3.0-dev \ libcairomm-1.0-dev \ libinsighttoolkit4-dev \ libyaml-cpp-dev ``` On OSX with [Homebrew](http://brew.sh), install the dependencies with ```sh brew install \ armadillo \ jsoncpp \ ann \ cairomm \ insighttoolkit \ vtk \ gtkmm3 \ yaml-cpp ``` ### Installation Process In order to install all tools, perform the following steps: - configuration, adapt the installation path if needed ```sh cmake CMakeLists.txt -DCMAKE_INSTALL_PREFIX=$HOME/usr ``` - installation ```sh make install ``` ## Documentation Documentation about the individual tools is available in their respective folders. The [dataFormats](./dataFormats) folder contains information about the various data formats used by our tools. ## License This work is licensed under the [MIT license](./LICENSE.md). If you are using our tools, please cite, for the time being, the following paper: ```bibtex @article{Hewer2018CSL, author = {Hewer, Alexander and Wuhrer, Stefanie and Steiner, Ingmar and Richmond, Korin}, doi = {10.1016/j.csl.2018.02.001}, eprint = {1612.05005}, eprinttype = {arxiv}, journal = {Computer Speech \& Language}, month = sep, pages = {68-92}, title = {A Multilinear Tongue Model Derived from Speech Related {MRI} Data of the Human Vocal Tract}, url = {https://arxiv.org/abs/1612.05005}, volume = {51}, year = {2018} } ``` [1]: http://arxiv.org/abs/1612.05005
{ "content_hash": "7cf688187a1082017c9b08879976fb25", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 161, "avg_line_length": 28.73404255319149, "alnum_prop": 0.7089966679007775, "repo_name": "m2ci-msp/mri-shape-tools", "id": "ab63984090118a2fae51f5920dc7c83dda56304a", "size": "2746", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "1277618" }, { "name": "CMake", "bytes": "69283" } ], "symlink_target": "" }
module.exports = function removeFilterString (str) { var filterReg = /filter\[(.+)]/g; var match = filterReg.exec(str); if (match) { return match[1]; } return str; };
{ "content_hash": "a4cd2d23ed34f4355e4de56a645aacac", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 52, "avg_line_length": 20.22222222222222, "alnum_prop": 0.6208791208791209, "repo_name": "TheScienceMuseum/collectionsonline", "id": "e189e8290c5c8cbd71e5642fa9a8aefcc459d064", "size": "182", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/helpers/remove-filter-string.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "106622" }, { "name": "JavaScript", "bytes": "474507" }, { "name": "SCSS", "bytes": "71018" } ], "symlink_target": "" }
@implementation NSLayoutConstraint (AutoLayout) + (id)constraintsWithVisualFormats:(NSArray *)visualFormats options:(NSLayoutFormatOptions)options metrics:(NSDictionary *)metrics views:(NSDictionary *)views { NSMutableArray *result = [NSMutableArray array]; for (NSString *visualFormat in visualFormats) { NSArray *array = [NSLayoutConstraint constraintsWithVisualFormat:visualFormat options:options metrics:metrics views:views]; [result addObjectsFromArray:array]; } return result; } @end
{ "content_hash": "eb06cb1e1af48c5258dfe2343c7b2b61", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 160, "avg_line_length": 45.27272727272727, "alnum_prop": 0.8112449799196787, "repo_name": "jmcd/evidence", "id": "9e8b50a2fbb96adcf8f5a230b50051d1df623162", "size": "541", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "evidence/jmcdMiniSDK/AutoLayout/NSLayoutConstraint+AutoLayout.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "55853" }, { "name": "Shell", "bytes": "123" } ], "symlink_target": "" }
import pytest import six from kafka.partitioner import Murmur2Partitioner from kafka.partitioner.default import DefaultPartitioner def test_default_partitioner(): partitioner = DefaultPartitioner() all_partitions = list(range(100)) available = all_partitions # partitioner should return the same partition for the same key p1 = partitioner(b'foo', all_partitions, available) p2 = partitioner(b'foo', all_partitions, available) assert p1 == p2 assert p1 in all_partitions # when key is None, choose one of available partitions assert partitioner(None, all_partitions, [123]) == 123 # with fallback to all_partitions assert partitioner(None, all_partitions, []) in all_partitions def test_hash_bytes(): p = Murmur2Partitioner(range(1000)) assert p.partition(bytearray(b'test')) == p.partition(b'test') def test_hash_encoding(): p = Murmur2Partitioner(range(1000)) assert p.partition('test') == p.partition(u'test') def test_murmur2_java_compatibility(): p = Murmur2Partitioner(range(1000)) # compare with output from Kafka's org.apache.kafka.clients.producer.Partitioner assert p.partition(b'') == 681 assert p.partition(b'a') == 524 assert p.partition(b'ab') == 434 assert p.partition(b'abc') == 107 assert p.partition(b'123456789') == 566 assert p.partition(b'\x00 ') == 742
{ "content_hash": "eb7f1bee78063ac5a85c6dcc80c1a13f", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 84, "avg_line_length": 32.23255813953488, "alnum_prop": 0.7027417027417028, "repo_name": "zackdever/kafka-python", "id": "52b6b81d138e96b9019f1ab44f0a99f1d5c83060", "size": "1386", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/test_partitioner.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "675698" }, { "name": "Shell", "bytes": "2646" } ], "symlink_target": "" }
import json from ..utils import check_resource, minimum_version class NetworkApiMixin(object): @minimum_version('1.21') def networks(self, names=None, ids=None): filters = {} if names: filters['name'] = names if ids: filters['id'] = ids params = {'filters': json.dumps(filters)} url = self._url("/networks") res = self._get(url, params=params) return self._result(res, json=True) @minimum_version('1.21') def create_network(self, name, driver=None, options=None, ipam=None): if options is not None and not isinstance(options, dict): raise TypeError('options must be a dictionary') data = { 'name': name, 'driver': driver, 'options': options, 'ipam': ipam, } url = self._url("/networks/create") res = self._post_json(url, data=data) return self._result(res, json=True) @minimum_version('1.21') def remove_network(self, net_id): url = self._url("/networks/{0}", net_id) res = self._delete(url) self._raise_for_status(res) @minimum_version('1.21') def inspect_network(self, net_id): url = self._url("/networks/{0}", net_id) res = self._get(url) return self._result(res, json=True) @check_resource @minimum_version('1.21') def connect_container_to_network(self, container, net_id): data = {"container": container} url = self._url("/networks/{0}/connect", net_id) self._post_json(url, data=data) @check_resource @minimum_version('1.21') def disconnect_container_from_network(self, container, net_id): data = {"container": container} url = self._url("/networks/{0}/disconnect", net_id) self._post_json(url, data=data)
{ "content_hash": "0520858d9994317981f5dcf0dd0a062d", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 73, "avg_line_length": 31.05, "alnum_prop": 0.5743424584004294, "repo_name": "rhatdan/docker-py", "id": "ce3f51119cd2f7fc6d655a03593ed910d8f7912d", "size": "1863", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docker/api/network.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "2227" }, { "name": "Python", "bytes": "329736" } ], "symlink_target": "" }
using System; using System.Threading.Tasks; using Windows.Security.Cryptography; using Windows.Security.Cryptography.DataProtection; namespace NavigationMenuSample.Common { public static class AlphaGain { public static async Task<string> GeneralRevil(this string clearText, string scope = "LOCAL=user") { if ((clearText == null) || (scope == null)) return null; var clearBuffer = CryptographicBuffer.ConvertStringToBinary(clearText, BinaryStringEncoding.Utf8); var provider = new DataProtectionProvider(scope); var encryptedBuffer = await provider.ProtectAsync(clearBuffer); return CryptographicBuffer.EncodeToBase64String(encryptedBuffer); } public static async Task<string> SaylaMass(this string encryptedText) { if (encryptedText == null) return null; var encryptedBuffer = CryptographicBuffer.DecodeFromBase64String(encryptedText); var provider = new DataProtectionProvider(); var clearBuffer = await provider.UnprotectAsync(encryptedBuffer); return CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, clearBuffer); } } }
{ "content_hash": "a243103e5e443870ce7c8a695349730b", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 101, "avg_line_length": 35.483870967741936, "alnum_prop": 0.7836363636363637, "repo_name": "shirothin/KunappUniversalApp", "id": "874db5b2783f423945b0519faa88927143121645", "size": "1102", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Common/AlphaGain.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "142049458" } ], "symlink_target": "" }
#include <boost/spirit/include/classic_scanner.hpp> #include <boost/utility/addressof.hpp> #include "symbols.hpp" typedef char char_type; typedef char const* iterator; char_type data_[] = "whatever"; iterator begin = data_; iterator end = data_ + sizeof(data_) / sizeof(char_type); // Yes, this is an intentional bug ;) int main() { typedef BOOST_SPIRIT_CLASSIC_NS::scanner<> scanner; typedef quickbook::tst<void*, char_type> symbols; symbols symbols_; symbols_.add(begin, end - 1, (void*)boost::addressof(symbols_)); // The symbol table parser should not choke on input containing the null // character. symbols_.find(scanner(begin, end)); }
{ "content_hash": "6b72d659ed9a6c62b91ce36e0ad0882b", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 76, "avg_line_length": 23.724137931034484, "alnum_prop": 0.684593023255814, "repo_name": "fceller/arangodb", "id": "0be8ab1e58b34c821b0f1257434b337e951e648a", "size": "1110", "binary": false, "copies": "9", "ref": "refs/heads/devel", "path": "3rdParty/boost/1.69.0/tools/quickbook/test/unit/symbols_find_null.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ada", "bytes": "89080" }, { "name": "AppleScript", "bytes": "1429" }, { "name": "Assembly", "bytes": "142084" }, { "name": "Batchfile", "bytes": "9073" }, { "name": "C", "bytes": "1938354" }, { "name": "C#", "bytes": "55625" }, { "name": "C++", "bytes": "79379178" }, { "name": "CLIPS", "bytes": "5291" }, { "name": "CMake", "bytes": "109718" }, { "name": "CSS", "bytes": "1341035" }, { "name": "CoffeeScript", "bytes": "94" }, { "name": "DIGITAL Command Language", "bytes": "27303" }, { "name": "Emacs Lisp", "bytes": "15477" }, { "name": "Go", "bytes": "1018005" }, { "name": "Groff", "bytes": "263567" }, { "name": "HTML", "bytes": "459886" }, { "name": "JavaScript", "bytes": "55446690" }, { "name": "LLVM", "bytes": "39361" }, { "name": "Lua", "bytes": "16189" }, { "name": "Makefile", "bytes": "178253" }, { "name": "Module Management System", "bytes": "1545" }, { "name": "NSIS", "bytes": "26909" }, { "name": "Objective-C", "bytes": "4430" }, { "name": "Objective-C++", "bytes": "1857" }, { "name": "Pascal", "bytes": "145262" }, { "name": "Perl", "bytes": "227308" }, { "name": "Protocol Buffer", "bytes": "5837" }, { "name": "Python", "bytes": "3563935" }, { "name": "Ruby", "bytes": "1000962" }, { "name": "SAS", "bytes": "1847" }, { "name": "Scheme", "bytes": "19885" }, { "name": "Shell", "bytes": "488846" }, { "name": "VimL", "bytes": "4075" }, { "name": "Yacc", "bytes": "36950" } ], "symlink_target": "" }
#ifndef BOOST_FUSION_ADAPTED_ADT_ADAPT_ASSOC_ADT_HPP #define BOOST_FUSION_ADAPTED_ADT_ADAPT_ASSOC_ADT_HPP #include <boost/fusion/support/config.hpp> #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/empty.hpp> #include <boost/preprocessor/tuple/elem.hpp> #include <boost/type_traits/add_reference.hpp> #include <boost/type_traits/is_const.hpp> #include <boost/type_traits/remove_const.hpp> #include <boost/fusion/adapted/struct/detail/extension.hpp> #include <boost/fusion/adapted/struct/detail/adapt_base.hpp> #include <boost/fusion/adapted/struct/detail/at_impl.hpp> #include <boost/fusion/adapted/struct/detail/is_view_impl.hpp> #include <boost/fusion/adapted/struct/detail/proxy_type.hpp> #include <boost/fusion/adapted/struct/detail/is_sequence_impl.hpp> #include <boost/fusion/adapted/struct/detail/value_at_impl.hpp> #include <boost/fusion/adapted/struct/detail/category_of_impl.hpp> #include <boost/fusion/adapted/struct/detail/size_impl.hpp> #include <boost/fusion/adapted/struct/detail/begin_impl.hpp> #include <boost/fusion/adapted/struct/detail/end_impl.hpp> #include <boost/fusion/adapted/struct/detail/value_of_impl.hpp> #include <boost/fusion/adapted/struct/detail/deref_impl.hpp> #include <boost/fusion/adapted/struct/detail/deref_data_impl.hpp> #include <boost/fusion/adapted/struct/detail/key_of_impl.hpp> #include <boost/fusion/adapted/struct/detail/value_of_data_impl.hpp> #include <boost/fusion/adapted/adt/detail/extension.hpp> #include <boost/fusion/adapted/adt/detail/adapt_base.hpp> #include <boost/fusion/adapted/adt/detail/adapt_base_assoc_attr_filler.hpp> #define BOOST_FUSION_ADAPT_ASSOC_ADT_C( \ TEMPLATE_PARAMS_SEQ, NAME_SEQ, IS_VIEW, I, ATTRIBUTE) \ \ BOOST_FUSION_ADAPT_ADT_C_BASE( \ TEMPLATE_PARAMS_SEQ, \ NAME_SEQ, \ I, \ BOOST_PP_IF(IS_VIEW, BOOST_FUSION_PROXY_PREFIX, BOOST_PP_EMPTY), \ BOOST_FUSION_ADAPT_ADT_WRAPPEDATTR(ATTRIBUTE), \ BOOST_FUSION_ADAPT_ADT_WRAPPEDATTR_SIZE(ATTRIBUTE), \ BOOST_PP_IF( \ BOOST_PP_LESS( \ BOOST_FUSION_ADAPT_ADT_WRAPPEDATTR_SIZE(ATTRIBUTE), 5) \ , 1, 0)) \ \ template< \ BOOST_FUSION_ADAPT_STRUCT_UNPACK_TEMPLATE_PARAMS(TEMPLATE_PARAMS_SEQ) \ > \ struct struct_assoc_key<BOOST_FUSION_ADAPT_STRUCT_UNPACK_NAME(NAME_SEQ), I> \ { \ typedef BOOST_FUSION_ADAPT_ASSOC_ADT_WRAPPEDATTR_GET_KEY(ATTRIBUTE) type;\ }; #define BOOST_FUSION_ADAPT_ASSOC_TPL_ADT( \ TEMPLATE_PARAMS_SEQ, NAME_SEQ, ATTRIBUTES) \ \ BOOST_FUSION_ADAPT_STRUCT_BASE( \ (1)TEMPLATE_PARAMS_SEQ, \ (1)NAME_SEQ, \ assoc_struct_tag, \ 0, \ BOOST_PP_CAT( \ BOOST_FUSION_ADAPT_ASSOC_ADT_FILLER_0(0,0,0,0,0)ATTRIBUTES,_END), \ BOOST_FUSION_ADAPT_ASSOC_ADT_C) #define BOOST_FUSION_ADAPT_ASSOC_ADT(NAME, ATTRIBUTES) \ BOOST_FUSION_ADAPT_STRUCT_BASE( \ (0), \ (0)(NAME), \ assoc_struct_tag, \ 0, \ BOOST_PP_CAT( \ BOOST_FUSION_ADAPT_ASSOC_ADT_FILLER_0(0,0,0,0,0)ATTRIBUTES,_END), \ BOOST_FUSION_ADAPT_ASSOC_ADT_C) #define BOOST_FUSION_ADAPT_ASSOC_ADT_AS_VIEW(NAME, ATTRIBUTES) \ BOOST_FUSION_ADAPT_STRUCT_BASE( \ (0), \ (0)(NAME), \ assoc_struct_tag, \ 1, \ BOOST_PP_CAT( \ BOOST_FUSION_ADAPT_ASSOC_ADT_FILLER_0(0,0,0,0,0)ATTRIBUTES,_END), \ BOOST_FUSION_ADAPT_ASSOC_ADT_C) #endif
{ "content_hash": "eecebb0c464e8d42cf8a3bd81a1891fa", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 82, "avg_line_length": 63.91011235955056, "alnum_prop": 0.41543600562587907, "repo_name": "ycsoft/FatCat-Server", "id": "526a307c03a908fe5fd28ff2ac4c13d44c272480", "size": "6178", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "LIBS/boost_1_58_0/boost/fusion/adapted/adt/adapt_assoc_adt.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "195345" }, { "name": "Batchfile", "bytes": "32367" }, { "name": "C", "bytes": "9529739" }, { "name": "C#", "bytes": "41850" }, { "name": "C++", "bytes": "175536080" }, { "name": "CMake", "bytes": "14812" }, { "name": "CSS", "bytes": "282447" }, { "name": "Cuda", "bytes": "26521" }, { "name": "FORTRAN", "bytes": "1856" }, { "name": "Groff", "bytes": "6163" }, { "name": "HTML", "bytes": "148956564" }, { "name": "JavaScript", "bytes": "174868" }, { "name": "Lex", "bytes": "1290" }, { "name": "Makefile", "bytes": "1045258" }, { "name": "Max", "bytes": "37424" }, { "name": "Objective-C", "bytes": "34644" }, { "name": "Objective-C++", "bytes": "246" }, { "name": "PHP", "bytes": "60249" }, { "name": "Perl", "bytes": "37297" }, { "name": "Perl6", "bytes": "2130" }, { "name": "Python", "bytes": "1717781" }, { "name": "QML", "bytes": "613" }, { "name": "QMake", "bytes": "9450" }, { "name": "Rebol", "bytes": "372" }, { "name": "Shell", "bytes": "372652" }, { "name": "Tcl", "bytes": "1205" }, { "name": "TeX", "bytes": "13819" }, { "name": "XSLT", "bytes": "564356" }, { "name": "Yacc", "bytes": "19612" } ], "symlink_target": "" }
function storage(AppSettings, $window) { 'ngInject'; function Storage() { this.storage = AppSettings.storage || 'sessionStorage'; } Storage.prototype.get = function (key) { return $window[this.storage].getItem(key); } Storage.prototype.set = function (key, value) { $window[this.storage].setItem(key, value); } Storage.prototype.remove = function (key) { $window[this.storage].removeItem(key); } return new Storage(); } export default { name: 'storage', fn: storage };
{ "content_hash": "cda30f3a65d52d503569f40b6297215b", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 59, "avg_line_length": 23.227272727272727, "alnum_prop": 0.6653620352250489, "repo_name": "tungptvn/tungpts-ng-blog", "id": "50cf48f5b50fe0e5b3f1492c6e2fe12b88f6acea", "size": "511", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/js/factories/storage.js", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "110" }, { "name": "C#", "bytes": "851515" }, { "name": "CSS", "bytes": "212147" }, { "name": "HTML", "bytes": "46132" }, { "name": "JavaScript", "bytes": "256744" } ], "symlink_target": "" }
from unittest import TestCase, mock from airflow.providers.google.marketing_platform.hooks.campaign_manager import GoogleCampaignManagerHook from tests.providers.google.cloud.utils.base_gcp_mock import mock_base_gcp_hook_default_project_id API_VERSION = "v3.3" GCP_CONN_ID = "google_cloud_default" REPORT_ID = "REPORT_ID" PROFILE_ID = "PROFILE_ID" ENCRYPTION_SOURCE = "encryption_source" ENCRYPTION_ENTITY_TYPE = "encryption_entity_type" ENCRYPTION_ENTITY_ID = 1234567 class TestGoogleCampaignManagerHook(TestCase): def setUp(self): with mock.patch( "airflow.providers.google.common.hooks.base_google.GoogleBaseHook.__init__", new=mock_base_gcp_hook_default_project_id, ): self.hook = GoogleCampaignManagerHook(gcp_conn_id=GCP_CONN_ID, api_version=API_VERSION) @mock.patch( "airflow.providers.google.marketing_platform.hooks." "campaign_manager.GoogleCampaignManagerHook._authorize" ) @mock.patch("airflow.providers.google.marketing_platform.hooks.campaign_manager.build") def test_gen_conn(self, mock_build, mock_authorize): result = self.hook.get_conn() mock_build.assert_called_once_with( "dfareporting", API_VERSION, http=mock_authorize.return_value, cache_discovery=False, ) assert mock_build.return_value == result @mock.patch( "airflow.providers.google.marketing_platform.hooks." "campaign_manager.GoogleCampaignManagerHook.get_conn" ) def test_delete_report(self, get_conn_mock): return_value = "TEST" get_conn_mock.return_value.reports.return_value.delete.return_value.execute.return_value = ( return_value ) result = self.hook.delete_report(profile_id=PROFILE_ID, report_id=REPORT_ID) get_conn_mock.return_value.reports.return_value.delete.assert_called_once_with( profileId=PROFILE_ID, reportId=REPORT_ID ) assert return_value == result @mock.patch( "airflow.providers.google.marketing_platform.hooks." "campaign_manager.GoogleCampaignManagerHook.get_conn" ) def test_get_report(self, get_conn_mock): file_id = "FILE_ID" return_value = "TEST" # fmt: off get_conn_mock.return_value.reports.return_value.files.return_value. \ get.return_value.execute.return_value = return_value # fmt: on result = self.hook.get_report(profile_id=PROFILE_ID, report_id=REPORT_ID, file_id=file_id) get_conn_mock.return_value.reports.return_value.files.return_value.get.assert_called_once_with( profileId=PROFILE_ID, reportId=REPORT_ID, fileId=file_id ) assert return_value == result @mock.patch( "airflow.providers.google.marketing_platform.hooks." "campaign_manager.GoogleCampaignManagerHook.get_conn" ) def test_get_report_file(self, get_conn_mock): file_id = "FILE_ID" return_value = "TEST" get_conn_mock.return_value.reports.return_value.files.return_value.get_media.return_value = ( return_value ) result = self.hook.get_report_file(profile_id=PROFILE_ID, report_id=REPORT_ID, file_id=file_id) get_conn_mock.return_value.reports.return_value.files.return_value.get_media.assert_called_once_with( profileId=PROFILE_ID, reportId=REPORT_ID, fileId=file_id ) assert return_value == result @mock.patch( "airflow.providers.google.marketing_platform.hooks." "campaign_manager.GoogleCampaignManagerHook.get_conn" ) def test_insert_report(self, get_conn_mock): report = {"body": "test"} return_value = "TEST" get_conn_mock.return_value.reports.return_value.insert.return_value.execute.return_value = ( return_value ) result = self.hook.insert_report(profile_id=PROFILE_ID, report=report) get_conn_mock.return_value.reports.return_value.insert.assert_called_once_with( profileId=PROFILE_ID, body=report ) assert return_value == result @mock.patch( "airflow.providers.google.marketing_platform.hooks." "campaign_manager.GoogleCampaignManagerHook.get_conn" ) def test_list_reports(self, get_conn_mock): max_results = 42 scope = "SCOPE" sort_field = "SORT_FIELD" sort_order = "SORT_ORDER" items = ["item"] return_value = {"nextPageToken": None, "items": items} get_conn_mock.return_value.reports.return_value.list.return_value.execute.return_value = return_value request_mock = mock.MagicMock() request_mock.execute.return_value = {"nextPageToken": None, "items": items} get_conn_mock.return_value.reports.return_value.list_next.side_effect = [ request_mock, request_mock, request_mock, None, ] result = self.hook.list_reports( profile_id=PROFILE_ID, max_results=max_results, scope=scope, sort_field=sort_field, sort_order=sort_order, ) get_conn_mock.return_value.reports.return_value.list.assert_called_once_with( profileId=PROFILE_ID, maxResults=max_results, scope=scope, sortField=sort_field, sortOrder=sort_order, ) assert items * 4 == result @mock.patch( "airflow.providers.google.marketing_platform.hooks." "campaign_manager.GoogleCampaignManagerHook.get_conn" ) def test_patch_report(self, get_conn_mock): update_mask = {"test": "test"} return_value = "TEST" get_conn_mock.return_value.reports.return_value.patch.return_value.execute.return_value = return_value result = self.hook.patch_report(profile_id=PROFILE_ID, report_id=REPORT_ID, update_mask=update_mask) get_conn_mock.return_value.reports.return_value.patch.assert_called_once_with( profileId=PROFILE_ID, reportId=REPORT_ID, body=update_mask ) assert return_value == result @mock.patch( "airflow.providers.google.marketing_platform.hooks." "campaign_manager.GoogleCampaignManagerHook.get_conn" ) def test_run_report(self, get_conn_mock): synchronous = True return_value = "TEST" get_conn_mock.return_value.reports.return_value.run.return_value.execute.return_value = return_value result = self.hook.run_report(profile_id=PROFILE_ID, report_id=REPORT_ID, synchronous=synchronous) get_conn_mock.return_value.reports.return_value.run.assert_called_once_with( profileId=PROFILE_ID, reportId=REPORT_ID, synchronous=synchronous ) assert return_value == result @mock.patch( "airflow.providers.google.marketing_platform.hooks." "campaign_manager.GoogleCampaignManagerHook.get_conn" ) def test_update_report(self, get_conn_mock): return_value = "TEST" get_conn_mock.return_value.reports.return_value.update.return_value.execute.return_value = ( return_value ) result = self.hook.update_report(profile_id=PROFILE_ID, report_id=REPORT_ID) get_conn_mock.return_value.reports.return_value.update.assert_called_once_with( profileId=PROFILE_ID, reportId=REPORT_ID ) assert return_value == result @mock.patch( "airflow.providers.google.marketing_platform." "hooks.campaign_manager.GoogleCampaignManagerHook.get_conn" ) @mock.patch( "airflow.providers.google.marketing_platform.hooks.campaign_manager.GoogleCampaignManagerHook" "._conversions_batch_request" ) def test_conversion_batch_insert(self, batch_request_mock, get_conn_mock): conversions = [{"conversions1": "value"}, {"conversions2": "value"}] return_value = {'hasFailures': False} get_conn_mock.return_value.conversions.return_value.batchinsert.return_value.execute.return_value = ( return_value ) batch_request_mock.return_value = "batch_request_mock" result = self.hook.conversions_batch_insert( profile_id=PROFILE_ID, conversions=conversions, encryption_entity_id=ENCRYPTION_ENTITY_ID, encryption_entity_type=ENCRYPTION_ENTITY_TYPE, encryption_source=ENCRYPTION_SOURCE, ) batch_request_mock.assert_called_once_with( conversions=conversions, encryption_entity_id=ENCRYPTION_ENTITY_ID, encryption_entity_type=ENCRYPTION_ENTITY_TYPE, encryption_source=ENCRYPTION_SOURCE, kind="dfareporting#conversionsBatchInsertRequest", ) get_conn_mock.return_value.conversions.return_value.batchinsert.assert_called_once_with( profileId=PROFILE_ID, body=batch_request_mock.return_value ) assert return_value == result @mock.patch( "airflow.providers.google.marketing_platform.hooks." "campaign_manager.GoogleCampaignManagerHook.get_conn" ) @mock.patch( "airflow.providers.google.marketing_platform.hooks.campaign_manager.GoogleCampaignManagerHook" "._conversions_batch_request" ) def test_conversions_batch_update(self, batch_request_mock, get_conn_mock): conversions = [{"conversions1": "value"}, {"conversions2": "value"}] return_value = {'hasFailures': False} get_conn_mock.return_value.conversions.return_value.batchupdate.return_value.execute.return_value = ( return_value ) batch_request_mock.return_value = "batch_request_mock" result = self.hook.conversions_batch_update( profile_id=PROFILE_ID, conversions=conversions, encryption_entity_id=ENCRYPTION_ENTITY_ID, encryption_entity_type=ENCRYPTION_ENTITY_TYPE, encryption_source=ENCRYPTION_SOURCE, ) batch_request_mock.assert_called_once_with( conversions=conversions, encryption_entity_id=ENCRYPTION_ENTITY_ID, encryption_entity_type=ENCRYPTION_ENTITY_TYPE, encryption_source=ENCRYPTION_SOURCE, kind="dfareporting#conversionsBatchUpdateRequest", ) get_conn_mock.return_value.conversions.return_value.batchupdate.assert_called_once_with( profileId=PROFILE_ID, body=batch_request_mock.return_value ) assert return_value == result
{ "content_hash": "fa50197dd19c501d4c15508185a464d9", "timestamp": "", "source": "github", "line_count": 289, "max_line_length": 110, "avg_line_length": 36.89273356401384, "alnum_prop": 0.6519414743950478, "repo_name": "lyft/incubator-airflow", "id": "9eae66a9cf21d7d5c2598228d9bd59a8c41effea", "size": "11449", "binary": false, "copies": "8", "ref": "refs/heads/main", "path": "tests/providers/google/marketing_platform/hooks/test_campaign_manager.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "13715" }, { "name": "Dockerfile", "bytes": "17280" }, { "name": "HTML", "bytes": "161328" }, { "name": "JavaScript", "bytes": "25360" }, { "name": "Jinja", "bytes": "8565" }, { "name": "Jupyter Notebook", "bytes": "2933" }, { "name": "Mako", "bytes": "1339" }, { "name": "Python", "bytes": "10019710" }, { "name": "Shell", "bytes": "220780" } ], "symlink_target": "" }
using namespace boost::interprocess; typedef list<int, allocator<int, managed_heap_memory::segment_manager> > MyList; int main () { //We will create a buffer of 1000 bytes to store a list managed_heap_memory heap_memory(1000); MyList * mylist = heap_memory.construct<MyList>("MyList") (heap_memory.get_segment_manager()); //Obtain handle, that identifies the list in the buffer managed_heap_memory::handle_t list_handle = heap_memory.get_handle_from_address(mylist); //Fill list until there is no more memory in the buffer BOOST_TRY{ while(1) { mylist->insert(mylist->begin(), 0); } } BOOST_CATCH(const bad_alloc &){ //memory is full } BOOST_CATCH_END //Let's obtain the size of the list MyList::size_type old_size = mylist->size(); //<- (void)old_size; //-> //To make the list bigger, let's increase the heap buffer //in 1000 bytes more. heap_memory.grow(1000); //If memory has been reallocated, the old pointer is invalid, so //use previously obtained handle to find the new pointer. mylist = static_cast<MyList *> (heap_memory.get_address_from_handle(list_handle)); //Fill list until there is no more memory in the buffer BOOST_TRY{ while(1) { mylist->insert(mylist->begin(), 0); } } BOOST_CATCH(const bad_alloc &){ //memory is full } BOOST_CATCH_END //Let's obtain the new size of the list MyList::size_type new_size = mylist->size(); //<- (void)new_size; //-> assert(new_size > old_size); //Destroy list heap_memory.destroy_ptr(mylist); return 0; } //]
{ "content_hash": "04aaa31180fc74c1b78b04cb8bf8f779", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 91, "avg_line_length": 26.109375, "alnum_prop": 0.6307600239377619, "repo_name": "arangodb/arangodb", "id": "a0c090e46c6bd4ffd1ac21c7b94d5fd7bee18df3", "size": "2357", "binary": false, "copies": "3", "ref": "refs/heads/devel", "path": "3rdParty/boost/1.78.0/libs/interprocess/example/doc_managed_heap_memory.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "61827" }, { "name": "C", "bytes": "311036" }, { "name": "C++", "bytes": "35149373" }, { "name": "CMake", "bytes": "387268" }, { "name": "CSS", "bytes": "210549" }, { "name": "EJS", "bytes": "232160" }, { "name": "HTML", "bytes": "23114" }, { "name": "JavaScript", "bytes": "33841256" }, { "name": "LLVM", "bytes": "15003" }, { "name": "NASL", "bytes": "381737" }, { "name": "NSIS", "bytes": "47138" }, { "name": "Pascal", "bytes": "75391" }, { "name": "Perl", "bytes": "9811" }, { "name": "PowerShell", "bytes": "6806" }, { "name": "Python", "bytes": "190515" }, { "name": "SCSS", "bytes": "255542" }, { "name": "Shell", "bytes": "133576" }, { "name": "TypeScript", "bytes": "179074" }, { "name": "Yacc", "bytes": "79620" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Security.Claims; using System.Threading; using System.Threading.Tasks; using System.Transactions; using Abp.Authorization.Roles; using Abp.Dependency; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.Extensions; using Abp.Linq; using Abp.Runtime.Session; using Abp.Zero; using Castle.Core.Logging; using JetBrains.Annotations; using Microsoft.AspNetCore.Identity; namespace Abp.Authorization.Users { /// <summary> /// Represents a new instance of a persistence store for the specified user and role types. /// </summary> public class AbpUserStore<TRole, TUser> : IUserLoginStore<TUser>, IUserRoleStore<TUser>, IUserClaimStore<TUser>, IUserPasswordStore<TUser>, IUserSecurityStampStore<TUser>, IUserEmailStore<TUser>, IUserLockoutStore<TUser>, IUserPhoneNumberStore<TUser>, IUserTwoFactorStore<TUser>, IUserAuthenticationTokenStore<TUser>, IUserPermissionStore<TUser>, IQueryableUserStore<TUser>, ITransientDependency where TRole : AbpRole<TUser> where TUser : AbpUser<TUser> { public ILogger Logger { get; set; } /// <summary> /// Gets or sets the <see cref="IdentityErrorDescriber"/> for any error that occurred with the current operation. /// </summary> public IdentityErrorDescriber ErrorDescriber { get; set; } /// <summary> /// Gets or sets a flag indicating if changes should be persisted after CreateAsync, UpdateAsync and DeleteAsync are called. /// </summary> /// <value> /// True if changes should be automatically persisted, otherwise false. /// </value> public bool AutoSaveChanges { get; set; } = true; public IAbpSession AbpSession { get; set; } public IQueryable<TUser> Users => UserRepository.GetAll(); public IRepository<TUser, long> UserRepository { get; } private readonly IRepository<TRole> _roleRepository; private readonly IRepository<UserRole, long> _userRoleRepository; private readonly IAsyncQueryableExecuter _asyncQueryableExecuter; private readonly IRepository<UserLogin, long> _userLoginRepository; private readonly IRepository<UserClaim, long> _userClaimRepository; private readonly IRepository<UserPermissionSetting, long> _userPermissionSettingRepository; private readonly IUnitOfWorkManager _unitOfWorkManager; public AbpUserStore( IUnitOfWorkManager unitOfWorkManager, IRepository<TUser, long> userRepository, IRepository<TRole> roleRepository, IAsyncQueryableExecuter asyncQueryableExecuter, IRepository<UserRole, long> userRoleRepository, IRepository<UserLogin, long> userLoginRepository, IRepository<UserClaim, long> userClaimRepository, IRepository<UserPermissionSetting, long> userPermissionSettingRepository) { _unitOfWorkManager = unitOfWorkManager; UserRepository = userRepository; _roleRepository = roleRepository; _asyncQueryableExecuter = asyncQueryableExecuter; _userRoleRepository = userRoleRepository; _userLoginRepository = userLoginRepository; _userClaimRepository = userClaimRepository; _userPermissionSettingRepository = userPermissionSettingRepository; AbpSession = NullAbpSession.Instance; ErrorDescriber = new IdentityErrorDescriber(); Logger = NullLogger.Instance; } /// <summary>Saves the current store.</summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> protected Task SaveChanges(CancellationToken cancellationToken) { if (!AutoSaveChanges || _unitOfWorkManager.Current == null) { return Task.CompletedTask; } return _unitOfWorkManager.Current.SaveChangesAsync(); } /// <summary> /// Gets the user identifier for the specified <paramref name="user"/>. /// </summary> /// <param name="user">The user whose identifier should be retrieved.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the identifier for the specified <paramref name="user"/>.</returns> public virtual Task<string> GetUserIdAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); return Task.FromResult(user.Id.ToString()); } /// <summary> /// Gets the user name for the specified <paramref name="user"/>. /// </summary> /// <param name="user">The user whose name should be retrieved.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the name for the specified <paramref name="user"/>.</returns> public virtual Task<string> GetUserNameAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); return Task.FromResult(user.UserName); } /// <summary> /// Sets the given <paramref name="userName" /> for the specified <paramref name="user"/>. /// </summary> /// <param name="user">The user whose name should be set.</param> /// <param name="userName">The user name to set.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual Task SetUserNameAsync([NotNull] TUser user, string userName, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); user.UserName = userName; return Task.CompletedTask; } /// <summary> /// Gets the normalized user name for the specified <paramref name="user"/>. /// </summary> /// <param name="user">The user whose normalized name should be retrieved.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the normalized user name for the specified <paramref name="user"/>.</returns> public virtual Task<string> GetNormalizedUserNameAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); return Task.FromResult(user.NormalizedUserName); } /// <summary> /// Sets the given normalized name for the specified <paramref name="user"/>. /// </summary> /// <param name="user">The user whose name should be set.</param> /// <param name="normalizedName">The normalized name to set.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual Task SetNormalizedUserNameAsync([NotNull] TUser user, string normalizedName, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); user.NormalizedUserName = normalizedName; return Task.CompletedTask; } /// <summary> /// Creates the specified <paramref name="user"/> in the user store. /// </summary> /// <param name="user">The user to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> of the creation operation.</returns> public virtual async Task<IdentityResult> CreateAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); await UserRepository.InsertAsync(user); await SaveChanges(cancellationToken); return IdentityResult.Success; } /// <summary> /// Updates the specified <paramref name="user"/> in the user store. /// </summary> /// <param name="user">The user to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> of the update operation.</returns> public virtual async Task<IdentityResult> UpdateAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); user.ConcurrencyStamp = Guid.NewGuid().ToString(); await UserRepository.UpdateAsync(user); try { await SaveChanges(cancellationToken); } catch (AbpDbConcurrencyException ex) { Logger.Warn(ex.ToString(), ex); return IdentityResult.Failed(ErrorDescriber.ConcurrencyFailure()); } await SaveChanges(cancellationToken); return IdentityResult.Success; } /// <summary> /// Deletes the specified <paramref name="user"/> from the user store. /// </summary> /// <param name="user">The user to delete.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> of the update operation.</returns> public virtual async Task<IdentityResult> DeleteAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); await UserRepository.DeleteAsync(user); try { await SaveChanges(cancellationToken); } catch (AbpDbConcurrencyException ex) { Logger.Warn(ex.ToString(), ex); return IdentityResult.Failed(ErrorDescriber.ConcurrencyFailure()); } await SaveChanges(cancellationToken); return IdentityResult.Success; } /// <summary> /// Finds and returns a user, if any, who has the specified <paramref name="userId"/>. /// </summary> /// <param name="userId">The user ID to search for.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the user matching the specified <paramref name="userId"/> if it exists. /// </returns> public virtual Task<TUser> FindByIdAsync(string userId, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return UserRepository.FirstOrDefaultAsync(userId.To<long>()); } /// <summary> /// Finds and returns a user, if any, who has the specified normalized user name. /// </summary> /// <param name="normalizedUserName">The normalized user name to search for.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the user matching the specified <paramref name="normalizedUserName"/> if it exists. /// </returns> public virtual Task<TUser> FindByNameAsync([NotNull] string normalizedUserName, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(normalizedUserName, nameof(normalizedUserName)); return UserRepository.FirstOrDefaultAsync(u => u.NormalizedUserName == normalizedUserName); } /// <summary> /// Sets the password hash for a user. /// </summary> /// <param name="user">The user to set the password hash for.</param> /// <param name="passwordHash">The password hash to set.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual Task SetPasswordHashAsync([NotNull] TUser user, string passwordHash, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); user.Password = passwordHash; return Task.CompletedTask; } /// <summary> /// Gets the password hash for a user. /// </summary> /// <param name="user">The user to retrieve the password hash for.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that contains the password hash for the user.</returns> public virtual Task<string> GetPasswordHashAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); return Task.FromResult(user.Password); } /// <summary> /// Returns a flag indicating if the specified user has a password. /// </summary> /// <param name="user">The user to retrieve the password hash for.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> containing a flag indicating if the specified user has a password. If the /// user has a password the returned value with be true, otherwise it will be false.</returns> public virtual Task<bool> HasPasswordAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); return Task.FromResult(user.Password != null); } /// <summary> /// Adds the given <paramref name="normalizedRoleName"/> to the specified <paramref name="user"/>. /// </summary> /// <param name="user">The user to add the role to.</param> /// <param name="normalizedRoleName">The role to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual async Task AddToRoleAsync([NotNull] TUser user, [NotNull] string normalizedRoleName, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); Check.NotNull(normalizedRoleName, nameof(normalizedRoleName)); if (await IsInRoleAsync(user, normalizedRoleName, cancellationToken)) { return; } var role = await _roleRepository.FirstOrDefaultAsync(r => r.NormalizedName== normalizedRoleName); if (role == null) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Role {0} does not exist!", normalizedRoleName)); } user.Roles.Add(new UserRole(user.TenantId, user.Id, role.Id)); } /// <summary> /// Removes the given <paramref name="normalizedRoleName"/> from the specified <paramref name="user"/>. /// </summary> /// <param name="user">The user to remove the role from.</param> /// <param name="normalizedRoleName">The role to remove.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual async Task RemoveFromRoleAsync([NotNull] TUser user, [NotNull] string normalizedRoleName, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); if (string.IsNullOrWhiteSpace(normalizedRoleName)) { throw new ArgumentException(nameof(normalizedRoleName) + " can not be null or whitespace"); } if (!await IsInRoleAsync(user, normalizedRoleName, cancellationToken)) { return; } var role = await _roleRepository.FirstOrDefaultAsync(r => r.NormalizedName == normalizedRoleName); if (role == null) { return; } user.Roles.RemoveAll(r => r.RoleId == role.Id); } /// <summary> /// Retrieves the roles the specified <paramref name="user"/> is a member of. /// </summary> /// <param name="user">The user whose roles should be retrieved.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that contains the roles the user is a member of.</returns> [UnitOfWork] public virtual async Task<IList<string>> GetRolesAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); var query = from userRole in _userRoleRepository.GetAll() join role in _roleRepository.GetAll() on userRole.RoleId equals role.Id where userRole.UserId == user.Id select role.Name; return await _asyncQueryableExecuter.ToListAsync(query); } /// <summary> /// Returns a flag indicating if the specified user is a member of the give <paramref name="normalizedRoleName"/>. /// </summary> /// <param name="user">The user whose role membership should be checked.</param> /// <param name="normalizedRoleName">The role to check membership of</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> containing a flag indicating if the specified user is a member of the given group. If the /// user is a member of the group the returned value with be true, otherwise it will be false.</returns> public virtual async Task<bool> IsInRoleAsync([NotNull] TUser user, [NotNull] string normalizedRoleName, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); if (string.IsNullOrWhiteSpace(normalizedRoleName)) { throw new ArgumentException(nameof(normalizedRoleName) + " can not be null or whitespace"); } var role = await _roleRepository.FirstOrDefaultAsync(r => r.NormalizedName == normalizedRoleName); if (role == null) { return false; } await UserRepository.EnsureLoadedAsync(user, u => u.Roles, cancellationToken); return user.Roles.Any(r => r.RoleId == role.Id); } /// <summary> /// Dispose the store /// </summary> public void Dispose() { } /// <summary> /// Get the claims associated with the specified <paramref name="user"/> as an asynchronous operation. /// </summary> /// <param name="user">The user whose claims should be retrieved.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that contains the claims granted to a user.</returns> public virtual async Task<IList<Claim>> GetClaimsAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); await UserRepository.EnsureLoadedAsync(user, u => u.Claims, cancellationToken); return user.Claims.Select(c => new Claim(c.ClaimType, c.ClaimValue)).ToList(); } /// <summary> /// Adds the <paramref name="claims"/> given to the specified <paramref name="user"/>. /// </summary> /// <param name="user">The user to add the claim to.</param> /// <param name="claims">The claim to add to the user.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual async Task AddClaimsAsync([NotNull] TUser user, [NotNull] IEnumerable<Claim> claims, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); Check.NotNull(claims, nameof(claims)); await UserRepository.EnsureLoadedAsync(user, u => u.Claims, cancellationToken); foreach (var claim in claims) { user.Claims.Add(new UserClaim(user, claim)); } } /// <summary> /// Replaces the <paramref name="claim"/> on the specified <paramref name="user"/>, with the <paramref name="newClaim"/>. /// </summary> /// <param name="user">The user to replace the claim on.</param> /// <param name="claim">The claim replace.</param> /// <param name="newClaim">The new claim replacing the <paramref name="claim"/>.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual async Task ReplaceClaimAsync([NotNull] TUser user, [NotNull] Claim claim, [NotNull] Claim newClaim, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); Check.NotNull(claim, nameof(claim)); Check.NotNull(newClaim, nameof(newClaim)); await UserRepository.EnsureLoadedAsync(user, u => u.Claims, cancellationToken); var userClaims = user.Claims.Where(uc => uc.ClaimValue == claim.Value && uc.ClaimType == claim.Type); foreach (var userClaim in userClaims) { userClaim.ClaimType = claim.Type; userClaim.ClaimValue = claim.Value; } } /// <summary> /// Removes the <paramref name="claims"/> given from the specified <paramref name="user"/>. /// </summary> /// <param name="user">The user to remove the claims from.</param> /// <param name="claims">The claim to remove.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual async Task RemoveClaimsAsync([NotNull] TUser user, [NotNull] IEnumerable<Claim> claims, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); Check.NotNull(claims, nameof(claims)); await UserRepository.EnsureLoadedAsync(user, u => u.Claims, cancellationToken); foreach (var claim in claims) { user.Claims.RemoveAll(c => c.ClaimValue == claim.Value && c.ClaimType == claim.Type); } } /// <summary> /// Adds the <paramref name="login"/> given to the specified <paramref name="user"/>. /// </summary> /// <param name="user">The user to add the login to.</param> /// <param name="login">The login to add to the user.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual async Task AddLoginAsync([NotNull] TUser user, [NotNull] UserLoginInfo login, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); Check.NotNull(login, nameof(login)); await UserRepository.EnsureLoadedAsync(user, u => u.Logins, cancellationToken); user.Logins.Add(new UserLogin(user.TenantId, user.Id, login.LoginProvider, login.ProviderKey)); } /// <summary> /// Removes the <paramref name="loginProvider"/> given from the specified <paramref name="user"/>. /// </summary> /// <param name="user">The user to remove the login from.</param> /// <param name="loginProvider">The login to remove from the user.</param> /// <param name="providerKey">The key provided by the <paramref name="loginProvider"/> to identify a user.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual async Task RemoveLoginAsync([NotNull] TUser user, [NotNull] string loginProvider, [NotNull] string providerKey, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); Check.NotNull(loginProvider, nameof(loginProvider)); Check.NotNull(providerKey, nameof(providerKey)); await UserRepository.EnsureLoadedAsync(user, u => u.Logins, cancellationToken); user.Logins.RemoveAll(userLogin => userLogin.LoginProvider == loginProvider && userLogin.ProviderKey == providerKey); } /// <summary> /// Retrieves the associated logins for the specified <param ref="user"/>. /// </summary> /// <param name="user">The user whose associated logins to retrieve.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns> /// The <see cref="Task"/> for the asynchronous operation, containing a list of <see cref="UserLoginInfo"/> for the specified <paramref name="user"/>, if any. /// </returns> public virtual async Task<IList<UserLoginInfo>> GetLoginsAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); await UserRepository.EnsureLoadedAsync(user, u => u.Logins, cancellationToken); return user.Logins.Select(l => new UserLoginInfo(l.LoginProvider, l.ProviderKey, l.LoginProvider)).ToList(); } /// <summary> /// Retrieves the user associated with the specified login provider and login provider key.. /// </summary> /// <param name="loginProvider">The login provider who provided the <paramref name="providerKey"/>.</param> /// <param name="providerKey">The key provided by the <paramref name="loginProvider"/> to identify a user.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns> /// The <see cref="Task"/> for the asynchronous operation, containing the user, if any which matched the specified login provider and key. /// </returns> [UnitOfWork] public virtual Task<TUser> FindByLoginAsync([NotNull] string loginProvider, [NotNull] string providerKey, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(loginProvider, nameof(loginProvider)); Check.NotNull(providerKey, nameof(providerKey)); var query = from userLogin in _userLoginRepository.GetAll() join user in UserRepository.GetAll() on userLogin.UserId equals user.Id where userLogin.LoginProvider == loginProvider && userLogin.ProviderKey == providerKey && userLogin.TenantId == AbpSession.TenantId select user; return _asyncQueryableExecuter.FirstOrDefaultAsync(query); } /// <summary> /// Gets a flag indicating whether the email address for the specified <paramref name="user"/> has been verified, true if the email address is verified otherwise /// false. /// </summary> /// <param name="user">The user whose email confirmation status should be returned.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns> /// The task object containing the results of the asynchronous operation, a flag indicating whether the email address for the specified <paramref name="user"/> /// has been confirmed or not. /// </returns> public virtual Task<bool> GetEmailConfirmedAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); return Task.FromResult(user.IsEmailConfirmed); } /// <summary> /// Sets the flag indicating whether the specified <paramref name="user"/>'s email address has been confirmed or not. /// </summary> /// <param name="user">The user whose email confirmation status should be set.</param> /// <param name="confirmed">A flag indicating if the email address has been confirmed, true if the address is confirmed otherwise false.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The task object representing the asynchronous operation.</returns> public virtual Task SetEmailConfirmedAsync([NotNull] TUser user, bool confirmed, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); user.IsEmailConfirmed = confirmed; return Task.CompletedTask; } /// <summary> /// Sets the <paramref name="email"/> address for a <paramref name="user"/>. /// </summary> /// <param name="user">The user whose email should be set.</param> /// <param name="email">The email to set.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The task object representing the asynchronous operation.</returns> public virtual Task SetEmailAsync([NotNull] TUser user, string email, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); user.EmailAddress = email; return Task.CompletedTask; } /// <summary> /// Gets the email address for the specified <paramref name="user"/>. /// </summary> /// <param name="user">The user whose email should be returned.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The task object containing the results of the asynchronous operation, the email address for the specified <paramref name="user"/>.</returns> public virtual Task<string> GetEmailAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); return Task.FromResult(user.EmailAddress); } /// <summary> /// Returns the normalized email for the specified <paramref name="user"/>. /// </summary> /// <param name="user">The user whose email address to retrieve.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns> /// The task object containing the results of the asynchronous lookup operation, the normalized email address if any associated with the specified user. /// </returns> public virtual Task<string> GetNormalizedEmailAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); return Task.FromResult(user.NormalizedEmailAddress); } /// <summary> /// Sets the normalized email for the specified <paramref name="user"/>. /// </summary> /// <param name="user">The user whose email address to set.</param> /// <param name="normalizedEmail">The normalized email to set for the specified <paramref name="user"/>.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The task object representing the asynchronous operation.</returns> public virtual Task SetNormalizedEmailAsync([NotNull] TUser user, string normalizedEmail, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); user.NormalizedEmailAddress = normalizedEmail; return Task.CompletedTask; } /// <summary> /// Gets the user, if any, associated with the specified, normalized email address. /// </summary> /// <param name="normalizedEmail">The normalized email address to return the user for.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns> /// The task object containing the results of the asynchronous lookup operation, the user if any associated with the specified normalized email address. /// </returns> public virtual Task<TUser> FindByEmailAsync(string normalizedEmail, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return UserRepository.FirstOrDefaultAsync(u => u.NormalizedEmailAddress == normalizedEmail); } /// <summary> /// Gets the last <see cref="DateTimeOffset"/> a user's last lockout expired, if any. /// Any time in the past should be indicates a user is not locked out. /// </summary> /// <param name="user">The user whose lockout date should be retrieved.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns> /// A <see cref="Task{TResult}"/> that represents the result of the asynchronous query, a <see cref="DateTimeOffset"/> containing the last time /// a user's lockout expired, if any. /// </returns> public virtual Task<DateTimeOffset?> GetLockoutEndDateAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); if (!user.LockoutEndDateUtc.HasValue) { return Task.FromResult<DateTimeOffset?>(null); } var lockoutEndDate = DateTime.SpecifyKind(user.LockoutEndDateUtc.Value, DateTimeKind.Utc); return Task.FromResult<DateTimeOffset?>(new DateTimeOffset(lockoutEndDate)); } /// <summary> /// Locks out a user until the specified end date has passed. Setting a end date in the past immediately unlocks a user. /// </summary> /// <param name="user">The user whose lockout date should be set.</param> /// <param name="lockoutEnd">The <see cref="DateTimeOffset"/> after which the <paramref name="user"/>'s lockout should end.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual Task SetLockoutEndDateAsync([NotNull] TUser user, DateTimeOffset? lockoutEnd, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); user.LockoutEndDateUtc = lockoutEnd?.UtcDateTime; return Task.CompletedTask; } /// <summary> /// Records that a failed access has occurred, incrementing the failed access count. /// </summary> /// <param name="user">The user whose cancellation count should be incremented.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the incremented failed access count.</returns> public virtual Task<int> IncrementAccessFailedCountAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); user.AccessFailedCount++; return Task.FromResult(user.AccessFailedCount); } /// <summary> /// Resets a user's failed access count. /// </summary> /// <param name="user">The user whose failed access count should be reset.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>This is typically called after the account is successfully accessed.</remarks> public virtual Task ResetAccessFailedCountAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); user.AccessFailedCount = 0; return Task.CompletedTask; } /// <summary> /// Retrieves the current failed access count for the specified <paramref name="user"/>.. /// </summary> /// <param name="user">The user whose failed access count should be retrieved.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the failed access count.</returns> public virtual Task<int> GetAccessFailedCountAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); return Task.FromResult(user.AccessFailedCount); } /// <summary> /// Retrieves a flag indicating whether user lockout can enabled for the specified user. /// </summary> /// <param name="user">The user whose ability to be locked out should be returned.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, true if a user can be locked out, otherwise false. /// </returns> public virtual Task<bool> GetLockoutEnabledAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); return Task.FromResult(user.IsLockoutEnabled); } /// <summary> /// Set the flag indicating if the specified <paramref name="user"/> can be locked out.. /// </summary> /// <param name="user">The user whose ability to be locked out should be set.</param> /// <param name="enabled">A flag indicating if lock out can be enabled for the specified <paramref name="user"/>.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual Task SetLockoutEnabledAsync([NotNull] TUser user, bool enabled, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); user.IsLockoutEnabled = enabled; return Task.CompletedTask; } /// <summary> /// Sets the telephone number for the specified <paramref name="user"/>. /// </summary> /// <param name="user">The user whose telephone number should be set.</param> /// <param name="phoneNumber">The telephone number to set.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual Task SetPhoneNumberAsync([NotNull] TUser user, string phoneNumber, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); user.PhoneNumber = phoneNumber; return Task.CompletedTask; } /// <summary> /// Gets the telephone number, if any, for the specified <paramref name="user"/>. /// </summary> /// <param name="user">The user whose telephone number should be retrieved.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the user's telephone number, if any.</returns> public virtual Task<string> GetPhoneNumberAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); return Task.FromResult(user.PhoneNumber); } /// <summary> /// Gets a flag indicating whether the specified <paramref name="user"/>'s telephone number has been confirmed. /// </summary> /// <param name="user">The user to return a flag for, indicating whether their telephone number is confirmed.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, returning true if the specified <paramref name="user"/> has a confirmed /// telephone number otherwise false. /// </returns> public virtual Task<bool> GetPhoneNumberConfirmedAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); return Task.FromResult(user.IsPhoneNumberConfirmed); } /// <summary> /// Sets a flag indicating if the specified <paramref name="user"/>'s phone number has been confirmed.. /// </summary> /// <param name="user">The user whose telephone number confirmation status should be set.</param> /// <param name="confirmed">A flag indicating whether the user's telephone number has been confirmed.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual Task SetPhoneNumberConfirmedAsync([NotNull] TUser user, bool confirmed, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); user.IsPhoneNumberConfirmed = confirmed; return Task.CompletedTask; } /// <summary> /// Sets the provided security <paramref name="stamp"/> for the specified <paramref name="user"/>. /// </summary> /// <param name="user">The user whose security stamp should be set.</param> /// <param name="stamp">The security stamp to set.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual Task SetSecurityStampAsync([NotNull] TUser user, string stamp, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); user.SecurityStamp = stamp; return Task.CompletedTask; } /// <summary> /// Get the security stamp for the specified <paramref name="user" />. /// </summary> /// <param name="user">The user whose security stamp should be set.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the security stamp for the specified <paramref name="user"/>.</returns> public virtual Task<string> GetSecurityStampAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); return Task.FromResult(user.SecurityStamp); } /// <summary> /// Sets a flag indicating whether the specified <paramref name="user"/> has two factor authentication enabled or not, /// as an asynchronous operation. /// </summary> /// <param name="user">The user whose two factor authentication enabled status should be set.</param> /// <param name="enabled">A flag indicating whether the specified <paramref name="user"/> has two factor authentication enabled.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual Task SetTwoFactorEnabledAsync([NotNull] TUser user, bool enabled, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); user.IsTwoFactorEnabled = enabled; return Task.CompletedTask; } /// <summary> /// Returns a flag indicating whether the specified <paramref name="user"/> has two factor authentication enabled or not, /// as an asynchronous operation. /// </summary> /// <param name="user">The user whose two factor authentication enabled status should be set.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing a flag indicating whether the specified /// <paramref name="user"/> has two factor authentication enabled or not. /// </returns> public virtual Task<bool> GetTwoFactorEnabledAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); return Task.FromResult(user.IsTwoFactorEnabled); } /// <summary> /// Retrieves all users with the specified claim. /// </summary> /// <param name="claim">The claim whose users should be retrieved.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns> /// The <see cref="Task"/> contains a list of users, if any, that contain the specified claim. /// </returns> [UnitOfWork] public virtual async Task<IList<TUser>> GetUsersForClaimAsync([NotNull] Claim claim, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(claim, nameof(claim)); var query = from userclaims in _userClaimRepository.GetAll() join user in UserRepository.GetAll() on userclaims.UserId equals user.Id where userclaims.ClaimValue == claim.Value && userclaims.ClaimType == claim.Type && userclaims.TenantId == AbpSession.TenantId select user; return await _asyncQueryableExecuter.ToListAsync(query); } /// <summary> /// Retrieves all users in the specified role. /// </summary> /// <param name="normalizedRoleName">The role whose users should be retrieved.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns> /// The <see cref="Task"/> contains a list of users, if any, that are in the specified role. /// </returns> [UnitOfWork] public virtual async Task<IList<TUser>> GetUsersInRoleAsync([NotNull] string normalizedRoleName, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (string.IsNullOrEmpty(normalizedRoleName)) { throw new ArgumentNullException(nameof(normalizedRoleName)); } var role = await _roleRepository.FirstOrDefaultAsync(r => r.NormalizedName == normalizedRoleName); if (role == null) { return new List<TUser>(); } var query = from userrole in _userRoleRepository.GetAll() join user in UserRepository.GetAll() on userrole.UserId equals user.Id where userrole.RoleId.Equals(role.Id) select user; return await _asyncQueryableExecuter.ToListAsync(query); } /// <summary> /// Sets the token value for a particular user. /// </summary> /// <param name="user">The user.</param> /// <param name="loginProvider">The authentication provider for the token.</param> /// <param name="name">The name of the token.</param> /// <param name="value">The value of the token.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual async Task SetTokenAsync([NotNull] TUser user, string loginProvider, string name, string value, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); await UserRepository.EnsureLoadedAsync(user, u => u.Tokens, cancellationToken); var token = user.Tokens.FirstOrDefault(t => t.LoginProvider == loginProvider && t.Name == name); if (token == null) { user.Tokens.Add(new UserToken(user, loginProvider, name, value)); } else { token.Value = value; } } /// <summary> /// Deletes a token for a user. /// </summary> /// <param name="user">The user.</param> /// <param name="loginProvider">The authentication provider for the token.</param> /// <param name="name">The name of the token.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public async Task RemoveTokenAsync(TUser user, string loginProvider, string name, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); await UserRepository.EnsureLoadedAsync(user, u => u.Tokens, cancellationToken); user.Tokens.RemoveAll(t => t.LoginProvider == loginProvider && t.Name == name); } /// <summary> /// Returns the token value. /// </summary> /// <param name="user">The user.</param> /// <param name="loginProvider">The authentication provider for the token.</param> /// <param name="name">The name of the token.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public async Task<string> GetTokenAsync(TUser user, string loginProvider, string name, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(user, nameof(user)); await UserRepository.EnsureLoadedAsync(user, u => u.Tokens, cancellationToken); return user.Tokens.FirstOrDefault(t => t.LoginProvider == loginProvider && t.Name == name)?.Value; } /// <summary> /// Tries to find a user with user name or email address in current tenant. /// </summary> /// <param name="userNameOrEmailAddress">User name or email address</param> /// <returns>User or null</returns> public virtual async Task<TUser> FindByNameOrEmailAsync(string userNameOrEmailAddress) { return await UserRepository.FirstOrDefaultAsync( user => (user.UserName == userNameOrEmailAddress || user.EmailAddress == userNameOrEmailAddress) ); } /// <summary> /// Tries to find a user with user name or email address in given tenant. /// </summary> /// <param name="tenantId">Tenant Id</param> /// <param name="userNameOrEmailAddress">User name or email address</param> /// <returns>User or null</returns> [UnitOfWork] public virtual async Task<TUser> FindByNameOrEmailAsync(int? tenantId, string userNameOrEmailAddress) { using (_unitOfWorkManager.Current.SetTenantId(tenantId)) { return await FindByNameOrEmailAsync(userNameOrEmailAddress); } } public virtual async Task<TUser> FindAsync(UserLoginInfo login) { var userLogin = await _userLoginRepository.FirstOrDefaultAsync( ul => ul.LoginProvider == login.LoginProvider && ul.ProviderKey == login.ProviderKey ); if (userLogin == null) { return null; } return await UserRepository.FirstOrDefaultAsync(u => u.Id == userLogin.UserId); } [UnitOfWork] public virtual Task<List<TUser>> FindAllAsync(UserLoginInfo login) { var query = from userLogin in _userLoginRepository.GetAll() join user in UserRepository.GetAll() on userLogin.UserId equals user.Id where userLogin.LoginProvider == login.LoginProvider && userLogin.ProviderKey == login.ProviderKey select user; return Task.FromResult(query.ToList()); } [UnitOfWork] public virtual Task<TUser> FindAsync(int? tenantId, UserLoginInfo login) { using (_unitOfWorkManager.Current.SetTenantId(tenantId)) { var query = from userLogin in _userLoginRepository.GetAll() join user in UserRepository.GetAll() on userLogin.UserId equals user.Id where userLogin.LoginProvider == login.LoginProvider && userLogin.ProviderKey == login.ProviderKey select user; return Task.FromResult(query.FirstOrDefault()); } } public async Task<string> GetUserNameFromDatabaseAsync(long userId) { //note: This workaround will not be needed after fixing https://github.com/aspnetboilerplate/aspnetboilerplate/issues/1828 var outerUow = _unitOfWorkManager.Current; using (var uow = _unitOfWorkManager.Begin(new UnitOfWorkOptions { Scope = TransactionScopeOption.RequiresNew, IsTransactional = false, IsolationLevel = IsolationLevel.ReadUncommitted })) { if (outerUow != null) { _unitOfWorkManager.Current.SetTenantId(outerUow.GetTenantId()); } var user = await UserRepository.GetAsync(userId); await uow.CompleteAsync(); return user.UserName; } } public virtual async Task AddPermissionAsync(TUser user, PermissionGrantInfo permissionGrant) { if (await HasPermissionAsync(user.Id, permissionGrant)) { return; } await _userPermissionSettingRepository.InsertAsync( new UserPermissionSetting { TenantId = user.TenantId, UserId = user.Id, Name = permissionGrant.Name, IsGranted = permissionGrant.IsGranted }); } public virtual async Task RemovePermissionAsync(TUser user, PermissionGrantInfo permissionGrant) { await _userPermissionSettingRepository.DeleteAsync( permissionSetting => permissionSetting.UserId == user.Id && permissionSetting.Name == permissionGrant.Name && permissionSetting.IsGranted == permissionGrant.IsGranted ); } public virtual async Task<IList<PermissionGrantInfo>> GetPermissionsAsync(long userId) { return (await _userPermissionSettingRepository.GetAllListAsync(p => p.UserId == userId)) .Select(p => new PermissionGrantInfo(p.Name, p.IsGranted)) .ToList(); } public virtual async Task<bool> HasPermissionAsync(long userId, PermissionGrantInfo permissionGrant) { return await _userPermissionSettingRepository.FirstOrDefaultAsync( p => p.UserId == userId && p.Name == permissionGrant.Name && p.IsGranted == permissionGrant.IsGranted ) != null; } public virtual async Task RemoveAllPermissionSettingsAsync(TUser user) { await _userPermissionSettingRepository.DeleteAsync(s => s.UserId == user.Id); } } }
{ "content_hash": "063b72379c2ab693fde01b9dd94c4214", "timestamp": "", "source": "github", "line_count": 1289, "max_line_length": 200, "avg_line_length": 50.86501163692785, "alnum_prop": 0.6475711126363151, "repo_name": "ilyhacker/module-zero", "id": "66f12989b15d60d1627572d34fa5d05aee0b5136", "size": "65565", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "src/Abp.ZeroCore/Authorization/Users/AbpUserStore.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "196" }, { "name": "C#", "bytes": "946280" }, { "name": "PowerShell", "bytes": "1066" } ], "symlink_target": "" }
export class LocalStorageHelper { public static ReadLocalStorageValue(key: string, defaultValue: number) { if (typeof Storage !== "undefined" && localStorage.getItem(key) !== null) { return parseInt(localStorage.getItem(key)!); } return defaultValue; } }
{ "content_hash": "9bc2492199ac3e2cfce664eabd0988a0", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 83, "avg_line_length": 34.333333333333336, "alnum_prop": 0.6245954692556634, "repo_name": "RaananW/Babylon.js", "id": "d646452448412cc225c657badd749ff43989e40c", "size": "309", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "packages/tools/sandbox/src/tools/localStorageHelper.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HLSL", "bytes": "813656" }, { "name": "HTML", "bytes": "91021" }, { "name": "JavaScript", "bytes": "946967" }, { "name": "Roff", "bytes": "276786" }, { "name": "SCSS", "bytes": "283614" }, { "name": "TypeScript", "bytes": "16524445" } ], "symlink_target": "" }
This application makes use of the following third party libraries: ## SlidingTabbarController Copyright (c) 2016 Yunus Eren Guzel <exculuber@gmail.com> 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. Generated by CocoaPods - http://cocoapods.org
{ "content_hash": "d27ac4fab1f4a141cab22c2a886f1fc1", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 77, "avg_line_length": 49, "alnum_prop": 0.8048979591836735, "repo_name": "yunuserenguzel/SlidingTabbarController", "id": "7a12f193709334a1b4841330685d3755d3c9ddea", "size": "1244", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Example/Pods/Target Support Files/Pods-SlidingTabbarController_Tests/Pods-SlidingTabbarController_Tests-acknowledgements.markdown", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "923" }, { "name": "Swift", "bytes": "14505" } ], "symlink_target": "" }
<!DOCTYPE html> <html xmlns:msxsl="urn:schemas-microsoft-com:xslt"> <head> <meta content="en-us" http-equiv="Content-Language" /> <meta content="text/html; charset=utf-16" http-equiv="Content-Type" /> <title _locid="PortabilityAnalysis0">.NET Portability Report</title> <style> /* Body style, for the entire document */ body { background: #F3F3F4; color: #1E1E1F; font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 0; margin: 0; } /* Header1 style, used for the main title */ h1 { padding: 10px 0px 10px 10px; font-size: 21pt; background-color: #E2E2E2; border-bottom: 1px #C1C1C2 solid; color: #201F20; margin: 0; font-weight: normal; } /* Header2 style, used for "Overview" and other sections */ h2 { font-size: 18pt; font-weight: normal; padding: 15px 0 5px 0; margin: 0; } /* Header3 style, used for sub-sections, such as project name */ h3 { font-weight: normal; font-size: 15pt; margin: 0; padding: 15px 0 5px 0; background-color: transparent; } h4 { font-weight: normal; font-size: 12pt; margin: 0; padding: 0 0 0 0; background-color: transparent; } /* Color all hyperlinks one color */ a { color: #1382CE; } /* Paragraph text (for longer informational messages) */ p { font-size: 10pt; } /* Table styles */ table { border-spacing: 0 0; border-collapse: collapse; font-size: 10pt; } table th { background: #E7E7E8; text-align: left; text-decoration: none; font-weight: normal; padding: 3px 6px 3px 6px; } table td { vertical-align: top; padding: 3px 6px 5px 5px; margin: 0px; border: 1px solid #E7E7E8; background: #F7F7F8; } .NoBreakingChanges { color: darkgreen; font-weight:bold; } .FewBreakingChanges { color: orange; font-weight:bold; } .ManyBreakingChanges { color: red; font-weight:bold; } .BreakDetails { margin-left: 30px; } .CompatMessage { font-style: italic; font-size: 10pt; } .GoodMessage { color: darkgreen; } /* Local link is a style for hyperlinks that link to file:/// content, there are lots so color them as 'normal' text until the user mouse overs */ .localLink { color: #1E1E1F; background: #EEEEED; text-decoration: none; } .localLink:hover { color: #1382CE; background: #FFFF99; text-decoration: none; } /* Center text, used in the over views cells that contain message level counts */ .textCentered { text-align: center; } /* The message cells in message tables should take up all avaliable space */ .messageCell { width: 100%; } /* Padding around the content after the h1 */ #content { padding: 0px 12px 12px 12px; } /* The overview table expands to width, with a max width of 97% */ #overview table { width: auto; max-width: 75%; } /* The messages tables are always 97% width */ #messages table { width: 97%; } /* All Icons */ .IconSuccessEncoded, .IconInfoEncoded, .IconWarningEncoded, .IconErrorEncoded { min-width: 18px; min-height: 18px; background-repeat: no-repeat; background-position: center; } /* Success icon encoded */ .IconSuccessEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconSuccess#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABPElEQVR4Xp1Tv0vDUBi8FqeA4NpBcBLcWnQSApncOnTo4FSnjP0DsnXpH5CxiwbHDg4Zuj4oOEXiJgiC4FDcCkLWmIMc1Pfw+eMgQ77v3Xf3Pe51YKGqqisAEwCR1TIAsiAIblSo6xrdHeJR85Xle3mdmCQKb0PsfqyxxzM8K15HZADl/H5+sHpZwYfxyRjTs+kWwKBx8yoHd2mRiuzF8mkJniWH/13u3Fjrs/EdhsdDFHGB/DLXEJBDLh1MWPAhPo1BLB4WX5yQywHR+m3tVe/t97D52CB/ziG0nIgD/qDuYg8WuCcVZ2YGwlJ3YDugkpR/VNcAEx6GEKhERSr71FuO4YCM4XBdwKvecjIlkSnsO0Hyp/GxSeJAdzBKzpOtnPwyyiPdAZhpZptT04tU+zk7s8czeges//s5C5+CwqrR4/gw+AAAAABJRU5ErkJggg==); } /* Information icon encoded */ .IconInfoEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconInformation#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABHElEQVR4Xs2TsUoDQRRF7wwoziokjZUKadInhdhukR9YP8DMX1hYW+QvdsXa/QHBbcXC7W0CamWTQnclFutceIQJwwaWNLlwm5k5d94M76mmaeCrrmsLYOocY12FcxZFUeozCqKqqgYA8uevv1H6VuPxcwlfk5N92KHBxfFeCSAxxswlYAW/Xr989x/mv9gkhtyMDhcAxgzRsp7flj8B/HF1RsMXq+NZMkopaHe7lbKxQUEIGbKsYNoGn969060hZBkQex/W8oRQwsQaW2o3Ago2SVcJUzAgY3N0lTCZZm+zPS8HB51gMmS1DEYyOz9acKO1D8JWTlafKIMxdhvlfdyT94Vv5h7P8Ky7nQzACmhvKq3zk3PjW9asz9D/1oigecsioooAAAAASUVORK5CYII=); } /* Warning icon encoded */ .IconWarningEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconWarning#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAx0lEQVR4XpWSMQ7CMAxFf4xAyBMLCxMrO8dhaBcuwdCJS3RJBw7SA/QGTCxdWJgiQYWKXJWKIXHIlyw5lqr34tQgEOdcBsCOx5yZK3hCCKdYXneQkh4pEfqzLfu+wVDSyyzFoJjfz9NB+pAF+eizx2Vruts0k15mPgvS6GYvpVtQhB61IB/dk6AF6fS4Ben0uIX5odtFe8Q/eW1KvFeH4e8khT6+gm5B+t3juyDt7n0jpe+CANTd+oTUjN/U3yVaABnSUjFz/gFq44JaVSCXeQAAAABJRU5ErkJggg==); } /* Error icon encoded */ .IconErrorEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconError#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABQElEQVR4XqWTvUoEQRCE6wYPZUA80AfwAQz23uCMjA7MDRQEIzPBVEyNTQUFIw00vcQTTMzuAh/AxEQQT8HF/3G/oGGnEUGuoNnd6qoZuqltyKEsyzVJq5I6rnUp6SjGeGhESikzzlc1eL7opfuVbrqbU1Zw9NCgtQMaZpY0eNnaaL2fHusvTK5vKu7sjSS1Y4y3QUA6K3e3Mau5UFDyMP7tYF9o8cAHZv68vipoIJg971PZIZ5HiwdvYGGvFVFHmGmZ2MxwmQYPXubPl9Up0tfoMQGetXd6mRbvhBw+boZ6WF7Mbv1+GsHRk0fQmPAH1GfmZirbCfDJ61tw3Px8/8pZsPAG4jlVhcPgZ7adwNWBB68lkRQWFiTgFlbnLY3DGGM7izIJIyT/jjIvEJw6fdJTc6krDzh6aMwMP9bvDH4ADSsa9uSWVJkAAAAASUVORK5CYII=); } </style> </head> <body> <h1 _locid="PortabilityReport">.NET Portability Report</h1> <div id="content"> <div id="submissionId" style="font-size:8pt;"> <p> <i> Submission Id&nbsp; 935b4cdb-6a8a-4201-a9ab-cfd228084d67 </i> </p> </div> <h2 _locid="SummaryTitle"> <a name="Portability Summary"></a>Portability Summary </h2> <div id="summary"> <table> <tbody> <tr> <th>Assembly</th> <th>ASP.NET 5,Version=v1.0</th> <th>Windows,Version=v8.1</th> <th>.NET Framework,Version=v4.6</th> <th>Windows Phone,Version=v8.1</th> </tr> <tr> <td><strong><a href="#SVG.Forms.Plugin.Abstractions">SVG.Forms.Plugin.Abstractions</a></strong></td> <td class="text-center">100.00 %</td> <td class="text-center">100.00 %</td> <td class="text-center">100.00 %</td> <td class="text-center">100.00 %</td> </tr> </tbody> </table> </div> <div id="details"> </div> </div> </body> </html>
{ "content_hash": "e13d732cce8c44be4a690802c9e8d99d", "timestamp": "", "source": "github", "line_count": 240, "max_line_length": 562, "avg_line_length": 40.30416666666667, "alnum_prop": 0.5742789207071229, "repo_name": "kuhlenh/port-to-core", "id": "62e43d150e513d3fadd81064b4394b60f47397a2", "size": "9673", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "Reports/xa/xam.plugins.forms.svg.1.0.0.24/SVG.Forms.Plugin.Abstractions-wp8.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2323514650" } ], "symlink_target": "" }
import {Bounds} from '../../geometry/Bounds'; import {LatLng} from '../LatLng'; import {LatLngBounds} from '../LatLngBounds'; import * as Util from '../../core/Util'; /* * @namespace CRS * @crs L.CRS.Base * Object that defines coordinate reference systems for projecting * geographical points into pixel (screen) coordinates and back (and to * coordinates in other units for [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services). See * [spatial reference system](https://en.wikipedia.org/wiki/Spatial_reference_system). * * Leaflet defines the most usual CRSs by default. If you want to use a * CRS not defined by default, take a look at the * [Proj4Leaflet](https://github.com/kartena/Proj4Leaflet) plugin. * * Note that the CRS instances do not inherit from Leaflet's `Class` object, * and can't be instantiated. Also, new classes can't inherit from them, * and methods can't be added to them with the `include` function. */ export var CRS = { // @method latLngToPoint(latlng: LatLng, zoom: Number): Point // Projects geographical coordinates into pixel coordinates for a given zoom. latLngToPoint: function (latlng, zoom) { var projectedPoint = this.projection.project(latlng), scale = this.scale(zoom); return this.transformation._transform(projectedPoint, scale); }, // @method pointToLatLng(point: Point, zoom: Number): LatLng // The inverse of `latLngToPoint`. Projects pixel coordinates on a given // zoom into geographical coordinates. pointToLatLng: function (point, zoom) { var scale = this.scale(zoom), untransformedPoint = this.transformation.untransform(point, scale); return this.projection.unproject(untransformedPoint); }, // @method project(latlng: LatLng): Point // Projects geographical coordinates into coordinates in units accepted for // this CRS (e.g. meters for EPSG:3857, for passing it to WMS services). project: function (latlng) { return this.projection.project(latlng); }, // @method unproject(point: Point): LatLng // Given a projected coordinate returns the corresponding LatLng. // The inverse of `project`. unproject: function (point) { return this.projection.unproject(point); }, // @method scale(zoom: Number): Number // Returns the scale used when transforming projected coordinates into // pixel coordinates for a particular zoom. For example, it returns // `256 * 2^zoom` for Mercator-based CRS. scale: function (zoom) { return 256 * Math.pow(2, zoom); }, // @method zoom(scale: Number): Number // Inverse of `scale()`, returns the zoom level corresponding to a scale // factor of `scale`. zoom: function (scale) { return Math.log(scale / 256) / Math.LN2; }, // @method getProjectedBounds(zoom: Number): Bounds // Returns the projection's bounds scaled and transformed for the provided `zoom`. getProjectedBounds: function (zoom) { if (this.infinite) { return null; } var b = this.projection.bounds, s = this.scale(zoom), min = this.transformation.transform(b.min, s), max = this.transformation.transform(b.max, s); return new Bounds(min, max); }, // @method distance(latlng1: LatLng, latlng2: LatLng): Number // Returns the distance between two geographical coordinates. // @property code: String // Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`) // // @property wrapLng: Number[] // An array of two numbers defining whether the longitude (horizontal) coordinate // axis wraps around a given range and how. Defaults to `[-180, 180]` in most // geographical CRSs. If `undefined`, the longitude axis does not wrap around. // // @property wrapLat: Number[] // Like `wrapLng`, but for the latitude (vertical) axis. // wrapLng: [min, max], // wrapLat: [min, max], // @property infinite: Boolean // If true, the coordinate space will be unbounded (infinite in both axes) infinite: false, // @method wrapLatLng(latlng: LatLng): LatLng // Returns a `LatLng` where lat and lng has been wrapped according to the // CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds. wrapLatLng: function (latlng) { var lng = this.wrapLng ? Util.wrapNum(latlng.lng, this.wrapLng, true) : latlng.lng, lat = this.wrapLat ? Util.wrapNum(latlng.lat, this.wrapLat, true) : latlng.lat, alt = latlng.alt; return new LatLng(lat, lng, alt); }, // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds // Returns a `LatLngBounds` with the same size as the given one, ensuring // that its center is within the CRS's bounds. // Only accepts actual `L.LatLngBounds` instances, not arrays. wrapLatLngBounds: function (bounds) { var center = bounds.getCenter(), newCenter = this.wrapLatLng(center), latShift = center.lat - newCenter.lat, lngShift = center.lng - newCenter.lng; if (latShift === 0 && lngShift === 0) { return bounds; } var sw = bounds.getSouthWest(), ne = bounds.getNorthEast(), newSw = new LatLng(sw.lat - latShift, sw.lng - lngShift), newNe = new LatLng(ne.lat - latShift, ne.lng - lngShift); return new LatLngBounds(newSw, newNe); } };
{ "content_hash": "991c90191a5204ae220b0a92903d301a", "timestamp": "", "source": "github", "line_count": 139, "max_line_length": 101, "avg_line_length": 37.992805755395686, "alnum_prop": 0.6877485324749101, "repo_name": "equinton/prototypephp", "id": "bfbdae6ac9da4f9af94ac24edbea9b46f8a2e5cf", "size": "5281", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "display/node_modules/leaflet/src/geo/crs/CRS.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "22" }, { "name": "CSS", "bytes": "245930" }, { "name": "HTML", "bytes": "6971441" }, { "name": "JavaScript", "bytes": "531684" }, { "name": "PHP", "bytes": "698384" }, { "name": "SCSS", "bytes": "80205" }, { "name": "Shell", "bytes": "14526" }, { "name": "Smarty", "bytes": "73392" } ], "symlink_target": "" }
import java.awt.*; import java.awt.event.*; /** * This class implements both the view and the controller for the * cat chasing application. Pay particular attention to * How the model is registered with this class so that the * controller code can notify the model about the mouse and * so that the model can notify the view of cat movements * How repaint is used to notify the windowing system of the * portion of the view that must be redrawn * How mouse movement events are enabled. * How mouse movement events are received. */ public class CatChase_Comp extends Component implements CatView { /** This contains the loaded image of the cat. */ Image cat; /** This is a pointer to the model for the cat. This object should * be notified every time the mouse moves. */ CatModel theModel; /** This constructor has the model that this view should use. */ public CatChase_Comp(CatModel newModel){ theModel = newModel; //Remember the model theModel.addCatViewListener(this); //The view is registering itself with // the model so that it will inform // the view whenever the cat moves. cat = getImage("c:\\bryan's files\\programs\\java\\BuzzWorld\\examples\\Cat.gif"); enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK); // This tells Java that this component // should receive Mouse Motion events } private Image getImage(String imageName){ Toolkit TK = Toolkit.getDefaultToolkit(); Image im = TK.getImage(imageName); MediaTracker track = new MediaTracker(this); track.addImage(im,0); try { track.waitForID(0); } catch(Exception e) {} return im; } /** * This method is required by the CatView interface. This is the method * that the model calls whenever the cat moves. The model stores the old * cat location. The new cat location is at (X,Y). * * Note that there is no drawing performed in this method. This method * simply informs the windowing system of those parts of the view * that must be repainted. All drawing is in the paint method. * * Note that the location of the cat is at its center. Drawing the cat image, * however, requires the top left position. */ public void catMoved(int X, int Y){ Point oldLoc = theModel.getCatLoc(); int catWidth = cat.getWidth(this); int catHeight = cat.getHeight(this); int catX = oldLoc.x-catWidth/2; int catY = oldLoc.y-catHeight/2; repaint(catX,catY,catWidth,catHeight); // This tells the windowing // system that the old location of the cat must be repainted // because the cat has moved. catX = X-catWidth/2; catY = Y-catHeight/2; repaint(catX,catY,catWidth,catHeight); // This tells the windowing system // that the new location of the cat must be repainted. } /** This method draws the cat in its new location. * This method will first retrieve the location of the cat from the * cat model. */ public void paint(Graphics g) { Point catLoc = theModel.getCatLoc(); g.drawImage(cat, // image to be drawn catLoc.x-cat.getWidth(this)/2, // left side of the image catLoc.y-cat.getHeight(this)/2, // top of the image this); // image observer to be used if this // image was not loaded previously. // Note that if the image is not already loaded, then the width // and height will be wrong. The getImage method makes sure that // the image is completely loaded before continuing. } /** This method is the only controller code found in this application. * Java AWT will call this method whenever the mouse is moved inside of * this component. This method is only called, however, if mouse motion * events have been enabled for this component. See the constructor for * this class to see how such events are enabled. */ public void processMouseMotionEvent(MouseEvent evnt) { Point mouseLoc = evnt.getPoint(); theModel.mousePlace(mouseLoc.x,mouseLoc.y); } }
{ "content_hash": "990a0f784b76303f964743c5de085389", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 86, "avg_line_length": 37.922330097087375, "alnum_prop": 0.7145417306707629, "repo_name": "HintonBR/scratch", "id": "6ad86989a4cca3b97543992f9c65e7e7c60304bc", "size": "3906", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "College Programs/User Interfaces game/BuzzWorld2/Examples/CatChase_Comp.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "947" }, { "name": "C#", "bytes": "5882" }, { "name": "Go", "bytes": "212" }, { "name": "HTML", "bytes": "61" }, { "name": "Scala", "bytes": "866" }, { "name": "TypeScript", "bytes": "101" } ], "symlink_target": "" }
<div class="modal" ng-controller="FlowableEscalationDefinitionsPopupCtrl"> <div class="modal-dialog modal-wide"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true" ng-click="close()">&times;</button> <h2>{{'PROPERTY.PROPERTY.EDIT.TITLE' | translate}} "{{property.title | translate}}"</h2> </div> <div class="modal-body"> <div class="row row-no-gutter"> <div class="col-xs-8"> <div ng-if="translationsRetrieved" class="kis-listener-grid" ui-grid="gridOptions" ui-grid-selection></div> <div class="pull-right"> <div class="btn-group"> <a class="btn btn-icon btn-lg" rel="tooltip" data-title="{{ACTION.ADD | translate}}" data-placement="bottom" data-original-title="" title="" ng-click="addNewEscalationDefinition()"><i class="glyphicon glyphicon-plus"></i></a> <a class="btn btn-icon btn-lg" rel="tooltip" data-title="{{ACTION.REMOVE | translate}}" data-placement="bottom" data-original-title="" title="" ng-click="removeEscalationDefinition()"><i class="glyphicon glyphicon-minus"></i></a> </div> </div> </div> <div class="col-xs-4" ng-show="selectedEscalationDefinition"> <div class="form-group"> <label>{{'PROPERTY.ESCALATIONDEFINITIONS.ID' | translate}}</label> <input type="text" class="form-control" ng-model="selectedEscalationDefinition.id"> </div> <div class="form-group"> <label>{{'PROPERTY.ESCALATIONDEFINITIONS.NAME' | translate}}</label> <input type="text" class="form-control" ng-model="selectedEscalationDefinition.name"> </div> </div> </div> </div> <div class="modal-footer"> <button ng-click="cancel()" class="btn btn-primary" translate>ACTION.CANCEL</button> <button ng-click="save()" class="btn btn-primary" translate>ACTION.SAVE</button> </div> </div> </div> </div>
{ "content_hash": "5c0c821163b6e81dcee287a92dbde7af", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 258, "avg_line_length": 49.83673469387755, "alnum_prop": 0.5184275184275184, "repo_name": "flowable/flowable-engine", "id": "b90a3a547ec06e5623f905d709d6934a664bd646", "size": "2442", "binary": false, "copies": "3", "ref": "refs/heads/main", "path": "modules/flowable-ui/flowable-ui-modeler-frontend/src/main/resources/static/modeler/editor-app/configuration/properties/escalation-definitions-popup.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "166" }, { "name": "CSS", "bytes": "673786" }, { "name": "Dockerfile", "bytes": "477" }, { "name": "Groovy", "bytes": "482" }, { "name": "HTML", "bytes": "1201811" }, { "name": "Handlebars", "bytes": "6004" }, { "name": "Java", "bytes": "46660725" }, { "name": "JavaScript", "bytes": "12668702" }, { "name": "Mustache", "bytes": "2383" }, { "name": "PLSQL", "bytes": "268970" }, { "name": "SQLPL", "bytes": "238673" }, { "name": "Shell", "bytes": "12773" }, { "name": "TSQL", "bytes": "19452" } ], "symlink_target": "" }
package com.gs.fw.common.mithra.attribute; import java.util.*; import com.gs.fw.common.mithra.*; import com.gs.fw.common.mithra.extractor.*; import com.gs.fw.common.mithra.finder.*; import com.gs.fw.common.mithra.util.*; public class TupleAttributeImpl implements TupleAttribute { private Attribute[] attributes; public TupleAttributeImpl(Attribute... attributes) { this.attributes = Arrays.copyOf(attributes, attributes.length); } public TupleAttributeImpl(Attribute first, Attribute second) { this.attributes = new Attribute[2]; this.attributes[0] = first; this.attributes[1] = second; } protected TupleAttributeImpl(TupleAttributeImpl tuple, Attribute attr) { this.attributes = new Attribute[tuple.attributes.length+1]; System.arraycopy(tuple.attributes, 0, this.attributes, 0, tuple.attributes.length); this.attributes[tuple.attributes.length] = attr; } protected TupleAttributeImpl(Attribute attr, TupleAttributeImpl tuple) { this.attributes = new Attribute[tuple.attributes.length+1]; this.attributes[0] = attr; System.arraycopy(tuple.attributes, 0, this.attributes, 1, tuple.attributes.length); } protected TupleAttributeImpl(Attribute attr, Attribute... attributes) { this.attributes = new Attribute[attributes.length+1]; this.attributes[0] = attr; System.arraycopy(attributes, 0, this.attributes, 1, attributes.length); } protected TupleAttributeImpl(TupleAttributeImpl first, TupleAttributeImpl second) { this.attributes = new Attribute[first.attributes.length+second.attributes.length]; System.arraycopy(first.attributes, 0, this.attributes, 0, first.attributes.length); System.arraycopy(second.attributes, 0, this.attributes, first.attributes.length, second.attributes.length); } public TupleAttributeImpl(TupleAttributeImpl first, Attribute[] attributes) { this.attributes = new Attribute[first.attributes.length+attributes.length]; System.arraycopy(first.attributes, 0, this.attributes, 0, first.attributes.length); System.arraycopy(attributes, 0, this.attributes, first.attributes.length, attributes.length); } public TupleAttribute tupleWith(Attribute attr) { return new TupleAttributeImpl(this, attr); } public TupleAttribute tupleWith(TupleAttribute attr) { return new TupleAttributeImpl(this, (TupleAttributeImpl) attr); } public TupleAttribute tupleWith(Attribute... attr) { return new TupleAttributeImpl(this, attr); } public Operation in(TupleSet tupleSet) { if (tupleSet.size() == 0) { return new None(this.attributes[0]); } return new MultiInOperation(this.attributes, (MithraTupleSet) tupleSet); } public Operation in(List dataHolders, Extractor[] extractors) { if (dataHolders.size() == 0) { return new None(this.attributes[0]); } for(int i=0;i<attributes.length;i++) { if (attributes[i].isSourceAttribute()) { return createInWithSourceAttribute(i, dataHolders, extractors, false); } } return createMultiInWithConstantCheck(this.attributes, dataHolders, extractors, false); } private Operation createMultiInWithConstantCheck(Attribute[] attributes, List dataHolders, Extractor[] extractors, boolean ignoreNulls) { boolean[] hasSingleValue = new boolean[extractors.length]; int constantCount = extractors.length; for(int i=0;i<hasSingleValue.length;i++) { hasSingleValue[i] = true; } Object first = dataHolders.get(0); for(int i=1;constantCount > 0 && i<dataHolders.size();i++) { for(int j=0;j<extractors.length;j++) { if (hasSingleValue[j] && !extractors[j].valueEquals(first, dataHolders.get(i))) { hasSingleValue[j] = false; constantCount--; } } } if (constantCount > 0) { Operation inOperation = NoOperation.instance(); Operation constantOp = NoOperation.instance(); int leftOver = extractors.length - constantCount; if (leftOver == 0) { for(int j=0;j<extractors.length;j++) { constantOp = constantOp.and(attributes[j].nonPrimitiveEq(extractors[j].valueOf(first))); } } else if (leftOver == 1) { for(int j=0;j<extractors.length;j++) { if (hasSingleValue[j]) { constantOp = constantOp.and(attributes[j].nonPrimitiveEq(extractors[j].valueOf(first))); } else { inOperation = attributes[j].in(dataHolders, extractors[j]); } } } else { Extractor[] extractorSubset = new Extractor[leftOver]; Attribute[] attributeSubset = new Attribute[leftOver]; int extractorCount = 0; for(int j=0;j<extractors.length;j++) { if (hasSingleValue[j]) { constantOp = constantOp.and(attributes[j].nonPrimitiveEq(extractors[j].valueOf(first))); } else { attributeSubset[extractorCount] = attributes[j]; extractorSubset[extractorCount++] = extractors[j]; } } inOperation = new MultiInOperation(attributeSubset, new MithraArrayTupleTupleSet(extractorSubset, dataHolders, ignoreNulls)); } return constantOp.and(inOperation); } else { return new MultiInOperation(attributes, new MithraArrayTupleTupleSet(extractors, dataHolders, ignoreNulls)); } } public Operation inIgnoreNulls(List dataHolders, Extractor[] extractors) { if (dataHolders.size() == 0) { return new None(this.attributes[0]); } for(int i=0;i<attributes.length;i++) { if (attributes[i].isSourceAttribute()) { return createInWithSourceAttribute(i, dataHolders, extractors, true); } } return new MultiInOperation(this.attributes, new MithraArrayTupleTupleSet(extractors, dataHolders, true)); } private Operation createInWithSourceAttribute(int sourceAttributeIndex, List dataHolders, Extractor[] extractors, boolean ignoreNulls) { Object first = dataHolders.get(0); Extractor dataHolderSourceAttribute = extractors[sourceAttributeIndex]; for(int i=1;i<dataHolders.size();i++) { Object data = dataHolders.get(i); if (!dataHolderSourceAttribute.valueEquals(first, data)) { return createMultiInWithConstantCheck(this.attributes, dataHolders, extractors, ignoreNulls); } } Operation op = this.attributes[sourceAttributeIndex].nonPrimitiveEq(dataHolderSourceAttribute.valueOf(first)); Attribute[] withoutSource = new Attribute[this.attributes.length - 1]; Extractor[] extractorsWithoutSource = new Extractor[this.attributes.length - 1]; int count = 0; for(int i=0;i<this.attributes.length;i++) { if (i != sourceAttributeIndex) { withoutSource[count] = this.attributes[i]; extractorsWithoutSource[count] = extractors[i]; count++; } } return op.and(createMultiInWithConstantCheck(withoutSource, dataHolders, extractorsWithoutSource, ignoreNulls)); } public Operation in(AggregateList aggList, String... aggregateAttributeName) { MithraArrayTupleTupleSet set = new MithraArrayTupleTupleSet(); int tupleLength = aggregateAttributeName.length; if (aggList.size() == 0) { return new None(this.attributes[0]); } for(int i=0;i<aggList.size();i++) { Object[] tuple = new Object[tupleLength]; for(int j=0;j<tupleLength;j++) { tuple[j] = aggList.get(i).getAttributeAsObject(aggregateAttributeName[j]); } set.add(tuple); } return this.in(set); } public Attribute[] getAttributes() { return attributes; } }
{ "content_hash": "c830247406e61daa1e343b8597df96d7", "timestamp": "", "source": "github", "line_count": 247, "max_line_length": 141, "avg_line_length": 36.927125506072876, "alnum_prop": 0.5768007893871286, "repo_name": "goldmansachs/reladomo", "id": "d4b931b533b3a70fb47994fc2aeb076fde495d6f", "size": "9705", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "reladomo/src/main/java/com/gs/fw/common/mithra/attribute/TupleAttributeImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5540" }, { "name": "CSS", "bytes": "13402" }, { "name": "HTML", "bytes": "64206" }, { "name": "Java", "bytes": "18211611" }, { "name": "JavaScript", "bytes": "18247" }, { "name": "Ruby", "bytes": "11034" }, { "name": "Shell", "bytes": "8454" }, { "name": "XSLT", "bytes": "383852" } ], "symlink_target": "" }
<<<<<<< HEAD Litecoin integration/staging tree ================================ http://www.litecoin.org Copyright (c) 2009-2014 Bitcoin Developers Copyright (c) 2011-2014 Litecoin Developers What is Litecoin? ---------------- Litecoin is a lite version of Bitcoin using scrypt as a proof-of-work algorithm. - 2.5 minute block targets - subsidy halves in 840k blocks (~4 years) - ~84 million total coins The rest is the same as Bitcoin. - 50 coins per block - 2016 blocks to retarget difficulty For more information, as well as an immediately useable, binary version of the Litecoin client sofware, see http://www.litecoin.org. ======= Litecoin Core integration/staging tree ===================================== https://litecoin.org What is Litecoin? ---------------- Litecoin is an experimental new digital currency that enables instant payments to anyone, anywhere in the world. Litecoin uses peer-to-peer technology to operate with no central authority: managing transactions and issuing money are carried out collectively by the network. Litecoin Core is the name of open source software which enables the use of this currency. For more information, as well as an immediately useable, binary version of the Litecoin Core software, see https://litecoin.org >>>>>>> d1691e599121d643db2c1f2b5f5529eb64f2a771 License ------- <<<<<<< HEAD Litecoin is released under the terms of the MIT license. See `COPYING` for more ======= Litecoin Core is released under the terms of the MIT license. See [COPYING](COPYING) for more >>>>>>> d1691e599121d643db2c1f2b5f5529eb64f2a771 information or see http://opensource.org/licenses/MIT. Development process ------------------- Developers work in their own trees, then submit pull requests when they think their feature or bug fix is ready. If it is a simple/trivial/non-controversial change, then one of the Litecoin development team members simply pulls it. If it is a *more complicated or potentially controversial* change, then the patch <<<<<<< HEAD submitter will be asked to start a discussion with the devs and community. ======= submitter will be asked to start a discussion (if they haven't already) on the [mailing list](https://groups.google.com/forum/#!forum/litecoin-dev). >>>>>>> d1691e599121d643db2c1f2b5f5529eb64f2a771 The patch will be accepted if there is broad consensus that it is a good thing. Developers should expect to rework and resubmit patches if the code doesn't match the project's coding conventions (see [doc/coding.md](doc/coding.md)) or are controversial. <<<<<<< HEAD The `master` branch is regularly built and tested, but is not guaranteed to be ======= The `master-0.10` branch is regularly built and tested, but is not guaranteed to be >>>>>>> d1691e599121d643db2c1f2b5f5529eb64f2a771 completely stable. [Tags](https://github.com/litecoin-project/litecoin/tags) are created regularly to indicate new official, stable release versions of Litecoin. Testing ------- Testing and code review is the bottleneck for development; we get more pull requests than we can review and test on short notice. Please be patient and help out by testing other people's pull requests, and remember this is a security-critical project where any mistake might cost people lots of money. ### Manual Quality Assurance (QA) Testing Large changes should have a test plan, and should be tested by somebody other than the developer who wrote the code. Creating a thread in the [Litecoin discussion forum](https://litecointalk.org/index.php?board=2.0) will allow the Litecoin development team members to review your proposal and to provide assistance with creating a test plan. Translations ------------ **Important**: We do not accept translation changes as GitHub pull requests because the next pull from Transifex would automatically overwrite them again. We only accept translation fixes that are submitted through [Bitcoin Core's Transifex page](https://www.transifex.com/projects/p/bitcoin/). Translations are converted to Litecoin periodically. <<<<<<< HEAD qmake BITCOIN_QT_TEST=1 -o Makefile.test bitcoin-qt.pro make -f Makefile.test ./litecoin-qt_test ======= Development tips and tricks --------------------------- **compiling for debugging** Run configure with the --enable-debug option, then make. Or run configure with CXXFLAGS="-g -ggdb -O0" or whatever debug flags you need. **debug.log** If the code is behaving strangely, take a look in the debug.log file in the data directory; error and debugging messages are written there. The -debug=... command-line option controls debugging; running with just -debug will turn on all categories (and give you a very large debug.log file). The Qt code routes qDebug() output to debug.log under category "qt": run with -debug=qt to see it. **testnet and regtest modes** Run with the -testnet option to run with "play litecoins" on the test network, if you are testing multi-machine code that needs to operate across the internet. If you are testing something that can run on one machine, run with the -regtest option. In regression test mode, blocks can be created on-demand; see qa/rpc-tests/ for tests that run in -regtest mode. **DEBUG_LOCKORDER** Litecoin Core is a multithreaded application, and deadlocks or other multithreading bugs can be very difficult to track down. Compiling with -DDEBUG_LOCKORDER (configure CXXFLAGS="-DDEBUG_LOCKORDER -g") inserts run-time checks to keep track of which locks are held, and adds warnings to the debug.log file if inconsistencies are detected. >>>>>>> d1691e599121d643db2c1f2b5f5529eb64f2a771
{ "content_hash": "91ec0daf564035ed67cc49a98ad20fb1", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 139, "avg_line_length": 37.817567567567565, "alnum_prop": 0.7530820082186885, "repo_name": "koharjidan/litecoin", "id": "3e3562d627698c0013b7fa13cb10c796882f7549", "size": "5597", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "7639" }, { "name": "C", "bytes": "393447" }, { "name": "C++", "bytes": "4024887" }, { "name": "CSS", "bytes": "1127" }, { "name": "Groff", "bytes": "18043" }, { "name": "HTML", "bytes": "50621" }, { "name": "Java", "bytes": "2100" }, { "name": "Makefile", "bytes": "68663" }, { "name": "Objective-C", "bytes": "2023" }, { "name": "Objective-C++", "bytes": "9224" }, { "name": "Protocol Buffer", "bytes": "2308" }, { "name": "Python", "bytes": "230668" }, { "name": "QMake", "bytes": "16733" }, { "name": "Shell", "bytes": "44272" } ], "symlink_target": "" }
/** * Polifill environment with missing functionality. */ define(function() { // Fix safari if (Number.isNaN === undefined) Number.isNaN = isNaN; if (Array.isArray === undefined) { Array.isArray = function(vArg) { // Taken from MDN. return Object.prototype.toString.call(vArg) === '[object Array]'; }; } });
{ "content_hash": "5606bc289cda7a3651efc6d066dfb35e", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 71, "avg_line_length": 21.5, "alnum_prop": 0.6133720930232558, "repo_name": "SebastianGlonner/messaging", "id": "bd00b889aef3fbdbe980ed443564e6ef22e49631", "size": "344", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bin/adapter.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "130917" } ], "symlink_target": "" }
/* $NetBSD: kern_stub.c,v 1.38 2013/12/09 18:06:27 pooka Exp $ */ /*- * Copyright (c) 2007, 2008 The NetBSD Foundation, Inc. * 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. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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. */ /* * Copyright (c) 1982, 1986, 1991, 1993 * The Regents of the University of California. 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. Neither the name of the University 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 REGENTS 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 REGENTS 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. * * @(#)subr_xxx.c 8.3 (Berkeley) 3/29/95 */ /* * Stubs for system calls and facilities not included in the system. */ #include <sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: kern_stub.c,v 1.38 2013/12/09 18:06:27 pooka Exp $"); #include "opt_ptrace.h" #include "opt_ktrace.h" #include <sys/param.h> #include <sys/kernel.h> #include <sys/proc.h> #include <sys/fstypes.h> #include <sys/signalvar.h> #include <sys/syscall.h> #include <sys/ktrace.h> #include <sys/intr.h> #include <sys/cpu.h> #include <sys/module.h> #include <sys/bus.h> #include <sys/userconf.h> bool default_bus_space_is_equal(bus_space_tag_t, bus_space_tag_t); bool default_bus_space_handle_is_equal(bus_space_tag_t, bus_space_handle_t, bus_space_handle_t); /* * Nonexistent system call-- signal process (may want to handle it). Flag * error in case process won't see signal immediately (blocked or ignored). */ #ifndef PTRACE __strong_alias(sys_ptrace,sys_nosys); #endif /* PTRACE */ /* * ktrace stubs. ktruser() goes to enosys as we want to fail the syscall, * but not kill the process: utrace() is a debugging feature. */ #ifndef KTRACE __strong_alias(ktr_csw,nullop); /* Probes */ __strong_alias(ktr_emul,nullop); __strong_alias(ktr_geniov,nullop); __strong_alias(ktr_genio,nullop); __strong_alias(ktr_mibio,nullop); __strong_alias(ktr_namei,nullop); __strong_alias(ktr_namei2,nullop); __strong_alias(ktr_psig,nullop); __strong_alias(ktr_syscall,nullop); __strong_alias(ktr_sysret,nullop); __strong_alias(ktr_kuser,nullop); __strong_alias(ktr_mib,nullop); __strong_alias(ktr_execarg,nullop); __strong_alias(ktr_execenv,nullop); __strong_alias(ktr_execfd,nullop); __strong_alias(sys_fktrace,sys_nosys); /* Syscalls */ __strong_alias(sys_ktrace,sys_nosys); __strong_alias(sys_utrace,sys_nosys); int ktrace_on; /* Misc */ __strong_alias(ktruser,enosys); __strong_alias(ktr_point,nullop); #endif /* KTRACE */ __weak_alias(device_register, voidop); __weak_alias(device_register_post_config, voidop); __weak_alias(spldebug_start, voidop); __weak_alias(spldebug_stop, voidop); __weak_alias(machdep_init,nullop); __weak_alias(pci_chipset_tag_create, eopnotsupp); __weak_alias(pci_chipset_tag_destroy, voidop); __weak_alias(bus_space_reserve, eopnotsupp); __weak_alias(bus_space_reserve_subregion, eopnotsupp); __weak_alias(bus_space_release, voidop); __weak_alias(bus_space_reservation_map, eopnotsupp); __weak_alias(bus_space_reservation_unmap, voidop); __weak_alias(bus_dma_tag_create, eopnotsupp); __weak_alias(bus_dma_tag_destroy, voidop); __weak_alias(bus_space_tag_create, eopnotsupp); __weak_alias(bus_space_tag_destroy, voidop); __strict_weak_alias(bus_space_is_equal, default_bus_space_is_equal); __strict_weak_alias(bus_space_handle_is_equal, default_bus_space_handle_is_equal); __weak_alias(userconf_bootinfo, voidop); __weak_alias(userconf_init, voidop); __weak_alias(userconf_prompt, voidop); __weak_alias(kobj_renamespace, nullop); /* * Scheduler activations system calls. These need to remain until libc's * major version is bumped. */ __strong_alias(sys_sa_register,sys_nosys); __strong_alias(sys_sa_stacks,sys_nosys); __strong_alias(sys_sa_enable,sys_nosys); __strong_alias(sys_sa_setconcurrency,sys_nosys); __strong_alias(sys_sa_yield,sys_nosys); __strong_alias(sys_sa_preempt,sys_nosys); __strong_alias(sys_sa_unblockyield,sys_nosys); /* * Stubs for compat_netbsd32. */ __strong_alias(dosa_register,sys_nosys); __strong_alias(sa_stacks1,sys_nosys); /* * Stubs for architectures that do not support kernel preemption. */ #ifndef __HAVE_PREEMPTION bool cpu_kpreempt_enter(uintptr_t where, int s) { return false; } void cpu_kpreempt_exit(uintptr_t where) { } bool cpu_kpreempt_disabled(void) { return true; } #else # ifndef MULTIPROCESSOR # error __HAVE_PREEMPTION requires MULTIPROCESSOR # endif #endif /* !__HAVE_PREEMPTION */ int sys_nosys(struct lwp *l, const void *v, register_t *retval) { mutex_enter(proc_lock); psignal(l->l_proc, SIGSYS); mutex_exit(proc_lock); return ENOSYS; } /* * Unsupported device function (e.g. writing to read-only device). */ int enodev(void) { return (ENODEV); } /* * Unconfigured device function; driver not configured. */ int enxio(void) { return (ENXIO); } /* * Unsupported ioctl function. */ int enoioctl(void) { return (ENOTTY); } /* * Unsupported system function. * This is used for an otherwise-reasonable operation * that is not supported by the current system binary. */ int enosys(void) { return (ENOSYS); } /* * Return error for operation not supported * on a specific object or file type. */ int eopnotsupp(void) { return (EOPNOTSUPP); } /* * Generic null operation, void return value. */ void voidop(void) { } /* * Generic null operation, always returns success. */ int nullop(void *v) { return (0); } bool default_bus_space_handle_is_equal(bus_space_tag_t t, bus_space_handle_t h1, bus_space_handle_t h2) { return memcmp(&h1, &h2, sizeof(h1)) == 0; } bool default_bus_space_is_equal(bus_space_tag_t t1, bus_space_tag_t t2) { return memcmp(&t1, &t2, sizeof(t1)) == 0; }
{ "content_hash": "9b7fe7a2e12e0a7d9629881c56db9e94", "timestamp": "", "source": "github", "line_count": 291, "max_line_length": 81, "avg_line_length": 28.054982817869416, "alnum_prop": 0.7272170504654581, "repo_name": "execunix/vinos", "id": "79dbaa6396e7c8a906e62b197a3747fc4dc0d3de", "size": "8164", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sys/kern/kern_stub.c", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/** * This example demonstrates how to use [`PuppeteerCrawler`](/docs/api/puppeteer-crawler) * in combination with [`RequestQueue`](/docs/api/request-queue) to recursively scrape the * [Hacker News website](https://news.ycombinator.com) using headless Chrome / Puppeteer. * The crawler starts with a single URL, finds links to next pages, * enqueues them and continues until no more desired links are available. * The results are stored to the default dataset. In local configuration, the results are stored as JSON files in `./apify_storage/datasets/default` * * To run this example on the Apify Platform, select the `Node.js 12 + Chrome on Debian (apify/actor-node-chrome)` base image * on the source tab of your actor configuration. */ const Apify = require('apify'); Apify.main(async () => { // Apify.openRequestQueue() is a factory to get a preconfigured RequestQueue instance. // We add our first request to it - the initial page the crawler will visit. const requestQueue = await Apify.openRequestQueue(); await requestQueue.addRequest({ url: 'https://news.ycombinator.com/' }); // Create an instance of the PuppeteerCrawler class - a crawler // that automatically loads the URLs in headless Chrome / Puppeteer. const crawler = new Apify.PuppeteerCrawler({ requestQueue, // Here you can set options that are passed to the Apify.launchPuppeteer() function. launchPuppeteerOptions: { // For example, by adding "slowMo" you'll slow down Puppeteer operations to simplify debugging // slowMo: 500, }, // Stop crawling after several pages maxRequestsPerCrawl: 10, // This function will be called for each URL to crawl. // Here you can write the Puppeteer scripts you are familiar with, // with the exception that browsers and pages are automatically managed by the Apify SDK. // The function accepts a single parameter, which is an object with the following fields: // - request: an instance of the Request class with information such as URL and HTTP method // - page: Puppeteer's Page object (see https://pptr.dev/#show=api-class-page) handlePageFunction: async ({ request, page }) => { console.log(`Processing ${request.url}...`); // A function to be evaluated by Puppeteer within the browser context. const pageFunction = ($posts) => { const data = []; // We're getting the title, rank and URL of each post on Hacker News. $posts.forEach(($post) => { data.push({ title: $post.querySelector('.title a').innerText, rank: $post.querySelector('.rank').innerText, href: $post.querySelector('.title a').href, }); }); return data; }; const data = await page.$$eval('.athing', pageFunction); // Store the results to the default dataset. await Apify.pushData(data); // Find a link to the next page and enqueue it if it exists. const infos = await Apify.utils.enqueueLinks({ page, requestQueue, selector: '.morelink', }); if (infos.length === 0) console.log(`${request.url} is the last page!`); }, // This function is called if the page processing failed more than maxRequestRetries+1 times. handleFailedRequestFunction: async ({ request }) => { console.log(`Request ${request.url} failed too many times`); await Apify.pushData({ '#debug': Apify.utils.createRequestDebugInfo(request), }); }, }); // Run the crawler and wait for it to finish. await crawler.run(); console.log('Crawler finished.'); });
{ "content_hash": "9ad727dab1f988b885b81f9dcff3b859", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 148, "avg_line_length": 45.37931034482759, "alnum_prop": 0.6208206686930091, "repo_name": "Apifier/apify-runtime-js", "id": "f5bafde7e4f3523d8db933599592893aeb9a4cb6", "size": "3948", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/puppeteer_crawler.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "147078" }, { "name": "Shell", "bytes": "2498" } ], "symlink_target": "" }
package gov.nist; import java.io.File; import io.proleap.cobol.preprocessor.CobolPreprocessor.CobolSourceFormatEnum; import io.proleap.cobol.runner.CobolParseTestRunner; import io.proleap.cobol.runner.impl.CobolParseTestRunnerImpl; import org.junit.Test; public class CM202MTest { @Test public void test() throws Exception { final File inputFile = new File("src/test/resources/gov/nist/CM202M.CBL"); final CobolParseTestRunner runner = new CobolParseTestRunnerImpl(); runner.parseFile(inputFile, CobolSourceFormatEnum.FIXED); } }
{ "content_hash": "345dcb008fade966728890889bc8aad5", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 77, "avg_line_length": 30.11111111111111, "alnum_prop": 0.8062730627306273, "repo_name": "uwol/cobol85parser", "id": "1ae81fd86374254bd667c35fb375edb164c1f3c0", "size": "542", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/test/java/gov/nist/CM202MTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "ANTLR", "bytes": "89712" }, { "name": "COBOL", "bytes": "28337364" }, { "name": "Java", "bytes": "2908548" } ], "symlink_target": "" }
<?php /** * Base class that represents a row from the 'membresia' table. * * * * @package propel.generator.feetcent_feetcenter.om */ abstract class BaseMembresia extends BaseObject implements Persistent { /** * Peer class name */ const PEER = 'MembresiaPeer'; /** * The Peer class. * Instance provides a convenient way of calling static methods on a class * that calling code may not be able to identify. * @var MembresiaPeer */ protected static $peer; /** * The flag var to prevent infinite loop in deep copy * @var boolean */ protected $startCopy = false; /** * The value for the idmembresia field. * @var int */ protected $idmembresia; /** * The value for the membresia_nombre field. * @var string */ protected $membresia_nombre; /** * The value for the membresia_descripcion field. * @var string */ protected $membresia_descripcion; /** * The value for the membresia_servicios field. * @var string */ protected $membresia_servicios; /** * The value for the membresia_cupones field. * @var string */ protected $membresia_cupones; /** * The value for the servicio_generaingreso field. * @var boolean */ protected $servicio_generaingreso; /** * The value for the servicio_generacomision field. * @var boolean */ protected $servicio_generacomision; /** * The value for the servicio_tipocomision field. * @var string */ protected $servicio_tipocomision; /** * The value for the servicio_comision field. * @var string */ protected $servicio_comision; /** * The value for the membresia_precio field. * @var string */ protected $membresia_precio; /** * The value for the membresia_vigencia field. * @var int */ protected $membresia_vigencia; /** * @var PropelObjectCollection|Membresiaclinica[] Collection to store aggregation of Membresiaclinica objects. */ protected $collMembresiaclinicas; protected $collMembresiaclinicasPartial; /** * @var PropelObjectCollection|Pacientemembresia[] Collection to store aggregation of Pacientemembresia objects. */ protected $collPacientemembresias; protected $collPacientemembresiasPartial; /** * @var PropelObjectCollection|Visitadetalle[] Collection to store aggregation of Visitadetalle objects. */ protected $collVisitadetalles; protected $collVisitadetallesPartial; /** * Flag to prevent endless save loop, if this object is referenced * by another object which falls in this transaction. * @var boolean */ protected $alreadyInSave = false; /** * Flag to prevent endless validation loop, if this object is referenced * by another object which falls in this transaction. * @var boolean */ protected $alreadyInValidation = false; /** * Flag to prevent endless clearAllReferences($deep=true) loop, if this object is referenced * @var boolean */ protected $alreadyInClearAllReferencesDeep = false; /** * An array of objects scheduled for deletion. * @var PropelObjectCollection */ protected $membresiaclinicasScheduledForDeletion = null; /** * An array of objects scheduled for deletion. * @var PropelObjectCollection */ protected $pacientemembresiasScheduledForDeletion = null; /** * An array of objects scheduled for deletion. * @var PropelObjectCollection */ protected $visitadetallesScheduledForDeletion = null; /** * Get the [idmembresia] column value. * * @return int */ public function getIdmembresia() { return $this->idmembresia; } /** * Get the [membresia_nombre] column value. * * @return string */ public function getMembresiaNombre() { return $this->membresia_nombre; } /** * Get the [membresia_descripcion] column value. * * @return string */ public function getMembresiaDescripcion() { return $this->membresia_descripcion; } /** * Get the [membresia_servicios] column value. * * @return string */ public function getMembresiaServicios() { return $this->membresia_servicios; } /** * Get the [membresia_cupones] column value. * * @return string */ public function getMembresiaCupones() { return $this->membresia_cupones; } /** * Get the [servicio_generaingreso] column value. * * @return boolean */ public function getServicioGeneraingreso() { return $this->servicio_generaingreso; } /** * Get the [servicio_generacomision] column value. * * @return boolean */ public function getServicioGeneracomision() { return $this->servicio_generacomision; } /** * Get the [servicio_tipocomision] column value. * * @return string */ public function getServicioTipocomision() { return $this->servicio_tipocomision; } /** * Get the [servicio_comision] column value. * * @return string */ public function getServicioComision() { return $this->servicio_comision; } /** * Get the [membresia_precio] column value. * * @return string */ public function getMembresiaPrecio() { return $this->membresia_precio; } /** * Get the [membresia_vigencia] column value. * * @return int */ public function getMembresiaVigencia() { return $this->membresia_vigencia; } /** * Set the value of [idmembresia] column. * * @param int $v new value * @return Membresia The current object (for fluent API support) */ public function setIdmembresia($v) { if ($v !== null && is_numeric($v)) { $v = (int) $v; } if ($this->idmembresia !== $v) { $this->idmembresia = $v; $this->modifiedColumns[] = MembresiaPeer::IDMEMBRESIA; } return $this; } // setIdmembresia() /** * Set the value of [membresia_nombre] column. * * @param string $v new value * @return Membresia The current object (for fluent API support) */ public function setMembresiaNombre($v) { if ($v !== null) { $v = (string) $v; } if ($this->membresia_nombre !== $v) { $this->membresia_nombre = $v; $this->modifiedColumns[] = MembresiaPeer::MEMBRESIA_NOMBRE; } return $this; } // setMembresiaNombre() /** * Set the value of [membresia_descripcion] column. * * @param string $v new value * @return Membresia The current object (for fluent API support) */ public function setMembresiaDescripcion($v) { if ($v !== null) { $v = (string) $v; } if ($this->membresia_descripcion !== $v) { $this->membresia_descripcion = $v; $this->modifiedColumns[] = MembresiaPeer::MEMBRESIA_DESCRIPCION; } return $this; } // setMembresiaDescripcion() /** * Set the value of [membresia_servicios] column. * * @param string $v new value * @return Membresia The current object (for fluent API support) */ public function setMembresiaServicios($v) { if ($v !== null && is_numeric($v)) { $v = (string) $v; } if ($this->membresia_servicios !== $v) { $this->membresia_servicios = $v; $this->modifiedColumns[] = MembresiaPeer::MEMBRESIA_SERVICIOS; } return $this; } // setMembresiaServicios() /** * Set the value of [membresia_cupones] column. * * @param string $v new value * @return Membresia The current object (for fluent API support) */ public function setMembresiaCupones($v) { if ($v !== null && is_numeric($v)) { $v = (string) $v; } if ($this->membresia_cupones !== $v) { $this->membresia_cupones = $v; $this->modifiedColumns[] = MembresiaPeer::MEMBRESIA_CUPONES; } return $this; } // setMembresiaCupones() /** * Sets the value of the [servicio_generaingreso] column. * Non-boolean arguments are converted using the following rules: * * 1, '1', 'true', 'on', and 'yes' are converted to boolean true * * 0, '0', 'false', 'off', and 'no' are converted to boolean false * Check on string values is case insensitive (so 'FaLsE' is seen as 'false'). * * @param boolean|integer|string $v The new value * @return Membresia The current object (for fluent API support) */ public function setServicioGeneraingreso($v) { if ($v !== null) { if (is_string($v)) { $v = in_array(strtolower($v), array('false', 'off', '-', 'no', 'n', '0', '')) ? false : true; } else { $v = (boolean) $v; } } if ($this->servicio_generaingreso !== $v) { $this->servicio_generaingreso = $v; $this->modifiedColumns[] = MembresiaPeer::SERVICIO_GENERAINGRESO; } return $this; } // setServicioGeneraingreso() /** * Sets the value of the [servicio_generacomision] column. * Non-boolean arguments are converted using the following rules: * * 1, '1', 'true', 'on', and 'yes' are converted to boolean true * * 0, '0', 'false', 'off', and 'no' are converted to boolean false * Check on string values is case insensitive (so 'FaLsE' is seen as 'false'). * * @param boolean|integer|string $v The new value * @return Membresia The current object (for fluent API support) */ public function setServicioGeneracomision($v) { if ($v !== null) { if (is_string($v)) { $v = in_array(strtolower($v), array('false', 'off', '-', 'no', 'n', '0', '')) ? false : true; } else { $v = (boolean) $v; } } if ($this->servicio_generacomision !== $v) { $this->servicio_generacomision = $v; $this->modifiedColumns[] = MembresiaPeer::SERVICIO_GENERACOMISION; } return $this; } // setServicioGeneracomision() /** * Set the value of [servicio_tipocomision] column. * * @param string $v new value * @return Membresia The current object (for fluent API support) */ public function setServicioTipocomision($v) { if ($v !== null) { $v = (string) $v; } if ($this->servicio_tipocomision !== $v) { $this->servicio_tipocomision = $v; $this->modifiedColumns[] = MembresiaPeer::SERVICIO_TIPOCOMISION; } return $this; } // setServicioTipocomision() /** * Set the value of [servicio_comision] column. * * @param string $v new value * @return Membresia The current object (for fluent API support) */ public function setServicioComision($v) { if ($v !== null && is_numeric($v)) { $v = (string) $v; } if ($this->servicio_comision !== $v) { $this->servicio_comision = $v; $this->modifiedColumns[] = MembresiaPeer::SERVICIO_COMISION; } return $this; } // setServicioComision() /** * Set the value of [membresia_precio] column. * * @param string $v new value * @return Membresia The current object (for fluent API support) */ public function setMembresiaPrecio($v) { if ($v !== null && is_numeric($v)) { $v = (string) $v; } if ($this->membresia_precio !== $v) { $this->membresia_precio = $v; $this->modifiedColumns[] = MembresiaPeer::MEMBRESIA_PRECIO; } return $this; } // setMembresiaPrecio() /** * Set the value of [membresia_vigencia] column. * * @param int $v new value * @return Membresia The current object (for fluent API support) */ public function setMembresiaVigencia($v) { if ($v !== null && is_numeric($v)) { $v = (int) $v; } if ($this->membresia_vigencia !== $v) { $this->membresia_vigencia = $v; $this->modifiedColumns[] = MembresiaPeer::MEMBRESIA_VIGENCIA; } return $this; } // setMembresiaVigencia() /** * Indicates whether the columns in this object are only set to default values. * * This method can be used in conjunction with isModified() to indicate whether an object is both * modified _and_ has some values set which are non-default. * * @return boolean Whether the columns in this object are only been set with default values. */ public function hasOnlyDefaultValues() { // otherwise, everything was equal, so return true return true; } // hasOnlyDefaultValues() /** * Hydrates (populates) the object variables with values from the database resultset. * * An offset (0-based "start column") is specified so that objects can be hydrated * with a subset of the columns in the resultset rows. This is needed, for example, * for results of JOIN queries where the resultset row includes columns from two or * more tables. * * @param array $row The row returned by PDOStatement->fetch(PDO::FETCH_NUM) * @param int $startcol 0-based offset column which indicates which resultset column to start with. * @param boolean $rehydrate Whether this object is being re-hydrated from the database. * @return int next starting column * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. */ public function hydrate($row, $startcol = 0, $rehydrate = false) { try { $this->idmembresia = ($row[$startcol + 0] !== null) ? (int) $row[$startcol + 0] : null; $this->membresia_nombre = ($row[$startcol + 1] !== null) ? (string) $row[$startcol + 1] : null; $this->membresia_descripcion = ($row[$startcol + 2] !== null) ? (string) $row[$startcol + 2] : null; $this->membresia_servicios = ($row[$startcol + 3] !== null) ? (string) $row[$startcol + 3] : null; $this->membresia_cupones = ($row[$startcol + 4] !== null) ? (string) $row[$startcol + 4] : null; $this->servicio_generaingreso = ($row[$startcol + 5] !== null) ? (boolean) $row[$startcol + 5] : null; $this->servicio_generacomision = ($row[$startcol + 6] !== null) ? (boolean) $row[$startcol + 6] : null; $this->servicio_tipocomision = ($row[$startcol + 7] !== null) ? (string) $row[$startcol + 7] : null; $this->servicio_comision = ($row[$startcol + 8] !== null) ? (string) $row[$startcol + 8] : null; $this->membresia_precio = ($row[$startcol + 9] !== null) ? (string) $row[$startcol + 9] : null; $this->membresia_vigencia = ($row[$startcol + 10] !== null) ? (int) $row[$startcol + 10] : null; $this->resetModified(); $this->setNew(false); if ($rehydrate) { $this->ensureConsistency(); } $this->postHydrate($row, $startcol, $rehydrate); return $startcol + 11; // 11 = MembresiaPeer::NUM_HYDRATE_COLUMNS. } catch (Exception $e) { throw new PropelException("Error populating Membresia object", $e); } } /** * Checks and repairs the internal consistency of the object. * * This method is executed after an already-instantiated object is re-hydrated * from the database. It exists to check any foreign keys to make sure that * the objects related to the current object are correct based on foreign key. * * You can override this method in the stub class, but you should always invoke * the base method from the overridden method (i.e. parent::ensureConsistency()), * in case your model changes. * * @throws PropelException */ public function ensureConsistency() { } // ensureConsistency /** * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. * * This will only work if the object has been saved and has a valid primary key set. * * @param boolean $deep (optional) Whether to also de-associated any related objects. * @param PropelPDO $con (optional) The PropelPDO connection to use. * @return void * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db */ public function reload($deep = false, PropelPDO $con = null) { if ($this->isDeleted()) { throw new PropelException("Cannot reload a deleted object."); } if ($this->isNew()) { throw new PropelException("Cannot reload an unsaved object."); } if ($con === null) { $con = Propel::getConnection(MembresiaPeer::DATABASE_NAME, Propel::CONNECTION_READ); } // We don't need to alter the object instance pool; we're just modifying this instance // already in the pool. $stmt = MembresiaPeer::doSelectStmt($this->buildPkeyCriteria(), $con); $row = $stmt->fetch(PDO::FETCH_NUM); $stmt->closeCursor(); if (!$row) { throw new PropelException('Cannot find matching row in the database to reload object values.'); } $this->hydrate($row, 0, true); // rehydrate if ($deep) { // also de-associate any related objects? $this->collMembresiaclinicas = null; $this->collPacientemembresias = null; $this->collVisitadetalles = null; } // if (deep) } /** * Removes this object from datastore and sets delete attribute. * * @param PropelPDO $con * @return void * @throws PropelException * @throws Exception * @see BaseObject::setDeleted() * @see BaseObject::isDeleted() */ public function delete(PropelPDO $con = null) { if ($this->isDeleted()) { throw new PropelException("This object has already been deleted."); } if ($con === null) { $con = Propel::getConnection(MembresiaPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $con->beginTransaction(); try { $deleteQuery = MembresiaQuery::create() ->filterByPrimaryKey($this->getPrimaryKey()); $ret = $this->preDelete($con); if ($ret) { $deleteQuery->delete($con); $this->postDelete($con); $con->commit(); $this->setDeleted(true); } else { $con->commit(); } } catch (Exception $e) { $con->rollBack(); throw $e; } } /** * Persists this object to the database. * * If the object is new, it inserts it; otherwise an update is performed. * All modified related objects will also be persisted in the doSave() * method. This method wraps all precipitate database operations in a * single transaction. * * @param PropelPDO $con * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. * @throws PropelException * @throws Exception * @see doSave() */ public function save(PropelPDO $con = null) { if ($this->isDeleted()) { throw new PropelException("You cannot save an object that has been deleted."); } if ($con === null) { $con = Propel::getConnection(MembresiaPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $con->beginTransaction(); $isInsert = $this->isNew(); try { $ret = $this->preSave($con); if ($isInsert) { $ret = $ret && $this->preInsert($con); } else { $ret = $ret && $this->preUpdate($con); } if ($ret) { $affectedRows = $this->doSave($con); if ($isInsert) { $this->postInsert($con); } else { $this->postUpdate($con); } $this->postSave($con); MembresiaPeer::addInstanceToPool($this); } else { $affectedRows = 0; } $con->commit(); return $affectedRows; } catch (Exception $e) { $con->rollBack(); throw $e; } } /** * Performs the work of inserting or updating the row in the database. * * If the object is new, it inserts it; otherwise an update is performed. * All related objects are also updated in this method. * * @param PropelPDO $con * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. * @throws PropelException * @see save() */ protected function doSave(PropelPDO $con) { $affectedRows = 0; // initialize var to track total num of affected rows if (!$this->alreadyInSave) { $this->alreadyInSave = true; if ($this->isNew() || $this->isModified()) { // persist changes if ($this->isNew()) { $this->doInsert($con); } else { $this->doUpdate($con); } $affectedRows += 1; $this->resetModified(); } if ($this->membresiaclinicasScheduledForDeletion !== null) { if (!$this->membresiaclinicasScheduledForDeletion->isEmpty()) { MembresiaclinicaQuery::create() ->filterByPrimaryKeys($this->membresiaclinicasScheduledForDeletion->getPrimaryKeys(false)) ->delete($con); $this->membresiaclinicasScheduledForDeletion = null; } } if ($this->collMembresiaclinicas !== null) { foreach ($this->collMembresiaclinicas as $referrerFK) { if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { $affectedRows += $referrerFK->save($con); } } } if ($this->pacientemembresiasScheduledForDeletion !== null) { if (!$this->pacientemembresiasScheduledForDeletion->isEmpty()) { PacientemembresiaQuery::create() ->filterByPrimaryKeys($this->pacientemembresiasScheduledForDeletion->getPrimaryKeys(false)) ->delete($con); $this->pacientemembresiasScheduledForDeletion = null; } } if ($this->collPacientemembresias !== null) { foreach ($this->collPacientemembresias as $referrerFK) { if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { $affectedRows += $referrerFK->save($con); } } } if ($this->visitadetallesScheduledForDeletion !== null) { if (!$this->visitadetallesScheduledForDeletion->isEmpty()) { VisitadetalleQuery::create() ->filterByPrimaryKeys($this->visitadetallesScheduledForDeletion->getPrimaryKeys(false)) ->delete($con); $this->visitadetallesScheduledForDeletion = null; } } if ($this->collVisitadetalles !== null) { foreach ($this->collVisitadetalles as $referrerFK) { if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { $affectedRows += $referrerFK->save($con); } } } $this->alreadyInSave = false; } return $affectedRows; } // doSave() /** * Insert the row in the database. * * @param PropelPDO $con * * @throws PropelException * @see doSave() */ protected function doInsert(PropelPDO $con) { $modifiedColumns = array(); $index = 0; $this->modifiedColumns[] = MembresiaPeer::IDMEMBRESIA; if (null !== $this->idmembresia) { throw new PropelException('Cannot insert a value for auto-increment primary key (' . MembresiaPeer::IDMEMBRESIA . ')'); } // check the columns in natural order for more readable SQL queries if ($this->isColumnModified(MembresiaPeer::IDMEMBRESIA)) { $modifiedColumns[':p' . $index++] = '`idmembresia`'; } if ($this->isColumnModified(MembresiaPeer::MEMBRESIA_NOMBRE)) { $modifiedColumns[':p' . $index++] = '`membresia_nombre`'; } if ($this->isColumnModified(MembresiaPeer::MEMBRESIA_DESCRIPCION)) { $modifiedColumns[':p' . $index++] = '`membresia_descripcion`'; } if ($this->isColumnModified(MembresiaPeer::MEMBRESIA_SERVICIOS)) { $modifiedColumns[':p' . $index++] = '`membresia_servicios`'; } if ($this->isColumnModified(MembresiaPeer::MEMBRESIA_CUPONES)) { $modifiedColumns[':p' . $index++] = '`membresia_cupones`'; } if ($this->isColumnModified(MembresiaPeer::SERVICIO_GENERAINGRESO)) { $modifiedColumns[':p' . $index++] = '`servicio_generaingreso`'; } if ($this->isColumnModified(MembresiaPeer::SERVICIO_GENERACOMISION)) { $modifiedColumns[':p' . $index++] = '`servicio_generacomision`'; } if ($this->isColumnModified(MembresiaPeer::SERVICIO_TIPOCOMISION)) { $modifiedColumns[':p' . $index++] = '`servicio_tipocomision`'; } if ($this->isColumnModified(MembresiaPeer::SERVICIO_COMISION)) { $modifiedColumns[':p' . $index++] = '`servicio_comision`'; } if ($this->isColumnModified(MembresiaPeer::MEMBRESIA_PRECIO)) { $modifiedColumns[':p' . $index++] = '`membresia_precio`'; } if ($this->isColumnModified(MembresiaPeer::MEMBRESIA_VIGENCIA)) { $modifiedColumns[':p' . $index++] = '`membresia_vigencia`'; } $sql = sprintf( 'INSERT INTO `membresia` (%s) VALUES (%s)', implode(', ', $modifiedColumns), implode(', ', array_keys($modifiedColumns)) ); try { $stmt = $con->prepare($sql); foreach ($modifiedColumns as $identifier => $columnName) { switch ($columnName) { case '`idmembresia`': $stmt->bindValue($identifier, $this->idmembresia, PDO::PARAM_INT); break; case '`membresia_nombre`': $stmt->bindValue($identifier, $this->membresia_nombre, PDO::PARAM_STR); break; case '`membresia_descripcion`': $stmt->bindValue($identifier, $this->membresia_descripcion, PDO::PARAM_STR); break; case '`membresia_servicios`': $stmt->bindValue($identifier, $this->membresia_servicios, PDO::PARAM_STR); break; case '`membresia_cupones`': $stmt->bindValue($identifier, $this->membresia_cupones, PDO::PARAM_STR); break; case '`servicio_generaingreso`': $stmt->bindValue($identifier, (int) $this->servicio_generaingreso, PDO::PARAM_INT); break; case '`servicio_generacomision`': $stmt->bindValue($identifier, (int) $this->servicio_generacomision, PDO::PARAM_INT); break; case '`servicio_tipocomision`': $stmt->bindValue($identifier, $this->servicio_tipocomision, PDO::PARAM_STR); break; case '`servicio_comision`': $stmt->bindValue($identifier, $this->servicio_comision, PDO::PARAM_STR); break; case '`membresia_precio`': $stmt->bindValue($identifier, $this->membresia_precio, PDO::PARAM_STR); break; case '`membresia_vigencia`': $stmt->bindValue($identifier, $this->membresia_vigencia, PDO::PARAM_INT); break; } } $stmt->execute(); } catch (Exception $e) { Propel::log($e->getMessage(), Propel::LOG_ERR); throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), $e); } try { $pk = $con->lastInsertId(); } catch (Exception $e) { throw new PropelException('Unable to get autoincrement id.', $e); } $this->setIdmembresia($pk); $this->setNew(false); } /** * Update the row in the database. * * @param PropelPDO $con * * @see doSave() */ protected function doUpdate(PropelPDO $con) { $selectCriteria = $this->buildPkeyCriteria(); $valuesCriteria = $this->buildCriteria(); BasePeer::doUpdate($selectCriteria, $valuesCriteria, $con); } /** * Array of ValidationFailed objects. * @var array ValidationFailed[] */ protected $validationFailures = array(); /** * Gets any ValidationFailed objects that resulted from last call to validate(). * * * @return array ValidationFailed[] * @see validate() */ public function getValidationFailures() { return $this->validationFailures; } /** * Validates the objects modified field values and all objects related to this table. * * If $columns is either a column name or an array of column names * only those columns are validated. * * @param mixed $columns Column name or an array of column names. * @return boolean Whether all columns pass validation. * @see doValidate() * @see getValidationFailures() */ public function validate($columns = null) { $res = $this->doValidate($columns); if ($res === true) { $this->validationFailures = array(); return true; } $this->validationFailures = $res; return false; } /** * This function performs the validation work for complex object models. * * In addition to checking the current object, all related objects will * also be validated. If all pass then <code>true</code> is returned; otherwise * an aggregated array of ValidationFailed objects will be returned. * * @param array $columns Array of column names to validate. * @return mixed <code>true</code> if all validations pass; array of <code>ValidationFailed</code> objects otherwise. */ protected function doValidate($columns = null) { if (!$this->alreadyInValidation) { $this->alreadyInValidation = true; $retval = null; $failureMap = array(); if (($retval = MembresiaPeer::doValidate($this, $columns)) !== true) { $failureMap = array_merge($failureMap, $retval); } if ($this->collMembresiaclinicas !== null) { foreach ($this->collMembresiaclinicas as $referrerFK) { if (!$referrerFK->validate($columns)) { $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); } } } if ($this->collPacientemembresias !== null) { foreach ($this->collPacientemembresias as $referrerFK) { if (!$referrerFK->validate($columns)) { $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); } } } if ($this->collVisitadetalles !== null) { foreach ($this->collVisitadetalles as $referrerFK) { if (!$referrerFK->validate($columns)) { $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); } } } $this->alreadyInValidation = false; } return (!empty($failureMap) ? $failureMap : true); } /** * Retrieves a field from the object by name passed in as a string. * * @param string $name name * @param string $type The type of fieldname the $name is of: * one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. * Defaults to BasePeer::TYPE_PHPNAME * @return mixed Value of field. */ public function getByName($name, $type = BasePeer::TYPE_PHPNAME) { $pos = MembresiaPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); $field = $this->getByPosition($pos); return $field; } /** * Retrieves a field from the object by Position as specified in the xml schema. * Zero-based. * * @param int $pos position in xml schema * @return mixed Value of field at $pos */ public function getByPosition($pos) { switch ($pos) { case 0: return $this->getIdmembresia(); break; case 1: return $this->getMembresiaNombre(); break; case 2: return $this->getMembresiaDescripcion(); break; case 3: return $this->getMembresiaServicios(); break; case 4: return $this->getMembresiaCupones(); break; case 5: return $this->getServicioGeneraingreso(); break; case 6: return $this->getServicioGeneracomision(); break; case 7: return $this->getServicioTipocomision(); break; case 8: return $this->getServicioComision(); break; case 9: return $this->getMembresiaPrecio(); break; case 10: return $this->getMembresiaVigencia(); break; default: return null; break; } // switch() } /** * Exports the object as an array. * * You can specify the key type of the array by passing one of the class * type constants. * * @param string $keyType (optional) One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. * Defaults to BasePeer::TYPE_PHPNAME. * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to true. * @param array $alreadyDumpedObjects List of objects to skip to avoid recursion * @param boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE. * * @return array an associative array containing the field names (as keys) and field values */ public function toArray($keyType = BasePeer::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false) { if (isset($alreadyDumpedObjects['Membresia'][$this->getPrimaryKey()])) { return '*RECURSION*'; } $alreadyDumpedObjects['Membresia'][$this->getPrimaryKey()] = true; $keys = MembresiaPeer::getFieldNames($keyType); $result = array( $keys[0] => $this->getIdmembresia(), $keys[1] => $this->getMembresiaNombre(), $keys[2] => $this->getMembresiaDescripcion(), $keys[3] => $this->getMembresiaServicios(), $keys[4] => $this->getMembresiaCupones(), $keys[5] => $this->getServicioGeneraingreso(), $keys[6] => $this->getServicioGeneracomision(), $keys[7] => $this->getServicioTipocomision(), $keys[8] => $this->getServicioComision(), $keys[9] => $this->getMembresiaPrecio(), $keys[10] => $this->getMembresiaVigencia(), ); $virtualColumns = $this->virtualColumns; foreach ($virtualColumns as $key => $virtualColumn) { $result[$key] = $virtualColumn; } if ($includeForeignObjects) { if (null !== $this->collMembresiaclinicas) { $result['Membresiaclinicas'] = $this->collMembresiaclinicas->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); } if (null !== $this->collPacientemembresias) { $result['Pacientemembresias'] = $this->collPacientemembresias->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); } if (null !== $this->collVisitadetalles) { $result['Visitadetalles'] = $this->collVisitadetalles->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); } } return $result; } /** * Sets a field from the object by name passed in as a string. * * @param string $name peer name * @param mixed $value field value * @param string $type The type of fieldname the $name is of: * one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. * Defaults to BasePeer::TYPE_PHPNAME * @return void */ public function setByName($name, $value, $type = BasePeer::TYPE_PHPNAME) { $pos = MembresiaPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); $this->setByPosition($pos, $value); } /** * Sets a field from the object by Position as specified in the xml schema. * Zero-based. * * @param int $pos position in xml schema * @param mixed $value field value * @return void */ public function setByPosition($pos, $value) { switch ($pos) { case 0: $this->setIdmembresia($value); break; case 1: $this->setMembresiaNombre($value); break; case 2: $this->setMembresiaDescripcion($value); break; case 3: $this->setMembresiaServicios($value); break; case 4: $this->setMembresiaCupones($value); break; case 5: $this->setServicioGeneraingreso($value); break; case 6: $this->setServicioGeneracomision($value); break; case 7: $this->setServicioTipocomision($value); break; case 8: $this->setServicioComision($value); break; case 9: $this->setMembresiaPrecio($value); break; case 10: $this->setMembresiaVigencia($value); break; } // switch() } /** * Populates the object using an array. * * This is particularly useful when populating an object from one of the * request arrays (e.g. $_POST). This method goes through the column * names, checking to see whether a matching key exists in populated * array. If so the setByName() method is called for that column. * * You can specify the key type of the array by additionally passing one * of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. * The default key type is the column's BasePeer::TYPE_PHPNAME * * @param array $arr An array to populate the object from. * @param string $keyType The type of keys the array uses. * @return void */ public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME) { $keys = MembresiaPeer::getFieldNames($keyType); if (array_key_exists($keys[0], $arr)) $this->setIdmembresia($arr[$keys[0]]); if (array_key_exists($keys[1], $arr)) $this->setMembresiaNombre($arr[$keys[1]]); if (array_key_exists($keys[2], $arr)) $this->setMembresiaDescripcion($arr[$keys[2]]); if (array_key_exists($keys[3], $arr)) $this->setMembresiaServicios($arr[$keys[3]]); if (array_key_exists($keys[4], $arr)) $this->setMembresiaCupones($arr[$keys[4]]); if (array_key_exists($keys[5], $arr)) $this->setServicioGeneraingreso($arr[$keys[5]]); if (array_key_exists($keys[6], $arr)) $this->setServicioGeneracomision($arr[$keys[6]]); if (array_key_exists($keys[7], $arr)) $this->setServicioTipocomision($arr[$keys[7]]); if (array_key_exists($keys[8], $arr)) $this->setServicioComision($arr[$keys[8]]); if (array_key_exists($keys[9], $arr)) $this->setMembresiaPrecio($arr[$keys[9]]); if (array_key_exists($keys[10], $arr)) $this->setMembresiaVigencia($arr[$keys[10]]); } /** * Build a Criteria object containing the values of all modified columns in this object. * * @return Criteria The Criteria object containing all modified values. */ public function buildCriteria() { $criteria = new Criteria(MembresiaPeer::DATABASE_NAME); if ($this->isColumnModified(MembresiaPeer::IDMEMBRESIA)) $criteria->add(MembresiaPeer::IDMEMBRESIA, $this->idmembresia); if ($this->isColumnModified(MembresiaPeer::MEMBRESIA_NOMBRE)) $criteria->add(MembresiaPeer::MEMBRESIA_NOMBRE, $this->membresia_nombre); if ($this->isColumnModified(MembresiaPeer::MEMBRESIA_DESCRIPCION)) $criteria->add(MembresiaPeer::MEMBRESIA_DESCRIPCION, $this->membresia_descripcion); if ($this->isColumnModified(MembresiaPeer::MEMBRESIA_SERVICIOS)) $criteria->add(MembresiaPeer::MEMBRESIA_SERVICIOS, $this->membresia_servicios); if ($this->isColumnModified(MembresiaPeer::MEMBRESIA_CUPONES)) $criteria->add(MembresiaPeer::MEMBRESIA_CUPONES, $this->membresia_cupones); if ($this->isColumnModified(MembresiaPeer::SERVICIO_GENERAINGRESO)) $criteria->add(MembresiaPeer::SERVICIO_GENERAINGRESO, $this->servicio_generaingreso); if ($this->isColumnModified(MembresiaPeer::SERVICIO_GENERACOMISION)) $criteria->add(MembresiaPeer::SERVICIO_GENERACOMISION, $this->servicio_generacomision); if ($this->isColumnModified(MembresiaPeer::SERVICIO_TIPOCOMISION)) $criteria->add(MembresiaPeer::SERVICIO_TIPOCOMISION, $this->servicio_tipocomision); if ($this->isColumnModified(MembresiaPeer::SERVICIO_COMISION)) $criteria->add(MembresiaPeer::SERVICIO_COMISION, $this->servicio_comision); if ($this->isColumnModified(MembresiaPeer::MEMBRESIA_PRECIO)) $criteria->add(MembresiaPeer::MEMBRESIA_PRECIO, $this->membresia_precio); if ($this->isColumnModified(MembresiaPeer::MEMBRESIA_VIGENCIA)) $criteria->add(MembresiaPeer::MEMBRESIA_VIGENCIA, $this->membresia_vigencia); return $criteria; } /** * Builds a Criteria object containing the primary key for this object. * * Unlike buildCriteria() this method includes the primary key values regardless * of whether or not they have been modified. * * @return Criteria The Criteria object containing value(s) for primary key(s). */ public function buildPkeyCriteria() { $criteria = new Criteria(MembresiaPeer::DATABASE_NAME); $criteria->add(MembresiaPeer::IDMEMBRESIA, $this->idmembresia); return $criteria; } /** * Returns the primary key for this object (row). * @return int */ public function getPrimaryKey() { return $this->getIdmembresia(); } /** * Generic method to set the primary key (idmembresia column). * * @param int $key Primary key. * @return void */ public function setPrimaryKey($key) { $this->setIdmembresia($key); } /** * Returns true if the primary key for this object is null. * @return boolean */ public function isPrimaryKeyNull() { return null === $this->getIdmembresia(); } /** * Sets contents of passed object to values from current object. * * If desired, this method can also make copies of all associated (fkey referrers) * objects. * * @param object $copyObj An object of Membresia (or compatible) type. * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. * @param boolean $makeNew Whether to reset autoincrement PKs and make the object new. * @throws PropelException */ public function copyInto($copyObj, $deepCopy = false, $makeNew = true) { $copyObj->setMembresiaNombre($this->getMembresiaNombre()); $copyObj->setMembresiaDescripcion($this->getMembresiaDescripcion()); $copyObj->setMembresiaServicios($this->getMembresiaServicios()); $copyObj->setMembresiaCupones($this->getMembresiaCupones()); $copyObj->setServicioGeneraingreso($this->getServicioGeneraingreso()); $copyObj->setServicioGeneracomision($this->getServicioGeneracomision()); $copyObj->setServicioTipocomision($this->getServicioTipocomision()); $copyObj->setServicioComision($this->getServicioComision()); $copyObj->setMembresiaPrecio($this->getMembresiaPrecio()); $copyObj->setMembresiaVigencia($this->getMembresiaVigencia()); if ($deepCopy && !$this->startCopy) { // important: temporarily setNew(false) because this affects the behavior of // the getter/setter methods for fkey referrer objects. $copyObj->setNew(false); // store object hash to prevent cycle $this->startCopy = true; foreach ($this->getMembresiaclinicas() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves $copyObj->addMembresiaclinica($relObj->copy($deepCopy)); } } foreach ($this->getPacientemembresias() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves $copyObj->addPacientemembresia($relObj->copy($deepCopy)); } } foreach ($this->getVisitadetalles() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves $copyObj->addVisitadetalle($relObj->copy($deepCopy)); } } //unflag object copy $this->startCopy = false; } // if ($deepCopy) if ($makeNew) { $copyObj->setNew(true); $copyObj->setIdmembresia(NULL); // this is a auto-increment column, so set to default value } } /** * Makes a copy of this object that will be inserted as a new row in table when saved. * It creates a new object filling in the simple attributes, but skipping any primary * keys that are defined for the table. * * If desired, this method can also make copies of all associated (fkey referrers) * objects. * * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. * @return Membresia Clone of current object. * @throws PropelException */ public function copy($deepCopy = false) { // we use get_class(), because this might be a subclass $clazz = get_class($this); $copyObj = new $clazz(); $this->copyInto($copyObj, $deepCopy); return $copyObj; } /** * Returns a peer instance associated with this om. * * Since Peer classes are not to have any instance attributes, this method returns the * same instance for all member of this class. The method could therefore * be static, but this would prevent one from overriding the behavior. * * @return MembresiaPeer */ public function getPeer() { if (self::$peer === null) { self::$peer = new MembresiaPeer(); } return self::$peer; } /** * Initializes a collection based on the name of a relation. * Avoids crafting an 'init[$relationName]s' method name * that wouldn't work when StandardEnglishPluralizer is used. * * @param string $relationName The name of the relation to initialize * @return void */ public function initRelation($relationName) { if ('Membresiaclinica' == $relationName) { $this->initMembresiaclinicas(); } if ('Pacientemembresia' == $relationName) { $this->initPacientemembresias(); } if ('Visitadetalle' == $relationName) { $this->initVisitadetalles(); } } /** * Clears out the collMembresiaclinicas collection * * This does not modify the database; however, it will remove any associated objects, causing * them to be refetched by subsequent calls to accessor method. * * @return Membresia The current object (for fluent API support) * @see addMembresiaclinicas() */ public function clearMembresiaclinicas() { $this->collMembresiaclinicas = null; // important to set this to null since that means it is uninitialized $this->collMembresiaclinicasPartial = null; return $this; } /** * reset is the collMembresiaclinicas collection loaded partially * * @return void */ public function resetPartialMembresiaclinicas($v = true) { $this->collMembresiaclinicasPartial = $v; } /** * Initializes the collMembresiaclinicas collection. * * By default this just sets the collMembresiaclinicas collection to an empty array (like clearcollMembresiaclinicas()); * however, you may wish to override this method in your stub class to provide setting appropriate * to your application -- for example, setting the initial array to the values stored in database. * * @param boolean $overrideExisting If set to true, the method call initializes * the collection even if it is not empty * * @return void */ public function initMembresiaclinicas($overrideExisting = true) { if (null !== $this->collMembresiaclinicas && !$overrideExisting) { return; } $this->collMembresiaclinicas = new PropelObjectCollection(); $this->collMembresiaclinicas->setModel('Membresiaclinica'); } /** * Gets an array of Membresiaclinica objects which contain a foreign key that references this object. * * If the $criteria is not null, it is used to always fetch the results from the database. * Otherwise the results are fetched from the database the first time, then cached. * Next time the same method is called without $criteria, the cached collection is returned. * If this Membresia is new, it will return * an empty collection or the current collection; the criteria is ignored on a new object. * * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @return PropelObjectCollection|Membresiaclinica[] List of Membresiaclinica objects * @throws PropelException */ public function getMembresiaclinicas($criteria = null, PropelPDO $con = null) { $partial = $this->collMembresiaclinicasPartial && !$this->isNew(); if (null === $this->collMembresiaclinicas || null !== $criteria || $partial) { if ($this->isNew() && null === $this->collMembresiaclinicas) { // return empty collection $this->initMembresiaclinicas(); } else { $collMembresiaclinicas = MembresiaclinicaQuery::create(null, $criteria) ->filterByMembresia($this) ->find($con); if (null !== $criteria) { if (false !== $this->collMembresiaclinicasPartial && count($collMembresiaclinicas)) { $this->initMembresiaclinicas(false); foreach ($collMembresiaclinicas as $obj) { if (false == $this->collMembresiaclinicas->contains($obj)) { $this->collMembresiaclinicas->append($obj); } } $this->collMembresiaclinicasPartial = true; } $collMembresiaclinicas->getInternalIterator()->rewind(); return $collMembresiaclinicas; } if ($partial && $this->collMembresiaclinicas) { foreach ($this->collMembresiaclinicas as $obj) { if ($obj->isNew()) { $collMembresiaclinicas[] = $obj; } } } $this->collMembresiaclinicas = $collMembresiaclinicas; $this->collMembresiaclinicasPartial = false; } } return $this->collMembresiaclinicas; } /** * Sets a collection of Membresiaclinica objects related by a one-to-many relationship * to the current object. * It will also schedule objects for deletion based on a diff between old objects (aka persisted) * and new objects from the given Propel collection. * * @param PropelCollection $membresiaclinicas A Propel collection. * @param PropelPDO $con Optional connection object * @return Membresia The current object (for fluent API support) */ public function setMembresiaclinicas(PropelCollection $membresiaclinicas, PropelPDO $con = null) { $membresiaclinicasToDelete = $this->getMembresiaclinicas(new Criteria(), $con)->diff($membresiaclinicas); $this->membresiaclinicasScheduledForDeletion = $membresiaclinicasToDelete; foreach ($membresiaclinicasToDelete as $membresiaclinicaRemoved) { $membresiaclinicaRemoved->setMembresia(null); } $this->collMembresiaclinicas = null; foreach ($membresiaclinicas as $membresiaclinica) { $this->addMembresiaclinica($membresiaclinica); } $this->collMembresiaclinicas = $membresiaclinicas; $this->collMembresiaclinicasPartial = false; return $this; } /** * Returns the number of related Membresiaclinica objects. * * @param Criteria $criteria * @param boolean $distinct * @param PropelPDO $con * @return int Count of related Membresiaclinica objects. * @throws PropelException */ public function countMembresiaclinicas(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) { $partial = $this->collMembresiaclinicasPartial && !$this->isNew(); if (null === $this->collMembresiaclinicas || null !== $criteria || $partial) { if ($this->isNew() && null === $this->collMembresiaclinicas) { return 0; } if ($partial && !$criteria) { return count($this->getMembresiaclinicas()); } $query = MembresiaclinicaQuery::create(null, $criteria); if ($distinct) { $query->distinct(); } return $query ->filterByMembresia($this) ->count($con); } return count($this->collMembresiaclinicas); } /** * Method called to associate a Membresiaclinica object to this object * through the Membresiaclinica foreign key attribute. * * @param Membresiaclinica $l Membresiaclinica * @return Membresia The current object (for fluent API support) */ public function addMembresiaclinica(Membresiaclinica $l) { if ($this->collMembresiaclinicas === null) { $this->initMembresiaclinicas(); $this->collMembresiaclinicasPartial = true; } if (!in_array($l, $this->collMembresiaclinicas->getArrayCopy(), true)) { // only add it if the **same** object is not already associated $this->doAddMembresiaclinica($l); if ($this->membresiaclinicasScheduledForDeletion and $this->membresiaclinicasScheduledForDeletion->contains($l)) { $this->membresiaclinicasScheduledForDeletion->remove($this->membresiaclinicasScheduledForDeletion->search($l)); } } return $this; } /** * @param Membresiaclinica $membresiaclinica The membresiaclinica object to add. */ protected function doAddMembresiaclinica($membresiaclinica) { $this->collMembresiaclinicas[]= $membresiaclinica; $membresiaclinica->setMembresia($this); } /** * @param Membresiaclinica $membresiaclinica The membresiaclinica object to remove. * @return Membresia The current object (for fluent API support) */ public function removeMembresiaclinica($membresiaclinica) { if ($this->getMembresiaclinicas()->contains($membresiaclinica)) { $this->collMembresiaclinicas->remove($this->collMembresiaclinicas->search($membresiaclinica)); if (null === $this->membresiaclinicasScheduledForDeletion) { $this->membresiaclinicasScheduledForDeletion = clone $this->collMembresiaclinicas; $this->membresiaclinicasScheduledForDeletion->clear(); } $this->membresiaclinicasScheduledForDeletion[]= clone $membresiaclinica; $membresiaclinica->setMembresia(null); } return $this; } /** * If this collection has already been initialized with * an identical criteria, it returns the collection. * Otherwise if this Membresia is new, it will return * an empty collection; or if this Membresia has previously * been saved, it will retrieve related Membresiaclinicas from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in Membresia. * * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) * @return PropelObjectCollection|Membresiaclinica[] List of Membresiaclinica objects */ public function getMembresiaclinicasJoinClinica($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { $query = MembresiaclinicaQuery::create(null, $criteria); $query->joinWith('Clinica', $join_behavior); return $this->getMembresiaclinicas($query, $con); } /** * Clears out the collPacientemembresias collection * * This does not modify the database; however, it will remove any associated objects, causing * them to be refetched by subsequent calls to accessor method. * * @return Membresia The current object (for fluent API support) * @see addPacientemembresias() */ public function clearPacientemembresias() { $this->collPacientemembresias = null; // important to set this to null since that means it is uninitialized $this->collPacientemembresiasPartial = null; return $this; } /** * reset is the collPacientemembresias collection loaded partially * * @return void */ public function resetPartialPacientemembresias($v = true) { $this->collPacientemembresiasPartial = $v; } /** * Initializes the collPacientemembresias collection. * * By default this just sets the collPacientemembresias collection to an empty array (like clearcollPacientemembresias()); * however, you may wish to override this method in your stub class to provide setting appropriate * to your application -- for example, setting the initial array to the values stored in database. * * @param boolean $overrideExisting If set to true, the method call initializes * the collection even if it is not empty * * @return void */ public function initPacientemembresias($overrideExisting = true) { if (null !== $this->collPacientemembresias && !$overrideExisting) { return; } $this->collPacientemembresias = new PropelObjectCollection(); $this->collPacientemembresias->setModel('Pacientemembresia'); } /** * Gets an array of Pacientemembresia objects which contain a foreign key that references this object. * * If the $criteria is not null, it is used to always fetch the results from the database. * Otherwise the results are fetched from the database the first time, then cached. * Next time the same method is called without $criteria, the cached collection is returned. * If this Membresia is new, it will return * an empty collection or the current collection; the criteria is ignored on a new object. * * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @return PropelObjectCollection|Pacientemembresia[] List of Pacientemembresia objects * @throws PropelException */ public function getPacientemembresias($criteria = null, PropelPDO $con = null) { $partial = $this->collPacientemembresiasPartial && !$this->isNew(); if (null === $this->collPacientemembresias || null !== $criteria || $partial) { if ($this->isNew() && null === $this->collPacientemembresias) { // return empty collection $this->initPacientemembresias(); } else { $collPacientemembresias = PacientemembresiaQuery::create(null, $criteria) ->filterByMembresia($this) ->find($con); if (null !== $criteria) { if (false !== $this->collPacientemembresiasPartial && count($collPacientemembresias)) { $this->initPacientemembresias(false); foreach ($collPacientemembresias as $obj) { if (false == $this->collPacientemembresias->contains($obj)) { $this->collPacientemembresias->append($obj); } } $this->collPacientemembresiasPartial = true; } $collPacientemembresias->getInternalIterator()->rewind(); return $collPacientemembresias; } if ($partial && $this->collPacientemembresias) { foreach ($this->collPacientemembresias as $obj) { if ($obj->isNew()) { $collPacientemembresias[] = $obj; } } } $this->collPacientemembresias = $collPacientemembresias; $this->collPacientemembresiasPartial = false; } } return $this->collPacientemembresias; } /** * Sets a collection of Pacientemembresia objects related by a one-to-many relationship * to the current object. * It will also schedule objects for deletion based on a diff between old objects (aka persisted) * and new objects from the given Propel collection. * * @param PropelCollection $pacientemembresias A Propel collection. * @param PropelPDO $con Optional connection object * @return Membresia The current object (for fluent API support) */ public function setPacientemembresias(PropelCollection $pacientemembresias, PropelPDO $con = null) { $pacientemembresiasToDelete = $this->getPacientemembresias(new Criteria(), $con)->diff($pacientemembresias); $this->pacientemembresiasScheduledForDeletion = $pacientemembresiasToDelete; foreach ($pacientemembresiasToDelete as $pacientemembresiaRemoved) { $pacientemembresiaRemoved->setMembresia(null); } $this->collPacientemembresias = null; foreach ($pacientemembresias as $pacientemembresia) { $this->addPacientemembresia($pacientemembresia); } $this->collPacientemembresias = $pacientemembresias; $this->collPacientemembresiasPartial = false; return $this; } /** * Returns the number of related Pacientemembresia objects. * * @param Criteria $criteria * @param boolean $distinct * @param PropelPDO $con * @return int Count of related Pacientemembresia objects. * @throws PropelException */ public function countPacientemembresias(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) { $partial = $this->collPacientemembresiasPartial && !$this->isNew(); if (null === $this->collPacientemembresias || null !== $criteria || $partial) { if ($this->isNew() && null === $this->collPacientemembresias) { return 0; } if ($partial && !$criteria) { return count($this->getPacientemembresias()); } $query = PacientemembresiaQuery::create(null, $criteria); if ($distinct) { $query->distinct(); } return $query ->filterByMembresia($this) ->count($con); } return count($this->collPacientemembresias); } /** * Method called to associate a Pacientemembresia object to this object * through the Pacientemembresia foreign key attribute. * * @param Pacientemembresia $l Pacientemembresia * @return Membresia The current object (for fluent API support) */ public function addPacientemembresia(Pacientemembresia $l) { if ($this->collPacientemembresias === null) { $this->initPacientemembresias(); $this->collPacientemembresiasPartial = true; } if (!in_array($l, $this->collPacientemembresias->getArrayCopy(), true)) { // only add it if the **same** object is not already associated $this->doAddPacientemembresia($l); if ($this->pacientemembresiasScheduledForDeletion and $this->pacientemembresiasScheduledForDeletion->contains($l)) { $this->pacientemembresiasScheduledForDeletion->remove($this->pacientemembresiasScheduledForDeletion->search($l)); } } return $this; } /** * @param Pacientemembresia $pacientemembresia The pacientemembresia object to add. */ protected function doAddPacientemembresia($pacientemembresia) { $this->collPacientemembresias[]= $pacientemembresia; $pacientemembresia->setMembresia($this); } /** * @param Pacientemembresia $pacientemembresia The pacientemembresia object to remove. * @return Membresia The current object (for fluent API support) */ public function removePacientemembresia($pacientemembresia) { if ($this->getPacientemembresias()->contains($pacientemembresia)) { $this->collPacientemembresias->remove($this->collPacientemembresias->search($pacientemembresia)); if (null === $this->pacientemembresiasScheduledForDeletion) { $this->pacientemembresiasScheduledForDeletion = clone $this->collPacientemembresias; $this->pacientemembresiasScheduledForDeletion->clear(); } $this->pacientemembresiasScheduledForDeletion[]= clone $pacientemembresia; $pacientemembresia->setMembresia(null); } return $this; } /** * If this collection has already been initialized with * an identical criteria, it returns the collection. * Otherwise if this Membresia is new, it will return * an empty collection; or if this Membresia has previously * been saved, it will retrieve related Pacientemembresias from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in Membresia. * * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) * @return PropelObjectCollection|Pacientemembresia[] List of Pacientemembresia objects */ public function getPacientemembresiasJoinClinica($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { $query = PacientemembresiaQuery::create(null, $criteria); $query->joinWith('Clinica', $join_behavior); return $this->getPacientemembresias($query, $con); } /** * If this collection has already been initialized with * an identical criteria, it returns the collection. * Otherwise if this Membresia is new, it will return * an empty collection; or if this Membresia has previously * been saved, it will retrieve related Pacientemembresias from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in Membresia. * * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) * @return PropelObjectCollection|Pacientemembresia[] List of Pacientemembresia objects */ public function getPacientemembresiasJoinPaciente($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { $query = PacientemembresiaQuery::create(null, $criteria); $query->joinWith('Paciente', $join_behavior); return $this->getPacientemembresias($query, $con); } /** * Clears out the collVisitadetalles collection * * This does not modify the database; however, it will remove any associated objects, causing * them to be refetched by subsequent calls to accessor method. * * @return Membresia The current object (for fluent API support) * @see addVisitadetalles() */ public function clearVisitadetalles() { $this->collVisitadetalles = null; // important to set this to null since that means it is uninitialized $this->collVisitadetallesPartial = null; return $this; } /** * reset is the collVisitadetalles collection loaded partially * * @return void */ public function resetPartialVisitadetalles($v = true) { $this->collVisitadetallesPartial = $v; } /** * Initializes the collVisitadetalles collection. * * By default this just sets the collVisitadetalles collection to an empty array (like clearcollVisitadetalles()); * however, you may wish to override this method in your stub class to provide setting appropriate * to your application -- for example, setting the initial array to the values stored in database. * * @param boolean $overrideExisting If set to true, the method call initializes * the collection even if it is not empty * * @return void */ public function initVisitadetalles($overrideExisting = true) { if (null !== $this->collVisitadetalles && !$overrideExisting) { return; } $this->collVisitadetalles = new PropelObjectCollection(); $this->collVisitadetalles->setModel('Visitadetalle'); } /** * Gets an array of Visitadetalle objects which contain a foreign key that references this object. * * If the $criteria is not null, it is used to always fetch the results from the database. * Otherwise the results are fetched from the database the first time, then cached. * Next time the same method is called without $criteria, the cached collection is returned. * If this Membresia is new, it will return * an empty collection or the current collection; the criteria is ignored on a new object. * * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @return PropelObjectCollection|Visitadetalle[] List of Visitadetalle objects * @throws PropelException */ public function getVisitadetalles($criteria = null, PropelPDO $con = null) { $partial = $this->collVisitadetallesPartial && !$this->isNew(); if (null === $this->collVisitadetalles || null !== $criteria || $partial) { if ($this->isNew() && null === $this->collVisitadetalles) { // return empty collection $this->initVisitadetalles(); } else { $collVisitadetalles = VisitadetalleQuery::create(null, $criteria) ->filterByMembresia($this) ->find($con); if (null !== $criteria) { if (false !== $this->collVisitadetallesPartial && count($collVisitadetalles)) { $this->initVisitadetalles(false); foreach ($collVisitadetalles as $obj) { if (false == $this->collVisitadetalles->contains($obj)) { $this->collVisitadetalles->append($obj); } } $this->collVisitadetallesPartial = true; } $collVisitadetalles->getInternalIterator()->rewind(); return $collVisitadetalles; } if ($partial && $this->collVisitadetalles) { foreach ($this->collVisitadetalles as $obj) { if ($obj->isNew()) { $collVisitadetalles[] = $obj; } } } $this->collVisitadetalles = $collVisitadetalles; $this->collVisitadetallesPartial = false; } } return $this->collVisitadetalles; } /** * Sets a collection of Visitadetalle objects related by a one-to-many relationship * to the current object. * It will also schedule objects for deletion based on a diff between old objects (aka persisted) * and new objects from the given Propel collection. * * @param PropelCollection $visitadetalles A Propel collection. * @param PropelPDO $con Optional connection object * @return Membresia The current object (for fluent API support) */ public function setVisitadetalles(PropelCollection $visitadetalles, PropelPDO $con = null) { $visitadetallesToDelete = $this->getVisitadetalles(new Criteria(), $con)->diff($visitadetalles); $this->visitadetallesScheduledForDeletion = $visitadetallesToDelete; foreach ($visitadetallesToDelete as $visitadetalleRemoved) { $visitadetalleRemoved->setMembresia(null); } $this->collVisitadetalles = null; foreach ($visitadetalles as $visitadetalle) { $this->addVisitadetalle($visitadetalle); } $this->collVisitadetalles = $visitadetalles; $this->collVisitadetallesPartial = false; return $this; } /** * Returns the number of related Visitadetalle objects. * * @param Criteria $criteria * @param boolean $distinct * @param PropelPDO $con * @return int Count of related Visitadetalle objects. * @throws PropelException */ public function countVisitadetalles(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) { $partial = $this->collVisitadetallesPartial && !$this->isNew(); if (null === $this->collVisitadetalles || null !== $criteria || $partial) { if ($this->isNew() && null === $this->collVisitadetalles) { return 0; } if ($partial && !$criteria) { return count($this->getVisitadetalles()); } $query = VisitadetalleQuery::create(null, $criteria); if ($distinct) { $query->distinct(); } return $query ->filterByMembresia($this) ->count($con); } return count($this->collVisitadetalles); } /** * Method called to associate a Visitadetalle object to this object * through the Visitadetalle foreign key attribute. * * @param Visitadetalle $l Visitadetalle * @return Membresia The current object (for fluent API support) */ public function addVisitadetalle(Visitadetalle $l) { if ($this->collVisitadetalles === null) { $this->initVisitadetalles(); $this->collVisitadetallesPartial = true; } if (!in_array($l, $this->collVisitadetalles->getArrayCopy(), true)) { // only add it if the **same** object is not already associated $this->doAddVisitadetalle($l); if ($this->visitadetallesScheduledForDeletion and $this->visitadetallesScheduledForDeletion->contains($l)) { $this->visitadetallesScheduledForDeletion->remove($this->visitadetallesScheduledForDeletion->search($l)); } } return $this; } /** * @param Visitadetalle $visitadetalle The visitadetalle object to add. */ protected function doAddVisitadetalle($visitadetalle) { $this->collVisitadetalles[]= $visitadetalle; $visitadetalle->setMembresia($this); } /** * @param Visitadetalle $visitadetalle The visitadetalle object to remove. * @return Membresia The current object (for fluent API support) */ public function removeVisitadetalle($visitadetalle) { if ($this->getVisitadetalles()->contains($visitadetalle)) { $this->collVisitadetalles->remove($this->collVisitadetalles->search($visitadetalle)); if (null === $this->visitadetallesScheduledForDeletion) { $this->visitadetallesScheduledForDeletion = clone $this->collVisitadetalles; $this->visitadetallesScheduledForDeletion->clear(); } $this->visitadetallesScheduledForDeletion[]= $visitadetalle; $visitadetalle->setMembresia(null); } return $this; } /** * If this collection has already been initialized with * an identical criteria, it returns the collection. * Otherwise if this Membresia is new, it will return * an empty collection; or if this Membresia has previously * been saved, it will retrieve related Visitadetalles from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in Membresia. * * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) * @return PropelObjectCollection|Visitadetalle[] List of Visitadetalle objects */ public function getVisitadetallesJoinProductoclinica($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { $query = VisitadetalleQuery::create(null, $criteria); $query->joinWith('Productoclinica', $join_behavior); return $this->getVisitadetalles($query, $con); } /** * If this collection has already been initialized with * an identical criteria, it returns the collection. * Otherwise if this Membresia is new, it will return * an empty collection; or if this Membresia has previously * been saved, it will retrieve related Visitadetalles from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in Membresia. * * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) * @return PropelObjectCollection|Visitadetalle[] List of Visitadetalle objects */ public function getVisitadetallesJoinServicioclinica($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { $query = VisitadetalleQuery::create(null, $criteria); $query->joinWith('Servicioclinica', $join_behavior); return $this->getVisitadetalles($query, $con); } /** * If this collection has already been initialized with * an identical criteria, it returns the collection. * Otherwise if this Membresia is new, it will return * an empty collection; or if this Membresia has previously * been saved, it will retrieve related Visitadetalles from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in Membresia. * * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) * @return PropelObjectCollection|Visitadetalle[] List of Visitadetalle objects */ public function getVisitadetallesJoinVisita($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { $query = VisitadetalleQuery::create(null, $criteria); $query->joinWith('Visita', $join_behavior); return $this->getVisitadetalles($query, $con); } /** * Clears the current object and sets all attributes to their default values */ public function clear() { $this->idmembresia = null; $this->membresia_nombre = null; $this->membresia_descripcion = null; $this->membresia_servicios = null; $this->membresia_cupones = null; $this->servicio_generaingreso = null; $this->servicio_generacomision = null; $this->servicio_tipocomision = null; $this->servicio_comision = null; $this->membresia_precio = null; $this->membresia_vigencia = null; $this->alreadyInSave = false; $this->alreadyInValidation = false; $this->alreadyInClearAllReferencesDeep = false; $this->clearAllReferences(); $this->resetModified(); $this->setNew(true); $this->setDeleted(false); } /** * Resets all references to other model objects or collections of model objects. * * This method is a user-space workaround for PHP's inability to garbage collect * objects with circular references (even in PHP 5.3). This is currently necessary * when using Propel in certain daemon or large-volume/high-memory operations. * * @param boolean $deep Whether to also clear the references on all referrer objects. */ public function clearAllReferences($deep = false) { if ($deep && !$this->alreadyInClearAllReferencesDeep) { $this->alreadyInClearAllReferencesDeep = true; if ($this->collMembresiaclinicas) { foreach ($this->collMembresiaclinicas as $o) { $o->clearAllReferences($deep); } } if ($this->collPacientemembresias) { foreach ($this->collPacientemembresias as $o) { $o->clearAllReferences($deep); } } if ($this->collVisitadetalles) { foreach ($this->collVisitadetalles as $o) { $o->clearAllReferences($deep); } } $this->alreadyInClearAllReferencesDeep = false; } // if ($deep) if ($this->collMembresiaclinicas instanceof PropelCollection) { $this->collMembresiaclinicas->clearIterator(); } $this->collMembresiaclinicas = null; if ($this->collPacientemembresias instanceof PropelCollection) { $this->collPacientemembresias->clearIterator(); } $this->collPacientemembresias = null; if ($this->collVisitadetalles instanceof PropelCollection) { $this->collVisitadetalles->clearIterator(); } $this->collVisitadetalles = null; } /** * return the string representation of this object * * @return string */ public function __toString() { return (string) $this->exportTo(MembresiaPeer::DEFAULT_STRING_FORMAT); } /** * return true is the object is in saving state * * @return boolean */ public function isAlreadyInSave() { return $this->alreadyInSave; } }
{ "content_hash": "10427f77d67fa13dc19ea6cc9ccf21af", "timestamp": "", "source": "github", "line_count": 2378, "max_line_length": 164, "avg_line_length": 36.8448275862069, "alnum_prop": 0.5908784824862755, "repo_name": "dcastanedob/feetcenter", "id": "82f289053307a083ccf6c07d5e8c40f51ce71b59", "size": "87617", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "module/Propel/build/classes/feetcent_feetcenter/om/BaseMembresia.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "711" }, { "name": "CSS", "bytes": "372682" }, { "name": "HTML", "bytes": "649253" }, { "name": "JavaScript", "bytes": "2538978" }, { "name": "PHP", "bytes": "14297161" } ], "symlink_target": "" }
package com.github.rapid.security.admin.mapper; import com.github.rapid.security.admin.entity.Element; import org.apache.ibatis.annotations.Param; import tk.mybatis.mapper.common.Mapper; import java.util.List; /** * * @author sun-abel * @create 2017-10-23 下午6:38 **/ public interface ElementMapper extends Mapper<Element> { public List<Element> selectAuthorityElementByUserId(@Param("userId")String userId); public List<Element> selectAuthorityMenuElementByUserId(@Param("userId")String userId,@Param("menuId")String menuId); public List<Element> selectAuthorityElementByClientId(@Param("clientId")String clientId); }
{ "content_hash": "48c7e3443a7e341f32a0218a79c95a97", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 121, "avg_line_length": 35.333333333333336, "alnum_prop": 0.7814465408805031, "repo_name": "TokenSoftware/Rapid-Security", "id": "2988206305efc6e747d20bf086f8f1e0dcfb1539", "size": "640", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rapid-admin/src/main/java/com/github/rapid/security/admin/mapper/ElementMapper.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "5186" }, { "name": "HTML", "bytes": "1607" }, { "name": "Java", "bytes": "177562" }, { "name": "PLpgSQL", "bytes": "74592" }, { "name": "Shell", "bytes": "338" } ], "symlink_target": "" }
/* Includes ------------------------------------------------------------------*/ #include "stm32f30x_pwr.h" #include "stm32f30x_rcc.h" /** @addtogroup STM32F30x_StdPeriph_Driver * @{ */ /** @defgroup PWR * @brief PWR driver modules * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* --------- PWR registers bit address in the alias region ---------- */ #define PWR_OFFSET (PWR_BASE - PERIPH_BASE) /* --- CR Register ---*/ /* Alias word address of DBP bit */ #define CR_OFFSET (PWR_OFFSET + 0x00) #define DBP_BitNumber 0x08 #define CR_DBP_BB (PERIPH_BB_BASE + (CR_OFFSET * 32) + (DBP_BitNumber * 4)) /* Alias word address of PVDE bit */ #define PVDE_BitNumber 0x04 #define CR_PVDE_BB (PERIPH_BB_BASE + (CR_OFFSET * 32) + (PVDE_BitNumber * 4)) /* ------------------ PWR registers bit mask ------------------------ */ /* CR register bit mask */ #define CR_DS_MASK ((uint32_t)0xFFFFFFFC) #define CR_PLS_MASK ((uint32_t)0xFFFFFF1F) /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /** @defgroup PWR_Private_Functions * @{ */ /** @defgroup PWR_Group1 Backup Domain Access function * @brief Backup Domain Access function * @verbatim ============================================================================== ##### Backup Domain Access function ##### ============================================================================== [..] After reset, the Backup Domain Registers (RCC BDCR Register, RTC registers and RTC backup registers) are protected against possible stray write accesses. [..] To enable access to Backup domain use the PWR_BackupAccessCmd(ENABLE) function. @endverbatim * @{ */ /** * @brief Deinitializes the PWR peripheral registers to their default reset values. * @param None * @retval None */ void PWR_DeInit(void) { RCC_APB1PeriphResetCmd(RCC_APB1Periph_PWR, ENABLE); RCC_APB1PeriphResetCmd(RCC_APB1Periph_PWR, DISABLE); } /** * @brief Enables or disables access to the RTC and backup registers. * @note If the HSE divided by 32 is used as the RTC clock, the * Backup Domain Access should be kept enabled. * @param NewState: new state of the access to the RTC and backup registers. * This parameter can be: ENABLE or DISABLE. * @retval None */ void PWR_BackupAccessCmd(FunctionalState NewState) { /* Check the parameters */ assert_param(IS_FUNCTIONAL_STATE(NewState)); *(__IO uint32_t *) CR_DBP_BB = (uint32_t)NewState; } /** * @} */ /** @defgroup PWR_Group2 PVD configuration functions * @brief PVD configuration functions * @verbatim =============================================================================== ##### PVD configuration functions ##### ============================================================================== [..] (+) The PVD is used to monitor the VDD power supply by comparing it to a threshold selected by the PVD Level (PLS[2:0] bits in the PWR_CR). (+) A PVDO flag is available to indicate if VDD/VDDA is higher or lower than the PVD threshold. This event is internally connected to the EXTI line16 and can generate an interrupt if enabled through the EXTI registers. (+) The PVD is stopped in Standby mode. @endverbatim * @{ */ /** * @brief Configures the voltage threshold detected by the Power Voltage Detector(PVD). * @param PWR_PVDLevel: specifies the PVD detection level * This parameter can be one of the following values: * @arg PWR_PVDLevel_0: PVD detection level set to 2.18V * @arg PWR_PVDLevel_1: PVD detection level set to 2.28V * @arg PWR_PVDLevel_2: PVD detection level set to 2.38V * @arg PWR_PVDLevel_3: PVD detection level set to 2.48V * @arg PWR_PVDLevel_4: PVD detection level set to 2.58V * @arg PWR_PVDLevel_5: PVD detection level set to 2.68V * @arg PWR_PVDLevel_6: PVD detection level set to 2.78V * @arg PWR_PVDLevel_7: PVD detection level set to 2.88V * @retval None */ void PWR_PVDLevelConfig(uint32_t PWR_PVDLevel) { uint32_t tmpreg = 0; /* Check the parameters */ assert_param(IS_PWR_PVD_LEVEL(PWR_PVDLevel)); tmpreg = PWR->CR; /* Clear PLS[7:5] bits */ tmpreg &= CR_PLS_MASK; /* Set PLS[7:5] bits according to PWR_PVDLevel value */ tmpreg |= PWR_PVDLevel; /* Store the new value */ PWR->CR = tmpreg; } /** * @brief Enables or disables the Power Voltage Detector(PVD). * @param NewState: new state of the PVD. * This parameter can be: ENABLE or DISABLE. * @retval None */ void PWR_PVDCmd(FunctionalState NewState) { /* Check the parameters */ assert_param(IS_FUNCTIONAL_STATE(NewState)); *(__IO uint32_t *) CR_PVDE_BB = (uint32_t)NewState; } /** * @} */ /** @defgroup PWR_Group3 WakeUp pins configuration functions * @brief WakeUp pins configuration functions * @verbatim =============================================================================== ##### WakeUp pins configuration functions ##### =============================================================================== [..] (+) WakeUp pins are used to wakeup the system from Standby mode. These pins are forced in input pull down configuration and are active on rising edges. (+) There are three WakeUp pins: WakeUp Pin 1 on PA.00, WakeUp Pin 2 on PC.13 and WakeUp Pin 3 on PE.06. @endverbatim * @{ */ /** * @brief Enables or disables the WakeUp Pin functionality. * @param PWR_WakeUpPin: specifies the WakeUpPin. * This parameter can be: PWR_WakeUpPin_1, PWR_WakeUpPin_2 or PWR_WakeUpPin_3. * @param NewState: new state of the WakeUp Pin functionality. * This parameter can be: ENABLE or DISABLE. * @retval None */ void PWR_WakeUpPinCmd(uint32_t PWR_WakeUpPin, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_PWR_WAKEUP_PIN(PWR_WakeUpPin)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the EWUPx pin */ PWR->CSR |= PWR_WakeUpPin; } else { /* Disable the EWUPx pin */ PWR->CSR &= ~PWR_WakeUpPin; } } /** * @} */ /** @defgroup PWR_Group4 Low Power modes configuration functions * @brief Low Power modes configuration functions * @verbatim =============================================================================== ##### Low Power modes configuration functions ##### ============================================================================== [..] The devices feature three low-power modes: (+) Sleep mode: Cortex-M4 core stopped, peripherals kept running. (+) Stop mode: all clocks are stopped, regulator running, regulator in low power mode (+) Standby mode: VCORE domain powered off *** Sleep mode *** ================== [..] (+) Entry: (++) The Sleep mode is entered by executing the WFE() or WFI() instructions. (+) Exit: (++) Any peripheral interrupt acknowledged by the nested vectored interrupt controller (NVIC) can wake up the device from Sleep mode. *** Stop mode *** ================= [..] In Stop mode, all clocks in the VCORE domain are stopped, the PLL, the HSI, and the HSE RC oscillators are disabled. Internal SRAM and register contents are preserved. The voltage regulator can be configured either in normal or low-power mode. (+) Entry: (++) The Stop mode is entered using the PWR_EnterSTOPMode(PWR_Regulator_LowPower,) function with regulator in LowPower or with Regulator ON. (+) Exit: (++) Any EXTI Line (Internal or External) configured in Interrupt/Event mode or any internal IPs (I2C or UASRT) wakeup event. *** Standby mode *** ==================== [..] The Standby mode allows to achieve the lowest power consumption. It is based on the Cortex-M4 deepsleep mode, with the voltage regulator disabled. The VCORE domain is consequently powered off. The PLL, the HSI, and the HSE oscillator are also switched off. SRAM and register contents are lost except for the Backup domain (RTC registers, RTC backup registers and Standby circuitry). [..] The voltage regulator is OFF. (+) Entry: (++) The Standby mode is entered using the PWR_EnterSTANDBYMode() function. (+) Exit: (++) WKUP pin rising edge, RTC alarm (Alarm A and Alarm B), RTC wakeup, tamper event, time-stamp event, external reset in NRST pin, IWDG reset. *** Auto-wakeup (AWU) from low-power mode *** ============================================= [..] The MCU can be woken up from low-power mode by an RTC Alarm event, a tamper event, a time-stamp event, or a comparator event, without depending on an external interrupt (Auto-wakeup mode). (+) RTC auto-wakeup (AWU) from the Stop mode (++) To wake up from the Stop mode with an RTC alarm event, it is necessary to: (+++) Configure the EXTI Line 17 to be sensitive to rising edges (Interrupt or Event modes) using the EXTI_Init() function. (+++) Enable the RTC Alarm Interrupt using the RTC_ITConfig() function (+++) Configure the RTC to generate the RTC alarm using the RTC_SetAlarm() and RTC_AlarmCmd() functions. (++) To wake up from the Stop mode with an RTC Tamper or time stamp event, it is necessary to: (+++) Configure the EXTI Line 19 to be sensitive to rising edges (Interrupt or Event modes) using the EXTI_Init() function. (+++) Enable the RTC Tamper or time stamp Interrupt using the RTC_ITConfig() function. (+++) Configure the RTC to detect the tamper or time stamp event using the RTC_TimeStampConfig(), RTC_TamperTriggerConfig() and RTC_TamperCmd() functions. (+) RTC auto-wakeup (AWU) from the Standby mode (++) To wake up from the Standby mode with an RTC alarm event, it is necessary to: (+++) Enable the RTC Alarm Interrupt using the RTC_ITConfig() function. (+++) Configure the RTC to generate the RTC alarm using the RTC_SetAlarm() and RTC_AlarmCmd() functions. (++) To wake up from the Standby mode with an RTC Tamper or time stamp event, it is necessary to: (+++) Enable the RTC Tamper or time stamp Interrupt using the RTC_ITConfig() function. (+++) Configure the RTC to detect the tamper or time stamp event using the RTC_TimeStampConfig(), RTC_TamperTriggerConfig() and RTC_TamperCmd() functions. (+) Comparator auto-wakeup (AWU) from the Stop mode (++) To wake up from the Stop mode with a comparator wakeup event, it is necessary to: (+++) Configure the correspondent comparator EXTI Line to be sensitive to the selected edges (falling, rising or falling and rising) (Interrupt or Event modes) using the EXTI_Init() function. (+++) Configure the comparator to generate the event. @endverbatim * @{ */ /** * @brief Enters Sleep mode. * @note In Sleep mode, all I/O pins keep the same state as in Run mode. * @param PWR_SLEEPEntry: specifies if SLEEP mode in entered with WFI or WFE instruction. * This parameter can be one of the following values: * @arg PWR_SLEEPEntry_WFI: enter SLEEP mode with WFI instruction * @arg PWR_SLEEPEntry_WFE: enter SLEEP mode with WFE instruction * @retval None */ void PWR_EnterSleepMode(uint8_t PWR_SLEEPEntry) { /* Check the parameters */ assert_param(IS_PWR_SLEEP_ENTRY(PWR_SLEEPEntry)); /* Clear SLEEPDEEP bit of Cortex System Control Register */ SCB->SCR &= (uint32_t)~((uint32_t)SCB_SCR_SLEEPDEEP_Msk); /* Select SLEEP mode entry -------------------------------------------------*/ if(PWR_SLEEPEntry == PWR_SLEEPEntry_WFI) { /* Request Wait For Interrupt */ __WFI(); } else { /* Request Wait For Event */ __SEV(); __WFE(); __WFE(); } } /** * @brief Enters STOP mode. * @note In Stop mode, all I/O pins keep the same state as in Run mode. * @note When exiting Stop mode by issuing an interrupt or a wakeup event, * the HSI RC oscillator is selected as system clock. * @note When the voltage regulator operates in low power mode, an additional * startup delay is incurred when waking up from Stop mode. * By keeping the internal regulator ON during Stop mode, the consumption * is higher although the startup time is reduced. * @param PWR_Regulator: specifies the regulator state in STOP mode. * This parameter can be one of the following values: * @arg PWR_Regulator_ON: STOP mode with regulator ON * @arg PWR_Regulator_LowPower: STOP mode with regulator in low power mode * @param PWR_STOPEntry: specifies if STOP mode in entered with WFI or WFE instruction. * This parameter can be one of the following values: * @arg PWR_STOPEntry_WFI: enter STOP mode with WFI instruction * @arg PWR_STOPEntry_WFE: enter STOP mode with WFE instruction * @retval None */ void PWR_EnterSTOPMode(uint32_t PWR_Regulator, uint8_t PWR_STOPEntry) { uint32_t tmpreg = 0; /* Check the parameters */ assert_param(IS_PWR_REGULATOR(PWR_Regulator)); assert_param(IS_PWR_STOP_ENTRY(PWR_STOPEntry)); /* Select the regulator state in STOP mode ---------------------------------*/ tmpreg = PWR->CR; /* Clear PDDS and LPDSR bits */ tmpreg &= CR_DS_MASK; /* Set LPDSR bit according to PWR_Regulator value */ tmpreg |= PWR_Regulator; /* Store the new value */ PWR->CR = tmpreg; /* Set SLEEPDEEP bit of Cortex System Control Register */ SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; /* Select STOP mode entry --------------------------------------------------*/ if(PWR_STOPEntry == PWR_STOPEntry_WFI) { /* Request Wait For Interrupt */ __WFI(); } else { /* Request Wait For Event */ __WFE(); } /* Reset SLEEPDEEP bit of Cortex System Control Register */ SCB->SCR &= (uint32_t)~((uint32_t)SCB_SCR_SLEEPDEEP_Msk); } /** * @brief Enters STANDBY mode. * @note In Standby mode, all I/O pins are high impedance except for: * @note Reset pad (still available) * @note RTC_AF1 pin (PC13) if configured for Wakeup pin 2 (WKUP2), tamper, * time-stamp, RTC Alarm out, or RTC clock calibration out. * @note WKUP pin 1 (PA0) and WKUP pin 3 (PE6), if enabled. * @note The Wakeup flag (WUF) need to be cleared at application level before to call this function. * @param None * @retval None */ void PWR_EnterSTANDBYMode(void) { /* Select STANDBY mode */ PWR->CR |= PWR_CR_PDDS; /* Set SLEEPDEEP bit of Cortex System Control Register */ SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; /* This option is used to ensure that store operations are completed */ #if defined ( __CC_ARM ) __force_stores(); #endif /* Request Wait For Interrupt */ __WFI(); } /** * @} */ /** @defgroup PWR_Group5 Flags management functions * @brief Flags management functions * @verbatim =============================================================================== ##### Flags management functions ##### =============================================================================== @endverbatim * @{ */ /** * @brief Checks whether the specified PWR flag is set or not. * @param PWR_FLAG: specifies the flag to check. * This parameter can be one of the following values: * @arg PWR_FLAG_WU: Wake Up flag. This flag indicates that a wakeup event * was received from the WKUP pin or from the RTC alarm (Alarm A or Alarm B), * RTC Tamper event, RTC TimeStamp event or RTC Wakeup. * @arg PWR_FLAG_SB: StandBy flag. This flag indicates that the system was * resumed from StandBy mode. * @arg PWR_FLAG_PVDO: PVD Output. This flag is valid only if PVD is enabled * by the PWR_PVDCmd() function. * @arg PWR_FLAG_VREFINTRDY: Internal Voltage Reference Ready flag. This * flag indicates the state of the internal voltage reference, VREFINT. * @retval The new state of PWR_FLAG (SET or RESET). */ FlagStatus PWR_GetFlagStatus(uint32_t PWR_FLAG) { FlagStatus bitstatus = RESET; /* Check the parameters */ assert_param(IS_PWR_GET_FLAG(PWR_FLAG)); if ((PWR->CSR & PWR_FLAG) != (uint32_t)RESET) { bitstatus = SET; } else { bitstatus = RESET; } /* Return the flag status */ return bitstatus; } /** * @brief Clears the PWR's pending flags. * @param PWR_FLAG: specifies the flag to clear. * This parameter can be one of the following values: * @arg PWR_FLAG_WU: Wake Up flag * @arg PWR_FLAG_SB: StandBy flag * @retval None */ void PWR_ClearFlag(uint32_t PWR_FLAG) { /* Check the parameters */ assert_param(IS_PWR_CLEAR_FLAG(PWR_FLAG)); PWR->CR |= PWR_FLAG << 2; } /** * @} */ /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
{ "content_hash": "c8defb3f1b6c3b9a770a1e3411c97073", "timestamp": "", "source": "github", "line_count": 506, "max_line_length": 109, "avg_line_length": 35.75296442687747, "alnum_prop": 0.5779669448897242, "repo_name": "KitSprout/MicroMultimeter", "id": "41b95de0985987c2b40f7000ac12248b77aa4522", "size": "19515", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "Software/uM_ModuleSTD_OLED-WF/Libraries/STM32F30x_StdPeriph_Driver/src/stm32f30x_pwr.c", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "132608" }, { "name": "Batchfile", "bytes": "2604" }, { "name": "C", "bytes": "43202857" }, { "name": "C++", "bytes": "689087" }, { "name": "HTML", "bytes": "1384586" } ], "symlink_target": "" }
.. extension-writing: **************************** Tutorial: Extension writing **************************** MathJax is designed in a way that makes it easy to write extensions. Examples can be found in the `MathJax third party extensions <https://github.com/mathjax/MathJax-third-party-extensions>`__ repository; see also :ref:`ThirdParty`. In this tutorial, we are going to see how to write your own MathJax extension. No specific prerequisites are assumed, except that you already have a local :ref:`installation <installation>` and of course some familiarity with how to use MathJax. The Big Picture --------------- We suppose that you have a copy of MathJax in a ``MathJax/`` directory and that the URL ``http://localhost/MathJax/`` points to that directory. We also assume that you have a local Web server running at ``http://localhost/`` ; this is not mandatory but will avoid issues with the cross-origin security policy. First, note that the source code of MathJax is "packed" so that the JavaScript files are smaller and take less time to download. These files are not easy to read and edit, so for development purposes we will work with the ``MathJax/unpacked/`` directory. Hence you should load the unpacked ``MathJax.js`` to run MathJax on your pages. For example if you write a file like .. code-block:: html MathJax/unpacked/test0.html <!doctype html> <html> <head> <title>testcase</title> <meta charset="utf-8"> <script type="text/javascript" src="http://localhost/MathJax/unpacked/MathJax.js?config=TeX-MML-AM_CHTML"> </script> </head> <body> <p>TeX: \(\frac a b\)</p> <p>MathML: <math><msqrt><mi>x</mi></msqrt></math></p> <p>AsciiMath: `a^2 + b^2 = c^2`</p> </body> </html> then the page ``http://localhost/MathJax/unpacked/test0.html`` should contain formatted equations corresponding to the TeX, MathML and AsciiMath sources. ``MathJax.js`` is the main file, which initializes MathJax and loads all its components. The most important ones are represented in the diagram below. The input modes (in blue) are located in ``unpacked/jax/input/`` and transform the corresponding given input text into MathJax's internal strutures (in red) located in ``unpacked/jax/element`` (only one format at the moment, essentially "MathML"). Then this internal structure is rendered by the output modes (in green) located in ``unpacked/jax/output``. The MathJax extensions are located in ``unpacked/extensions/`` and can modify or extend the MathJax components. .. image:: /_static/components.svg :width: 50% :alt: MathJax components One feature of MathJax is that other Javascript files are loaded only when they are necessary. Extensions generally use other components so you must be sure that they are already loaded before running the extension. Similarly, the extension may need to indicate when it is ready so that other components can use it. :ref:`synchronization` is explained in the MathJax documentation but we will review the rules when needed. A Simple measureTime Extension ------------------------------ In this section, we are willing to write a small extension that indicates at the bottom of the page how much time MathJax has taken to typeset the page. First we create the following Javascript file: .. code-block:: javascript // unpacked/extensions/measureTime.js MathJax.HTML.addElement(document.body, "div", {style: {color: "red"}}, ["Hello World!"]); MathJax.Ajax.loadComplete("[MathJax]/extensions/measureTime.js"); The first line is just using the convenient :ref:`MathJax.HTML <api-html>` to create a ``<div style="color: red;">Hello World!</div>`` element. The second line will tell MathJax that ``measureTime.js`` has been successfully loaded. Again, we refer to :ref:`Synchronizing your code with MathJax <synchronization>` for details. Now modify test0.html and insert a ``text/x-mathjax-config`` script just before the one loading MathJax. Use that to add ``measureTime.js`` to the list of extensions to load: .. code-block:: html <!-- MathJax/test/test1.html --> ... <script type="text/x-mathjax-config"> MathJax.Hub.config.extensions.push("measureTime.js"); </script> <script type="text/javascript" src="http://localhost/MathJax/unpacked/MathJax.js?config=TeX-MML-AM_CHTML"> ... The page ``http://localhost/MathJax/unpacked/test1.html`` should now render the same as ``test0.html``, except that a red "Hello World!" message is appended at the end of the page! Our goal is now to replace that message by something like "Typeset by MathJax in 2 second(s)". A quick look at the :ref:`MathJax Startup Sequence <startup-sequence>` shows that the extensions are loaded before the typesetting pass. Also, the typesetting starts with a "Begin Typeset" signal and ends by a "End Typeset" signal. The startup sequence ends by a final "End" signal. In order to add listeners for these signals are sent, we use ``MathJax.Hub.Register.StartupHook``. Writing the extension is now straighforward. We save the data specific to the measureTime extension in a ``MathJax.Extension.measureTime`` object. When we listen the start and end typeset signals we set the corresponding ``startTime`` and ``endTime`` members to the current time. Finally when we listen the final End signal, we append the desired div (note that the previous version appended it immediately): .. code-block:: javascript // unpacked/extensions/measureTime.js MathJax.Extension.measureTime = {}; MathJax.Hub.Register.StartupHook("Begin Typeset", function () { MathJax.Extension.measureTime.startTime = (new Date()).getTime(); }); MathJax.Hub.Register.StartupHook("End Typeset", function () { MathJax.Extension.measureTime.endTime = (new Date()).getTime(); }); MathJax.Hub.Register.StartupHook("End", function () { var delta = (MathJax.Extension.measureTime.endTime - MathJax.Extension.measureTime.startTime) / 1000.; MathJax.HTML.addElement(document.body, "div", null, ["Typeset by MathJax in " + delta + " second(s)"]); }); MathJax.Ajax.loadComplete("[MathJax]/extensions/measureTime.js"); Now load ``test1.html`` again (clearing the browser cache if necessary) and verify if you see the desired "Typeset by MathJax in ... seconds" message. Note that this was a basic extension to demonstrate the extension mechanism but it obviously has some limitations; e.g. only the typeset time is measured (not the whole MathJax execution time), the message is not updated when you switch the rendering mode via the menu, the message is not localizable, etc. Extension to define TeX macros ------------------------------ TeX already has a macro mechanism to define new commands from those already available. This mechanism exists in MathJax, too, and one can rely on it to create a MathJax extension that defines a collection of TeX macros. Consider the following example: .. code-block:: javascript //unpacked/extensions/TeX/Taylor.js MathJax.Hub.Register.StartupHook("TeX Jax Ready", function () { MathJax.InputJax.TeX.Definitions.Add({ macros: { expexpansion: ["Macro", "\\sum_{n=0}^{+\\infty} \\frac{x^n}{n!}"], taylor: ["Macro","\\sum_{n=0}^{+\\infty} \\frac{{#1}^{(n)} \\left({#2}\\right)}{n!} {\\left( {#3} - {#2} \\right)}^n", 3], taylorlog: ["Macro","\\sum_{n=1}^{+\\infty} {(-1)}^{n+1} \\frac{#1^n}{n}", 1], taylorsin: ["Macro","\\sum_{n=0}^{+\\infty} \\frac{{(-1)}^n}{(2n+1)!} {#1}^{2n+1}", 1] } }); }); MathJax.Ajax.loadComplete("[MathJax]/extensions/TeX/Taylor.js"); The structure is similar to the measureTime extension: we wait until the TeX input is ready by listening the appropriate signal. Then we extend the set of TeX macros with some definitions. For example .. code-block:: javascript expexpansion: ["Macro", "\\sum_{n=0}^{+\\infty} \\frac{x^n}{n!}"] will define a TeX command for the exponential series. Note these definitions are given in Javascript strings, so you need to escape some special characters: for example double backslashes are used. If your macro has parameters, you must specify the expected number thus the 3 at the end of the array in .. code-block:: javascript taylor: ["Macro","\\sum_{n=0}^{+\\infty} \\frac{{#1}^{(n)} \\left({#2}\\right)}{n!} {\\left( {#3} - {#2} \\right)}^n", 3], Finally, you can use the Taylor extension in a test page: .. code-block:: html <!--MathJax/unpacked/test2.html--> ... <script type="text/x-mathjax-config"> MathJax.Hub.Config({ TeX: { extensions: ["Taylor.js"] }}); </script> ... <body> \[ \exp(x) = \expexpansion \] \[ f(x) = \taylor{f}{x}{a} \] \[ \log(1+h) = \taylorlog{h} \text{ for } |h| \lt 1 \] \[ \sin\left(\frac{\epsilon}{3}\right) = \taylorsin{\left(\frac{\epsilon}{3}\right)} \] </body> Dealing with Dependencies ------------------------- Suppose that we want to create another extension Taylor2.js that uses some command from Taylor.js. Hence Taylor2 depends on Taylor and we should do some synchronization. We have already seen that the Taylor extension waits for the "TeX Jax Ready" signal before defining the macros. In order to inform the Taylor2 extensions when it is ready, the Taylor extension must itself send a "TeX Taylor Ready" signal. The appropriate place for that is of course after the macros are defined: .. code-block:: javascript // unpacked/extensions/TeX/Taylor.js MathJax.Hub.Register.StartupHook("TeX Jax Ready", function () { MathJax.InputJax.TeX.Definitions.Add({ ... }); MathJax.Hub.Startup.signal.Post("TeX Taylor Ready"); }); MathJax.Ajax.loadComplete("[MathJax]/extensions/TeX/Taylor.js"); Now define Taylor2.js as follows: .. code-block:: javascript // unpacked/extensions/TeX/Taylor2.js MathJax.Hub.Register.StartupHook("TeX Jax Ready", function () { MathJax.InputJax.TeX.Definitions.Add({ macros: { sinexpansion: ["Extension", "Taylor"] } }); }); MathJax.Hub.Register.StartupHook("TeX Taylor Ready", function () { MathJax.Hub.Insert(MathJax.InputJax.TeX.Definitions, { macros: { sinexpansion: ["Macro", "\\taylorsin{x}"] } }); }); MathJax.Ajax.loadComplete("[MathJax]/extensions/TeX/Taylor2.js"); When the input Jax is ready, ``\sinexpansion`` will be define as a function that loads the Taylor extension and restarts the processing afterward. When the Taylor extension is ready, ``\sinexpansion`` becomes the wanted ``\\taylorsin{x}`` definition. Now, you can use this command in a test3 page. Note that only the Taylor2 extension is specified in the list of extensions to load (Taylor will be loaded when the `\sinexpansion` macro is first used). .. code-block:: html <!--MathJax/unpacked/test3.html--> ... <script type="text/x-mathjax-config"> MathJax.Hub.Config({ TeX: { extensions: ["Taylor2.js"] }}); </script> ... <body> \[ \sin(x) = \sinexpansion \] ... We won't give the details in this tutorial, but note that other MathJax components have similar methods to stop, wait for an extension, and restart the execution again. More Advanced Extensions ------------------------ In general, writing more sophisticated extensions require a good understanding of the MathJax codebase. Although the :ref:`public MathJax API <mathjax-api>` is available in the documentation, this is not always the case for the internal code. The rule of thumb is thus to read the relevant ``jax.js`` files in ``unpacked/jax`` (if necessary the Javascript files they can load, too) and to make your extension redefine or expand the code. Here is an example. We modify the behavior of ``\frac`` so that the outermost fractions are drawn normally but those that have a ``\frac`` ancestor are drawn bevelled. We also define a new command ``\bfrac`` that draws bevelled fractions by default. It has an optional parameter to indicate whether we want a bevelled fraction and can take values "auto" (like ``\frac``), "true" or "false". One has to read carefully the TeX parser to understand how this extension is working. .. code-block:: javascript //unpacked/extensions/bevelledFraction.js MathJax.Hub.Register.StartupHook("TeX Jax Ready", function () { MathJax.InputJax.TeX.Definitions.Add({ macros: { frac: "Frac", bfrac: "BFrac" } }, null, true); MathJax.InputJax.TeX.Parse.Augment({ Frac: function (name) { var old = this.stack.env.bevelled; this.stack.env.bevelled = true; var num = this.ParseArg(name); var den = this.ParseArg(name); this.stack.env.bevelled = old; var frac = MathJax.ElementJax.mml.mfrac(num, den); frac.bevelled = this.stack.env.bevelled; this.Push(frac); }, BFrac: function (name) { var bevelled = this.GetBrackets(name); if (bevelled === "auto") bevelled = this.stack.env.bevelled; else bevelled = (bevelled !== "false"); var old = this.stack.env.bevelled; this.stack.env.bevelled = true; var num = this.ParseArg(name); var den = this.ParseArg(name); this.stack.env.bevelled = old; var frac = MathJax.ElementJax.mml.mfrac(num, den); frac.bevelled = bevelled; this.Push(frac); } }); }); MathJax.Ajax.loadComplete("[MathJax]/extensions/TeX/mfracBevelled.js"); Again you can use this command in a ``test4`` page. .. code-block:: html <!--MathJax/unpacked/test4.html--> ... <script type="text/x-mathjax-config"> MathJax.Hub.Config({ TeX: { extensions: ["mfracBevelled.js"] }}); </script> ... \[ \frac a b \] \[ \frac {\frac a b}{\frac c d} \] \[ \bfrac a b \] \[ \bfrac[true] a b \] \[ \bfrac[false] a b \] \[ \bfrac[auto] a b \] \[ \frac {\bfrac[auto] a b}{\bfrac[false] a b} \] \[ \bfrac {\frac a b}{\bfrac[auto] a b} \] ...
{ "content_hash": "a056e792d936b8b07dfcfda568363821", "timestamp": "", "source": "github", "line_count": 394, "max_line_length": 132, "avg_line_length": 36.1497461928934, "alnum_prop": 0.6749280348241241, "repo_name": "GerHobbelt/MathJax-docs", "id": "b775c8e33a7e2360273f39a52088b3e559470756", "size": "14243", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "advanced/extension-writing.rst", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "139" }, { "name": "JavaScript", "bytes": "1944" }, { "name": "Python", "bytes": "6569" } ], "symlink_target": "" }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tf.gpx.edit.extension; /** * * @author thomas */ public interface IGPXExtension { String getName(); String getNamespace(); String getSchemaDefinition(); String getSchemaLocation(); boolean useSeparateNode(); default String nameWithNamespace(final IGPXExtension ext) { if (!ext.getNamespace().isEmpty()) { return ext.getNamespace() + ":" + getName(); } else { return getName(); } } }
{ "content_hash": "988ab51c5be287e0f7cf308125c49b99", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 79, "avg_line_length": 25.423076923076923, "alnum_prop": 0.6399394856278366, "repo_name": "ThomasDaheim/GPXEditor", "id": "3f1c306aeec2a264219c63b6f4a13ce541234895", "size": "661", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/tf/gpx/edit/extension/IGPXExtension.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "3934" }, { "name": "CSS", "bytes": "61020" }, { "name": "HTML", "bytes": "1111" }, { "name": "Java", "bytes": "2323575" }, { "name": "JavaScript", "bytes": "705956" }, { "name": "Roff", "bytes": "159249" } ], "symlink_target": "" }
import scrapy class ProxySpiderItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() pass
{ "content_hash": "74319ec5f646bd5e191c3817d50e847d", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 48, "avg_line_length": 19.714285714285715, "alnum_prop": 0.6884057971014492, "repo_name": "arthurmmm/hq-proxies", "id": "dfa18d041543dda43e82bfb1c64c0d23bbe3f4d3", "size": "290", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "proxy_spider/items.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "28484" } ], "symlink_target": "" }
ros1_pytemplate package ======================= Submodules ---------- ros1_pytemplate.lib_module module --------------------------------- .. automodule:: ros1_pytemplate.lib_module :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: ros1_pytemplate :members: :undoc-members: :show-inheritance:
{ "content_hash": "3a861c76647d02bacb45fe86f830996b", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 42, "avg_line_length": 16.59090909090909, "alnum_prop": 0.5452054794520548, "repo_name": "pyros-dev/ros1_template", "id": "a4bb0df8060ab2e14abc4dfa1d4dd404acd7b0f6", "size": "365", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ros1_pytemplate/doc/ros1_pytemplate.rst", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "13446" }, { "name": "C++", "bytes": "23761" }, { "name": "CMake", "bytes": "17179" }, { "name": "Makefile", "bytes": "13612" }, { "name": "Python", "bytes": "76603" } ], "symlink_target": "" }
<!DOCTYPE html > <html> <head> <title>MatchSucceeded - ScalaTest 3.0.4 - org.scalatest.matchers.MatchSucceeded</title> <meta name="description" content="MatchSucceeded - ScalaTest 3.0.4 - org.scalatest.matchers.MatchSucceeded" /> <meta name="keywords" content="MatchSucceeded ScalaTest 3.0.4 org.scalatest.matchers.MatchSucceeded" /> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" /> <link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" /> <script type="text/javascript" src="../../../lib/jquery.js" id="jquery-js"></script> <script type="text/javascript" src="../../../lib/jquery-ui.js"></script> <script type="text/javascript" src="../../../lib/template.js"></script> <script type="text/javascript" src="../../../lib/tools.tooltip.js"></script> <script type="text/javascript"> if(top === self) { var url = '../../../index.html'; var hash = 'org.scalatest.matchers.MatchSucceeded$'; var anchor = window.location.hash; var anchor_opt = ''; if (anchor.length >= 1) anchor_opt = '@' + anchor.substring(1); window.location.href = url + '#' + hash + anchor_opt; } </script> <!-- gtag [javascript] --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-71294502-1"></script> <script defer> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-71294502-1'); </script> </head> <body class="value"> <!-- Top of doc.scalatest.org [javascript] --> <script type="text/javascript"> var rnd = window.rnd || Math.floor(Math.random()*10e6); var pid204546 = window.pid204546 || rnd; var plc204546 = window.plc204546 || 0; var abkw = window.abkw || ''; var absrc = 'http://ab167933.adbutler-ikon.com/adserve/;ID=167933;size=468x60;setID=204546;type=js;sw='+screen.width+';sh='+screen.height+';spr='+window.devicePixelRatio+';kw='+abkw+';pid='+pid204546+';place='+(plc204546++)+';rnd='+rnd+';click=CLICK_MACRO_PLACEHOLDER'; document.write('<scr'+'ipt src="'+absrc+'" type="text/javascript"></scr'+'ipt>'); </script> <div id="definition"> <img alt="Object" src="../../../lib/object_big.png" /> <p id="owner"><a href="../../package.html" class="extype" name="org">org</a>.<a href="../package.html" class="extype" name="org.scalatest">scalatest</a>.<a href="package.html" class="extype" name="org.scalatest.matchers">matchers</a></p> <h1>MatchSucceeded</h1><h3><span class="morelinks"><div>Related Doc: <a href="package.html" class="extype" name="org.scalatest.matchers">package matchers</a> </div></span></h3><span class="permalink"> <a href="../../../index.html#org.scalatest.matchers.MatchSucceeded$" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> </div> <h4 id="signature" class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">object</span> </span> <span class="symbol"> <span class="name">MatchSucceeded</span> </span> </h4> <div id="comment" class="fullcommenttop"><div class="comment cmt"><p>Singleton object that provides <code>unapply</code> method to extract negated failure message from <code>MatchResult</code> having <code>matches</code> property value of <code>true</code>. </p></div><dl class="attributes block"> <dt>Source</dt><dd><a href="https://github.com/scalatest/scalatest/tree/release-3.0.4/scalatest//src/main/scala/org/scalatest/matchers/MatchSucceeded.scala" target="_blank">MatchSucceeded.scala</a></dd></dl><div class="toggleContainer block"> <span class="toggle">Linear Supertypes</span> <div class="superTypes hiddenContent"><span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div> </div></div> <div id="mbrsel"> <div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div> <div id="order"> <span class="filtertype">Ordering</span> <ol> <li class="alpha in"><span>Alphabetic</span></li> <li class="inherit out"><span>By Inheritance</span></li> </ol> </div> <div id="ancestors"> <span class="filtertype">Inherited<br /> </span> <ol id="linearization"> <li class="in" name="org.scalatest.matchers.MatchSucceeded"><span>MatchSucceeded</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li> </ol> </div><div id="ancestors"> <span class="filtertype"></span> <ol> <li class="hideall out"><span>Hide All</span></li> <li class="showall in"><span>Show All</span></li> </ol> </div> <div id="visbl"> <span class="filtertype">Visibility</span> <ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol> </div> </div> <div id="template"> <div id="allMembers"> <div id="values" class="values members"> <h3>Value Members</h3> <ol><li name="scala.AnyRef#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="!=(x$1:Any):Boolean"></a> <a id="!=(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.matchers.MatchSucceeded$@!=(x$1:Any):Boolean" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef###" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="##():Int"></a> <a id="##():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.matchers.MatchSucceeded$@##():Int" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="==(x$1:Any):Boolean"></a> <a id="==(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.matchers.MatchSucceeded$@==(x$1:Any):Boolean" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.Any#asInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="asInstanceOf[T0]:T0"></a> <a id="asInstanceOf[T0]:T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.matchers.MatchSucceeded$@asInstanceOf[T0]:T0" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#clone" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="clone():Object"></a> <a id="clone():AnyRef"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.matchers.MatchSucceeded$@clone():Object" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.CloneNotSupportedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#eq" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="eq(x$1:AnyRef):Boolean"></a> <a id="eq(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.matchers.MatchSucceeded$@eq(x$1:AnyRef):Boolean" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#equals" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="equals(x$1:Any):Boolean"></a> <a id="equals(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">equals</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.matchers.MatchSucceeded$@equals(x$1:Any):Boolean" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#finalize" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="finalize():Unit"></a> <a id="finalize():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.matchers.MatchSucceeded$@finalize():Unit" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="symbol">classOf[java.lang.Throwable]</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#getClass" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getClass():Class[_]"></a> <a id="getClass():Class[_]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.matchers.MatchSucceeded$@getClass():Class[_]" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#hashCode" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="hashCode():Int"></a> <a id="hashCode():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">hashCode</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.matchers.MatchSucceeded$@hashCode():Int" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.Any#isInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="isInstanceOf[T0]:Boolean"></a> <a id="isInstanceOf[T0]:Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.matchers.MatchSucceeded$@isInstanceOf[T0]:Boolean" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#ne" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="ne(x$1:AnyRef):Boolean"></a> <a id="ne(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.matchers.MatchSucceeded$@ne(x$1:AnyRef):Boolean" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notify" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notify():Unit"></a> <a id="notify():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.matchers.MatchSucceeded$@notify():Unit" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notifyAll" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notifyAll():Unit"></a> <a id="notifyAll():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.matchers.MatchSucceeded$@notifyAll():Unit" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#synchronized" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="synchronized[T0](x$1:=&gt;T0):T0"></a> <a id="synchronized[T0](⇒T0):T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.matchers.MatchSucceeded$@synchronized[T0](x$1:=&gt;T0):T0" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#toString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="toString():String"></a> <a id="toString():String"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.matchers.MatchSucceeded$@toString():String" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="org.scalatest.matchers.MatchSucceeded#unapply" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="unapply(matchResult:org.scalatest.matchers.MatchResult)(implicitprettifier:org.scalactic.Prettifier):Option[String]"></a> <a id="unapply(MatchResult)(Prettifier):Option[String]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">unapply</span><span class="params">(<span name="matchResult">matchResult: <a href="MatchResult.html" class="extype" name="org.scalatest.matchers.MatchResult">MatchResult</a></span>)</span><span class="params">(<span class="implicit">implicit </span><span name="prettifier">prettifier: <span class="extype" name="org.scalactic.Prettifier">Prettifier</span></span>)</span><span class="result">: <span class="extype" name="scala.Option">Option</span>[<span class="extype" name="scala.Predef.String">String</span>]</span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.matchers.MatchSucceeded$@unapply(matchResult:org.scalatest.matchers.MatchResult)(implicitprettifier:org.scalactic.Prettifier):Option[String]" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <p class="shortcomment cmt">Extractor enabling patterns that match <code>MatchResult</code> having <code>matches</code> property value of <code>true</code>, extracting the contained negated failure message.</code></code></code></p><div class="fullcomment"><div class="comment cmt"><p>Extractor enabling patterns that match <code>MatchResult</code> having <code>matches</code> property value of <code>true</code>, extracting the contained negated failure message.</p><p>For example, you can use this extractor to get the negated failure message of a <code>MatchResult</code> like this:</p><p><pre> matchResult match { case MatchSucceeded(negatedFailureMessage) => // do something with negatedFailureMessage case _ => // when matchResult.matches equal to <code>false</code> } </pre> </p></div><dl class="paramcmts block"><dt class="param">matchResult</dt><dd class="cmt"><p>the <code>MatchResult</code> to extract the negated failure message from.</p></dd><dt>returns</dt><dd class="cmt"><p>a <code>Some</code> wrapping the contained negated failure message if <code>matchResult.matches</code> is equal to <code>true</code>, else <code>None</code>.</p></dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait():Unit"></a> <a id="wait():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.matchers.MatchSucceeded$@wait():Unit" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long,x$2:Int):Unit"></a> <a id="wait(Long,Int):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.matchers.MatchSucceeded$@wait(x$1:Long,x$2:Int):Unit" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long):Unit"></a> <a id="wait(Long):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.matchers.MatchSucceeded$@wait(x$1:Long):Unit" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li></ol> </div> </div> <div id="inheritedMembers"> <div class="parent" name="scala.AnyRef"> <h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3> </div><div class="parent" name="scala.Any"> <h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3> </div> </div> <div id="groupedMembers"> <div class="group" name="Ungrouped"> <h3>Ungrouped</h3> </div> </div> </div> <div id="tooltip"></div> <div id="footer"> </div> </body> </html>
{ "content_hash": "e389364c8b3962b0d2033ded917d0224", "timestamp": "", "source": "github", "line_count": 545, "max_line_length": 544, "avg_line_length": 52.7302752293578, "alnum_prop": 0.5953441436425638, "repo_name": "scalatest/scalatest-website", "id": "435429ba70e1098e5b1caa49487fbd08eaef7f35", "size": "28756", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/scaladoc/3.0.4/org/scalatest/matchers/MatchSucceeded$.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "8401192" }, { "name": "HTML", "bytes": "4508833233" }, { "name": "JavaScript", "bytes": "12256885" }, { "name": "Procfile", "bytes": "62" }, { "name": "Scala", "bytes": "136544" } ], "symlink_target": "" }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/container/v1/cluster_service.proto package com.google.container.v1; /** * * * <pre> * ListOperationsResponse is the result of ListOperationsRequest. * </pre> * * Protobuf type {@code google.container.v1.ListOperationsResponse} */ public final class ListOperationsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.container.v1.ListOperationsResponse) ListOperationsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListOperationsResponse.newBuilder() to construct. private ListOperationsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListOperationsResponse() { operations_ = java.util.Collections.emptyList(); missingZones_ = com.google.protobuf.LazyStringArrayList.EMPTY; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListOperationsResponse(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.container.v1.ClusterServiceProto .internal_static_google_container_v1_ListOperationsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.container.v1.ClusterServiceProto .internal_static_google_container_v1_ListOperationsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.container.v1.ListOperationsResponse.class, com.google.container.v1.ListOperationsResponse.Builder.class); } public static final int OPERATIONS_FIELD_NUMBER = 1; private java.util.List<com.google.container.v1.Operation> operations_; /** * * * <pre> * A list of operations in the project in the specified zone. * </pre> * * <code>repeated .google.container.v1.Operation operations = 1;</code> */ @java.lang.Override public java.util.List<com.google.container.v1.Operation> getOperationsList() { return operations_; } /** * * * <pre> * A list of operations in the project in the specified zone. * </pre> * * <code>repeated .google.container.v1.Operation operations = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.container.v1.OperationOrBuilder> getOperationsOrBuilderList() { return operations_; } /** * * * <pre> * A list of operations in the project in the specified zone. * </pre> * * <code>repeated .google.container.v1.Operation operations = 1;</code> */ @java.lang.Override public int getOperationsCount() { return operations_.size(); } /** * * * <pre> * A list of operations in the project in the specified zone. * </pre> * * <code>repeated .google.container.v1.Operation operations = 1;</code> */ @java.lang.Override public com.google.container.v1.Operation getOperations(int index) { return operations_.get(index); } /** * * * <pre> * A list of operations in the project in the specified zone. * </pre> * * <code>repeated .google.container.v1.Operation operations = 1;</code> */ @java.lang.Override public com.google.container.v1.OperationOrBuilder getOperationsOrBuilder(int index) { return operations_.get(index); } public static final int MISSING_ZONES_FIELD_NUMBER = 2; private com.google.protobuf.LazyStringList missingZones_; /** * * * <pre> * If any zones are listed here, the list of operations returned * may be missing the operations from those zones. * </pre> * * <code>repeated string missing_zones = 2;</code> * * @return A list containing the missingZones. */ public com.google.protobuf.ProtocolStringList getMissingZonesList() { return missingZones_; } /** * * * <pre> * If any zones are listed here, the list of operations returned * may be missing the operations from those zones. * </pre> * * <code>repeated string missing_zones = 2;</code> * * @return The count of missingZones. */ public int getMissingZonesCount() { return missingZones_.size(); } /** * * * <pre> * If any zones are listed here, the list of operations returned * may be missing the operations from those zones. * </pre> * * <code>repeated string missing_zones = 2;</code> * * @param index The index of the element to return. * @return The missingZones at the given index. */ public java.lang.String getMissingZones(int index) { return missingZones_.get(index); } /** * * * <pre> * If any zones are listed here, the list of operations returned * may be missing the operations from those zones. * </pre> * * <code>repeated string missing_zones = 2;</code> * * @param index The index of the value to return. * @return The bytes of the missingZones at the given index. */ public com.google.protobuf.ByteString getMissingZonesBytes(int index) { return missingZones_.getByteString(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < operations_.size(); i++) { output.writeMessage(1, operations_.get(i)); } for (int i = 0; i < missingZones_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, missingZones_.getRaw(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < operations_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, operations_.get(i)); } { int dataSize = 0; for (int i = 0; i < missingZones_.size(); i++) { dataSize += computeStringSizeNoTag(missingZones_.getRaw(i)); } size += dataSize; size += 1 * getMissingZonesList().size(); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.container.v1.ListOperationsResponse)) { return super.equals(obj); } com.google.container.v1.ListOperationsResponse other = (com.google.container.v1.ListOperationsResponse) obj; if (!getOperationsList().equals(other.getOperationsList())) return false; if (!getMissingZonesList().equals(other.getMissingZonesList())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getOperationsCount() > 0) { hash = (37 * hash) + OPERATIONS_FIELD_NUMBER; hash = (53 * hash) + getOperationsList().hashCode(); } if (getMissingZonesCount() > 0) { hash = (37 * hash) + MISSING_ZONES_FIELD_NUMBER; hash = (53 * hash) + getMissingZonesList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.container.v1.ListOperationsResponse parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.container.v1.ListOperationsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.container.v1.ListOperationsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.container.v1.ListOperationsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.container.v1.ListOperationsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.container.v1.ListOperationsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.container.v1.ListOperationsResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.container.v1.ListOperationsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.container.v1.ListOperationsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.container.v1.ListOperationsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.container.v1.ListOperationsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.container.v1.ListOperationsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.container.v1.ListOperationsResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * ListOperationsResponse is the result of ListOperationsRequest. * </pre> * * Protobuf type {@code google.container.v1.ListOperationsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.container.v1.ListOperationsResponse) com.google.container.v1.ListOperationsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.container.v1.ClusterServiceProto .internal_static_google_container_v1_ListOperationsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.container.v1.ClusterServiceProto .internal_static_google_container_v1_ListOperationsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.container.v1.ListOperationsResponse.class, com.google.container.v1.ListOperationsResponse.Builder.class); } // Construct using com.google.container.v1.ListOperationsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); if (operationsBuilder_ == null) { operations_ = java.util.Collections.emptyList(); } else { operations_ = null; operationsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); missingZones_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000002); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.container.v1.ClusterServiceProto .internal_static_google_container_v1_ListOperationsResponse_descriptor; } @java.lang.Override public com.google.container.v1.ListOperationsResponse getDefaultInstanceForType() { return com.google.container.v1.ListOperationsResponse.getDefaultInstance(); } @java.lang.Override public com.google.container.v1.ListOperationsResponse build() { com.google.container.v1.ListOperationsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.container.v1.ListOperationsResponse buildPartial() { com.google.container.v1.ListOperationsResponse result = new com.google.container.v1.ListOperationsResponse(this); int from_bitField0_ = bitField0_; if (operationsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { operations_ = java.util.Collections.unmodifiableList(operations_); bitField0_ = (bitField0_ & ~0x00000001); } result.operations_ = operations_; } else { result.operations_ = operationsBuilder_.build(); } if (((bitField0_ & 0x00000002) != 0)) { missingZones_ = missingZones_.getUnmodifiableView(); bitField0_ = (bitField0_ & ~0x00000002); } result.missingZones_ = missingZones_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.container.v1.ListOperationsResponse) { return mergeFrom((com.google.container.v1.ListOperationsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.container.v1.ListOperationsResponse other) { if (other == com.google.container.v1.ListOperationsResponse.getDefaultInstance()) return this; if (operationsBuilder_ == null) { if (!other.operations_.isEmpty()) { if (operations_.isEmpty()) { operations_ = other.operations_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureOperationsIsMutable(); operations_.addAll(other.operations_); } onChanged(); } } else { if (!other.operations_.isEmpty()) { if (operationsBuilder_.isEmpty()) { operationsBuilder_.dispose(); operationsBuilder_ = null; operations_ = other.operations_; bitField0_ = (bitField0_ & ~0x00000001); operationsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getOperationsFieldBuilder() : null; } else { operationsBuilder_.addAllMessages(other.operations_); } } } if (!other.missingZones_.isEmpty()) { if (missingZones_.isEmpty()) { missingZones_ = other.missingZones_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureMissingZonesIsMutable(); missingZones_.addAll(other.missingZones_); } onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.container.v1.Operation m = input.readMessage( com.google.container.v1.Operation.parser(), extensionRegistry); if (operationsBuilder_ == null) { ensureOperationsIsMutable(); operations_.add(m); } else { operationsBuilder_.addMessage(m); } break; } // case 10 case 18: { java.lang.String s = input.readStringRequireUtf8(); ensureMissingZonesIsMutable(); missingZones_.add(s); break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.container.v1.Operation> operations_ = java.util.Collections.emptyList(); private void ensureOperationsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { operations_ = new java.util.ArrayList<com.google.container.v1.Operation>(operations_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.container.v1.Operation, com.google.container.v1.Operation.Builder, com.google.container.v1.OperationOrBuilder> operationsBuilder_; /** * * * <pre> * A list of operations in the project in the specified zone. * </pre> * * <code>repeated .google.container.v1.Operation operations = 1;</code> */ public java.util.List<com.google.container.v1.Operation> getOperationsList() { if (operationsBuilder_ == null) { return java.util.Collections.unmodifiableList(operations_); } else { return operationsBuilder_.getMessageList(); } } /** * * * <pre> * A list of operations in the project in the specified zone. * </pre> * * <code>repeated .google.container.v1.Operation operations = 1;</code> */ public int getOperationsCount() { if (operationsBuilder_ == null) { return operations_.size(); } else { return operationsBuilder_.getCount(); } } /** * * * <pre> * A list of operations in the project in the specified zone. * </pre> * * <code>repeated .google.container.v1.Operation operations = 1;</code> */ public com.google.container.v1.Operation getOperations(int index) { if (operationsBuilder_ == null) { return operations_.get(index); } else { return operationsBuilder_.getMessage(index); } } /** * * * <pre> * A list of operations in the project in the specified zone. * </pre> * * <code>repeated .google.container.v1.Operation operations = 1;</code> */ public Builder setOperations(int index, com.google.container.v1.Operation value) { if (operationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureOperationsIsMutable(); operations_.set(index, value); onChanged(); } else { operationsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * A list of operations in the project in the specified zone. * </pre> * * <code>repeated .google.container.v1.Operation operations = 1;</code> */ public Builder setOperations( int index, com.google.container.v1.Operation.Builder builderForValue) { if (operationsBuilder_ == null) { ensureOperationsIsMutable(); operations_.set(index, builderForValue.build()); onChanged(); } else { operationsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * A list of operations in the project in the specified zone. * </pre> * * <code>repeated .google.container.v1.Operation operations = 1;</code> */ public Builder addOperations(com.google.container.v1.Operation value) { if (operationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureOperationsIsMutable(); operations_.add(value); onChanged(); } else { operationsBuilder_.addMessage(value); } return this; } /** * * * <pre> * A list of operations in the project in the specified zone. * </pre> * * <code>repeated .google.container.v1.Operation operations = 1;</code> */ public Builder addOperations(int index, com.google.container.v1.Operation value) { if (operationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureOperationsIsMutable(); operations_.add(index, value); onChanged(); } else { operationsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * A list of operations in the project in the specified zone. * </pre> * * <code>repeated .google.container.v1.Operation operations = 1;</code> */ public Builder addOperations(com.google.container.v1.Operation.Builder builderForValue) { if (operationsBuilder_ == null) { ensureOperationsIsMutable(); operations_.add(builderForValue.build()); onChanged(); } else { operationsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * A list of operations in the project in the specified zone. * </pre> * * <code>repeated .google.container.v1.Operation operations = 1;</code> */ public Builder addOperations( int index, com.google.container.v1.Operation.Builder builderForValue) { if (operationsBuilder_ == null) { ensureOperationsIsMutable(); operations_.add(index, builderForValue.build()); onChanged(); } else { operationsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * A list of operations in the project in the specified zone. * </pre> * * <code>repeated .google.container.v1.Operation operations = 1;</code> */ public Builder addAllOperations( java.lang.Iterable<? extends com.google.container.v1.Operation> values) { if (operationsBuilder_ == null) { ensureOperationsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, operations_); onChanged(); } else { operationsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * A list of operations in the project in the specified zone. * </pre> * * <code>repeated .google.container.v1.Operation operations = 1;</code> */ public Builder clearOperations() { if (operationsBuilder_ == null) { operations_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { operationsBuilder_.clear(); } return this; } /** * * * <pre> * A list of operations in the project in the specified zone. * </pre> * * <code>repeated .google.container.v1.Operation operations = 1;</code> */ public Builder removeOperations(int index) { if (operationsBuilder_ == null) { ensureOperationsIsMutable(); operations_.remove(index); onChanged(); } else { operationsBuilder_.remove(index); } return this; } /** * * * <pre> * A list of operations in the project in the specified zone. * </pre> * * <code>repeated .google.container.v1.Operation operations = 1;</code> */ public com.google.container.v1.Operation.Builder getOperationsBuilder(int index) { return getOperationsFieldBuilder().getBuilder(index); } /** * * * <pre> * A list of operations in the project in the specified zone. * </pre> * * <code>repeated .google.container.v1.Operation operations = 1;</code> */ public com.google.container.v1.OperationOrBuilder getOperationsOrBuilder(int index) { if (operationsBuilder_ == null) { return operations_.get(index); } else { return operationsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * A list of operations in the project in the specified zone. * </pre> * * <code>repeated .google.container.v1.Operation operations = 1;</code> */ public java.util.List<? extends com.google.container.v1.OperationOrBuilder> getOperationsOrBuilderList() { if (operationsBuilder_ != null) { return operationsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(operations_); } } /** * * * <pre> * A list of operations in the project in the specified zone. * </pre> * * <code>repeated .google.container.v1.Operation operations = 1;</code> */ public com.google.container.v1.Operation.Builder addOperationsBuilder() { return getOperationsFieldBuilder() .addBuilder(com.google.container.v1.Operation.getDefaultInstance()); } /** * * * <pre> * A list of operations in the project in the specified zone. * </pre> * * <code>repeated .google.container.v1.Operation operations = 1;</code> */ public com.google.container.v1.Operation.Builder addOperationsBuilder(int index) { return getOperationsFieldBuilder() .addBuilder(index, com.google.container.v1.Operation.getDefaultInstance()); } /** * * * <pre> * A list of operations in the project in the specified zone. * </pre> * * <code>repeated .google.container.v1.Operation operations = 1;</code> */ public java.util.List<com.google.container.v1.Operation.Builder> getOperationsBuilderList() { return getOperationsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.container.v1.Operation, com.google.container.v1.Operation.Builder, com.google.container.v1.OperationOrBuilder> getOperationsFieldBuilder() { if (operationsBuilder_ == null) { operationsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.container.v1.Operation, com.google.container.v1.Operation.Builder, com.google.container.v1.OperationOrBuilder>( operations_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); operations_ = null; } return operationsBuilder_; } private com.google.protobuf.LazyStringList missingZones_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureMissingZonesIsMutable() { if (!((bitField0_ & 0x00000002) != 0)) { missingZones_ = new com.google.protobuf.LazyStringArrayList(missingZones_); bitField0_ |= 0x00000002; } } /** * * * <pre> * If any zones are listed here, the list of operations returned * may be missing the operations from those zones. * </pre> * * <code>repeated string missing_zones = 2;</code> * * @return A list containing the missingZones. */ public com.google.protobuf.ProtocolStringList getMissingZonesList() { return missingZones_.getUnmodifiableView(); } /** * * * <pre> * If any zones are listed here, the list of operations returned * may be missing the operations from those zones. * </pre> * * <code>repeated string missing_zones = 2;</code> * * @return The count of missingZones. */ public int getMissingZonesCount() { return missingZones_.size(); } /** * * * <pre> * If any zones are listed here, the list of operations returned * may be missing the operations from those zones. * </pre> * * <code>repeated string missing_zones = 2;</code> * * @param index The index of the element to return. * @return The missingZones at the given index. */ public java.lang.String getMissingZones(int index) { return missingZones_.get(index); } /** * * * <pre> * If any zones are listed here, the list of operations returned * may be missing the operations from those zones. * </pre> * * <code>repeated string missing_zones = 2;</code> * * @param index The index of the value to return. * @return The bytes of the missingZones at the given index. */ public com.google.protobuf.ByteString getMissingZonesBytes(int index) { return missingZones_.getByteString(index); } /** * * * <pre> * If any zones are listed here, the list of operations returned * may be missing the operations from those zones. * </pre> * * <code>repeated string missing_zones = 2;</code> * * @param index The index to set the value at. * @param value The missingZones to set. * @return This builder for chaining. */ public Builder setMissingZones(int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureMissingZonesIsMutable(); missingZones_.set(index, value); onChanged(); return this; } /** * * * <pre> * If any zones are listed here, the list of operations returned * may be missing the operations from those zones. * </pre> * * <code>repeated string missing_zones = 2;</code> * * @param value The missingZones to add. * @return This builder for chaining. */ public Builder addMissingZones(java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureMissingZonesIsMutable(); missingZones_.add(value); onChanged(); return this; } /** * * * <pre> * If any zones are listed here, the list of operations returned * may be missing the operations from those zones. * </pre> * * <code>repeated string missing_zones = 2;</code> * * @param values The missingZones to add. * @return This builder for chaining. */ public Builder addAllMissingZones(java.lang.Iterable<java.lang.String> values) { ensureMissingZonesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, missingZones_); onChanged(); return this; } /** * * * <pre> * If any zones are listed here, the list of operations returned * may be missing the operations from those zones. * </pre> * * <code>repeated string missing_zones = 2;</code> * * @return This builder for chaining. */ public Builder clearMissingZones() { missingZones_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * If any zones are listed here, the list of operations returned * may be missing the operations from those zones. * </pre> * * <code>repeated string missing_zones = 2;</code> * * @param value The bytes of the missingZones to add. * @return This builder for chaining. */ public Builder addMissingZonesBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureMissingZonesIsMutable(); missingZones_.add(value); onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.container.v1.ListOperationsResponse) } // @@protoc_insertion_point(class_scope:google.container.v1.ListOperationsResponse) private static final com.google.container.v1.ListOperationsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.container.v1.ListOperationsResponse(); } public static com.google.container.v1.ListOperationsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListOperationsResponse> PARSER = new com.google.protobuf.AbstractParser<ListOperationsResponse>() { @java.lang.Override public ListOperationsResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<ListOperationsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListOperationsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.container.v1.ListOperationsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
{ "content_hash": "842ce4d90c3c2462de9fb714b2b5e63f", "timestamp": "", "source": "github", "line_count": 1193, "max_line_length": 100, "avg_line_length": 31.79798826487846, "alnum_prop": 0.64286279161724, "repo_name": "googleapis/java-container", "id": "3cf7a437b96ce56227daaba6316ba4a6eb1bacd7", "size": "38529", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "proto-google-cloud-container-v1/src/main/java/com/google/container/v1/ListOperationsResponse.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "801" }, { "name": "Java", "bytes": "17165820" }, { "name": "Python", "bytes": "1016" }, { "name": "Shell", "bytes": "22851" } ], "symlink_target": "" }
/* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ ELMO.Views.BroadcastsView = class BroadcastsView extends ELMO.Views.FormView { get el() { return '.broadcast_form'; } get events() { return { 'change #broadcast_medium': 'medium_changed', 'change #broadcast_recipient_selection': 'recipient_selection_changed', 'keyup #broadcast_body': 'update_char_limit', }; } initialize(options) { this.medium_changed(); this.recipient_selection_changed(); return this.$('#broadcast_recipient_ids').select2({ ajax: (new ELMO.Utils.Select2OptionBuilder()).ajax(options.recipient_options_url) }); } recipient_selection_changed(e) { const specific = this.form_value('broadcast', 'recipient_selection') === 'specific'; return this.showField('recipient_ids', specific); } medium_changed(e) { const selected = this.form_value('broadcast', 'medium'); const sms_possible = (selected !== 'email_only') && (selected !== ''); this.$('#char_limit').toggle(sms_possible); this.showField('which_phone', sms_possible); this.showField('subject', !sms_possible); if (sms_possible) { return this.update_char_limit(); } } update_char_limit() { const div = this.$('#char_limit'); if (div.is(':visible')) { const diff = 140 - this.$('#broadcast_body').val().length; const msg = I18n.t(`broadcast.chars.${diff >= 0 ? 'remaining' : 'too_many'}`); div.text(`${Math.abs(diff)} ${msg}`); return div.css('color', diff >= 0 ? 'black' : '#d02000'); } } };
{ "content_hash": "2e614ac159001637f17dc21a4cd08afe", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 141, "avg_line_length": 36.02127659574468, "alnum_prop": 0.6467808623744832, "repo_name": "thecartercenter/elmo", "id": "5259a7ca3f12ad464ab1677cf5ee7f9de9644489", "size": "1693", "binary": false, "copies": "1", "ref": "refs/heads/12085_prevent_dupes", "path": "app/assets/javascripts/views/broadcasts_view.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "97107" }, { "name": "CoffeeScript", "bytes": "57714" }, { "name": "HTML", "bytes": "144925" }, { "name": "JavaScript", "bytes": "194066" }, { "name": "Ruby", "bytes": "1756251" } ], "symlink_target": "" }
package com.blazebit.persistence.impl.function.jsonset; import com.blazebit.persistence.impl.function.jsonget.AbstractJsonGetFunction; import com.blazebit.persistence.spi.FunctionRenderContext; import java.util.List; /** * @author Moritz Becker * @since 1.5.0 */ public class OracleJsonSetFunction extends AbstractJsonSetFunction { @Override protected void render0(FunctionRenderContext context) { List<Object> jsonPathElements = AbstractJsonGetFunction.retrieveJsonPathElements(context, 2); context.addChunk("(select "); context.addChunk("json_mergepatch("); context.addArgument(0); context.addChunk(",'"); for (int i = 0; i < jsonPathElements.size(); i++) { startJsonPathElement(context, jsonPathElements, i); } context.addChunk("' || "); context.addChunk("column_value"); context.addChunk(" || '"); for (int i = jsonPathElements.size() - 1; i >= 0; i--) { endJsonPathElement(context, jsonPathElements, i); } context.addChunk("')"); context.addChunk(" from table(sys.ODCIVARCHAR2LIST("); context.addArgument(1); context.addChunk(")))"); } private void startJsonPathElement(FunctionRenderContext context, List<Object> pathElems, int curIndex) { Object pathElem = pathElems.get(curIndex); if (pathElem instanceof Integer) { context.addChunk("[' || "); context.addChunk("(select (dbms_xmlgen.convert(substr(xmlagg(xmlelement(e,to_clob(',') || quoted_array_element.value).extract('//text()')).getClobVal(),2),1)) from ("); context.addChunk("select array_element.row_number, COALESCE(array_element.\"complex_value\", COALESCE(CASE WHEN array_element.\"scalar_value\" IS NOT NULL AND array_element.\"number_value\" IS NULL THEN '\"' || array_element.\"scalar_value\" || '\"' ELSE array_element.\"scalar_value\" END, 'null')) as value from "); context.addChunk("json_table("); context.addArgument(0); context.addChunk(",'"); context.addChunk(AbstractJsonGetFunction.toJsonPath(pathElems, curIndex, true) + "[*]"); context.addChunk("' COLUMNS ("); context.addChunk("row_number FOR ORDINALITY,"); context.addChunk("\"complex_value\" varchar2 FORMAT JSON PATH '$',"); context.addChunk("\"scalar_value\" varchar2 PATH '$',"); context.addChunk("\"number_value\" number PATH '$' null on error"); context.addChunk(")) array_element where array_element.row_number != "); context.addChunk(pathElem.toString()); context.addChunk("+1"); context.addChunk(" union all "); context.addChunk("select "); context.addChunk(pathElem.toString()); context.addChunk("+1, "); if (curIndex < pathElems.size() - 1) { context.addChunk("coalesce(json_mergepatch("); renderJsonGet(context, AbstractJsonGetFunction.toJsonPath(pathElems, curIndex + 1, true)); context.addChunk(",'"); } else { context.addChunk("'"); } } else { context.addChunk("{\""); context.addChunk((String) pathElem); context.addChunk("\":"); } } private void endJsonPathElement(FunctionRenderContext context, List<Object> pathElems, int curIndex) { Object pathElem = pathElems.get(curIndex); if (pathElem instanceof Integer) { context.addChunk("'"); if (curIndex < pathElems.size() - 1) { context.addChunk("), '"); for (int i = curIndex + 1; i < pathElems.size(); i++) { startJsonPathElement(context, pathElems, i); } context.addChunk("' || column_value || '"); for (int i = pathElems.size() - 1; i >= curIndex + 1; i--) { endJsonPathElement(context, pathElems, i); } context.addChunk("')"); } context.addChunk("from table (sys.ODCIVARCHAR2LIST(column_value)) "); context.addChunk("order by row_number"); context.addChunk(") quoted_array_element) "); context.addChunk(" || ']"); } else { context.addChunk("}"); } } private void renderJsonGet(FunctionRenderContext context, String jsonPath) { context.addChunk("coalesce(json_value("); context.addArgument(0); context.addChunk(" format json,'"); context.addChunk(jsonPath); context.addChunk("'),json_query("); context.addArgument(0); context.addChunk(" format json,'"); context.addChunk(jsonPath); context.addChunk("'))"); } }
{ "content_hash": "970dc92ba76aba6dc4f026c835b09609", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 329, "avg_line_length": 42.31304347826087, "alnum_prop": 0.584669132757912, "repo_name": "Blazebit/blaze-persistence", "id": "9405bcb5aad647dbfd33be1c237fa840c7667b94", "size": "5466", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "core/impl/src/main/java/com/blazebit/persistence/impl/function/jsonset/OracleJsonSetFunction.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "44368" }, { "name": "Batchfile", "bytes": "727" }, { "name": "CSS", "bytes": "85149" }, { "name": "FreeMarker", "bytes": "16964" }, { "name": "HTML", "bytes": "8988" }, { "name": "Java", "bytes": "20068561" }, { "name": "JavaScript", "bytes": "7022" }, { "name": "Shell", "bytes": "12643" } ], "symlink_target": "" }
#!/usr/bin/env php <?php // This is the base directory of the SimpleSAMLphp installation $baseDir = dirname(dirname(dirname(dirname(__FILE__)))); // Add library autoloader. require_once($baseDir . '/lib/_autoload.php'); /* Initialize the configuration. */ $configdir = SimpleSAML\Utils\Config::getConfigDir(); SimpleSAML_Configuration::setConfigDir($configdir); SimpleSAML\Utils\Time::initTimezone(); $progName = array_shift($argv); $debug = FALSE; $dryrun = FALSE; foreach($argv as $a) { if(strlen($a) === 0) continue; if(strpos($a, '=') !== FALSE) { $p = strpos($a, '='); $v = substr($a, $p + 1); $a = substr($a, 0, $p); } else { $v = NULL; } /* Map short options to long options. */ $shortOptMap = array( '-d' => '--debug', ); if(array_key_exists($a, $shortOptMap)) $a = $shortOptMap[$a]; switch($a) { case '--help': printHelp(); exit(0); case '--debug': $debug = TRUE; break; case '--dry-run': $dryrun = TRUE; break; default: echo('Unknown option: ' . $a . "\n"); echo('Please run `' . $progName . ' --help` for usage information.' . "\n"); exit(1); } } $aggregator = new sspmod_statistics_Aggregator(TRUE); $aggregator->dumpConfig(); $aggregator->debugInfo(); $results = $aggregator->aggregate($debug); $aggregator->debugInfo(); if (!$dryrun) { $aggregator->store($results); } foreach ($results AS $slot => $val) { foreach ($val AS $sp => $no) { echo $sp . " " . count($no) . " - "; } echo "\n"; } /** * This function prints the help output. */ function printHelp() { global $progName; /* '======================================================================' */ echo('Usage: ' . $progName . ' [options] This program parses and aggregates SimpleSAMLphp log files. Options: -d, --debug Used when configuring the log file syntax. See doc. --dry-run Aggregate but do not store the results. '); }
{ "content_hash": "249622c9edd62fc1253b2ae4228a5eac", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 81, "avg_line_length": 20.462365591397848, "alnum_prop": 0.5880189174986863, "repo_name": "RKathees/is-connectors", "id": "37578856b2dc07b38383b06893d9e4f12b49f264", "size": "1903", "binary": false, "copies": "14", "ref": "refs/heads/master", "path": "tiqr/tiqr-client/modules/statistics/bin/loganalyzer.php", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "39100" }, { "name": "Java", "bytes": "335940" }, { "name": "JavaScript", "bytes": "14552" }, { "name": "PHP", "bytes": "2048700" }, { "name": "Perl", "bytes": "2266" }, { "name": "Shell", "bytes": "1239" } ], "symlink_target": "" }
FROM balenalib/asus-tinker-edge-t-debian:buster-build ENV GO_VERSION 1.16.14 RUN mkdir -p /usr/local/go \ && curl -SLO "https://storage.googleapis.com/golang/go$GO_VERSION.linux-arm64.tar.gz" \ && echo "5e59056e36704acb25809bcdb27191f27593cb7aba4d716b523008135a1e764a go$GO_VERSION.linux-arm64.tar.gz" | sha256sum -c - \ && tar -xzf "go$GO_VERSION.linux-arm64.tar.gz" -C /usr/local/go --strip-components=1 \ && rm -f go$GO_VERSION.linux-arm64.tar.gz ENV GOROOT /usr/local/go ENV GOPATH /go ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH" WORKDIR $GOPATH CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/613d8e9ca8540f29a43fddf658db56a8d826fffe/scripts/assets/tests/test-stack@golang.sh" \ && echo "Running test-stack@golang" \ && chmod +x test-stack@golang.sh \ && bash test-stack@golang.sh \ && rm -rf test-stack@golang.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Debian Buster \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nGo v1.16.14 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{ "content_hash": "0b23938173bb750bc9e346c75031c57d", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 675, "avg_line_length": 64.12903225806451, "alnum_prop": 0.7263581488933601, "repo_name": "resin-io-library/base-images", "id": "9f1f8872b4cf787343d05a5e673f2aa715733c43", "size": "2009", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/golang/asus-tinker-edge-t/debian/buster/1.16.14/build/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "71234697" }, { "name": "JavaScript", "bytes": "13096" }, { "name": "Shell", "bytes": "12051936" }, { "name": "Smarty", "bytes": "59789" } ], "symlink_target": "" }
class ScenarioController < ApplicationController before_action :load_response, only: [:get, :post] def index @cards = Card.all end def timeout sleep((params[:time] || 5).to_i) @example_url = timeout_scenario_url(time: rand(1..60)) end def not_found render file: 'public/404.html', status: 404 end def server_error render file: 'public/500.html', status: 500 end def get sleep_time if params[:response_id].blank? ResponseHandler.new(self, @response).resolve end def post sleep_time redirect_to get_scenario_path(params[:request_by], response_id: @response.try(:id)) end private def load_response @response = if params[:response_id] Response.find_by(id: params[:response_id]) else Response.where(request_type: action_name.upcase).find_by(request_by: params[:request_by]) end end def sleep_time sleep(@response.try(:wait_time).to_i) end end
{ "content_hash": "5bdabc299c0361c23ea633c77ac3718a", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 95, "avg_line_length": 21.177777777777777, "alnum_prop": 0.664218258132214, "repo_name": "jnormington/mimiq", "id": "277b7c324ed941f8fcb180acf9ed0752a958832e", "size": "953", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/controllers/scenario_controller.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "956" }, { "name": "HTML", "bytes": "12096" }, { "name": "Ruby", "bytes": "51046" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_151) on Thu Dec 05 05:02:04 MST 2019 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>SslSessionConsumer (BOM: * : All 2.6.0.Final API)</title> <meta name="date" content="2019-12-05"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="SslSessionConsumer (BOM: * : All 2.6.0.Final API)"; } } catch(err) { } //--> var methods = {"i0":6,"i1":18}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"],16:["t5","Default Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/SslSessionConsumer.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Thorntail API, 2.6.0.Final</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/wildfly/swarm/config/elytron/SslSession.html" title="class in org.wildfly.swarm.config.elytron"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../org/wildfly/swarm/config/elytron/SslSessionSupplier.html" title="interface in org.wildfly.swarm.config.elytron"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/wildfly/swarm/config/elytron/SslSessionConsumer.html" target="_top">Frames</a></li> <li><a href="SslSessionConsumer.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.wildfly.swarm.config.elytron</div> <h2 title="Interface SslSessionConsumer" class="title">Interface SslSessionConsumer&lt;T extends <a href="../../../../../org/wildfly/swarm/config/elytron/SslSession.html" title="class in org.wildfly.swarm.config.elytron">SslSession</a>&lt;T&gt;&gt;</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>Functional Interface:</dt> <dd>This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.</dd> </dl> <hr> <br> <pre><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html?is-external=true" title="class or interface in java.lang">@FunctionalInterface</a> public interface <span class="typeNameLabel">SslSessionConsumer&lt;T extends <a href="../../../../../org/wildfly/swarm/config/elytron/SslSession.html" title="class in org.wildfly.swarm.config.elytron">SslSession</a>&lt;T&gt;&gt;</span></pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t5" class="tableTab"><span><a href="javascript:show(16);">Default Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/config/elytron/SslSessionConsumer.html#accept-T-">accept</a></span>(<a href="../../../../../org/wildfly/swarm/config/elytron/SslSessionConsumer.html" title="type parameter in SslSessionConsumer">T</a>&nbsp;value)</code> <div class="block">Configure a pre-constructed instance of SslSession resource</div> </td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>default <a href="../../../../../org/wildfly/swarm/config/elytron/SslSessionConsumer.html" title="interface in org.wildfly.swarm.config.elytron">SslSessionConsumer</a>&lt;<a href="../../../../../org/wildfly/swarm/config/elytron/SslSessionConsumer.html" title="type parameter in SslSessionConsumer">T</a>&gt;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/config/elytron/SslSessionConsumer.html#andThen-org.wildfly.swarm.config.elytron.SslSessionConsumer-">andThen</a></span>(<a href="../../../../../org/wildfly/swarm/config/elytron/SslSessionConsumer.html" title="interface in org.wildfly.swarm.config.elytron">SslSessionConsumer</a>&lt;<a href="../../../../../org/wildfly/swarm/config/elytron/SslSessionConsumer.html" title="type parameter in SslSessionConsumer">T</a>&gt;&nbsp;after)</code>&nbsp;</td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="accept-org.wildfly.swarm.config.elytron.SslSession-"> <!-- --> </a><a name="accept-T-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>accept</h4> <pre>void&nbsp;accept(<a href="../../../../../org/wildfly/swarm/config/elytron/SslSessionConsumer.html" title="type parameter in SslSessionConsumer">T</a>&nbsp;value)</pre> <div class="block">Configure a pre-constructed instance of SslSession resource</div> </li> </ul> <a name="andThen-org.wildfly.swarm.config.elytron.SslSessionConsumer-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>andThen</h4> <pre>default&nbsp;<a href="../../../../../org/wildfly/swarm/config/elytron/SslSessionConsumer.html" title="interface in org.wildfly.swarm.config.elytron">SslSessionConsumer</a>&lt;<a href="../../../../../org/wildfly/swarm/config/elytron/SslSessionConsumer.html" title="type parameter in SslSessionConsumer">T</a>&gt;&nbsp;andThen(<a href="../../../../../org/wildfly/swarm/config/elytron/SslSessionConsumer.html" title="interface in org.wildfly.swarm.config.elytron">SslSessionConsumer</a>&lt;<a href="../../../../../org/wildfly/swarm/config/elytron/SslSessionConsumer.html" title="type parameter in SslSessionConsumer">T</a>&gt;&nbsp;after)</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/SslSessionConsumer.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Thorntail API, 2.6.0.Final</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/wildfly/swarm/config/elytron/SslSession.html" title="class in org.wildfly.swarm.config.elytron"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../org/wildfly/swarm/config/elytron/SslSessionSupplier.html" title="interface in org.wildfly.swarm.config.elytron"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/wildfly/swarm/config/elytron/SslSessionConsumer.html" target="_top">Frames</a></li> <li><a href="SslSessionConsumer.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2019 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
{ "content_hash": "10d9095a5cbe2ccc2781323796886162", "timestamp": "", "source": "github", "line_count": 248, "max_line_length": 646, "avg_line_length": 45.068548387096776, "alnum_prop": 0.6534848349288718, "repo_name": "wildfly-swarm/wildfly-swarm-javadocs", "id": "fb50656b1cb339b1dec1eb431e7f86e2c87904ba", "size": "11177", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "2.6.0.Final/apidocs/org/wildfly/swarm/config/elytron/SslSessionConsumer.html", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import qctests.CSIRO_wire_break import util.testingProfile import numpy ##### CSIRO_wire_break_test --------------------------------------------------- def test_CSIRO_wire_break(): ''' Spot-check the nominal behavior of the CSIRO wire break test. ''' # too cold at the bottom of xbt profile p = util.testingProfile.fakeProfile([-2.399,-2.399,-2.4001], [10,20,30], probe_type=2) qc = qctests.CSIRO_wire_break.test(p, None) truth = numpy.zeros(3, dtype=bool) truth[2] = True assert numpy.array_equal(qc, truth), 'failed to flag too-cold temperature at bottom of profile' # too hot at bottom of xbt profile p = util.testingProfile.fakeProfile([31.99,31.99,32.001], [10,20,30], probe_type=2) qc = qctests.CSIRO_wire_break.test(p, None) truth = numpy.zeros(3, dtype=bool) truth[2] = True assert numpy.array_equal(qc, truth), 'failed to flag too-hot temperature at bottom of profile' # right on border - no flag p = util.testingProfile.fakeProfile([-2.399,-2.399,-2.4], [10,20,30], probe_type=2) qc = qctests.CSIRO_wire_break.test(p, None) truth = numpy.zeros(3, dtype=bool) print(qc) print(truth) assert numpy.array_equal(qc, truth), 'flagged marginally cold temperature at bottom of profile' p = util.testingProfile.fakeProfile([31.99,31.99,32], [10,20,30], probe_type=2) qc = qctests.CSIRO_wire_break.test(p, None) truth = numpy.zeros(3, dtype=bool) assert numpy.array_equal(qc, truth), 'flagged marginally hot temperature at bottom of profile' # don't flag if not an xbt p = util.testingProfile.fakeProfile([0,0,-100], [10,20,30], probe_type=1) qc = qctests.CSIRO_wire_break.test(p, None) truth = numpy.zeros(3, dtype=bool) assert numpy.array_equal(qc, truth), 'flagged non-xbt profile' # don't flag if not at bottom of profile p = util.testingProfile.fakeProfile([0,32.01,31.99], [10,20,30], probe_type=2) qc = qctests.CSIRO_wire_break.test(p, None) truth = numpy.zeros(3, dtype=bool) assert numpy.array_equal(qc, truth), "flagged hot temperature that wasn't at bottom of profile" # flag both sides of a gap p = util.testingProfile.fakeProfile([9,9,10], [10,20,30], probe_type=2) qc = qctests.CSIRO_wire_break.test(p, None) truth = numpy.ones(3, dtype=bool) truth[0] = False assert numpy.array_equal(qc, truth), "should flag both sides of a gap"
{ "content_hash": "2c94c1bab47385e9fda3d3818decb406", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 103, "avg_line_length": 43.44642857142857, "alnum_prop": 0.6588573777229757, "repo_name": "BillMills/AutoQC", "id": "c617d6dbeba3014f3450b02e08c7e71af2a23380", "size": "2433", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "tests/CSIRO_wire_break_validation.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "830437" }, { "name": "Shell", "bytes": "2581" } ], "symlink_target": "" }
/* Author: James Fraser Date: June 10th Purpose: Simple Structure for testing. University of Guelph, 2016. CIS*2520 (DE) S16 */ #ifndef SIMPLE_TEST_STRUCTURE_ #define SIMPLE_TEST_STRUCTURE_ #include<stdio.h> #include<stdlib.h> #include<string.h> #include<time.h> /* Simple structure simpilar to that of an array */ /* Array is a simple test structure to provide an example for testing purpose. int* arr => contains the data in the array. int size => indicates the size of the array. */ typedef struct simpleStruct { int * arr; int size; } Array; /* Summary: Creates an array initialized to a specific size. Pre: 0 or a positive number provided. Post: If unable to create NULL returned, else an integer array of size is created. */ Array* createArray(int arraySize); /* Summary: Check if a position is valid within an array Pre: None Post: returns 0 if position doesn't exist, 1 if valid. */ int positionExists(Array * array, int position); /* Summary: Returns the integer value at the start of the array Pre: Given an array Post: Returns -1 if invalid array size or value at first position of array. */ int getFirstValue(Array * array); /* Summary: Modifies a value at a specific position in the array, if it exists. Pre: Given an array, a potential position in the array and a new value. Post:if invalid position array remains the same. Else, array value at position is changed to newValue */ void modifyValue(Array * array, int position, int newValue ); /* Summary: Returns the length or size of the array Pre: None Post: 0 or the length of the array is provided */ int getLength( Array * arr ); /* Summary:Prints the integer array Pre: None Post:Array has been printed to the console. */ void printArray( Array * array ); /* Summary: Destorys the array and frees the memory. Pre: None Post:Array has been destroyed and any memory used has been returned. */ void destroyArray( Array** array); #endif // End the Simple Structure
{ "content_hash": "cfcb7136e201be4597497965d2fbfbaf", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 103, "avg_line_length": 25.164556962025316, "alnum_prop": 0.7283702213279678, "repo_name": "ian-james/IFS", "id": "e2d8a845aa990ae4218fd7549b8bff34fc79b5c5", "size": "1988", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ifs/tests/programmingTests/noDirProj/array.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "86873" }, { "name": "C++", "bytes": "2738" }, { "name": "CSS", "bytes": "9006" }, { "name": "HTML", "bytes": "168078" }, { "name": "JavaScript", "bytes": "638111" }, { "name": "Makefile", "bytes": "4765" }, { "name": "Python", "bytes": "232930" }, { "name": "Shell", "bytes": "27093" }, { "name": "TSQL", "bytes": "28765" } ], "symlink_target": "" }
START_ATF_NAMESPACE namespace vc_attributes { namespace atl { template<> struct rdxAttribute { const char *key; const char *valuename; const char *regtype; }; }; // end namespace atl }; // end namespace vc_attributes END_ATF_NAMESPACE
{ "content_hash": "b479f4996d5008aee5570b09cdf74e4b", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 38, "avg_line_length": 24.466666666666665, "alnum_prop": 0.47956403269754766, "repo_name": "goodwinxp/Yorozuya", "id": "f6aed6836dc6b0871496a276aa446ca8c8dd0960", "size": "519", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "library/ATF/__atl__rdxAttribute.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "207291" }, { "name": "C++", "bytes": "21670817" } ], "symlink_target": "" }
from __future__ import print_function import os import numpy as np import pandas as pd import scipy.stats as sps import matplotlib.pyplot as plt import seaborn as sns from statsmodels.stats.multicomp import pairwise_tukeyhsd from shelve import DbfilenameShelf from contextlib import closing from collections import defaultdict from functools import partial from sklearn.preprocessing import OneHotEncoder from genomic_neuralnet.analyses.plots \ import get_nn_model_data, palette, out_dir \ , get_significance_letters sns.set_style('dark') sns.set_palette(palette) def string_to_label((species, trait)): trait_name = trait.replace('_', ' ').title() species_name = species.title() if trait_name.count(' ') > 1: trait_name = trait_name.replace(' ', '\n') return '{}\n{}'.format(species_name, trait_name) def make_best_dataframe(shelf_data): data_dict = defaultdict(partial(defaultdict, dict)) num_models = len(shelf_data) for model_name, optimization in shelf_data.iteritems(): for species_trait, opt_result in optimization.iteritems(): species, trait, gpu = tuple(species_trait.split('|')) max_fit_index = opt_result.df['mean'].idxmax() best_fit = opt_result.df.loc[max_fit_index] mean_acc = best_fit.loc['mean'] sd_acc = best_fit.loc['std_dev'] hidden = best_fit.loc['hidden'] count = opt_result.folds * opt_result.runs raw_results = best_fit.loc['raw_results'] data_dict[species][trait][model_name] = (mean_acc, sd_acc, count, raw_results, hidden) # Add species column. Repeat once per trait per model (2*num models). accuracy_df = pd.DataFrame({'species': np.repeat(data_dict.keys(), num_models*2)}) # Add trait column. flattened_data = [] for species, trait_dict in data_dict.iteritems(): for trait, model_dict in trait_dict.iteritems(): for model, (mean, sd, count, raw_res, hidden) in model_dict.iteritems(): flattened_data.append((trait, model, mean, sd, count, raw_res, hidden)) accuracy_df['trait'], accuracy_df['model'], accuracy_df['mean'], \ accuracy_df['sd'], accuracy_df['count'], accuracy_df['raw_results'], \ accuracy_df['hidden'] = zip(*flattened_data) return accuracy_df def make_plot(accuracy_df): accuracy_df = accuracy_df.sort_values(by=['species', 'trait'], ascending=[1,0]) fig, ax = plt.subplots() species_and_traits = accuracy_df[['species', 'trait']].drop_duplicates() x = np.arange(len(species_and_traits)) models = sorted(accuracy_df['model'].unique()) width = 0.22 species_list = species_and_traits['species'] trait_list = species_and_traits['trait'] bar_sets = [] error_offsets = [] for idx, model in enumerate(models): means = accuracy_df[accuracy_df['model'] == model]['mean'].values std_devs = accuracy_df[accuracy_df['model'] == model]['sd'].values counts = accuracy_df[accuracy_df['model'] == model]['count'].values std_errs = std_devs / np.sqrt(counts) # SE = sigma / sqrt(N) # Size of 95% CI is the SE multiplied by a constant from the t distribution # with n-1 degrees of freedom. [0] is the positive interval direction. #confidence_interval_mult = sps.t.interval(alpha=0.95, df=counts - 1)[0] #confidence_interval = confidence_interval_mult * std_errs offset = width * idx color = palette[idx] b = ax.bar(x + offset, means, width, color=color) e = ax.errorbar(x + offset + width/2, means, yerr=std_errs, ecolor='black', fmt='none') bar_sets.append((b, model)) error_offsets.append(std_errs) significance_letter_lookup = get_significance_letters(accuracy_df, ordered_model_names=models) def label(idx, rects, model): errors = error_offsets[idx] for error, rect, species, trait in zip(errors, rects, species_list, trait_list): height = rect.get_height() significance_letter = significance_letter_lookup[model][species][trait] ax.text( rect.get_x() + rect.get_width()/2. , height + error + 0.02 , significance_letter , ha='center' , va='bottom') [label(idx, b, m) for idx, (b,m) in enumerate(bar_sets)] # Axis labels (layer 1). ax.set_ylabel('Accuracy') ax.set_xticks(x + width / 2 * len(models)) ax.set_xticklabels(map(string_to_label, zip(species_list, trait_list))) ax.set_xlim((0 - width / 2, len(trait_list))) ax.set_ylim((0, 1)) # Legend ax.legend(map(lambda x: x[0], bar_sets), list(models)) plt.tight_layout() fig_path = os.path.join(out_dir, 'network_comparison.png') plt.savefig(fig_path, dpi=500) plt.show() def main(): data = get_nn_model_data() accuracy_df = make_best_dataframe(data) make_plot(accuracy_df) if __name__ == '__main__': main()
{ "content_hash": "05a00e6c8133e81f86224e55d6bff1d4", "timestamp": "", "source": "github", "line_count": 135, "max_line_length": 98, "avg_line_length": 37.37777777777778, "alnum_prop": 0.6266349583828775, "repo_name": "rileymcdowell/genomic-neuralnet", "id": "bb99ed02b2320b769b94b87eec7311b89c06aa43", "size": "5046", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "genomic_neuralnet/analyses/plots/network_comparison/compare_networks.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "101344" }, { "name": "R", "bytes": "1914" }, { "name": "Shell", "bytes": "12629" } ], "symlink_target": "" }
<project name="common-build" basedir="." xmlns:ac="antlib:net.sf.antcontrib"> <description>Common Build File</description> <dirname property="current.dir" file="${ant.file.common-build}"/> <property name="root.dir" location="${current.dir}/../"/> <property name="tmp.dir" location="${root.dir}/output/tmp/"/> <property name="yc.jar" location="${current.dir}/yuicompressor.jar"/> <property name="charset" value="utf-8"/> <property name="version" value="1.1.6"/> <tstamp> <format property="release" pattern="yyyy-MM-dd" locale="en,UK"/> </tstamp> <!-- 清空、复制等准备工作 --> <target name="prepare"> <delete dir="${root.dir}/output/"/> <mkdir dir="${tmp.dir}"/> <copy todir="${tmp.dir}"> <fileset dir="${module.dir}" includes="*-combo.js"/> </copy> <!-- 脚本库的版本号 --> <replaceregexp match="\$version\$" replace="${version}" flags="g" encoding="${charset}"> <fileset dir="${tmp.dir}" includes="*-combo.js"/> </replaceregexp> <!-- 脚本库的发布号(小版本) --> <replaceregexp match="\$release\$" replace="${release}" flags="g" encoding="${charset}"> <fileset dir="${tmp.dir}" includes="*-combo.js"/> </replaceregexp> <!-- 保存 debug 版本 --> <copy todir="${tmp.dir}"> <fileset dir="${tmp.dir}"/> <mapper type="regexp" from="^(.*?)(?:-combo)?\.(css|js)$" to="\1_debug.\2"/> </copy> </target> <!-- 压缩代码 --> <target name="compress"> <!-- 用 YUICompressor 压缩 js --> <apply executable="java" verbose="true" dir="${tmp.dir}"> <arg line="-jar"/> <arg path="${yc.jar}"/> <arg line="--charset ${charset}"/> <arg line="-o "/> <targetfile/> <fileset dir="${tmp.dir}" includes="*-combo.js"/> <mapper type="regexp" from="^(.*?)(?:-combo)?\.(css|js)$" to="output/tmp/\1.\2"/> </apply> <delete> <fileset dir="${tmp.dir}" includes="*-combo.js"/> </delete> </target> <!-- 给文件加上版权信息 --> <target name="copyright"> <mkdir dir="${tmp.dir}/cp"/> <move todir="${tmp.dir}/cp"> <fileset dir="${tmp.dir}" includes="*.js,*.css" excludes="*_debug.js" /> </move> <ac:for param="file"> <path> <fileset dir="${tmp.dir}/cp" /> </path> <sequential> <concat destfile="@{file}.tmp" encoding="${charset}" outputencoding="${charset}"> <header filtering="no" trimleading="yes">/* QWrap-QiWu ${version}(${release}) */ </header> <fileset file="@{file}"/> </concat> <move file="@{file}.tmp" tofile="@{file}"/> </sequential> </ac:for> <move todir="${tmp.dir}"> <fileset dir="${tmp.dir}/cp" /> </move> <delete dir="${tmp.dir}/cp"/> </target> <!-- 扫尾工作 --> <target name="destroy"> <move todir="${tmp.dir}/../"> <fileset dir="${tmp.dir}" includes="*.js,*.css"/> </move> <delete dir="${tmp.dir}"/> </target> <!-- 拷贝release到其他文件夹 --> <target name="distribute"> <copy file="${root.dir}/output/qwrap_qiwu_full_debug.js" tofile="${js.dir}/_docs/_youa/js/apps/qwrap.js" /> <copy file="${root.dir}/output/qwrap_qiwu_full_debug.js" tofile="${js.dir}/apps_qiwu/qwrap_qiwu_combo.js" /> </target> <target name="common.build" depends="prepare,compress,copyright,destroy,distribute"> </target> </project>
{ "content_hash": "df72edfc547b18c0dcf5a9b2be926652", "timestamp": "", "source": "github", "line_count": 114, "max_line_length": 110, "avg_line_length": 29.06140350877193, "alnum_prop": 0.5553878659824932, "repo_name": "wedteam/qwrap", "id": "b3eed0dd0a171d52607a4ff97d265129bb02ace7", "size": "3435", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "resource/_tools/build/assets/common-build.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "22715" }, { "name": "CSS", "bytes": "16472" }, { "name": "HTML", "bytes": "3226599" }, { "name": "JavaScript", "bytes": "1673525" }, { "name": "PHP", "bytes": "719" }, { "name": "Perl", "bytes": "9840" }, { "name": "Python", "bytes": "3401" }, { "name": "Shell", "bytes": "11722" }, { "name": "XSLT", "bytes": "226410" } ], "symlink_target": "" }
#pragma once namespace clockwork { /** * Returns true if two floating-point values are equal. */ bool fequal(const double& a, const double& b); } // namespace clockwork
{ "content_hash": "1f0e6ed7c3f984e2109c801e022427c9", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 55, "avg_line_length": 15.909090909090908, "alnum_prop": 0.7028571428571428, "repo_name": "supranove/clockwork", "id": "d05619c65b88707f83e35b40881468b3c37d4efc", "size": "1322", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "codebase/include/types/math/numerical.hh", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "383598" }, { "name": "IDL", "bytes": "8496" } ], "symlink_target": "" }
@interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
{ "content_hash": "c13611858126250e125caf553cf54339", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 60, "avg_line_length": 16.857142857142858, "alnum_prop": 0.7796610169491526, "repo_name": "kaushalkantawala/blood-sugar-simulator", "id": "f85d921853411a3029f5154646228c07632df902", "size": "287", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BloodSugarSimulator/BloodSugarSimulator/AppDelegate.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "4306" } ], "symlink_target": "" }
class Answer < ActiveRecord::Base acts_as_votable belongs_to :question belongs_to :user validates :content, presence: true after_create :answer_mailer private def answer_mailer AnswerMailer.answer_notification(self).deliver end end
{ "content_hash": "b112caef963fbab4cb5a8edcd26ff272", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 50, "avg_line_length": 16.933333333333334, "alnum_prop": 0.7480314960629921, "repo_name": "ankawiecorek/challenge_app", "id": "05cdf43c9116f59d19a1fc876d192eec213ed98a", "size": "254", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/models/answer.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2749" }, { "name": "CoffeeScript", "bytes": "48" }, { "name": "Cucumber", "bytes": "3338" }, { "name": "HTML", "bytes": "20109" }, { "name": "JavaScript", "bytes": "2883" }, { "name": "Ruby", "bytes": "56766" } ], "symlink_target": "" }
\hypertarget{exclusion__recursive__mutex_8h}{\section{exclusion\-\_\-recursive\-\_\-mutex.\-h File Reference} \label{exclusion__recursive__mutex_8h}\index{exclusion\-\_\-recursive\-\_\-mutex.\-h@{exclusion\-\_\-recursive\-\_\-mutex.\-h}} } exclusion object \-: mutex which can be called recursively. {\ttfamily \#include $<$mutex$>$}\\* {\ttfamily \#include \char`\"{}hryky/exclusion/exclusion\-\_\-waitable\-\_\-lock.\-h\char`\"{}}\\* This graph shows which files directly or indirectly include this file\-: \nopagebreak \begin{figure}[H] \begin{center} \leavevmode \includegraphics[width=350pt]{exclusion__recursive__mutex_8h__dep__incl} \end{center} \end{figure} \subsection*{Classes} \begin{DoxyCompactItemize} \item class \hyperlink{classhryky_1_1exclusion_1_1_recursive_mutex}{hryky\-::exclusion\-::\-Recursive\-Mutex} \begin{DoxyCompactList}\small\item\em exclusion object \-: mutex which can be called recursively. \end{DoxyCompactList}\item class \hyperlink{classhryky_1_1exclusion_1_1_recursive_mutex_1_1_raw}{hryky\-::exclusion\-::\-Recursive\-Mutex\-::\-Raw} \begin{DoxyCompactList}\small\item\em retrieves the raw object by limited classes. \end{DoxyCompactList}\end{DoxyCompactItemize} \subsection*{Namespaces} \begin{DoxyCompactItemize} \item namespace \hyperlink{namespacehryky}{hryky} \begin{DoxyCompactList}\small\item\em the root of all namespaces in hryky-\/codebase. \end{DoxyCompactList}\item namespace \hyperlink{namespacehryky_1_1exclusion}{hryky\-::exclusion} \begin{DoxyCompactList}\small\item\em modules for exclusion control. \end{DoxyCompactList}\end{DoxyCompactItemize} \subsection*{Typedefs} \begin{DoxyCompactItemize} \item \hypertarget{namespacehryky_1_1exclusion_a1562883d89e93695e533a4de08782445}{typedef Recursive\-Mutex \hyperlink{namespacehryky_1_1exclusion_a1562883d89e93695e533a4de08782445}{hryky\-::exclusion\-::recursive\-\_\-mutex\-\_\-type}}\label{namespacehryky_1_1exclusion_a1562883d89e93695e533a4de08782445} \begin{DoxyCompactList}\small\item\em represents a mutex. \end{DoxyCompactList}\end{DoxyCompactItemize} \subsection{Detailed Description} exclusion object \-: mutex which can be called recursively. \begin{DoxyAuthor}{Author} H\-R\-Y\-K\-Y \end{DoxyAuthor} \begin{DoxyVersion}{Version} \end{DoxyVersion} \begin{DoxyParagraph}{Id\-:} \hyperlink{exclusion__recursive__mutex_8h}{exclusion\-\_\-recursive\-\_\-mutex.\-h} 150 2013-\/02-\/10 10\-:08\-:03\-Z \href{mailto:hryky.private@gmail.com}{\tt hryky.\-private@gmail.\-com} \end{DoxyParagraph}
{ "content_hash": "675f6b1837c90f4baf8e20ce69b3649b", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 298, "avg_line_length": 50.28, "alnum_prop": 0.7597454256165473, "repo_name": "hiroyuki-seki/hryky-codebase", "id": "f0d8795f7fcad3050655adfe62a2cce822adab90", "size": "2514", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/latex/exclusion__recursive__mutex_8h.tex", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "80878" }, { "name": "C", "bytes": "408" }, { "name": "C++", "bytes": "5645481" }, { "name": "CMake", "bytes": "165309" }, { "name": "Common Lisp", "bytes": "96981" }, { "name": "JavaScript", "bytes": "26" }, { "name": "M4", "bytes": "1801" }, { "name": "Makefile", "bytes": "2674" }, { "name": "Ruby", "bytes": "8244" }, { "name": "Shell", "bytes": "5675" }, { "name": "Vim script", "bytes": "40988" }, { "name": "Yacc", "bytes": "119704" } ], "symlink_target": "" }
package com.google.cloud; import static com.google.common.base.Preconditions.checkNotNull; import com.google.api.core.BetaApi; import com.google.api.gax.retrying.ResultRetryAlgorithm; import com.google.api.gax.retrying.TimedAttemptSettings; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import java.io.Serializable; import java.lang.reflect.Method; import java.util.Objects; import java.util.Set; import java.util.concurrent.Callable; /** * Exception retry algorithm implementation used by {@link RetryHelper}. */ @BetaApi public final class ExceptionHandler implements ResultRetryAlgorithm<Object>, Serializable { private static final long serialVersionUID = -2460707015779532919L; private static final ExceptionHandler DEFAULT_INSTANCE = newBuilder().retryOn(Exception.class).abortOn(RuntimeException.class).build(); private final ImmutableList<Interceptor> interceptors; private final ImmutableSet<Class<? extends Exception>> retriableExceptions; private final ImmutableSet<Class<? extends Exception>> nonRetriableExceptions; private final Set<RetryInfo> retryInfo = Sets.newHashSet(); public interface Interceptor extends Serializable { enum RetryResult { NO_RETRY, RETRY, CONTINUE_EVALUATION; } /** * This method is called before exception evaluation and could short-circuit the process. * * @param exception the exception that is being evaluated * @return {@link RetryResult} to indicate if the exception should be ignored ( * {@link RetryResult#RETRY}), propagated ({@link RetryResult#NO_RETRY}), or evaluation * should proceed ({@link RetryResult#CONTINUE_EVALUATION}). */ RetryResult beforeEval(Exception exception); /** * This method is called after the evaluation and could alter its result. * * @param exception the exception that is being evaluated * @param retryResult the result of the evaluation so far * @return {@link RetryResult} to indicate if the exception should be ignored ( * {@link RetryResult#RETRY}), propagated ({@link RetryResult#NO_RETRY}), or evaluation * should proceed ({@link RetryResult#CONTINUE_EVALUATION}). */ RetryResult afterEval(Exception exception, RetryResult retryResult); } /** * ExceptionHandler builder. */ public static class Builder { private final ImmutableList.Builder<Interceptor> interceptors = ImmutableList.builder(); private final ImmutableSet.Builder<Class<? extends Exception>> retriableExceptions = ImmutableSet.builder(); private final ImmutableSet.Builder<Class<? extends Exception>> nonRetriableExceptions = ImmutableSet.builder(); private Builder() {} /** * Adds the exception handler interceptors. Call order will be maintained. * * @param interceptors the interceptors for this exception handler * @return the Builder for chaining */ public Builder addInterceptors(Interceptor... interceptors) { for (Interceptor interceptor : interceptors) { this.interceptors.add(interceptor); } return this; } /** * Add the exceptions to ignore/retry-on. * * @param exceptions retry should continue when such exceptions are thrown * @return the Builder for chaining */ @SafeVarargs public final Builder retryOn(Class<? extends Exception>... exceptions) { for (Class<? extends Exception> exception : exceptions) { retriableExceptions.add(checkNotNull(exception)); } return this; } /** * Adds the exceptions to abort on. * * @param exceptions retry should abort when such exceptions are thrown * @return the Builder for chaining */ @SafeVarargs public final Builder abortOn(Class<? extends Exception>... exceptions) { for (Class<? extends Exception> exception : exceptions) { nonRetriableExceptions.add(checkNotNull(exception)); } return this; } /** * Returns a new ExceptionHandler instance. */ public ExceptionHandler build() { return new ExceptionHandler(this); } } @VisibleForTesting static final class RetryInfo implements Serializable { private static final long serialVersionUID = -4264634837841455974L; private final Class<? extends Exception> exception; private final Interceptor.RetryResult retry; private final Set<RetryInfo> children = Sets.newHashSet(); RetryInfo(Class<? extends Exception> exception, Interceptor.RetryResult retry) { this.exception = checkNotNull(exception); this.retry = checkNotNull(retry); } @Override public int hashCode() { return exception.hashCode(); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof RetryInfo)) { return false; } // We only care about exception in equality as we allow only one instance per exception return ((RetryInfo) obj).exception.equals(exception); } } private ExceptionHandler(Builder builder) { interceptors = builder.interceptors.build(); retriableExceptions = builder.retriableExceptions.build(); nonRetriableExceptions = builder.nonRetriableExceptions.build(); Preconditions.checkArgument( Sets.intersection(retriableExceptions, nonRetriableExceptions).isEmpty(), "Same exception was found in both retryable and non-retryable sets"); for (Class<? extends Exception> exception : retriableExceptions) { addRetryInfo(new RetryInfo(exception, Interceptor.RetryResult.RETRY), retryInfo); } for (Class<? extends Exception> exception : nonRetriableExceptions) { addRetryInfo(new RetryInfo(exception, Interceptor.RetryResult.NO_RETRY), retryInfo); } } private static void addRetryInfo(RetryInfo retryInfo, Set<RetryInfo> dest) { for (RetryInfo current : dest) { if (current.exception.isAssignableFrom(retryInfo.exception)) { addRetryInfo(retryInfo, current.children); return; } if (retryInfo.exception.isAssignableFrom(current.exception)) { retryInfo.children.add(current); } } dest.removeAll(retryInfo.children); dest.add(retryInfo); } private static RetryInfo findMostSpecificRetryInfo(Set<RetryInfo> retryInfo, Class<? extends Exception> exception) { for (RetryInfo current : retryInfo) { if (current.exception.isAssignableFrom(exception)) { RetryInfo match = findMostSpecificRetryInfo(current.children, exception); return match == null ? current : match; } } return null; } // called for Class<? extends Callable>, therefore a "call" method must be found. private static Method getCallableMethod(Class<?> clazz) { try { return clazz.getDeclaredMethod("call"); } catch (NoSuchMethodException e) { // check parent return getCallableMethod(clazz.getSuperclass()); } catch (SecurityException e) { // This should never happen throw new IllegalStateException("Unexpected exception", e); } } void verifyCaller(Callable<?> callable) { Method callMethod = getCallableMethod(callable.getClass()); for (Class<?> exceptionOrError : callMethod.getExceptionTypes()) { Preconditions.checkArgument(Exception.class.isAssignableFrom(exceptionOrError), "Callable method exceptions must be derived from Exception"); @SuppressWarnings("unchecked") Class<? extends Exception> exception = (Class<? extends Exception>) exceptionOrError; Preconditions.checkArgument(findMostSpecificRetryInfo(retryInfo, exception) != null, "Declared exception '" + exception + "' is not covered by exception handler"); } } @Override public boolean shouldRetry(Throwable prevThrowable, Object prevResponse) { if(!(prevThrowable instanceof Exception)) { return false; } Exception ex = (Exception) prevThrowable; for (Interceptor interceptor : interceptors) { Interceptor.RetryResult retryResult = checkNotNull(interceptor.beforeEval(ex)); if (retryResult != Interceptor.RetryResult.CONTINUE_EVALUATION) { return retryResult == Interceptor.RetryResult.RETRY; } } RetryInfo retryInfo = findMostSpecificRetryInfo(this.retryInfo, ex.getClass()); Interceptor.RetryResult retryResult = retryInfo == null ? Interceptor.RetryResult.NO_RETRY : retryInfo.retry; for (Interceptor interceptor : interceptors) { Interceptor.RetryResult interceptorRetry = checkNotNull(interceptor.afterEval(ex, retryResult)); if (interceptorRetry != Interceptor.RetryResult.CONTINUE_EVALUATION) { retryResult = interceptorRetry; } } return retryResult == Interceptor.RetryResult.RETRY; } @Override public TimedAttemptSettings createNextAttempt(Throwable prevThrowable, Object prevResponse, TimedAttemptSettings prevSettings) { // Return null to indicate that this implementation does not provide any specific attempt // settings, so by default the TimedRetryAlgorithm options can be used instead. return null; } @Override public int hashCode() { return Objects.hash(interceptors, retriableExceptions, nonRetriableExceptions, retryInfo); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof ExceptionHandler)) { return false; } ExceptionHandler other = (ExceptionHandler) obj; return Objects.equals(interceptors, other.interceptors) && Objects.equals(retriableExceptions, other.retriableExceptions) && Objects.equals(nonRetriableExceptions, other.nonRetriableExceptions) && Objects.equals(retryInfo, other.retryInfo); } /** * Returns an instance which retry any checked exception and abort on any runtime exception. */ public static ExceptionHandler getDefaultInstance() { return DEFAULT_INSTANCE; } public static Builder newBuilder() { return new Builder(); } }
{ "content_hash": "ec1f77fbec8b38266c7d24f843e16444", "timestamp": "", "source": "github", "line_count": 291, "max_line_length": 99, "avg_line_length": 35.48453608247423, "alnum_prop": 0.7086964942862677, "repo_name": "shinfan/gcloud-java", "id": "70d6cd49bbeaa9b9049449b454fe02c33d414a27", "size": "10943", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "google-cloud-core/src/main/java/com/google/cloud/ExceptionHandler.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "23036" }, { "name": "HTML", "bytes": "16224" }, { "name": "Java", "bytes": "8281673" }, { "name": "JavaScript", "bytes": "989" }, { "name": "Python", "bytes": "15024" }, { "name": "Shell", "bytes": "17472" } ], "symlink_target": "" }
(function(){ 'use strict'; /** * @class Global.core.Array * Wrapper class for Array * @extends Global.core.BaseClass * @alternateClassName Global.Arra * @singleton * */ Global.define('Global.core.Array',{ alias: 'Global.Array', singleton: true, /** * @method args2Array * Returns array which arguments is convert to. * @param {Object} arguments arguments. * @return {Array} converted array object. * * // return Array object. * function awesomeFunc(){ * var ary = Global.core.Array.args2Array(arguments); * } * */ args2Array: function(args){ if(args instanceof Array){ return args; }else{ return Array.prototype.slice.call(args); } }, /** * @method map2Array * Returns array which map{key:value} is convert to. * @param {Object} map The map to be converted. * @return {Array} converted array object. * * var map = { * hoge: 'hoge', * fuga: 'fuga', * piyo: 'piyo' * }, * list = Global.core.Array.map2Array(map); * * console.log(list); // ['hoge', 'fuga', 'piyo']; * */ map2Array: function(map) { var list = [], key; for(key in map){ list.push(map[key]); } return list; }, /** * @method each * Iterates an array. * @param {Object} map The map to be converted. * * var list = ['hoge', 'fuga', 'piyo']; * * Global.core.Array.each(list, function(index, value){ * console.log(index); // 0, 1, 2 * console.log(value); // 'hoge', 'fuga', 'piyo' * }); * */ each: function(list, callback){ var l = list.length, i = 0; for(; i < l; i++){ callback(i, list[i]); } }, /** * @method contains * Checks whether or not the given array contains the specified item. * @param {Boolean} return true when the given array contains the specified item. * * var list = ['hoge', 'fuga', 'piyo']; * * // return true. * console.log(Global.core.Array.contains(list, 'fuga')); */ contains: function(list, target) { var i = 0, l = list.length; for(; i < l; i++){ if(list[i] === target){ return true; } } return false; }, /** * @method remove */ remove: function(target, index, count){ var _count = count || 1; target.splice(index, _count); }, /** * @method makeRandomList * @param {Array} list to make ramdom * @param {Number} num length of new ramdom list. default: length of list */ makeRandomList: function(list, num) { var _num = num || list.length, randoms = Global.math.Random.getRandomNumList(_num), res = []; Global.Array.each(randoms, function(index, random) { res.push(list[random]); }); return res; } }); })();
{ "content_hash": "c7783a3c40f6feb6102a699452978cc1", "timestamp": "", "source": "github", "line_count": 129, "max_line_length": 89, "avg_line_length": 28.17829457364341, "alnum_prop": 0.43191196698762035, "repo_name": "kashiro/GlobalJS", "id": "a5ca542b60ff2214e24258434d9331aede81013f", "size": "3635", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "sample/app/scripts/core/Array.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7285" }, { "name": "JavaScript", "bytes": "306637" } ], "symlink_target": "" }
/** * $Id: XMLUTF8Transcoder.cpp 1662882 2015-02-28 02:07:25Z scantor $ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/TranscodingException.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/util/XMLUniDefs.hpp> #include <xercesc/util/XMLUTF8Transcoder.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // Local static data // // gUTFBytes // A list of counts of trailing bytes for each initial byte in the input. // // gUTFByteIndicator // For a UTF8 sequence of n bytes, n>=2, the first byte of the // sequence must contain n 1's followed by precisely 1 0 with the // rest of the byte containing arbitrary bits. This array stores // the required bit pattern for validity checking. // gUTFByteIndicatorTest // When bitwise and'd with the observed value, if the observed // value is correct then a result matching gUTFByteIndicator will // be produced. // // gUTFOffsets // A list of values to offset each result char type, according to how // many source bytes when into making it. // // gFirstByteMark // A list of values to mask onto the first byte of an encoded sequence, // indexed by the number of bytes used to create the sequence. // --------------------------------------------------------------------------- static const XMLByte gUTFBytes[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 , 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 , 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5 }; static const XMLByte gUTFByteIndicator[6] = { 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; static const XMLByte gUTFByteIndicatorTest[6] = { 0x80, 0xE0, 0xF0, 0xF8, 0xFC, 0xFE }; static const XMLUInt32 gUTFOffsets[6] = { 0, 0x3080, 0xE2080, 0x3C82080, 0xFA082080, 0x82082080 }; static const XMLByte gFirstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; // --------------------------------------------------------------------------- // XMLUTF8Transcoder: Constructors and Destructor // --------------------------------------------------------------------------- XMLUTF8Transcoder::XMLUTF8Transcoder(const XMLCh* const encodingName , const XMLSize_t blockSize , MemoryManager* const manager) :XMLTranscoder(encodingName, blockSize, manager) { } XMLUTF8Transcoder::~XMLUTF8Transcoder() { } // --------------------------------------------------------------------------- // XMLUTF8Transcoder: Implementation of the transcoder API // --------------------------------------------------------------------------- XMLSize_t XMLUTF8Transcoder::transcodeFrom(const XMLByte* const srcData , const XMLSize_t srcCount , XMLCh* const toFill , const XMLSize_t maxChars , XMLSize_t& bytesEaten , unsigned char* const charSizes) { // Watch for pathological scenario. Shouldn't happen, but... if (!srcCount || !maxChars) return 0; // // Get pointers to our start and end points of the input and output // buffers. // const XMLByte* srcPtr = srcData; const XMLByte* srcEnd = srcPtr + srcCount; XMLCh* outPtr = toFill; XMLCh* outEnd = outPtr + maxChars; unsigned char* sizePtr = charSizes; // // We now loop until we either run out of input data, or room to store // output chars. // while ((srcPtr < srcEnd) && (outPtr < outEnd)) { // Special-case ASCII, which is a leading byte value of <= 127 if (*srcPtr <= 127) { // Handle ASCII in groups instead of single character at a time. const XMLByte* srcPtr_save = srcPtr; const XMLSize_t chunkSize = (srcEnd-srcPtr)<(outEnd-outPtr)?(srcEnd-srcPtr):(outEnd-outPtr); for(XMLSize_t i=0;i<chunkSize && *srcPtr <= 127;++i) *outPtr++ = XMLCh(*srcPtr++); memset(sizePtr,1,srcPtr - srcPtr_save); sizePtr += srcPtr - srcPtr_save; if (srcPtr == srcEnd || outPtr == outEnd) break; } // See how many trailing src bytes this sequence is going to require const unsigned int trailingBytes = gUTFBytes[*srcPtr]; // // If there are not enough source bytes to do this one, then we // are done. Note that we done >= here because we are implicitly // counting the 1 byte we get no matter what. // // If we break out here, then there is nothing to undo since we // haven't updated any pointers yet. // if (srcPtr + trailingBytes >= srcEnd) break; // Looks ok, so lets build up the value // or at least let's try to do so--remembering that // we cannot assume the encoding to be valid: // first, test first byte if((gUTFByteIndicatorTest[trailingBytes] & *srcPtr) != gUTFByteIndicator[trailingBytes]) { char pos[2] = {(char)0x31, 0}; char len[2] = {(char)(trailingBytes+0x31), 0}; char byte[2] = {(char)*srcPtr,0}; ThrowXMLwithMemMgr3(UTFDataFormatException, XMLExcepts::UTF8_FormatError, pos, byte, len, getMemoryManager()); } /*** * http://www.unicode.org/reports/tr27/ * * Table 3.1B. lists all of the byte sequences that are legal in UTF-8. * A range of byte values such as A0..BF indicates that any byte from A0 to BF (inclusive) * is legal in that position. * Any byte value outside of the ranges listed is illegal. * For example, * the byte sequence <C0 AF> is illegal since C0 is not legal in the 1st Byte column. * The byte sequence <E0 9F 80> is illegal since in the row * where E0 is legal as a first byte, * 9F is not legal as a second byte. * The byte sequence <F4 80 83 92> is legal, since every byte in that sequence matches * a byte range in a row of the table (the last row). * * * Table 3.1B. Legal UTF-8 Byte Sequences * Code Points 1st Byte 2nd Byte 3rd Byte 4th Byte * ========================================================================= * U+0000..U+007F 00..7F * ------------------------------------------------------------------------- * U+0080..U+07FF C2..DF 80..BF * * ------------------------------------------------------------------------- * U+0800..U+0FFF E0 A0..BF 80..BF * -- * * U+1000..U+FFFF E1..EF 80..BF 80..BF * * -------------------------------------------------------------------------- * U+10000..U+3FFFF F0 90..BF 80..BF 80..BF * -- * U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF * U+100000..U+10FFFF F4 80..8F 80..BF 80..BF * -- * ========================================================================== * * Cases where a trailing byte range is not 80..BF are underlined in the table to * draw attention to them. These occur only in the second byte of a sequence. * ***/ XMLUInt32 tmpVal = 0; switch(trailingBytes) { case 1 : // UTF-8: [110y yyyy] [10xx xxxx] // Unicode: [0000 0yyy] [yyxx xxxx] // // 0xC0, 0xC1 has been filtered out checkTrailingBytes(*(srcPtr+1), 1, 1); tmpVal = *srcPtr++; tmpVal <<= 6; tmpVal += *srcPtr++; break; case 2 : // UTF-8: [1110 zzzz] [10yy yyyy] [10xx xxxx] // Unicode: [zzzz yyyy] [yyxx xxxx] // if (( *srcPtr == 0xE0) && ( *(srcPtr+1) < 0xA0)) { char byte0[2] = {(char)*srcPtr ,0}; char byte1[2] = {(char)*(srcPtr+1),0}; ThrowXMLwithMemMgr2(UTFDataFormatException , XMLExcepts::UTF8_Invalid_3BytesSeq , byte0 , byte1 , getMemoryManager()); } checkTrailingBytes(*(srcPtr+1), 2, 1); checkTrailingBytes(*(srcPtr+2), 2, 2); // // D36 (a) UTF-8 is the Unicode Transformation Format that serializes // a Unicode code point as a sequence of one to four bytes, // as specified in Table 3.1, UTF-8 Bit Distribution. // (b) An illegal UTF-8 code unit sequence is any byte sequence that // does not match the patterns listed in Table 3.1B, Legal UTF-8 // Byte Sequences. // (c) An irregular UTF-8 code unit sequence is a six-byte sequence // where the first three bytes correspond to a high surrogate, // and the next three bytes correspond to a low surrogate. // As a consequence of C12, these irregular UTF-8 sequences shall // not be generated by a conformant process. // //irregular three bytes sequence // that is zzzzyy matches leading surrogate tag 110110 or // trailing surrogate tag 110111 // *srcPtr=1110 1101 // *(srcPtr+1)=1010 yyyy or // *(srcPtr+1)=1011 yyyy // // 0xED 1110 1101 // 0xA0 1010 0000 if ((*srcPtr == 0xED) && (*(srcPtr+1) >= 0xA0)) { char byte0[2] = {(char)*srcPtr, 0}; char byte1[2] = {(char)*(srcPtr+1),0}; ThrowXMLwithMemMgr2(UTFDataFormatException , XMLExcepts::UTF8_Irregular_3BytesSeq , byte0 , byte1 , getMemoryManager()); } tmpVal = *srcPtr++; tmpVal <<= 6; tmpVal += *srcPtr++; tmpVal <<= 6; tmpVal += *srcPtr++; break; case 3 : // UTF-8: [1111 0uuu] [10uu zzzz] [10yy yyyy] [10xx xxxx]* // Unicode: [1101 10ww] [wwzz zzyy] (high surrogate) // [1101 11yy] [yyxx xxxx] (low surrogate) // * uuuuu = wwww + 1 // if (((*srcPtr == 0xF0) && (*(srcPtr+1) < 0x90)) || ((*srcPtr == 0xF4) && (*(srcPtr+1) > 0x8F)) ) { char byte0[2] = {(char)*srcPtr ,0}; char byte1[2] = {(char)*(srcPtr+1),0}; ThrowXMLwithMemMgr2(UTFDataFormatException , XMLExcepts::UTF8_Invalid_4BytesSeq , byte0 , byte1 , getMemoryManager()); } checkTrailingBytes(*(srcPtr+1), 3, 1); checkTrailingBytes(*(srcPtr+2), 3, 2); checkTrailingBytes(*(srcPtr+3), 3, 3); tmpVal = *srcPtr++; tmpVal <<= 6; tmpVal += *srcPtr++; tmpVal <<= 6; tmpVal += *srcPtr++; tmpVal <<= 6; tmpVal += *srcPtr++; break; default: // trailingBytes > 3 /*** * The definition of UTF-8 in Annex D of ISO/IEC 10646-1:2000 also allows * for the use of five- and six-byte sequences to encode characters that * are outside the range of the Unicode character set; those five- and * six-byte sequences are illegal for the use of UTF-8 as a transformation * of Unicode characters. ISO/IEC 10646 does not allow mapping of unpaired * surrogates, nor U+FFFE and U+FFFF (but it does allow other noncharacters). ***/ char len[2] = {(char)(trailingBytes+0x31), 0}; char byte[2] = {(char)*srcPtr,0}; ThrowXMLwithMemMgr2(UTFDataFormatException , XMLExcepts::UTF8_Exceeds_BytesLimit , byte , len , getMemoryManager()); break; } // since trailingBytes comes from an array, this logic is redundant // default : // ThrowXMLwithMemMgr(TranscodingException, XMLExcepts::Trans_BadSrcSeq); //} tmpVal -= gUTFOffsets[trailingBytes]; // // If it will fit into a single char, then put it in. Otherwise // encode it as a surrogate pair. If its not valid, use the // replacement char. // if (!(tmpVal & 0xFFFF0000)) { *sizePtr++ = trailingBytes + 1; *outPtr++ = XMLCh(tmpVal); } else if (tmpVal > 0x10FFFF) { // // If we've gotten more than 32 chars so far, then just break // out for now and lets process those. When we come back in // here again, we'll get no chars and throw an exception. This // way, the error will have a line and col number closer to // the real problem area. // if ((outPtr - toFill) > 32) break; ThrowXMLwithMemMgr(TranscodingException, XMLExcepts::Trans_BadSrcSeq, getMemoryManager()); } else { // // If we have enough room to store the leading and trailing // chars, then lets do it. Else, pretend this one never // happened, and leave it for the next time. Since we don't // update the bytes read until the bottom of the loop, by // breaking out here its like it never happened. // if (outPtr + 1 >= outEnd) break; // Store the leading surrogate char tmpVal -= 0x10000; *sizePtr++ = trailingBytes + 1; *outPtr++ = XMLCh((tmpVal >> 10) + 0xD800); // // And then the trailing char. This one accounts for no // bytes eaten from the source, so set the char size for this // one to be zero. // *sizePtr++ = 0; *outPtr++ = XMLCh((tmpVal & 0x3FF) + 0xDC00); } } // Update the bytes eaten bytesEaten = srcPtr - srcData; // Return the characters read return outPtr - toFill; } XMLSize_t XMLUTF8Transcoder::transcodeTo( const XMLCh* const srcData , const XMLSize_t srcCount , XMLByte* const toFill , const XMLSize_t maxBytes , XMLSize_t& charsEaten , const UnRepOpts options) { // Watch for pathological scenario. Shouldn't happen, but... if (!srcCount || !maxBytes) return 0; // // Get pointers to our start and end points of the input and output // buffers. // const XMLCh* srcPtr = srcData; const XMLCh* srcEnd = srcPtr + srcCount; XMLByte* outPtr = toFill; XMLByte* outEnd = toFill + maxBytes; while (srcPtr < srcEnd) { // // Tentatively get the next char out. We have to get it into a // 32 bit value, because it could be a surrogate pair. // XMLUInt32 curVal = *srcPtr; // // If its a leading surrogate, then lets see if we have the trailing // available. If not, then give up now and leave it for next time. // unsigned int srcUsed = 1; if ((curVal >= 0xD800) && (curVal <= 0xDBFF)) { if (srcPtr + 1 >= srcEnd) break; // Create the composite surrogate pair curVal = ((curVal - 0xD800) << 10) + ((*(srcPtr + 1) - 0xDC00) + 0x10000); // And indicate that we ate another one srcUsed++; } // Figure out how many bytes we need unsigned int encodedBytes; if (curVal < 0x80) encodedBytes = 1; else if (curVal < 0x800) encodedBytes = 2; else if (curVal < 0x10000) encodedBytes = 3; else if (curVal < 0x110000) encodedBytes = 4; else { // If the options say to throw, then throw if (options == UnRep_Throw) { XMLCh tmpBuf[17]; XMLString::binToText(curVal, tmpBuf, 16, 16, getMemoryManager()); ThrowXMLwithMemMgr2 ( TranscodingException , XMLExcepts::Trans_Unrepresentable , tmpBuf , getEncodingName() , getMemoryManager() ); } // Else, use the replacement character *outPtr++ = chSpace; srcPtr += srcUsed; continue; } // // If we cannot fully get this char into the output buffer, // then leave it for the next time. // if (outPtr + encodedBytes > outEnd) break; // We can do it, so update the source index srcPtr += srcUsed; // // And spit out the bytes. We spit them out in reverse order // here, so bump up the output pointer and work down as we go. // outPtr += encodedBytes; switch(encodedBytes) { case 6 : *--outPtr = XMLByte((curVal | 0x80UL) & 0xBFUL); curVal >>= 6; case 5 : *--outPtr = XMLByte((curVal | 0x80UL) & 0xBFUL); curVal >>= 6; case 4 : *--outPtr = XMLByte((curVal | 0x80UL) & 0xBFUL); curVal >>= 6; case 3 : *--outPtr = XMLByte((curVal | 0x80UL) & 0xBFUL); curVal >>= 6; case 2 : *--outPtr = XMLByte((curVal | 0x80UL) & 0xBFUL); curVal >>= 6; case 1 : *--outPtr = XMLByte ( curVal | gFirstByteMark[encodedBytes] ); } // Add the encoded bytes back in again to indicate we've eaten them outPtr += encodedBytes; } // Fill in the chars we ate charsEaten = (srcPtr - srcData); // And return the bytes we filled in return (outPtr - toFill); } bool XMLUTF8Transcoder::canTranscodeTo(const unsigned int toCheck) { // We can represent anything in the Unicode (with surrogates) range return (toCheck <= 0x10FFFF); } XERCES_CPP_NAMESPACE_END
{ "content_hash": "75425d647ad325081ae02506a8e498db", "timestamp": "", "source": "github", "line_count": 541, "max_line_length": 122, "avg_line_length": 38.613678373382626, "alnum_prop": 0.4572044040210627, "repo_name": "JLUCPGROUP/cuda8_sac", "id": "2af68a2cdb8b43b2f075edfea2eb37d2c38bed79", "size": "21694", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "cuda8_sac/include/xercesc/util/XMLUTF8Transcoder.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "198775" }, { "name": "C++", "bytes": "9954685" }, { "name": "Cuda", "bytes": "94245" }, { "name": "Makefile", "bytes": "2272" } ], "symlink_target": "" }
package com.hp.alm.ali.idea.services; import com.hp.alm.ali.ServerVersion; import com.hp.alm.ali.idea.IntellijTest; import com.hp.alm.ali.idea.entity.EntityAdapter; import com.hp.alm.ali.idea.entity.EntityListener; import com.hp.alm.ali.idea.entity.EntityRef; import com.hp.alm.ali.idea.model.Entity; import com.hp.alm.ali.idea.progress.IndicatingInputStream; import com.hp.alm.ali.idea.rest.RestException; import org.apache.commons.io.IOUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.StringReader; public class AttachmentServiceTest extends IntellijTest { public AttachmentServiceTest() { super(ServerVersion.AGM); } private AttachmentService attachmentService; private File file; @Before public void preCleanup() throws IOException { attachmentService = getComponent(AttachmentService.class); file = createFile(); } @Test public void testCreateAttachment() throws IOException { handler.addRequest("POST", "/qcbin/rest/domains/domain/projects/project/defects/1/attachments", 201) .expectHeader("Content-Type", "application/octet-stream") .expectHeader("Slug", "logfile.txt") .content("attachmentServiceTest_attachment.xml"); handler.async(); addEntityListener(new EntityLoaded(handler, new EntityLoaded.Listener() { @Override public void evaluate(Entity entity, EntityListener.Event event) { checkAttachment(entity); Assert.assertEquals(EntityListener.Event.CREATE, event); } })); String name = attachmentService.createAttachment("logfile.txt", new IndicatingInputStream(file, null), file.length(), new EntityRef("defect", 1)); Assert.assertEquals("logfile.txt", name); } @Test public void testCreateAttachment_failure() throws IOException { handler.addRequest("POST", "/qcbin/rest/domains/domain/projects/project/defects/1/attachments", 500) .responseBody("Failed"); String name = attachmentService.createAttachment("logfile.txt", new IndicatingInputStream(file, null), file.length(), new EntityRef("defect", 1)); Assert.assertNull(name); checkError("Failed"); } @Test public void testDeleteAttachment() { handler.addRequest("DELETE", "/qcbin/rest/domains/domain/projects/project/defects/1/attachments/logfile.txt", 200) .content("attachmentServiceTest_attachment.xml"); handler.async(); addEntityListener(new EntityNotFound(handler, "attachment", 653, true)); attachmentService.deleteAttachment("logfile.txt", new EntityRef("defect", 1)); } @Test public void testDeleteAttachment_failure() { handler.addRequest("DELETE", "/qcbin/rest/domains/domain/projects/project/defects/1/attachments/logfile.txt", 500) .responseBody("Failed"); attachmentService.deleteAttachment("logfile.txt", new EntityRef("defect", 1)); checkError("Failed"); } @Test public void testUpdateAttachmentProperty() { handler.addRequest("PUT", "/qcbin/rest/domains/domain/projects/project/defects/1/attachments/logfile.txt", 200) .content("attachmentServiceTest_attachment.xml"); handler.async(); addEntityListener(new EntityLoaded(handler, new EntityLoaded.Listener() { @Override public void evaluate(Entity entity, EntityListener.Event event) { checkAttachment(entity); Assert.assertEquals(EntityListener.Event.GET, event); } })); Entity attachment = attachmentService.updateAttachmentProperty("logfile.txt", new EntityRef("defect", 1), "description", "newValue", false); checkAttachment(attachment); } @Test public void testUpdateAttachmentProperty_fail() { handler.addRequest("PUT", "/qcbin/rest/domains/domain/projects/project/defects/1/attachments/logfile.txt", 500) .responseBody("Failed"); Entity attachment = attachmentService.updateAttachmentProperty("logfile.txt", new EntityRef("defect", 1), "description", "newValue", false); Assert.assertNull(attachment); checkError("Failed"); } @Test public void testUpdateAttachmentProperty_failSilently() { handler.addRequest("PUT", "/qcbin/rest/domains/domain/projects/project/defects/1/attachments/logfile.txt", 500) .responseBody("Failed"); Entity attachment = attachmentService.updateAttachmentProperty("logfile.txt", new EntityRef("defect", 1), "description", "newValue", true); Assert.assertNull(attachment); } @Test public void testUpdateAttachmentContent() throws FileNotFoundException { handler.addRequest("PUT", "/qcbin/rest/domains/domain/projects/project/defects/1/attachments/logfile.txt", 200) .expectHeader("Content-Type", "application/octet-stream") .content("attachmentServiceTest_attachment.xml"); handler.async(); addEntityListener(new EntityLoaded(handler, new EntityLoaded.Listener() { @Override public void evaluate(Entity entity, EntityListener.Event event) { checkAttachment(entity); Assert.assertEquals(EntityListener.Event.GET, event); } })); boolean updated = attachmentService.updateAttachmentContent("logfile.txt", new EntityRef("defect", 1), new IndicatingInputStream(file, null), file.length(), false); Assert.assertTrue(updated); } @Test public void testUpdateAttachmentContent_fail() throws FileNotFoundException { handler.addRequest("PUT", "/qcbin/rest/domains/domain/projects/project/defects/1/attachments/logfile.txt", 500) .responseBody("Failed"); boolean updated = attachmentService.updateAttachmentContent("logfile.txt", new EntityRef("defect", 1), new IndicatingInputStream(file, null), file.length(), false); Assert.assertFalse(updated); checkError("Failed"); } @Test public void testUpdateAttachmentContent_failSilently() throws FileNotFoundException { handler.addRequest("PUT", "/qcbin/rest/domains/domain/projects/project/defects/1/attachments/logfile.txt", 500) .responseBody("Failed"); boolean updated = attachmentService.updateAttachmentContent("logfile.txt", new EntityRef("defect", 1), new IndicatingInputStream(file, null), file.length(), true); Assert.assertFalse(updated); } @Test public void testGetAttachmentEntity() { handler.addRequest("GET", "/qcbin/rest/domains/domain/projects/project/defects/1/attachments/my%20name?alt=application/xml", 200) .content("attachmentServiceTest_attachment.xml"); Entity attachment = new Entity("attachment", 653); attachment.setProperty("name", "my name"); attachment.setProperty("parent-type", "defect"); attachment.setProperty("parent-id", "1"); Entity entity = attachmentService.getAttachmentEntity(attachment); checkAttachment(entity); } @Test public void testGetAttachmentEntity_alternative() { handler.addRequest("GET", "/qcbin/rest/domains/domain/projects/project/defects/1/attachments/my%20name?alt=application/xml", 200) .content("attachmentServiceTest_attachment.xml"); Entity entity = attachmentService.getAttachmentEntity("my name", new EntityRef("defect", 1)); checkAttachment(entity); } @Test public void testGetAttachmentEntity_failure() { handler.addRequest("GET", "/qcbin/rest/domains/domain/projects/project/defects/1/attachments/my%20name?alt=application/xml", 500) .responseBody("Not this time"); Entity entity = attachmentService.getAttachmentEntity("my name", new EntityRef("defect", 1)); Assert.assertNull(entity); checkError("Not this time"); } @Test public void testGetAttachmentEntity_illegal() { Entity defect = new Entity("defect", 1); try { attachmentService.getAttachmentEntity(defect); Assert.fail("should have failed"); } catch (IllegalArgumentException e) { } } private void checkAttachment(Entity entity) { Assert.assertEquals("attachment", entity.getType()); Assert.assertEquals(653, entity.getId()); Assert.assertEquals("1", entity.getPropertyValue("parent-id")); Assert.assertEquals("defect", entity.getPropertyValue("parent-type")); Assert.assertEquals("7", entity.getPropertyValue("file-size")); } private File createFile() throws IOException { File tempFile = File.createTempFile("AttachmentServiceTest", null); tempFile.deleteOnExit(); FileWriter fw = new FileWriter(tempFile); IOUtils.copy(new StringReader("content"), fw); fw.close(); return tempFile; } }
{ "content_hash": "2b381c32c24d69a60374d37a2779e7b5", "timestamp": "", "source": "github", "line_count": 223, "max_line_length": 172, "avg_line_length": 41.300448430493276, "alnum_prop": 0.6770901194353963, "repo_name": "janotav/ali-idea-plugin", "id": "aa0a29842920252813fedb857bd9dd5acf182a9a", "size": "9833", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "ali-plugin-main/src/test/java/com/hp/alm/ali/idea/services/AttachmentServiceTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "1138" }, { "name": "Java", "bytes": "1995293" }, { "name": "Shell", "bytes": "2825" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("Symmetry")] [assembly: AssemblyDescription("The fundamental abstractions that Microsoft forgot to include.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("2011 Johan Kullbom")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
{ "content_hash": "1003b041dc5f2c5b8480c85cc188b44a", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 97, "avg_line_length": 39.03703703703704, "alnum_prop": 0.7514231499051234, "repo_name": "kullbom/Symmetry", "id": "f123c1eadcdd68c31fa42658e22a787714f059e4", "size": "1054", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "source/Symmetry/AssemblyInfo.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C#", "bytes": "27371" } ], "symlink_target": "" }
package hypervisor import ( "fmt" "strings" "sync" "github.com/hyperhq/runv/api" hyperstartapi "github.com/hyperhq/runv/hyperstart/api/json" "github.com/hyperhq/runv/hypervisor/network" ) const ( MAX_NIC = int(^uint(0) >> 1) // Eth is network card, while lo is alias, what's the maximum for each? same? // let upper level logic care about the restriction. here is just an upbond. DEFAULT_LO_DEVICE_NAME = "lo" ) type NetworkContext struct { *api.SandboxConfig sandbox *VmContext ports []*api.PortDescription eth map[int]*InterfaceCreated lo map[string]*InterfaceCreated idMap map[string]*InterfaceCreated // a secondary index for both eth and lo, for lo, the hostdevice is empty slotLock *sync.RWMutex } func NewNetworkContext() *NetworkContext { return &NetworkContext{ ports: []*api.PortDescription{}, eth: make(map[int]*InterfaceCreated), lo: make(map[string]*InterfaceCreated), idMap: make(map[string]*InterfaceCreated), slotLock: &sync.RWMutex{}, } } func (nc *NetworkContext) sandboxInfo() *hyperstartapi.Pod { vmSpec := NewVmSpec() vmSpec.Hostname = nc.Hostname vmSpec.Dns = nc.Dns vmSpec.DnsSearch = nc.DnsSearch vmSpec.DnsOptions = nc.DnsOptions if nc.Neighbors != nil { vmSpec.PortmappingWhiteLists = &hyperstartapi.PortmappingWhiteList{ InternalNetworks: nc.Neighbors.InternalNetworks, ExternalNetworks: nc.Neighbors.ExternalNetworks, } } return vmSpec } func (nc *NetworkContext) applySlot() int { for i := 0; i <= MAX_NIC; i++ { if _, ok := nc.eth[i]; !ok { nc.eth[i] = nil return i } } return -1 } func (nc *NetworkContext) freeSlot(slot int) { if inf, ok := nc.eth[slot]; !ok { nc.sandbox.Log(WARNING, "Freeing an unoccupied eth slot %d", slot) return } else if inf != nil { if _, ok := nc.idMap[inf.Id]; ok { delete(nc.idMap, inf.Id) } } nc.sandbox.Log(DEBUG, "Free slot %d of eth", slot) delete(nc.eth, slot) } // nextAvailableDevName find the initial device name in guest when add a new tap device // then rename it to some new name. // For example: user want to insert a new nic named "eth5" into container, which already owns // "eth0", "eth3" and "eth4". After tap device is added to VM, guest will detect a new device // named "eth1" which is first available "ethX" device, then guest will try to rename "eth1" to // "eth5". Then container will have "eth0", "eth3", "eth4" and "eth5" in the last. // This function try to find the first available "ethX" as said above. @WeiZhang555 func (nc *NetworkContext) nextAvailableDevName() string { for i := 0; i <= MAX_NIC; i++ { find := false for _, inf := range nc.eth { if inf != nil && inf.NewName == fmt.Sprintf("eth%d", i) { find = true break } } if !find { return fmt.Sprintf("eth%d", i) } } return "" } func (nc *NetworkContext) addInterface(inf *api.InterfaceDescription, result chan api.Result) { if inf.Lo { if len(inf.Ip) == 0 { estr := fmt.Sprintf("creating an interface without an IP address: %#v", inf) nc.sandbox.Log(ERROR, estr) result <- NewSpecError(inf.Id, estr) return } if inf.Id == "" { inf.Id = "lo" } i := &InterfaceCreated{ Id: inf.Id, DeviceName: DEFAULT_LO_DEVICE_NAME, IpAddr: inf.Ip, Mtu: inf.Mtu, } nc.lo[inf.Ip] = i nc.idMap[inf.Id] = i result <- &api.ResultBase{ Id: inf.Id, Success: true, } return } var devChan chan VmEvent = make(chan VmEvent, 1) go func() { nc.slotLock.Lock() defer nc.slotLock.Unlock() idx := nc.applySlot() initialDevName := nc.nextAvailableDevName() if inf.Id == "" { inf.Id = fmt.Sprintf("%d", idx) } if idx < 0 || initialDevName == "" { estr := fmt.Sprintf("no available ethernet slot/name for interface %#v", inf) nc.sandbox.Log(ERROR, estr) result <- NewBusyError(inf.Id, estr) close(devChan) return } nc.configureInterface(idx, nc.sandbox.NextPciAddr(), initialDevName, inf, devChan) }() go func() { ev, ok := <-devChan if !ok { nc.sandbox.Log(ERROR, "chan closed while waiting network inserted event: %#v", ev) return } // ev might be DeviceInsert failed, or inserted if fe, ok := ev.(*DeviceFailed); ok { if inf, ok := fe.Session.(*InterfaceCreated); ok { nc.netdevInsertFailed(inf.Index, inf.DeviceName) nc.sandbox.Log(ERROR, "interface creation failed: %#v", inf) } else if inf, ok := fe.Session.(*NetDevInsertedEvent); ok { nc.netdevInsertFailed(inf.Index, inf.DeviceName) nc.sandbox.Log(ERROR, "interface creation failed: %#v", inf) } result <- fe return } else if ni, ok := ev.(*NetDevInsertedEvent); ok { created := nc.idMap[inf.Id] created.TapFd = ni.TapFd nc.sandbox.Log(DEBUG, "nic insert success: %s", ni.Id) result <- ni return } nc.sandbox.Log(ERROR, "got unknown event while waiting network inserted event: %#v", ev) result <- NewDeviceError(inf.Id, "unknown event") }() } func (nc *NetworkContext) removeInterface(id string, result chan api.Result) { if inf, ok := nc.idMap[id]; !ok { nc.sandbox.Log(WARNING, "trying remove a non-exist interface %s", id) result <- api.NewResultBase(id, true, "not exist") return } else if inf.HostDevice == "" { // a virtual interface delete(nc.idMap, id) delete(nc.lo, inf.IpAddr) result <- api.NewResultBase(id, true, "") return } else { nc.slotLock.Lock() defer nc.slotLock.Unlock() if _, ok := nc.eth[inf.Index]; !ok { delete(nc.idMap, id) nc.sandbox.Log(INFO, "non-configured network device %d remove failed", inf.Index) result <- api.NewResultBase(id, true, "not configured eth") return } var devChan chan VmEvent = make(chan VmEvent, 1) nc.sandbox.Log(DEBUG, "remove network card %d: %s", inf.Index, inf.IpAddr) nc.sandbox.DCtx.RemoveNic(nc.sandbox, inf, &NetDevRemovedEvent{Index: inf.Index}, devChan) go func() { ev, ok := <-devChan if !ok { return } success := true message := "" if fe, ok := ev.(*DeviceFailed); ok { success = false message = "unplug failed" if inf, ok := fe.Session.(*NetDevRemovedEvent); ok { nc.sandbox.Log(ERROR, "interface remove failed: %#v", inf) } } nc.slotLock.Lock() defer nc.slotLock.Unlock() nc.freeSlot(inf.Index) nc.cleanupInf(inf) result <- api.NewResultBase(id, success, message) }() } } // allInterfaces return all the network interfaces except loop func (nc *NetworkContext) allInterfaces() (nics []*InterfaceCreated) { nc.slotLock.Lock() defer nc.slotLock.Unlock() for _, v := range nc.eth { if v != nil { nics = append(nics, v) } } return } func (nc *NetworkContext) updateInterface(inf *api.InterfaceDescription) error { oldInf, ok := nc.idMap[inf.Id] if !ok { nc.sandbox.Log(WARNING, "trying update a non-exist interface %s", inf.Id) return fmt.Errorf("interface %q not exists", inf.Id) } // only support update some fields: Name, ip addresses, mtu nc.slotLock.Lock() defer nc.slotLock.Unlock() if inf.Name != "" { oldInf.NewName = inf.Name } if inf.Mtu > 0 { oldInf.Mtu = inf.Mtu } if len(inf.Ip) > 0 { addrs := strings.Split(inf.Ip, ",") oldAddrs := strings.Split(oldInf.IpAddr, ",") for _, ip := range addrs { var found bool if ip[0] == '-' { // to delete ip = ip[1:] for k, i := range oldAddrs { if i == ip { oldAddrs = append(oldAddrs[:k], oldAddrs[k+1:]...) found = true break } } if !found { return fmt.Errorf("failed to delete %q: not found", ip) } } else { // to add oldAddrs = append(oldAddrs, ip) } } oldInf.IpAddr = strings.Join(oldAddrs, ",") } return nil } func (nc *NetworkContext) netdevInsertFailed(idx int, name string) { nc.slotLock.Lock() defer nc.slotLock.Unlock() if _, ok := nc.eth[idx]; !ok { nc.sandbox.Log(INFO, "network device %d (%s) insert failed before configured", idx, name) return } nc.sandbox.Log(INFO, "network device %d (%s) insert failed", idx, name) nc.freeSlot(idx) } func (nc *NetworkContext) configureInterface(index, pciAddr int, name string, inf *api.InterfaceDescription, result chan<- VmEvent) { if inf.TapName == "" { inf.TapName = network.NicName(nc.sandbox.Id, index) } settings, err := network.Configure(inf) if err != nil { nc.sandbox.Log(ERROR, "interface creating failed: %v", err.Error()) session := &InterfaceCreated{Id: inf.Id, Index: index, PCIAddr: pciAddr, DeviceName: name, NewName: inf.Name, Mtu: inf.Mtu} result <- &DeviceFailed{Session: session} return } created, err := interfaceGot(inf.Id, index, pciAddr, name, inf.Name, settings) if err != nil { result <- &DeviceFailed{Session: created} return } h := &HostNicInfo{ Id: created.Id, Device: created.HostDevice, Mac: created.MacAddr, Bridge: created.Bridge, Gateway: created.Bridge, Options: inf.Options, } // Note: Use created.NewName add tap name // this is because created.DeviceName isn't always uniq, // instead NewName is real nic name in VM which is certainly uniq g := &GuestNicInfo{ Device: created.NewName, Ipaddr: created.IpAddr, Index: created.Index, Busaddr: created.PCIAddr, } nc.eth[index] = created nc.idMap[created.Id] = created nc.sandbox.DCtx.AddNic(nc.sandbox, h, g, result) } func (nc *NetworkContext) cleanupInf(inf *InterfaceCreated) { network.ReleaseAddr(inf.IpAddr) } func (nc *NetworkContext) getInterface(id string) *InterfaceCreated { nc.slotLock.RLock() defer nc.slotLock.RUnlock() inf, ok := nc.idMap[id] if ok { return inf } return nil } func (nc *NetworkContext) getIPAddrs() []string { nc.slotLock.RLock() defer nc.slotLock.RUnlock() res := []string{} for _, inf := range nc.eth { if inf.IpAddr != "" { addrs := strings.Split(inf.IpAddr, ",") res = append(res, addrs...) } } return res } func (nc *NetworkContext) getRoutes() []hyperstartapi.Route { nc.slotLock.RLock() defer nc.slotLock.RUnlock() routes := []hyperstartapi.Route{} for _, inf := range nc.idMap { for _, r := range inf.RouteTable { routes = append(routes, hyperstartapi.Route{ Dest: r.Destination, Gateway: r.Gateway, Device: inf.NewName, }) } } return routes } func (nc *NetworkContext) close() { nc.slotLock.Lock() defer nc.slotLock.Unlock() for _, inf := range nc.eth { nc.cleanupInf(inf) } nc.eth = map[int]*InterfaceCreated{} nc.lo = map[string]*InterfaceCreated{} nc.idMap = map[string]*InterfaceCreated{} } func interfaceGot(id string, index int, pciAddr int, deviceName, newName string, inf *network.Settings) (*InterfaceCreated, error) { rt := []*RouteRule{} /* Route rule is generated automaticly on first interface, * or generated on the gateway configured interface. */ if (index == 0 && inf.Automatic) || (!inf.Automatic && inf.Gateway != "") { rt = append(rt, &RouteRule{ Destination: "0.0.0.0/0", Gateway: inf.Gateway, ViaThis: true, }) } infc := &InterfaceCreated{ Id: id, Index: index, PCIAddr: pciAddr, Bridge: inf.Bridge, HostDevice: inf.Device, DeviceName: deviceName, NewName: newName, MacAddr: inf.Mac, IpAddr: inf.IPAddress, Mtu: inf.Mtu, RouteTable: rt, } return infc, nil }
{ "content_hash": "1cafd8d7bddc0392cb2abb1487bbf4e2", "timestamp": "", "source": "github", "line_count": 439, "max_line_length": 133, "avg_line_length": 25.660592255125284, "alnum_prop": 0.6561917443408788, "repo_name": "gao-feng/hyper", "id": "bf07a936351e0d272962c19a7f846480dea3b593", "size": "11265", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vendor/github.com/hyperhq/runv/hypervisor/network.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "420622" }, { "name": "HTML", "bytes": "1172" }, { "name": "Makefile", "bytes": "2228" }, { "name": "Perl", "bytes": "8619" }, { "name": "Shell", "bytes": "29081" } ], "symlink_target": "" }
package Interface; import BuilderPattern.Reservation; import FactoryMethod.Customer; import FactoryMethod.CustomerFactory; import FactoryMethod.TravelAgencyMain; import Iterator.Collection; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.TimeUnit; public class RaportInterface extends javax.swing.JFrame { private static RaportInterface instance; static Collection collections; DateFormat sdf= new SimpleDateFormat("yyyy-MM-dd"); TravelAgencyMain travelAgencyMain= new TravelAgencyMain(); public RaportInterface() { initComponents(); } public static RaportInterface getInstance() { if (instance==null) { instance= new RaportInterface(); return instance; } else { return instance; } } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { txtIdCustomer = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); btnGenerateRaport = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); txtResultField = new javax.swing.JTextArea(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel2.setText("Insert Customer Id"); btnGenerateRaport.setText("Generate Raport"); btnGenerateRaport.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnGenerateRaportActionPerformed(evt); } }); txtResultField.setColumns(20); txtResultField.setRows(5); jScrollPane1.setViewportView(txtResultField); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel2) .addGap(18, 18, 18) .addComponent(txtIdCustomer, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnGenerateRaport) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(txtIdCustomer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnGenerateRaport)) .addGap(73, 73, 73) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)) ); pack(); }// </editor-fold> private void btnGenerateRaportActionPerformed(java.awt.event.ActionEvent evt) { try{ travelAgencyMain.setCollections(travelAgencyMain.populateCollections()); collections=travelAgencyMain.getCollections(); int idCustomer= Integer.parseInt(txtIdCustomer.getText()); int countRes=0; double totalSum=0; double twoYearsSum=0; Iterator customerIterator=travelAgencyMain.getCustomerIterator(collections); Iterator reservationIterator=travelAgencyMain.getReservationIterator(collections); while(reservationIterator.hasNext()) { Reservation res=(Reservation)reservationIterator.next(); if(res.getCustId()==idCustomer) { countRes++; totalSum+=res.getTotalSum(); double diffDays=(TimeUnit.MILLISECONDS.toDays(new Date().getTime())-TimeUnit.MILLISECONDS.toDays(res.getDepartDate().getTime())); if((int)diffDays/365 <=2) { twoYearsSum+=res.getTotalSum(); } } } txtResultField.setText("The customer has "+countRes+" reservations. \n " + "The customer has spent "+totalSum+" Euros with the agency. \n The customer has spent "+twoYearsSum+" Euros within the last two years. \n"); HashMap<String,Integer> frequencies= new HashMap(); frequencies=travelAgencyMain.getFrequencies(collections); Map.Entry mostPreferredDest=travelAgencyMain.getPreferredDestination(frequencies); txtResultField.append("The most preferred destination is"+mostPreferredDest.getKey().toString()+ " with number of reservations: "+mostPreferredDest.getValue().toString()+"\n"); HashMap<Integer,Double> frequencyClients=travelAgencyMain.getClientFrequencies(collections); Map.Entry bestClient=travelAgencyMain.getBestClient(frequencyClients); txtResultField.append("The best client of the agency is "+ travelAgencyMain.getCustomerbyId(Integer.parseInt(bestClient.getKey().toString())).getName()+" "+travelAgencyMain.getCustomerbyId(Integer.parseInt(bestClient.getKey().toString())).getSurname()+ " with money spent: "+ bestClient.getValue().toString()); } catch (Exception ex){ex.printStackTrace();} } public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(RaportInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(RaportInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(RaportInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(RaportInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new RaportInterface().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton btnGenerateRaport; private javax.swing.JLabel jLabel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextField txtIdCustomer; private javax.swing.JTextArea txtResultField; // End of variables declaration }
{ "content_hash": "f3114b737cef9539a4d260f8ebca451d", "timestamp": "", "source": "github", "line_count": 183, "max_line_length": 322, "avg_line_length": 43.69945355191257, "alnum_prop": 0.6252344629235963, "repo_name": "levisjani/java", "id": "d4363dbe1ba615f83308d05124cd047b0685a052", "size": "7997", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "travel-agency-platform/src/Interface/RaportInterface.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "186138" } ], "symlink_target": "" }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin Developers // Copyright (c) 2011-2012 Litecoin Developers // Copyright (c) 2013 NeoGulden Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // // Why base-58 instead of standard base-64 encoding? // - Don't want 0OIl characters that look the same in some fonts and // could be used to create visually identical looking account numbers. // - A string with non-alphanumeric characters is not as easily accepted as an account number. // - E-mail usually won't line-break if there's no punctuation to break at. // - Doubleclicking selects the whole number as one word if it's all alphanumeric. // #ifndef BITCOIN_BASE58_H #define BITCOIN_BASE58_H #include <string> #include <vector> #include "bignum.h" #include "key.h" #include "script.h" static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; // Encode a byte sequence as a base58-encoded string inline std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend) { CAutoBN_CTX pctx; CBigNum bn58 = 58; CBigNum bn0 = 0; // Convert big endian data to little endian // Extra zero at the end make sure bignum will interpret as a positive number std::vector<unsigned char> vchTmp(pend-pbegin+1, 0); reverse_copy(pbegin, pend, vchTmp.begin()); // Convert little endian data to bignum CBigNum bn; bn.setvch(vchTmp); // Convert bignum to std::string std::string str; // Expected size increase from base58 conversion is approximately 137% // use 138% to be safe str.reserve((pend - pbegin) * 138 / 100 + 1); CBigNum dv; CBigNum rem; while (bn > bn0) { if (!BN_div(&dv, &rem, &bn, &bn58, pctx)) throw bignum_error("EncodeBase58 : BN_div failed"); bn = dv; unsigned int c = rem.getulong(); str += pszBase58[c]; } // Leading zeroes encoded as base58 zeros for (const unsigned char* p = pbegin; p < pend && *p == 0; p++) str += pszBase58[0]; // Convert little endian std::string to big endian reverse(str.begin(), str.end()); return str; } // Encode a byte vector as a base58-encoded string inline std::string EncodeBase58(const std::vector<unsigned char>& vch) { return EncodeBase58(&vch[0], &vch[0] + vch.size()); } // Decode a base58-encoded string psz into byte vector vchRet // returns true if decoding is successful inline bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet) { CAutoBN_CTX pctx; vchRet.clear(); CBigNum bn58 = 58; CBigNum bn = 0; CBigNum bnChar; while (isspace(*psz)) psz++; // Convert big endian string to bignum for (const char* p = psz; *p; p++) { const char* p1 = strchr(pszBase58, *p); if (p1 == NULL) { while (isspace(*p)) p++; if (*p != '\0') return false; break; } bnChar.setulong(p1 - pszBase58); if (!BN_mul(&bn, &bn, &bn58, pctx)) throw bignum_error("DecodeBase58 : BN_mul failed"); bn += bnChar; } // Get bignum as little endian data std::vector<unsigned char> vchTmp = bn.getvch(); // Trim off sign byte if present if (vchTmp.size() >= 2 && vchTmp.end()[-1] == 0 && vchTmp.end()[-2] >= 0x80) vchTmp.erase(vchTmp.end()-1); // Restore leading zeros int nLeadingZeros = 0; for (const char* p = psz; *p == pszBase58[0]; p++) nLeadingZeros++; vchRet.assign(nLeadingZeros + vchTmp.size(), 0); // Convert little endian data to big endian reverse_copy(vchTmp.begin(), vchTmp.end(), vchRet.end() - vchTmp.size()); return true; } // Decode a base58-encoded string str into byte vector vchRet // returns true if decoding is successful inline bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet) { return DecodeBase58(str.c_str(), vchRet); } // Encode a byte vector to a base58-encoded string, including checksum inline std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn) { // add 4-byte hash check to the end std::vector<unsigned char> vch(vchIn); uint256 hash = Hash(vch.begin(), vch.end()); vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4); return EncodeBase58(vch); } // Decode a base58-encoded string psz that includes a checksum, into byte vector vchRet // returns true if decoding is successful inline bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet) { if (!DecodeBase58(psz, vchRet)) return false; if (vchRet.size() < 4) { vchRet.clear(); return false; } uint256 hash = Hash(vchRet.begin(), vchRet.end()-4); if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) { vchRet.clear(); return false; } vchRet.resize(vchRet.size()-4); return true; } // Decode a base58-encoded string str that includes a checksum, into byte vector vchRet // returns true if decoding is successful inline bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet) { return DecodeBase58Check(str.c_str(), vchRet); } /** Base class for all base58-encoded data */ class CBase58Data { protected: // the version byte unsigned char nVersion; // the actually encoded data std::vector<unsigned char> vchData; CBase58Data() { nVersion = 0; vchData.clear(); } ~CBase58Data() { // zero the memory, as it may contain sensitive data if (!vchData.empty()) memset(&vchData[0], 0, vchData.size()); } void SetData(int nVersionIn, const void* pdata, size_t nSize) { nVersion = nVersionIn; vchData.resize(nSize); if (!vchData.empty()) memcpy(&vchData[0], pdata, nSize); } void SetData(int nVersionIn, const unsigned char *pbegin, const unsigned char *pend) { SetData(nVersionIn, (void*)pbegin, pend - pbegin); } public: bool SetString(const char* psz) { std::vector<unsigned char> vchTemp; DecodeBase58Check(psz, vchTemp); if (vchTemp.empty()) { vchData.clear(); nVersion = 0; return false; } nVersion = vchTemp[0]; vchData.resize(vchTemp.size() - 1); if (!vchData.empty()) memcpy(&vchData[0], &vchTemp[1], vchData.size()); memset(&vchTemp[0], 0, vchTemp.size()); return true; } bool SetString(const std::string& str) { return SetString(str.c_str()); } std::string ToString() const { std::vector<unsigned char> vch(1, nVersion); vch.insert(vch.end(), vchData.begin(), vchData.end()); return EncodeBase58Check(vch); } int CompareTo(const CBase58Data& b58) const { if (nVersion < b58.nVersion) return -1; if (nVersion > b58.nVersion) return 1; if (vchData < b58.vchData) return -1; if (vchData > b58.vchData) return 1; return 0; } bool operator==(const CBase58Data& b58) const { return CompareTo(b58) == 0; } bool operator<=(const CBase58Data& b58) const { return CompareTo(b58) <= 0; } bool operator>=(const CBase58Data& b58) const { return CompareTo(b58) >= 0; } bool operator< (const CBase58Data& b58) const { return CompareTo(b58) < 0; } bool operator> (const CBase58Data& b58) const { return CompareTo(b58) > 0; } }; /** base58-encoded Bitcoin addresses. * Public-key-hash-addresses have version 0 (or 111 testnet). * The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key. * Script-hash-addresses have version 5 (or 196 testnet). * The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script. */ class CBitcoinAddress; class CBitcoinAddressVisitor : public boost::static_visitor<bool> { private: CBitcoinAddress *addr; public: CBitcoinAddressVisitor(CBitcoinAddress *addrIn) : addr(addrIn) { } bool operator()(const CKeyID &id) const; bool operator()(const CScriptID &id) const; bool operator()(const CNoDestination &no) const; }; class CBitcoinAddress : public CBase58Data { public: enum { PUBKEY_ADDRESS = 93, // NeoGulden addresses start with e SCRIPT_ADDRESS = 5, PUBKEY_ADDRESS_TEST = 111, SCRIPT_ADDRESS_TEST = 196, }; bool Set(const CKeyID &id) { SetData(fTestNet ? PUBKEY_ADDRESS_TEST : PUBKEY_ADDRESS, &id, 20); return true; } bool Set(const CScriptID &id) { SetData(fTestNet ? SCRIPT_ADDRESS_TEST : SCRIPT_ADDRESS, &id, 20); return true; } bool Set(const CTxDestination &dest) { return boost::apply_visitor(CBitcoinAddressVisitor(this), dest); } bool IsValid() const { unsigned int nExpectedSize = 20; bool fExpectTestNet = false; switch(nVersion) { case PUBKEY_ADDRESS: nExpectedSize = 20; // Hash of public key fExpectTestNet = false; break; case SCRIPT_ADDRESS: nExpectedSize = 20; // Hash of CScript fExpectTestNet = false; break; case PUBKEY_ADDRESS_TEST: nExpectedSize = 20; fExpectTestNet = true; break; case SCRIPT_ADDRESS_TEST: nExpectedSize = 20; fExpectTestNet = true; break; default: return false; } return fExpectTestNet == fTestNet && vchData.size() == nExpectedSize; } CBitcoinAddress() { } CBitcoinAddress(const CTxDestination &dest) { Set(dest); } CBitcoinAddress(const std::string& strAddress) { SetString(strAddress); } CBitcoinAddress(const char* pszAddress) { SetString(pszAddress); } CTxDestination Get() const { if (!IsValid()) return CNoDestination(); switch (nVersion) { case PUBKEY_ADDRESS: case PUBKEY_ADDRESS_TEST: { uint160 id; memcpy(&id, &vchData[0], 20); return CKeyID(id); } case SCRIPT_ADDRESS: case SCRIPT_ADDRESS_TEST: { uint160 id; memcpy(&id, &vchData[0], 20); return CScriptID(id); } } return CNoDestination(); } bool GetKeyID(CKeyID &keyID) const { if (!IsValid()) return false; switch (nVersion) { case PUBKEY_ADDRESS: case PUBKEY_ADDRESS_TEST: { uint160 id; memcpy(&id, &vchData[0], 20); keyID = CKeyID(id); return true; } default: return false; } } bool IsScript() const { if (!IsValid()) return false; switch (nVersion) { case SCRIPT_ADDRESS: case SCRIPT_ADDRESS_TEST: { return true; } default: return false; } } }; bool inline CBitcoinAddressVisitor::operator()(const CKeyID &id) const { return addr->Set(id); } bool inline CBitcoinAddressVisitor::operator()(const CScriptID &id) const { return addr->Set(id); } bool inline CBitcoinAddressVisitor::operator()(const CNoDestination &id) const { return false; } /** A base58-encoded secret key */ class CBitcoinSecret : public CBase58Data { public: enum { PRIVKEY_ADDRESS = CBitcoinAddress::PUBKEY_ADDRESS + 128, PRIVKEY_ADDRESS_TEST = CBitcoinAddress::PUBKEY_ADDRESS_TEST + 128, }; void SetSecret(const CSecret& vchSecret, bool fCompressed) { assert(vchSecret.size() == 32); SetData(fTestNet ? PRIVKEY_ADDRESS_TEST : PRIVKEY_ADDRESS, &vchSecret[0], vchSecret.size()); if (fCompressed) vchData.push_back(1); } CSecret GetSecret(bool &fCompressedOut) { CSecret vchSecret; vchSecret.resize(32); memcpy(&vchSecret[0], &vchData[0], 32); fCompressedOut = vchData.size() == 33; return vchSecret; } bool IsValid() const { bool fExpectTestNet = false; switch(nVersion) { case PRIVKEY_ADDRESS: break; case PRIVKEY_ADDRESS_TEST: fExpectTestNet = true; break; default: return false; } return fExpectTestNet == fTestNet && (vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1)); } bool SetString(const char* pszSecret) { return CBase58Data::SetString(pszSecret) && IsValid(); } bool SetString(const std::string& strSecret) { return SetString(strSecret.c_str()); } CBitcoinSecret(const CSecret& vchSecret, bool fCompressed) { SetSecret(vchSecret, fCompressed); } CBitcoinSecret() { } }; #endif
{ "content_hash": "398357c67481c8caaa9792ca0666c2cf", "timestamp": "", "source": "github", "line_count": 468, "max_line_length": 114, "avg_line_length": 28.363247863247864, "alnum_prop": 0.6030586108181407, "repo_name": "neogulden/neogulden", "id": "e49bacdba5d6ed92fc43df2a80f06488c47e461b", "size": "13274", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/base58.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "14758" }, { "name": "C++", "bytes": "1440185" }, { "name": "Makefile", "bytes": "4571" }, { "name": "Objective-C++", "bytes": "2463" }, { "name": "Python", "bytes": "47538" }, { "name": "Shell", "bytes": "1402" } ], "symlink_target": "" }
#ifndef QOEMBED_PHOTO_H #define QOEMBED_PHOTO_H #include "qoembed_global.h" #include "response.h" namespace qoembed { class PhotoPrivate; class QOEMBEDSHARED_EXPORT Photo : public Response { public: Photo(); Photo(const Photo &other); ~Photo(); Photo &operator=(const Photo &rhs); virtual QString render() const; void setUrl(const QString &url); QString url() const; void setWidth(unsigned width); unsigned width() const; void setHeight(unsigned height); unsigned height() const; private: PhotoPrivate *d; }; } // namespace qoembed #endif // QOEMBED_PHOTO_H
{ "content_hash": "7eebd57a727a5ce4bb3185a9b75bc53b", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 50, "avg_line_length": 16.289473684210527, "alnum_prop": 0.6801292407108239, "repo_name": "cloose/qoembed", "id": "38c7e6c97aa8f3c7f05e2c5046e5d51fd1525b21", "size": "1988", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/photo.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "240" }, { "name": "C++", "bytes": "76219" } ], "symlink_target": "" }
This module includes some scikit-learn style transformers that perform basis expansions on a feature `x` for use in regression. A basis expansions for the feature `x` is a collection of functions f_0, f_1, f_2, ... that are meant to be applied to the feature to construct derived features in a regression model. The functions in the expansions are often chosen to allow the model to adapt to non-linear shapes in the predictor/response relationship. When a basis expansion is *applied* to the feature `x`, the result is a new matrix or data frame of derived features f_0(x), f_1(x), f_2(x), ... ## Installation You can install this library directly from github: ```bash pip install git+https://github.com/madrury/basis-expansions.git ``` If you would prefer to install from source, first clone this repository: ```bash git clone https://github.com/madrury/basis-expansions.git ``` And then navigate into the cloned directory, and run `pip install` ```bash cd basis_expansions pip install . ``` ## Supported Expansions The following classes are included: - `Binner`: Creates indicator variables by segmenting the range of `x` into disjoint intervals. - `GaussianKernel`: Create Gaussian Kernel features, also known as "radial basis functions" by people cooler than me. - `Polynomial`: Creates polynomial features. Using these features in a regression fits a polynomial function of a given degree `x` to `y`. - `LinearSpline`: Creates a piecewise linear spline which joins continuously at the knots. Using this in a regression fits a piecewise linear function of `x` to `y`. - `CubicSpline`: Creates a piecewise cubic spline which joins continuously, differentiably, and second differentiably at a set of supplied knots. - `NaturalCubicSpline`: Creates a piecewise natural cubic spline (cubic curves in the interior segments, linear in the exterior segments) which joins continuously, differentiably, and second differentiably at a set of supplied knots. ![Basis Expansions](examples/img/basis-expansions.png) ## Examples The most basic use case is to transform a `numpy.array`: ```python x = np.random.uniform(0, 1, size=10) pl = LinearSpline(knots=[0.25, 0.75]) pl.fit_transform(x) ``` which results in a two dimensional `array`: ```python array([[ 0.21776114, 0. , 0. ], [ 0.63360478, 0.38360478, 0. ], [ 0.29089787, 0.04089787, 0. ], [ 0.83284663, 0.58284663, 0.08284663], [ 0.89158883, 0.64158883, 0.14158883], [ 0.97076139, 0.72076139, 0.22076139], [ 0.83373019, 0.58373019, 0.08373019], [ 0.39301854, 0.14301854, 0. ], [ 0.27773455, 0.02773455, 0. ], [ 0.68772864, 0.43772864, 0. ]]) ``` If we transform a `pandas.Series`: ```python s = pd.Series(x, name="moshi") pl = LinearSpline(knots=[0.25, 0.75]) pl.fit_transform(s) ``` the result is a `pandas.DataFrame`: ```python moshi_spline_linear moshi_spline_0 moshi_spline_1 0 0.217761 0.000000 0.000000 1 0.633605 0.383605 0.000000 2 0.290898 0.040898 0.000000 3 0.832847 0.582847 0.082847 4 0.891589 0.641589 0.141589 5 0.970761 0.720761 0.220761 6 0.833730 0.583730 0.083730 7 0.393019 0.143019 0.000000 8 0.277735 0.027735 0.000000 9 0.687729 0.437729 0.000000 ``` More advanced use can combine these transformers with `sklearn.pipeline` objects. For helper classes that allow for transformations on `pandas.DataFrames`, see `examples/dftransformers.py`. ## Examples See the `basis-expansions-regressions.ipynb` notebook for examples of use.
{ "content_hash": "d79de557014fafe4028fe1b682cb5e8e", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 235, "avg_line_length": 37.33980582524272, "alnum_prop": 0.6653666146645866, "repo_name": "madrury/basis-expansions", "id": "f6078197186862c93b67a6bca220acf866ab30d5", "size": "3866", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "14079" } ], "symlink_target": "" }
<?php return create_function('$params', 'return include "lambda.php";');
{ "content_hash": "ade3fddb2fe1d2698da374f340280cb0", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 66, "avg_line_length": 24.666666666666668, "alnum_prop": 0.6891891891891891, "repo_name": "lokothodida/php-lambda-5.2", "id": "cd9038721957d4f720bf9b83b10b4e56376bdf49", "size": "74", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/lambda-local.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "913" } ], "symlink_target": "" }
from __future__ import absolute_import from os.path import dirname from tml.api.mock import File FIXTURES_PATH = '%s/fixtures' % dirname(dirname(__file__)) URLS = [('projects/current/definition', None), ('projects/current/definition', {'locale': 'en'}), ('projects/2/definition', None), ('languages/ru/definition', ), ('languages/en/definition', ), ('projects/1/translations', {'locale':'ru','page':1}), ('projects/1768/definition', {'locale':'ru,en', 'source': '/home/index'}), ('sources/register_keys', None), ('translation_keys/8ad5a7fe0a12729764e31a1e3ca80059/translations', {'locale':'ru','page':1}), ('translation_keys/bdc08159a02e7ff01ca188c03fa1323e/translations', {'locale':'ru','page':1}), ('sources/6a992d5529f459a44fee58c733255e86/translations', {'locale':'ru'}),] class Client(File): def __init__(self, data = {}): super(Client, self).__init__(FIXTURES_PATH, data, False) @classmethod def read_all(cls): return cls().readdir('') class DummyUser(object): def __init__(self, name, gender=None): self.name = name self.gender = gender or 'male'
{ "content_hash": "9ed2235d51ed6cfad229a3e710e64809", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 101, "avg_line_length": 38.32258064516129, "alnum_prop": 0.6254208754208754, "repo_name": "translationexchange/tml-python", "id": "5e2201024a9509c456695d668d6b21b6867225e6", "size": "1207", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/mock/__init__.py", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "1262" }, { "name": "Python", "bytes": "446575" }, { "name": "Shell", "bytes": "294" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html><head><title></title> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta name="generator" content="Doxygen 1.8.6"> <link rel="stylesheet" type="text/css" href="search.css"/> <script type="text/javascript" src="all_a.js"></script> <script type="text/javascript" src="search.js"></script> </head> <body class="SRPage"> <div id="SRIndex"> <div class="SRStatus" id="Loading">Chargement...</div> <div id="SRResults"></div> <script type="text/javascript"><!-- createResults(); --></script> <div class="SRStatus" id="Searching">Recherche...</div> <div class="SRStatus" id="NoMatches">Aucune correspondance</div> <script type="text/javascript"><!-- document.getElementById("Loading").style.display="none"; document.getElementById("NoMatches").style.display="none"; var searchResults = new SearchResults("searchResults"); searchResults.Search(); --></script> </div> </body> </html>
{ "content_hash": "d647bf8ed66283fa89edf17de3910ab5", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 121, "avg_line_length": 39.42307692307692, "alnum_prop": 0.7092682926829268, "repo_name": "kirapoetica974/M1ALMA-semestre2-SolfHelp", "id": "ba4065defb941d535185a9846c94873695193524", "size": "1025", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "html/search/all_a.html", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "81291" }, { "name": "CSS", "bytes": "59118" }, { "name": "HTML", "bytes": "973239" }, { "name": "JavaScript", "bytes": "85176" }, { "name": "PostScript", "bytes": "52880" }, { "name": "QMake", "bytes": "1217" }, { "name": "TeX", "bytes": "157428" } ], "symlink_target": "" }
title: Dialog desc: The QDialog component provides a UI for modals with functionalities like positioning, styling, maximizing and more. keys: QDialog related: - /quasar-plugins/dialog - /vue-directives/close-popup - /vue-components/card - /vue-components/popup-proxy --- The QDialog component is a great way to offer the user the ability to choose a specific action or list of actions. They also can provide the user with important information, or require them to make a decision (or multiple decisions). From a UI perspective, you can think of Dialogs as a type of floating modal, which covers only a portion of the screen. This means Dialogs should only be used for quick user actions, like verifying a password, getting a short App notification or selecting an option or options quickly. ::: tip Dialogs can also be used as a globally available method for more basic use cases, like the native JS alert(), prompt(), etc. For the latter behaviour, go to [Dialog Plugin](/quasar-plugins/dialog) page. ::: ::: warning Masterclass TIP Rather than cluttering your .vue templates with QDialogs, it's best if you write a component for your dialog and use the [Dialog Plugin](/quasar-plugins/dialog#invoking-custom-component) to invoke it from anywhere in your app. ::: ## QDialog API <doc-api file="QDialog" /> ## Usage ::: warning Note It's best that your QDialog main content is a QCard. However, if you are planning on using any other component (like QForm) or tag, make sure that the direct child of QDialog is rendered with a `<div>` tag (or wrap it with one yourself). ::: ### Basic <doc-example title="Basic" file="QDialog/Basic" /> ### Styling <doc-example title="Styling" file="QDialog/Style" /> ### Positioning <doc-example title="Positions" file="QDialog/Positioning" /> ::: tip Do not mistake "position" prop with the show/hide animation. If you want a custom animation, you should use `transition-show` and `transition-hide` which can be applied regardless of "position" or "maximized". ::: <doc-example title="Maximized" file="QDialog/Maximized" /> ### Various content Dialogs can contain any content. Some examples: <doc-example title="Various content" file="QDialog/VariousContent" /> <doc-example title="With containerized QLayout" file="QDialog/Layout" /> ::: tip If you are going to use the containerized QLayout, you'll need to put a width on your QDialog, if using left/right position, or a height, if using top/bottom position. You can use vw and vh units. ::: ### Handling scroll <doc-example title="Scrollable dialogs" file="QDialog/Scrollable" /> ### Different modes User cannot dismiss the Dialog by pressing ESCAPE key or by clicking/tapping on its backdrop. <doc-example title="Persistent" file="QDialog/Persistent" /> Dialogs can also be a part of the page, without requiring immediate focus. It's where "seamless" mode comes into play: <doc-example title="Seamless" file="QDialog/Seamless" /> ### Dialog in dialog You are able to open dialogs on top of other dialogs, with infinite number of depth levels. <doc-example title="Inception" file="QDialog/Inception" /> ### Sizing You are able to customize the size of the Dialogs. Notice we either tamper with the content's style or we use `full-width` or `full-height` props: <doc-example title="Sizing examples" file="QDialog/Sizing" /> ## Cordova/Capacitor back button Quasar handles the back button for you by default so it can hide any opened Dialogs instead of the default behavior which is to return to the previous page (which is not a nice user experience). However, should you wish to disable this behavior, edit your /quasar.config.js file: ```js // quasar.config.js; // for Cordova (only!): return { framework: { config: { cordova: { // Quasar handles app exit on mobile phone back button. backButtonExit: true/false/'*'/['/login', '/home', '/my-page'], // On the other hand, the following completely // disables Quasar's back button management. backButton: true/false } } } } // quasar.config.js; // for Capacitor (only!) return { framework: { config: { capacitor: { // Quasar handles app exit on mobile phone back button. backButtonExit: true/false/'*'/['/login', '/home', '/my-page'], // On the other hand, the following completely // disables Quasar's back button management. backButton: true/false } } } } ```
{ "content_hash": "abcb3b04c55e43c8cf36915785d2be33", "timestamp": "", "source": "github", "line_count": 122, "max_line_length": 285, "avg_line_length": 36.631147540983605, "alnum_prop": 0.7229805325576192, "repo_name": "rstoenescu/quasar-framework", "id": "8e338c8a35ef02f8acf498921185e0bd78acd26f", "size": "4473", "binary": false, "copies": "2", "ref": "refs/heads/dev", "path": "docs/src/pages/vue-components/dialog.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "182588" }, { "name": "HTML", "bytes": "954" }, { "name": "JavaScript", "bytes": "166413" }, { "name": "Shell", "bytes": "1024" }, { "name": "Vue", "bytes": "369926" } ], "symlink_target": "" }
module Authlogic # This allows you to scope your authentication. For example, let's say all users belong to an account, you want to make sure only users # that belong to that account can actually login into that account. Simple, just do: # # class Account < ActiveRecord::Base # authenticates_many :user_sessions # end # # Now you can scope sessions just like everything else in ActiveRecord: # # @account.user_sessions.new(*args) # @account.user_sessions.create(*args) # @account.user_sessions.find(*args) # # ... etc # # Checkout the authenticates_many method for a list of options. # You may also want to checkout Authlogic::ActsAsAuthentic::Scope to scope your model. module AuthenticatesMany module Base # Allows you set essentially set up a relationship with your sessions. See module definition above for more details. # # === Options # # * <tt>session_class:</tt> default: "#{name}Session", # This is the related session class. # # * <tt>relationship_name:</tt> default: options[:session_class].klass_name.underscore.pluralize, # This is the name of the relationship you want to use to scope everything. For example an Account has many Users. There should be a relationship # called :users that you defined with a has_many. The reason we use the relationship is so you don't have to repeat yourself. The relatonship # could have all kinds of custom options. So instead of repeating yourself we essentially use the scope that the relationship creates. # # * <tt>find_options:</tt> default: nil, # By default the find options are created from the relationship you specify with :relationship_name. But if you want to override this and # manually specify find_options you can do it here. Specify options just as you would in ActiveRecord::Base.find. # # * <tt>scope_cookies:</tt> default: false # By the nature of cookies they scope theirself if you are using subdomains to access accounts. If you aren't using subdomains you need to have # separate cookies for each account, assuming a user is logging into mroe than one account. Authlogic can take care of this for you by # prefixing the name of the cookie and sessin with the model id. You just need to tell Authlogic to do this by passing this option. def authenticates_many(name, options = {}) options[:session_class] ||= name.to_s.classify.constantize options[:relationship_name] ||= options[:session_class].klass_name.underscore.pluralize class_eval <<-"end_eval", __FILE__, __LINE__ def #{name} find_options = #{options[:find_options].inspect} || #{options[:relationship_name]}.scoped @#{name} ||= Authlogic::AuthenticatesMany::Association.new(#{options[:session_class]}, find_options, #{options[:scope_cookies] ? "self.class.model_name.underscore + '_' + self.send(self.class.primary_key).to_s" : "nil"}) end end_eval end end ::ActiveRecord::Base.extend(Base) if defined?(::ActiveRecord) end end
{ "content_hash": "e9cda89ccb5489b775ed4a595fc0d2e1", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 232, "avg_line_length": 58.31481481481482, "alnum_prop": 0.6865671641791045, "repo_name": "bioritmo/authlogic", "id": "4ac019b3c0c9deed2b086e2d80f4cf1e9b7d8b97", "size": "3149", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/authlogic/authenticates_many/base.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "263408" } ], "symlink_target": "" }
<textarea <?php echo $view['form']->block($form, 'attributes') ?>><?php echo htmlspecialchars($value) ?></textarea> <?php if ($enable) : ?> <?php if ($autoload) : ?> <script type="text/javascript"> var CKEDITOR_BASEPATH = "<?php echo $view['ivory_ckeditor']->renderBasePath($base_path); ?>"; </script> <script type="text/javascript" src="<?php echo $view['ivory_ckeditor']->renderJsPath($js_path); ?>"></script> <?php if ($jquery) : ?> <script type="text/javascript" src="<?php echo $view['ivory_ckeditor']->renderJsPath($jquery_path); ?>"></script> <?php endif; ?> <?php endif; ?> <script type="text/javascript"> <?php if ($jquery) : ?> $(function () { <?php endif; ?> <?php echo $view['ivory_ckeditor']->renderDestroy($id); ?> <?php foreach ($plugins as $pluginName => $plugin): ?> <?php echo $view['ivory_ckeditor']->renderPlugin($pluginName, $plugin); ?> <?php endforeach; ?> <?php foreach ($styles as $styleName => $style): ?> <?php echo $view['ivory_ckeditor']->renderStylesSet($styleName, $style); ?> <?php endforeach; ?> <?php foreach ($templates as $templateName => $template): ?> <?php echo $view['ivory_ckeditor']->renderTemplate($templateName, $template); ?> <?php endforeach; ?> <?php echo $view['ivory_ckeditor']->renderWidget($id, $config, $inline, $input_sync); ?> <?php if ($jquery) : ?> }); <?php endif; ?> </script> <?php endif; ?>
{ "content_hash": "d91af648838fc3f8766ee12c8422bec0", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 125, "avg_line_length": 41.94736842105263, "alnum_prop": 0.5457967377666249, "repo_name": "markusmichel/IvoryCKEditorBundle", "id": "b9f9987a07e03d3f89871671d4050cc30f37f5b5", "size": "1594", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "Resources/views/Form/ckeditor_widget.html.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5702" }, { "name": "HTML", "bytes": "5071" }, { "name": "JavaScript", "bytes": "7238" }, { "name": "PHP", "bytes": "150901" }, { "name": "Shell", "bytes": "468" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <sponge xmlns="https://sponge.openksavi.org" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://sponge.openksavi.org https://sponge.openksavi.org/schema/config.xsd"> <properties> <property name="sponge.home">.</property> <property name="groovy.classpath">${sponge.home}/examples/script/groovy/knowledge_base_script_overriding</property> </properties> <knowledgeBases> <knowledgeBase name="kb"> <file>${sponge.home}/examples/script/groovy/knowledge_base_script_overriding.groovy</file> </knowledgeBase> </knowledgeBases> </sponge>
{ "content_hash": "5d0e5d2d716b181605641f53b1933c50", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 123, "avg_line_length": 41.6875, "alnum_prop": 0.6896551724137931, "repo_name": "softelnet/sponge", "id": "058b1a10d3eed02033a75b934304a1134877ec5d", "size": "667", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sponge-groovy/examples/script/groovy/knowledge_base_script_overriding.xml", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "482" }, { "name": "Dockerfile", "bytes": "2389" }, { "name": "Groovy", "bytes": "70914" }, { "name": "HTML", "bytes": "6759" }, { "name": "Java", "bytes": "3300560" }, { "name": "JavaScript", "bytes": "70716" }, { "name": "Kotlin", "bytes": "113542" }, { "name": "Mustache", "bytes": "38" }, { "name": "Python", "bytes": "426240" }, { "name": "Ruby", "bytes": "65491" }, { "name": "SCSS", "bytes": "6217" }, { "name": "Shell", "bytes": "1388" } ], "symlink_target": "" }
'use strict'; // Configuring the Articles module angular.module('graphtypes').run(['Menus', function(Menus) { // Set top bar menu items Menus.addMenuItem('topbar', 'Graphtypes', 'graphtypes', 'dropdown', '/graphtypes(/create)?', false, ['admin']); Menus.addSubMenuItem('topbar', 'graphtypes', 'List Graphtypes', 'graphtypes'); Menus.addSubMenuItem('topbar', 'graphtypes', 'New Graphtype', 'graphtypes/create'); } ]);
{ "content_hash": "01efbb53fcc7218a370ddde1b6d612b1", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 113, "avg_line_length": 38.81818181818182, "alnum_prop": 0.6955503512880562, "repo_name": "amirsaber/DeepDepth", "id": "a326a98e97e4243e8d47b235cb6d71682adc203e", "size": "427", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/modules/graphtypes/config/graphtypes.client.config.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8131" }, { "name": "JavaScript", "bytes": "196067" }, { "name": "Perl", "bytes": "48" }, { "name": "Shell", "bytes": "669" }, { "name": "TeX", "bytes": "115785" } ], "symlink_target": "" }
export default class ImportStatement { constructor({id, moduleName, members}){ this.moduleName = moduleName; this.members = members; this.id = id; } }
{ "content_hash": "37070579403b12788559e8975adbb703", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 41, "avg_line_length": 23.714285714285715, "alnum_prop": 0.6807228915662651, "repo_name": "RikardLegge/modulin", "id": "3c07c2edabd5a4d21b8eab0192fd8c25b32530e4", "size": "166", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/modulin/ImportStatement.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "329" }, { "name": "HTML", "bytes": "2009" }, { "name": "JavaScript", "bytes": "41219" } ], "symlink_target": "" }
package flex.messaging.io.amf.translator.decoder; /** * Decode a java.lang.String or java.lang.Character to * a java.lang.Character instance. * <p> * Note that a String must be non-zero length and only the first * character in the String will be used. * </p> * * */ public class CharacterDecoder extends ActionScriptDecoder { public Object decodeObject(Object shell, Object encodedObject, Class desiredClass) { Character result = null; if (encodedObject == null) { char c = 0; result = new Character(c); } else if (encodedObject instanceof String) { String str = (String)encodedObject; char[] chars = str.toCharArray(); if (chars.length > 0) { result = new Character(chars[0]); } } else if (encodedObject instanceof Character) { result = (Character)encodedObject; } if (result == null) { DecoderFactory.invalidType(encodedObject, desiredClass); } return result; } }
{ "content_hash": "4c7359f970758885dedbd1517f98f877", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 86, "avg_line_length": 23.541666666666668, "alnum_prop": 0.5681415929203539, "repo_name": "apache/flex-blazeds", "id": "b58c37f6a5016f3e1691d77c44a4f08b80c3216c", "size": "1931", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "core/src/main/java/flex/messaging/io/amf/translator/decoder/CharacterDecoder.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "3671263" } ], "symlink_target": "" }
package org.apache.ignite.loadtests.hashmap; import org.apache.ignite.cache.store.*; import org.apache.ignite.configuration.*; import org.apache.ignite.internal.processors.cache.*; import org.apache.ignite.internal.processors.cache.datastructures.*; import org.apache.ignite.internal.processors.cache.dr.*; import org.apache.ignite.internal.processors.cache.jta.*; import org.apache.ignite.internal.processors.cache.query.*; import org.apache.ignite.internal.processors.cache.query.continuous.*; import org.apache.ignite.internal.processors.cache.store.*; import org.apache.ignite.internal.processors.cache.transactions.*; import org.apache.ignite.internal.processors.cache.version.*; import org.apache.ignite.internal.processors.plugin.*; import org.apache.ignite.testframework.junits.*; import java.util.*; import static org.apache.ignite.testframework.junits.GridAbstractTest.*; /** * Cache test context. */ public class GridCacheTestContext<K, V> extends GridCacheContext<K, V> { /** * @param ctx Context. * @throws Exception If failed. */ @SuppressWarnings("NullableProblems") public GridCacheTestContext(GridTestKernalContext ctx) throws Exception { super( ctx, new GridCacheSharedContext<>( ctx, new IgniteTxManager(), new GridCacheVersionManager(), new GridCacheMvccManager(), new GridCacheDeploymentManager<K, V>(), new GridCachePartitionExchangeManager<K, V>(), new GridCacheIoManager(), new CacheNoopJtaManager(), null ), defaultCacheConfiguration(), CacheType.USER, true, true, new GridCacheEventManager(), new GridCacheSwapManager(false), new CacheOsStoreManager(null, new CacheConfiguration()), new GridCacheEvictionManager(), new GridCacheLocalQueryManager<K, V>(), new CacheContinuousQueryManager(), new GridCacheAffinityManager(), new CacheDataStructuresManager(), new GridCacheTtlManager(), new GridOsCacheDrManager(), new CacheOsConflictResolutionManager<K, V>(), new CachePluginManager(ctx, new CacheConfiguration()) ); store().initialize(null, new IdentityHashMap<CacheStore, ThreadLocal>()); } }
{ "content_hash": "8a8df4e8e2aeab1d431e70a910680d49", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 81, "avg_line_length": 37.18181818181818, "alnum_prop": 0.6621841890790546, "repo_name": "kidaa/incubator-ignite", "id": "9a883b301b5989ca80ec3c6c4f34eedaa59858a5", "size": "3256", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "modules/core/src/test/java/org/apache/ignite/loadtests/hashmap/GridCacheTestContext.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "34170" }, { "name": "C++", "bytes": "28098" }, { "name": "CSS", "bytes": "17517" }, { "name": "Groovy", "bytes": "15102" }, { "name": "HTML", "bytes": "4669" }, { "name": "Java", "bytes": "18797422" }, { "name": "JavaScript", "bytes": "1085" }, { "name": "PHP", "bytes": "18527" }, { "name": "Scala", "bytes": "728041" }, { "name": "Shell", "bytes": "398112" } ], "symlink_target": "" }
<?php /** * @file * Contains \Drupal\forum\Tests\Migrate\d7\MigrateForumSettingsTest. */ namespace Drupal\forum\Tests\Migrate\d7; use Drupal\migrate_drupal\Tests\d7\MigrateDrupal7TestBase; /** * Tests migration of Forum's variables to configuration. * * @group forum */ class MigrateForumSettingsTest extends MigrateDrupal7TestBase { // Don't alphabetize these. They're in dependency order. public static $modules = [ 'comment', 'field', 'filter', 'text', 'node', 'taxonomy', 'forum', ]; /** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->executeMigration('d7_taxonomy_vocabulary'); $this->executeMigration('d7_forum_settings'); } /** * Tests the migration of Forum's settings to configuration. */ public function testForumSettingsMigration() { $config = $this->config('forum.settings'); $this->assertIdentical(9, $config->get('block.active.limit')); $this->assertIdentical(4, $config->get('block.new.limit')); $this->assertIdentical(10, $config->get('topics.hot_threshold')); $this->assertIdentical(25, $config->get('topics.page_limit')); $this->assertIdentical(1, $config->get('topics.order')); $this->assertIdentical('forums', $config->get('vocabulary')); } }
{ "content_hash": "0b5aca22ce8c3f3049a0c2b7825c665e", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 69, "avg_line_length": 25.01923076923077, "alnum_prop": 0.6633358954650269, "repo_name": "edwardchan/d8-drupalvm", "id": "f702b9a9e7ed77b8ea40d31c90361d51c43d9125", "size": "1301", "binary": false, "copies": "144", "ref": "refs/heads/master", "path": "drupal/core/modules/forum/src/Tests/Migrate/d7/MigrateForumSettingsTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "50616" }, { "name": "CSS", "bytes": "1250515" }, { "name": "HTML", "bytes": "646836" }, { "name": "JavaScript", "bytes": "1018469" }, { "name": "PHP", "bytes": "31387248" }, { "name": "Shell", "bytes": "675" }, { "name": "SourcePawn", "bytes": "31943" } ], "symlink_target": "" }
package com.onboard.domain.model.type; import java.util.List; import com.onboard.domain.model.Attachment; /** * 可添加附件的对象 * * @author yewei * */ public interface Attachable extends BaseProjectItem { List<Attachment> getAttachments(); void setAttachments(List<Attachment> attachments); List<Attachment> getDiscardAttachments(); void setDiscardAttachments(List<Attachment> attachments); }
{ "content_hash": "dcc5c1ee5b98242360d5c177a23da307", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 61, "avg_line_length": 18.130434782608695, "alnum_prop": 0.7410071942446043, "repo_name": "ruixie/onboard", "id": "5f2fd507aa153ba7ad9ff30ae1667dfbc5dd139b", "size": "1215", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "kernel/com.onboard.domain.model/src/main/java/com/onboard/domain/model/type/Attachable.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "837787" }, { "name": "HTML", "bytes": "752542" }, { "name": "Java", "bytes": "3853483" }, { "name": "JavaScript", "bytes": "2115360" }, { "name": "Shell", "bytes": "1838" } ], "symlink_target": "" }
import os import time from tornado.testing import ExpectLog, AsyncTestCase, gen_test from remoteappmanager.tests.temp_mixin import TempMixin from remoteappmanager.tests.utils import mock_coro_factory from unittest.mock import Mock, patch from remoteappmanager.jupyterhub.auth import GitHubWhitelistAuthenticator class TestGithubWhiteListAuthenticator(TempMixin, AsyncTestCase): def setUp(self): self.auth = GitHubWhitelistAuthenticator() self.auth.authenticate = mock_coro_factory(return_value="foo") super().setUp() @gen_test def test_basic_auth(self): auth = self.auth response = yield auth.authenticate(Mock(), {"username": "foo"}) self.assertEqual(response, "foo") @gen_test def test_basic_auth_with_whitelist_file(self): whitelist_path = os.path.join(self.tempdir, "whitelist.txt") with open(whitelist_path, "w") as f: f.write("foo\n") f.write("bar\n") auth = self.auth auth.whitelist_file = whitelist_path response = yield auth.get_authenticated_user( Mock(), {"username": "foo"}) self.assertEqual(response['name'], "foo") # Check again to touch the code that does not trigger another load response = yield auth.get_authenticated_user( Mock(), {"username": "foo"}) self.assertEqual(response["name"], "foo") # wait one second, so that we see a change in mtime. time.sleep(1) # Change the file and see if we get a different behavior with open(whitelist_path, "w") as f: f.write("bar\n") with ExpectLog('traitlets', "User 'foo' not in whitelist."): response = yield auth.get_authenticated_user( Mock(), {"username": "foo"}) self.assertEqual(response, None) @gen_test def test_basic_auth_without_whitelist_file(self): auth = self.auth auth.whitelist_file = "/does/not/exist.txt" response = yield auth.get_authenticated_user(Mock(), {"username": "foo"}) # Should be equivalent to no whitelist, so everybody allowed self.assertEqual(response['name'], "foo") @gen_test def test_exception_during_read(self): whitelist_path = os.path.join(self.tempdir, "whitelist.txt") with open(whitelist_path, "w") as f: f.write("bar\n") auth = self.auth auth.whitelist_file = whitelist_path # Do the first triggering, so that we load the file content. with ExpectLog('traitlets', "User 'foo' not in whitelist."): response = yield auth.get_authenticated_user( Mock(), {"username": "foo"}) self.assertEqual(response, None) # Then try again with an exception occurring with patch("os.path.getmtime") as p: p.side_effect = Exception("BOOM!") with ExpectLog('traitlets', ""): response = yield auth.get_authenticated_user( Mock(), {"username": "foo"}) self.assertEqual(response, None) def test_dummy_setter(self): whitelist_path = os.path.join(self.tempdir, "whitelist.txt") with open(whitelist_path, "w") as f: f.write("bar\n") auth = self.auth auth.whitelist_file = whitelist_path auth.whitelist = set() self.assertNotEqual(auth.whitelist, set()) @gen_test def test_comment_out(self): whitelist_path = os.path.join(self.tempdir, "whitelist.txt") with open(whitelist_path, "w") as f: f.write("# this is a comment\n") f.write("foo\n") f.write("bar\n") auth = self.auth auth.whitelist_file = whitelist_path yield auth.get_authenticated_user(Mock(), {"username": "foo"}) self.assertEqual(len(auth.whitelist), 2)
{ "content_hash": "937e271dbec370c577267e5ff850d4bc", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 74, "avg_line_length": 34.310344827586206, "alnum_prop": 0.5974874371859297, "repo_name": "simphony/simphony-remote", "id": "b933661ed2019d51caf8f68ee6c63f67cd01dd32", "size": "3980", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "remoteappmanager/jupyterhub/auth/tests/test_github_whitelist_authenticator.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "14011" }, { "name": "JavaScript", "bytes": "51718" }, { "name": "Makefile", "bytes": "6052" }, { "name": "Mako", "bytes": "494" }, { "name": "Python", "bytes": "418020" }, { "name": "Shell", "bytes": "1690" }, { "name": "Vue", "bytes": "46644" } ], "symlink_target": "" }
class FdoSpatialContextMismatchException : public FdoException { protected: /// Constructs a default instance of an FdoSpatialContextMismatchException. FDO_API FdoSpatialContextMismatchException(); /// Constructs an instance of an FdoSpatialContextMismatchException using the specified /// arguments. FDO_API FdoSpatialContextMismatchException(FdoString* message); /// Constructs an instance of an FdoSpatialContextMismatchException using the specified /// arguments. FDO_API FdoSpatialContextMismatchException(FdoString* message, FdoException* cause); FDO_API virtual ~FdoSpatialContextMismatchException(); FDO_API virtual void Dispose(); public: /// \brief /// Constructs a default instance of an FdoSpatialContextMismatchException. /// /// \return /// Returns FdoSpatialContextMismatchException /// FDO_API static FdoSpatialContextMismatchException* Create(); /// \brief /// Constructs an instance of an FdoSpatialContextMismatchException using the specified arguments. /// /// \param message /// Input message text /// /// \return /// Returns FdoSpatialContextMismatchException /// FDO_API static FdoSpatialContextMismatchException* Create(FdoString* message); /// \brief /// Constructs an instance of an FdoSpatialContextMismatchException using the specified arguments. /// /// \param message /// Input name text /// \param cause /// Input cause of exception /// /// \return /// Returns FdoSpatialContextMismatchException /// FDO_API static FdoSpatialContextMismatchException* Create(FdoString* message, FdoException* cause); }; /// \ingroup (typedefs) /// \brief /// FdoSpatialContextMismatchExceptionP is a FdoPtr on FdoSpatialContextMismatchException, provided for convenience. typedef FdoPtr<FdoSpatialContextMismatchException> FdoSpatialContextMismatchExceptionP; #endif
{ "content_hash": "54e6b464b68770fe5d11361ed3766910", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 116, "avg_line_length": 32.65, "alnum_prop": 0.7299642674834099, "repo_name": "SuperMap/Fdo_SuperMap", "id": "ade2c0a7d127369a0c2e213dd910d8265b1053f7", "size": "3267", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "源代码/Thirdparty/FDO/Inc(3.3.1)/Fdo/Commands/SpatialContext/SpatialContextMismatchException.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "9090" }, { "name": "Bison", "bytes": "28258" }, { "name": "C", "bytes": "2684451" }, { "name": "C#", "bytes": "30420" }, { "name": "C++", "bytes": "10149737" }, { "name": "CSS", "bytes": "33248" }, { "name": "HTML", "bytes": "45157" }, { "name": "JavaScript", "bytes": "69484" }, { "name": "Objective-C", "bytes": "4414" }, { "name": "PLSQL", "bytes": "32296" }, { "name": "TeX", "bytes": "926" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <me.panpf.sketch.sample.widget.SampleImageView android:id="@+id/image_gaussianBlurFragment" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /> <SeekBar android:id="@+id/seekBar_gaussianBlurFragment" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" android:paddingBottom="16dp" android:paddingTop="16dp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="16dp" android:layout_marginLeft="16dp" android:layout_marginRight="16dp"> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:textColor="@color/text_normal" android:text="模糊半径"/> <TextView android:id="@+id/text_gaussianBlurFragment" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/text_normal" android:gravity="right" /> </LinearLayout> </LinearLayout>
{ "content_hash": "b1403b9ba7769dcf59118349f4a1062a", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 72, "avg_line_length": 35.53488372093023, "alnum_prop": 0.637434554973822, "repo_name": "xiaopansky/Sketch", "id": "2a93661c53ab7e396061530f5fa56bc3f209456d", "size": "1536", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sample/src/main/res/layout/fragment_gaussian_blur.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1001099" } ], "symlink_target": "" }