text
stringlengths
2
99.9k
meta
dict
(function (Prism) { /** * Returns the placeholder for the given language id and index. * * @param {string} language * @param {string|number} index * @returns {string} */ function getPlaceholder(language, index) { return '___' + language.toUpperCase() + index + '___'; } Object.defineProperties(Prism.languages['markup-templating'] = {}, { buildPlaceholders: { /** * Tokenize all inline templating expressions matching `placeholderPattern`. * * If `replaceFilter` is provided, only matches of `placeholderPattern` for which `replaceFilter` returns * `true` will be replaced. * * @param {object} env The environment of the `before-tokenize` hook. * @param {string} language The language id. * @param {RegExp} placeholderPattern The matches of this pattern will be replaced by placeholders. * @param {(match: string) => boolean} [replaceFilter] */ value: function (env, language, placeholderPattern, replaceFilter) { if (env.language !== language) { return; } var tokenStack = env.tokenStack = []; env.code = env.code.replace(placeholderPattern, function (match) { if (typeof replaceFilter === 'function' && !replaceFilter(match)) { return match; } var i = tokenStack.length; var placeholder; // Check for existing strings while (env.code.indexOf(placeholder = getPlaceholder(language, i)) !== -1) ++i; // Create a sparse array tokenStack[i] = match; return placeholder; }); // Switch the grammar to markup env.grammar = Prism.languages.markup; } }, tokenizePlaceholders: { /** * Replace placeholders with proper tokens after tokenizing. * * @param {object} env The environment of the `after-tokenize` hook. * @param {string} language The language id. */ value: function (env, language) { if (env.language !== language || !env.tokenStack) { return; } // Switch the grammar back env.grammar = Prism.languages[language]; var j = 0; var keys = Object.keys(env.tokenStack); function walkTokens(tokens) { for (var i = 0; i < tokens.length; i++) { // all placeholders are replaced already if (j >= keys.length) { break; } var token = tokens[i]; if (typeof token === 'string' || (token.content && typeof token.content === 'string')) { var k = keys[j]; var t = env.tokenStack[k]; var s = typeof token === 'string' ? token : token.content; var placeholder = getPlaceholder(language, k); var index = s.indexOf(placeholder); if (index > -1) { ++j; var before = s.substring(0, index); var middle = new Prism.Token(language, Prism.tokenize(t, env.grammar), 'language-' + language, t); var after = s.substring(index + placeholder.length); var replacement = []; if (before) { replacement.push.apply(replacement, walkTokens([before])); } replacement.push(middle); if (after) { replacement.push.apply(replacement, walkTokens([after])); } if (typeof token === 'string') { tokens.splice.apply(tokens, [i, 1].concat(replacement)); } else { token.content = replacement; } } } else if (token.content /* && typeof token.content !== 'string' */) { walkTokens(token.content); } } return tokens; } walkTokens(env.tokens); } } }); }(Prism));
{ "pile_set_name": "Github" }
-----BEGIN CERTIFICATE----- MIIFRTCCBC2gAwIBAgIBADANBgkqhkiG9w0BAQUFADCBszEPMA0GA1UEAxMGZHNh LWNhMQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMH U2VhdHRsZTESMBAGA1UEChMJQ2FzdGFnbGlhMSEwHwYDVQQLExhSZXNlYXJjaCBh bmQgRGV2ZWxvcG1lbnQxFDASBgNVBAsTC1RKIFNhdW5kZXJzMR8wHQYJKoZIhvcN AQkBFhB0akBjYXN0YWdsaWEub3JnMB4XDTEyMTIwNDAyMTMwMloXDTEzMTIwNDAy MTMwMlowgbMxDzANBgNVBAMTBmRzYS1jYTELMAkGA1UEBhMCVVMxEzARBgNVBAgT Cldhc2hpbmd0b24xEDAOBgNVBAcTB1NlYXR0bGUxEjAQBgNVBAoTCUNhc3RhZ2xp YTEhMB8GA1UECxMYUmVzZWFyY2ggYW5kIERldmVsb3BtZW50MRQwEgYDVQQLEwtU SiBTYXVuZGVyczEfMB0GCSqGSIb3DQEJARYQdGpAY2FzdGFnbGlhLm9yZzCCASIw DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKNxLf0g9QzYZt3SyvVSHPpbjecD dzD0PYrj7m6YID77fiBAMXXBL3DNDIIthYalrfDPIc8jzm3TCmBuq8avP/v9yYdv T/a/qfMdKLF8LoArCy6uQgi8TV1VyM3Qx/NVMAy8i3AAk53aE0vnQKSfU0QyWj6R wUxWdYMFgQNhpOJoYpg+K6kyGGo3KFeHKgpMtoasTjmAL2MTR7N8nWX1u1LXEVl1 CKEPSLfOQbT2VHzMS1jkAb+Xj5i+XKGcfy3FQaact/Ly0zPncZLZEYjlFH+0tbv1 3yaKlTknZ7SDpUNczlr7YZnrDa5J0ZuFELLEZeASu/vlOX7BXAXuiNxsEBkCAwEA AaOCAWAwggFcMAwGA1UdEwQFMAMBAf8wSgYDVR0RBEMwQYINY2FzdGFnbGlhLm9y Z4EQdGpAY2FzdGFnbGlhLm9yZ4cEfwAAAYYYaHR0cDovL3d3dy5jYXN0YWdsaWEu b3JnMB0GA1UdDgQWBBRekvGDTXRlsV7bXmrU/wk9+ZCtwDCB4AYDVR0jBIHYMIHV gBRekvGDTXRlsV7bXmrU/wk9+ZCtwKGBuaSBtjCBszEPMA0GA1UEAxMGZHNhLWNh MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHU2Vh dHRsZTESMBAGA1UEChMJQ2FzdGFnbGlhMSEwHwYDVQQLExhSZXNlYXJjaCBhbmQg RGV2ZWxvcG1lbnQxFDASBgNVBAsTC1RKIFNhdW5kZXJzMR8wHQYJKoZIhvcNAQkB FhB0akBjYXN0YWdsaWEub3JnggEAMA0GCSqGSIb3DQEBBQUAA4IBAQCKhbmMVD0j MSyEqfZJ0mf9jQsUINNih39MxwVFr90FqE78iVaPHXuebksGB8AlVAcvgaopUQzd knt+OliGQr4ce9SbwICBIKaA+KCJefXbtk58fx9GI5dMYLSH/51fKiYIsMWagy1p WteQRGOLQ26/iTBQ8wzZDvn0a7a4B5+BIXy+bJ7TYIRx//qX58d5A1CLSb8z0DUl xiSV2ST9fv914csRs4EA1mUry0ZXHCaprwLuWE7akSmJaru0nqdY1J+iIYlKsGHO uiHSTybfW8ZgpNOk3FPAbCznYRBSYI/aZljKZLY8n4Vts9hTbM3m0JhLd1geKTdG /qYnjcw5C3RJ -----END CERTIFICATE----- -----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEAo3Et/SD1DNhm3dLK9VIc+luN5wN3MPQ9iuPubpggPvt+IEAx dcEvcM0Mgi2FhqWt8M8hzyPObdMKYG6rxq8/+/3Jh29P9r+p8x0osXwugCsLLq5C CLxNXVXIzdDH81UwDLyLcACTndoTS+dApJ9TRDJaPpHBTFZ1gwWBA2Gk4mhimD4r qTIYajcoV4cqCky2hqxOOYAvYxNHs3ydZfW7UtcRWXUIoQ9It85BtPZUfMxLWOQB v5ePmL5coZx/LcVBppy38vLTM+dxktkRiOUUf7S1u/XfJoqVOSdntIOlQ1zOWvth mesNrknRm4UQssRl4BK7++U5fsFcBe6I3GwQGQIDAQABAoIBAHeIPLQVuGIumfy9 P0XvSdYnwz4ioLciySeczzH+/AZT88guan3OTZ3XuMAz/qWc4ftt4TIW49AaOkqQ ZfynCsqGry7nz7mMLwToXGyBf5io4kK/mve8j3AlXvh3KuThdoS6F9hP86XMabRn ajV7eHA1yx5bht0HlmW+Tr5kWSxjM4hYryVT0c861tqOIo11bAanUsipH7ZZ9odz Pr7U+BIFzSMTePLZ96QofltyfGii7vOrisd/FyQRooliTNrSdVlsw/nGzO0rVD8w 2ieEPSA0rkTAwYqailAUrqwgK7sumYnpi6lAEVlE+tXZt6uIHkq9RWV8x6Xj/8fJ IaNaHCkCgYEA2VpqyfnL1dVhpGMOb66bNi3xegxVNsxm3oPFxV1k71pP4cddVMgK rYGW1gSMVUjXJtStekxQ3WmZqxUCbm6j3xRhNn9rNPuiUoBM4nIj0EzcvCNpQ+w6 1BR5xVIz+TvuCcWD2dWQdV4sRDHqc3pxwNi5H+7EbU5TYKW7nJ9wgZsCgYEAwIDQ GtcnUy0NdTo178hB1PiPn0Rx6OunCHN7zVRWF884c5RwfkOMELHG/L5fCaTqR++A ub9YWbJpze/rvZcLKkFK3rRS+OFTata+FY5tEMWbqRY7JxVJVFzXFoyTjDiEDcPi 220U1jLgWm6ySd7Wu0Z2jAuUCBd013lRlXww2lsCgYEApaYmOvZYpghw2RLxXqZo /jq3jbe2fgP75lvxL0DFezGOLdl+RO4MTT21Uji3JwxThPGToOBmxMgFaICjkLxb wdlLWXh0oTWh+VR0xCQPLWJW3D/0quJv11AfmgXTPICzItlYan08EmcKP5L3Rrkr 1riVJkQXieKm4sKMoIpW+T8CgYAWmwnVHQ7xJYk/CubqkYmpiMbU3STDRWkIBQe0 xQKXKS5n5DaRnT0FeNr1MyXV7BfW+rkTFvU5E0p5dIMqcGJPQ/uWy3Yy48L3+N+5 iFAmeA4ffQzVOhqyXXSkoT1yafCX7Tjmq5iWzsKp2/Xz1sdAlrW1HGb1zEtcQlLi SwMxoQKBgQCFZWWDM3i5kflLT1E++qN5wGJJ1gU5gorQWo8dtSteBgZ5Ol01fscu 7MsCWwokO0/DDgRgGsWe0DaCbHJtmteNSO7zYbLWrITy1DNbisVtptWR5X/62Qnj xv8s9kZUwPrGyL0LM77FC9th/8Vii8n4Ccxhu2ttJetzh5/5OC0jrA== -----END RSA PRIVATE KEY-----
{ "pile_set_name": "Github" }
<?php class TaxRulesTaxManager extends TaxRulesTaxManagerCore { }
{ "pile_set_name": "Github" }
<Location /server-info> SetHandler server-info <%- if @restrict_access -%> <%- if scope.function_versioncmp([@apache_version, '2.4']) >= 0 -%> Require ip <%= Array(@allow_from).join(" ") %> <%- else -%> Order deny,allow Deny from all <%- if @allow_from and ! @allow_from.empty? -%> <%- @allow_from.each do |allowed| -%> Allow from <%= allowed %> <%- end -%> <%- else -%> Allow from 127.0.0.1 Allow from ::1 <%- end -%> <%- end -%> <%- end -%> </Location>
{ "pile_set_name": "Github" }
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package util //DeviceUtil is a util for common device methods type DeviceUtil interface { FindMultipathDeviceForDevice(disk string) string FindSlaveDevicesOnMultipath(disk string) []string } type deviceHandler struct { get_io IoUtil } //NewDeviceHandler Create a new IoHandler implementation func NewDeviceHandler(io IoUtil) DeviceUtil { return &deviceHandler{get_io: io} }
{ "pile_set_name": "Github" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using PermissionControlSystem; namespace PCS.DomainModel.FileSystem { public class FileOperation : IOperation { public FileOperation() { } public FileOperation(string optName) { this.OperationName = optName; } public string OperationName { get; set; } /// <summary> /// 执行实现类的操作,如果需要参数,需要先设置本类的参数 /// </summary> /// <returns></returns> public object Execute() { return dnycExecute(this, this.OperationName, this.Parameters); } private object dnycExecute(object tartgetObj, string method, object[] paras) { //调用动态执行方法 return null; } /// <summary> /// 操作的参数 /// </summary> public object[] Parameters { get; set; } } public class FileCreate : FileOperation { public FileCreate() { base.OperationName = "Create"; } //具体的操作方法 public bool Create(string fileName) { try { var f = System.IO.File.Create(fileName); f.Close(); return true; } catch { } return false; } } }
{ "pile_set_name": "Github" }
# reflectx The sqlx package has special reflect needs. In particular, it needs to: * be able to map a name to a field * understand embedded structs * understand mapping names to fields by a particular tag * user specified name -> field mapping functions These behaviors mimic the behaviors by the standard library marshallers and also the behavior of standard Go accessors. The first two are amply taken care of by `Reflect.Value.FieldByName`, and the third is addressed by `Reflect.Value.FieldByNameFunc`, but these don't quite understand struct tags in the ways that are vital to most marshallers, and they are slow. This reflectx package extends reflect to achieve these goals.
{ "pile_set_name": "Github" }
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package tag contains functionality handling tags and related data. package tag // import "golang.org/x/text/internal/tag" import "sort" // An Index converts tags to a compact numeric value. // // All elements are of size 4. Tags may be up to 4 bytes long. Excess bytes can // be used to store additional information about the tag. type Index string // Elem returns the element data at the given index. func (s Index) Elem(x int) string { return string(s[x*4 : x*4+4]) } // Index reports the index of the given key or -1 if it could not be found. // Only the first len(key) bytes from the start of the 4-byte entries will be // considered for the search and the first match in Index will be returned. func (s Index) Index(key []byte) int { n := len(key) // search the index of the first entry with an equal or higher value than // key in s. index := sort.Search(len(s)/4, func(i int) bool { return cmp(s[i*4:i*4+n], key) != -1 }) i := index * 4 if cmp(s[i:i+len(key)], key) != 0 { return -1 } return index } // Next finds the next occurrence of key after index x, which must have been // obtained from a call to Index using the same key. It returns x+1 or -1. func (s Index) Next(key []byte, x int) int { if x++; x*4 < len(s) && cmp(s[x*4:x*4+len(key)], key) == 0 { return x } return -1 } // cmp returns an integer comparing a and b lexicographically. func cmp(a Index, b []byte) int { n := len(a) if len(b) < n { n = len(b) } for i, c := range b[:n] { switch { case a[i] > c: return 1 case a[i] < c: return -1 } } switch { case len(a) < len(b): return -1 case len(a) > len(b): return 1 } return 0 } // Compare returns an integer comparing a and b lexicographically. func Compare(a string, b []byte) int { return cmp(Index(a), b) } // FixCase reformats b to the same pattern of cases as form. // If returns false if string b is malformed. func FixCase(form string, b []byte) bool { if len(form) != len(b) { return false } for i, c := range b { if form[i] <= 'Z' { if c >= 'a' { c -= 'z' - 'Z' } if c < 'A' || 'Z' < c { return false } } else { if c <= 'Z' { c += 'z' - 'Z' } if c < 'a' || 'z' < c { return false } } b[i] = c } return true }
{ "pile_set_name": "Github" }
/* Copyright (c) 2007 Scott Lembcke * * 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. */ #include <string.h> #include "chipmunk/chipmunk_private.h" //MARK: Sleeping Functions void cpSpaceActivateBody(cpSpace *space, cpBody *body) { cpAssertHard(cpBodyGetType(body) == CP_BODY_TYPE_DYNAMIC, "Internal error: Attempting to activate a non-dynamic body."); if(space->locked){ // cpSpaceActivateBody() is called again once the space is unlocked if(!cpArrayContains(space->rousedBodies, body)) cpArrayPush(space->rousedBodies, body); } else { cpAssertSoft(body->sleeping.root == NULL && body->sleeping.next == NULL, "Internal error: Activating body non-NULL node pointers."); cpArrayPush(space->dynamicBodies, body); CP_BODY_FOREACH_SHAPE(body, shape){ cpSpatialIndexRemove(space->staticShapes, shape, shape->hashid); cpSpatialIndexInsert(space->dynamicShapes, shape, shape->hashid); } CP_BODY_FOREACH_ARBITER(body, arb){ cpBody *bodyA = arb->body_a; // Arbiters are shared between two bodies that are always woken up together. // You only want to restore the arbiter once, so bodyA is arbitrarily chosen to own the arbiter. // The edge case is when static bodies are involved as the static bodies never actually sleep. // If the static body is bodyB then all is good. If the static body is bodyA, that can easily be checked. if(body == bodyA || cpBodyGetType(bodyA) == CP_BODY_TYPE_STATIC){ int numContacts = arb->count; struct cpContact *contacts = arb->contacts; // Restore contact values back to the space's contact buffer memory arb->contacts = cpContactBufferGetArray(space); memcpy(arb->contacts, contacts, numContacts*sizeof(struct cpContact)); cpSpacePushContacts(space, numContacts); // Reinsert the arbiter into the arbiter cache const cpShape *a = arb->a, *b = arb->b; const cpShape *shape_pair[] = {a, b}; cpHashValue arbHashID = CP_HASH_PAIR((cpHashValue)a, (cpHashValue)b); cpHashSetInsert(space->cachedArbiters, arbHashID, shape_pair, NULL, arb); // Update the arbiter's state arb->stamp = space->stamp; cpArrayPush(space->arbiters, arb); cpfree(contacts); } } CP_BODY_FOREACH_CONSTRAINT(body, constraint){ cpBody *bodyA = constraint->a; if(body == bodyA || cpBodyGetType(bodyA) == CP_BODY_TYPE_STATIC) cpArrayPush(space->constraints, constraint); } } } static void cpSpaceDeactivateBody(cpSpace *space, cpBody *body) { cpAssertHard(cpBodyGetType(body) == CP_BODY_TYPE_DYNAMIC, "Internal error: Attempting to deactivate a non-dynamic body."); cpArrayDeleteObj(space->dynamicBodies, body); CP_BODY_FOREACH_SHAPE(body, shape){ cpSpatialIndexRemove(space->dynamicShapes, shape, shape->hashid); cpSpatialIndexInsert(space->staticShapes, shape, shape->hashid); } CP_BODY_FOREACH_ARBITER(body, arb){ cpBody *bodyA = arb->body_a; if(body == bodyA || cpBodyGetType(bodyA) == CP_BODY_TYPE_STATIC){ cpSpaceUncacheArbiter(space, arb); // Save contact values to a new block of memory so they won't time out size_t bytes = arb->count*sizeof(struct cpContact); struct cpContact *contacts = (struct cpContact *)cpcalloc(1, bytes); memcpy(contacts, arb->contacts, bytes); arb->contacts = contacts; } } CP_BODY_FOREACH_CONSTRAINT(body, constraint){ cpBody *bodyA = constraint->a; if(body == bodyA || cpBodyGetType(bodyA) == CP_BODY_TYPE_STATIC) cpArrayDeleteObj(space->constraints, constraint); } } static inline cpBody * ComponentRoot(cpBody *body) { return (body ? body->sleeping.root : NULL); } void cpBodyActivate(cpBody *body) { if(body != NULL && cpBodyGetType(body) == CP_BODY_TYPE_DYNAMIC){ body->sleeping.idleTime = 0.0f; cpBody *root = ComponentRoot(body); if(root && cpBodyIsSleeping(root)){ // TODO should cpBodyIsSleeping(root) be an assertion? cpAssertSoft(cpBodyGetType(root) == CP_BODY_TYPE_DYNAMIC, "Internal Error: Non-dynamic body component root detected."); cpSpace *space = root->space; cpBody *body = root; while(body){ cpBody *next = body->sleeping.next; body->sleeping.idleTime = 0.0f; body->sleeping.root = NULL; body->sleeping.next = NULL; cpSpaceActivateBody(space, body); body = next; } cpArrayDeleteObj(space->sleepingComponents, root); } CP_BODY_FOREACH_ARBITER(body, arb){ // Reset the idle timer of things the body is touching as well. // That way things don't get left hanging in the air. cpBody *other = (arb->body_a == body ? arb->body_b : arb->body_a); if(cpBodyGetType(other) != CP_BODY_TYPE_STATIC) other->sleeping.idleTime = 0.0f; } } } void cpBodyActivateStatic(cpBody *body, cpShape *filter) { cpAssertHard(cpBodyGetType(body) == CP_BODY_TYPE_STATIC, "cpBodyActivateStatic() called on a non-static body."); CP_BODY_FOREACH_ARBITER(body, arb){ if(!filter || filter == arb->a || filter == arb->b){ cpBodyActivate(arb->body_a == body ? arb->body_b : arb->body_a); } } // TODO: should also activate joints? } static inline void cpBodyPushArbiter(cpBody *body, cpArbiter *arb) { cpAssertSoft(cpArbiterThreadForBody(arb, body)->next == NULL, "Internal Error: Dangling contact graph pointers detected. (A)"); cpAssertSoft(cpArbiterThreadForBody(arb, body)->prev == NULL, "Internal Error: Dangling contact graph pointers detected. (B)"); cpArbiter *next = body->arbiterList; cpAssertSoft(next == NULL || cpArbiterThreadForBody(next, body)->prev == NULL, "Internal Error: Dangling contact graph pointers detected. (C)"); cpArbiterThreadForBody(arb, body)->next = next; if(next) cpArbiterThreadForBody(next, body)->prev = arb; body->arbiterList = arb; } static inline void ComponentAdd(cpBody *root, cpBody *body){ body->sleeping.root = root; if(body != root){ body->sleeping.next = root->sleeping.next; root->sleeping.next = body; } } static inline void FloodFillComponent(cpBody *root, cpBody *body) { // Kinematic bodies cannot be put to sleep and prevent bodies they are touching from sleeping. // Static bodies are effectively sleeping all the time. if(cpBodyGetType(body) == CP_BODY_TYPE_DYNAMIC){ cpBody *other_root = ComponentRoot(body); if(other_root == NULL){ ComponentAdd(root, body); CP_BODY_FOREACH_ARBITER(body, arb) FloodFillComponent(root, (body == arb->body_a ? arb->body_b : arb->body_a)); CP_BODY_FOREACH_CONSTRAINT(body, constraint) FloodFillComponent(root, (body == constraint->a ? constraint->b : constraint->a)); } else { cpAssertSoft(other_root == root, "Internal Error: Inconsistency dectected in the contact graph."); } } } static inline cpBool ComponentActive(cpBody *root, cpFloat threshold) { CP_BODY_FOREACH_COMPONENT(root, body){ if(body->sleeping.idleTime < threshold) return cpTrue; } return cpFalse; } void cpSpaceProcessComponents(cpSpace *space, cpFloat dt) { cpBool sleep = (space->sleepTimeThreshold != INFINITY); cpArray *bodies = space->dynamicBodies; #ifndef NDEBUG for(int i=0; i<bodies->num; i++){ cpBody *body = (cpBody*)bodies->arr[i]; cpAssertSoft(body->sleeping.next == NULL, "Internal Error: Dangling next pointer detected in contact graph."); cpAssertSoft(body->sleeping.root == NULL, "Internal Error: Dangling root pointer detected in contact graph."); } #endif // Calculate the kinetic energy of all the bodies. if(sleep){ cpFloat dv = space->idleSpeedThreshold; cpFloat dvsq = (dv ? dv*dv : cpvlengthsq(space->gravity)*dt*dt); // update idling and reset component nodes for(int i=0; i<bodies->num; i++){ cpBody *body = (cpBody*)bodies->arr[i]; // TODO should make a separate array for kinematic bodies. if(cpBodyGetType(body) != CP_BODY_TYPE_DYNAMIC) continue; // Need to deal with infinite mass objects cpFloat keThreshold = (dvsq ? body->m*dvsq : 0.0f); body->sleeping.idleTime = (cpBodyKineticEnergy(body) > keThreshold ? 0.0f : body->sleeping.idleTime + dt); } } // Awaken any sleeping bodies found and then push arbiters to the bodies' lists. cpArray *arbiters = space->arbiters; for(int i=0, count=arbiters->num; i<count; i++){ cpArbiter *arb = (cpArbiter*)arbiters->arr[i]; cpBody *a = arb->body_a, *b = arb->body_b; if(sleep){ // TODO checking cpBodyIsSleepin() redundant? if(cpBodyGetType(b) == CP_BODY_TYPE_KINEMATIC || cpBodyIsSleeping(a)) cpBodyActivate(a); if(cpBodyGetType(a) == CP_BODY_TYPE_KINEMATIC || cpBodyIsSleeping(b)) cpBodyActivate(b); } cpBodyPushArbiter(a, arb); cpBodyPushArbiter(b, arb); } if(sleep){ // Bodies should be held active if connected by a joint to a kinematic. cpArray *constraints = space->constraints; for(int i=0; i<constraints->num; i++){ cpConstraint *constraint = (cpConstraint *)constraints->arr[i]; cpBody *a = constraint->a, *b = constraint->b; if(cpBodyGetType(b) == CP_BODY_TYPE_KINEMATIC) cpBodyActivate(a); if(cpBodyGetType(a) == CP_BODY_TYPE_KINEMATIC) cpBodyActivate(b); } // Generate components and deactivate sleeping ones for(int i=0; i<bodies->num;){ cpBody *body = (cpBody*)bodies->arr[i]; if(ComponentRoot(body) == NULL){ // Body not in a component yet. Perform a DFS to flood fill mark // the component in the contact graph using this body as the root. FloodFillComponent(body, body); // Check if the component should be put to sleep. if(!ComponentActive(body, space->sleepTimeThreshold)){ cpArrayPush(space->sleepingComponents, body); CP_BODY_FOREACH_COMPONENT(body, other) cpSpaceDeactivateBody(space, other); // cpSpaceDeactivateBody() removed the current body from the list. // Skip incrementing the index counter. continue; } } i++; // Only sleeping bodies retain their component node pointers. body->sleeping.root = NULL; body->sleeping.next = NULL; } } } void cpBodySleep(cpBody *body) { cpBodySleepWithGroup(body, NULL); } void cpBodySleepWithGroup(cpBody *body, cpBody *group){ cpAssertHard(cpBodyGetType(body) == CP_BODY_TYPE_DYNAMIC, "Non-dynamic bodies cannot be put to sleep."); cpSpace *space = body->space; cpAssertHard(!cpSpaceIsLocked(space), "Bodies cannot be put to sleep during a query or a call to cpSpaceStep(). Put these calls into a post-step callback."); cpAssertHard(cpSpaceGetSleepTimeThreshold(space) < INFINITY, "Sleeping is not enabled on the space. You cannot sleep a body without setting a sleep time threshold on the space."); cpAssertHard(group == NULL || cpBodyIsSleeping(group), "Cannot use a non-sleeping body as a group identifier."); if(cpBodyIsSleeping(body)){ cpAssertHard(ComponentRoot(body) == ComponentRoot(group), "The body is already sleeping and it's group cannot be reassigned."); return; } CP_BODY_FOREACH_SHAPE(body, shape) cpShapeCacheBB(shape); cpSpaceDeactivateBody(space, body); if(group){ cpBody *root = ComponentRoot(group); body->sleeping.root = root; body->sleeping.next = root->sleeping.next; body->sleeping.idleTime = 0.0f; root->sleeping.next = body; } else { body->sleeping.root = body; body->sleeping.next = NULL; body->sleeping.idleTime = 0.0f; cpArrayPush(space->sleepingComponents, body); } cpArrayDeleteObj(space->dynamicBodies, body); }
{ "pile_set_name": "Github" }
# [1387. Sort Integers by The Power Value (Medium)](https://leetcode.com/problems/sort-integers-by-the-power-value/) <p>The power of an integer <code>x</code> is defined as the number of steps needed to transform&nbsp;<code>x</code> into <code>1</code> using the following steps:</p> <ul> <li>if <code>x</code> is even then <code>x = x / 2</code></li> <li>if <code>x</code> is odd then <code>x = 3 * x + 1</code></li> </ul> <p>For example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 (3 --&gt; 10 --&gt; 5 --&gt; 16 --&gt; 8 --&gt; 4 --&gt; 2 --&gt; 1).</p> <p>Given three integers <code>lo</code>, <code>hi</code> and <code>k</code>. The task is to sort all integers in the interval <code>[lo, hi]</code> by the power value in <strong>ascending order</strong>, if two or more integers have <strong>the same</strong> power value sort them by <strong>ascending order</strong>.</p> <p>Return the <code>k-th</code> integer in the range <code>[lo, hi]</code> sorted by the power value.</p> <p>Notice that for any&nbsp;integer <code>x</code> <code>(lo &lt;= x &lt;= hi)</code> it is <strong>guaranteed</strong> that <code>x</code> will transform into <code>1</code> using these steps and that the power of <code>x</code> is will <strong>fit</strong> in 32 bit signed integer.</p> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre><strong>Input:</strong> lo = 12, hi = 15, k = 2 <strong>Output:</strong> 13 <strong>Explanation:</strong> The power of 12 is 9 (12 --&gt; 6 --&gt; 3 --&gt; 10 --&gt; 5 --&gt; 16 --&gt; 8 --&gt; 4 --&gt; 2 --&gt; 1) The power of 13 is 9 The power of 14 is 17 The power of 15 is 17 The interval sorted by the power value [12,13,14,15]. For k = 2 answer is the second element which is 13. Notice that 12 and 13 have the same power value and we sorted them in ascending order. Same for 14 and 15. </pre> <p><strong>Example 2:</strong></p> <pre><strong>Input:</strong> lo = 1, hi = 1, k = 1 <strong>Output:</strong> 1 </pre> <p><strong>Example 3:</strong></p> <pre><strong>Input:</strong> lo = 7, hi = 11, k = 4 <strong>Output:</strong> 7 <strong>Explanation:</strong> The power array corresponding to the interval [7, 8, 9, 10, 11] is [16, 3, 19, 6, 14]. The interval sorted by power is [8, 10, 11, 7, 9]. The fourth number in the sorted array is 7. </pre> <p><strong>Example 4:</strong></p> <pre><strong>Input:</strong> lo = 10, hi = 20, k = 5 <strong>Output:</strong> 13 </pre> <p><strong>Example 5:</strong></p> <pre><strong>Input:</strong> lo = 1, hi = 1000, k = 777 <strong>Output:</strong> 570 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= lo &lt;= hi &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= hi - lo + 1</code></li> </ul> **Related Topics**: [Sort](https://leetcode.com/tag/sort/), [Graph](https://leetcode.com/tag/graph/) ## Solution 1. ```cpp // OJ: https://leetcode.com/problems/sort-integers-by-the-power-value/ // Author: github.com/lzl124631x // Time: O(NlogN) // Space: O(N) class Solution { int power(int x) { int ans = 0; while (x != 1) { if (x % 2) x = x * 3 + 1; else x /= 2; ++ans; } return ans; } public: int getKth(int lo, int hi, int k) { vector<pair<int, int>> v; for (int i = lo; i <= hi; ++i) v.emplace_back(power(i), i); sort(v.begin(), v.end()); return v[k - 1].second; } }; ```
{ "pile_set_name": "Github" }
# frozen_string_literal: true module Asciidoctor module PDF module FormattedText grammar Markup rule text complex end rule complex (cdata / element / charref)* { def content elements.map {|e| e.content } end } end rule element # strict tag matching (costs a minor toll) # void_element / start_tag complex end_tag &{|seq| seq[0].name == seq[2].name } { void_element / start_tag complex end_tag { # NOTE: content only applies to non-void elements (second part of rule) def content { type: :element, name: (tag_element = elements[0]).name.to_sym, attributes: tag_element.attributes, pcdata: elements[1].content } end } end rule void_element '<' void_tag_name attributes (spaces? '/')? '>' { def content { type: :element, name: elements[1].text_value.to_sym, attributes: elements[2].content } end } end rule start_tag '<' tag_name attributes '>' { def name elements[1].text_value end def attributes elements[2].content end } end rule tag_name # QUESTION: faster to do regex? # QUESTION: what about supporting hr? 'a' / 'strong' / 'em' / 'code' / 'font' / 'span' / 'button' / 'key' / 'sup' / 'sub' / 'mark' / 'del' end rule void_tag_name 'br' / 'img' end rule attributes attribute* { def content attrs = {} elements.each {|e| attr_name, attr_val = e.content attrs[attr_name.to_sym] = attr_val } attrs end } end rule attribute spaces [a-z_]+ '=' '"' [^"]* '"' { def content [elements[1].text_value, elements[4].text_value] end } end rule end_tag '</' tag_name '>' { def name elements[1].text_value end } end rule cdata [^<&]+ { def content { type: :text, value: text_value } end } end rule charref '&' ('#' character_decimal / '#x' character_hex / character_name) ';' { def content if (ref_data = elements[1]).terminal? { type: :charref, reference_type: :name, value: ref_data.text_value.to_sym } elsif ref_data.elements[0].text_value == '#' { type: :charref, reference_type: :decimal, value: ref_data.elements[1].text_value.to_i } else { type: :charref, reference_type: :hex, value: ref_data.elements[1].text_value } end end } end rule character_decimal [0-9] 2..6 end rule character_hex [0-9a-f] 2..5 end rule character_name 'amp' / 'apos' / 'gt' / 'lt' / 'nbsp' / 'quot' end rule spaces ' '+ end end end end end
{ "pile_set_name": "Github" }
/* * Copyright (c) 2017, Circonus, 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: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name Circonus, Inc. nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* BIG IDEA: * * The ideal behind clustering in reconnoiter is to ensure that if a single * instance of reconnoiter goes down, another instance will continue running * the checks. This is more complicated for push checks (data sent to broker) * than for pull checks (broker queries for data). * * Regardless, there are two things in reconnoiter that make checks "go": * (1) checks, (2) filtersets. In order to synchronize broker configuration * we need to replicate these two things. It is up to the operator to make * sure the noitd's are all configured similarly enough to run the checks. * * clustering leverages libmtev "cluster" tech. * Each time the configuration of the cluster changes, node state is cleared. * Each time a node changes state, that node state is cleared. * Each noitd maintains an outbound queue of changes to filtersets and checks * from which other noitds consume. * When the state of a node is cleared, all checks and all filtersets are * considered changed and queued for that broker. * * The state is small enough on the brokers that simple "replay from scratch" * is tenable. * Checks and filtersets have a "seq" that must increase which resolves * conflicts. The operator is responible for assigned "seq" numbers. */ #include <mtev_defines.h> #include <mtev_cluster.h> #include <mtev_uuid.h> #include <mtev_memory.h> #include "noit_clustering.h" #include "noit_check.h" #include "noit_filters.h" #include "noit_filters_lmdb.h" #include <curl/curl.h> #include <sys/mman.h> #include <errno.h> #define MAX_CLUSTER_NODES 128 /* 128 this is insanely high */ #define REPL_FAIL_WAIT_US 500000 static char *cainfo; static char *certinfo; static char *keyinfo; static uint32_t batch_size = 500; /* for fetching clusters and filters */ static void noit_cluster_setup_ssl(int port) { char xpath[1024]; if(cainfo && certinfo && keyinfo) return; snprintf(xpath, sizeof(xpath), "//listeners//listener[@port=\"%d\"]", port); mtev_conf_section_t listener = mtev_conf_get_section_read(MTEV_CONF_ROOT, xpath); if(mtev_conf_section_is_empty(listener)) { mtev_conf_release_section_read(listener); return; } mtev_hash_table *sslconfig = mtev_conf_get_hash(listener, "sslconfig"); #define SSLSETUP(sslconfig, name, var) do { \ const char *v; \ free(var); \ var = NULL; \ if(mtev_hash_retr_str(sslconfig, name, strlen(name), &v)) \ var = strdup(v); \ } while(0) SSLSETUP(sslconfig, "ca_chain", cainfo); SSLSETUP(sslconfig, "certificate_file", certinfo); SSLSETUP(sslconfig, "key_file", keyinfo); mtev_hash_destroy(sslconfig, free, free); free(sslconfig); #undef SSLSETUP mtev_conf_release_section_read(listener); } static mtev_log_stream_t clerr, cldeb; static eventer_jobq_t *repl_jobq; static int64_t checks_produced = 0; static int64_t checks_produced_netseq = 0; static int64_t filters_produced = 0; static int64_t filters_produced_netseq = 0; struct check_changes { uuid_t checkid; int64_t seq; struct check_changes *next; }; struct filter_changes { char *name; int64_t seq; struct filter_changes *next; }; typedef struct { uuid_t id; char *cn; struct sockaddr *addr; socklen_t addrlen; struct timeval boot; struct { /* these are inbound */ int64_t prev_fetched; int64_t fetched; int64_t available; int last_batch; /* these out outbound */ int64_t sent; struct check_changes *head, *tail; } checks; struct { /* these are inbound */ int64_t prev_fetched; int64_t fetched; int64_t available; int last_batch; /* these out outbound */ int64_t sent; struct filter_changes *head, *tail; } filters; int64_t generation; mtev_boolean job_inflight; } noit_peer_t; typedef struct repl_job_t { uuid_t peerid; struct { int64_t prev, end; int batch_size; mtev_boolean success; } checks, filters; } repl_job_t; static int64_t generation = 0; static mtev_cluster_t *my_cluster = NULL; static pthread_mutex_t noit_peer_lock = PTHREAD_MUTEX_INITIALIZER; static mtev_hash_table peers; static void possibly_start_job(noit_peer_t *peer); static void check_changes_free(void *v) { free(v); } static void filter_changes_free(void *v) { free(((struct filter_changes *)v)->name); free(v); } static void noit_peer_clear_changelog(noit_peer_t *p) { while(p->checks.head) { struct check_changes *tofree = p->checks.head; p->checks.head = p->checks.head->next; check_changes_free(tofree); } while(p->filters.head) { struct filter_changes *tofree = p->filters.head; p->filters.head = p->filters.head->next; filter_changes_free(tofree); } p->checks.head = p->checks.tail = NULL; p->filters.head = p->filters.tail = NULL; } static void noit_peer_free(void *vnp) { noit_peer_t *p = vnp; free(p->cn); free(p->addr); noit_peer_clear_changelog(p); free(p); } static void noit_peer_rebuild_changelog(noit_peer_t *peer) { noit_peer_clear_changelog(peer); noit_filtersets_build_cluster_changelog(peer); noit_check_build_cluster_changelog(peer); } void noit_cluster_mark_check_changed(noit_check_t *check, void *vpeer) { if(!strcmp(check->module, "selfcheck")) return; if(check->config_seq <= 0) return; mtevL(cldeb, "marking check %s [%s] %"PRId64" for repl\n", check->name, check->module, check->config_seq); pthread_mutex_lock(&noit_peer_lock); mtev_hash_iter iter = MTEV_HASH_ITER_ZERO; checks_produced++; while(mtev_hash_adv(&peers, &iter)) { noit_peer_t *peer = iter.value.ptr; if(vpeer && (void *)peer != vpeer) continue; struct check_changes *change = calloc(1, sizeof(*change)); mtev_uuid_copy(change->checkid, check->checkid); change->seq = checks_produced; if(peer->checks.tail) peer->checks.tail->next = change; else { peer->checks.head = change; } peer->checks.tail = change; } checks_produced_netseq = htonll(checks_produced); pthread_mutex_unlock(&noit_peer_lock); } void noit_cluster_mark_filter_changed(const char *name, void *vpeer) { pthread_mutex_lock(&noit_peer_lock); mtev_hash_iter iter = MTEV_HASH_ITER_ZERO; filters_produced++; while(mtev_hash_adv(&peers, &iter)) { noit_peer_t *peer = iter.value.ptr; if(vpeer && (void *)peer != vpeer) continue; struct filter_changes *change = calloc(1, sizeof(*change)); change->name = strdup(name); change->seq = filters_produced; if(peer->filters.tail) peer->filters.tail->next = change; else { peer->filters.head = change; } peer->filters.tail = change; } filters_produced_netseq = htonll(filters_produced); pthread_mutex_unlock(&noit_peer_lock); } void noit_cluster_xml_check_changes(uuid_t peerid, const char *cn, int64_t prev_end, int64_t limit, xmlNodePtr parent) { void *vp; int64_t last_seen = 0; noit_peer_t *peer; mtev_hash_table dedup; mtev_hash_init(&dedup); pthread_mutex_lock(&noit_peer_lock); if(!mtev_hash_retrieve(&peers, (const char *)peerid, UUID_SIZE, &vp)) { char peerid_str[UUID_STR_LEN + 1]; mtev_uuid_unparse_lower(peerid, peerid_str); mtevL(clerr, "Check changes request by unknown peer [%s].\n", peerid_str); pthread_mutex_unlock(&noit_peer_lock); return; } peer = vp; if(strcmp(peer->cn, cn)) { mtevL(clerr, "Check changes request by peer with bad cn [%s != %s].\n", cn, peer->cn); pthread_mutex_unlock(&noit_peer_lock); return; } struct check_changes *node = peer->checks.head; /* First eat anything we know they've seen */ while(peer->checks.head && peer->checks.head->seq <= prev_end) { struct check_changes *tofree = peer->checks.head; peer->checks.head = peer->checks.head->next; if(NULL == peer->checks.head) peer->checks.tail = NULL; check_changes_free(tofree); } for(node = peer->checks.head; node && node->seq <= limit; node = node->next) { if(mtev_hash_store(&dedup, (const char *)node->checkid, UUID_SIZE, NULL)) { noit_check_t *check = noit_poller_lookup(node->checkid); if(check && 0 != strcmp(check->module, "selfcheck")) { xmlNodePtr checknode = noit_check_to_xml(check, parent->doc, parent); xmlAddChild(parent, checknode); last_seen = node->seq; } } } pthread_mutex_unlock(&noit_peer_lock); char produced_str[32]; snprintf(produced_str, sizeof(produced_str), "%"PRId64, last_seen); xmlSetProp(parent, (xmlChar *)"seq", (xmlChar *)produced_str); mtev_hash_destroy(&dedup, NULL, NULL); } void noit_cluster_xml_filter_changes(uuid_t peerid, const char *cn, int64_t prev_end, int64_t limit, xmlNodePtr parent) { void *vp; int64_t last_seen = 0; noit_peer_t *peer; mtev_hash_table dedup; mtev_hash_init(&dedup); pthread_mutex_lock(&noit_peer_lock); if(!mtev_hash_retrieve(&peers, (const char *)peerid, UUID_SIZE, &vp)) { char peerid_str[UUID_STR_LEN + 1]; mtev_uuid_unparse_lower(peerid, peerid_str); mtevL(clerr, "Filter changes request by unknown peer [%s].\n", peerid_str); pthread_mutex_unlock(&noit_peer_lock); return; } peer = vp; if(strcmp(peer->cn, cn)) { mtevL(clerr, "Filter changes request by peer with bad cn [%s != %s].\n", cn, peer->cn); pthread_mutex_unlock(&noit_peer_lock); return; } struct filter_changes *node = peer->filters.head; /* First eat anything we know they've seen */ while(peer->filters.head && peer->filters.head->seq <= prev_end) { struct filter_changes *tofree = peer->filters.head; peer->filters.head = peer->filters.head->next; if(NULL == peer->filters.head) peer->filters.tail = NULL; filter_changes_free(tofree); } for(node = peer->filters.head; node && node->seq <= limit; node = node->next) { if(mtev_hash_store(&dedup, (const char *)node->name, strlen(node->name), NULL)) { char xpath[512]; snprintf(xpath, sizeof(xpath), "//filtersets//filterset[@name=\"%s\"]", node->name); mtev_conf_section_t filternode = mtev_conf_get_section_read(MTEV_CONF_ROOT, xpath); if(!mtev_conf_section_is_empty(filternode)) { xmlAddChild(parent, xmlCopyNode(mtev_conf_section_to_xmlnodeptr(filternode),1)); last_seen = node->seq; } mtev_conf_release_section_read(filternode); } } pthread_mutex_unlock(&noit_peer_lock); char produced_str[32]; snprintf(produced_str, sizeof(produced_str), "%"PRId64, last_seen); xmlSetProp(parent, (xmlChar *)"seq", (xmlChar *)produced_str); mtev_hash_destroy(&dedup, NULL, NULL); } void noit_cluster_lmdb_filter_changes(uuid_t peerid, const char *cn, int64_t prev_end, int64_t limit, xmlNodePtr parent) { void *vp; int64_t last_seen = 0; noit_peer_t *peer; mtev_hash_table dedup; mtev_hash_init(&dedup); pthread_mutex_lock(&noit_peer_lock); if(!mtev_hash_retrieve(&peers, (const char *)peerid, UUID_SIZE, &vp)) { char peerid_str[UUID_STR_LEN + 1]; mtev_uuid_unparse_lower(peerid, peerid_str); mtevL(clerr, "Filter changes request by unknown peer [%s].\n", peerid_str); pthread_mutex_unlock(&noit_peer_lock); return; } peer = vp; if(strcmp(peer->cn, cn)) { mtevL(clerr, "Filter changes request by peer with bad cn [%s != %s].\n", cn, peer->cn); pthread_mutex_unlock(&noit_peer_lock); return; } struct filter_changes *node = peer->filters.head; /* First eat anything we know they've seen */ while(peer->filters.head && peer->filters.head->seq <= prev_end) { struct filter_changes *tofree = peer->filters.head; peer->filters.head = peer->filters.head->next; if(NULL == peer->filters.head) peer->filters.tail = NULL; filter_changes_free(tofree); } for(node = peer->filters.head; node && node->seq <= limit; node = node->next) { if(mtev_hash_store(&dedup, (const char *)node->name, strlen(node->name), NULL)) { if(noit_filters_lmdb_already_in_db(node->name) == mtev_true) { xmlNodePtr new_node = xmlNewNode(NULL, (xmlChar *)"filterset"); if (noit_filters_lmdb_populate_filterset_xml_from_lmdb(new_node, node->name) == 0) { xmlAddChild(parent, new_node); last_seen = node->seq; } else { mtevL(mtev_error, "noit_filters_lmdb_populate_filterset_xml_from_lmdb: could not add node %s\n", node->name); xmlFreeNode(new_node); } } } } pthread_mutex_unlock(&noit_peer_lock); char produced_str[32]; snprintf(produced_str, sizeof(produced_str), "%"PRId64, last_seen); xmlSetProp(parent, (xmlChar *)"seq", (xmlChar *)produced_str); mtev_hash_destroy(&dedup, NULL, NULL); } static void clear_old_peers() { mtev_hash_iter iter = MTEV_HASH_ITER_ZERO; while(mtev_hash_adv(&peers, &iter)) { noit_peer_t *peer = iter.value.ptr; if(peer->generation < generation) { mtevL(cldeb, "removing peer %s\n", peer->cn); mtev_hash_delete(&peers, iter.key.str, UUID_SIZE, NULL, noit_peer_free); } } } struct curl_tls { CURL *curl; mtev_boolean ssl_is_setup; }; static pthread_key_t curl_tls; void curl_tls_free(void *v) { struct curl_tls *ctls = v; curl_easy_cleanup(ctls->curl); free(v); } static CURL *get_curl_handle() { struct curl_tls *ctls; ctls = pthread_getspecific(curl_tls); if(!ctls) { CURL *curl; curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1); curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS, 2000); curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, "gzip"); curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, 120000); curl_easy_setopt(curl, CURLOPT_BUFFERSIZE, 131072); ctls = calloc(1, sizeof(*ctls)); ctls->curl = curl; pthread_setspecific(curl_tls, ctls); } if(cainfo && certinfo && keyinfo && !ctls->ssl_is_setup) { curl_easy_setopt(ctls->curl, CURLOPT_CAINFO, cainfo); curl_easy_setopt(ctls->curl, CURLOPT_SSLCERT, certinfo); curl_easy_setopt(ctls->curl, CURLOPT_SSLKEY, keyinfo); ctls->ssl_is_setup = mtev_true; } return ctls->ssl_is_setup ? ctls->curl : NULL; } static size_t write_data_to_file(void *buff, size_t s, size_t n, void *vd) { int *fd = vd; ssize_t len = s*n; mtevL(cldeb, "XML[%.*s]\n", (int)len, (char *)buff); while((len = write(*fd, buff, (size_t)len)) == -1 && errno == EINTR); return len < 0 ? 0 : (size_t)len; } static xmlDocPtr fetch_xml_from_noit(CURL *curl, const char *url, struct curl_slist *connect_to) { xmlDocPtr doc = NULL; int fd = -1; char tfile[PATH_MAX]; long code, httpcode; strlcpy(tfile, "/tmp/noitext.XXXXXX", PATH_MAX); fd = mkstemp(tfile); if(fd < 0) return NULL; unlink(tfile); mtevL(cldeb, "REPL_JOB Pulling %s\n", url); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_CONNECT_TO, connect_to); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &fd); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data_to_file); httpcode = 0; code = curl_easy_perform(curl); if(code == CURLE_OK && curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpcode) == CURLE_OK && httpcode == 200) { struct stat sb; int rv; while((rv = fstat(fd, &sb)) == -1 && errno == EINTR); if(rv == 0) { void *buff = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if(buff != MAP_FAILED) { doc = xmlParseMemory(buff, sb.st_size); munmap(buff, sb.st_size); } else { mtevL(clerr, "curl mmap failed: %s\n", strerror(errno)); } } else { mtevL(clerr, "curl stat error: %s\n", strerror(errno)); } } else { mtevL(clerr, "Error fetching %s: %ld/%ld\n", url, code, httpcode); } close(fd); return doc; } static int repl_work(eventer_t e, int mask, void *closure, struct timeval *now) { repl_job_t *rj = closure; void *vp; if(mask == EVENTER_ASYNCH_WORK) { uuid_t my_id; char my_id_str[UUID_STR_LEN+1]; pthread_mutex_lock(&noit_peer_lock); if(!mtev_hash_retrieve(&peers, (const char *)rj->peerid, UUID_SIZE, &vp)) { pthread_mutex_unlock(&noit_peer_lock); return 0; } mtevL(cldeb, "REPL_JOB start [%s] F[%"PRId64",%"PRId64"] C:[%"PRId64",%"PRId64"]\n", ((noit_peer_t *)vp)->cn, rj->filters.prev, rj->filters.end, rj->checks.prev, rj->checks.end); if(rj->filters.end == 0 && rj->checks.end == 0) { mtevL(cldeb, "REPL_JOB noop, nothing to do.\n"); pthread_mutex_unlock(&noit_peer_lock); sleep(1); return 0; } pthread_mutex_unlock(&noit_peer_lock); mtev_cluster_get_self(my_id); mtev_uuid_unparse_lower(my_id, my_id_str); CURL *curl = get_curl_handle(); if(curl == NULL) { mtevL(clerr, "Can't get curl handle: waiting %fs\n", (double)REPL_FAIL_WAIT_US/1000000); usleep(REPL_FAIL_WAIT_US); return 0; } mtev_memory_begin(); mtev_cluster_node_t *node = mtev_cluster_get_node(my_cluster, rj->peerid); if(node) { struct sockaddr *addr; socklen_t addrlen; const char *cn = mtev_cluster_node_get_cn(node); char port_str[10]; char host_port[128]; char connect_str[256]; char url[1024]; struct curl_slist *connect_to = NULL; switch(mtev_cluster_node_get_addr(node, &addr, &addrlen)) { case AF_INET: inet_ntop(AF_INET, &((struct sockaddr_in *)addr)->sin_addr, host_port, sizeof(host_port)); strlcat(host_port, ":", sizeof(host_port)); snprintf(port_str, sizeof(port_str), "%u", ntohs(((struct sockaddr_in *)addr)->sin_port)); strlcat(host_port, port_str, sizeof(host_port)); break; case AF_INET6: host_port[0] = '['; inet_ntop(AF_INET, &((struct sockaddr_in6 *)addr)->sin6_addr, host_port+1, sizeof(host_port)-1); strlcat(host_port, "]:", sizeof(host_port)); snprintf(port_str, sizeof(port_str), "%u", ntohs(((struct sockaddr_in6 *)addr)->sin6_port)); strlcat(host_port, port_str, sizeof(host_port)); break; default: strlcpy(host_port, mtev_cluster_node_get_cn(node), sizeof(host_port)); } snprintf(connect_str, sizeof(connect_str), "%s:43191:%s", cn, host_port); connect_to = curl_slist_append(NULL, connect_str); /* First pull filtersets */ if(rj->filters.end) { snprintf(url, sizeof(url), "https://%s:43191/filters/updates?peer=%s&prev=%"PRId64"&end=%"PRId64, cn, my_id_str, rj->filters.prev, rj->filters.end); xmlDocPtr doc = fetch_xml_from_noit(curl, url, connect_to); if(doc) { rj->filters.batch_size = noit_filters_process_repl(doc); if(rj->filters.batch_size >= 0) rj->filters.success = mtev_true; xmlFreeDoc(doc); } if(!rj->filters.success) usleep(REPL_FAIL_WAIT_US); } /* Second pull checks */ if(rj->checks.end) { snprintf(url, sizeof(url), "https://%s:43191/checks/updates?peer=%s&prev=%"PRId64"&end=%"PRId64, cn, my_id_str, rj->checks.prev, rj->checks.end); xmlDocPtr doc = fetch_xml_from_noit(curl, url, connect_to); if(doc) { rj->checks.batch_size = noit_check_process_repl(doc); if(rj->checks.batch_size >= 0) rj->checks.success = mtev_true; xmlFreeDoc(doc); } if(!rj->checks.success) usleep(REPL_FAIL_WAIT_US); } curl_easy_setopt(curl, CURLOPT_CONNECT_TO, NULL); curl_slist_free_all(connect_to); } mtev_memory_end(); } else if(mask == EVENTER_ASYNCH) { pthread_mutex_lock(&noit_peer_lock); if(mtev_hash_retrieve(&peers, (const char *)rj->peerid, UUID_SIZE, &vp)) { noit_peer_t *peer = vp; peer->job_inflight = mtev_false; peer->filters.last_batch = rj->filters.batch_size; if(rj->filters.success && rj->filters.prev) { peer->filters.prev_fetched = rj->filters.prev; } if(rj->filters.success && rj->filters.end) { peer->filters.fetched = rj->filters.end; } peer->checks.last_batch = rj->checks.batch_size; if(rj->checks.success && rj->checks.prev) { peer->checks.prev_fetched = rj->checks.prev; } if(rj->checks.success && rj->checks.end) { peer->checks.fetched = rj->checks.end; } mtevL(cldeb, "REPL_JOB finish [%s] F[%"PRId64",%"PRId64"] %d C:[%"PRId64",%"PRId64"] %d\n", ((noit_peer_t *)vp)->cn, peer->filters.fetched, peer->filters.available, peer->filters.last_batch, peer->checks.fetched, peer->checks.available, peer->checks.last_batch); possibly_start_job(peer); } pthread_mutex_unlock(&noit_peer_lock); free(closure); } return 0; } static void possibly_start_job(noit_peer_t *peer) { if(peer->job_inflight) { mtevL(cldeb, "REPL_JOB job already inflight\n"); return; } if(mtev_cluster_get_node(my_cluster, peer->id) == NULL) { mtevL(cldeb, "REPL_JOB peer %s no longer in cluster\n", peer->cn); return; } if(peer->checks.last_batch || peer->filters.last_batch || peer->checks.available != peer->checks.prev_fetched || peer->filters.available != peer->filters.prev_fetched) { /* We have work to do */ repl_job_t *rj = calloc(1, sizeof(*rj)); mtev_uuid_copy(rj->peerid, peer->id); rj->checks.prev = peer->checks.fetched; rj->checks.end = peer->checks.available; if (batch_size > 0 && (rj->checks.end - rj->checks.prev > batch_size)) { rj->checks.end = rj->checks.prev + batch_size; } rj->filters.prev = peer->filters.fetched; rj->filters.end = peer->filters.available; if (batch_size > 0 && (rj->filters.end - rj->filters.prev > batch_size)) { rj->filters.end = rj->filters.prev + batch_size; } if(peer->checks.prev_fetched == rj->checks.end && peer->checks.last_batch == 0) { rj->checks.prev = rj->checks.end = 0; } if(peer->filters.prev_fetched == rj->filters.end && peer->filters.last_batch == 0) { rj->filters.prev = rj->filters.end = 0; } peer->job_inflight = true; eventer_add_asynch(repl_jobq, eventer_alloc_asynch(repl_work, rj)); } else { mtevL(cldeb, "REPL_JOB no more work to do\n"); } } mtev_boolean noit_cluster_checkid_replication_pending(uuid_t checkid) { if(!my_cluster) return mtev_false; pthread_mutex_lock(&noit_peer_lock); mtev_hash_iter iter = MTEV_HASH_ITER_ZERO; while(mtev_hash_adv(&peers, &iter)) { struct check_changes *n; noit_peer_t *peer = iter.value.ptr; for(n = peer->checks.head; n; n = n->next) { if(mtev_uuid_compare(n->checkid, checkid) == 0) { pthread_mutex_unlock(&noit_peer_lock); return mtev_true; } } } pthread_mutex_unlock(&noit_peer_lock); return mtev_false; } static void update_peer(mtev_cluster_node_t *node) { void *vp; int64_t *check_seqnet = NULL, *filter_seqnet = NULL; noit_peer_t *peer; uuid_t nodeid; struct sockaddr *addr; socklen_t addrlen; struct timeval boot; const char *cn = mtev_cluster_node_get_cn(node); (void)mtev_cluster_node_get_addr(node, &addr, &addrlen); boot = mtev_cluster_node_get_boot_time(node); if(mtev_cluster_is_that_me(node)) return; /* must have lock here */ mtev_cluster_node_get_id(node, nodeid); char nodeidstr[UUID_STR_LEN+1]; mtev_uuid_unparse_lower(nodeid, nodeidstr); if(mtev_hash_retrieve(&peers, (const char *)nodeid, UUID_SIZE, &vp)) { peer = vp; mtevL(cldeb, "updating peer %s/%s\n", cn, nodeidstr); } else { peer = calloc(1, sizeof(*peer)); mtev_uuid_copy(peer->id, nodeid); mtev_hash_store(&peers, (const char *)peer->id, UUID_SIZE, peer); mtevL(cldeb, "adding peer %s/%s\n", cn, nodeidstr); } peer->generation = generation; if(!peer->cn || strcmp(peer->cn, cn)) { free(peer->cn); peer->cn = strdup(cn); } if(!peer->addr || (peer->addrlen != addrlen) || memcmp(peer->addr, addr, addrlen)) { free(peer->addr); peer->addrlen = addrlen; peer->addr = malloc(peer->addrlen); memcpy(peer->addr, addr, peer->addrlen); } if(memcmp(&peer->boot, &boot, sizeof(boot))) { /* boot time changes, we know nothing now */ memcpy(&peer->boot, &boot, sizeof(boot)); peer->checks.fetched = 0; peer->filters.fetched = 0; peer->checks.prev_fetched = 0; peer->filters.prev_fetched = 0; noit_peer_rebuild_changelog(peer); } if(mtev_cluster_get_heartbeat_payload(node, NOIT_MTEV_CLUSTER_APP_ID, NOIT_MTEV_CLUSTER_CHECK_SEQ_KEY, (void **)&check_seqnet) > 0) { peer->checks.available = ntohll(*check_seqnet); } if(mtev_cluster_get_heartbeat_payload(node, NOIT_MTEV_CLUSTER_APP_ID, NOIT_MTEV_CLUSTER_FILTER_SEQ_KEY, (void **)&filter_seqnet) > 0) { peer->filters.available = ntohll(*filter_seqnet); } possibly_start_job(peer); if(check_seqnet) { mtevL(cldeb, " node %s -> check:[%"PRId64" -> %"PRId64"]\n", mtev_cluster_node_get_cn(node), peer->checks.fetched, peer->checks.available); } if(filter_seqnet) { mtevL(cldeb, " node %s -> filter:[%"PRId64" -> %"PRId64"]\n", mtev_cluster_node_get_cn(node), peer->filters.fetched, peer->filters.available); } } static void attach_to_cluster(mtev_cluster_t *nc) { int i, n; if(nc == my_cluster) return; my_cluster = nc; pthread_mutex_lock(&noit_peer_lock); generation++; if(!my_cluster) { mtev_hash_delete_all(&peers, NULL, noit_peer_free); pthread_mutex_unlock(&noit_peer_lock); return; } mtev_cluster_node_t *nodeset[MAX_CLUSTER_NODES]; n = mtev_cluster_get_nodes(my_cluster, nodeset, MAX_CLUSTER_NODES, mtev_false); pthread_mutex_unlock(&noit_peer_lock); for(i=0; i<n; i++) { update_peer(nodeset[i]); } pthread_mutex_lock(&noit_peer_lock); clear_old_peers(); pthread_mutex_unlock(&noit_peer_lock); eventer_jobq_set_min_max(repl_jobq, 0, i); mtev_cluster_set_heartbeat_payload(my_cluster, NOIT_MTEV_CLUSTER_APP_ID, NOIT_MTEV_CLUSTER_CHECK_SEQ_KEY, &checks_produced_netseq, sizeof(int64_t)); mtev_cluster_set_heartbeat_payload(my_cluster, NOIT_MTEV_CLUSTER_APP_ID, NOIT_MTEV_CLUSTER_FILTER_SEQ_KEY, &filters_produced_netseq, sizeof(int64_t)); } static const char * cluster_change_nice_name(mtev_cluster_node_changes_t c, long tdiff) { switch(c) { case MTEV_CLUSTER_NODE_DIED: return "died"; case MTEV_CLUSTER_NODE_REBOOTED: return tdiff < 0 ? "is present" : "(re)booted"; case MTEV_CLUSTER_NODE_CHANGED_SEQ: return "reconfigured"; case MTEV_CLUSTER_NODE_CHANGED_PAYLOAD: return "has changes"; } return "unknown"; } static int my_cluster_id = -1; int noit_cluster_self_index(void) { if(my_cluster_id >= 0) return my_cluster_id; mtev_cluster_t *cluster = mtev_cluster_by_name(NOIT_MTEV_CLUSTER_NAME); if(!cluster) return -1; uuid_t me; mtev_cluster_get_self(me); mtev_cluster_node_t *self = mtev_cluster_get_node(cluster, me); if(!self) return -1; my_cluster_id = mtev_cluster_node_get_idx(self); return my_cluster_id; } static mtev_hook_return_t cluster_topo_cb(void *closure, mtev_cluster_node_changes_t node_changes, mtev_cluster_node_t *updated_node, mtev_cluster_t *cluster, struct timeval old_boot_time) { uuid_t id, me; char id_str[UUID_STR_LEN+1]; mtev_cluster_get_self(me); mtev_cluster_node_t *self = mtev_cluster_get_node(cluster, me); struct timeval my_boot_time = mtev_cluster_node_get_boot_time(self); mtev_cluster_node_get_id(updated_node, id); mtev_uuid_unparse_lower(id, id_str); struct timeval boot_time = mtev_cluster_node_get_boot_time(updated_node); struct timeval diff; sub_timeval(boot_time, my_boot_time, &diff); mtevL(node_changes == MTEV_CLUSTER_NODE_CHANGED_PAYLOAD ? cldeb : mtev_notice, "cluster %s:%s [%s%s] -> %s\n", mtev_cluster_get_name(cluster), mtev_cluster_node_get_cn(updated_node), mtev_uuid_compare(me,id) ? "" : "me:", id_str, cluster_change_nice_name(node_changes, diff.tv_sec)); if(!strcmp(mtev_cluster_get_name(cluster), NOIT_MTEV_CLUSTER_NAME)) { my_cluster_id = -1; attach_to_cluster(cluster); if(!mtev_cluster_is_that_me(updated_node)) update_peer(updated_node); else { struct sockaddr *addr; int port = 43191; switch(mtev_cluster_node_get_addr(updated_node, &addr, NULL)) { case AF_INET: port = ntohs(((struct sockaddr_in *)addr)->sin_port); break; case AF_INET6: port = ntohs(((struct sockaddr_in6 *)addr)->sin6_port); break; default: break; } noit_cluster_setup_ssl(port); } } return MTEV_HOOK_CONTINUE; } static mtev_boolean alive_nodes(mtev_cluster_node_t *node, mtev_boolean me, void *closure) { return !mtev_cluster_node_is_dead(node); } mtev_boolean noit_should_run_check(noit_check_t *check, mtev_cluster_node_t **node) { /* No clustering means I own everything */ if(!my_cluster) return mtev_true; if(!strcmp(check->module, "selfcheck")) return mtev_true; mtev_boolean i_own; mtev_cluster_node_t *nodeset[MAX_CLUSTER_NODES]; int w = MAX_CLUSTER_NODES; i_own = mtev_cluster_filter_owners(my_cluster, check->checkid, UUID_SIZE, nodeset, &w, alive_nodes, NULL); /* something is very wrong, we better run the check */ if(w < 1) return mtev_true; /* Fill in the address of the node */ if(w > 0 && node) *node = nodeset[0]; return i_own; } static int noit_clustering_show(mtev_console_closure_t ncct, int argc, char **argv, mtev_console_state_t *state, void *closure) { nc_printf(ncct, "my_cluster_id: %d\n", noit_cluster_self_index()); if(!my_cluster) { nc_printf(ncct, "clustering not configured.\n"); return 0; } pthread_mutex_lock(&noit_peer_lock); mtev_hash_iter iter = MTEV_HASH_ITER_ZERO; while(mtev_hash_adv(&peers, &iter)) { struct check_changes *n; noit_peer_t *peer = iter.value.ptr; char idstr[UUID_STR_LEN+1]; mtev_uuid_unparse_lower(peer->id, idstr); nc_printf(ncct, "-- %s (%s) --\n", idstr, peer->cn); nc_printf(ncct, " checks_produced: %" PRId64 "\n", checks_produced); nc_printf(ncct, " queued checks:\n"); for(n = peer->checks.head; n; n = n->next) { mtev_uuid_unparse_lower(n->checkid, idstr); nc_printf(ncct, " %s : %" PRId64 "\n", idstr, n->seq); } } pthread_mutex_unlock(&noit_peer_lock); return 0; } void noit_mtev_cluster_init() { mtev_console_state_t *tl; cmd_info_t *showcmd; pthread_key_create(&curl_tls, curl_tls_free); cldeb = mtev_log_stream_find("debug/noit/cluster"); clerr = mtev_log_stream_find("error/noit/cluster"); mtev_hash_init(&peers); tl = mtev_console_state_initial(); showcmd = mtev_console_state_get_cmd(tl, "show"); mtevAssert(showcmd && showcmd->dstate); mtev_conf_get_uint32(MTEV_CONF_ROOT, "//clusters/cluster[@name=\"noit\"]/@batch_size", &batch_size); mtev_console_state_add_cmd(showcmd->dstate, NCSCMD("noit-cluster", noit_clustering_show, NULL, NULL, NULL)); repl_jobq = eventer_jobq_create_ms("noit_cluster", EVENTER_JOBQ_MS_GC); mtevAssert(repl_jobq); eventer_jobq_set_min_max(repl_jobq, 0, 1); mtev_cluster_init(); mtev_cluster_handle_node_update_hook_register("noit-cluster", cluster_topo_cb, NULL); attach_to_cluster(mtev_cluster_by_name(NOIT_MTEV_CLUSTER_NAME)); }
{ "pile_set_name": "Github" }
// This is brl/bbas/bsta/bsta_basic_functors.h #ifndef bsta_basic_functors_h_ #define bsta_basic_functors_h_ //: // \file // \brief Basic functors for simple operations on Gaussian mixtures // \author Matt Leotta ([email protected]) // \date January 30, 2006 // // \verbatim // Modifications // (none yet) // \endverbatim #include <iostream> #include <vector> #ifdef _MSC_VER # include <vcl_msvc_warnings.h> #endif #include <bsta/bsta_attributes.h> #include <bsta/bsta_gaussian_indep.h> #include <bsta/bsta_gaussian_sphere.h> #include <vpdl/vpdt/vpdt_enable_if.h> #include <vpdl/vpdt/vpdt_dist_traits.h> #include <vpdl/vpdt/vpdt_mixture_accessors.h> //: A functor to return the probability density at a sample template <class dist_> class bsta_prob_density_functor { public: typedef typename dist_::math_type T; typedef typename dist_::vector_type vector_; typedef T return_T; typedef return_T return_type; // for compatibility with vpdl/vdpt enum { return_dim = 1 }; //: The main function bool operator() ( const dist_& d, const vector_& sample, return_T& retval ) const { retval = d.prob_density(sample); return true; } }; //: A functor to return the probability density with additional covariance template <class mix_dist_> class bsta_prob_density_addcovar_functor { public: typedef typename mix_dist_::dist_type::math_type T; typedef typename mix_dist_::dist_type::vector_type vector_; typedef typename mix_dist_::dist_type::covar_type covar_t_; typedef T return_T; typedef return_T return_type; // for compatibility with vpdl/vdpt enum { return_dim = 1 }; //: The main function bool operator() ( const mix_dist_& d, const vector_& sample, const covar_t_& add_covar, return_T& retval ) const { unsigned nc = d.num_components(); std::vector<covar_t_> initial_covars(nc); mix_dist_& non_const_d = const_cast<mix_dist_&>(d); for (unsigned i = 0; i<nc; ++i) { initial_covars[i]=(d.distribution(i)).covar(); non_const_d.distribution(i).set_covar(initial_covars[i]+add_covar); } retval = non_const_d.prob_density(sample); for (unsigned i = 0; i<nc; ++i) non_const_d.distribution(i).set_covar(initial_covars[i]); return true; } }; //: A functor to return the probability integrated over a box template <class dist_> class bsta_probability_functor { public: typedef typename dist_::math_type T; typedef typename dist_::vector_type vector_; typedef T return_T; typedef return_T return_type; // for compatibility with vpdl/vdpt enum { return_dim = 1 }; //: The main function bool operator() ( const dist_& d, const vector_& min_pt, const vector_& max_pt, return_T& retval ) const { retval = d.probability(min_pt,max_pt); return true; } }; //: A functor to return the probability with added covariance template <class mix_dist_> class bsta_probability_addcovar_functor { public: typedef typename mix_dist_::dist_type::math_type T; typedef typename mix_dist_::dist_type::vector_type vector_; typedef typename mix_dist_::dist_type::covar_type covar_t_; typedef T return_T; typedef return_T return_type; // for compatibility with vpdl/vdpt enum { return_dim = 1 }; //: The main function bool operator() ( const mix_dist_& d, const vector_& min_pt, const vector_& max_pt, const covar_t_& add_covar, return_T& retval ) const { unsigned nc = d.num_components(); mix_dist_& non_const_d = const_cast<mix_dist_&>(d); std::vector<covar_t_> initial_covars(nc); for (unsigned i = 0; i<nc; ++i){ initial_covars[i]=(d.distribution(i)).covar(); non_const_d.distribution(i).set_covar(initial_covars[i]+add_covar); } retval = d.probability(min_pt, max_pt); for (unsigned i = 0; i<nc; ++i) non_const_d.distribution(i).set_covar(initial_covars[i]); return true; } }; //: A functor to return the mean of the Gaussian // \note the distribution must be Gaussian template <class dist_, class Disambiguate = void> class bsta_mean_functor { public: typedef typename dist_::math_type T; typedef typename dist_::vector_type vector_; typedef vector_ return_T; typedef return_T return_type; // for compatibility with vpdl/vdpt //: is this functor valid for its distribution type static const bool valid_functor = true; enum { return_dim = dist_::dimension }; //: rebind this functor to another distribution type template <class other_dist> struct rebind { typedef bsta_mean_functor<other_dist> other; }; //: The main function bool operator() ( const dist_& d, return_T& retval ) const { retval = d.mean(); return true; } }; //: for compatibility with vpdl/vpdt template <class dist_> class bsta_mean_functor<dist_, typename vpdt_enable_if<vpdt_is_mixture<dist_> >::type > { public: typedef typename dist_::field_type return_type; enum { return_dim = dist_::dimension }; //: is this functor valid for its distribution type static const bool valid_functor = false; //: rebind this functor to another distribution type template <class other_dist> struct rebind { typedef bsta_mean_functor<other_dist> other; }; //: The main function bool operator() ( const dist_& /*d*/, return_type& /*retval*/ ) const { return false; } }; //: A functor to return the variance of the Gaussian // \note the distribution must be spherical Gaussian template <class dist_> class bsta_var_functor { public: typedef typename dist_::math_type T; typedef T return_T; typedef return_T return_type; // for compatibility with vpdl/vdpt enum { return_dim = 1 }; //: is this functor valid for its distribution type static const bool valid_functor = false; //: rebind this functor to another distribution type template <class other_dist> struct rebind { typedef bsta_var_functor<other_dist> other; }; //: The main function #if 0 bool operator() (dist_ const& d, return_T& retval) const { retval = d.var(); return true; } #else bool operator() (dist_ const&, return_T&) const { return false; } #endif }; //: A functor to return the variance of the Gaussian // \note the distribution must be a spherical Gaussian with one dimensions // the default template does nothing. // This solution is really just a hack. // The correct solution requires is_base_of from Boost or TR1. // This class should work for any derived class of bsta_gaussian_indep template <class T> class bsta_var_functor<bsta_num_obs<bsta_gaussian_sphere<T,1> > > { public: typedef bsta_gaussian_sphere<T,1> dist_; typedef typename dist_::vector_type vector_; typedef vector_ return_T; typedef return_T return_type; // for compatibility with vpdl/vdpt enum { return_dim = dist_::dimension }; //: is this functor valid for its distribution type static const bool valid_functor = true; //: rebind this functor to another distribution type template <class other_dist> struct rebind { typedef bsta_var_functor<other_dist> other; }; //: The main function bool operator() ( const dist_& d, return_T& retval ) const { retval = d.var(); return true; } }; //: A functor to return the variance of the Gaussian // \note the distribution must be an independent Gaussian // the default template does nothing template <class dist_> class bsta_diag_covar_functor { public: typedef typename dist_::math_type T; typedef typename dist_::vector_type vector_; typedef vector_ return_T; typedef return_T return_type; // for compatibility with vpdl/vdpt enum { return_dim = dist_::dimension }; //: is this functor valid for its distribution type static const bool valid_functor = false; //: rebind this functor to another distribution type template <class other_dist> struct rebind { typedef bsta_diag_covar_functor<other_dist> other; }; //: The main function #if 0 bool operator() (dist_ const& d, return_T& retval) const { retval = d.var(); return true; } #else bool operator() (dist_ const&, return_T&) const { return false; } #endif }; //: A functor to return the variance of the Gaussian // \note the distribution must be an independent Gaussian // the default template does nothing. // This solution is really just a hack. // The correct solution requires is_base_of from Boost or TR1. // This class should work for any derived class of bsta_gaussian_indep template <class T, unsigned n> class bsta_diag_covar_functor<bsta_num_obs<bsta_gaussian_indep<T,n> > > { public: typedef bsta_gaussian_indep<T,n> dist_; typedef typename dist_::vector_type vector_; typedef vector_ return_T; typedef return_T return_type; // for compatibility with vpdl/vdpt enum { return_dim = dist_::dimension }; //: is this functor valid for its distribution type static const bool valid_functor = true; //: rebind this functor to another distribution type template <class other_dist> struct rebind { typedef bsta_diag_covar_functor<other_dist> other; }; //: The main function bool operator() ( const dist_& d, return_T& retval ) const { retval = d.diag_covar(); return true; } }; //: A functor to return the determinant of the covariance of the Gaussian // \note the distribution must be Gaussian template <class dist_> class bsta_det_covar_functor { public: typedef typename dist_::math_type T; typedef T return_T; typedef return_T return_type; // for compatibility with vpdl/vdpt enum { return_dim = 1 }; //: The main function bool operator() ( const dist_& d, return_T& retval ) const { retval = d.det_covar(); return true; } }; //: A functor to return the weight of the component with given index // "Disambiguate" is for compatibility with vpdl/vpdt. // \note the distribution must be a mixture template <class mixture_, class Disambiguate=void> class bsta_weight_functor { public: typedef typename mixture_::math_type T; typedef T return_T; typedef return_T return_type; // for compatibility with vpdl/vdpt enum { return_dim = 1 }; //: is this functor valid for its distribution type static const bool valid_functor = false; //: rebind this functor to another distribution type template <class other_dist> struct rebind { typedef bsta_weight_functor<other_dist> other; }; //: Constructor bsta_weight_functor(unsigned int index = 0) {} //: The main function bool operator() ( const mixture_& mix, return_T& retval ) const { return false; } }; //: A functor to return the weight of the component with given index // \note the distribution must be a mixture template <class mixture_> class bsta_weight_functor<mixture_, typename vpdt_enable_if<vpdt_is_mixture<mixture_> >::type> { public: typedef typename mixture_::math_type T; typedef T return_T; typedef return_T return_type; // for compatibility with vpdl/vdpt enum { return_dim = 1 }; //: is this functor valid for its distribution type static const bool valid_functor = true; //: rebind this functor to another distribution type template <class other_dist> struct rebind { typedef bsta_weight_functor<other_dist> other; }; //: Constructor bsta_weight_functor(unsigned int index = 0) : idx(index) {} //: The main function bool operator() ( const mixture_& mix, return_T& retval ) const { if (idx < mix.num_components()){ retval = mix.weight(idx); return true; } return false; } unsigned int idx; }; //: A vpdt specialization to make the weight functor work as a mixture accessor // This is needed because weight is not a property of the mixture component, // it is a property on the mixture itself that is defined for each component. template <class mixture_> class vpdt_mixture_accessor<mixture_, bsta_weight_functor<typename mixture_::component_type>, typename vpdt_enable_if<vpdt_is_mixture<mixture_> >::type> { public: //: the accessor type typedef bsta_weight_functor<typename mixture_::component_type> accessor_type; //: the functor return type typedef typename vpdt_dist_traits<mixture_>::scalar_type return_type; //: the distribution operated on by the functor typedef mixture_ distribution_type; //: is this functor valid for its distribution type static const bool valid_functor = true; //: rebind this functor to another distribution type template <class other_dist, class other_accessor = accessor_type> struct rebind { typedef vpdt_mixture_accessor<other_dist,other_accessor> other; }; //: Constructor vpdt_mixture_accessor(unsigned int index = 0) : idx(index) {} //: Constructor vpdt_mixture_accessor(const accessor_type& a, unsigned int index = 0) : idx(index) {} //: The main function bool operator() ( const mixture_& mix, return_type& retval ) const { if (idx < mix.num_components()){ retval = mix.weight(idx); return true; } return false; } //: The component index unsigned int idx; }; //: A functor to apply another functor to one distribution in the mixture // \note the distribution must be a mixture template <class mixture_, class functor_> class bsta_mixture_functor { public: typedef typename mixture_::math_type T; typedef typename functor_::return_T return_T; typedef return_T return_type; // for compatibility with vpdl/vdpt enum { return_dim = functor_::return_dim }; //: Constructor bsta_mixture_functor(const functor_& f, unsigned int index = 0 ) : functor(f), idx(index) {} //: The main function bool operator() ( const mixture_& mix, return_T& retval ) const { if (idx < mix.num_components() && mix.weight(idx) > T(0)){ return functor(mix.distribution(idx),retval); } return false; } //: The functor to apply functor_ functor; //: The index to apply to unsigned int idx; }; //: A functor to apply another functor with data to one distribution in the mixture // \note the distribution must be a mixture template <class mixture_, class functor_> class bsta_mixture_data_functor { public: typedef typename mixture_::math_type T; typedef typename functor_::return_T return_T; typedef return_T return_type; // for compatibility with vpdl/vdpt typedef typename mixture_::vector_type vector_; enum { return_dim = functor_::return_dim }; //: Constructor bsta_mixture_data_functor(const functor_& f, unsigned int index = 0 ) : functor(f), idx(index) {} //: The main function bool operator() ( const mixture_& mix, const vector_& sample, return_T& retval ) const { if (idx < mix.num_components() && mix.weight(idx) > T(0)){ return functor(mix.distribution(idx),sample,retval); } return false; } //: The functor to apply functor_ functor; //: The index to apply to unsigned int idx; }; //: A functor to apply another functor to each distribution and produce a weighted sum // \note the distribution must be a mixture template <class mixture_, class functor_> class bsta_weighted_sum_functor { public: typedef typename mixture_::math_type T; typedef typename functor_::return_T return_T; typedef return_T return_type; // for compatibility with vpdl/vdpt enum { return_dim = functor_::return_dim }; //: Constructor bsta_weighted_sum_functor() : functor() {} //: Constructor bsta_weighted_sum_functor(const functor_& f) : functor(f) {} //: The main function bool operator() ( const mixture_& mix, return_T& retval ) const { const unsigned int nc = mix.num_components(); if (nc > 0) { return_T temp; if ( !functor(mix.distribution(0),temp) ) return false; retval = mix.weight(0) * temp; for (unsigned int idx=1; idx<nc; ++idx){ if ( !functor(mix.distribution(idx),temp) ) return false; retval += mix.weight(idx) * temp; } return true; } return false; } //: The functor to apply functor_ functor; }; //: A functor to apply another functor with data to each distribution and produce a weighted sum // \note the distribution must be a mixture template <class mixture_, class functor_> class bsta_weighted_sum_data_functor { public: typedef typename mixture_::math_type T; typedef typename functor_::return_T return_T; typedef return_T return_type; // for compatibility with vpdl/vdpt typedef typename mixture_::vector_type vector_; enum { return_dim = functor_::return_dim }; //: Constructor bsta_weighted_sum_data_functor() : functor() {} //: Constructor bsta_weighted_sum_data_functor(const functor_& f) : functor(f) {} //: The main function bool operator() ( const mixture_& mix, const vector_& sample, return_T& retval ) const { const unsigned int nc = mix.num_components(); if (nc > 0) { return_T temp; if ( !functor(mix.distribution(0),sample,temp) ) return false; retval = mix.weight(0) * temp; for (unsigned int idx=1; idx<nc; ++idx){ if ( !functor(mix.distribution(idx),sample,temp) ) return false; retval += mix.weight(idx) * temp; } return true; } return false; } //: The functor to apply functor_ functor; }; //: A functor to count the number of components in the mixture // \note the distribution must be a mixture template <class mixture_> class bsta_mixture_size_functor { public: typedef typename mixture_::math_type T; typedef unsigned int return_T; typedef return_T return_type; // for compatibility with vpdl/vdpt enum { return_dim = 1 }; //: The main function bool operator() ( const mixture_& mix, return_T& retval ) const { retval = mix.num_components(); return true; } }; #endif // bsta_basic_functors_h_
{ "pile_set_name": "Github" }
import QueryChooser from 'components/Markdown/QueryChooser' import Code from 'components/Markdown/Code' export const meta = { title: 'Set up Prisma', position: 1, gettingStartedOrder: 1, gettingStartedTitle: 'New database', nextText: 'Great work! 👏 Move on to learn how you can change your datamodel and (re-)generate your Prisma client.', technology: 'flow', technologyOrder: 3, articleGroup: 'Set up Prisma', } ## Coming soon This tutorial is currently being worked on and will be published soon. In the meantime, feel free to explore the corresponding [JavaScript tutorial](a002).
{ "pile_set_name": "Github" }
var NAVTREEINDEX2 = { "classfabgl_1_1_v_g_a16_controller.html#a8b25fa500a76153044da83d4f9133001":[7,0,0,93,9], "classfabgl_1_1_v_g_a16_controller.html#a8dfff3e791759134e96813c465abc767":[7,0,0,93,22], "classfabgl_1_1_v_g_a16_controller.html#a9592f436f7c627d30985f50967003fe9":[7,0,0,93,0], "classfabgl_1_1_v_g_a16_controller.html#a999c2b67a3b1320909211feb5e647217":[7,0,0,93,21], "classfabgl_1_1_v_g_a16_controller.html#a9a63b64a03a930820652d3b1c2cb9a04":[7,0,0,93,8], "classfabgl_1_1_v_g_a16_controller.html#a9b52443accc98230f7560144d7165b02":[7,0,0,93,25], "classfabgl_1_1_v_g_a16_controller.html#aa0fc0548ecde92597745b8fd6b513eb6":[7,0,0,93,14], "classfabgl_1_1_v_g_a16_controller.html#abb21f56cbf682423f7cdc4ce8656b017":[7,0,0,93,19], "classfabgl_1_1_v_g_a16_controller.html#ac5ce66824aa948074c07002b8edf4b62":[7,0,0,93,13], "classfabgl_1_1_v_g_a16_controller.html#ac6059fbf80a2005a4ae6829de2d67c7b":[7,0,0,93,11], "classfabgl_1_1_v_g_a16_controller.html#ad3175c9d60cdd00b72dcfa61dda9df7a":[7,0,0,93,23], "classfabgl_1_1_v_g_a16_controller.html#ae5843958fc71b17ee900fbd4297acdcd":[7,0,0,93,20], "classfabgl_1_1_v_g_a16_controller.html#af5488939dfd5c3fe1481bc6f87c707b3":[7,0,0,93,17], "classfabgl_1_1_v_g_a16_controller.html#afd008a0de0eaec247e4810d1a9afb924":[7,0,0,93,5], "classfabgl_1_1_v_g_a_controller.html":[7,0,0,94], "classfabgl_1_1_v_g_a_controller.html#a0d6de0c7ee0601e9b0f61873df56baa9":[7,0,0,94,19], "classfabgl_1_1_v_g_a_controller.html#a0e315e01651c743b29840a36641e196f":[7,0,0,94,16], "classfabgl_1_1_v_g_a_controller.html#a10e3b1a7467ff759302462216162fe70":[7,0,0,94,0], "classfabgl_1_1_v_g_a_controller.html#a11b70942a5879a6241dea608b28a65b8":[7,0,0,94,1], "classfabgl_1_1_v_g_a_controller.html#a1714be70aa7c740976cd3a5a6d7457c2":[7,0,0,94,10], "classfabgl_1_1_v_g_a_controller.html#a1feb3cc90f3460ebaa677fb959523d00":[7,0,0,94,3], "classfabgl_1_1_v_g_a_controller.html#a299c2bfe3660c0a8bc6ce38525f61788":[7,0,0,94,12], "classfabgl_1_1_v_g_a_controller.html#a387538792224c2a84be34d8621b41111":[7,0,0,94,18], "classfabgl_1_1_v_g_a_controller.html#a470fa64af60a3f689e263587a5fc5560":[7,0,0,94,21], "classfabgl_1_1_v_g_a_controller.html#a4ebecec3224ffb2ae98ab0cf358d23e6":[7,0,0,94,7], "classfabgl_1_1_v_g_a_controller.html#a54d7923d1beec800077e93769cf8a38b":[7,0,0,94,9], "classfabgl_1_1_v_g_a_controller.html#a5889bb0a66166d713ccbc4adf21e82d4":[7,0,0,94,5], "classfabgl_1_1_v_g_a_controller.html#a5cb70db85d96d99e7dd709e2e0231aac":[7,0,0,94,11], "classfabgl_1_1_v_g_a_controller.html#a6044d318c3b5dfbf9cd16cfa2dbe7bf4":[7,0,0,94,28], "classfabgl_1_1_v_g_a_controller.html#a62aed395da993973e820ffa87d2ce6ce":[7,0,0,94,14], "classfabgl_1_1_v_g_a_controller.html#a885f286b5f21b9ca89b626f9c40a0b00":[7,0,0,94,29], "classfabgl_1_1_v_g_a_controller.html#a8dfff3e791759134e96813c465abc767":[7,0,0,94,25], "classfabgl_1_1_v_g_a_controller.html#a999c2b67a3b1320909211feb5e647217":[7,0,0,94,24], "classfabgl_1_1_v_g_a_controller.html#a9a7a0081752e32ea318eb93dea8d337e":[7,0,0,94,27], "classfabgl_1_1_v_g_a_controller.html#aa0ec3b010db626bc0014f93119a46f8f":[7,0,0,94,8], "classfabgl_1_1_v_g_a_controller.html#aa736ad5f187de5c21088de98acafcb02":[7,0,0,94,13], "classfabgl_1_1_v_g_a_controller.html#aaa2d1522cce88d3ca2717db380f2e692":[7,0,0,94,22], "classfabgl_1_1_v_g_a_controller.html#aaae49991e2b9cb391cf97786612f59c1":[7,0,0,94,4], "classfabgl_1_1_v_g_a_controller.html#ab261f12432eea2de7530e3787412586d":[7,0,0,94,17], "classfabgl_1_1_v_g_a_controller.html#abaaf0f6e938018660ab0b15d073e5821":[7,0,0,94,2], "classfabgl_1_1_v_g_a_controller.html#ac1080e32a32fc6b8339575223c5e6574":[7,0,0,94,30], "classfabgl_1_1_v_g_a_controller.html#ac16c89bbf7ab603912b73cf2e0624d1a":[7,0,0,94,26], "classfabgl_1_1_v_g_a_controller.html#ac5ce66824aa948074c07002b8edf4b62":[7,0,0,94,15], "classfabgl_1_1_v_g_a_controller.html#ae00f244127ad138d378ec0fcc9c6ef36":[7,0,0,94,31], "classfabgl_1_1_v_g_a_controller.html#ae5843958fc71b17ee900fbd4297acdcd":[7,0,0,94,23], "classfabgl_1_1_v_g_a_controller.html#af5488939dfd5c3fe1481bc6f87c707b3":[7,0,0,94,20], "classfabgl_1_1_v_g_a_controller.html#afd008a0de0eaec247e4810d1a9afb924":[7,0,0,94,6], "classfabgl_1_1_v_g_a_text_controller.html":[7,0,0,95], "classfabgl_1_1_v_g_a_text_controller.html#a0d0c9197a495ed85cd9bc9a3525c5291":[7,0,0,95,2], "classfabgl_1_1_v_g_a_text_controller.html#a1b6c8ff133ab82213dcb512a50195603":[7,0,0,95,1], "classfabgl_1_1_v_g_a_text_controller.html#a7479b5046b15710c0bf0637338c0a047":[7,0,0,95,7], "classfabgl_1_1_v_g_a_text_controller.html#a7bb82fecb4a421a16439507f09d93e8b":[7,0,0,95,5], "classfabgl_1_1_v_g_a_text_controller.html#a7efa04f1999f53ee90adde56e032f9b4":[7,0,0,95,4], "classfabgl_1_1_v_g_a_text_controller.html#a857994ccd587b33f618c8f4a9ba99379":[7,0,0,95,3], "classfabgl_1_1_v_g_a_text_controller.html#aab6e3a3130a088e1c97ceb5d76ac5475":[7,0,0,95,0], "classfabgl_1_1_v_g_a_text_controller.html#abb7479cf592f81319f3cc064e73d0182":[7,0,0,95,6], "classfabgl_1_1_v_g_a_text_controller.html#aea018a6c891a6e35089afe984513c572":[7,0,0,95,8], "classfabgl_1_1_v_i_c_noise_generator.html":[7,0,0,97], "classfabgl_1_1_v_i_c_noise_generator.html#a3609e56aeabaca8f1abead8f3c5dbaf2":[7,0,0,97,8], "classfabgl_1_1_v_i_c_noise_generator.html#a3997ed6c38469277ecb1f7aee3d1d16d":[7,0,0,97,0], "classfabgl_1_1_v_i_c_noise_generator.html#a3f07b1ecc429aca6a2f6bc4fac58aeda":[7,0,0,97,1], "classfabgl_1_1_v_i_c_noise_generator.html#a748a2471c112f1c9174c98ef7e3b5a4a":[7,0,0,97,6], "classfabgl_1_1_v_i_c_noise_generator.html#a82e33967b946c874baa79fb8f44d4092":[7,0,0,97,10], "classfabgl_1_1_v_i_c_noise_generator.html#a991950a06c627d12eb907be8f72a2fec":[7,0,0,97,5], "classfabgl_1_1_v_i_c_noise_generator.html#a9ed2561601ab702b0f0cc7f91da83f88":[7,0,0,97,2], "classfabgl_1_1_v_i_c_noise_generator.html#aaa38bc65bc96ee15966b8bca6d50cb62":[7,0,0,97,9], "classfabgl_1_1_v_i_c_noise_generator.html#ad6154860ff73ddc630c45d1824baf00c":[7,0,0,97,4], "classfabgl_1_1_v_i_c_noise_generator.html#ae1b07155e13f5e82581c05d9cb4fe71e":[7,0,0,97,7], "classfabgl_1_1_v_i_c_noise_generator.html#aeb019e42701d54a43c8bb0e33488e967":[7,0,0,97,3], "classfabgl_1_1_v_i_c_noise_generator.html#aff943804948eae06f7509bf69ef51f05":[7,0,0,97,11], "classfabgl_1_1_waveform_generator.html":[7,0,0,99], "classfabgl_1_1_waveform_generator.html#a3997ed6c38469277ecb1f7aee3d1d16d":[7,0,0,99,0], "classfabgl_1_1_waveform_generator.html#a3f07b1ecc429aca6a2f6bc4fac58aeda":[7,0,0,99,1], "classfabgl_1_1_waveform_generator.html#a41fcee4e8dec08daca32045ad41e9f53":[7,0,0,99,3], "classfabgl_1_1_waveform_generator.html#a748a2471c112f1c9174c98ef7e3b5a4a":[7,0,0,99,6], "classfabgl_1_1_waveform_generator.html#a82e33967b946c874baa79fb8f44d4092":[7,0,0,99,10], "classfabgl_1_1_waveform_generator.html#a991950a06c627d12eb907be8f72a2fec":[7,0,0,99,5], "classfabgl_1_1_waveform_generator.html#a9ed2561601ab702b0f0cc7f91da83f88":[7,0,0,99,2], "classfabgl_1_1_waveform_generator.html#aaa38bc65bc96ee15966b8bca6d50cb62":[7,0,0,99,9], "classfabgl_1_1_waveform_generator.html#ac6f831361d9087d2e52e36b5eafed967":[7,0,0,99,8], "classfabgl_1_1_waveform_generator.html#ad6154860ff73ddc630c45d1824baf00c":[7,0,0,99,4], "classfabgl_1_1_waveform_generator.html#ae1b07155e13f5e82581c05d9cb4fe71e":[7,0,0,99,7], "classfabgl_1_1_waveform_generator.html#aff943804948eae06f7509bf69ef51f05":[7,0,0,99,11], "classfabgl_1_1ui_app.html":[7,0,0,48], "classfabgl_1_1ui_app.html#a0192d896b39a2c0265b87c7f39d32b59":[7,0,0,48,3], "classfabgl_1_1ui_app.html#a05a6271de5e4925cff22073bf48f7952":[7,0,0,48,4], "classfabgl_1_1ui_app.html#a1b38652b37ee1438d6832660a824a9e7":[7,0,0,48,10], "classfabgl_1_1ui_app.html#a2827139ff542f663753683dd90ae1c16":[7,0,0,48,25], "classfabgl_1_1ui_app.html#a28d5e0a0e711f84215f6435e29754c1d":[7,0,0,48,39], "classfabgl_1_1ui_app.html#a3b064db7d90f05a37fe70533811455ba":[7,0,0,48,38], "classfabgl_1_1ui_app.html#a3dd886b08dc0cd588edff12ca093ed73":[7,0,0,48,26], "classfabgl_1_1ui_app.html#a431860c2985484bf3d2f136075146d8c":[7,0,0,48,35], "classfabgl_1_1ui_app.html#a44b68bf7a9d9712c123eac4b5525d181":[7,0,0,48,36], "classfabgl_1_1ui_app.html#a55fabea8349dd5282b80ace47dd5fda1":[7,0,0,48,31], "classfabgl_1_1ui_app.html#a5d9e0d168144bdc2d838fcd43aa7c9aa":[7,0,0,48,5], "classfabgl_1_1ui_app.html#a68077cf2afc33bb423e924fa5bcfa4f8":[7,0,0,48,23], "classfabgl_1_1ui_app.html#a6ed22ad4af635c027637db8807b6a9af":[7,0,0,48,27], "classfabgl_1_1ui_app.html#a720fa1bbd49df02213234328814ea0ff":[7,0,0,48,37], "classfabgl_1_1ui_app.html#a74260184a9dd8e9dfb3d2106feda9a7e":[7,0,0,48,30], "classfabgl_1_1ui_app.html#a77aa2e78b40ecf2f29e8180b30272d84":[7,0,0,48,8], "classfabgl_1_1ui_app.html#a7ff4ce4e13be33ca40959adfd7c3edb8":[7,0,0,48,20], "classfabgl_1_1ui_app.html#a88d9a7c51e4ef93b617d3dc483fa293d":[7,0,0,48,16], "classfabgl_1_1ui_app.html#a8bda82c9f53c538ab1fb3edb7d6f25d0":[7,0,0,48,17], "classfabgl_1_1ui_app.html#a8d59a05eaedc8f165178fc412e475394":[7,0,0,48,11], "classfabgl_1_1ui_app.html#a93618eccc73d66e981f8c02170875226":[7,0,0,48,18], "classfabgl_1_1ui_app.html#a93a96823b4a884c8cb4141383197837f":[7,0,0,48,0], "classfabgl_1_1ui_app.html#a96d17d0396113602bd2367a7f0c09492":[7,0,0,48,1], "classfabgl_1_1ui_app.html#a9ae6a6ec628a81da2c936deb63d9ca0e":[7,0,0,48,24], "classfabgl_1_1ui_app.html#a9d02447c5bc871d783d5d7ba57483929":[7,0,0,48,21], "classfabgl_1_1ui_app.html#aa1dc4b980216c98b8a693ba15bf87065":[7,0,0,48,9], "classfabgl_1_1ui_app.html#aa9e48af5ad63a3cb3060ae3171a08969":[7,0,0,48,34], "classfabgl_1_1ui_app.html#aaa42ff6a21e47f3fbb761c20347390a4":[7,0,0,48,33], "classfabgl_1_1ui_app.html#aadc98d9de237a32bcff2f63a9b3129f2":[7,0,0,48,22], "classfabgl_1_1ui_app.html#ab716b086b3e3013a0967bd35a3a7e6d4":[7,0,0,48,32], "classfabgl_1_1ui_app.html#aba04179c4fc7e695c58022629b3983da":[7,0,0,48,12], "classfabgl_1_1ui_app.html#abd745cf2c678274d91003403433b5a40":[7,0,0,48,28], "classfabgl_1_1ui_app.html#ac462bde3e4a0084396e727e2c3a85004":[7,0,0,48,2], "classfabgl_1_1ui_app.html#ac656798fd31a27213c2f8bf5f0433bfa":[7,0,0,48,19], "classfabgl_1_1ui_app.html#ad2c90364f95b06bccc5ac585da94b1c3":[7,0,0,48,29], "classfabgl_1_1ui_app.html#ad7e36716653703be98d54d3ec55d1aaa":[7,0,0,48,15], "classfabgl_1_1ui_app.html#add1a241eb65b95232d28a469c025e46c":[7,0,0,48,14], "classfabgl_1_1ui_app.html#ae4ee677b3ec3ee727ede27010cae8798":[7,0,0,48,7], "classfabgl_1_1ui_app.html#ae5d4a0245850056343938ef814726407":[7,0,0,48,13], "classfabgl_1_1ui_app.html#aeaa73b91e36c97bbbee6a8b1b989f625":[7,0,0,48,6], "classfabgl_1_1ui_button.html":[7,0,0,50], "classfabgl_1_1ui_button.html#a07502831b1868e591781c24316570ea0":[7,0,0,50,39], "classfabgl_1_1ui_button.html#a089762995d65c9282f545a376810c055":[7,0,0,50,4], "classfabgl_1_1ui_button.html#a0f99de29b80538213ccbb22ee3cf7bdb":[7,0,0,50,27], "classfabgl_1_1ui_button.html#a12aa63ec46d29c74b6db844a67a4132b":[7,0,0,50,1], "classfabgl_1_1ui_button.html#a18735a70e697ff18647ce7034e9b480c":[7,0,0,50,13], "classfabgl_1_1ui_button.html#a1af6b3b72ee09464a86babf436f3121f":[7,0,0,50,9], "classfabgl_1_1ui_button.html#a2501acfdc9a197a1d1aae77c8c755bdb":[7,0,0,50,34], "classfabgl_1_1ui_button.html#a255c095f02a3d23689856ffad66aebc3":[7,0,0,50,25], "classfabgl_1_1ui_button.html#a2815a9866e3f3c11b4b9ca85d5cd858a":[7,0,0,50,18], "classfabgl_1_1ui_button.html#a28c8bf12d13b6eadbc05bc64a65c33c0":[7,0,0,50,11], "classfabgl_1_1ui_button.html#a31846cbe8d90b9effac80a15bb541bb2":[7,0,0,50,33], "classfabgl_1_1ui_button.html#a3d60b8c35960cbfb6688aca9073784b7":[7,0,0,50,3], "classfabgl_1_1ui_button.html#a4e8935392003598877aac433827d4b42":[7,0,0,50,41], "classfabgl_1_1ui_button.html#a50f29dabe9a4c99dfdb01d252fa173f4":[7,0,0,50,32], "classfabgl_1_1ui_button.html#a66c382ed75bd6bd40693c34eb41e1138":[7,0,0,50,16], "classfabgl_1_1ui_button.html#a770f88193b45a54df6f944efe1fc25d5":[7,0,0,50,6], "classfabgl_1_1ui_button.html#a7dda3febd65ff81f639eb07fa45c10be":[7,0,0,50,35], "classfabgl_1_1ui_button.html#a816b2248826f6f182df7f0e804712784":[7,0,0,50,22], "classfabgl_1_1ui_button.html#a8723fdee4c289c10af882284d4f6c191":[7,0,0,50,37], "classfabgl_1_1ui_button.html#a8a314b4877419783308d71f688339d14":[7,0,0,50,40], "classfabgl_1_1ui_button.html#a9004255d52a55f34ffa56731ac1add9d":[7,0,0,50,0], "classfabgl_1_1ui_button.html#a906aa0c527b912e79c4ebbc0ca2b7a74":[7,0,0,50,7], "classfabgl_1_1ui_button.html#a90e462004b5bbd74d5d981ddcbf5a38a":[7,0,0,50,28], "classfabgl_1_1ui_button.html#a93618eccc73d66e981f8c02170875226":[7,0,0,50,19], "classfabgl_1_1ui_button.html#a96d17d0396113602bd2367a7f0c09492":[7,0,0,50,2], "classfabgl_1_1ui_button.html#a98f5b2828f58c2dcf9832ed7a52669b1":[7,0,0,50,17], "classfabgl_1_1ui_button.html#a9a5f66fd22b7c2d08db466f76d8b4088":[7,0,0,50,15], "classfabgl_1_1ui_button.html#a9be2ddbe0bd611d553f11722297789ee":[7,0,0,50,29], "classfabgl_1_1ui_button.html#aa333a558758b6c4ce97ccc9c92663dce":[7,0,0,50,21], "classfabgl_1_1ui_button.html#ab0949695ec9e34377724f26e0dc7fa31":[7,0,0,50,5], "classfabgl_1_1ui_button.html#aba6b75880074a221f215486ebb675a6c":[7,0,0,50,24], "classfabgl_1_1ui_button.html#abcd9c544e7c4d62b0c2a092296f2dedb":[7,0,0,50,20], "classfabgl_1_1ui_button.html#ac2c887ae821ce1a3f64f5888408c121e":[7,0,0,50,8], "classfabgl_1_1ui_button.html#ac952f5d603f8e2565e36e3549563a548":[7,0,0,50,14], "classfabgl_1_1ui_button.html#acc966ed4cd8d335139580fcf9995db21":[7,0,0,50,23], "classfabgl_1_1ui_button.html#ad1986d853fc82a7084467fea41e7a684":[7,0,0,50,26], "classfabgl_1_1ui_button.html#ad4a6f53a4642fe6497ea7695b7812ea4":[7,0,0,50,31], "classfabgl_1_1ui_button.html#ad8348bf5ff940271dca5e42018c10025":[7,0,0,50,30], "classfabgl_1_1ui_button.html#ade72949808b8fc1c345dc696b31e33bf":[7,0,0,50,10], "classfabgl_1_1ui_button.html#ae16282f1881ec8ded65ad239f3d17735":[7,0,0,50,36], "classfabgl_1_1ui_button.html#afe4a4306d8c4225e04a933701df99000":[7,0,0,50,38], "classfabgl_1_1ui_button.html#affd6f6e94bee7b5e370a3f772173d895":[7,0,0,50,12], "classfabgl_1_1ui_check_box.html":[7,0,0,52], "classfabgl_1_1ui_check_box.html#a089762995d65c9282f545a376810c055":[7,0,0,52,4], "classfabgl_1_1ui_check_box.html#a12aa63ec46d29c74b6db844a67a4132b":[7,0,0,52,1], "classfabgl_1_1ui_check_box.html#a18735a70e697ff18647ce7034e9b480c":[7,0,0,52,14], "classfabgl_1_1ui_check_box.html#a2501acfdc9a197a1d1aae77c8c755bdb":[7,0,0,52,35], "classfabgl_1_1ui_check_box.html#a255c095f02a3d23689856ffad66aebc3":[7,0,0,52,26], "classfabgl_1_1ui_check_box.html#a2815a9866e3f3c11b4b9ca85d5cd858a":[7,0,0,52,19], "classfabgl_1_1ui_check_box.html#a28c8bf12d13b6eadbc05bc64a65c33c0":[7,0,0,52,11], "classfabgl_1_1ui_check_box.html#a2c12f6e69cbbaf70f45757b9f767f46c":[7,0,0,52,30], "classfabgl_1_1ui_check_box.html#a31846cbe8d90b9effac80a15bb541bb2":[7,0,0,52,34], "classfabgl_1_1ui_check_box.html#a3d60b8c35960cbfb6688aca9073784b7":[7,0,0,52,3], "classfabgl_1_1ui_check_box.html#a4e8935392003598877aac433827d4b42":[7,0,0,52,41], "classfabgl_1_1ui_check_box.html#a50f29dabe9a4c99dfdb01d252fa173f4":[7,0,0,52,33], "classfabgl_1_1ui_check_box.html#a66c382ed75bd6bd40693c34eb41e1138":[7,0,0,52,17], "classfabgl_1_1ui_check_box.html#a6a31feb592b1ed700fb61acd4a708e40":[7,0,0,52,0], "classfabgl_1_1ui_check_box.html#a770f88193b45a54df6f944efe1fc25d5":[7,0,0,52,7], "classfabgl_1_1ui_check_box.html#a816b2248826f6f182df7f0e804712784":[7,0,0,52,23], "classfabgl_1_1ui_check_box.html#a8723fdee4c289c10af882284d4f6c191":[7,0,0,52,37], "classfabgl_1_1ui_check_box.html#a8a314b4877419783308d71f688339d14":[7,0,0,52,40], "classfabgl_1_1ui_check_box.html#a8fccf14dc0d57e3040f39d859b93a4a3":[7,0,0,52,28], "classfabgl_1_1ui_check_box.html#a906aa0c527b912e79c4ebbc0ca2b7a74":[7,0,0,52,8], "classfabgl_1_1ui_check_box.html#a90e462004b5bbd74d5d981ddcbf5a38a":[7,0,0,52,29], "classfabgl_1_1ui_check_box.html#a93618eccc73d66e981f8c02170875226":[7,0,0,52,20], "classfabgl_1_1ui_check_box.html#a96d17d0396113602bd2367a7f0c09492":[7,0,0,52,2], "classfabgl_1_1ui_check_box.html#a98f5b2828f58c2dcf9832ed7a52669b1":[7,0,0,52,18], "classfabgl_1_1ui_check_box.html#a9a5f66fd22b7c2d08db466f76d8b4088":[7,0,0,52,16], "classfabgl_1_1ui_check_box.html#a9be2ddbe0bd611d553f11722297789ee":[7,0,0,52,31], "classfabgl_1_1ui_check_box.html#aa333a558758b6c4ce97ccc9c92663dce":[7,0,0,52,22], "classfabgl_1_1ui_check_box.html#aa9e5e827623091f7fe16ded0b6e94555":[7,0,0,52,5], "classfabgl_1_1ui_check_box.html#ab8c4606b0f5cfd7182da12f7897b6b02":[7,0,0,52,13], "classfabgl_1_1ui_check_box.html#aba6b75880074a221f215486ebb675a6c":[7,0,0,52,25], "classfabgl_1_1ui_check_box.html#abcd9c544e7c4d62b0c2a092296f2dedb":[7,0,0,52,21], "classfabgl_1_1ui_check_box.html#ac2c887ae821ce1a3f64f5888408c121e":[7,0,0,52,9], "classfabgl_1_1ui_check_box.html#ac952f5d603f8e2565e36e3549563a548":[7,0,0,52,15], "classfabgl_1_1ui_check_box.html#acc966ed4cd8d335139580fcf9995db21":[7,0,0,52,24], "classfabgl_1_1ui_check_box.html#ad1986d853fc82a7084467fea41e7a684":[7,0,0,52,27], "classfabgl_1_1ui_check_box.html#ad7f3084c4430175cbe9274e5fe3e7740":[7,0,0,52,39], "classfabgl_1_1ui_check_box.html#ad8348bf5ff940271dca5e42018c10025":[7,0,0,52,32], "classfabgl_1_1ui_check_box.html#ade72949808b8fc1c345dc696b31e33bf":[7,0,0,52,10], "classfabgl_1_1ui_check_box.html#ae16282f1881ec8ded65ad239f3d17735":[7,0,0,52,36], "classfabgl_1_1ui_check_box.html#ae1f15607b213f624893240f618847732":[7,0,0,52,6], "classfabgl_1_1ui_check_box.html#afe4a4306d8c4225e04a933701df99000":[7,0,0,52,38], "classfabgl_1_1ui_check_box.html#affd6f6e94bee7b5e370a3f772173d895":[7,0,0,52,12], "classfabgl_1_1ui_color_box.html":[7,0,0,54], "classfabgl_1_1ui_color_box.html#a089762995d65c9282f545a376810c055":[7,0,0,54,4], "classfabgl_1_1ui_color_box.html#a12aa63ec46d29c74b6db844a67a4132b":[7,0,0,54,1], "classfabgl_1_1ui_color_box.html#a16ae960104beb3d37d521a060fc81fcc":[7,0,0,54,26], "classfabgl_1_1ui_color_box.html#a18735a70e697ff18647ce7034e9b480c":[7,0,0,54,12], "classfabgl_1_1ui_color_box.html#a2501acfdc9a197a1d1aae77c8c755bdb":[7,0,0,54,32], "classfabgl_1_1ui_color_box.html#a255c095f02a3d23689856ffad66aebc3":[7,0,0,54,24], "classfabgl_1_1ui_color_box.html#a2815a9866e3f3c11b4b9ca85d5cd858a":[7,0,0,54,17], "classfabgl_1_1ui_color_box.html#a28c8bf12d13b6eadbc05bc64a65c33c0":[7,0,0,54,10], "classfabgl_1_1ui_color_box.html#a31846cbe8d90b9effac80a15bb541bb2":[7,0,0,54,31], "classfabgl_1_1ui_color_box.html#a3d60b8c35960cbfb6688aca9073784b7":[7,0,0,54,3], "classfabgl_1_1ui_color_box.html#a3df056422ce8e19bee7bba95ddcf3e29":[7,0,0,54,0], "classfabgl_1_1ui_color_box.html#a4e8935392003598877aac433827d4b42":[7,0,0,54,37], "classfabgl_1_1ui_color_box.html#a50f29dabe9a4c99dfdb01d252fa173f4":[7,0,0,54,30], "classfabgl_1_1ui_color_box.html#a66c382ed75bd6bd40693c34eb41e1138":[7,0,0,54,15], "classfabgl_1_1ui_color_box.html#a770f88193b45a54df6f944efe1fc25d5":[7,0,0,54,5], "classfabgl_1_1ui_color_box.html#a816b2248826f6f182df7f0e804712784":[7,0,0,54,21], "classfabgl_1_1ui_color_box.html#a8723fdee4c289c10af882284d4f6c191":[7,0,0,54,34], "classfabgl_1_1ui_color_box.html#a8a314b4877419783308d71f688339d14":[7,0,0,54,36], "classfabgl_1_1ui_color_box.html#a906aa0c527b912e79c4ebbc0ca2b7a74":[7,0,0,54,6], "classfabgl_1_1ui_color_box.html#a90e462004b5bbd74d5d981ddcbf5a38a":[7,0,0,54,27], "classfabgl_1_1ui_color_box.html#a9247f51a999e40eaa52fcaa6f62047ef":[7,0,0,54,8], "classfabgl_1_1ui_color_box.html#a93618eccc73d66e981f8c02170875226":[7,0,0,54,18], "classfabgl_1_1ui_color_box.html#a96d17d0396113602bd2367a7f0c09492":[7,0,0,54,2], "classfabgl_1_1ui_color_box.html#a98f5b2828f58c2dcf9832ed7a52669b1":[7,0,0,54,16], "classfabgl_1_1ui_color_box.html#a9a5f66fd22b7c2d08db466f76d8b4088":[7,0,0,54,14], "classfabgl_1_1ui_color_box.html#a9be2ddbe0bd611d553f11722297789ee":[7,0,0,54,28], "classfabgl_1_1ui_color_box.html#aa333a558758b6c4ce97ccc9c92663dce":[7,0,0,54,20], "classfabgl_1_1ui_color_box.html#aba6b75880074a221f215486ebb675a6c":[7,0,0,54,23], "classfabgl_1_1ui_color_box.html#abcd9c544e7c4d62b0c2a092296f2dedb":[7,0,0,54,19], "classfabgl_1_1ui_color_box.html#ac2c887ae821ce1a3f64f5888408c121e":[7,0,0,54,7], "classfabgl_1_1ui_color_box.html#ac952f5d603f8e2565e36e3549563a548":[7,0,0,54,13], "classfabgl_1_1ui_color_box.html#acc966ed4cd8d335139580fcf9995db21":[7,0,0,54,22], "classfabgl_1_1ui_color_box.html#ad1986d853fc82a7084467fea41e7a684":[7,0,0,54,25], "classfabgl_1_1ui_color_box.html#ad8348bf5ff940271dca5e42018c10025":[7,0,0,54,29], "classfabgl_1_1ui_color_box.html#ade72949808b8fc1c345dc696b31e33bf":[7,0,0,54,9], "classfabgl_1_1ui_color_box.html#ae16282f1881ec8ded65ad239f3d17735":[7,0,0,54,33], "classfabgl_1_1ui_color_box.html#afe4a4306d8c4225e04a933701df99000":[7,0,0,54,35], "classfabgl_1_1ui_color_box.html#affd6f6e94bee7b5e370a3f772173d895":[7,0,0,54,11], "classfabgl_1_1ui_color_combo_box.html":[7,0,0,55] };
{ "pile_set_name": "Github" }
// Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma // de Barcelona (UAB). // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #include "Carla.h" #include "TrafficSignBase.h" #include "SignComponent.h" ATrafficSignBase::ATrafficSignBase(const FObjectInitializer &ObjectInitializer) : Super(ObjectInitializer) { PrimaryActorTick.bCanEverTick = false; RootComponent = ObjectInitializer.CreateDefaultSubobject<USceneComponent>(this, TEXT("SceneRootComponent")); RootComponent->SetMobility(EComponentMobility::Static); } TArray<UBoxComponent*> ATrafficSignBase::GetTriggerVolumes() const { TArray<USignComponent*> Components; GetComponents<USignComponent>(Components, false); if (Components.Num()) { USignComponent* SignComponent = Components.Top(); return SignComponent->GetEffectTriggerVolume(); } else { TArray<UBoxComponent*> TriggerVolumes; TriggerVolumes.Add(GetTriggerVolume()); return TriggerVolumes; } }
{ "pile_set_name": "Github" }
#include "lut.h" const COMPLEX16 MAPA_16QAM_LUT[MAPA_16QAM_LUT_SIZE] = { {-10169, -10169}, {-10169, -10169}, { 10169, -10169}, {-10169, -10169}, { -3389, -10169}, {-10169, -10169}, { 3389, -10169}, {-10169, -10169}, {-10169, 10169}, {-10169, -10169}, { 10169, 10169}, {-10169, -10169}, { -3389, 10169}, {-10169, -10169}, { 3389, 10169}, {-10169, -10169}, {-10169, -3389}, {-10169, -10169}, { 10169, -3389}, {-10169, -10169}, { -3389, -3389}, {-10169, -10169}, { 3389, -3389}, {-10169, -10169}, {-10169, 3389}, {-10169, -10169}, { 10169, 3389}, {-10169, -10169}, { -3389, 3389}, {-10169, -10169}, { 3389, 3389}, {-10169, -10169}, {-10169, -10169}, { 10169, -10169}, { 10169, -10169}, { 10169, -10169}, { -3389, -10169}, { 10169, -10169}, { 3389, -10169}, { 10169, -10169}, {-10169, 10169}, { 10169, -10169}, { 10169, 10169}, { 10169, -10169}, { -3389, 10169}, { 10169, -10169}, { 3389, 10169}, { 10169, -10169}, {-10169, -3389}, { 10169, -10169}, { 10169, -3389}, { 10169, -10169}, { -3389, -3389}, { 10169, -10169}, { 3389, -3389}, { 10169, -10169}, {-10169, 3389}, { 10169, -10169}, { 10169, 3389}, { 10169, -10169}, { -3389, 3389}, { 10169, -10169}, { 3389, 3389}, { 10169, -10169}, {-10169, -10169}, { -3389, -10169}, { 10169, -10169}, { -3389, -10169}, { -3389, -10169}, { -3389, -10169}, { 3389, -10169}, { -3389, -10169}, {-10169, 10169}, { -3389, -10169}, { 10169, 10169}, { -3389, -10169}, { -3389, 10169}, { -3389, -10169}, { 3389, 10169}, { -3389, -10169}, {-10169, -3389}, { -3389, -10169}, { 10169, -3389}, { -3389, -10169}, { -3389, -3389}, { -3389, -10169}, { 3389, -3389}, { -3389, -10169}, {-10169, 3389}, { -3389, -10169}, { 10169, 3389}, { -3389, -10169}, { -3389, 3389}, { -3389, -10169}, { 3389, 3389}, { -3389, -10169}, {-10169, -10169}, { 3389, -10169}, { 10169, -10169}, { 3389, -10169}, { -3389, -10169}, { 3389, -10169}, { 3389, -10169}, { 3389, -10169}, {-10169, 10169}, { 3389, -10169}, { 10169, 10169}, { 3389, -10169}, { -3389, 10169}, { 3389, -10169}, { 3389, 10169}, { 3389, -10169}, {-10169, -3389}, { 3389, -10169}, { 10169, -3389}, { 3389, -10169}, { -3389, -3389}, { 3389, -10169}, { 3389, -3389}, { 3389, -10169}, {-10169, 3389}, { 3389, -10169}, { 10169, 3389}, { 3389, -10169}, { -3389, 3389}, { 3389, -10169}, { 3389, 3389}, { 3389, -10169}, {-10169, -10169}, {-10169, 10169}, { 10169, -10169}, {-10169, 10169}, { -3389, -10169}, {-10169, 10169}, { 3389, -10169}, {-10169, 10169}, {-10169, 10169}, {-10169, 10169}, { 10169, 10169}, {-10169, 10169}, { -3389, 10169}, {-10169, 10169}, { 3389, 10169}, {-10169, 10169}, {-10169, -3389}, {-10169, 10169}, { 10169, -3389}, {-10169, 10169}, { -3389, -3389}, {-10169, 10169}, { 3389, -3389}, {-10169, 10169}, {-10169, 3389}, {-10169, 10169}, { 10169, 3389}, {-10169, 10169}, { -3389, 3389}, {-10169, 10169}, { 3389, 3389}, {-10169, 10169}, {-10169, -10169}, { 10169, 10169}, { 10169, -10169}, { 10169, 10169}, { -3389, -10169}, { 10169, 10169}, { 3389, -10169}, { 10169, 10169}, {-10169, 10169}, { 10169, 10169}, { 10169, 10169}, { 10169, 10169}, { -3389, 10169}, { 10169, 10169}, { 3389, 10169}, { 10169, 10169}, {-10169, -3389}, { 10169, 10169}, { 10169, -3389}, { 10169, 10169}, { -3389, -3389}, { 10169, 10169}, { 3389, -3389}, { 10169, 10169}, {-10169, 3389}, { 10169, 10169}, { 10169, 3389}, { 10169, 10169}, { -3389, 3389}, { 10169, 10169}, { 3389, 3389}, { 10169, 10169}, {-10169, -10169}, { -3389, 10169}, { 10169, -10169}, { -3389, 10169}, { -3389, -10169}, { -3389, 10169}, { 3389, -10169}, { -3389, 10169}, {-10169, 10169}, { -3389, 10169}, { 10169, 10169}, { -3389, 10169}, { -3389, 10169}, { -3389, 10169}, { 3389, 10169}, { -3389, 10169}, {-10169, -3389}, { -3389, 10169}, { 10169, -3389}, { -3389, 10169}, { -3389, -3389}, { -3389, 10169}, { 3389, -3389}, { -3389, 10169}, {-10169, 3389}, { -3389, 10169}, { 10169, 3389}, { -3389, 10169}, { -3389, 3389}, { -3389, 10169}, { 3389, 3389}, { -3389, 10169}, {-10169, -10169}, { 3389, 10169}, { 10169, -10169}, { 3389, 10169}, { -3389, -10169}, { 3389, 10169}, { 3389, -10169}, { 3389, 10169}, {-10169, 10169}, { 3389, 10169}, { 10169, 10169}, { 3389, 10169}, { -3389, 10169}, { 3389, 10169}, { 3389, 10169}, { 3389, 10169}, {-10169, -3389}, { 3389, 10169}, { 10169, -3389}, { 3389, 10169}, { -3389, -3389}, { 3389, 10169}, { 3389, -3389}, { 3389, 10169}, {-10169, 3389}, { 3389, 10169}, { 10169, 3389}, { 3389, 10169}, { -3389, 3389}, { 3389, 10169}, { 3389, 3389}, { 3389, 10169}, {-10169, -10169}, {-10169, -3389}, { 10169, -10169}, {-10169, -3389}, { -3389, -10169}, {-10169, -3389}, { 3389, -10169}, {-10169, -3389}, {-10169, 10169}, {-10169, -3389}, { 10169, 10169}, {-10169, -3389}, { -3389, 10169}, {-10169, -3389}, { 3389, 10169}, {-10169, -3389}, {-10169, -3389}, {-10169, -3389}, { 10169, -3389}, {-10169, -3389}, { -3389, -3389}, {-10169, -3389}, { 3389, -3389}, {-10169, -3389}, {-10169, 3389}, {-10169, -3389}, { 10169, 3389}, {-10169, -3389}, { -3389, 3389}, {-10169, -3389}, { 3389, 3389}, {-10169, -3389}, {-10169, -10169}, { 10169, -3389}, { 10169, -10169}, { 10169, -3389}, { -3389, -10169}, { 10169, -3389}, { 3389, -10169}, { 10169, -3389}, {-10169, 10169}, { 10169, -3389}, { 10169, 10169}, { 10169, -3389}, { -3389, 10169}, { 10169, -3389}, { 3389, 10169}, { 10169, -3389}, {-10169, -3389}, { 10169, -3389}, { 10169, -3389}, { 10169, -3389}, { -3389, -3389}, { 10169, -3389}, { 3389, -3389}, { 10169, -3389}, {-10169, 3389}, { 10169, -3389}, { 10169, 3389}, { 10169, -3389}, { -3389, 3389}, { 10169, -3389}, { 3389, 3389}, { 10169, -3389}, {-10169, -10169}, { -3389, -3389}, { 10169, -10169}, { -3389, -3389}, { -3389, -10169}, { -3389, -3389}, { 3389, -10169}, { -3389, -3389}, {-10169, 10169}, { -3389, -3389}, { 10169, 10169}, { -3389, -3389}, { -3389, 10169}, { -3389, -3389}, { 3389, 10169}, { -3389, -3389}, {-10169, -3389}, { -3389, -3389}, { 10169, -3389}, { -3389, -3389}, { -3389, -3389}, { -3389, -3389}, { 3389, -3389}, { -3389, -3389}, {-10169, 3389}, { -3389, -3389}, { 10169, 3389}, { -3389, -3389}, { -3389, 3389}, { -3389, -3389}, { 3389, 3389}, { -3389, -3389}, {-10169, -10169}, { 3389, -3389}, { 10169, -10169}, { 3389, -3389}, { -3389, -10169}, { 3389, -3389}, { 3389, -10169}, { 3389, -3389}, {-10169, 10169}, { 3389, -3389}, { 10169, 10169}, { 3389, -3389}, { -3389, 10169}, { 3389, -3389}, { 3389, 10169}, { 3389, -3389}, {-10169, -3389}, { 3389, -3389}, { 10169, -3389}, { 3389, -3389}, { -3389, -3389}, { 3389, -3389}, { 3389, -3389}, { 3389, -3389}, {-10169, 3389}, { 3389, -3389}, { 10169, 3389}, { 3389, -3389}, { -3389, 3389}, { 3389, -3389}, { 3389, 3389}, { 3389, -3389}, {-10169, -10169}, {-10169, 3389}, { 10169, -10169}, {-10169, 3389}, { -3389, -10169}, {-10169, 3389}, { 3389, -10169}, {-10169, 3389}, {-10169, 10169}, {-10169, 3389}, { 10169, 10169}, {-10169, 3389}, { -3389, 10169}, {-10169, 3389}, { 3389, 10169}, {-10169, 3389}, {-10169, -3389}, {-10169, 3389}, { 10169, -3389}, {-10169, 3389}, { -3389, -3389}, {-10169, 3389}, { 3389, -3389}, {-10169, 3389}, {-10169, 3389}, {-10169, 3389}, { 10169, 3389}, {-10169, 3389}, { -3389, 3389}, {-10169, 3389}, { 3389, 3389}, {-10169, 3389}, {-10169, -10169}, { 10169, 3389}, { 10169, -10169}, { 10169, 3389}, { -3389, -10169}, { 10169, 3389}, { 3389, -10169}, { 10169, 3389}, {-10169, 10169}, { 10169, 3389}, { 10169, 10169}, { 10169, 3389}, { -3389, 10169}, { 10169, 3389}, { 3389, 10169}, { 10169, 3389}, {-10169, -3389}, { 10169, 3389}, { 10169, -3389}, { 10169, 3389}, { -3389, -3389}, { 10169, 3389}, { 3389, -3389}, { 10169, 3389}, {-10169, 3389}, { 10169, 3389}, { 10169, 3389}, { 10169, 3389}, { -3389, 3389}, { 10169, 3389}, { 3389, 3389}, { 10169, 3389}, {-10169, -10169}, { -3389, 3389}, { 10169, -10169}, { -3389, 3389}, { -3389, -10169}, { -3389, 3389}, { 3389, -10169}, { -3389, 3389}, {-10169, 10169}, { -3389, 3389}, { 10169, 10169}, { -3389, 3389}, { -3389, 10169}, { -3389, 3389}, { 3389, 10169}, { -3389, 3389}, {-10169, -3389}, { -3389, 3389}, { 10169, -3389}, { -3389, 3389}, { -3389, -3389}, { -3389, 3389}, { 3389, -3389}, { -3389, 3389}, {-10169, 3389}, { -3389, 3389}, { 10169, 3389}, { -3389, 3389}, { -3389, 3389}, { -3389, 3389}, { 3389, 3389}, { -3389, 3389}, {-10169, -10169}, { 3389, 3389}, { 10169, -10169}, { 3389, 3389}, { -3389, -10169}, { 3389, 3389}, { 3389, -10169}, { 3389, 3389}, {-10169, 10169}, { 3389, 3389}, { 10169, 10169}, { 3389, 3389}, { -3389, 10169}, { 3389, 3389}, { 3389, 10169}, { 3389, 3389}, {-10169, -3389}, { 3389, 3389}, { 10169, -3389}, { 3389, 3389}, { -3389, -3389}, { 3389, 3389}, { 3389, -3389}, { 3389, 3389}, {-10169, 3389}, { 3389, 3389}, { 10169, 3389}, { 3389, 3389}, { -3389, 3389}, { 3389, 3389}, { 3389, 3389}, { 3389, 3389}, };
{ "pile_set_name": "Github" }
(* Copyright (C) 2015-2016 Bloomberg Finance L.P. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * In addition to the permissions granted to you by the LGPL, you may combine * or link a "work that uses the Library" with a publicly distributed version * of this file to produce a combined library or application, then distribute * that combined work under the terms of your choosing, with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 (or the corresponding section of a later version of the LGPL * should you choose to use a later version). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) val get : string -> int -> char val make : int -> char -> string
{ "pile_set_name": "Github" }
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file and, per its terms, should not be removed: * * Copyright (c) 2002 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. This program is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. * See W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.xpath; import org.w3c.dom.Node; import org.w3c.dom.DOMException; /** * The <code>XPathExpression</code> interface represents a parsed and resolved * XPath expression. * <p>See also the <a href='https://www.w3.org/TR/DOM-Level-3-XPath/'>Document Object Model (DOM) Level 3 XPath Specification</a>. */ public interface XPathExpression { /** * Evaluates this XPath expression and returns a result. * @param contextNode The <code>context</code> is context node for the * evaluation of this XPath expression.If the XPathEvaluator was * obtained by casting the <code>Document</code> then this must be * owned by the same document and must be a <code>Document</code>, * <code>Element</code>, <code>Attribute</code>, <code>Text</code>, * <code>CDATASection</code>, <code>Comment</code>, * <code>ProcessingInstruction</code>, or <code>XPathNamespace</code> * node.If the context node is a <code>Text</code> or a * <code>CDATASection</code>, then the context is interpreted as the * whole logical text node as seen by XPath, unless the node is empty * in which case it may not serve as the XPath context. * @param type If a specific <code>type</code> is specified, then the * result will be coerced to return the specified type relying on * XPath conversions and fail if the desired coercion is not possible. * This must be one of the type codes of <code>XPathResult</code>. * @param result The <code>result</code> specifies a specific result * object which may be reused and returned by this method. If this is * specified as <code>null</code>or the implementation does not reuse * the specified result, a new result object will be constructed and * returned.For XPath 1.0 results, this object will be of type * <code>XPathResult</code>. * @return The result of the evaluation of the XPath expression.For XPath * 1.0 results, this object will be of type <code>XPathResult</code>. * @exception XPathException * TYPE_ERR: Raised if the result cannot be converted to return the * specified type. * @exception DOMException * WRONG_DOCUMENT_ERR: The Node is from a document that is not supported * by the XPathEvaluator that created this <code>XPathExpression</code> * . * <br>NOT_SUPPORTED_ERR: The Node is not a type permitted as an XPath * context node or the request type is not permitted by this * <code>XPathExpression</code>. */ public Object evaluate(Node contextNode, short type, Object result) throws XPathException, DOMException; }
{ "pile_set_name": "Github" }
{ "ver": "1.0.4", "uuid": "881c322b-cbf1-4df0-b1df-a3ef74ff60ec", "subMetas": {} }
{ "pile_set_name": "Github" }
#include "cbase.h" #include "DoubleLabel.h" #include "util/mom_util.h" #include "fmtstr.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" using namespace vgui; DoubleLabel::DoubleLabel(Panel *parent, const char *panelName) : BaseClass(parent, panelName, "") { SetupSecondaryLabel(parent, CFmtStr("%sSecondary", panelName).Get(), ""); } DoubleLabel::DoubleLabel(Panel *parent, const char *panelName, const char *secondPanelName) : BaseClass(parent, panelName, "") { SetupSecondaryLabel(parent, secondPanelName, ""); } DoubleLabel::DoubleLabel(Panel *parent, const char *panelName, const char *text1, const char *text2) : BaseClass(parent, panelName, text1) { SetupSecondaryLabel(parent, CFmtStr("%sSecondary", panelName).Get(), text2); } DoubleLabel::DoubleLabel(Panel *parent, const char *panelName, const char *secondPanelName, const char *text1, const char *text2) : BaseClass(parent, panelName, text1) { SetupSecondaryLabel(parent, secondPanelName, text2); } void DoubleLabel::SetupSecondaryLabel(Panel *parent, const char *panelName, const char *text) { m_pSecondaryLabel = new Label(parent, panelName, text); m_pSecondaryLabel->SetAutoTall(true); } void DoubleLabel::PerformLayout() { BaseClass::PerformLayout(); char szMain[256], szSecondary[256]; GetText(szMain, sizeof(szMain), szSecondary, sizeof(szSecondary)); HFont labelFont = GetFont(); int iPrimaryTextLength = UTIL_ComputeStringWidth(labelFont, szMain); int iSecondaryTextLength = UTIL_ComputeStringWidth(labelFont, szSecondary); int iCombinedTextLength = iPrimaryTextLength + iSecondaryTextLength; // both labels have west content alignment by default // this alignment is for this class specifically switch (m_TextAlignment) { case a_northwest: case a_west: case a_southwest: SetPrimaryTextInset(0, 0); SetSecondaryTextInset(iPrimaryTextLength, 0); break; case a_center: SetPrimaryTextInset((GetWide() - iCombinedTextLength) / 2, 0); SetSecondaryTextInset((GetWide() + iPrimaryTextLength - iSecondaryTextLength) / 2, 0); break; case a_northeast: case a_east: case a_southeast: SetPrimaryTextInset(GetWide() - iCombinedTextLength, 0); SetSecondaryTextInset(GetWide() - iSecondaryTextLength, 0); break; default: break; } } void vgui::DoubleLabel::ApplySchemeSettings(vgui::IScheme *pScheme) { BaseClass::ApplySchemeSettings(pScheme); m_pSecondaryLabel->SetPos(GetXPos(), GetYPos()); m_pSecondaryLabel->SetWide(GetWide()); } void vgui::DoubleLabel::SetYPos(int y) { SetPos(GetXPos(), y); m_pSecondaryLabel->SetPos(GetXPos(), y); } void vgui::DoubleLabel::SetAlpha(int alpha) { BaseClass::SetAlpha(alpha); m_pSecondaryLabel->SetAlpha(alpha); } void vgui::DoubleLabel::SetWide(int wide) { BaseClass::SetWide(wide); m_pSecondaryLabel->SetWide(wide); } void DoubleLabel::SetFont(HFont font) { BaseClass::SetFont(font); m_pSecondaryLabel->SetFont(font); } void DoubleLabel::SetText(const char *textPrimary, const char *textSecondary) { BaseClass::SetText(textPrimary); m_pSecondaryLabel->SetText(textSecondary); } void DoubleLabel::SetText(const wchar_t *unicodeStringPrimary, const wchar_t *unicodeStringSecondary, bool bClearUnlocalizedSymbolPrimary, bool bClearUnlocalizedSymbolSecondary) { BaseClass::SetText(unicodeStringPrimary, bClearUnlocalizedSymbolPrimary); m_pSecondaryLabel->SetText(unicodeStringSecondary, bClearUnlocalizedSymbolSecondary); } void DoubleLabel::GetText(OUT_Z_BYTECAP(bufferLenPrimary) char *textOutPrimary, int bufferLenPrimary, OUT_Z_BYTECAP(bufferLenSecondary) char *textOutSecondary, int bufferLenSecondary) { BaseClass::GetText(textOutPrimary, bufferLenPrimary); m_pSecondaryLabel->GetText(textOutSecondary, bufferLenSecondary); } void DoubleLabel::SetFgColor(Color colorPrimary, Color colorSecondary) { BaseClass::SetFgColor(colorPrimary); m_pSecondaryLabel->SetFgColor(colorSecondary); } void DoubleLabel::GetFgColor(Color &colorPrimary, Color &colorSecondary) { colorPrimary = BaseClass::GetFgColor(); colorSecondary = m_pSecondaryLabel->GetFgColor(); } void DoubleLabel::SetTextInset(int xInsetPrimary, int yInsetPrimary, int xInsetSecondary, int yInsetSecondary) { BaseClass::SetTextInset(xInsetPrimary, yInsetPrimary); m_pSecondaryLabel->SetTextInset(xInsetSecondary, yInsetSecondary); } void vgui::DoubleLabel::SetVisible(bool statePrimary, bool stateSecondary) { BaseClass::SetVisible(statePrimary); m_pSecondaryLabel->SetVisible(stateSecondary); }
{ "pile_set_name": "Github" }
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // +k8s:deepcopy-gen=package // +k8s:openapi-gen=true package v2beta1 // import "k8s.io/api/autoscaling/v2beta1"
{ "pile_set_name": "Github" }
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.WafV2.Inputs { public sealed class WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementFieldToMatchUriPathArgs : Pulumi.ResourceArgs { public WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementFieldToMatchUriPathArgs() { } } }
{ "pile_set_name": "Github" }
bdb-description: The BDB environment used to store/load crawl history. historydb-name-description: The name of the database used to store/load crawl history.
{ "pile_set_name": "Github" }
class A { m() { soutm<caret> } }
{ "pile_set_name": "Github" }
package io.gitlab.arturbosch.detekt.rules import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.MultiRule import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.RuleSetProvider import io.gitlab.arturbosch.detekt.api.internal.BaseRule import io.gitlab.arturbosch.detekt.api.internal.DefaultRuleSetProvider import io.gitlab.arturbosch.detekt.rules.bugs.PotentialBugProvider import io.gitlab.arturbosch.detekt.rules.complexity.ComplexityProvider import io.gitlab.arturbosch.detekt.rules.coroutines.CoroutinesProvider import io.gitlab.arturbosch.detekt.rules.documentation.CommentSmellProvider import io.gitlab.arturbosch.detekt.rules.empty.EmptyCodeProvider import io.gitlab.arturbosch.detekt.rules.exceptions.ExceptionsProvider import io.gitlab.arturbosch.detekt.rules.naming.NamingProvider import io.gitlab.arturbosch.detekt.rules.performance.PerformanceProvider import io.gitlab.arturbosch.detekt.rules.style.StyleGuideProvider import org.assertj.core.api.Assertions.assertThat import org.reflections.Reflections import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.lang.reflect.Modifier class RuleProviderTest : Spek({ describe("Rule Provider") { it("checks whether all rules are called in the corresponding RuleSetProvider") { val reflections = Reflections("io.gitlab.arturbosch.detekt.rules") val providers = reflections.getSubTypesOf(DefaultRuleSetProvider::class.java) providers.forEach { providerType -> val packageName = getRulesPackageNameForProvider(providerType) val provider = providerType.getDeclaredConstructor().newInstance() val rules = getRules(provider) val classes = getClasses(packageName) classes.forEach { clazz -> val rule = rules.singleOrNull { it.javaClass.simpleName == clazz.simpleName } assertThat(rule).withFailMessage( "Rule $clazz is not called in the corresponding RuleSetProvider $providerType" ).isNotNull() } } } } }) private val ruleMap = mapOf<Class<*>, String>( CommentSmellProvider().javaClass to "io.gitlab.arturbosch.detekt.rules.documentation", ComplexityProvider().javaClass to "io.gitlab.arturbosch.detekt.rules.complexity", EmptyCodeProvider().javaClass to "io.gitlab.arturbosch.detekt.rules.empty", ExceptionsProvider().javaClass to "io.gitlab.arturbosch.detekt.rules.exceptions", NamingProvider().javaClass to "io.gitlab.arturbosch.detekt.rules.naming", PerformanceProvider().javaClass to "io.gitlab.arturbosch.detekt.rules.performance", PotentialBugProvider().javaClass to "io.gitlab.arturbosch.detekt.rules.bugs", StyleGuideProvider().javaClass to "io.gitlab.arturbosch.detekt.rules.style", CoroutinesProvider().javaClass to "io.gitlab.arturbosch.detekt.rules.coroutines" ) private fun getRulesPackageNameForProvider(providerType: Class<out RuleSetProvider>): String { val packageName = ruleMap[providerType] assertThat(packageName) .withFailMessage("No rules package for provider of type $providerType was defined in the ruleMap") .isNotNull() @Suppress("UnsafeCallOnNullableType") return packageName!! } private fun getRules(provider: RuleSetProvider): List<BaseRule> { @Suppress("UnsafeCallOnNullableType") val ruleSet = provider.instance(Config.empty) val rules = ruleSet.rules.flatMap { (it as? MultiRule)?.rules ?: listOf(it) } assertThat(rules).isNotEmpty return rules } private fun getClasses(packageName: String): List<Class<out Rule>> { val classes = Reflections(packageName) .getSubTypesOf(Rule::class.java) .filterNot { "Test" in it.name } .filter { !Modifier.isAbstract(it.modifiers) && !Modifier.isStatic(it.modifiers) } assertThat(classes).isNotEmpty return classes }
{ "pile_set_name": "Github" }
/* * Copyright 2020 The Magma Authors. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @flow strict-local * @format */ import type {DataRows} from '../../components/DataGrid'; import type {EnodebInfo} from '../../components/lte/EnodebUtils'; import type {lte_gateway} from '@fbcnms/magma-api'; import ActionTable from '../../components/ActionTable'; import AddEditGatewayButton from './GatewayDetailConfigEdit'; import Button from '@material-ui/core/Button'; import CardTitleRow from '../../components/layout/CardTitleRow'; import DataGrid from '../../components/DataGrid'; import EnodebContext from '../../components/context/EnodebContext'; import GatewayContext from '../../components/context/GatewayContext'; import Grid from '@material-ui/core/Grid'; import JsonEditor from '../../components/JsonEditor'; import React from 'react'; import SettingsIcon from '@material-ui/icons/Settings'; import nullthrows from '@fbcnms/util/nullthrows'; import {colors, typography} from '../../theme/default'; import {makeStyles} from '@material-ui/styles'; import {useContext, useState} from 'react'; import {useEnqueueSnackbar} from '@fbcnms/ui/hooks/useSnackbar'; import {useRouter} from '@fbcnms/ui/hooks'; const useStyles = makeStyles(theme => ({ dashboardRoot: { margin: theme.spacing(3), flexGrow: 1, }, appBarBtn: { color: colors.primary.white, background: colors.primary.comet, fontFamily: typography.button.fontFamily, fontWeight: typography.button.fontWeight, fontSize: typography.button.fontSize, lineHeight: typography.button.lineHeight, letterSpacing: typography.button.letterSpacing, '&:hover': { background: colors.primary.mirage, }, }, })); export function GatewayJsonConfig() { const {match, history} = useRouter(); const [error, setError] = useState(''); const gatewayId: string = nullthrows(match.params.gatewayId); const enqueueSnackbar = useEnqueueSnackbar(); const ctx = useContext(GatewayContext); const gwInfo = ctx.state[gatewayId]; const {['status']: _status, ...gwInfoJson} = gwInfo; return ( <JsonEditor content={{ ...gwInfoJson, connected_enodeb_serials: gwInfoJson.connected_enodeb_serials ?? [], }} error={error} onSave={async gateway => { try { await ctx.setState(gatewayId, gateway); enqueueSnackbar('Gateway saved successfully', { variant: 'success', }); setError(''); history.goBack(); } catch (e) { setError(e.response?.data?.message ?? e.message); } }} /> ); } export default function GatewayConfig() { const classes = useStyles(); const {history, match, relativeUrl} = useRouter(); const gatewayId: string = nullthrows(match.params.gatewayId); const ctx = useContext(GatewayContext); const gwInfo = ctx.state[gatewayId]; function ConfigFilter() { return ( <Button className={classes.appBarBtn} onClick={() => { history.push(relativeUrl('/json')); }}> Edit JSON </Button> ); } function editGateway() { return ( <AddEditGatewayButton title={'Edit'} isLink={true} editProps={{ editTable: 'info', }} /> ); } function editAggregations() { return ( <AddEditGatewayButton title={'Edit'} isLink={true} editProps={{ editTable: 'aggregation', }} /> ); } function editEPC() { return ( <AddEditGatewayButton title={'Edit'} isLink={true} editProps={{ editTable: 'epc', }} /> ); } function editRan() { return ( <AddEditGatewayButton title={'Edit'} isLink={true} editProps={{ editTable: 'ran', }} /> ); } return ( <div className={classes.dashboardRoot}> <Grid container spacing={4}> <Grid item xs={12}> <Grid item xs={12}> <CardTitleRow icon={SettingsIcon} label="Config" filter={ConfigFilter} /> </Grid> <Grid container spacing={4}> <Grid item xs={12} md={6} alignItems="center"> <Grid container spacing={4}> <Grid item xs={12}> <CardTitleRow label="Gateway" filter={editGateway} /> <GatewayInfoConfig gwInfo={gwInfo} /> </Grid> <Grid item xs={12}> <CardTitleRow label="Aggregations" filter={editAggregations} /> <GatewayAggregation gwInfo={gwInfo} /> </Grid> </Grid> </Grid> <Grid item xs={12} md={6} alignItems="center"> <Grid container spacing={4}> <Grid item xs={12}> <CardTitleRow label="EPC" filter={editEPC} /> <GatewayEPC gwInfo={gwInfo} /> </Grid> <Grid item xs={12}> <CardTitleRow label="Ran" filter={editRan} /> <GatewayRAN gwInfo={gwInfo} /> </Grid> </Grid> </Grid> </Grid> </Grid> </Grid> </div> ); } function GatewayInfoConfig({gwInfo}: {gwInfo: lte_gateway}) { const data: DataRows[] = [ [ { category: 'Name', value: gwInfo.name, }, ], [ { category: 'Gateway ID', value: gwInfo.id, }, ], [ { category: 'Hardware UUID', value: gwInfo.device.hardware_id, }, ], [ { category: 'Version', value: gwInfo.status?.platform_info?.packages?.[0]?.version ?? 'null', }, ], [ { category: 'Description', value: gwInfo.description, }, ], ]; return <DataGrid data={data} />; } function GatewayEPC({gwInfo}: {gwInfo: lte_gateway}) { const collapse: DataRows[] = [ [ { value: gwInfo.cellular.epc.ip_block ?? '-', }, ], ]; const data: DataRows[] = [ [ { category: 'IP Allocation', value: gwInfo.cellular.epc.nat_enabled ? 'NAT' : 'Custom', collapse: <DataGrid data={collapse} />, }, ], [ { category: 'Primary DNS', value: gwInfo.cellular.epc.dns_primary ?? '-', }, ], [ { category: 'Secondary DNS', value: gwInfo.cellular.epc.dns_secondary ?? '-', }, ], ]; return <DataGrid data={data} />; } function GatewayAggregation({gwInfo}: {gwInfo: lte_gateway}) { const logAggregation = !!gwInfo.magmad.dynamic_services?.includes( 'td-agent-bit', ); const eventAggregation = !!gwInfo.magmad?.dynamic_services?.includes( 'eventd', ); const aggregations: DataRows[] = [ [ { category: 'Aggregation', value: logAggregation ? 'Enabled' : 'Disabled', statusCircle: false, }, { category: 'Aggregation', value: eventAggregation ? 'Enabled' : 'Disabled', statusCircle: false, }, ], ]; return <DataGrid data={aggregations} />; } function EnodebsTable({enbInfo}: {enbInfo: {[string]: EnodebInfo}}) { type EnodebRowType = { name: string, id: string, }; const enbRows: Array<EnodebRowType> = Object.keys(enbInfo).map( (serialNum: string) => { const enbInf = enbInfo[serialNum]; return { name: enbInf.enb.name, id: serialNum, }; }, ); return ( <ActionTable title="" data={enbRows} columns={[{title: 'Serial Number', field: 'id'}]} menuItems={[ {name: 'View'}, {name: 'Edit'}, {name: 'Remove'}, {name: 'Deactivate'}, {name: 'Reboot'}, ]} options={{ actionsColumnIndex: -1, pageSizeOptions: [5], toolbar: false, header: false, paging: false, }} /> ); } function GatewayRAN({gwInfo}: {gwInfo: lte_gateway}) { const enbCtx = useContext(EnodebContext); const enbInfo = gwInfo.connected_enodeb_serials?.reduce( (enbs: {[string]: EnodebInfo}, serial: string) => { if (enbCtx?.state?.enbInfo?.[serial] != null) { enbs[serial] = enbCtx.state.enbInfo[serial]; } return enbs; }, {}, ) || {}; const dhcpServiceStatus = gwInfo.cellular.dns?.dhcp_server_enabled ?? true; const ran: DataRows[] = [ [ { category: 'eNodeB DHCP Service', value: dhcpServiceStatus ? 'Enabled' : 'Disabled', statusCircle: true, status: dhcpServiceStatus, }, ], [ { category: 'PCI', value: gwInfo.cellular.ran.pci, statusCircle: false, }, { category: 'eNodeB Transmit', value: gwInfo.cellular.ran.transmit_enabled ? 'Enabled' : 'Disabled', statusCircle: false, }, ], [ { category: 'Registered eNodeBs', value: gwInfo.connected_enodeb_serials?.length || 0, collapse: <EnodebsTable gwInfo={gwInfo} enbInfo={enbInfo} />, }, ], ]; return <DataGrid data={ran} />; }
{ "pile_set_name": "Github" }
"######################################## "######################################## " Mintchoc (rainglow) " " https://github.com/rainglow/vim " " Copyright (c) Dayle Rees. "######################################## "######################################## "######################################## "# Settings. # "######################################## set background=dark highlight clear if exists("syntax_on") syntax reset endif let g:colors_name = "mintchoc" "######################################## "# Base Colors. # "######################################## hi Cursor guifg=#2b221c guibg=#f8f8f0 gui=NONE hi Visual guifg=#ffffff guibg=#008d62 gui=NONE hi CursorLine guifg=NONE guibg=#342922 gui=NONE hi CursorLineNr guifg=#886b58 guibg=#15110e gui=NONE hi CursorColumn guifg=NONE guibg=#15110e gui=NONE hi ColorColumn guifg=NONE guibg=#0c0a08 gui=NONE hi LineNr guifg=#4a3a30 guibg=#1c1612 gui=NONE hi VertSplit guifg=#4a3a30 guibg=#4a3a30 gui=NONE hi MatchParen guifg=#008d62 guibg=NONE gui=underline hi StatusLine guifg=#bababa guibg=#1c1612 gui=bold hi StatusLineNC guifg=#bababa guibg=#1c1612 gui=NONE hi Pmenu guifg=#bababa guibg=#1c1612 gui=NONE hi PmenuSel guifg=NONE guibg=#9d8262 gui=NONE hi IncSearch guifg=#bababa guibg=#00e08c gui=NONE hi Search guifg=NONE guibg=NONE gui=underline hi Directory guifg=#9d8262 guibg=NONE gui=NONE hi Folded guifg=#adadad guibg=#0c0a08 gui=NONE hi Normal guifg=#00e08c guibg=#2b221c gui=NONE hi Boolean guifg=#00e08c guibg=NONE gui=NONE hi Character guifg=#00e08c guibg=NONE gui=NONE hi Comment guifg=#564439 guibg=NONE gui=NONE hi Conditional guifg=#9d8262 guibg=NONE gui=NONE hi Constant guifg=NONE guibg=NONE gui=NONE hi Define guifg=#9d8262 guibg=NONE gui=NONE hi DiffAdd guifg=#59473a guibg=#a7da1e gui=bold hi DiffDelete guifg=#59473a guibg=#e61f44 gui=NONE hi DiffChange guifg=#59473a guibg=#f7b83d gui=NONE hi DiffText guifg=#59473a guibg=#f7b83d gui=bold hi ErrorMsg guifg=#59473a guibg=#e61f44 gui=NONE hi WarningMsg guifg=#59473a guibg=#f7b83d gui=NONE hi Float guifg=#00e08c guibg=NONE gui=NONE hi Function guifg=#9d8262 guibg=NONE gui=NONE hi Identifier guifg=#bababa guibg=NONE gui=NONE hi Keyword guifg=#9d8262 guibg=NONE gui=NONE hi Label guifg=#00e08c guibg=NONE gui=NONE hi NonText guifg=#545454 guibg=#251d18 gui=NONE hi Number guifg=#00e08c guibg=NONE gui=NONE hi Operator guifg=#bababa guibg=NONE gui=NONE hi PreProc guifg=#846857 guibg=NONE gui=NONE hi Special guifg=#bababa guibg=NONE gui=NONE hi SpecialKey guifg=#bababa guibg=#9d8262 gui=NONE hi Statement guifg=#9d8262 guibg=NONE gui=NONE hi StorageClass guifg=#008d62 guibg=NONE gui=NONE hi String guifg=#00e08c guibg=NONE gui=NONE hi Tag guifg=#9d8262 guibg=NONE gui=NONE hi Title guifg=#9d8262 guibg=NONE gui=bold hi Todo guifg=#846857 guibg=NONE gui=inverse,bold hi Type guifg=NONE guibg=NONE gui=NONE hi Underlined guifg=NONE guibg=NONE gui=underline "######################################## "# Language Overrides # "######################################## hi phpIdentifier guifg=#bababa hi phpMethodsVar guifg=#dfd4cd hi xmlTag guifg=#9d8262 guibg=NONE gui=NONE hi xmlTagName guifg=#9d8262 guibg=NONE gui=NONE hi xmlEndTag guifg=#9d8262 guibg=NONE gui=NONE "######################################## "# Light Theme Overrides # "########################################
{ "pile_set_name": "Github" }
// Copyright (c) 2016, 2018, 2020, Oracle and/or its affiliates. All rights reserved. // This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. // Code generated. DO NOT EDIT. // DNS API // // API for the DNS service. Use this API to manage DNS zones, records, and other DNS resources. // For more information, see Overview of the DNS Service (https://docs.cloud.oracle.com/iaas/Content/DNS/Concepts/dnszonemanagement.htm). // package dns import ( "github.com/oracle/oci-go-sdk/v25/common" ) // MigrationReplacement A record to add to a zone in replacement of contents that cannot be migrated. type MigrationReplacement struct { // The canonical name for the type of the replacement record, such as A or CNAME. Rtype *string `mandatory:"true" json:"rtype"` // The Time To Live of the replacement record, in seconds. Ttl *int `mandatory:"true" json:"ttl"` // The record data of the replacement record, as whitespace-delimited tokens in // type-specific presentation format. Rdata *string `mandatory:"true" json:"rdata"` // The canonical name for a substitute type of the replacement record to be used if the specified `rtype` is not allowed at the domain. The specified `ttl` and `rdata` will still apply with the substitute type. SubstituteRtype *string `mandatory:"false" json:"substituteRtype"` } func (m MigrationReplacement) String() string { return common.PointerString(m) }
{ "pile_set_name": "Github" }
// // Copyright (c) ZeroC, Inc. All rights reserved. // #pragma once ["cs:namespace:Ice.enums"] module Test { const byte ByteConst1 = 10; const short ShortConst1 = 20; const int IntConst1 = 30; const long LongConst1 = 40; const byte ByteConst2 = 126; const short ShortConst2 = 32766; const int IntConst2 = 2147483647; const long LongConst2 = 2147483646; enum ByteEnum { benum1, benum2, benum3 = ByteConst1, benum4, benum5 = ShortConst1, benum6, benum7 = IntConst1, benum8, benum9 = LongConst1, benum10, benum11 = ByteConst2 } sequence<ByteEnum> ByteEnumSeq; enum ShortEnum { senum1 = 3, senum2, senum3 = ByteConst1, senum4, senum5 = ShortConst1, senum6, senum7 = IntConst1, senum8, senum9 = LongConst1, senum10, senum11 = ShortConst2 } sequence<ShortEnum> ShortEnumSeq; enum IntEnum { ienum1, ienum2, ienum3 = ByteConst1, ienum4, ienum5 = ShortConst1, ienum6, ienum7 = IntConst1, ienum8, ienum9 = LongConst1, ienum10, ienum11 = IntConst2, ienum12 = LongConst2 } sequence<IntEnum> IntEnumSeq; enum SimpleEnum { red, green, blue } sequence<SimpleEnum> SimpleEnumSeq; interface TestIntf { ByteEnum opByte(ByteEnum b1, out ByteEnum b2); ShortEnum opShort(ShortEnum s1, out ShortEnum s2); IntEnum opInt(IntEnum i1, out IntEnum i2); SimpleEnum opSimple(SimpleEnum s1, out SimpleEnum s2); ByteEnumSeq opByteSeq(ByteEnumSeq b1, out ByteEnumSeq b2); ShortEnumSeq opShortSeq(ShortEnumSeq s1, out ShortEnumSeq s2); IntEnumSeq opIntSeq(IntEnumSeq i1, out IntEnumSeq i2); SimpleEnumSeq opSimpleSeq(SimpleEnumSeq s1, out SimpleEnumSeq s2); void shutdown(); } }
{ "pile_set_name": "Github" }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #import <UIKit/UIKit.h> #import "bat/ledger/ledger.h" #import "bat/ledger/ledger_database.h" #import "bat/ledger/global_constants.h" #import "bat/ledger/option_keys.h" #import "ledger.mojom.objc+private.h" #import "BATBraveLedger.h" #import "BATBraveAds.h" #import "BATCommonOperations.h" #import "NSURL+Extensions.h" #import "NativeLedgerClient.h" #import "NativeLedgerClientBridge.h" #import "CppTransformations.h" #import <objc/runtime.h> #import "BATLedgerDatabase.h" #import "DataController.h" #import "brave/base/containers/utils.h" #import "base/time/time.h" #import "url/gurl.h" #import "net/base/registry_controlled_domains/registry_controlled_domain.h" #import "base/strings/sys_string_conversions.h" #import "components/os_crypt/os_crypt.h" #import "base/i18n/icu_util.h" #import "base/ios/ios_util.h" #import "base/base64.h" #import "base/command_line.h" #import "RewardsLogging.h" #define BATLedgerReadonlyBridge(__type, __objc_getter, __cpp_getter) \ - (__type)__objc_getter { return ledger->__cpp_getter(); } #define BATLedgerBridge(__type, __objc_getter, __objc_setter, __cpp_getter, __cpp_setter) \ - (__type)__objc_getter { return ledger->__cpp_getter(); } \ - (void)__objc_setter:(__type)newValue { ledger->__cpp_setter(newValue); } #define BATClassLedgerBridge(__type, __objc_getter, __objc_setter, __cpp_var) \ + (__type)__objc_getter { return ledger::__cpp_var; } \ + (void)__objc_setter:(__type)newValue { ledger::__cpp_var = newValue; } NSString * const BATBraveLedgerErrorDomain = @"BATBraveLedgerErrorDomain"; NSNotificationName const BATBraveLedgerNotificationAdded = @"BATBraveLedgerNotificationAdded"; BATBraveGeneralLedgerNotificationID const BATBraveGeneralLedgerNotificationIDWalletNowVerified = @"wallet_new_verified"; BATBraveGeneralLedgerNotificationID const BATBraveGeneralLedgerNotificationIDWalletDisconnected = @"wallet_disconnected"; static NSString * const kNextAddFundsDateNotificationKey = @"BATNextAddFundsDateNotification"; static NSString * const kBackupNotificationIntervalKey = @"BATBackupNotificationInterval"; static NSString * const kBackupNotificationFrequencyKey = @"BATBackupNotificationFrequency"; static NSString * const kUserHasFundedKey = @"BATRewardsUserHasFunded"; static NSString * const kBackupSucceededKey = @"BATRewardsBackupSucceeded"; static NSString * const kMigrationSucceeded = @"BATRewardsMigrationSucceeded"; static NSString * const kContributionQueueAutoincrementID = @"BATContributionQueueAutoincrementID"; static NSString * const kUnblindedTokenAutoincrementID = @"BATUnblindedTokenAutoincrementID"; static NSString * const kExternalWalletsPrefKey = @"external_wallets"; static NSString * const kTransferFeesPrefKey = @"transfer_fees"; static const auto kOneDay = base::Time::kHoursPerDay * base::Time::kSecondsPerHour; /// Ledger Prefs, keys will be defined in `bat/ledger/option_keys.h` const std::map<std::string, bool> kBoolOptions = {}; const std::map<std::string, int> kIntegerOptions = {}; const std::map<std::string, double> kDoubleOptions = {}; const std::map<std::string, std::string> kStringOptions = {}; const std::map<std::string, int64_t> kInt64Options = {}; const std::map<std::string, uint64_t> kUInt64Options = { {ledger::option::kPublisherListRefreshInterval, 7 * base::Time::kHoursPerDay * base::Time::kSecondsPerHour} }; /// --- /// When initializing the ledger, what should we do when migrating typedef NS_ENUM(NSInteger, BATLedgerDatabaseMigrationType) { /// Attempt to migrate all rewards data if needed BATLedgerDatabaseMigrationTypeDefault = 0, /// Only migrate unblinded tokens if needed BATLedgerDatabaseMigrationTypeTokensOnly, /// Do not migrate any data (essentially resetting rewards activity & balance) BATLedgerDatabaseMigrationTypeNone }; @interface BATBraveLedger () <NativeLedgerClientBridge> { NativeLedgerClient *ledgerClient; ledger::Ledger *ledger; ledger::LedgerDatabase *rewardsDatabase; } @property (nonatomic, copy) NSString *storagePath; @property (nonatomic) BATRewardsParameters *rewardsParameters; @property (nonatomic) BATBalance *balance; @property (nonatomic) BATUpholdWallet *upholdWallet; @property (nonatomic) dispatch_queue_t fileWriteThread; @property (nonatomic) NSMutableDictionary<NSString *, NSString *> *state; @property (nonatomic) BATCommonOperations *commonOps; @property (nonatomic) NSMutableDictionary<NSString *, __kindof NSObject *> *prefs; @property (nonatomic) NSMutableArray<BATPromotion *> *mPendingPromotions; @property (nonatomic) NSMutableArray<BATPromotion *> *mFinishedPromotions; @property (nonatomic) NSHashTable<BATBraveLedgerObserver *> *observers; @property (nonatomic, getter=isInitialized) BOOL initialized; @property (nonatomic) BOOL initializing; @property (nonatomic) BOOL dataMigrationFailed; @property (nonatomic) BATResult initializationResult; @property (nonatomic, getter=isLoadingPublisherList) BOOL loadingPublisherList; @property (nonatomic, getter=isInitializingWallet) BOOL initializingWallet; @property (nonatomic) BATLedgerDatabaseMigrationType migrationType; @property (nonatomic) dispatch_queue_t databaseQueue; /// Notifications @property (nonatomic) NSMutableArray<BATRewardsNotification *> *mNotifications; @property (nonatomic) NSTimer *notificationStartupTimer; @property (nonatomic) NSDate *lastNotificationCheckDate; /// Temporary blocks @end @implementation BATBraveLedger - (instancetype)initWithStateStoragePath:(NSString *)path { if ((self = [super init])) { self.storagePath = path; self.commonOps = [[BATCommonOperations alloc] initWithStoragePath:path]; self.state = [[NSMutableDictionary alloc] initWithContentsOfFile:self.randomStatePath] ?: [[NSMutableDictionary alloc] init]; self.fileWriteThread = dispatch_queue_create("com.rewards.file-write", DISPATCH_QUEUE_SERIAL); self.mPendingPromotions = [[NSMutableArray alloc] init]; self.mFinishedPromotions = [[NSMutableArray alloc] init]; self.observers = [NSHashTable weakObjectsHashTable]; rewardsDatabase = nullptr; self.prefs = [[NSMutableDictionary alloc] initWithContentsOfFile:[self prefsPath]]; if (!self.prefs) { self.prefs = [[NSMutableDictionary alloc] init]; // Setup defaults self.prefs[kNextAddFundsDateNotificationKey] = @([[NSDate date] timeIntervalSince1970]); self.prefs[kBackupNotificationFrequencyKey] = @(7 * kOneDay); // 7 days self.prefs[kBackupNotificationIntervalKey] = @(7 * kOneDay); // 7 days self.prefs[kBackupSucceededKey] = @(NO); self.prefs[kUserHasFundedKey] = @(NO); self.prefs[kMigrationSucceeded] = @(NO); [self savePrefs]; } const auto pathToICUDTL = [[NSBundle bundleForClass:[BATBraveLedger class]] pathForResource:@"icudtl" ofType:@"dat"]; base::ios::OverridePathOfEmbeddedICU(pathToICUDTL.UTF8String); if (!base::i18n::InitializeICU()) { BLOG(0, @"Failed to initialize ICU data"); } const auto args = [NSProcessInfo processInfo].arguments; const char *argv[args.count]; for (NSInteger i = 0; i < args.count; i++) { argv[i] = args[i].UTF8String; } base::CommandLine::Init(args.count, argv); self.databaseQueue = dispatch_queue_create("com.rewards.db-transactions", DISPATCH_QUEUE_SERIAL); const auto* dbPath = [self rewardsDatabasePath].UTF8String; rewardsDatabase = ledger::LedgerDatabase::CreateInstance(base::FilePath(dbPath)); ledgerClient = new NativeLedgerClient(self); ledger = ledger::Ledger::CreateInstance(ledgerClient); self.migrationType = BATLedgerDatabaseMigrationTypeDefault; BOOL needsMigration = [self databaseNeedsMigration]; if (needsMigration) { [BATLedgerDatabase deleteCoreDataServerPublisherList:nil]; } [self initializeLedgerService:needsMigration]; // Add notifications for standard app foreground/background [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(applicationDidBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil]; [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(applicationDidBackground) name:UIApplicationDidEnterBackgroundNotification object:nil]; if (self.walletCreated) { [self getRewardsParameters:nil]; [self fetchBalance:nil]; [self fetchUpholdWallet:nil]; } [self readNotificationsFromDisk]; } return self; } - (void)dealloc { [NSNotificationCenter.defaultCenter removeObserver:self]; [self.notificationStartupTimer invalidate]; delete ledger; delete ledgerClient; delete rewardsDatabase; } - (void)initializeLedgerService:(BOOL)executeMigrateScript { if (self.initialized || self.initializing) { return; } self.initializing = YES; BLOG(3, @"DB: Migrate from CoreData? %@", (executeMigrateScript ? @"YES" : @"NO")); ledger->Initialize(executeMigrateScript, ^(ledger::type::Result result){ self.initialized = (result == ledger::type::Result::LEDGER_OK || result == ledger::type::Result::NO_LEDGER_STATE || result == ledger::type::Result::NO_PUBLISHER_STATE); self.initializing = NO; if (self.initialized) { self.prefs[kMigrationSucceeded] = @(YES); [self savePrefs]; if (self.isEnabled) { [self.ads initializeIfAdsEnabled]; } } else { BLOG(0, @"Ledger Initialization Failed with error: %d", result); if (result == ledger::type::Result::DATABASE_INIT_FAILED) { // Failed to migrate data... switch (self.migrationType) { case BATLedgerDatabaseMigrationTypeDefault: BLOG(0, @"DB: Full migration failed, attempting BAT only migration."); self.dataMigrationFailed = YES; self.migrationType = BATLedgerDatabaseMigrationTypeTokensOnly; [self resetRewardsDatabase]; // attempt re-initialize without other data [self initializeLedgerService:YES]; return; case BATLedgerDatabaseMigrationTypeTokensOnly: BLOG(0, @"DB: BAT only migration failed. Initializing without migration."); self.dataMigrationFailed = YES; self.migrationType = BATLedgerDatabaseMigrationTypeNone; [self resetRewardsDatabase]; // attempt initialize without migrating at all [self initializeLedgerService:NO]; return; default: break; } } } self.initializationResult = static_cast<BATResult>(result); for (BATBraveLedgerObserver *observer in [self.observers copy]) { if (observer.walletInitalized) { observer.walletInitalized(self.initializationResult); } } }); } - (BOOL)databaseNeedsMigration { // Check if we even have a DB to migrate if (!DataController.defaultStoreExists) { return NO; } // Have we set the pref saying ledger has alaready initialized successfully? if ([self.prefs[kMigrationSucceeded] boolValue]) { return NO; } // Can we even check the DB if (!rewardsDatabase) { BLOG(3, @"DB: No rewards database object"); return YES; } // Check integrity of the new DB. Safe to assume if `publisher_info` table // exists, then all the others do as well. auto transaction = ledger::type::DBTransaction::New(); const auto command = ledger::type::DBCommand::New(); command->type = ledger::type::DBCommand::Type::READ; command->command = "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'publisher_info';"; command->record_bindings = { ledger::type::DBCommand::RecordBindingType::STRING_TYPE }; transaction->commands.push_back(command->Clone()); auto response = ledger::type::DBCommandResponse::New(); rewardsDatabase->RunTransaction(std::move(transaction), response.get()); // Failed to even run the check, tables probably don't exist, // restart from scratch if (response->status != ledger::type::DBCommandResponse::Status::RESPONSE_OK) { [self resetRewardsDatabase]; BLOG(3, @"DB: Failed to run transaction with status: %d", response->status); return YES; } const auto record = std::move(response->result->get_records()); // sqlite_master table exists, but the publisher_info table doesn't exist? // Restart from scratch if (record.empty() || record.front()->fields.empty()) { [self resetRewardsDatabase]; BLOG(3, @"DB: Migrate because we couldnt find tables in sqlite_master"); return YES; } // Tables exist so migration has happened already, but somehow the flag wasn't // saved. self.prefs[kMigrationSucceeded] = @(YES); [self savePrefs]; return NO; } - (NSString *)rewardsDatabasePath { return [self.storagePath stringByAppendingPathComponent:@"Rewards.db"]; } - (void)resetRewardsDatabase { delete rewardsDatabase; const auto dbPath = [self rewardsDatabasePath]; [NSFileManager.defaultManager removeItemAtPath:dbPath error:nil]; [NSFileManager.defaultManager removeItemAtPath:[dbPath stringByAppendingString:@"-journal"] error:nil]; rewardsDatabase = ledger::LedgerDatabase::CreateInstance(base::FilePath(dbPath.UTF8String)); } - (void)getCreateScript:(ledger::client::GetCreateScriptCallback)callback { NSString *migrationScript = @""; switch (self.migrationType) { case BATLedgerDatabaseMigrationTypeNone: // We shouldn't be migrating, therefore doesn't make sense that // `getCreateScript` was called BLOG(0, @"DB: Attempted CoreData migration with an empty migration script"); break; case BATLedgerDatabaseMigrationTypeTokensOnly: migrationScript = [BATLedgerDatabase migrateCoreDataBATOnlyToSQLTransaction]; break; case BATLedgerDatabaseMigrationTypeDefault: default: migrationScript = [BATLedgerDatabase migrateCoreDataToSQLTransaction]; } callback(migrationScript.UTF8String, 10); } - (NSString *)randomStatePath { return [self.storagePath stringByAppendingPathComponent:@"random_state.plist"]; } - (NSString *)prefsPath { return [self.storagePath stringByAppendingPathComponent:@"ledger_pref.plist"]; } - (void)savePrefs { NSDictionary *prefs = [self.prefs copy]; NSString *path = [self prefsPath]; dispatch_async(self.fileWriteThread, ^{ [prefs writeToFile:path atomically:YES]; }); } #pragma mark - Observers - (void)addObserver:(BATBraveLedgerObserver *)observer { [self.observers addObject:observer]; } - (void)removeObserver:(BATBraveLedgerObserver *)observer { [self.observers removeObject:observer]; } #pragma mark - Global BATClassLedgerBridge(BOOL, isDebug, setDebug, is_debug) BATClassLedgerBridge(BOOL, isTesting, setTesting, is_testing) BATClassLedgerBridge(int, reconcileInterval, setReconcileInterval, reconcile_interval) BATClassLedgerBridge(BOOL, useShortRetries, setUseShortRetries, short_retries) + (BATEnvironment)environment { return static_cast<BATEnvironment>(ledger::_environment); } + (void)setEnvironment:(BATEnvironment)environment { ledger::_environment = static_cast<ledger::type::Environment>(environment); } #pragma mark - Wallet BATLedgerReadonlyBridge(BOOL, isWalletCreated, IsWalletCreated) - (void)createWallet:(void (^)(NSError * _Nullable))completion { const auto __weak weakSelf = self; // Results that can come from CreateWallet(): // - WALLET_CREATED: Good to go // - LEDGER_ERROR: Already initialized // - BAD_REGISTRATION_RESPONSE: Request credentials call failure or malformed data // - REGISTRATION_VERIFICATION_FAILED: Missing master user token self.initializingWallet = YES; ledger->CreateWallet(^(ledger::type::Result result) { const auto strongSelf = weakSelf; if (!strongSelf) { return; } NSError *error = nil; if (result != ledger::type::Result::WALLET_CREATED) { std::map<ledger::type::Result, std::string> errorDescriptions { { ledger::type::Result::LEDGER_ERROR, "The wallet was already initialized" }, { ledger::type::Result::BAD_REGISTRATION_RESPONSE, "Request credentials call failure or malformed data" }, { ledger::type::Result::REGISTRATION_VERIFICATION_FAILED, "Missing master user token from registered persona" }, }; NSDictionary *userInfo = @{}; const auto description = errorDescriptions[static_cast<ledger::type::Result>(result)]; if (description.length() > 0) { userInfo = @{ NSLocalizedDescriptionKey: [NSString stringWithUTF8String:description.c_str()] }; } error = [NSError errorWithDomain:BATBraveLedgerErrorDomain code:static_cast<NSInteger>(result) userInfo:userInfo]; } strongSelf.ads.enabled = [BATBraveAds isCurrentLocaleSupported]; [strongSelf startNotificationTimers]; strongSelf.initializingWallet = NO; dispatch_async(dispatch_get_main_queue(), ^{ if (completion) { completion(error); } for (BATBraveLedgerObserver *observer in [strongSelf.observers copy]) { if (observer.rewardsEnabledStateUpdated) { observer.rewardsEnabledStateUpdated(strongSelf.isEnabled); } } for (BATBraveLedgerObserver *observer in [strongSelf.observers copy]) { if (observer.walletInitalized) { observer.walletInitalized(static_cast<BATResult>(result)); } } }); }); } - (void)getRewardsParameters:(void (^)(BATRewardsParameters * _Nullable))completion { ledger->GetRewardsParameters(^(ledger::type::RewardsParametersPtr info) { if (info) { self.rewardsParameters = [[BATRewardsParameters alloc] initWithRewardsParametersPtr:std::move(info)]; } else { self.rewardsParameters = nil; } const auto __weak weakSelf = self; dispatch_async(dispatch_get_main_queue(), ^{ if (completion) { completion(weakSelf.rewardsParameters); } }); }); } - (void)fetchBalance:(void (^)(BATBalance * _Nullable))completion { const auto __weak weakSelf = self; ledger->FetchBalance(^(ledger::type::Result result, ledger::type::BalancePtr balance) { const auto strongSelf = weakSelf; if (result == ledger::type::Result::LEDGER_OK) { strongSelf.balance = [[BATBalance alloc] initWithBalancePtr:std::move(balance)]; } dispatch_async(dispatch_get_main_queue(), ^{ for (BATBraveLedgerObserver *observer in [self.observers copy]) { if (observer.fetchedBalance) { observer.fetchedBalance(); } } if (completion) { completion(strongSelf.balance); } }); }); } - (void)recoverWalletUsingPassphrase:(NSString *)passphrase completion:(void (^)(NSError *_Nullable))completion { const auto __weak weakSelf = self; // Results that can come from CreateWallet(): // - LEDGER_OK: Good to go // - LEDGER_ERROR: Recovery failed ledger->RecoverWallet(std::string(passphrase.UTF8String), ^(const ledger::type::Result result) { const auto strongSelf = weakSelf; if (!strongSelf) { return; } NSError *error = nil; if (result != ledger::type::Result::LEDGER_OK) { std::map<ledger::type::Result, std::string> errorDescriptions { { ledger::type::Result::LEDGER_ERROR, "The recovery failed" }, }; NSDictionary *userInfo = @{}; const auto description = errorDescriptions[result]; if (description.length() > 0) { userInfo = @{ NSLocalizedDescriptionKey: [NSString stringWithUTF8String:description.c_str()] }; } error = [NSError errorWithDomain:BATBraveLedgerErrorDomain code:static_cast<NSInteger>(result) userInfo:userInfo]; } if (completion) { completion(error); } } ); } - (void)hasSufficientBalanceToReconcile:(void (^)(BOOL))completion { ledger->HasSufficientBalanceToReconcile(completion); } - (void)pendingContributionsTotal:(void (^)(double amount))completion { ledger->GetPendingContributionsTotal(^(double total){ completion(total); }); } #pragma mark - User Wallets - (void)fetchUpholdWallet:(nullable void (^)(BATUpholdWallet * _Nullable wallet))completion { const auto __weak weakSelf = self; ledger->GetUpholdWallet(^(ledger::type::Result result, ledger::type::UpholdWalletPtr walletPtr) { if (result == ledger::type::Result::LEDGER_OK && walletPtr.get() != nullptr) { const auto bridgedWallet = [[BATUpholdWallet alloc] initWithUpholdWallet:*walletPtr]; weakSelf.upholdWallet = bridgedWallet; if (completion) { completion(bridgedWallet); } } else { if (completion) { completion(nil); } } }); } - (void)disconnectWalletOfType:(BATWalletType)walletType completion:(nullable void (^)(BATResult result))completion { ledger->DisconnectWallet(walletType.UTF8String, ^(ledger::type::Result result){ if (completion) { completion(static_cast<BATResult>(result)); } for (BATBraveLedgerObserver *observer in self.observers) { if (observer.externalWalletDisconnected) { observer.externalWalletDisconnected(walletType); } } }); } - (void)authorizeExternalWalletOfType:(BATWalletType)walletType queryItems:(NSDictionary<NSString *, NSString *> *)queryItems completion:(void (^)(BATResult result, NSURL * _Nullable redirectURL))completion { ledger->ExternalWalletAuthorization(walletType.UTF8String, MapFromNSDictionary(queryItems), ^(ledger::type::Result result, std::map<std::string, std::string> args) { const auto it = args.find("redirect_url"); std::string redirect; if (it != args.end()) { redirect = it->second; } NSURL *url = redirect.empty() ? nil : [NSURL URLWithString:[NSString stringWithUTF8String:redirect.c_str()]]; completion(static_cast<BATResult>(result), url); if (result == ledger::type::Result::LEDGER_OK) { for (BATBraveLedgerObserver *observer in self.observers) { if (observer.externalWalletAuthorized) { observer.externalWalletAuthorized(walletType); } } } }); } - (std::string)getLegacyWallet { NSDictionary *externalWallets = self.prefs[kExternalWalletsPrefKey] ?: [[NSDictionary alloc] init]; std::string wallet; NSData *data = [NSJSONSerialization dataWithJSONObject:externalWallets options:0 error:nil]; if (data != nil) { NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; if (dataString.UTF8String != nil) { wallet = dataString.UTF8String; } } return wallet; } #pragma mark - Publishers - (void)listActivityInfoFromStart:(unsigned int)start limit:(unsigned int)limit filter:(BATActivityInfoFilter *)filter completion:(void (NS_NOESCAPE ^)(NSArray<BATPublisherInfo *> *))completion { auto cppFilter = filter ? filter.cppObjPtr : ledger::type::ActivityInfoFilter::New(); if (filter.excluded == BATExcludeFilterFilterExcluded) { ledger->GetExcludedList(^(ledger::type::PublisherInfoList list) { const auto publishers = NSArrayFromVector(&list, ^BATPublisherInfo *(const ledger::type::PublisherInfoPtr& info){ return [[BATPublisherInfo alloc] initWithPublisherInfo:*info]; }); completion(publishers); }); } else { ledger->GetActivityInfoList(start, limit, std::move(cppFilter), ^(ledger::type::PublisherInfoList list) { const auto publishers = NSArrayFromVector(&list, ^BATPublisherInfo *(const ledger::type::PublisherInfoPtr& info){ return [[BATPublisherInfo alloc] initWithPublisherInfo:*info]; }); completion(publishers); }); } } - (void)fetchPublisherActivityFromURL:(NSURL *)URL faviconURL:(nullable NSURL *)faviconURL publisherBlob:(nullable NSString *)publisherBlob tabId:(uint64_t)tabId { if (!URL.absoluteString) { return; } GURL parsedUrl(base::SysNSStringToUTF8(URL.absoluteString)); if (!parsedUrl.is_valid()) { return; } auto origin = parsedUrl.GetOrigin(); std::string baseDomain = GetDomainAndRegistry(origin.host(), net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); if (baseDomain == "") { return; } ledger::type::VisitDataPtr visitData = ledger::type::VisitData::New(); visitData->domain = visitData->name = baseDomain; visitData->path = parsedUrl.PathForRequest(); visitData->url = origin.spec(); if (faviconURL.absoluteString) { visitData->favicon_url = base::SysNSStringToUTF8(faviconURL.absoluteString); } std::string blob = std::string(); if (publisherBlob) { blob = base::SysNSStringToUTF8(publisherBlob); } ledger->GetPublisherActivityFromUrl(tabId, std::move(visitData), blob); } - (void)updatePublisherExclusionState:(NSString *)publisherId state:(BATPublisherExclude)state { ledger->SetPublisherExclude(std::string(publisherId.UTF8String), (ledger::type::PublisherExclude)state, ^(const ledger::type::Result result) { if (result != ledger::type::Result::LEDGER_OK) { return; } for (BATBraveLedgerObserver *observer in [self.observers copy]) { if (observer.excludedSitesChanged) { observer.excludedSitesChanged(publisherId, state); } } }); } - (void)restoreAllExcludedPublishers { ledger->RestorePublishers(^(const ledger::type::Result result) { if (result != ledger::type::Result::LEDGER_OK) { return; } for (BATBraveLedgerObserver *observer in [self.observers copy]) { if (observer.excludedSitesChanged) { observer.excludedSitesChanged(@"-1", static_cast<BATPublisherExclude>(ledger::type::PublisherExclude::ALL)); } } }); } - (void)publisherBannerForId:(NSString *)publisherId completion:(void (^)(BATPublisherBanner * _Nullable banner))completion { ledger->GetPublisherBanner(std::string(publisherId.UTF8String), ^(ledger::type::PublisherBannerPtr banner) { auto bridgedBanner = banner.get() != nullptr ? [[BATPublisherBanner alloc] initWithPublisherBanner:*banner] : nil; // native libs prefixes the logo and background image with this URL scheme const auto imagePrefix = @"chrome://rewards-image/"; bridgedBanner.background = [bridgedBanner.background stringByReplacingOccurrencesOfString:imagePrefix withString:@""]; bridgedBanner.logo = [bridgedBanner.logo stringByReplacingOccurrencesOfString:imagePrefix withString:@""]; completion(bridgedBanner); }); } - (void)refreshPublisherWithId:(NSString *)publisherId completion:(void (^)(BATPublisherStatus status))completion { if (self.loadingPublisherList) { completion(BATPublisherStatusNotVerified); return; } ledger->RefreshPublisher(std::string(publisherId.UTF8String), ^(ledger::type::PublisherStatus status) { completion(static_cast<BATPublisherStatus>(status)); }); } #pragma mark - SKUs - (void)processSKUItems:(NSArray<BATSKUOrderItem *> *)items completion:(void (^)(BATResult result, NSString *orderID))completion { ledger->ProcessSKU(VectorFromNSArray(items, ^ledger::type::SKUOrderItem(BATSKUOrderItem *item) { return *item.cppObjPtr; }), ledger::constant::kWalletUnBlinded, ^(const ledger::type::Result result, const std::string& order_id) { completion(static_cast<BATResult>(result), [NSString stringWithUTF8String:order_id.c_str()]); }); } #pragma mark - Tips - (void)listRecurringTips:(void (^)(NSArray<BATPublisherInfo *> *))completion { ledger->GetRecurringTips(^(ledger::type::PublisherInfoList list){ const auto publishers = NSArrayFromVector(&list, ^BATPublisherInfo *(const ledger::type::PublisherInfoPtr& info){ return [[BATPublisherInfo alloc] initWithPublisherInfo:*info]; }); completion(publishers); }); } - (void)addRecurringTipToPublisherWithId:(NSString *)publisherId amount:(double)amount completion:(void (^)(BOOL success))completion { ledger::type::RecurringTipPtr info = ledger::type::RecurringTip::New(); info->publisher_key = publisherId.UTF8String; info->amount = amount; info->created_at = [[NSDate date] timeIntervalSince1970]; ledger->SaveRecurringTip(std::move(info), ^(ledger::type::Result result){ const auto success = (result == ledger::type::Result::LEDGER_OK); if (success) { for (BATBraveLedgerObserver *observer in [self.observers copy]) { if (observer.recurringTipAdded) { observer.recurringTipAdded(publisherId); } } } completion(success); }); } - (void)removeRecurringTipForPublisherWithId:(NSString *)publisherId { ledger->RemoveRecurringTip(std::string(publisherId.UTF8String), ^(ledger::type::Result result){ if (result == ledger::type::Result::LEDGER_OK) { for (BATBraveLedgerObserver *observer in [self.observers copy]) { if (observer.recurringTipRemoved) { observer.recurringTipRemoved(publisherId); } } } }); } - (void)listOneTimeTips:(void (^)(NSArray<BATPublisherInfo *> *))completion { ledger->GetOneTimeTips(^(ledger::type::PublisherInfoList list){ const auto publishers = NSArrayFromVector(&list, ^BATPublisherInfo *(const ledger::type::PublisherInfoPtr& info){ return [[BATPublisherInfo alloc] initWithPublisherInfo:*info]; }); completion(publishers); }); } - (void)tipPublisherDirectly:(BATPublisherInfo *)publisher amount:(double)amount currency:(NSString *)currency completion:(void (^)(BATResult result))completion { ledger->OneTimeTip(std::string(publisher.id.UTF8String), amount, ^(ledger::type::Result result) { completion(static_cast<BATResult>(result)); }); } #pragma mark - Grants - (NSArray<BATPromotion *> *)pendingPromotions { return [self.mPendingPromotions copy]; } - (NSArray<BATPromotion *> *)finishedPromotions { return [self.mFinishedPromotions copy]; } - (NSString *)notificationIDForPromo:(const ledger::type::PromotionPtr)promo { bool isUGP = promo->type == ledger::type::PromotionType::UGP; const auto prefix = isUGP ? @"rewards_grant_" : @"rewards_grant_ads_"; const auto promotionId = [NSString stringWithUTF8String:promo->id.c_str()]; return [NSString stringWithFormat:@"%@%@", prefix, promotionId]; } - (void)updatePendingAndFinishedPromotions:(void (^)())completion { ledger->GetAllPromotions(^(ledger::type::PromotionMap map) { NSMutableArray *promos = [[NSMutableArray alloc] init]; for (auto it = map.begin(); it != map.end(); ++it) { if (it->second.get() != nullptr) { [promos addObject:[[BATPromotion alloc] initWithPromotion:*it->second]]; } } for (BATPromotion *promo in [self.mPendingPromotions copy]) { [self clearNotificationWithID:[self notificationIDForPromo:promo.cppObjPtr]]; } [self.mFinishedPromotions removeAllObjects]; [self.mPendingPromotions removeAllObjects]; for (BATPromotion *promotion in promos) { if (promotion.status == BATPromotionStatusFinished) { [self.mFinishedPromotions addObject:promotion]; if (promotion.type == BATPromotionTypeAds) { [self.ads updateAdRewards:true]; } } else if (promotion.status == BATPromotionStatusActive || promotion.status == BATPromotionStatusAttested) { [self.mPendingPromotions addObject:promotion]; bool isUGP = promotion.type == BATPromotionTypeUgp; auto notificationKind = isUGP ? BATRewardsNotificationKindGrant : BATRewardsNotificationKindGrantAds; [self addNotificationOfKind:notificationKind userInfo:nil notificationID:[self notificationIDForPromo:promotion.cppObjPtr] onlyOnce:YES]; } } if (completion) { completion(); } for (BATBraveLedgerObserver *observer in [self.observers copy]) { if (observer.promotionsAdded) { observer.promotionsAdded(self.pendingPromotions); } if (observer.finishedPromotionsAdded) { observer.finishedPromotionsAdded(self.finishedPromotions); } } }); } - (void)fetchPromotions:(nullable void (^)(NSArray<BATPromotion *> *grants))completion { ledger->FetchPromotions(^(ledger::type::Result result, std::vector<ledger::type::PromotionPtr> promotions) { if (result != ledger::type::Result::LEDGER_OK) { return; } [self updatePendingAndFinishedPromotions:^{ if (completion) { completion(self.pendingPromotions); } }]; }); } - (void)claimPromotion:(NSString *)promotionId publicKey:(NSString *)deviceCheckPublicKey completion:(void (^)(BATResult result, NSString * _Nonnull nonce))completion { const auto payload = [NSDictionary dictionaryWithObject:deviceCheckPublicKey forKey:@"publicKey"]; const auto jsonData = [NSJSONSerialization dataWithJSONObject:payload options:0 error:nil]; if (!jsonData) { BLOG(0, @"Missing JSON payload while attempting to claim promotion"); return; } const auto jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; ledger->ClaimPromotion(promotionId.UTF8String, jsonString.UTF8String, ^(const ledger::type::Result result, const std::string& nonce) { dispatch_async(dispatch_get_main_queue(), ^{ completion(static_cast<BATResult>(result), [NSString stringWithUTF8String:nonce.c_str()]); }); }); } - (void)attestPromotion:(NSString *)promotionId solution:(BATPromotionSolution *)solution completion:(void (^)(BATResult result, BATPromotion * _Nullable promotion))completion { ledger->AttestPromotion(std::string(promotionId.UTF8String), solution.JSONPayload.UTF8String, ^(const ledger::type::Result result, ledger::type::PromotionPtr promotion) { if (promotion.get() == nullptr) return; const auto bridgedPromotion = [[BATPromotion alloc] initWithPromotion:*promotion]; if (result == ledger::type::Result::LEDGER_OK) { [self fetchBalance:nil]; [self clearNotificationWithID:[self notificationIDForPromo:std::move(promotion)]]; } dispatch_async(dispatch_get_main_queue(), ^{ if (completion) { completion(static_cast<BATResult>(result), bridgedPromotion); } if (result == ledger::type::Result::LEDGER_OK) { for (BATBraveLedgerObserver *observer in [self.observers copy]) { if (observer.promotionClaimed) { observer.promotionClaimed(bridgedPromotion); } } } }); }); } #pragma mark - History - (void)balanceReportForMonth:(BATActivityMonth)month year:(int)year completion:(void (^)(BATBalanceReportInfo * _Nullable info))completion { ledger->GetBalanceReport((ledger::type::ActivityMonth)month, year, ^(const ledger::type::Result result, ledger::type::BalanceReportInfoPtr info) { auto bridgedInfo = info.get() != nullptr ? [[BATBalanceReportInfo alloc] initWithBalanceReportInfo:*info.get()] : nil; completion(result == ledger::type::Result::LEDGER_OK ? bridgedInfo : nil); }); } - (BATAutoContributeProperties *)autoContributeProperties { ledger::type::AutoContributePropertiesPtr props = ledger->GetAutoContributeProperties(); return [[BATAutoContributeProperties alloc] initWithAutoContributePropertiesPtr:std::move(props)]; } #pragma mark - Pending Contributions - (void)pendingContributions:(void (^)(NSArray<BATPendingContributionInfo *> *publishers))completion { ledger->GetPendingContributions(^(ledger::type::PendingContributionInfoList list){ const auto convetedList = NSArrayFromVector(&list, ^BATPendingContributionInfo *(const ledger::type::PendingContributionInfoPtr& info){ return [[BATPendingContributionInfo alloc] initWithPendingContributionInfo:*info]; }); completion(convetedList); }); } - (void)removePendingContribution:(BATPendingContributionInfo *)info completion:(void (^)(BATResult result))completion { ledger->RemovePendingContribution(info.id, ^(const ledger::type::Result result){ completion(static_cast<BATResult>(result)); }); } - (void)removeAllPendingContributions:(void (^)(BATResult result))completion { ledger->RemoveAllPendingContributions(^(const ledger::type::Result result){ completion(static_cast<BATResult>(result)); }); } #pragma mark - Reconcile - (void)onReconcileComplete:(ledger::type::Result)result contribution:(ledger::type::ContributionInfoPtr)contribution { // TODO we changed from probi to amount, so from string to double if (result == ledger::type::Result::LEDGER_OK) { if (contribution->type == ledger::type::RewardsType::RECURRING_TIP) { [self showTipsProcessedNotificationIfNeccessary]; } [self fetchBalance:nil]; } if ((result == ledger::type::Result::LEDGER_OK && contribution->type == ledger::type::RewardsType::AUTO_CONTRIBUTE) || result == ledger::type::Result::LEDGER_ERROR || result == ledger::type::Result::NOT_ENOUGH_FUNDS || result == ledger::type::Result::TIP_ERROR) { const auto contributionId = [NSString stringWithUTF8String:contribution->contribution_id.c_str()]; const auto info = @{ @"viewingId": contributionId, @"result": @((BATResult)result), @"type": @((BATRewardsType)contribution->type), @"amount": [@(contribution->amount) stringValue] }; [self addNotificationOfKind:BATRewardsNotificationKindAutoContribute userInfo:info notificationID:[NSString stringWithFormat:@"contribution_%@", contributionId]]; } for (BATBraveLedgerObserver *observer in [self.observers copy]) { if (observer.balanceReportUpdated) { observer.balanceReportUpdated(); } if (observer.reconcileCompleted) { observer.reconcileCompleted(static_cast<BATResult>(result), [NSString stringWithUTF8String:contribution->contribution_id.c_str()], static_cast<BATRewardsType>(contribution->type), [@(contribution->amount) stringValue]); } } } #pragma mark - Misc + (bool)isMediaURL:(NSURL *)url firstPartyURL:(NSURL *)firstPartyURL referrerURL:(NSURL *)referrerURL { std::string referrer = referrerURL != nil ? referrerURL.absoluteString.UTF8String : ""; return ledger::Ledger::IsMediaLink(url.absoluteString.UTF8String, firstPartyURL.absoluteString.UTF8String, referrer); } - (NSString *)encodedURI:(NSString *)uri { const auto encoded = ledger->URIEncode(std::string(uri.UTF8String)); return [NSString stringWithUTF8String:encoded.c_str()]; } - (void)rewardsInternalInfo:(void (NS_NOESCAPE ^)(BATRewardsInternalsInfo * _Nullable info))completion { ledger->GetRewardsInternalsInfo(^(ledger::type::RewardsInternalsInfoPtr info) { auto bridgedInfo = info.get() != nullptr ? [[BATRewardsInternalsInfo alloc] initWithRewardsInternalsInfo:*info.get()] : nil; completion(bridgedInfo); }); } - (void)allContributions:(void (^)(NSArray<BATContributionInfo *> *contributions))completion { ledger->GetAllContributions(^(ledger::type::ContributionInfoList list) { const auto convetedList = NSArrayFromVector(&list, ^BATContributionInfo *(const ledger::type::ContributionInfoPtr& info){ return [[BATContributionInfo alloc] initWithContributionInfo:*info]; }); completion(convetedList); }); } #pragma mark - Reporting - (void)setSelectedTabId:(UInt32)selectedTabId { if (!self.initialized) { return; } if (_selectedTabId != selectedTabId) { ledger->OnHide(_selectedTabId, [[NSDate date] timeIntervalSince1970]); } _selectedTabId = selectedTabId; if (_selectedTabId > 0) { ledger->OnShow(_selectedTabId, [[NSDate date] timeIntervalSince1970]); } } - (void)applicationDidBecomeActive { if (!self.initialized) { return; } ledger->OnForeground(self.selectedTabId, [[NSDate date] timeIntervalSince1970]); // Check if the last notification check was more than a day ago if (fabs([self.lastNotificationCheckDate timeIntervalSinceNow]) > kOneDay) { [self checkForNotificationsAndFetchGrants]; } } - (void)applicationDidBackground { if (!self.initialized) { return; } ledger->OnBackground(self.selectedTabId, [[NSDate date] timeIntervalSince1970]); } - (void)reportLoadedPageWithURL:(NSURL *)url tabId:(UInt32)tabId { if (!self.initialized) { return; } GURL parsedUrl(url.absoluteString.UTF8String); auto origin = parsedUrl.GetOrigin(); const std::string baseDomain = GetDomainAndRegistry(origin.host(), net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); if (baseDomain == "") { return; } const std::string publisher_url = origin.scheme() + "://" + baseDomain + "/"; ledger::type::VisitDataPtr data = ledger::type::VisitData::New(); data->tld = data->name = baseDomain; data->domain = origin.host(); data->path = parsedUrl.path(); data->tab_id = tabId; data->url = publisher_url; ledger->OnLoad(std::move(data), [[NSDate date] timeIntervalSince1970]); } - (void)reportXHRLoad:(NSURL *)url tabId:(UInt32)tabId firstPartyURL:(NSURL *)firstPartyURL referrerURL:(NSURL *)referrerURL { if (!self.initialized) { return; } std::map<std::string, std::string> partsMap; const auto urlComponents = [[NSURLComponents alloc] initWithURL:url resolvingAgainstBaseURL:NO]; for (NSURLQueryItem *item in urlComponents.queryItems) { std::string value = item.value != nil ? item.value.UTF8String : ""; partsMap[std::string(item.name.UTF8String)] = value; } auto visit = ledger::type::VisitData::New(); visit->path = url.absoluteString.UTF8String; visit->tab_id = tabId; std::string ref = referrerURL != nil ? referrerURL.absoluteString.UTF8String : ""; std::string fpu = firstPartyURL != nil ? firstPartyURL.absoluteString.UTF8String : ""; ledger->OnXHRLoad(tabId, url.absoluteString.UTF8String, partsMap, fpu, ref, std::move(visit)); } - (void)reportPostData:(NSData *)postData url:(NSURL *)url tabId:(UInt32)tabId firstPartyURL:(NSURL *)firstPartyURL referrerURL:(NSURL *)referrerURL { if (!self.initialized) { return; } GURL parsedUrl(url.absoluteString.UTF8String); if (!parsedUrl.is_valid()) { return; } const auto postDataString = [[[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding] stringByRemovingPercentEncoding]; auto visit = ledger::type::VisitData::New(); visit->path = parsedUrl.spec(); visit->tab_id = tabId; std::string ref = referrerURL != nil ? referrerURL.absoluteString.UTF8String : ""; std::string fpu = firstPartyURL != nil ? firstPartyURL.absoluteString.UTF8String : ""; ledger->OnPostData(parsedUrl.spec(), fpu, ref, postDataString.UTF8String, std::move(visit)); } - (void)reportTabNavigationOrClosedWithTabId:(UInt32)tabId { if (!self.initialized) { return; } ledger->OnUnload(tabId, [[NSDate date] timeIntervalSince1970]); } #pragma mark - Preferences BATLedgerReadonlyBridge(BOOL, isEnabled, GetRewardsMainEnabled) - (void)setEnabled:(BOOL)enabled { ledger->SetRewardsMainEnabled(enabled); if (enabled) { [self.ads initializeIfAdsEnabled]; } else { [self.ads shutdown]; } for (BATBraveLedgerObserver *observer in [self.observers copy]) { if (observer.rewardsEnabledStateUpdated) { observer.rewardsEnabledStateUpdated(enabled); } } } BATLedgerBridge(int, minimumVisitDuration, setMinimumVisitDuration, GetPublisherMinVisitTime, SetPublisherMinVisitTime) BATLedgerBridge(int, minimumNumberOfVisits, setMinimumNumberOfVisits, GetPublisherMinVisits, SetPublisherMinVisits) BATLedgerBridge(BOOL, allowUnverifiedPublishers, setAllowUnverifiedPublishers, GetPublisherAllowNonVerified, SetPublisherAllowNonVerified) BATLedgerBridge(BOOL, allowVideoContributions, setAllowVideoContributions, GetPublisherAllowVideos, SetPublisherAllowVideos) BATLedgerReadonlyBridge(double, contributionAmount, GetAutoContributionAmount) - (void)setContributionAmount:(double)contributionAmount { ledger->SetAutoContributionAmount(contributionAmount); } BATLedgerBridge(BOOL, isAutoContributeEnabled, setAutoContributeEnabled, GetAutoContributeEnabled, SetAutoContributeEnabled) - (void)setBooleanState:(const std::string&)name value:(bool)value { const auto key = [NSString stringWithUTF8String:name.c_str()]; self.prefs[key] = [NSNumber numberWithBool:value]; [self savePrefs]; } - (bool)getBooleanState:(const std::string&)name { const auto key = [NSString stringWithUTF8String:name.c_str()]; if (![self.prefs objectForKey:key]) { return NO; } return [self.prefs[key] boolValue]; } - (void)setIntegerState:(const std::string&)name value:(int)value { const auto key = [NSString stringWithUTF8String:name.c_str()]; self.prefs[key] = [NSNumber numberWithInt:value]; [self savePrefs]; } - (int)getIntegerState:(const std::string&)name { const auto key = [NSString stringWithUTF8String:name.c_str()]; return [self.prefs[key] intValue]; } - (void)setDoubleState:(const std::string&)name value:(double)value { const auto key = [NSString stringWithUTF8String:name.c_str()]; self.prefs[key] = [NSNumber numberWithDouble:value]; [self savePrefs]; } - (double)getDoubleState:(const std::string&)name { const auto key = [NSString stringWithUTF8String:name.c_str()]; return [self.prefs[key] doubleValue]; } - (void)setStringState:(const std::string&)name value:(const std::string&)value { const auto key = [NSString stringWithUTF8String:name.c_str()]; self.prefs[key] = [NSString stringWithUTF8String:value.c_str()]; [self savePrefs]; } - (std::string)getStringState:(const std::string&)name { const auto key = [NSString stringWithUTF8String:name.c_str()]; const auto value = (NSString *)self.prefs[key]; if (!value) { return ""; } return value.UTF8String; } - (void)setInt64State:(const std::string&)name value:(int64_t)value { const auto key = [NSString stringWithUTF8String:name.c_str()]; self.prefs[key] = [NSNumber numberWithLongLong:value]; [self savePrefs]; } - (int64_t)getInt64State:(const std::string&)name { const auto key = [NSString stringWithUTF8String:name.c_str()]; return [self.prefs[key] longLongValue]; } - (void)setUint64State:(const std::string&)name value:(uint64_t)value { const auto key = [NSString stringWithUTF8String:name.c_str()]; self.prefs[key] = [NSNumber numberWithUnsignedLongLong:value]; [self savePrefs]; } - (uint64_t)getUint64State:(const std::string&)name { const auto key = [NSString stringWithUTF8String:name.c_str()]; return [self.prefs[key] unsignedLongLongValue]; } - (void)clearState:(const std::string&)name { const auto key = [NSString stringWithUTF8String:name.c_str()]; [self.prefs removeObjectForKey:key]; [self savePrefs]; } - (bool)getBooleanOption:(const std::string&)name { DCHECK(!name.empty()); const auto it = kBoolOptions.find(name); DCHECK(it != kBoolOptions.end()); return kBoolOptions.at(name); } - (int)getIntegerOption:(const std::string&)name { DCHECK(!name.empty()); const auto it = kIntegerOptions.find(name); DCHECK(it != kIntegerOptions.end()); return kIntegerOptions.at(name); } - (double)getDoubleOption:(const std::string&)name { DCHECK(!name.empty()); const auto it = kDoubleOptions.find(name); DCHECK(it != kDoubleOptions.end()); return kDoubleOptions.at(name); } - (std::string)getStringOption:(const std::string&)name { DCHECK(!name.empty()); const auto it = kStringOptions.find(name); DCHECK(it != kStringOptions.end()); return kStringOptions.at(name); } - (int64_t)getInt64Option:(const std::string&)name { DCHECK(!name.empty()); const auto it = kInt64Options.find(name); DCHECK(it != kInt64Options.end()); return kInt64Options.at(name); } - (uint64_t)getUint64Option:(const std::string&)name { DCHECK(!name.empty()); const auto it = kUInt64Options.find(name); DCHECK(it != kUInt64Options.end()); return kUInt64Options.at(name); } #pragma mark - Notifications - (NSArray<BATRewardsNotification *> *)notifications { return [self.mNotifications copy]; } - (void)clearNotificationWithID:(NSString *)notificationID { for (BATRewardsNotification *n in self.notifications) { if ([n.id isEqualToString:notificationID]) { [self clearNotification:n]; return; } } } - (void)clearNotification:(BATRewardsNotification *)notification { [self.mNotifications removeObject:notification]; [self writeNotificationsToDisk]; for (BATBraveLedgerObserver *observer in [self.observers copy]) { if (observer.notificationsRemoved) { observer.notificationsRemoved(@[notification]); } } } - (void)clearAllNotifications { NSArray *notifications = [self.mNotifications copy]; [self.mNotifications removeAllObjects]; [self writeNotificationsToDisk]; for (BATBraveLedgerObserver *observer in [self.observers copy]) { if (observer.notificationsRemoved) { observer.notificationsRemoved(notifications); } } } - (void)startNotificationTimers { if (!self.isEnabled) { return; } dispatch_async(dispatch_get_main_queue(), ^{ // Startup timer, begins after 30-second delay. self.notificationStartupTimer = [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(checkForNotificationsAndFetchGrants) userInfo:nil repeats:NO]; }); } - (void)checkForNotificationsAndFetchGrants { self.lastNotificationCheckDate = [NSDate date]; [self showBackupNotificationIfNeccessary]; [self showAddFundsNotificationIfNeccessary]; [self fetchPromotions:nil]; } - (void)showBackupNotificationIfNeccessary { // This is currently not required as the user cannot manage their wallet on mobile... yet /* auto bootstamp = ledger->GetCreationStamp(); auto userFunded = [self.prefs[kUserHasFundedKey] boolValue]; auto backupSucceeded = [self.prefs[kBackupSucceededKey] boolValue]; if (userFunded && !backupSucceeded) { auto frequency = 10; [self.prefs[kBackupNotificationFrequencyKey] doubleValue]; auto interval = 10; [self.prefs[kBackupNotificationIntervalKey] doubleValue]; auto delta = [[NSDate date] timeIntervalSinceDate:[NSDate dateWithTimeIntervalSince1970:bootstamp]]; if (delta > interval) { auto nextBackupNotificationInterval = frequency + interval; self.prefs[kBackupNotificationIntervalKey] = @(nextBackupNotificationInterval); [self savePrefs]; [self addNotificationOfKind:BATRewardsNotificationKindBackupWallet arguments:nil notificationID:@"rewards_notification_backup_wallet"]; } } */ } - (void)showAddFundsNotificationIfNeccessary { const auto stamp = ledger->GetReconcileStamp(); const auto now = [[NSDate date] timeIntervalSince1970]; // Show add funds notification if reconciliation will occur in the // next 3 days and balance is too low. if (stamp - now > 3 * kOneDay) { return; } // Make sure it hasnt already been shown const auto upcomingAddFundsNotificationTime = [self.prefs[kNextAddFundsDateNotificationKey] doubleValue]; if (upcomingAddFundsNotificationTime != 0.0 && now < upcomingAddFundsNotificationTime) { return; } const auto __weak weakSelf = self; // Make sure they don't have a sufficient balance [self hasSufficientBalanceToReconcile:^(BOOL sufficient) { if (sufficient) { return; } const auto strongSelf = weakSelf; // Set next add funds notification in 3 days const auto nextTime = [[NSDate date] timeIntervalSince1970] + (kOneDay * 3); strongSelf.prefs[kNextAddFundsDateNotificationKey] = @(nextTime); [strongSelf savePrefs]; [strongSelf addNotificationOfKind:BATRewardsNotificationKindInsufficientFunds userInfo:nil notificationID:@"rewards_notification_insufficient_funds"]; }]; } - (void)showTipsProcessedNotificationIfNeccessary { if (!self.autoContributeEnabled) { return; } [self addNotificationOfKind:BATRewardsNotificationKindTipsProcessed userInfo:nil notificationID:@"rewards_notification_tips_processed"]; } - (void)addNotificationOfKind:(BATRewardsNotificationKind)kind userInfo:(nullable NSDictionary *)userInfo notificationID:(nullable NSString *)identifier { [self addNotificationOfKind:kind userInfo:userInfo notificationID:identifier onlyOnce:NO]; } - (void)addNotificationOfKind:(BATRewardsNotificationKind)kind userInfo:(nullable NSDictionary *)userInfo notificationID:(nullable NSString *)identifier onlyOnce:(BOOL)onlyOnce { NSParameterAssert(kind != BATRewardsNotificationKindInvalid); NSString *notificationID = [identifier copy]; if (!identifier || identifier.length == 0) { notificationID = [NSUUID UUID].UUIDString; } else if (onlyOnce) { const auto idx = [self.mNotifications indexOfObjectPassingTest:^BOOL(BATRewardsNotification * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { return obj.displayed && [obj.id isEqualToString:identifier]; }]; if (idx != NSNotFound) { return; } } const auto notification = [[BATRewardsNotification alloc] initWithID:notificationID dateAdded:[[NSDate date] timeIntervalSince1970] kind:kind userInfo:userInfo]; if (onlyOnce) { notification.displayed = YES; } [self.mNotifications addObject:notification]; // Post to observers for (BATBraveLedgerObserver *observer in [self.observers copy]) { if (observer.notificationAdded) { observer.notificationAdded(notification); } } [NSNotificationCenter.defaultCenter postNotificationName:BATBraveLedgerNotificationAdded object:nil]; [self writeNotificationsToDisk]; } - (void)readNotificationsFromDisk { const auto path = [self.storagePath stringByAppendingPathComponent:@"notifications"]; const auto data = [NSData dataWithContentsOfFile:path]; if (!data) { // Nothing to read self.mNotifications = [[NSMutableArray alloc] init]; return; } NSError *error; self.mNotifications = [NSKeyedUnarchiver unarchivedObjectOfClass:NSArray.self fromData:data error:&error]; if (!self.mNotifications) { self.mNotifications = [[NSMutableArray alloc] init]; if (error) { BLOG(0, @"Failed to unarchive notifications on disk: %@", error.debugDescription); } } } - (void)writeNotificationsToDisk { const auto path = [self.storagePath stringByAppendingPathComponent:@"notifications"]; if (self.notifications.count == 0) { // Nothing to write, delete anything we have stored if ([[NSFileManager defaultManager] fileExistsAtPath:path]) { [[NSFileManager defaultManager] removeItemAtPath:path error:nil]; } return; } NSError *error; const auto data = [NSKeyedArchiver archivedDataWithRootObject:self.notifications requiringSecureCoding:YES error:&error]; if (!data) { if (error) { BLOG(0, @"Failed to write notifications to disk: %@", error.debugDescription); } return; } dispatch_async(self.fileWriteThread, ^{ [data writeToFile:path atomically:YES]; }); } #pragma mark - State - (void)loadLedgerState:(ledger::client::OnLoadCallback)callback { const auto contents = [self.commonOps loadContentsFromFileWithName:"ledger_state.json"]; if (contents.length() > 0) { callback(ledger::type::Result::LEDGER_OK, contents); } else { callback(ledger::type::Result::NO_LEDGER_STATE, contents); } [self startNotificationTimers]; } - (void)loadPublisherState:(ledger::client::OnLoadCallback)callback { const auto contents = [self.commonOps loadContentsFromFileWithName:"publisher_state.json"]; if (contents.length() > 0) { callback(ledger::type::Result::LEDGER_OK, contents); } else { callback(ledger::type::Result::NO_PUBLISHER_STATE, contents); } } - (void)loadState:(const std::string &)name callback:(ledger::client::OnLoadCallback)callback { const auto key = [NSString stringWithUTF8String:name.c_str()]; const auto value = self.state[key]; if (value) { callback(ledger::type::Result::LEDGER_OK, std::string(value.UTF8String)); } else { callback(ledger::type::Result::LEDGER_ERROR, ""); } } - (void)resetState:(const std::string &)name callback:(ledger::ResultCallback)callback { const auto key = [NSString stringWithUTF8String:name.c_str()]; self.state[key] = nil; callback(ledger::type::Result::LEDGER_OK); // In brave-core, failed callback returns `LEDGER_ERROR` NSDictionary *state = [self.state copy]; NSString *path = [self.randomStatePath copy]; dispatch_async(self.fileWriteThread, ^{ [state writeToFile:path atomically:YES]; }); } - (void)saveState:(const std::string &)name value:(const std::string &)value callback:(ledger::ResultCallback)callback { const auto key = [NSString stringWithUTF8String:name.c_str()]; self.state[key] = [NSString stringWithUTF8String:value.c_str()]; callback(ledger::type::Result::LEDGER_OK); // In brave-core, failed callback returns `LEDGER_ERROR` NSDictionary *state = [self.state copy]; NSString *path = [self.randomStatePath copy]; dispatch_async(self.fileWriteThread, ^{ [state writeToFile:path atomically:YES]; }); } #pragma mark - Network - (NSString *)customUserAgent { return self.commonOps.customUserAgent; } - (void)setCustomUserAgent:(NSString *)customUserAgent { self.commonOps.customUserAgent = [customUserAgent stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; } - (void)loadURL:(ledger::type::UrlRequestPtr)request callback:(ledger::client::LoadURLCallback)callback { std::map<ledger::type::UrlMethod, std::string> methodMap { {ledger::type::UrlMethod::GET, "GET"}, {ledger::type::UrlMethod::POST, "POST"}, {ledger::type::UrlMethod::PUT, "PUT"} }; if (!request) { request = ledger::type::UrlRequest::New(); } const auto copiedURL = [NSString stringWithUTF8String:request->url.c_str()]; return [self.commonOps loadURLRequest:request->url headers:request->headers content:request->content content_type:request->content_type method:methodMap[request->method] callback:^(const std::string& errorDescription, int statusCode, const std::string &response, const std::map<std::string, std::string> &headers) { ledger::type::UrlResponse url_response; url_response.url = copiedURL.UTF8String; url_response.error = errorDescription; url_response.status_code = statusCode; url_response.body = response; url_response.headers = base::MapToFlatMap(headers); callback(url_response); }]; } - (std::string)URIEncode:(const std::string &)value { const auto allowedCharacters = [NSMutableCharacterSet alphanumericCharacterSet]; [allowedCharacters addCharactersInString:@"-._~"]; const auto string = [NSString stringWithUTF8String:value.c_str()]; const auto encoded = [string stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters]; return std::string(encoded.UTF8String); } - (void)fetchFavIcon:(const std::string &)url faviconKey:(const std::string &)favicon_key callback:(ledger::client::FetchIconCallback)callback { if (!self.faviconFetcher) { callback(NO, std::string()); return; } const auto pageURL = [NSURL URLWithString:[NSString stringWithUTF8String:url.c_str()]]; self.faviconFetcher(pageURL, ^(NSURL * _Nullable faviconURL) { dispatch_async(dispatch_get_main_queue(), ^{ callback(faviconURL != nil, faviconURL.absoluteString.UTF8String); }); }); } #pragma mark - Logging - (void)log:(const char *)file line:(const int)line verboseLevel:(const int)verbose_level message:(const std::string &) message { rewards::LogMessage(file, line, verbose_level, [NSString stringWithUTF8String:message.c_str()]); } #pragma mark - Publisher Database - (void)handlePublisherListing:(NSArray<BATPublisherInfo *> *)publishers start:(uint32_t)start limit:(uint32_t)limit callback:(ledger::PublisherInfoListCallback)callback { callback(VectorFromNSArray(publishers, ^ledger::type::PublisherInfoPtr(BATPublisherInfo *info){ return info.cppObjPtr; })); } - (void)publisherListNormalized:(ledger::type::PublisherInfoList)list { const auto list_converted = NSArrayFromVector(&list, ^BATPublisherInfo *(const ledger::type::PublisherInfoPtr& info) { return [[BATPublisherInfo alloc] initWithPublisherInfo:*info]; }); for (BATBraveLedgerObserver *observer in [self.observers copy]) { if (observer.publisherListNormalized) { observer.publisherListNormalized(list_converted); } } } - (void)onPanelPublisherInfo:(ledger::type::Result)result publisherInfo:(ledger::type::PublisherInfoPtr)publisher_info windowId:(uint64_t)windowId { if (publisher_info.get() == nullptr || result != ledger::type::Result::LEDGER_OK) { return; } auto info = [[BATPublisherInfo alloc] initWithPublisherInfo:*publisher_info]; for (BATBraveLedgerObserver *observer in [self.observers copy]) { if (observer.fetchedPanelPublisher) { observer.fetchedPanelPublisher(info, windowId); } } } - (void)onContributeUnverifiedPublishers:(ledger::type::Result)result publisherKey:(const std::string &)publisher_key publisherName:(const std::string &)publisher_name { switch (result) { case ledger::type::Result::PENDING_NOT_ENOUGH_FUNDS: [self addNotificationOfKind:BATRewardsNotificationKindPendingNotEnoughFunds userInfo:nil notificationID:@"not_enough_funds_for_pending"]; break; case ledger::type::Result::PENDING_PUBLISHER_REMOVED: { const auto publisherID = [NSString stringWithUTF8String:publisher_key.c_str()]; for (BATBraveLedgerObserver *observer in [self.observers copy]) { if (observer.pendingContributionsRemoved) { observer.pendingContributionsRemoved(@[publisherID]); } } break; } case ledger::type::Result::VERIFIED_PUBLISHER: { const auto notificationID = [NSString stringWithFormat:@"verified_publisher_%@", [NSString stringWithUTF8String:publisher_key.c_str()]]; const auto name = [NSString stringWithUTF8String:publisher_name.c_str()]; [self addNotificationOfKind:BATRewardsNotificationKindVerifiedPublisher userInfo:@{ @"publisher_name": name } notificationID:notificationID]; break; } default: break; } } - (void)showNotification:(const std::string &)type args:(const std::vector<std::string>&)args callback:(ledger::ResultCallback)callback { const auto notificationID = [NSString stringWithUTF8String:type.c_str()]; const auto info = [[NSMutableDictionary<NSNumber *, NSString *> alloc] init]; for (NSInteger i = 0; i < args.size(); i++) { info[@(i)] = [NSString stringWithUTF8String:args[i].c_str()]; } [self addNotificationOfKind:BATRewardsNotificationKindGeneralLedger userInfo:info notificationID:notificationID onlyOnce:NO]; } - (ledger::type::ClientInfoPtr)getClientInfo { auto info = ledger::type::ClientInfo::New(); info->os = ledger::type::OperatingSystem::UNDEFINED; info->platform = ledger::type::Platform::IOS; return info; } - (void)unblindedTokensReady { [self fetchBalance:nil]; for (BATBraveLedgerObserver *observer in [self.observers copy]) { if (observer.balanceReportUpdated) { observer.balanceReportUpdated(); } } } - (void)reconcileStampReset { for (BATBraveLedgerObserver *observer in [self.observers copy]) { if (observer.reconcileStampReset) { observer.reconcileStampReset(); } } } - (void)runDBTransaction:(ledger::type::DBTransactionPtr)transaction callback:(ledger::client::RunDBTransactionCallback)callback { if (!rewardsDatabase || transaction.get() == nullptr) { auto response = ledger::type::DBCommandResponse::New(); response->status = ledger::type::DBCommandResponse::Status::RESPONSE_ERROR; callback(std::move(response)); } else { __block auto transactionClone = transaction->Clone(); dispatch_async(self.databaseQueue, ^{ __block auto response = ledger::type::DBCommandResponse::New(); rewardsDatabase->RunTransaction(std::move(transactionClone), response.get()); dispatch_async(dispatch_get_main_queue(), ^{ callback(std::move(response)); }); }); } } - (void)pendingContributionSaved:(const ledger::type::Result)result { for (BATBraveLedgerObserver *observer in [self.observers copy]) { if (observer.pendingContributionAdded) { observer.pendingContributionAdded(); } } } - (void)walletDisconnected:(const std::string &)wallet_type { const auto bridgedType = static_cast<BATWalletType>([NSString stringWithUTF8String:wallet_type.c_str()]); for (BATBraveLedgerObserver *observer in self.observers) { if (observer.externalWalletDisconnected) { observer.externalWalletDisconnected(bridgedType); } } } - (void)deleteLog:(ledger::ResultCallback)callback { // TODO implement } - (bool)setEncryptedStringState:(const std::string&)key value:(const std::string&)value { const auto bridgedKey = [NSString stringWithUTF8String:key.c_str()]; std::string encrypted_value; if (!OSCrypt::EncryptString(value, &encrypted_value)) { BLOG(0, @"Couldn't encrypt value for %@", bridgedKey); return false; } std::string encoded_value; base::Base64Encode(encrypted_value, &encoded_value); self.prefs[bridgedKey] = [NSString stringWithUTF8String:encoded_value.c_str()]; [self savePrefs]; return true; } - (std::string)getEncryptedStringState:(const std::string&)key { const auto bridgedKey = [NSString stringWithUTF8String:key.c_str()]; NSString *savedValue = self.prefs[bridgedKey]; if (!savedValue || ![savedValue isKindOfClass:NSString.class]) { return ""; } std::string encoded_value = savedValue.UTF8String; std::string encrypted_value; if (!base::Base64Decode(encoded_value, &encrypted_value)) { BLOG(0, @"base64 decode failed for %@", bridgedKey); return ""; } std::string value; if (!OSCrypt::DecryptString(encrypted_value, &value)) { BLOG(0, @"Decrypting failed for %@", bridgedKey); return ""; } return value; } @end
{ "pile_set_name": "Github" }
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- import uuid from msrest.pipeline import ClientRawResponse from msrestazure.azure_exceptions import CloudError from .. import models class UsagesOperations(object): """UsagesOperations operations. :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. :ivar api_version: The API version to use for this operation. Constant value: "2018-07-01". """ models = models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self.api_version = "2018-07-01" self.config = config def list_by_location( self, location, custom_headers=None, raw=False, **operation_config): """Gets the current usage count and the limit for the resources of the location under the subscription. :param location: The location of the Azure Storage resource. :type location: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: An iterator like instance of Usage :rtype: ~azure.mgmt.storage.v2018_07_01.models.UsagePaged[~azure.mgmt.storage.v2018_07_01.models.Usage] :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ def internal_paging(next_link=None, raw=False): if not next_link: # Construct URL url = self.list_by_location.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str', min_length=1), 'location': self._serialize.url("location", location, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str', min_length=1) else: url = next_link query_parameters = {} # Construct headers header_parameters = {} header_parameters['Accept'] = 'application/json' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters, header_parameters) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp return response # Deserialize response deserialized = models.UsagePaged(internal_paging, self._deserialize.dependencies) if raw: header_dict = {} client_raw_response = models.UsagePaged(internal_paging, self._deserialize.dependencies, header_dict) return client_raw_response return deserialized list_by_location.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Storage/locations/{location}/usages'}
{ "pile_set_name": "Github" }
7a576933ab047f344fba6280025b169c99afca733a98166f1843815c32e19d825d023f848e8c3b09f0d10dff64c452fc6a0f246c6570e37b86d3ea04ae5a3546
{ "pile_set_name": "Github" }
Retrying in 1 seconds
{ "pile_set_name": "Github" }
/** * Originally from: https://github.com/jorgeecardona/ansi-to-html * Modified by jschorr: Add ability to repeat existing styles and not close them out automatically. */ angular.module('ansiToHtml', []).value('ansi2html', (function() { // Define the styles supported from ANSI. var STYLES = { 'ef0': 'color:#000', 'ef1': 'color:#A00', 'ef2': 'color:#0A0', 'ef3': 'color:#A50', 'ef4': 'color:#00A', 'ef5': 'color:#A0A', 'ef6': 'color:#0AA', 'ef7': 'color:#AAA', 'ef8': 'color:#555', 'ef9': 'color:#F55', 'ef10': 'color:#5F5', 'ef11': 'color:#FF5', 'ef12': 'color:#55F', 'ef13': 'color:#F5F', 'ef14': 'color:#5FF', 'ef15': 'color:#FFF', 'eb0': 'background-color:#000', 'eb1': 'background-color:#A00', 'eb2': 'background-color:#0A0', 'eb3': 'background-color:#A50', 'eb4': 'background-color:#00A', 'eb5': 'background-color:#A0A', 'eb6': 'background-color:#0AA', 'eb7': 'background-color:#AAA', 'eb8': 'background-color:#555', 'eb9': 'background-color:#F55', 'eb10': 'background-color:#5F5', 'eb11': 'background-color:#FF5', 'eb12': 'background-color:#55F', 'eb13': 'background-color:#F5F', 'eb14': 'background-color:#5FF', 'eb15': 'background-color:#FFF' }; // Define the default styles. var DEFAULTS = { fg: '#FFF', bg: '#000' }; var __slice = [].slice; var toHexString = function(num) { num = num.toString(16); while (num.length < 2) { num = "0" + num; } return num; }; var escapeHtml = function (unsafe) { return unsafe .replace(/&/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;") .replace(/"/g, "&quot;") .replace(/'/g, "&#039;"); }; // Define the derived styles. [0, 1, 2, 3, 4, 5].forEach( function(red) { return [0, 1, 2, 3, 4, 5].forEach( function(green) { return [0, 1, 2, 3, 4, 5].forEach( function(blue) { var b, c, g, n, r, rgb; c = 16 + (red * 36) + (green * 6) + blue; r = red > 0 ? red * 40 + 55 : 0; g = green > 0 ? green * 40 + 55 : 0; b = blue > 0 ? blue * 40 + 55 : 0; rgb = ((function() { var _i, _len, _ref, _results; _ref = [r, g, b]; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { n = _ref[_i]; _results.push(toHexString(n)); } return _results; })()).join(''); STYLES["ef" + c] = "color:#" + rgb; return STYLES["eb" + c] = "background-color:#" + rgb; }); }); }); (function() { _results = []; for (_i = 0; _i <= 23; _i++){ _results.push(_i); } return _results; }).apply(this).forEach( function(gray) { var c, l; c = gray + 232; l = toHexString(gray * 10 + 8); STYLES["ef" + c] = "color:#" + l + l + l; return STYLES["eb" + c] = "background-color:#" + l + l + l; }); // Define the filter class which will track all the ANSI style state. function Filter(options) { this.opts = $.extend(true, DEFAULTS, options || {}); this.input = []; this.stack = []; } Filter.create = function() { return new Filter(); }; Filter.prototype.toHtml = function(input) { this.resetStyles(); var html = this.addInputToStream(input) + this.getTeardownHtml(); this.resetStyles(); return html; }; Filter.prototype.addInputToStream = function(input) { var buf = []; this.input = typeof input === 'string' ? [input] : input; this.forEach(function(chunk) { return buf.push(chunk); }); return buf.join(''); }; Filter.prototype.getSetupHtml = function() { return this.stack.map(function(data) { return data['html']; }).join(''); }; Filter.prototype.getTeardownHtml = function() { var stackCopy = this.stack.slice(); return stackCopy.reverse().map(function(data) { return "</" + data['kind'] + ">"; }).join(''); }; Filter.prototype.forEach = function(callback) { var that = this; var buf = ''; var handleDisplay = function(code) { code = parseInt(code, 10); if (code === -1) { callback('<br/>'); } if (code === 0) { callback(that.getTeardownHtml()); that.resetStyles(); } if (code === 1) { callback(that.pushTag('b')); } if (code === 2) { } if ((2 < code && code < 5)) { callback(that.pushTag('u')); } if ((4 < code && code < 7)) { callback(that.pushTag('blink')); } if (code === 7) { } if (code === 8) { callback(that.pushStyle('display:none')); } if (code === 9) { callback(that.pushTag('strike')); } if (code === 24) { callback(that.closeTag('u')); } if ((29 < code && code < 38)) { callback(that.pushStyle("ef" + (code - 30))); } if (code === 39) { callback(that.pushStyle("color:" + that.opts.fg)); } if ((39 < code && code < 48)) { callback(that.pushStyle("eb" + (code - 40))); } if (code === 49) { callback(that.pushStyle("background-color:" + that.opts.bg)); } if ((89 < code && code < 98)) { callback(that.pushStyle("ef" + (8 + (code - 90)))); } if ((99 < code && code < 108)) { return callback(that.pushStyle("eb" + (8 + (code - 100)))); } }; this.input.forEach(function(chunk) { buf += chunk; return that.tokenize(buf, function(tok, data) { switch (tok) { case 'text': return callback(escapeHtml(data)); case 'display': return handleDisplay(data); case 'xterm256': return callback(that.pushStyle("ef" + data)); } }); }); }; Filter.prototype.pushTag = function(tag, style) { if (style == null) { style = ''; } if (style.length && style.indexOf(':') === -1) { style = STYLES[style]; } var html = ["<" + tag, (style ? " style=\"" + style + "\"" : void 0), ">"].join(''); this.stack.push({'html': html, 'kind': tag}); return html; }; Filter.prototype.pushStyle = function(style) { return this.pushTag("span", style); }; Filter.prototype.closeTag = function(style) { var last; if (this.stack.slice(-1)[0]['kind'] === style) { last = this.stack.pop(); } if (last != null) { return "</" + style + ">"; } }; Filter.prototype.resetStyles = function() { this.stack = []; }; Filter.prototype.tokenize = function(text, callback) { var ansiHandler, ansiMatch, ansiMess, handler, i, length, newline, process, realText, remove, removeXterm256, tokens, _j, _len, _results1, _this = this; ansiMatch = false; ansiHandler = 3; remove = function(m) { return ''; }; removeXterm256 = function(m, g1) { callback('xterm256', g1); return ''; }; newline = function(m) { if (_this.opts.newline) { callback('display', -1); } else { callback('text', m); } return ''; }; ansiMess = function(m, g1) { var code, _j, _len; ansiMatch = true; if (g1.trim().length === 0) { g1 = '0'; } g1 = g1.trimRight(';').split(';'); for (_j = 0, _len = g1.length; _j < _len; _j++) { code = g1[_j]; callback('display', code); } return ''; }; realText = function(m) { callback('text', m); return ''; }; tokens = [ { pattern: /^\x08+/, sub: remove }, { pattern: /^\x1b\[38;5;(\d+)m/, sub: removeXterm256 }, { pattern: /^\n+/, sub: newline }, { pattern: /^\x1b\[((?:\d{1,3};?)+|)m/, sub: ansiMess }, { pattern: /^\x1b\[?[\d;]{0,3}/, sub: remove }, { pattern: /^([^\x1b\x08\n]+)/, sub: realText } ]; process = function(handler, i) { var matches; if (i > ansiHandler && ansiMatch) { return; } else { ansiMatch = false; } matches = text.match(handler.pattern); text = text.replace(handler.pattern, handler.sub); }; _results1 = []; while ((length = text.length) > 0) { for (i = _j = 0, _len = tokens.length; _j < _len; i = ++_j) { handler = tokens[i]; process(handler, i); } if (text.length === length) { break; } else { _results1.push(void 0); } } return _results1; }; return Filter; })());
{ "pile_set_name": "Github" }
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.build.jetifier.core.pom /** * Contains sets of mappings for dependency version variables. * * E.g. alpha1 => { newSlVersion: 1.0.0-alpha1, newArchVersion: 2.0.0-alpha1 } */ data class DependencyVersionsMap(val data: Map<String, Map<String, String>>) { companion object { val EMPTY = DependencyVersionsMap(emptyMap()) } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleExecutable</key> <string>${EXECUTABLE_NAME}</string> <key>CFBundleIdentifier</key> <string>${PRODUCT_BUNDLE_IDENTIFIER}</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>${PRODUCT_NAME}</string> <key>CFBundlePackageType</key> <string>FMWK</string> <key>CFBundleShortVersionString</key> <string>8.0.1</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleVersion</key> <string>${CURRENT_PROJECT_VERSION}</string> <key>NSPrincipalClass</key> <string></string> </dict> </plist>
{ "pile_set_name": "Github" }
var redis = require("redis"), client1 = redis.createClient(), msg_count = 0, client2 = redis.createClient(); redis.debug_mode = false; // Most clients probably don't do much on "subscribe". This example uses it to coordinate things within one program. client1.on("subscribe", function (channel, count) { console.log("client1 subscribed to " + channel + ", " + count + " total subscriptions"); if (count === 2) { client2.publish("a nice channel", "I am sending a message."); client2.publish("another one", "I am sending a second message."); client2.publish("a nice channel", "I am sending my last message."); } }); client1.on("unsubscribe", function (channel, count) { console.log("client1 unsubscribed from " + channel + ", " + count + " total subscriptions"); if (count === 0) { client2.end(); client1.end(); } }); client1.on("message", function (channel, message) { console.log("client1 channel " + channel + ": " + message); msg_count += 1; if (msg_count === 3) { client1.unsubscribe(); } }); client1.on("ready", function () { // if you need auth, do it here client1.incr("did a thing"); client1.subscribe("a nice channel", "another one"); }); client2.on("ready", function () { // if you need auth, do it here });
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <Scheme LastUpgradeVersion = "0830" version = "1.3"> <BuildAction parallelizeBuildables = "YES" buildImplicitDependencies = "YES"> <BuildActionEntries> <BuildActionEntry buildForTesting = "YES" buildForRunning = "YES" buildForProfiling = "YES" buildForArchiving = "YES" buildForAnalyzing = "YES"> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "1F17B5011E9E614C00BF1239" BuildableName = "Inkwell.framework" BlueprintName = "Inkwell" ReferencedContainer = "container:Inkwell.xcodeproj"> </BuildableReference> </BuildActionEntry> <BuildActionEntry buildForTesting = "YES" buildForRunning = "NO" buildForProfiling = "NO" buildForArchiving = "NO" buildForAnalyzing = "YES"> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "1F17B50A1E9E614D00BF1239" BuildableName = "InkwellTests.xctest" BlueprintName = "InkwellTests" ReferencedContainer = "container:Inkwell.xcodeproj"> </BuildableReference> </BuildActionEntry> </BuildActionEntries> </BuildAction> <TestAction buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" shouldUseLaunchSchemeArgsEnv = "YES"> <Testables> <TestableReference skipped = "NO"> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "1F17B50A1E9E614D00BF1239" BuildableName = "InkwellTests.xctest" BlueprintName = "InkwellTests" ReferencedContainer = "container:Inkwell.xcodeproj"> </BuildableReference> </TestableReference> </Testables> <MacroExpansion> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "1F17B5011E9E614C00BF1239" BuildableName = "Inkwell.framework" BlueprintName = "Inkwell" ReferencedContainer = "container:Inkwell.xcodeproj"> </BuildableReference> </MacroExpansion> <AdditionalOptions> </AdditionalOptions> </TestAction> <LaunchAction buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" launchStyle = "0" useCustomWorkingDirectory = "NO" ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" allowLocationSimulation = "YES"> <MacroExpansion> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "1F17B5011E9E614C00BF1239" BuildableName = "Inkwell.framework" BlueprintName = "Inkwell" ReferencedContainer = "container:Inkwell.xcodeproj"> </BuildableReference> </MacroExpansion> <AdditionalOptions> </AdditionalOptions> </LaunchAction> <ProfileAction buildConfiguration = "Release" shouldUseLaunchSchemeArgsEnv = "YES" savedToolIdentifier = "" useCustomWorkingDirectory = "NO" debugDocumentVersioning = "YES"> <MacroExpansion> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "1F17B5011E9E614C00BF1239" BuildableName = "Inkwell.framework" BlueprintName = "Inkwell" ReferencedContainer = "container:Inkwell.xcodeproj"> </BuildableReference> </MacroExpansion> </ProfileAction> <AnalyzeAction buildConfiguration = "Debug"> </AnalyzeAction> <ArchiveAction buildConfiguration = "Release" revealArchiveInOrganizer = "YES"> </ArchiveAction> </Scheme>
{ "pile_set_name": "Github" }
title: Shiro 源码分析(4) - 数据域(Realm) date: 2018-01-05 tag: categories: Shiro permalink: Shiro/xiaoqiyiye/Realm author: xiaoqiyiye from_url: https://my.oschina.net/xiaoqiyiye/blog/1618341 wechat_url: ------- 摘要: 原创出处 https://my.oschina.net/xiaoqiyiye/blog/1618341 「xiaoqiyiye」欢迎转载,保留摘要,谢谢! - [CachingRealm抽象类](http://www.iocoder.cn/Shiro/xiaoqiyiye/Realm/) - [AuthenticatingRealm抽象类](http://www.iocoder.cn/Shiro/xiaoqiyiye/Realm/) - [AuthorizingRealm抽象类](http://www.iocoder.cn/Shiro/xiaoqiyiye/Realm/) - [基于Jdbc的Realm(JdbcRealm类)](http://www.iocoder.cn/Shiro/xiaoqiyiye/Realm/) - [总结](http://www.iocoder.cn/Shiro/xiaoqiyiye/Realm/) ------- ![](http://www.iocoder.cn/images/common/wechat_mp_2017_07_31.jpg) > 🙂🙂🙂关注**微信公众号:【芋道源码】**有福利: > 1. RocketMQ / MyCAT / Sharding-JDBC **所有**源码分析文章列表 > 2. RocketMQ / MyCAT / Sharding-JDBC **中文注释源码 GitHub 地址** > 3. 您对于源码的疑问每条留言**都**将得到**认真**回复。**甚至不知道如何读源码也可以请教噢**。 > 4. **新的**源码解析文章**实时**收到通知。**每周更新一篇左右**。 > 5. **认真的**源码交流微信群。 ------- ``` 本文在于分析Shiro源码,对于新学习的朋友可以参考 [开涛博客](http://jinnianshilongnian.iteye.com/blog/2018398)进行学习。 ``` 本篇主要分析Shiro中的Realm接口。Shiro使用Realm接口作为外部数据源,主要处理认证和授权工作。Realm接口如下。 ```Java public interface Realm { /** * Realm必须要有一个唯一的名称 */ String getName(); /** * 判断该Realm是否支持处理给定的token认证 */ boolean supports(AuthenticationToken token); /** * 认证token,并返回已认证的AuthenticationInfo * 如果没有账户可以认证,返回null,如果认证失败抛出异常 */ AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException; } ``` # CachingRealm抽象类 CachingRealm是带有缓存功能的Realm抽象实现。在CachingRealm中提供了对Realm进行缓存功能的缓存管理器CacheManager,但并没有实现具体缓存什么。在CachingRealm中提供了对onLogout的处理,该方法从LogoutAware实现来,用来处理用户登出后清理缓存数据。Shiro默认对Realm开启缓存功能。 ```Java // Realm名称 private String name; // 是否开启缓存,默认构造方法开启缓存 private boolean cachingEnabled; // 缓存管理器 private CacheManager cacheManager; public CachingRealm() { this.cachingEnabled = true; this.name = getClass().getName() + "_" + INSTANCE_COUNT.getAndIncrement(); } ``` 值得一提的是afterCacheManagerSet()这个钩子方法,在设置缓存处理器后会调用这个方法,在后面的分析中会由子类重写。 ```Java public void setCacheManager(CacheManager cacheManager) { this.cacheManager = cacheManager; afterCacheManagerSet(); } protected void afterCacheManagerSet() { } ``` # AuthenticatingRealm抽象类 AuthenticatingRealm是一个可认证的Realm抽象实现类。 AuthenticatingRealm继承了CachingRealm,并实现了Initializable。Initializable提供的init()方法在初始化时会调用。下面是AuthenticatingRealm的属性和构造方法。 ```Java // 凭证匹配器,用来匹配凭证是否正确 private CredentialsMatcher credentialsMatcher; // 缓存通过认证的认证数据 private Cache<Object, AuthenticationInfo> authenticationCache; // 是否认证缓存 private boolean authenticationCachingEnabled; // 认证缓存的名称 private String authenticationCacheName; /** * 定义Realm支持的AuthenticationToken类型 */ private Class<? extends AuthenticationToken> authenticationTokenClass; public AuthenticatingRealm() { this(null, new SimpleCredentialsMatcher()); } public AuthenticatingRealm(CacheManager cacheManager) { this(cacheManager, new SimpleCredentialsMatcher()); } public AuthenticatingRealm(CredentialsMatcher matcher) { this(null, matcher); } public AuthenticatingRealm(CacheManager cacheManager, CredentialsMatcher matcher) { // 默认支持UsernamePasswordToken类型 authenticationTokenClass = UsernamePasswordToken.class; // 认证不缓存 this.authenticationCachingEnabled = false; // 设置认证缓存的名称 int instanceNumber = INSTANCE_COUNT.getAndIncrement(); this.authenticationCacheName = getClass().getName() + DEFAULT_AUTHORIZATION_CACHE_SUFFIX; if (instanceNumber > 0) { this.authenticationCacheName = this.authenticationCacheName + "." + instanceNumber; } // 设置缓存管理器 if (cacheManager != null) { setCacheManager(cacheManager); } // 设置凭证匹配器 if (matcher != null) { setCredentialsMatcher(matcher); } } ``` 从属性和构造方法我们可以看出,AuthenticatingRealm会进行认证,对认证的结果AuthenticationInfo进行缓存,认证时需要使用凭证匹配器来匹配凭证是否正确。下面,我们根据这个思路可以去看看进行认证的方法getAuthenticationInfo(AuthenticationToken token)。 ```Java public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { // 从认证缓存中获取认证结果 AuthenticationInfo info = getCachedAuthenticationInfo(token); if (info == null) { // 这是一个抽象方法,子类去完成认证过程 info = doGetAuthenticationInfo(token); if (token != null && info != null) { // 如果认证通过,则将认证结果缓存起来 cacheAuthenticationInfoIfPossible(token, info); } } // 匹配凭证是否正确,如果不正确将会抛出异常 if (info != null) { assertCredentialsMatch(token, info); } return info; } ``` 关于AuthenticationInfo缓存过程中的一些细节。在缓存的过程中是以AuthenticationToken中的身份进行缓存的,所有身份肯定要是唯一的。属性authenticationCache可以由外部提供,也可以通过缓存管理器生成,一般情况下authenticationCache不需要外部设置。 # AuthorizingRealm抽象类 AuthorizingRealm继承了AuthenticatingRealm,负责处理角色和权限。AuthorizingRealm的实现方式和AuthenticatingRealm一样,提供了一个抽象的doGetAuthorizationInfo(PrincipalCollection principals)方法。这里不做详细介绍,我们会在后面分析角色权限时介绍。 # 基于Jdbc的Realm(JdbcRealm类) JdbcRealm类可以直接和数据库连接,从数据中获取用户名、密码、角色、权限等数据信息。通过和数据库的直接连接来判断认证是否正确,是否有角色权限功能。 在JdbcRealm中提供了一些Sql语句常量,通过这些sql来做数据库操作。当然,操作数据肯定需要数据库数据源。 ```Java // 通过用户名查找密码的Sql语句 protected static final String DEFAULT_AUTHENTICATION_QUERY = "select password from users where username = ?"; /** * 通过用户名称查找密码和加密盐的Sql语句 */ protected static final String DEFAULT_SALTED_AUTHENTICATION_QUERY = "select password, password_salt from users where username = ?"; /** * 通过用户名查找用户所有角色 */ protected static final String DEFAULT_USER_ROLES_QUERY = "select role_name from user_roles where username = ?"; /** * 通过角色名称查找角色拥有的权限 */ protected static final String DEFAULT_PERMISSIONS_QUERY = "select permission from roles_permissions where role_name = ?"; /** * 定义了几种加盐模式: * NO_SALT - 密码没有加密盐 * CRYPT - unix加密(这种模式目前还支持) * COLUMN - 加密盐存储在数据库表字段中 * EXTERNAL - 加密盐没有存储在数据库 */ public enum SaltStyle {NO_SALT, CRYPT, COLUMN, EXTERNAL}; // 数据库数据源 protected DataSource dataSource; // 查询密码和加密盐的SQL protected String authenticationQuery = DEFAULT_AUTHENTICATION_QUERY; // 查询用户角色的SQL protected String userRolesQuery = DEFAULT_USER_ROLES_QUERY; // 查询角色拥有权限的SQL protected String permissionsQuery = DEFAULT_PERMISSIONS_QUERY; protected boolean permissionsLookupEnabled = false; // 密码没有加密盐模式 protected SaltStyle saltStyle = SaltStyle.NO_SALT; ``` 对于不同的数据库,这些默认的Sql是可以更改的,JdbcRealm都提供了相应的setter方法。那么,Jdbc是如何认证和获取角色权限的呢?下面继续分析doGetAuthenticationInfo和doGetAuthorizationInfo这两个方法。 1. 认证过程 ```Java protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { // 只支持UsernamePasswordToken类型 UsernamePasswordToken upToken = (UsernamePasswordToken) token; // 用户名 String username = upToken.getUsername(); // 用户名空判断 if (username == null) { throw new AccountException("Null usernames are not allowed by this realm."); } Connection conn = null; SimpleAuthenticationInfo info = null; try { // 获取数据库连接 conn = dataSource.getConnection(); String password = null; String salt = null; switch (saltStyle) { case NO_SALT: password = getPasswordForUser(conn, username)[0]; break; case CRYPT: // TODO: separate password and hash from getPasswordForUser[0] throw new ConfigurationException("Not implemented yet"); //break; case COLUMN: String[] queryResults = getPasswordForUser(conn, username); password = queryResults[0]; salt = queryResults[1]; break; case EXTERNAL: password = getPasswordForUser(conn, username)[0]; // 以用户名作为加密盐 salt = getSaltForUser(username); } if (password == null) { throw new UnknownAccountException("No account found for user [" + username + "]"); } // 创建一个认证信息 info = new SimpleAuthenticationInfo(username, password.toCharArray(), getName()); if (salt != null) { info.setCredentialsSalt(ByteSource.Util.bytes(salt)); } } catch (SQLException e) { throw new AuthenticationException(message, e); } finally { // 关闭数据连接 JdbcUtils.closeConnection(conn); } return info; } ``` 2 授权过程 ```Java protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { // 身份不能为空 if (principals == null) { throw new AuthorizationException("PrincipalCollection method argument cannot be null."); } // 从身份中获取用户名 String username = (String) getAvailablePrincipal(principals); Connection conn = null; Set<String> roleNames = null; Set<String> permissions = null; try { // 获取数据库连接 conn = dataSource.getConnection(); // 获取角色集合 roleNames = getRoleNamesForUser(conn, username); if (permissionsLookupEnabled) { // 获取权限集合 permissions = getPermissions(conn, username, roleNames); } } catch (SQLException e) { throw new AuthorizationException(message, e); } finally { JdbcUtils.closeConnection(conn); } // 返回带有角色权限的认证信息 SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames); info.setStringPermissions(permissions); return info; } ``` 在Shiro中还提供了一些其他的Realm。SimpleAccountRealm、TextConfigurationRealm、IniRealm、PropertiesRealm。这里就不一一介绍了,有兴趣可以自己去看。 # 总结 在Shiro中Realm接口作为一个与应用程序外接的接口,可以通过Realm提供认证和授权的数据信息。在开发使用中最常用的就是从AuthenticatingRealm或AuthorizingRealm抽象类来实现业务中具体的Realm实例。doGetAuthenticationInfo(AuthenticationToken token)处理认证过程,doGetAuthorizationInfo(PrincipalCollection principals)处理授权过程。
{ "pile_set_name": "Github" }
/* * Copyright (C) 2015 Free Electrons * Copyright (C) 2015 NextThing Co * * Boris Brezillon <[email protected]> * Maxime Ripard <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. */ #ifndef __SUN4I_TCON_H__ #define __SUN4I_TCON_H__ #include <drm/drm_crtc.h> #include <linux/kernel.h> #include <linux/list.h> #include <linux/reset.h> #define SUN4I_TCON_GCTL_REG 0x0 #define SUN4I_TCON_GCTL_TCON_ENABLE BIT(31) #define SUN4I_TCON_GCTL_IOMAP_MASK BIT(0) #define SUN4I_TCON_GCTL_IOMAP_TCON1 (1 << 0) #define SUN4I_TCON_GCTL_IOMAP_TCON0 (0 << 0) #define SUN4I_TCON_GINT0_REG 0x4 #define SUN4I_TCON_GINT0_VBLANK_ENABLE(pipe) BIT(31 - (pipe)) #define SUN4I_TCON_GINT0_VBLANK_INT(pipe) BIT(15 - (pipe)) #define SUN4I_TCON_GINT1_REG 0x8 #define SUN4I_TCON_FRM_CTL_REG 0x10 #define SUN4I_TCON0_CTL_REG 0x40 #define SUN4I_TCON0_CTL_TCON_ENABLE BIT(31) #define SUN4I_TCON0_CTL_CLK_DELAY_MASK GENMASK(8, 4) #define SUN4I_TCON0_CTL_CLK_DELAY(delay) ((delay << 4) & SUN4I_TCON0_CTL_CLK_DELAY_MASK) #define SUN4I_TCON0_DCLK_REG 0x44 #define SUN4I_TCON0_DCLK_GATE_BIT (31) #define SUN4I_TCON0_DCLK_DIV_SHIFT (0) #define SUN4I_TCON0_DCLK_DIV_WIDTH (7) #define SUN4I_TCON0_BASIC0_REG 0x48 #define SUN4I_TCON0_BASIC0_X(width) ((((width) - 1) & 0xfff) << 16) #define SUN4I_TCON0_BASIC0_Y(height) (((height) - 1) & 0xfff) #define SUN4I_TCON0_BASIC1_REG 0x4c #define SUN4I_TCON0_BASIC1_H_TOTAL(total) ((((total) - 1) & 0x1fff) << 16) #define SUN4I_TCON0_BASIC1_H_BACKPORCH(bp) (((bp) - 1) & 0xfff) #define SUN4I_TCON0_BASIC2_REG 0x50 #define SUN4I_TCON0_BASIC2_V_TOTAL(total) (((total) & 0x1fff) << 16) #define SUN4I_TCON0_BASIC2_V_BACKPORCH(bp) (((bp) - 1) & 0xfff) #define SUN4I_TCON0_BASIC3_REG 0x54 #define SUN4I_TCON0_BASIC3_H_SYNC(width) ((((width) - 1) & 0x7ff) << 16) #define SUN4I_TCON0_BASIC3_V_SYNC(height) (((height) - 1) & 0x7ff) #define SUN4I_TCON0_HV_IF_REG 0x58 #define SUN4I_TCON0_CPU_IF_REG 0x60 #define SUN4I_TCON0_CPU_WR_REG 0x64 #define SUN4I_TCON0_CPU_RD0_REG 0x68 #define SUN4I_TCON0_CPU_RDA_REG 0x6c #define SUN4I_TCON0_TTL0_REG 0x70 #define SUN4I_TCON0_TTL1_REG 0x74 #define SUN4I_TCON0_TTL2_REG 0x78 #define SUN4I_TCON0_TTL3_REG 0x7c #define SUN4I_TCON0_TTL4_REG 0x80 #define SUN4I_TCON0_LVDS_IF_REG 0x84 #define SUN4I_TCON0_IO_POL_REG 0x88 #define SUN4I_TCON0_IO_POL_DCLK_PHASE(phase) ((phase & 3) << 28) #define SUN4I_TCON0_IO_POL_HSYNC_POSITIVE BIT(25) #define SUN4I_TCON0_IO_POL_VSYNC_POSITIVE BIT(24) #define SUN4I_TCON0_IO_TRI_REG 0x8c #define SUN4I_TCON0_IO_TRI_HSYNC_DISABLE BIT(25) #define SUN4I_TCON0_IO_TRI_VSYNC_DISABLE BIT(24) #define SUN4I_TCON0_IO_TRI_DATA_PINS_DISABLE(pins) GENMASK(pins, 0) #define SUN4I_TCON1_CTL_REG 0x90 #define SUN4I_TCON1_CTL_TCON_ENABLE BIT(31) #define SUN4I_TCON1_CTL_INTERLACE_ENABLE BIT(20) #define SUN4I_TCON1_CTL_CLK_DELAY_MASK GENMASK(8, 4) #define SUN4I_TCON1_CTL_CLK_DELAY(delay) ((delay << 4) & SUN4I_TCON1_CTL_CLK_DELAY_MASK) #define SUN4I_TCON1_BASIC0_REG 0x94 #define SUN4I_TCON1_BASIC0_X(width) ((((width) - 1) & 0xfff) << 16) #define SUN4I_TCON1_BASIC0_Y(height) (((height) - 1) & 0xfff) #define SUN4I_TCON1_BASIC1_REG 0x98 #define SUN4I_TCON1_BASIC1_X(width) ((((width) - 1) & 0xfff) << 16) #define SUN4I_TCON1_BASIC1_Y(height) (((height) - 1) & 0xfff) #define SUN4I_TCON1_BASIC2_REG 0x9c #define SUN4I_TCON1_BASIC2_X(width) ((((width) - 1) & 0xfff) << 16) #define SUN4I_TCON1_BASIC2_Y(height) (((height) - 1) & 0xfff) #define SUN4I_TCON1_BASIC3_REG 0xa0 #define SUN4I_TCON1_BASIC3_H_TOTAL(total) ((((total) - 1) & 0x1fff) << 16) #define SUN4I_TCON1_BASIC3_H_BACKPORCH(bp) (((bp) - 1) & 0xfff) #define SUN4I_TCON1_BASIC4_REG 0xa4 #define SUN4I_TCON1_BASIC4_V_TOTAL(total) (((total) & 0x1fff) << 16) #define SUN4I_TCON1_BASIC4_V_BACKPORCH(bp) (((bp) - 1) & 0xfff) #define SUN4I_TCON1_BASIC5_REG 0xa8 #define SUN4I_TCON1_BASIC5_H_SYNC(width) ((((width) - 1) & 0x3ff) << 16) #define SUN4I_TCON1_BASIC5_V_SYNC(height) (((height) - 1) & 0x3ff) #define SUN4I_TCON1_IO_POL_REG 0xf0 #define SUN4I_TCON1_IO_TRI_REG 0xf4 #define SUN4I_TCON_CEU_CTL_REG 0x100 #define SUN4I_TCON_CEU_MUL_RR_REG 0x110 #define SUN4I_TCON_CEU_MUL_RG_REG 0x114 #define SUN4I_TCON_CEU_MUL_RB_REG 0x118 #define SUN4I_TCON_CEU_ADD_RC_REG 0x11c #define SUN4I_TCON_CEU_MUL_GR_REG 0x120 #define SUN4I_TCON_CEU_MUL_GG_REG 0x124 #define SUN4I_TCON_CEU_MUL_GB_REG 0x128 #define SUN4I_TCON_CEU_ADD_GC_REG 0x12c #define SUN4I_TCON_CEU_MUL_BR_REG 0x130 #define SUN4I_TCON_CEU_MUL_BG_REG 0x134 #define SUN4I_TCON_CEU_MUL_BB_REG 0x138 #define SUN4I_TCON_CEU_ADD_BC_REG 0x13c #define SUN4I_TCON_CEU_RANGE_R_REG 0x140 #define SUN4I_TCON_CEU_RANGE_G_REG 0x144 #define SUN4I_TCON_CEU_RANGE_B_REG 0x148 #define SUN4I_TCON_MUX_CTRL_REG 0x200 #define SUN4I_TCON1_FILL_CTL_REG 0x300 #define SUN4I_TCON1_FILL_BEG0_REG 0x304 #define SUN4I_TCON1_FILL_END0_REG 0x308 #define SUN4I_TCON1_FILL_DATA0_REG 0x30c #define SUN4I_TCON1_FILL_BEG1_REG 0x310 #define SUN4I_TCON1_FILL_END1_REG 0x314 #define SUN4I_TCON1_FILL_DATA1_REG 0x318 #define SUN4I_TCON1_FILL_BEG2_REG 0x31c #define SUN4I_TCON1_FILL_END2_REG 0x320 #define SUN4I_TCON1_FILL_DATA2_REG 0x324 #define SUN4I_TCON1_GAMMA_TABLE_REG 0x400 #define SUN4I_TCON_MAX_CHANNELS 2 struct sun4i_tcon_quirks { bool has_unknown_mux; /* sun5i has undocumented mux */ bool has_channel_1; /* a33 does not have channel 1 */ }; struct sun4i_tcon { struct device *dev; struct drm_device *drm; struct regmap *regs; /* Main bus clock */ struct clk *clk; /* Clocks for the TCON channels */ struct clk *sclk0; struct clk *sclk1; /* Pixel clock */ struct clk *dclk; /* Reset control */ struct reset_control *lcd_rst; struct drm_panel *panel; /* Platform adjustments */ const struct sun4i_tcon_quirks *quirks; /* Associated crtc */ struct sun4i_crtc *crtc; int id; /* TCON list management */ struct list_head list; }; struct drm_bridge *sun4i_tcon_find_bridge(struct device_node *node); struct drm_panel *sun4i_tcon_find_panel(struct device_node *node); /* Global Control */ void sun4i_tcon_disable(struct sun4i_tcon *tcon); void sun4i_tcon_enable(struct sun4i_tcon *tcon); /* Channel Control */ void sun4i_tcon_channel_disable(struct sun4i_tcon *tcon, int channel); void sun4i_tcon_channel_enable(struct sun4i_tcon *tcon, int channel); void sun4i_tcon_enable_vblank(struct sun4i_tcon *tcon, bool enable); /* Mode Related Controls */ void sun4i_tcon_set_mux(struct sun4i_tcon *tcon, int channel, struct drm_encoder *encoder); void sun4i_tcon0_mode_set(struct sun4i_tcon *tcon, struct drm_display_mode *mode); void sun4i_tcon1_mode_set(struct sun4i_tcon *tcon, struct drm_display_mode *mode); #endif /* __SUN4I_TCON_H__ */
{ "pile_set_name": "Github" }
#define CONFIG_WC 1
{ "pile_set_name": "Github" }
The conversation event `form` was renamed to `active_loop`. Rasa Open Source will continue to be able to read and process old `form` events. Note that serialized trackers will no longer have the `active_form` field. Instead the `active_loop` field will contain the same information. Story representations in Markdown and YAML will use `active_loop` instead of `form` to represent the event.
{ "pile_set_name": "Github" }
# Created by: TAKATSU Tomonari <[email protected]> # $FreeBSD$ PORTNAME= memoise PORTVERSION= 1.1.0 PORTREVISION= 4 CATEGORIES= devel DISTNAME= ${PORTNAME}_${PORTVERSION} MAINTAINER= [email protected] COMMENT= Memoise functions for R LICENSE= MIT CRAN_DEPENDS= R-cran-digest>=0.6.3:security/R-cran-digest BUILD_DEPENDS= ${CRAN_DEPENDS} RUN_DEPENDS= ${CRAN_DEPENDS} USES= cran:auto-plist .include <bsd.port.mk>
{ "pile_set_name": "Github" }
/* * Copyright 2006-2011, Haiku, Inc. All Rights Reserved. * Distributed under the terms of the MIT License. * * Authors: * Axel Dörfler, [email protected] */ #ifndef INTERFACES_H #define INTERFACES_H #include "routes.h" #include "stack_private.h" #include <net_datalink.h> #include <net_stack.h> #include <Referenceable.h> #include <util/AutoLock.h> #include <util/DoublyLinkedList.h> #include <util/OpenHashTable.h> struct net_device_interface; // Additional address flags #define IFAF_DIRECT_ADDRESS 0x1000 struct InterfaceAddress : DoublyLinkedListLinkImpl<InterfaceAddress>, net_interface_address, BReferenceable { InterfaceAddress(); InterfaceAddress(net_interface* interface, net_domain* domain); virtual ~InterfaceAddress(); status_t SetTo(const ifaliasreq& request); status_t SetLocal(const sockaddr* to); status_t SetDestination(const sockaddr* to); status_t SetMask(const sockaddr* to); sockaddr** AddressFor(int32 option); void AddDefaultRoutes(int32 option); void RemoveDefaultRoutes(int32 option); bool LocalIsDefined() const; InterfaceAddress*& HashTableLink() { return fLink; } #if ENABLE_DEBUGGER_COMMANDS void Dump(size_t index = 0, bool hideInterface = false); #endif static status_t Set(sockaddr** _address, const sockaddr* to); static sockaddr* Prepare(sockaddr** _address, size_t length); private: void _Init(net_interface* interface, net_domain* domain); private: InterfaceAddress* fLink; }; typedef DoublyLinkedList<InterfaceAddress> AddressList; struct domain_datalink { domain_datalink* hash_link; net_domain* domain; struct net_datalink_protocol* first_protocol; struct net_datalink_protocol_module_info* first_info; // support for binding to an interface net_route_private direct_route; InterfaceAddress direct_address; }; struct DatalinkHashDefinition { typedef const int KeyType; typedef domain_datalink ValueType; DatalinkHashDefinition() { } size_t HashKey(const KeyType& key) const { return (size_t)key; } size_t Hash(domain_datalink* datalink) const { return datalink->domain->family; } bool Compare(const KeyType& key, domain_datalink* datalink) const { return datalink->domain->family == key; } domain_datalink*& GetLink(domain_datalink* datalink) const { return datalink->hash_link; } }; typedef BOpenHashTable<DatalinkHashDefinition, true, true> DatalinkTable; class Interface : public DoublyLinkedListLinkImpl<Interface>, public net_interface, public BReferenceable { public: Interface(const char* name, net_device_interface* deviceInterface); virtual ~Interface(); InterfaceAddress* FirstForFamily(int family); InterfaceAddress* FirstUnconfiguredForFamily(int family); InterfaceAddress* AddressForDestination(net_domain* domain, const sockaddr* destination); InterfaceAddress* AddressForLocal(net_domain* domain, const sockaddr* local); status_t AddAddress(InterfaceAddress* address); void RemoveAddress(InterfaceAddress* address); bool GetNextAddress(InterfaceAddress** _address); InterfaceAddress* AddressAt(size_t index); int32 IndexOfAddress(InterfaceAddress* address); size_t CountAddresses(); void RemoveAddresses(); status_t Control(net_domain* domain, int32 option, ifreq& request, ifreq* userRequest, size_t length); void SetDown(); void WentDown(); recursive_lock& Lock() { return fLock; } net_device_interface* DeviceInterface() { return fDeviceInterface; } status_t CreateDomainDatalinkIfNeeded( net_domain* domain); domain_datalink* DomainDatalink(uint8 family); domain_datalink* DomainDatalink(net_domain* domain) { return DomainDatalink(domain->family); } inline void SetBusy(bool busy) { atomic_set(&fBusy, busy ? 1 : 0); } inline bool IsBusy() const { return atomic_get((int32*)&fBusy) == 1 ; } #if ENABLE_DEBUGGER_COMMANDS void Dump() const; #endif private: status_t _SetUp(); InterfaceAddress* _FirstForFamily(int family); status_t _ChangeAddress(RecursiveLocker& locker, InterfaceAddress* address, int32 option, const sockaddr* oldAddress, const sockaddr* newAddress); private: recursive_lock fLock; int32 fBusy; net_device_interface* fDeviceInterface; AddressList fAddresses; DatalinkTable fDatalinkTable; }; typedef DoublyLinkedList<Interface> InterfaceList; status_t init_interfaces(); status_t uninit_interfaces(); // interfaces status_t add_interface(const char* name, net_domain_private* domain, const ifaliasreq& request, net_device_interface* deviceInterface); void remove_interface(Interface* interface); void interface_removed_device_interface(net_device_interface* deviceInterface); status_t add_interface_address(Interface* interface, net_domain_private* domain, const ifaliasreq& request); status_t update_interface_address(InterfaceAddress* interfaceAddress, int32 option, const sockaddr* oldAddress, const sockaddr* newAddress); Interface* get_interface(net_domain* domain, uint32 index); Interface* get_interface(net_domain* domain, const char* name); Interface* get_interface_for_device(net_domain* domain, uint32 index); Interface* get_interface_for_link(net_domain* domain, const sockaddr* address); InterfaceAddress* get_interface_address(const struct sockaddr* address); InterfaceAddress* get_interface_address_for_destination(net_domain* domain, const sockaddr* destination); InterfaceAddress* get_interface_address_for_link(net_domain* domain, const sockaddr* linkAddress, bool unconfiguredOnly); uint32 count_interfaces(); status_t list_interfaces(int family, void* buffer, size_t* _bufferSize); #endif // INTERFACES_H
{ "pile_set_name": "Github" }
This file was derived from http://www.gutenberg.org/files/23864/23864-0.txt after converting from Traditional Chinese to Simplified Chinese. -------- 始计第一 孙子曰:兵者,国之大事,死生之地,存亡之道,不可不察也。 故经之以五事,校之以计,而索其情:一曰道,二曰天,三曰地,四曰将,五曰法。 道者,令民与上同意,可与之死,可与之生,而不畏危也;天者,阴阳、寒暑、时制也;地者,远近、险易、广狭、死生也;将者,智、信、仁、勇、严也;法者,曲制、官道、主用也。凡此五者,将莫不闻,知之者胜,不知者不胜。 故校之以计,而索其情,曰:主孰有道?将孰有能?天地孰得?法令孰行?兵眾孰强?士卒孰练?赏罚孰明?吾以此知胜负矣。 将听吾计,用之必胜,留之;将不听吾计,用之必败,去之。 计利以听,乃為之势,以佐其外。势者,因利而制权也。 兵者,诡道也。故能而示之不能,用而示之不用,近而示之远,远而示之近。利而诱之,乱而取之,实而备之,强而避之,怒而挠之,卑而骄之,佚而劳之,亲而离之,攻其无备,出其不意。此兵家之胜,不可先传也。 夫未战而庙算胜者,得算多也;未战而庙算不胜者,得算少也。多算胜,少算不胜,而况无算乎!吾以此观之,胜负见矣。 作战第二 孙子曰:凡用兵之法,驰车千駟,革车千乘,带甲十万,千里馈粮。则内外之费,宾客之用,胶漆之材,车甲之奉,日费千金,然后十万之师举矣。 其用战也,贵胜,久则钝兵挫锐,攻城则力屈,久暴师则国用不足。夫钝兵挫锐,屈力殫货,则诸侯乘其弊而起,虽有智者,不能善其后矣。故兵闻拙速,未睹巧之久也。夫兵久而国利者,未之有也。故不尽知用兵之害者,则不能尽知用兵之利也。 善用兵者,役不再籍,粮不三载,取用於国,因粮於敌,故军食可足也。国之贫於师者远输,远输则百姓贫;近於师者贵卖,贵卖则百姓竭,财竭则急於丘役。力屈财殫,中原内虚於家,百姓之费,十去其七;公家之费,破军罢马,甲胄矢弩,戟楯矛櫓,丘牛大车,十去其六。 故智将务食於敌,食敌一钟,当吾二十钟;萁秆一石,当吾二十石。故杀敌者,怒也;取敌之利者,货也。故车战,得车十乘以上,赏其先得者,而更其旌旗。车杂而乘之,卒善而养之,是谓胜敌而益强。 故兵贵胜,不贵久。故知兵之将,民之司命。国家安危之主也。 谋攻第三 孙子曰:凡用兵之法,全国為上,破国次之;全军為上,破军次之;全旅為上,破旅次之;全卒為上,破卒次之;全伍為上,破伍次之。是故百战百胜,非善之善者也;不战而屈人之兵,善之善者也。 故上兵伐谋,其次伐交,其次伐兵,其下攻城。攻城之法,為不得已。修櫓轒轀,具器械,三月而后成;距闉,又三月而后已。将不胜其忿,而蚁附之,杀士三分之一,而城不拔者,此攻之灾也。 故善用兵者,屈人之兵,而非战也,拔人之城而非攻也,毁人之国而非久也,必以全争於天下,故兵不顿而利可全,此谋攻之法也。 故用兵之法,十则围之,五则攻之,倍则分之,敌则能战之,少则能逃之,不若则能避之。故小敌之坚,大敌之擒也。 夫将者,国之辅也。辅周则国必强,辅隙则国必弱。故君之所以患於军者三:不知军之不可以进而谓之进,不知军之不可以退而谓之退,是谓縻军;不知三军之事,而同三军之政,则军士惑矣;不知三军之权,而同三军之任,则军士疑矣。三军既惑且疑,则诸侯之难至矣。是谓乱军引胜。 故知胜有五:知可以战与不可以战者,胜。识眾寡之用者,胜。上下同欲者,胜。以虞待不虞者,胜。将能而君不御者,胜。此五者,知胜之道也。 故曰:知己知彼,百战不貽;不知彼而知己,一胜一负;不知彼不知己,每战必败。 军形第四 孙子曰:昔之善战者,先為不可胜,以待敌之可胜。不可胜在己,可胜在敌。故善战者,能為不可胜,不能使敌必可胜。故曰:胜可知,而不可為。 不可胜者,守也;可胜者,攻也。守则不足,攻则有餘。善守者,藏於九地之下,善攻者,动於九天之上,故能自保而全胜也。 见胜不过眾人之所知,非善之善者也;战胜而天下曰善,非善之善者也。故举秋毫不為多力,见日月不為明目,闻雷霆不為聪耳。古之善战者,胜於易胜者也。故善战者之胜也,无智名,无勇功,故其战胜不忒。不忒者,其所措必胜,胜已败者也。故善战者,先立於不败之地,而不失敌之败也。是故胜兵先胜,而后求战,败兵先战而后求胜。善用兵者,修道而保法,故能為胜败之政。 兵法:一曰度,二曰量,三曰数,四曰称,五曰胜。地生度,度生量,量生数,数生称,称生胜。故胜兵若以鎰称銖,败兵若以銖称鎰。胜者之战,若决积水於千仞之谿者,形也。 兵势第五 孙子曰:凡治眾如治寡,分数是也;斗眾如斗寡,形名是也;三军之眾,可使必受敌而无败者,奇正是也;兵之所加,如以碫投卵者,虚实是也。 凡战者,以正合,以奇胜。故善出奇者,无穷如天地,不竭如江海。终而复始,日月是也。死而復生,四时是也。声不过五,五声之变,不可胜听也;色不过五,五色之变,不可胜观也;味不过五,五味之变,不可胜尝也;战势,不过奇正,奇正之变,不可胜穷也。奇正相生,如循环之无端,熟能穷之哉? 激水之疾,至於漂石者,势也;鷙鸟之疾,至於毁折者,节也。是故善战者,其势险,其节短。势如张弩,节如发机。 纷纷紜紜,斗乱而不可乱也;浑浑沌沌,形圆而不可败也。乱生於治,怯生於勇,弱生於强。治乱,数也;勇怯,势也;强弱,形也。故善动敌者,形之,敌必从之;予之,敌必取之。以利动之,以卒待之。 故善战者,求之於势,不责於人;故能择人而任势。任势者,其战人也,如转木石。木石之性,安则静,危则动,方则止,圆则行。故善战人之势,如转圆石於千仞之山者,势也。 虚实第六 孙子曰:凡先处战地而待敌者佚,后处战地而趋战者劳。 故善战者,致人而不致於人。能使敌人自至者,利之也;能使敌人不得至者,害之也。故敌佚能劳之,饱能饥之,安能动之。出其所必趋,趋其所不意。行千里而不劳者,行於无人之地也;攻而必取者,攻其所不守也。守而必固者,守其所不攻也。 故善攻者,敌不知其所守;善守者,敌不知其所攻。微乎微乎,至於无形;神乎神乎,至於无声,故能為敌之司命。进而不可御者,冲其虚也;退而不可追者,速而不可及也。故我欲战,敌虽高垒深沟,不得不与我战者,攻其所必救也;我不欲战,虽画地而守之,敌不得与我战者,乖其所之也。故形人而我无形,则我专而敌分。我专為一,敌分為十,是以十攻其一也。则我眾敌寡,能以眾击寡者,则吾之所与战者约矣。吾所与战之地不可知,不可知则敌所备者多,敌所备者多,则吾所与战者寡矣。故备前则后寡,备后则前寡,备左则右寡,备右则左寡,无所不备,则无所不寡。寡者,备人者也;眾者,使人备己者也。故知战之地,知战之日,则可千里而会战;不知战之地,不知战日,则左不能救右,右不能救左,前不能救后,后不能救前,而况远者数十里,近者数里乎!以吾度之,越人之兵虽多,亦奚益於胜哉!故曰:胜可為也。敌虽眾,可使无斗。故策之而知得失之计,候之而知动静之理,形之而知死生之地,角之而知有餘不足之处。故形兵之极,至於无形。无形则深间不能窥,智者不能谋。因形而措胜於眾,眾不能知。人皆知我所以胜之形,而莫知吾所以制胜之形。故其战胜不復,而应形於无穷。夫兵形象水,水之行避高而趋下,兵之形避实而击虚;水因地而制流,兵因敌而制胜。故兵无常势,水无常形。能因敌变化而取胜者,谓之神。故五行无常胜,四时无常位,日有短长,月有死生。 军争第七 孙子曰: 凡用兵之法,将受命於君,合军聚眾,交和而舍,莫难於军争。军争之难者,以迂為直,以患為利。故迂其途,而诱之以利,后人发,先人至,此知迂直之计者也。军争為利,军争為危。举军而争利则不及,委军而争利则輜重捐。是故捲甲而趋,日夜不处,倍道兼行,百裡而争利,则擒三将军,劲者先,疲者后,其法十一而至;五十里而争利,则蹶上将军,其法半至;三十里而争利,则三分之二至。是故军无輜重则亡,无粮食则亡,无委积则亡。故不知诸侯之谋者,不能豫交;不知山林、险阻、沮泽之形者,不能行军;不用乡导者,不能得地利。故兵以诈立,以利动,以分和為变者也。故其疾如风,其徐如林,侵掠如火,不动如山,难知如阴,动如雷震。掠乡分眾,廓地分利,悬权而动。先知迂直之计者胜,此军争之法也。《军政》曰:“言不相闻,故為之金鼓;视不相见,故為之旌旗。”夫金鼓旌旗者,所以一民之耳目也。民既专一,则勇者不得独进,怯者不得独退,此用眾之法也。故夜战多金鼓,昼战多旌旗,所以变人之耳目也。三军可夺气,将军可夺心。是故朝气锐,昼气惰,暮气归。善用兵者,避其锐气,击其惰归,此治气者也。以治待乱,以静待哗,此治心者也。以近待远,以佚待劳,以饱待饥,此治力者也。无邀正正之旗,无击堂堂之陈,此治变者也。故用兵之法,高陵勿向,背丘勿逆,佯北勿从,锐卒勿攻,饵兵勿食,归师勿遏,围师遗闕,穷寇勿迫,此用兵之法也。 九变第八 孙子曰: 凡用兵之法,将受命於君,合军聚合。泛地无舍,衢地合交,绝地无留,围地则谋,死地则战,途有所不由,军有所不击,城有所不攻,地有所不争,君命有所不受。故将通於九变之利者,知用兵矣;将不通九变之利,虽知地形,不能得地之利矣;治兵不知九变之术,虽知五利,不能得人之用矣。是故智者之虑,必杂於利害,杂於利而务可信也,杂於害而患可解也。是故屈诸侯者以害,役诸侯者以业,趋诸侯者以利。故用兵之法,无恃其不来,恃吾有以待之;无恃其不攻,恃吾有所不可攻也。故将有五危,必死可杀,必生可虏,忿速可侮,廉洁可辱,爱民可烦。凡此五者,将之过也,用兵之灾也。覆军杀将,必以五危,不可不察也。 行军第九 孙子曰:凡处军相敌,绝山依穀,视生处高,战隆无登,此处山之军也。绝水必远水,客绝水而来,勿迎之於水内,令半渡而击之利,欲战者,无附於水而迎客,视生处高,无迎水流,此处水上之军也。绝斥泽,唯亟去无留,若交军於斥泽之中,必依水草而背眾树,此处斥泽之军也。平陆处易,右背高,前死后生,此处平陆之军也。凡此四军之利,黄帝之所以胜四帝也。凡军好高而恶下,贵阳而贱阴,养生而处实,军无百疾,是谓必胜。丘陵堤防,必处其阳而右背之,此兵之利,地之助也。上雨水流至,欲涉者,待其定也。凡地有绝涧、天井、天牢、天罗、天陷、天隙,必亟去之,勿近也。吾远之,敌近之;吾迎之,敌背之。军旁有险阻、潢井、蒹葭、小林、蘙薈者,必谨覆索之,此伏姦之所处也。敌近而静者,恃其险也;远而挑战者,欲人之进也;其所居易者,利也;眾树动者,来也;眾草多障者,疑也;鸟起者,伏也;兽骇者,覆也;尘高而锐者,车来也;卑而广者,徒来也;散而条达者,樵採也;少而往来者,营军也;辞卑而备者,进也;辞强而进驱者,退也;轻车先出居其侧者,陈也;无约而请和者,谋也;奔走而陈兵者,期也;半进半退者,诱也;杖而立者,饥也;汲而先饮者,渴也;见利而不进者,劳也;鸟集者,虚也;夜呼者,恐也;军扰者,将不重也;旌旗动者,乱也;吏怒者,倦也;杀马肉食者,军无粮也;悬甀不返其舍者,穷寇也;谆谆翕翕,徐与人言者,失眾也;数赏者,窘也;数罚者,困也;先暴而后畏其眾者,不精之至也;来委谢者,欲休息也。兵怒而相迎,久而不合,又不相去,必谨察之。兵非贵益多也,惟无武进,足以并力料敌取人而已。夫惟无虑而易敌者,必擒於人。卒未亲而罚之,则不服,不服则难用。卒已亲附而罚不行,则不可用。故合之以文,齐之以武,是谓必取。令素行以教其民,则民服;令素不行以教其民,则民不服。令素行者,与眾相得也。 地形第十 孙子曰:地形有通者、有掛者、有支者、有隘者、有险者、有远者。我可以往,彼可以来,曰通。通形者,先居高阳,利粮道,以战则利。可以往,难以返,曰掛。掛形者,敌无备,出而胜之,敌若有备,出而不胜,难以返,不利。我出而不利,彼出而不利,曰支。支形者,敌虽利我,我无出也,引而去之,令敌半出而击之利。隘形者,我先居之,必盈之以待敌。若敌先居之,盈而勿从,不盈而从之。险形者,我先居之,必居高阳以待敌;若敌先居之,引而去之,勿从也。远形者,势均难以挑战,战而不利。凡此六者,地之道也,将之至任,不可不察也。凡兵有走者、有驰者、有陷者、有崩者、有乱者、有北者。凡此六者,非天地之灾,将之过也。夫势均,以一击十,曰走;卒强吏弱,曰驰;吏强卒弱,曰陷;大吏怒而不服,遇敌懟而自战,将不知其能,曰崩;将弱不严,教道不明,吏卒无常,陈兵纵横,曰乱;将不能料敌,以少合眾,以弱击强,兵无选锋,曰北。凡此六者,败之道也,将之至任,不可不察也。夫地形者,兵之助也。料敌制胜,计险隘远近,上将之道也。知此而用战者必胜,不知此而用战者必败。故战道必胜,主曰无战,必战可也;战道不胜,主曰必战,无战可也。故进不求名,退不避罪,唯民是保,而利於主,国之宝也。视卒如婴儿,故可以与之赴深溪;视卒如爱子,故可与之俱死。厚而不能使,爱而不能令,乱而不能治,譬若骄子,不可用也。知吾卒之可以击,而不知敌之不可击,胜之半也;知敌之可击,而不知吾卒之不可以击,胜之半也;知敌之可击,知吾卒之可以击,而不知地形之不可以战,胜之半也。故知兵者,动而不迷,举而不穷。故曰:知彼知己,胜乃不殆;知天知地,胜乃可全。 九地第十一 孙子曰:用兵之法,有散地,有轻地,有争地,有交地,有衢地,有重地,有泛地,有围地,有死地。诸侯自战其地者,為散地;入人之地不深者,為轻地;我得亦利,彼得亦利者,為争地;我可以往,彼可以来者,為交地;诸侯之地三属,先至而得天下眾者,為衢地;入人之地深,背城邑多者,為重地;山林、险阻、沮泽,凡难行之道者,為泛地;所由入者隘,所从归者迂,彼寡可以击吾之眾者,為围地;疾战则存,不疾战则亡者,為死地。是故散地则无战,轻地则无止,争地则无攻,交地则无绝,衢地则合交,重地则掠,泛地则行,围地则谋,死地则战。古之善用兵者,能使敌人前后不相及,眾寡不相恃,贵贱不相救,上下不相收,卒离而不集,兵合而不齐。合於利而动,不合於利而止。敢问敌眾而整将来,待之若何曰:先夺其所爱则听矣。兵之情主速,乘人之不及。由不虞之道,攻其所不戒也。凡為客之道,深入则专。主人不克,掠於饶野,三军足食。谨养而勿劳,并气积力,运兵计谋,為不可测。投之无所往,死且不北。死焉不得,士人尽力。兵士甚陷则不惧,无所往则固,深入则拘,不得已则斗。是故其兵不修而戒,不求而得,不约而亲,不令而信,禁祥去疑,至死无所之。吾士无餘财,非恶货也;无餘命,非恶寿也。令发之日,士卒坐者涕沾襟,偃卧者涕交颐,投之无所往,诸、劌之勇也。故善用兵者,譬如率然。率然者,常山之蛇也。击其首则尾至,击其尾则首至,击其中则首尾俱至。敢问兵可使如率然乎?曰可。夫吴人与越人相恶也,当其同舟而济而遇风,其相救也如左右手。是故方马埋轮,未足恃也;齐勇如一,政之道也;刚柔皆得,地之理也。故善用兵者,携手若使一人,不得已也。将军之事,静以幽,正以治,能愚士卒之耳目,使之无知;易其事,革其谋,使人无识;易其居,迂其途,使民不得虑。帅与之期,如登高而去其梯;帅与之深入诸侯之地,而发其机。若驱群羊,驱而往,驱而来,莫知所之。聚三军之眾,投之於险,此谓将军之事也。九地之变,屈伸之力,人情之理,不可不察也。凡為客之道,深则专,浅则散。去国越境而师者,绝地也;四彻者,衢地也;入深者,重地也;入浅者,轻地也;背固前隘者,围地也;无所往者,死地也。是故散地吾将一其志,轻地吾将使之属,争地吾将趋其后,交地吾将谨其守,交地吾将固其结,衢地吾将谨其恃,重地吾将继其食,泛地吾将进其途,围地吾将塞其闕,死地吾将示之以不活。故兵之情:围则御,不得已则斗,过则从。是故不知诸侯之谋者,不能预交;不知山林、险阻、沮泽之形者,不能行军;不用乡导,不能得地利。四五者,一不知,非霸王之兵也。夫霸王之兵,伐大国,则其眾不得聚;威加於敌,则其交不得合。是故不争天下之交,不养天下之权,信己之私,威加於敌,则其城可拔,其国可隳。施无法之赏,悬无政之令。犯三军之眾,若使一人。犯之以事,勿告以言;犯之以害,勿告以利。投之亡地然后存,陷之死地然后生。夫眾陷於害,然后能為胜败。故為兵之事,在顺详敌之意,并敌一向,千里杀将,是谓巧能成事。是故政举之日,夷关折符,无通其使,厉於廊庙之上,以诛其事。敌人开闔,必亟入之,先其所爱,微与之期,践墨随敌,以决战事。是故始如处女,敌人开户;后如脱兔,敌不及拒。 火攻第十二 孙子曰:凡火攻有五:一曰火人,二曰火积,三曰火輜,四曰火库,五曰火队。行火必有因,因必素具。发火有时,起火有日。时者,天之燥也。日者,月在箕、壁、翼、軫也。凡此四宿者,风起之日也。凡火攻,必因五火之变而应之:火发於内,则早应之於外;火发而其兵静者,待而勿攻,极其火力,可从而从之,不可从则上。火可发於外,无待於内,以时发之,火发上风,无攻下风,昼风久,夜风止。凡军必知五火之变,以数守之。故以火佐攻者明,以水佐攻者强。水可以绝,不可以夺。夫战胜攻取而不惰其功者凶,命曰“费留”。故曰:明主虑之,良将惰之,非利不动,非得不用,非危不战。主不可以怒而兴师,将不可以慍而攻战。合於利而动,不合於利而上。怒可以复喜,慍可以复说,亡国不可以复存,死者不可以复生。故明主慎之,良将警之。此安国全军之道也。 用间第十三 孙子曰: 凡兴师十万,出征千里,百姓之费,公家之奉,日费千金,内外骚动,怠於道路,不得操事者,七十万家。相守数年,以争一日之胜,而爱爵禄百金,不知敌之情者,不仁之至也,非民之将也,非主之佐也,非胜之主也。故明君贤将所以动而胜人,成功出於眾者,先知也。先知者,不可取於鬼神,不可象於事,不可验於度,必取於人,知敌之情者也。故用间有五:有因间,有内间,有反间,有死间,有生间。五间俱起,莫知其道,是谓神纪,人君之宝也。乡间者,因其乡人而用之;内间者,因其官人而用之;反间者,因其敌间而用之;死间者,為誑事於外,令吾闻知之而传於敌间也;生间者,反报也。故三军之事,莫亲於间,赏莫厚於间,事莫密於间,非圣贤不能用间,非仁义不能使间,非微妙不能得间之实。微哉微哉!无所不用间也。间事未发而先闻者,间与所告者兼死。凡军之所欲击,城之所欲攻,人之所欲杀,必先知其守将、左右、謁者、门者、舍人之姓名,令吾间必索知之。敌间之来间我者,因而利之,导而舍之,故反间可得而用也;因是而知之,故乡间、内间可得而使也;因是而知之,故死间為誑事,可使告敌;因是而知之,故生间可使如期。五间之事,主必知之,知之必在於反间,故反间不可不厚也。昔殷之兴也,伊挚在夏;周之兴也,吕牙在殷。故明君贤将,能以上智為间者,必成大功。此兵之要,三军之所恃而动也。
{ "pile_set_name": "Github" }
======================================================= Human Gut Metagenomics Functional & Taxonomic Profiling ======================================================= .. note:: If you are starting out with NGLess for metagenomics profiling, consider using the predefined pipeline collection, `NG-meta-profiler <ng-meta-profiler.html>`__. This tutorial is based on deconstructing a pipeline very similar to those. In this tutorial, we will analyse a small dataset of human gut microbial metagenomes. .. note:: This tutorial is also available as a `slide presentation <https://ngless.embl.de/_static/gut-metagenomics-tutorial-presentation/gut_specI_tutorial.html>`__ 1. Download the toy dataset First download all the tutorial data:: ngless --download-demo gut-short This will `download <https://ngless.embl.de/ressources/Demos/gut-short.tar.gz>`__ and expand the data to a directory called ``gut-short``. This is a toy dataset. It is based on `real data <https://www.ebi.ac.uk/ena/data/view/PRJNA339914>`__, but the samples were trimmed so that they contains only 250k paired-end reads. The dataset is organized in classical MOCAT style, with one sample per directory. NGLess does not require this structure, but this tutorial also demonstrates how to upgrade from your existing MOCAT-based projects.:: $ find ./igc.demo.short ./SAMN05615097.short ./SAMN05615097.short/SRR4052022.single.fq.gz ./SAMN05615097.short/SRR4052022.pair.2.fq.gz ./SAMN05615097.short/SRR4052022.pair.1.fq.gz ./SAMN05615096.short ./SAMN05615096.short/SRR4052021.pair.1.fq.gz ./SAMN05615096.short/SRR4052021.single.fq.gz ./SAMN05615096.short/SRR4052021.pair.2.fq.gz ./SAMN05615098.short ./SAMN05615098.short/SRR4052033.pair.2.fq.gz ./SAMN05615098.short/SRR4052033.pair.1.fq.gz ./SAMN05615098.short/SRR4052033.single.fq.gz ./process.ngl The whole script we will be using is there as well (``process.ngl``), so you can immediately run it with:: ngless process.ngl The rest of this tutorial is an explanation of the steps in this script. 2. Preliminary imports To run ngless, we need write a script. We start with a few imports:: ngless "1.0" import "parallel" version "0.6" import "mocat" version "0.0" import "motus" version "0.1" import "igc" version "0.0" These will all be used in the tutorial. 3. Parallelization We are going to process each sample separately. For this, we use the ``lock1`` function from the `parallel <stdlib.html#parallel-module>`__ module (which we imported before):: samples = readlines('igc.demo.short') sample = lock1(samples) The ``readlines`` function reads a file and returns all lines. In this case, we are reading the ``tara.demo.short`` file, which contains the three samples (``SAMEA2621229.sampled``, ``SAMEA2621155.sampled``, and ``SAMEA2621033.sampled``). ``lock1()`` is a slightly more complex function. It takes a list and *locks one of the elements* and returns it. It always chooses an element which has not been locked before, so you each time you run ``NGLess``, you will get a different sample. .. note:: When you are using ``lock1()`` you will need to run ``NGLess`` multiple times. But you can run multiple instances in parallel. 3. Preprocessing First, we load the data (the FastQ files):: input = load_mocat_sample(sample) And, now, we preprocess the data:: input = preprocess(input, keep_singles=False) using |read|: read = substrim(read, min_quality=25) if len(read) < 45: discard 4. Filter against the human genome We want to remove reads which map to the human genome, so we first map the reads to the human genome:: mapped = map(input, reference='hg19') ``hg19`` is a built-in reference and the genome will be automatically download it the first time you use it. Now, we discard the matched reads:: mapped = select(mapped) using |mr|: mr = mr.filter(min_match_size=45, min_identity_pc=90, action={unmatch}) if mr.flag({mapped}): discard The ``mapped`` object is a set of ``mappedreads`` (i.e., the same information that is saved in a SAM/BAM file). we use the ``as_reads`` function to get back to reads:: input = as_reads(mapped) Now, we will use the ``input`` object which has been filtered of human reads. 5. Profiling using the IGC .. note:: This section of the tutorial uses the `Integrated Gene Catalogue <http://www.nature.com/nbt/journal/v32/n8/full/nbt.2942.html>`__ and requires ca. **15GiB** of RAM. Skip to step 9 if your machine does not have this much memory. After preprocessing, we map the reads to the integrated gene catalog:: mapped = map(input, reference='igc', mode_all=True) The line above is the reason we needed to import the ``igc`` module: it made the ``igc`` reference available. Now, we need to ``count`` the results. This function takes the result of the above and aggregates it different ways. In this case, we want to aggregate by KEGG KOs, and eggNOG OGs:: counts = count(mapped, features=['KEGG_ko', 'eggNOG_OG'], normalization={scaled}) 7. Aggregate the results We have done all this computation, now we need to save it somewhere. We will use the ``collect()`` function to aggregate across all the samples processed:: collect(counts, current=sample, allneeded=samples, ofile='igc.profiles.txt') 9. Taxonomic profling using mOTUS Map the samples against the ``motus`` reference (this reference comes with the `motus module <motus.html>`__ we imported earlier):: mapped = map(input, reference='motus', mode_all=True) Now call the built-in ``count`` function to summarize your reads at gene level:: counted = count(mapped, features=['gene'], multiple={dist1}) To get the final taconomic profile, we call the ``motus`` function, which takes the gene count table and performs the motus quantification. The result of this call is another table, which we can concatenate with ``collect()``:: motus_table = motus(counted) collect(motus_table, current=sample, allneeded=samples, ofile='motus-counts.txt') 10. Run it! This is our script. We save it to a file (``process.ngl`` in this example) and run it from the command line:: $ ngless process.ngl .. note:: **You need to run this script once for each sample**. However, this can be done in parallel, taking advantage of high performance computing clusters. Full script ----------- Here is the full script:: ngless "1.0" import "parallel" version "0.6" import "mocat" version "0.0" import "motus" version "0.1" import "igc" version "0.0" samples = readlines('igc.demo.short') sample = lock1(samples) input = load_mocat_sample(sample) input = preprocess(input, keep_singles=False) using |read|: read = substrim(read, min_quality=25) if len(read) < 45: discard mapped = map(input, reference='hg19') mapped = select(mapped) using |mr|: mr = mr.filter(min_match_size=45, min_identity_pc=90, action={unmatch}) if mr.flag({mapped}): discard input = as_reads(mapped) mapped = map(input, reference='igc', mode_all=True) counts = count(mapped, features=['KEGG_ko', 'eggNOG_OG'], normalization={scaled}) collect(counts, current=sample, allneeded=samples, ofile='igc.profiles.txt') mapped = map(input, reference='motus', mode_all=True) counted = count(mapped, features=['gene'], multiple={dist1}) motus_table = motus(counted) collect(motus_table, current=sample, allneeded=samples, ofile='motus-counts.txt')
{ "pile_set_name": "Github" }
# =========================================================================== # http://www.gnu.org/software/autoconf-archive/ax_boost_base.html # =========================================================================== # # SYNOPSIS # # AX_BOOST_BASE([MINIMUM-VERSION], [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND]) # # DESCRIPTION # # Test for the Boost C++ libraries of a particular version (or newer) # # If no path to the installed boost library is given the macro searchs # under /usr, /usr/local, /opt and /opt/local and evaluates the # $BOOST_ROOT environment variable. Further documentation is available at # <http://randspringer.de/boost/index.html>. # # This macro calls: # # AC_SUBST(BOOST_CPPFLAGS) / AC_SUBST(BOOST_LDFLAGS) # # And sets: # # HAVE_BOOST # # LICENSE # # Copyright (c) 2008 Thomas Porschberg <[email protected]> # Copyright (c) 2009 Peter Adolphs # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice # and this notice are preserved. This file is offered as-is, without any # warranty. #serial 27 AC_DEFUN([AX_BOOST_BASE], [ AC_ARG_WITH([boost], [AS_HELP_STRING([--with-boost@<:@=ARG@:>@], [use Boost library from a standard location (ARG=yes), from the specified location (ARG=<path>), or disable it (ARG=no) @<:@ARG=yes@:>@ ])], [ if test "$withval" = "no"; then want_boost="no" elif test "$withval" = "yes"; then want_boost="yes" ac_boost_path="" else want_boost="yes" ac_boost_path="$withval" fi ], [want_boost="yes"]) AC_ARG_WITH([boost-libdir], AS_HELP_STRING([--with-boost-libdir=LIB_DIR], [Force given directory for boost libraries. Note that this will override library path detection, so use this parameter only if default library detection fails and you know exactly where your boost libraries are located.]), [ if test -d "$withval" then ac_boost_lib_path="$withval" else AC_MSG_ERROR(--with-boost-libdir expected directory name) fi ], [ac_boost_lib_path=""] ) if test "x$want_boost" = "xyes"; then boost_lib_version_req=ifelse([$1], ,1.20.0,$1) boost_lib_version_req_shorten=`expr $boost_lib_version_req : '\([[0-9]]*\.[[0-9]]*\)'` boost_lib_version_req_major=`expr $boost_lib_version_req : '\([[0-9]]*\)'` boost_lib_version_req_minor=`expr $boost_lib_version_req : '[[0-9]]*\.\([[0-9]]*\)'` boost_lib_version_req_sub_minor=`expr $boost_lib_version_req : '[[0-9]]*\.[[0-9]]*\.\([[0-9]]*\)'` if test "x$boost_lib_version_req_sub_minor" = "x" ; then boost_lib_version_req_sub_minor="0" fi WANT_BOOST_VERSION=`expr $boost_lib_version_req_major \* 100000 \+ $boost_lib_version_req_minor \* 100 \+ $boost_lib_version_req_sub_minor` AC_MSG_CHECKING(for boostlib >= $boost_lib_version_req) succeeded=no dnl On 64-bit systems check for system libraries in both lib64 and lib. dnl The former is specified by FHS, but e.g. Debian does not adhere to dnl this (as it rises problems for generic multi-arch support). dnl The last entry in the list is chosen by default when no libraries dnl are found, e.g. when only header-only libraries are installed! libsubdirs="lib" ax_arch=`uname -m` case $ax_arch in x86_64) libsubdirs="lib64 libx32 lib lib64" ;; ppc64|s390x|sparc64|aarch64|ppc64le) libsubdirs="lib64 lib lib64" ;; esac dnl allow for real multi-arch paths e.g. /usr/lib/x86_64-linux-gnu. Give dnl them priority over the other paths since, if libs are found there, they dnl are almost assuredly the ones desired. AC_REQUIRE([AC_CANONICAL_HOST]) libsubdirs="lib/${host_cpu}-${host_os} $libsubdirs" case ${host_cpu} in i?86) libsubdirs="lib/i386-${host_os} $libsubdirs" ;; esac dnl some arches may advertise a cpu type that doesn't line up with their dnl prefix's cpu type. For example, uname may report armv7l while libs are dnl installed to /usr/lib/arm-linux-gnueabihf. Try getting the compiler's dnl value for an extra chance of finding the correct path. libsubdirs="lib/`$CXX -dumpmachine 2>/dev/null` $libsubdirs" dnl first we check the system location for boost libraries dnl this location ist chosen if boost libraries are installed with the --layout=system option dnl or if you install boost with RPM if test "$ac_boost_path" != ""; then BOOST_CPPFLAGS="-I$ac_boost_path/include" for ac_boost_path_tmp in $libsubdirs; do if test -d "$ac_boost_path"/"$ac_boost_path_tmp" ; then BOOST_LDFLAGS="-L$ac_boost_path/$ac_boost_path_tmp" break fi done elif test "$cross_compiling" != yes; then for ac_boost_path_tmp in /usr /usr/local /opt /opt/local ; do if test -d "$ac_boost_path_tmp/include/boost" && test -r "$ac_boost_path_tmp/include/boost"; then for libsubdir in $libsubdirs ; do if ls "$ac_boost_path_tmp/$libsubdir/libboost_"* >/dev/null 2>&1 ; then break; fi done BOOST_LDFLAGS="-L$ac_boost_path_tmp/$libsubdir" BOOST_CPPFLAGS="-I$ac_boost_path_tmp/include" break; fi done fi dnl overwrite ld flags if we have required special directory with dnl --with-boost-libdir parameter if test "$ac_boost_lib_path" != ""; then BOOST_LDFLAGS="-L$ac_boost_lib_path" fi CPPFLAGS_SAVED="$CPPFLAGS" CPPFLAGS="$CPPFLAGS $BOOST_CPPFLAGS" export CPPFLAGS LDFLAGS_SAVED="$LDFLAGS" LDFLAGS="$LDFLAGS $BOOST_LDFLAGS" export LDFLAGS AC_REQUIRE([AC_PROG_CXX]) AC_LANG_PUSH(C++) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ @%:@include <boost/version.hpp> ]], [[ #if BOOST_VERSION >= $WANT_BOOST_VERSION // Everything is okay #else # error Boost version is too old #endif ]])],[ AC_MSG_RESULT(yes) succeeded=yes found_system=yes ],[ ]) AC_LANG_POP([C++]) dnl if we found no boost with system layout we search for boost libraries dnl built and installed without the --layout=system option or for a staged(not installed) version if test "x$succeeded" != "xyes"; then CPPFLAGS="$CPPFLAGS_SAVED" LDFLAGS="$LDFLAGS_SAVED" BOOST_CPPFLAGS= BOOST_LDFLAGS= _version=0 if test "$ac_boost_path" != ""; then if test -d "$ac_boost_path" && test -r "$ac_boost_path"; then for i in `ls -d $ac_boost_path/include/boost-* 2>/dev/null`; do _version_tmp=`echo $i | sed "s#$ac_boost_path##" | sed 's/\/include\/boost-//' | sed 's/_/./'` V_CHECK=`expr $_version_tmp \> $_version` if test "$V_CHECK" = "1" ; then _version=$_version_tmp fi VERSION_UNDERSCORE=`echo $_version | sed 's/\./_/'` BOOST_CPPFLAGS="-I$ac_boost_path/include/boost-$VERSION_UNDERSCORE" done dnl if nothing found search for layout used in Windows distributions if test -z "$BOOST_CPPFLAGS"; then if test -d "$ac_boost_path/boost" && test -r "$ac_boost_path/boost"; then BOOST_CPPFLAGS="-I$ac_boost_path" fi fi fi else if test "$cross_compiling" != yes; then for ac_boost_path in /usr /usr/local /opt /opt/local ; do if test -d "$ac_boost_path" && test -r "$ac_boost_path"; then for i in `ls -d $ac_boost_path/include/boost-* 2>/dev/null`; do _version_tmp=`echo $i | sed "s#$ac_boost_path##" | sed 's/\/include\/boost-//' | sed 's/_/./'` V_CHECK=`expr $_version_tmp \> $_version` if test "$V_CHECK" = "1" ; then _version=$_version_tmp best_path=$ac_boost_path fi done fi done VERSION_UNDERSCORE=`echo $_version | sed 's/\./_/'` BOOST_CPPFLAGS="-I$best_path/include/boost-$VERSION_UNDERSCORE" if test "$ac_boost_lib_path" = ""; then for libsubdir in $libsubdirs ; do if ls "$best_path/$libsubdir/libboost_"* >/dev/null 2>&1 ; then break; fi done BOOST_LDFLAGS="-L$best_path/$libsubdir" fi fi if test "x$BOOST_ROOT" != "x"; then for libsubdir in $libsubdirs ; do if ls "$BOOST_ROOT/stage/$libsubdir/libboost_"* >/dev/null 2>&1 ; then break; fi done if test -d "$BOOST_ROOT" && test -r "$BOOST_ROOT" && test -d "$BOOST_ROOT/stage/$libsubdir" && test -r "$BOOST_ROOT/stage/$libsubdir"; then version_dir=`expr //$BOOST_ROOT : '.*/\(.*\)'` stage_version=`echo $version_dir | sed 's/boost_//' | sed 's/_/./g'` stage_version_shorten=`expr $stage_version : '\([[0-9]]*\.[[0-9]]*\)'` V_CHECK=`expr $stage_version_shorten \>\= $_version` if test "$V_CHECK" = "1" -a "$ac_boost_lib_path" = "" ; then AC_MSG_NOTICE(We will use a staged boost library from $BOOST_ROOT) BOOST_CPPFLAGS="-I$BOOST_ROOT" BOOST_LDFLAGS="-L$BOOST_ROOT/stage/$libsubdir" fi fi fi fi CPPFLAGS="$CPPFLAGS $BOOST_CPPFLAGS" export CPPFLAGS LDFLAGS="$LDFLAGS $BOOST_LDFLAGS" export LDFLAGS AC_LANG_PUSH(C++) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ @%:@include <boost/version.hpp> ]], [[ #if BOOST_VERSION >= $WANT_BOOST_VERSION // Everything is okay #else # error Boost version is too old #endif ]])],[ AC_MSG_RESULT(yes) succeeded=yes found_system=yes ],[ ]) AC_LANG_POP([C++]) fi if test "$succeeded" != "yes" ; then if test "$_version" = "0" ; then AC_MSG_NOTICE([[We could not detect the boost libraries (version $boost_lib_version_req_shorten or higher). If you have a staged boost library (still not installed) please specify \$BOOST_ROOT in your environment and do not give a PATH to --with-boost option. If you are sure you have boost installed, then check your version number looking in <boost/version.hpp>. See http://randspringer.de/boost for more documentation.]]) else AC_MSG_NOTICE([Your boost libraries seems to old (version $_version).]) fi # execute ACTION-IF-NOT-FOUND (if present): ifelse([$3], , :, [$3]) else AC_SUBST(BOOST_CPPFLAGS) AC_SUBST(BOOST_LDFLAGS) AC_DEFINE(HAVE_BOOST,,[define if the Boost library is available]) # execute ACTION-IF-FOUND (if present): ifelse([$2], , :, [$2]) fi CPPFLAGS="$CPPFLAGS_SAVED" LDFLAGS="$LDFLAGS_SAVED" fi ])
{ "pile_set_name": "Github" }
------------------------------------------------------------------------------ -- GNAT Studio -- -- -- -- Copyright (C) 2007-2020, AdaCore -- -- -- -- This is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. This software is distributed in the hope that it will be useful, -- -- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- -- -- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -- -- License for more details. You should have received a copy of the GNU -- -- General Public License distributed with this software; see file -- -- COPYING3. If not, go to http://www.gnu.org/licenses for a complete copy -- -- of the license. -- ------------------------------------------------------------------------------ with String_Utils; use String_Utils; package body Codefix.Error_Lists is use type Basic_Types.Visible_Column_Type; procedure Internal_Add_Error (List : Error_Message_List; Error : Error_Message); ---------------- -- Initialize -- ---------------- procedure Initialize (This : out Error_Message_List) is begin This := new Error_Message_List_Record; end Initialize; ---------- -- Free -- ---------- procedure Free (This : in out Error_Message_List) is procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Error_Message_List_Record, Error_Message_List); begin Clear_Messages (This); Free (This.File_Regexp); Unchecked_Free (This); end Free; --------------------- -- Add_Errors_From -- --------------------- procedure Add_Errors_From (List : Error_Message_List; Registry : Project_Registry_Access; Messages : String) is Last_Index : Integer := Messages'First; Current_Index : Integer := Messages'First; Order_Id : Long_Long_Integer := 0; begin while Current_Index < Messages'Last loop Order_Id := Order_Id + 1; Last_Index := Current_Index; Skip_To_Char (Messages, Current_Index, ASCII.LF); declare Error : Error_Message; begin Initialize (Error, Registry => Registry, Error_Line => To_Unbounded_String (Messages (Last_Index .. Current_Index - 1)), Regexp => List.File_Regexp.all, File_Index => List.File_Index, Line_Index => List.Line_Index, Col_Index => List.Col_Index, Msg_Index => List.Msg_Index, Style_Index => List.Style_Index, Warning_Index => List.Warning_Index, Order => Order_Id); Internal_Add_Error (List, Error); end; Current_Index := Current_Index + 1; end loop; end Add_Errors_From; --------------- -- Add_Error -- --------------- procedure Add_Error (List : Error_Message_List; File : Virtual_File; Line : Integer; Column : Visible_Column_Type; Message : Unbounded_String; Order : Long_Long_Integer) is Error : Error_Message; begin Initialize (This => Error, File => File, Line => Line, Col => Column, Message => Message, Order => Order); Internal_Add_Error (List, Error); end Add_Error; ------------------------ -- Internal_Add_Error -- ------------------------ procedure Internal_Add_Error (List : Error_Message_List; Error : Error_Message) is Loc : Messages_Loc; Loc_List : Internal_List_Access; begin if Error /= Invalid_Error_Message then Loc.File := Error.Get_File; Loc.Line := Error.Get_Line; Loc.Column := Error.Get_Column; if Contains (List.Messages, Loc) then Loc_List := Element (List.Messages, Loc); else Loc_List := new Internal_Message_List_Pckg.Set; Insert (List.Messages, Loc, Loc_List); end if; Insert (Loc_List.all, Error); end if; end Internal_Add_Error; -------------------- -- Clear_Messages -- -------------------- procedure Clear_Messages (List : Error_Message_List) is Cur : Error_Message_Container.Cursor := First (List.Messages); Loc_List : Internal_List_Access; begin while Cur /= Error_Message_Container.No_Element loop Loc_List := Element (Cur); Free (Loc_List); Cur := Next (Cur); end loop; Clear (List.Messages); end Clear_Messages; -------------------------------- -- Clear_Messages_At_Location -- -------------------------------- procedure Clear_Messages_At_Location (List : Error_Message_List; File : Virtual_File; Line : Integer; Column : Visible_Column_Type) is Loc : Messages_Loc; Loc_List : Internal_List_Access; begin Loc.File := File; Loc.Line := Line; Loc.Column := Column; if Contains (List.Messages, Loc) then Loc_List := Element (List.Messages, Loc); Free (Loc_List); Delete (List.Messages, Loc); end if; end Clear_Messages_At_Location; ----------- -- First -- ----------- function First (List : Error_Message_List) return Error_Message_Iterator is It : Error_Message_Iterator; begin It.Map_Cur := First (List.Messages); if It.Map_Cur /= Error_Message_Container.No_Element then It.Message_List := Element (First (List.Messages)); It.List_Cur := First (It.Message_List.all); else It.List_Cur := Internal_Message_List_Pckg.No_Element; end if; return It; end First; ----------------------- -- First_At_Location -- ----------------------- function First_At_Location (List : Error_Message_List; File : Virtual_File; Line : Integer; Column : Visible_Column_Type; Order : Long_Long_Integer) return Error_Message_Iterator is Loc : Messages_Loc; It : Error_Message_Iterator; begin Loc.File := File; Loc.Line := Line; Loc.Column := Column; if not Contains (List.Messages, Loc) then return (Map_Cur => Error_Message_Container.No_Element, List_Cur => Internal_Message_List_Pckg.No_Element, Message_List => null); else It := (Map_Cur => Error_Message_Container.No_Element, List_Cur => First (Element (List.Messages, Loc).all), Message_List => Element (List.Messages, Loc)); while It.List_Cur /= Internal_Message_List_Pckg.No_Element loop declare Message : constant Error_Message := Get_Message (It); begin exit when Message.Get_Order = Order and then not Message.Is_Cancelled; end; It.List_Cur := Next (It.List_Cur); end loop; return It; end if; end First_At_Location; ---------- -- Next -- ---------- function Next (It : Error_Message_Iterator) return Error_Message_Iterator is Result : Error_Message_Iterator := It; begin Result.List_Cur := Next (Result.List_Cur); if Result.List_Cur = Internal_Message_List_Pckg.No_Element and then Result.Map_Cur /= Error_Message_Container.No_Element then Result.Map_Cur := Next (Result.Map_Cur); if Result.Map_Cur /= Error_Message_Container.No_Element then Result.Message_List := Element (Result.Map_Cur); Result.List_Cur := First (Result.Message_List.all); end if; end if; if not At_End (Result) and then Get_Message (Result).Is_Cancelled then return Next (Result); else return Result; end if; end Next; ----------------- -- Get_Message -- ----------------- function Get_Message (It : Error_Message_Iterator) return Error_Message is begin return Element (It.List_Cur); end Get_Message; -------------------- -- Cancel_Message -- -------------------- procedure Cancel_Message (It : Error_Message_Iterator) is Message : Error_Message := Get_Message (It); begin Message.Cancel; Internal_Message_List_Pckg.Replace_Element (It.Message_List.all, It.List_Cur, Message); end Cancel_Message; ------------ -- At_End -- ------------ function At_End (It : Error_Message_Iterator) return Boolean is begin return It.List_Cur = Internal_Message_List_Pckg.No_Element; end At_End; ---------------- -- Set_Regexp -- ---------------- procedure Set_Regexp (This : in out Error_Message_List; File_Location_Regexp : GNAT.Regpat.Pattern_Matcher; File_Index_In_Regexp : Integer; Line_Index_In_Regexp : Integer; Col_Index_In_Regexp : Integer; Msg_Index_In_Regexp : Integer; Style_Index_In_Regexp : Integer; Warning_Index_In_Regexp : Integer) is begin Free (This.File_Regexp); This.File_Regexp := new Pattern_Matcher'(File_Location_Regexp); This.File_Index := File_Index_In_Regexp; This.Line_Index := Line_Index_In_Regexp; This.Col_Index := Col_Index_In_Regexp; This.Msg_Index := Msg_Index_In_Regexp; This.Style_Index := Style_Index_In_Regexp; This.Warning_Index := Warning_Index_In_Regexp; end Set_Regexp; -------- -- Lt -- -------- function Lt (Left, Right : Error_Message) return Boolean is begin return Left.Get_Order < Right.Get_Order; end Lt; --------- -- "<" -- --------- function "<" (Left, Right : Messages_Loc) return Boolean is begin return Left.Line < Right.Line or else (Left.Line = Right.Line and then (Left.Column < Right.Column or else (Left.Column = Right.Column and then Left.File < Right.File))); end "<"; end Codefix.Error_Lists;
{ "pile_set_name": "Github" }
/* Copyright (c) Marshall Clow 2017. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ /// \file transform_reduce.hpp /// \brief Combine the (transformed) elements of a sequence (or two) into a single value. /// \author Marshall Clow #ifndef BOOST_ALGORITHM_TRANSFORM_REDUCE_HPP #define BOOST_ALGORITHM_TRANSFORM_REDUCE_HPP #include <functional> // for std::plus #include <iterator> // for std::iterator_traits #include <boost/config.hpp> #include <boost/range/begin.hpp> #include <boost/range/end.hpp> #include <boost/range/value_type.hpp> namespace boost { namespace algorithm { template<class InputIterator1, class InputIterator2, class T, class BinaryOperation1, class BinaryOperation2> T transform_reduce(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, T init, BinaryOperation1 bOp1, BinaryOperation2 bOp2) { for (; first1 != last1; ++first1, (void) ++first2) init = bOp1(init, bOp2(*first1, *first2)); return init; } template<class InputIterator, class T, class BinaryOperation, class UnaryOperation> T transform_reduce(InputIterator first, InputIterator last, T init, BinaryOperation bOp, UnaryOperation uOp) { for (; first != last; ++first) init = bOp(init, uOp(*first)); return init; } template<class InputIterator1, class InputIterator2, class T> T transform_reduce(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, T init) { return boost::algorithm::transform_reduce(first1, last1, first2, init, std::plus<T>(), std::multiplies<T>()); } }} // namespace boost and algorithm #endif // BOOST_ALGORITHM_TRANSFORM_REDUCE_HPP
{ "pile_set_name": "Github" }
package alicloud import ( "fmt" "time" "github.com/alibaba/terraform-provider/alicloud/connectivity" "github.com/denverdino/aliyungo/common" "github.com/denverdino/aliyungo/dns" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" ) func resourceAlicloudDnsRecord() *schema.Resource { return &schema.Resource{ Create: resourceAlicloudDnsRecordCreate, Read: resourceAlicloudDnsRecordRead, Update: resourceAlicloudDnsRecordUpdate, Delete: resourceAlicloudDnsRecordDelete, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Schema: map[string]*schema.Schema{ "name": &schema.Schema{ Type: schema.TypeString, Required: true, }, "host_record": { Type: schema.TypeString, Required: true, ValidateFunc: validateRR, }, "type": { Type: schema.TypeString, Required: true, ValidateFunc: validateDomainRecordType, }, "value": { Type: schema.TypeString, Required: true, }, "ttl": { Type: schema.TypeInt, Optional: true, Default: 600, }, "priority": { Type: schema.TypeInt, Optional: true, ValidateFunc: validateDomainRecordPriority, DiffSuppressFunc: dnsPriorityDiffSuppressFunc, }, "routing": { Type: schema.TypeString, Optional: true, ValidateFunc: validateDomainRecordLine, Default: "default", }, "status": { Type: schema.TypeString, Computed: true, }, "locked": { Type: schema.TypeBool, Computed: true, }, }, } } func resourceAlicloudDnsRecordCreate(d *schema.ResourceData, meta interface{}) error { client := meta.(*connectivity.AliyunClient) args := &dns.AddDomainRecordArgs{ DomainName: d.Get("name").(string), RR: d.Get("host_record").(string), Type: d.Get("type").(string), Value: d.Get("value").(string), Priority: int32(d.Get("priority").(int)), } if _, ok := d.GetOk("priority"); !ok && args.Type == dns.MXRecord { return fmt.Errorf("'priority': required field when 'type' is MX.") } if v, ok := d.GetOk("routing"); ok && v != "default" && args.Type == dns.ForwordURLRecord { return fmt.Errorf("The ForwordURLRecord only support default line.") } raw, err := client.WithDnsClient(func(dnsClient *dns.Client) (interface{}, error) { return dnsClient.AddDomainRecord(args) }) if err != nil { return fmt.Errorf("AddDomainRecord got a error: %#v", err) } response, _ := raw.(*dns.AddDomainRecordResponse) d.SetId(response.RecordId) return resourceAlicloudDnsRecordUpdate(d, meta) } func resourceAlicloudDnsRecordUpdate(d *schema.ResourceData, meta interface{}) error { client := meta.(*connectivity.AliyunClient) d.Partial(true) attributeUpdate := false args := &dns.UpdateDomainRecordArgs{ RecordId: d.Id(), RR: d.Get("host_record").(string), Type: d.Get("type").(string), Value: d.Get("value").(string), } if !d.IsNewResource() { requiredParams := []string{"host_record", "type", "value"} for _, v := range requiredParams { if d.HasChange(v) { d.SetPartial(v) attributeUpdate = true } } } if d.HasChange("priority") && !d.IsNewResource() { d.SetPartial("priority") args.Priority = int32(d.Get("priority").(int)) attributeUpdate = true } if d.HasChange("ttl") && !d.IsNewResource() { d.SetPartial("ttl") args.TTL = int32(d.Get("ttl").(int)) attributeUpdate = true } if d.HasChange("routing") && !d.IsNewResource() { d.SetPartial("routing") args.Line = d.Get("routing").(string) attributeUpdate = true } if attributeUpdate { _, err := client.WithDnsClient(func(dnsClient *dns.Client) (interface{}, error) { return dnsClient.UpdateDomainRecord(args) }) if err != nil { return fmt.Errorf("UpdateDomainRecord got an error: %#v", err) } } d.Partial(false) return resourceAlicloudDnsRecordRead(d, meta) } func resourceAlicloudDnsRecordRead(d *schema.ResourceData, meta interface{}) error { client := meta.(*connectivity.AliyunClient) args := &dns.DescribeDomainRecordInfoNewArgs{ RecordId: d.Id(), } raw, err := client.WithDnsClient(func(dnsClient *dns.Client) (interface{}, error) { return dnsClient.DescribeDomainRecordInfoNew(args) }) if err != nil { if NotFoundError(err) { d.SetId("") return nil } return err } response, _ := raw.(*dns.DescribeDomainRecordInfoNewResponse) record := response.RecordTypeNew d.Set("ttl", record.TTL) d.Set("priority", record.Priority) d.Set("name", record.DomainName) d.Set("host_record", record.RR) d.Set("type", record.Type) d.Set("value", record.Value) d.Set("routing", record.Line) d.Set("status", record.Status) d.Set("locked", record.Locked) return nil } func resourceAlicloudDnsRecordDelete(d *schema.ResourceData, meta interface{}) error { client := meta.(*connectivity.AliyunClient) args := &dns.DeleteDomainRecordArgs{ RecordId: d.Id(), } return resource.Retry(5*time.Minute, func() *resource.RetryError { _, err := client.WithDnsClient(func(dnsClient *dns.Client) (interface{}, error) { return dnsClient.DeleteDomainRecord(args) }) if err != nil { e, _ := err.(*common.Error) if e.ErrorResponse.Code == RecordForbiddenDNSChange { return resource.RetryableError(fmt.Errorf("Operation forbidden because DNS is changing - trying again after change complete.")) } return resource.NonRetryableError(fmt.Errorf("Error deleting domain record %s: %#v", d.Id(), err)) } raw, err := client.WithDnsClient(func(dnsClient *dns.Client) (interface{}, error) { return dnsClient.DescribeDomainRecordInfoNew(&dns.DescribeDomainRecordInfoNewArgs{ RecordId: d.Id(), }) }) if err != nil { if NotFoundError(err) || IsExceptedError(err, DomainRecordNotBelongToUser) { return nil } return resource.NonRetryableError(fmt.Errorf("Describe domain record got an error: %#v.", err)) } response, _ := raw.(*dns.DescribeDomainRecordInfoNewResponse) if response == nil { return nil } return nil }) }
{ "pile_set_name": "Github" }
package com.kezong.fataar class Constants { public static final String RE_BUNDLE_FOLDER = "aar_rebundle" public static final String INTERMEDIATES_TEMP_FOLDER = "fat-aar" }
{ "pile_set_name": "Github" }
# VGG 16-layer network convolutional finetuning # Network modified to have smaller receptive field (128 pixels) # and smaller stride (8 pixels) when run in convolutional mode. # # In this model we also change max pooling size in the first 4 layer # from 2 to 3 while retaining stride = 2 # which makes it easier to exactly align responses at different layer. # name: "${NET_ID}" layer { name: "data" type: "ImageSegData" top: "data" top: "label" top: "data_dim" image_data_param { root_folder: "${DATA_ROOT}" source: "${EXP}/list/${TEST_SET}.txt" label_type: PIXEL batch_size: 1 } transform_param { mean_value: 104.008 mean_value: 116.669 mean_value: 122.675 crop_size: 513 mirror: false } include: { phase: TEST } } # BEG (0) Direct path to classifier layer { bottom: "data" top: "data_conv" name: "data_conv" type: "Convolution" convolution_param { num_output: 128 kernel_size: 3 stride: 1 pad: 1 } } layer { bottom: "data_conv" top: "data_conv" name: "relu_data_conv" type: "ReLU" } layer { bottom: "data_conv" top: "data_conv" name: "drop_data_conv" type: "Dropout" dropout_param { dropout_ratio: 0.5 } } layer { bottom: "data_conv" top: "data_fc" name: "data_fc" type: "Convolution" convolution_param { num_output: 128 kernel_size: 1 stride: 1 } } layer { bottom: "data_fc" top: "data_fc" name: "relu_data_fc" type: "ReLU" } layer { bottom: "data_fc" top: "data_fc" name: "drop_data_fc" type: "Dropout" dropout_param { dropout_ratio: 0.5 } } layer { bottom: "data_fc" top: "data_ms" name: "data_ms" type: "Convolution" convolution_param { num_output: ${NUM_LABELS} kernel_size: 1 } } # END (0) Direct path to classifier ### NETWORK ### layer { bottom: "data" top: "conv1_1" name: "conv1_1" type: "Convolution" convolution_param { num_output: 64 pad: 1 kernel_size: 3 } } layer { bottom: "conv1_1" top: "conv1_1" name: "relu1_1" type: "ReLU" } layer { bottom: "conv1_1" top: "conv1_2" name: "conv1_2" type: "Convolution" convolution_param { num_output: 64 pad: 1 kernel_size: 3 } } layer { bottom: "conv1_2" top: "conv1_2" name: "relu1_2" type: "ReLU" } layer { bottom: "conv1_2" top: "pool1" name: "pool1" type: "Pooling" pooling_param { pool: MAX kernel_size: 3 stride: 2 pad: 1 } } # BEG (1) Direct path to classifier layer { bottom: "pool1" top: "pool1_conv" name: "pool1_conv" type: "Convolution" convolution_param { num_output: 128 kernel_size: 3 stride:1 pad: 1 } } layer { bottom: "pool1_conv" top: "pool1_conv" name: "relu_pool1_conv" type: "ReLU" } layer { bottom: "pool1_conv" top: "pool1_conv" name: "drop_pool1_conv" type: "Dropout" dropout_param { dropout_ratio: 0.5 } } layer { bottom: "pool1_conv" top: "pool1_fc" name: "pool1_fc" type: "Convolution" convolution_param { num_output: 128 kernel_size: 1 } } layer { bottom: "pool1_fc" top: "pool1_fc" name: "relu_pool1_fc" type: "ReLU" } layer { bottom: "pool1_fc" top: "pool1_fc" name: "drop_pool1_fc" type: "Dropout" dropout_param { dropout_ratio: 0.5 } } layer { bottom: "pool1_fc" top: "pool1_ms" name: "pool1_ms" type: "Convolution" convolution_param { num_output: ${NUM_LABELS} kernel_size: 1 } } # END (1) Direct path to classifier layer { bottom: "pool1" top: "conv2_1" name: "conv2_1" type: "Convolution" convolution_param { num_output: 128 pad: 1 kernel_size: 3 } } layer { bottom: "conv2_1" top: "conv2_1" name: "relu2_1" type: "ReLU" } layer { bottom: "conv2_1" top: "conv2_2" name: "conv2_2" type: "Convolution" convolution_param { num_output: 128 pad: 1 kernel_size: 3 } } layer { bottom: "conv2_2" top: "conv2_2" name: "relu2_2" type: "ReLU" } layer { bottom: "conv2_2" top: "pool2" name: "pool2" type: "Pooling" pooling_param { pool: MAX kernel_size: 3 stride: 2 pad: 1 } } # BEG (2) Direct path to classifier layer { bottom: "pool2" top: "pool2_conv" name: "pool2_conv" type: "Convolution" convolution_param { num_output: 128 kernel_size: 3 stride: 1 pad: 1 } } layer { bottom: "pool2_conv" top: "pool2_conv" name: "relu_pool2_conv" type: "ReLU" } layer { bottom: "pool2_conv" top: "pool2_conv" name: "drop_pool2_conv" type: "Dropout" dropout_param { dropout_ratio: 0.5 } } layer { bottom: "pool2_conv" top: "pool2_fc" name: "pool2_fc" type: "Convolution" convolution_param { num_output: 128 kernel_size: 1 } } layer { bottom: "pool2_fc" top: "pool2_fc" name: "relu_pool2_fc" type: "ReLU" } layer { bottom: "pool2_fc" top: "pool2_fc" name: "drop_pool2_fc" type: "Dropout" dropout_param { dropout_ratio: 0.5 } } layer { bottom: "pool2_fc" top: "pool2_ms" name: "pool2_ms" type: "Convolution" convolution_param { num_output: ${NUM_LABELS} kernel_size: 1 } } # END (2) Direct path to classifier layer { bottom: "pool2" top: "conv3_1" name: "conv3_1" type: "Convolution" convolution_param { num_output: 256 pad: 1 kernel_size: 3 } } layer { bottom: "conv3_1" top: "conv3_1" name: "relu3_1" type: "ReLU" } layer { bottom: "conv3_1" top: "conv3_2" name: "conv3_2" type: "Convolution" convolution_param { num_output: 256 pad: 1 kernel_size: 3 } } layer { bottom: "conv3_2" top: "conv3_2" name: "relu3_2" type: "ReLU" } layer { bottom: "conv3_2" top: "conv3_3" name: "conv3_3" type: "Convolution" convolution_param { num_output: 256 pad: 1 kernel_size: 3 } } layer { bottom: "conv3_3" top: "conv3_3" name: "relu3_3" type: "ReLU" } layer { bottom: "conv3_3" top: "pool3" name: "pool3" type: "Pooling" pooling_param { pool: MAX kernel_size: 3 stride: 2 pad: 1 } } # BEG (3) Direct path to classifier layer { bottom: "pool3" top: "pool3_conv" name: "pool3_conv" type: "Convolution" convolution_param { num_output: 128 kernel_size: 3 stride: 1 pad: 1 } } layer { bottom: "pool3_conv" top: "pool3_conv" name: "relu_pool3_conv" type: "ReLU" } layer { bottom: "pool3_conv" top: "pool3_conv" name: "drop_pool3_conv" type: "Dropout" dropout_param { dropout_ratio: 0.5 } } layer { bottom: "pool3_conv" top: "pool3_fc" name: "pool3_fc" type: "Convolution" convolution_param { num_output: 128 kernel_size: 1 stride: 1 } } layer { bottom: "pool3_fc" top: "pool3_fc" name: "relu_pool3_fc" type: "ReLU" } layer { bottom: "pool3_fc" top: "pool3_fc" name: "drop_pool3_fc" type: "Dropout" dropout_param { dropout_ratio: 0.5 } } layer { bottom: "pool3_fc" top: "pool3_ms" name: "pool3_ms" type: "Convolution" convolution_param { num_output: ${NUM_LABELS} kernel_size: 1 } } # END (3) Direct path to classifier layer { bottom: "pool3" top: "conv4_1" name: "conv4_1" type: "Convolution" convolution_param { num_output: 512 pad: 1 kernel_size: 3 } } layer { bottom: "conv4_1" top: "conv4_1" name: "relu4_1" type: "ReLU" } layer { bottom: "conv4_1" top: "conv4_2" name: "conv4_2" type: "Convolution" convolution_param { num_output: 512 pad: 1 kernel_size: 3 } } layer { bottom: "conv4_2" top: "conv4_2" name: "relu4_2" type: "ReLU" } layer { bottom: "conv4_2" top: "conv4_3" name: "conv4_3" type: "Convolution" convolution_param { num_output: 512 pad: 1 kernel_size: 3 } } layer { bottom: "conv4_3" top: "conv4_3" name: "relu4_3" type: "ReLU" } layer { bottom: "conv4_3" top: "pool4" name: "pool4" type: "Pooling" pooling_param { pool: MAX kernel_size: 3 pad: 1 #stride: 2 stride: 1 } } # BEG (4) Direct path to classifier layer { bottom: "pool4" top: "pool4_conv" name: "pool4_conv" type: "Convolution" convolution_param { num_output: 128 kernel_size: 3 stride: 1 pad: 1 } } layer { bottom: "pool4_conv" top: "pool4_conv" name: "relu_pool4_conv" type: "ReLU" } layer { bottom: "pool4_conv" top: "pool4_conv" name: "drop_pool4_conv" type: "Dropout" dropout_param { dropout_ratio: 0.5 } } layer { bottom: "pool4_conv" top: "pool4_fc" name: "pool4_fc" type: "Convolution" convolution_param { num_output: 128 kernel_size: 1 stride: 1 weight_filler { type: "gaussian" std: 0.005 } bias_filler { type: "constant" value: 0 } } } layer { bottom: "pool4_fc" top: "pool4_fc" name: "relu_pool4_fc" type: "ReLU" } layer { bottom: "pool4_fc" top: "pool4_fc" name: "drop_pool4_fc" type: "Dropout" dropout_param { dropout_ratio: 0.5 } } layer { bottom: "pool4_fc" top: "pool4_ms" name: "pool4_ms" type: "Convolution" convolution_param { num_output: ${NUM_LABELS} kernel_size: 1 } } # END (4) Direct path to classifier layer { bottom: "pool4" top: "conv5_1" name: "conv5_1" type: "Convolution" convolution_param { num_output: 512 #pad: 1 pad: 2 dilation: 2 kernel_size: 3 } } layer { bottom: "conv5_1" top: "conv5_1" name: "relu5_1" type: "ReLU" } layer { bottom: "conv5_1" top: "conv5_2" name: "conv5_2" type: "Convolution" convolution_param { num_output: 512 #pad: 1 pad: 2 dilation: 2 kernel_size: 3 } } layer { bottom: "conv5_2" top: "conv5_2" name: "relu5_2" type: "ReLU" } layer { bottom: "conv5_2" top: "conv5_3" name: "conv5_3" type: "Convolution" convolution_param { num_output: 512 #pad: 1 pad: 2 dilation: 2 kernel_size: 3 } } layer { bottom: "conv5_3" top: "conv5_3" name: "relu5_3" type: "ReLU" } layer { bottom: "conv5_3" top: "pool5" name: "pool5" type: "Pooling" pooling_param { pool: MAX #kernel_size: 2 #stride: 2 kernel_size: 3 stride: 1 pad: 1 } } layer { bottom: "pool5" top: "pool5a" name: "pool5a" type: "Pooling" pooling_param { pool: AVE kernel_size: 3 stride: 1 pad: 1 } } layer { bottom: "pool5a" top: "fc6" name: "fc6" type: "Convolution" #strict_dim: false convolution_param { num_output: 1024 pad: 12 dilation: 12 kernel_size: 3 } } layer { bottom: "fc6" top: "fc6" name: "relu6" type: "ReLU" } layer { bottom: "fc6" top: "fc6" name: "drop6" type: "Dropout" dropout_param { dropout_ratio: 0.5 } } layer { bottom: "fc6" top: "fc7" name: "fc7" type: "Convolution" #strict_dim: false convolution_param { num_output: 1024 kernel_size: 1 } } layer { bottom: "fc7" top: "fc7" name: "relu7" type: "ReLU" } layer { bottom: "fc7" top: "fc7" name: "drop7" type: "Dropout" dropout_param { dropout_ratio: 0.5 } } layer { bottom: "fc7" top: "fc8_${EXP}" name: "fc8_${EXP}" type: "Convolution" #strict_dim: false convolution_param { num_output: ${NUM_LABELS} kernel_size: 1 } } # Upsampling and fusion layer { bottom: "pool1_ms" top: "pool1_interp" name: "pool1_interp" type: "Interp" interp_param { zoom_factor: 2 } } layer { bottom: "pool2_ms" top: "pool2_interp" name: "pool2_interp" type: "Interp" interp_param { zoom_factor: 4 } } layer { bottom: "pool3_ms" top: "pool3_interp" name: "pool3_interp" type: "Interp" interp_param { zoom_factor: 8 } } layer { bottom: "pool4_ms" top: "pool4_interp" name: "pool4_interp" type: "Interp" interp_param { zoom_factor: 8 } } layer { bottom: "fc8_${EXP}" top: "fc8_interp" name: "fc8_interp" type: "Interp" interp_param { zoom_factor: 8 } } # Fusion layer layer { bottom: "data_ms" bottom: "pool1_interp" bottom: "pool2_interp" bottom: "pool3_interp" bottom: "pool4_interp" bottom: "fc8_interp" top: "fc_fusion" name: "fc_fusion" type: "Eltwise" eltwise_param { operation: SUM } } # JAY EDIT THIS LAYER #layer { # bottom: "fc8_interp" # bottom: "data_dim" # bottom: "data" # top: "crf_inf" # name: "crf" # type: DENSE_CRF # dense_crf_param { # max_iter: 10 # pos_w: 3 # pos_xy_std: 3 # bi_w: 5 # bi_xy_std: 50 # bi_rgb_std: 10 # } # include: { phase: TEST } #} #layer { # name: "crf_mat" # type: MAT_WRITE # bottom: "crf_inf" # mat_write_param { # prefix: "${FEATURE_DIR}/${TEST_SET}/crf/" # source: "${EXP}/list/${TEST_SET}_id.txt" # strip: 0 # period: 1 # } # include: { phase: TEST } #} # layer { # bottom: "label" # name: "silence" # type: SILENCE # include: { phase: TEST } # } layer { name: "accuracy" type: "SegAccuracy" bottom: "fc_fusion" bottom: "label" top: "accuracy" seg_accuracy_param { ignore_label: 255 reset: false } } ########### DENSE CRF ############ #layer { # bottom: "fc_fusion" # bottom: "data_dim" # bottom: "data" # top: "crf_inf" # name: "crf" # type: "DenseCRF" # dense_crf_param { # max_iter: 10 # pos_w: 3 # pos_xy_std: 3 # bi_w: 4 # bi_xy_std: 83 # bi_rgb_std: 5 # } #} #layer { # name: "accuracyCRF" # type: "SegAccuracy" # bottom: "crf_inf" # bottom: "label" # top: "accuracyCRF" # seg_accuracy_param { # ignore_label: 255 # reset: false # } #} #layer { # name: "crf_mat" # type: "MatWrite" # bottom: "crf_inf" # include { # phase: TEST # } # mat_write_param { # prefix: "${FEATURE_DIR}/${TEST_SET}/crf/" # source: "${EXP}/list/${TEST_SET}_id.txt" # strip: 0 # period: 1 # } #}
{ "pile_set_name": "Github" }
<?php /* * This file is part of the Predis package. * * (c) Daniele Alessandri <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Predis\Collection\Iterator; use InvalidArgumentException; use Iterator; use Predis\ClientInterface; use Predis\NotSupportedException; /** * Abstracts the iteration of items stored in a list by leveraging the LRANGE * command wrapped in a fully-rewindable PHP iterator. * * This iterator tries to emulate the behaviour of cursor-based iterators based * on the SCAN-family of commands introduced in Redis <= 2.8, meaning that due * to its incremental nature with multiple fetches it can only offer limited * guarantees on the returned elements because the collection can change several * times (trimmed, deleted, overwritten) during the iteration process. * * @author Daniele Alessandri <[email protected]> * @link http://redis.io/commands/lrange */ class ListKey implements Iterator { protected $client; protected $count; protected $key; protected $valid; protected $fetchmore; protected $elements; protected $position; protected $current; /** * @param ClientInterface $client Client connected to Redis. * @param string $key Redis list key. * @param int $count Number of items retrieved on each fetch operation. */ public function __construct(ClientInterface $client, $key, $count = 10) { $this->requiredCommand($client, 'LRANGE'); if ((false === $count = filter_var($count, FILTER_VALIDATE_INT)) || $count < 0) { throw new InvalidArgumentException('The $count argument must be a positive integer.'); } $this->client = $client; $this->key = $key; $this->count = $count; $this->reset(); } /** * Ensures that the client instance supports the specified Redis * command required to fetch elements from the server to perform * the iteration. * * @param ClientInterface $client Client connected to Redis. * @param string $commandID Command ID. */ protected function requiredCommand(ClientInterface $client, $commandID) { if (!$client->getProfile()->supportsCommand($commandID)) { throw new NotSupportedException("The specified server profile does not support the `$commandID` command."); } } /** * Resets the inner state of the iterator. */ protected function reset() { $this->valid = true; $this->fetchmore = true; $this->elements = array(); $this->position = -1; $this->current = null; } /** * Fetches a new set of elements from the remote collection, * effectively advancing the iteration process. * * @return array */ protected function executeCommand() { return $this->client->lrange($this->key, $this->position + 1, $this->position + $this->count); } /** * Populates the local buffer of elements fetched from the * server during the iteration. */ protected function fetch() { $elements = $this->executeCommand(); if (count($elements) < $this->count) { $this->fetchmore = false; } $this->elements = $elements; } /** * Extracts next values for key() and current(). */ protected function extractNext() { $this->position++; $this->current = array_shift($this->elements); } /** * {@inheritdoc} */ public function rewind() { $this->reset(); $this->next(); } /** * {@inheritdoc} */ public function current() { return $this->current; } /** * {@inheritdoc} */ public function key() { return $this->position; } /** * {@inheritdoc} */ public function next() { if (!$this->elements && $this->fetchmore) { $this->fetch(); } if ($this->elements) { $this->extractNext(); } else { $this->valid = false; } } /** * {@inheritdoc} */ public function valid() { return $this->valid; } }
{ "pile_set_name": "Github" }
// greater_equal.hpp // // (C) Copyright 2011 Vicente J. Botet Escriba // Use, modification and distribution are subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt). // #ifndef BOOST_RATIO_MPL_GREATER_EQUAL_HPP #define BOOST_RATIO_MPL_GREATER_EQUAL_HPP #include <boost/ratio/ratio.hpp> #include <boost/ratio/mpl/numeric_cast.hpp> #include <boost/mpl/greater_equal.hpp> namespace boost { namespace mpl { template<> struct greater_equal_impl< rational_c_tag,rational_c_tag > { template< typename R1, typename R2 > struct apply : ratio_greater_equal<R1, R2> { }; }; } } #endif // BOOST_RATIO_MPL_GREATER_EQUAL_HPP
{ "pile_set_name": "Github" }
package clock import ( "fmt" "log" "time" ) //ExampleClock_AddJobRepeat, show how to add repeat job。 func ExampleClock_AddJobRepeat() { var ( myClock = NewClock() ) fn := func() { fmt.Println("schedule repeat") } //create a task that executes three times,interval 50 millisecond _, inserted := myClock.AddJobRepeat(time.Duration(time.Millisecond*50), 3, fn) if !inserted { log.Println("failure") } //wait a second,watching time.Sleep(time.Second) //Output: // //schedule repeat //schedule repeat //schedule repeat } //ExampleClock_AddJobForEvent,show receive signal when job is called by system func ExampleClock_AddJobForEvent() { var ( myClock = NewClock() ) //define a repeat task fn := func() { //fmt.Println("schedule repeat") } //add in clock,execute three times,interval 200 millisecond job, inserted := myClock.AddJobRepeat(time.Duration(time.Millisecond*200), 3, fn) if !inserted { log.Println("failure") } go func() { for _ = range job.C() { fmt.Println("job done") } }() //wait a second,watching time.Sleep(time.Second) //Output: // //job done //job done //job done } //ExampleClock_AddJobWithInterval,show how to add a job just do once with interval func ExampleClock_AddJobWithInterval() { var ( jobClock = NewClock() jobFunc = func() { fmt.Println("schedule once") } ) //add a task that executes once,interval 100 millisecond jobClock.AddJobWithInterval(time.Duration(100*time.Millisecond), jobFunc) //wait a second,watching time.Sleep(1 * time.Second) //Output: // //schedule once } //ExampleClock_AddJobWithDeadtime,show how to add a job with a point time func ExampleClock_AddJobWithDeadtime() { var ( myClock = Default() jobFunc = func() { fmt.Println("schedule once") } actionTime = time.Now().Add(time.Millisecond * 500) ) //创建一次性任务,定时500ms job, _ := myClock.AddJobWithDeadtime(actionTime, jobFunc) //任务执行前,撤销任务 time.Sleep(time.Millisecond * 300) job.Cancel() //等待2秒,正常情况下,事件不会再执行 time.Sleep(2 * time.Second) //Output: // // } //ExampleClock_AddJobWithDeadtime,show how to cancel a job which added in system func ExampleClock_RmJob() { var ( myClock = NewClock() count int jobFunc = func() { count++ fmt.Println("do ", count) } ) //创建任务,间隔1秒,执行两次 job, _ := myClock.AddJobRepeat(time.Second*1, 2, jobFunc) //任务执行前,撤销任务 time.Sleep(time.Millisecond * 500) job.Cancel() //等待2秒,正常情况下,事件不会再执行 time.Sleep(2 * time.Second) //再次添加一个任务,病观察 myClock.AddJobRepeat(time.Second*1, 1, jobFunc) time.Sleep(time.Second * 2) //Output: // //do 1 }
{ "pile_set_name": "Github" }
azure.mgmt.authorization package ================================ Submodules ---------- .. toctree:: azure.mgmt.authorization.models azure.mgmt.authorization.operations Module contents --------------- .. automodule:: azure.mgmt.authorization :members: :undoc-members: :show-inheritance:
{ "pile_set_name": "Github" }
#tb 0: 1/25 #media_type 0: video #codec_id 0: rawvideo #dimensions 0: 416x240 #sar 0: 0/1 0, 0, 0, 1, 149760, 0xb92d38ee
{ "pile_set_name": "Github" }
(function (r) { 'use strong' const fse = r('fs-extra') const chalk = r('chalk') fse.readFile('./license.txt', 'utf8', (err, data) => { if (err) { return new Error('Couldn\'t read license information.') } console.log(chalk.magenta(data)) }) console.log(chalk.blue('Project is ready.')) })(require)
{ "pile_set_name": "Github" }
/*<FILE_LICENSE> * NFX (.NET Framework Extension) Unistack Library * Copyright 2003-2018 Agnicore Inc. portions ITAdapter Corp. Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. </FILE_LICENSE>*/ /* NFX by ITAdapter * Originated: 2006.01 * Revision: NFX 0.3 2009.10.12 */ using System; using System.Collections.Generic; using System.Text; using System.Security.Principal; using System.Runtime.Serialization; namespace NFX.Security { /// <summary> /// Marker interface denoting entities that represents information about users /// depending on the particular security system implementation /// </summary> public interface IIdentityDescriptor { /// <summary> /// Represents identity of the descriptor such as User.ID, User.GDID etc. /// Specifics depend on the system /// </summary> object IdentityDescriptorID { get; } /// <summary> /// Provides descriptor name such as User.Name, User.ScreenName etc. /// </summary> string IdentityDescriptorName { get; } /// <summary> /// Denotes types of identities: Users, Groups etc. /// </summary> IdentityType IdentityDescriptorType { get; } } /// <summary> /// Represents information about user identity /// </summary> public struct UserIdentityDescriptor : IIdentityDescriptor { public UserIdentityDescriptor(object id, string name) { m_IdentityDescriptorID = id; m_IdentityDescriptorName = name; } private object m_IdentityDescriptorID; private string m_IdentityDescriptorName; public object IdentityDescriptorID { get { return m_IdentityDescriptorID; } } public string IdentityDescriptorName { get { return m_IdentityDescriptorName; } } public IdentityType IdentityDescriptorType { get { return IdentityType.User; } } } /// <summary> /// Provides base user functionality. Particular security manager implementations may return users derived from this class /// </summary> [Serializable] public class User : IIdentityDescriptor, IIdentity, IPrincipal, IDeserializationCallback { #region Static private static readonly User s_FakeUserInstance = new User(BlankCredentials.Instance, new AuthenticationToken(), UserStatus.Invalid, "John Doe", "Fake user", NFX.Security.Rights.None); /// <summary> /// Returns default instance of the fake user that has no rights /// </summary> public static User Fake{ get{ return s_FakeUserInstance; } } #endregion #region .ctor private User() { } //for quicker serialization public User(Credentials credentials, AuthenticationToken token, UserStatus status, string name, string descr, Rights rights) { m_Credentials = credentials; m_AuthenticationToken = token; m_Status = status; m_Name = name; m_Description = descr; m_Rights = rights; m_StatusTimeStampUTC = App.TimeSource.UTCNow; } public User(Credentials credentials, AuthenticationToken token, string name, Rights rights) : this(credentials, token, UserStatus.User, name, null, rights) { } #endregion #region Fields private DateTime m_StatusTimeStampUTC; private Credentials m_Credentials; private AuthenticationToken m_AuthenticationToken; private UserStatus m_Status; private string m_Name; private string m_Description; [NonSerialized]//Important, rights are NOT serializable private Rights m_Rights; #endregion #region Properties /// <summary> /// Captures timestamp when this user was set to current status (created/set rights) /// Security managers may elect to reftech user rights after some period /// </summary> public DateTime StatusTimeStampUTC { get{ return m_StatusTimeStampUTC;} } public Credentials Credentials { get { return m_Credentials ?? BlankCredentials.Instance; } } public AuthenticationToken AuthToken { get { return m_AuthenticationToken; } } public string Name { get { return m_Name ?? string.Empty; } } public string Description { get { return m_Description ?? string.Empty; } } public UserStatus Status { get { return m_Status; } } /// <summary> /// Returns data bag that contains user rights. This is a framework-only internal property /// which should not be used by application developers. This bag may get populated fully-or-partially /// by ISecurityManager implementation. Use User[permission] indexer or Application.SecurityManager.Authorize() /// to obtain AccessLevel /// </summary> public Rights Rights { get { return m_Rights ?? NFX.Security.Rights.None; } } /// <summary> /// Authorizes user to specified permission. /// Note: this authorization call returns AccessLevel object that may contain a complex data structure. /// The final assertion of user's ability to perform a certain action is encapsulated in Permission.Check() method. /// Call Permission.AuthorizeAndGuardAction(MemberInfo, ISession) to guard classes and methods from unauthorized access /// </summary> public AccessLevel this[Permission permission] { get { return App.SecurityManager.Authorize(this, permission); } } #endregion #region Public /// <summary> /// Makes user invalid /// </summary> public void Invalidate() { m_Status = UserStatus.Invalid; } /// <summary> /// Framework-internal. Do not call /// </summary> public void ___update_status( UserStatus status, string name, string descr, Rights rights) { if (object.ReferenceEquals(this, s_FakeUserInstance)) return;//Fake user is immutable m_Status = status; m_Name = name; m_Description = descr; m_Rights = rights; m_StatusTimeStampUTC = App.TimeSource.UTCNow; } public override string ToString() { return "[{0}]{1},{2}".Args(Status, Name, Description); } #endregion #region IIdentity Members /// <summary> /// Implementation of IIdentity interface /// </summary> public string AuthenticationType { get { return m_AuthenticationToken.Realm ?? string.Empty; } } /// <summary> /// Implementation of IIdentity interface. Checks to see if user is not in invalid status /// </summary> public bool IsAuthenticated { get { return m_Status != UserStatus.Invalid; } } #endregion #region IPrincipal Members /// <summary> /// Implementation of IPrincipal interface /// </summary> public IIdentity Identity { get { return this; } } /// <summary> /// Determines whether the current principal belongs to the specified role. /// This method implements IPrincipal and has little application in NFX framework context /// as NFX permissions are more granular than just boolean. This method really checks user kind (User/Admin/Sys). /// Confusion comes from the fact that what Microsoft calls role really is just a single named permission - /// a role is a named permission set in NFX. /// </summary> public bool IsInRole(string role) { return m_Status.ToString().ToUpperInvariant() == role.ToUpperInvariant(); } #endregion #region IIdentityDescriptor public virtual string IdentityDescriptorName { get { return this.Name; } } public virtual object IdentityDescriptorID { get { return AuthToken; } } public virtual IdentityType IdentityDescriptorType { get { return IdentityType.User; } } #endregion #region IDeserializationCallback public void OnDeserialization(object sender) { //Re-authorizes user re-fetches Rights (Rights are not serializable) App.SecurityManager.Authenticate(this); } #endregion } }
{ "pile_set_name": "Github" }
// Copyright 2019 Google // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #import <Foundation/Foundation.h> /** * Completion block that can be called in your subclass implementation. It is up to you when you * want to call it. */ typedef void (^FIRCLSFABAsyncOperationCompletionBlock)(NSError *__nullable error); /** * FIRCLSFABAsyncOperation is a subclass of NSOperation that allows for asynchronous work to be * performed, for things like networking, IPC or UI-driven logic. Create your own subclasses to * encapsulate custom logic. * @warning When subclassing to create your own operations, be sure to call -[finishWithError:] at * some point, or program execution will hang. * @see -[finishWithError:] in FIRCLSFABAsyncOperation_Private.h */ @interface FIRCLSFABAsyncOperation : NSOperation /** * Add a callback method for consumers of your subclasses to set when the asynchronous work is * marked as complete with -[finishWithError:]. */ @property(copy, nonatomic, nullable) FIRCLSFABAsyncOperationCompletionBlock asyncCompletion; @end
{ "pile_set_name": "Github" }
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ declare(strict_types=1); namespace Magento\Elasticsearch\SearchAdapter\Query; /** * Pool of value transformers. */ class ValueTransformerPool { /** * @var ValueTransformerInterface[] */ private $transformers; /** * @param ValueTransformerInterface[] $valueTransformers */ public function __construct(array $valueTransformers = []) { foreach ($valueTransformers as $valueTransformer) { if (!$valueTransformer instanceof ValueTransformerInterface) { throw new \InvalidArgumentException( \sprintf('"%s" is not a instance of ValueTransformerInterface.', get_class($valueTransformer)) ); } } $this->transformers = $valueTransformers; } /** * Get value transformer related to field type. * * @param string $fieldType * @return ValueTransformerInterface */ public function get(string $fieldType): ValueTransformerInterface { return $this->transformers[$fieldType] ?? $this->transformers['default']; } }
{ "pile_set_name": "Github" }
defmodule Cog.Test.Commands.Group.Member.RemoveTest do use Cog.CommandCase, command_module: Cog.Commands.Group alias Cog.Commands.Group.Member import Cog.Support.ModelUtilities, only: [user: 1, group: 1, add_to_group: 2] setup [:with_user, :with_group] test "can be removed from a group", %{user: user, group: group} do # Add the user to the group group = add_to_group(group, user) # Make sure that it's there assert(is_group_user?(group, user.username)) # Then remove it via the group command {:ok, response} = new_req(args: [group.name, user.username]) |> send_req(Member.Remove) refute(is_group_user?(response, user.username)) end defp with_user(_), do: [user: user("belf")] defp with_group(_), do: [group: group("elves")] defp is_group_user?(%Cog.Models.Group{}=group, username) do Enum.map(group.users, &(&1.username)) |> Enum.member?(username) end defp is_group_user?(%{members: members}, username) do Enum.map(members, &(&1.username)) |> Enum.member?(username) end end
{ "pile_set_name": "Github" }
<filters> <item enabled="true">t=◎Bilibili_Block_List_Main_By_Jn_xyp_[0.7.048-Plus]</item> <item enabled="true">t=◎Special_Thanks:Thiece__BlackGlory__deerchao</item> <item enabled="true">t=◎Thanks:_章程__Incredible灵动__ssslos__知白Dive__点草丶麻花疼__食谱?D?铭__liuyuzhelyzlyz__445621607__LOOK冯</item> <item enabled="true">t=◎加X在前代表有争议,讨论是否删除【这是屏蔽示例】提意见请贴吧@Jn_xyp或邮件到[email protected]</item> <item enabled="true">t=(?#【屏蔽单字弹幕】)^.$</item> <item enabled="true">t=(?#【屏蔽空白弹幕】)^\s+$</item> <item enabled="true">t=(?#【屏蔽单刷弹幕】)[?!/?/!~~,/.,。]{6,}|[啊Aa]{5,}|哦{5,}|[哈Hh]{7,}|[呜5u]{5,}|嗷{5,}|美{5,}|帅{5,}</item> <item enabled="true">t=(?#【弹幕留念】)弹幕(测试|留念)|合影</item> <item enabled="true">t=(?#【弹幕由我组成】)由我(来){0,}[组租]成</item> <item enabled="true">t=(?#【挡XX】)关.*[弹彈]幕|[当档挡].*([屏字]幕|字母)|[低底][端部][弹彈]幕</item> <item enabled="true">t=(?#【弹幕相关A】)(清|刷|增加)([弹彈][幕目]|屏|频)</item> <item enabled="true">t=(?#【弹幕相关B】)([弹彈][幕目]|人).{0,2}(清|不见|多|少|薄|厚|没|木|有|无|呢|捏|哪|纳|支援)|(清|不见|多|少|薄|厚|没|木|有|无).{0,2}([弹彈][幕目]|人)|^([弹彈][幕目]|人)[呢捏哪纳].{0,3}$|求不刷</item> <item enabled="true">t=(?#【单字屏蔽】)屄|尻|娼|嫖|贱|肏|吠|傻|痴|呸|呕|淫</item> <item enabled="true">t=(?#【刷一发,没有我大XX能忍?!?】)[来刷撸]一发|能忍|忍不住|炸[出粗]来|助[攻力]|[百千万Ww].*(达成|破|播放)|达成|破|播放).*([百千万Ww]|^我大</item> <item enabled="true">t=(?#【每日签到,X遍,X周目】)签到|打卡|留..念|到此一游|观光团|每[天日]\S{1,}|\S{1,}周目|[第每]\S{1,}遍|一[天日]不[看听].*难受|[①②③④⑤⑥⑦⑧⑨01234567890-9 〇一二两俩三仨四五六七八九十零百千万亿Ww]{2,4}.{0,1}遍|[就才].*(看|听|循环)遍.*关</item> <item enabled="true">t=(?#【前100,第一】)^\S{0,4}第[①②③④⑤⑥⑦⑧⑨01234567890-9 〇一二两俩三仨四五六七八九十零百千万亿Ww]{1,4}\S{0,4}$|前[①②③④⑤⑥⑦⑧⑨01234567890-9 〇一二两俩三仨四五六七八九十零百千万亿Ww]{1,4}|(前){3,}|前[?!/?/!~~]|[①②③④⑤⑥⑦⑧⑨01234567890-9 〇一二两俩三仨四五六七八九十零百千万亿Ww][Ll楼][楼lL]</item> <item enabled="true">t=(?#【求不卡,小水管,竟然卡】)(好|求不)卡|卡了|卡成[狗翔屎]|.*(带宽|宽带)|[小大粗细]水管|看不了|[黑花绿]屏</item> <item enabled="true">t=(?#【沙发,路过】)沙发|板凳|地板|前排|(好|这么|如此)[前钱钳早]|[路飘飞游撸]过|sf|Sf|SF</item> <item enabled="true">t=(?#【XX不行】)(AV|Av|av|渣|烂|屎).*画质|(水平|片源|画质|BGM|Bgm|bgm|音乐|歌曲|配乐|CV|Cv|cv|声优)(不[行喜]|垃圾|辣鸡)|辣鸡|垃圾|渣渣|用烂|烂|屎|[比没].{1,}[好差强弱跳翻唱说做调剪编拍写早晚原作做隔[国|國]]|凭什么</item> <item enabled="true">t=(?#【什么啊,这都什么鬼】)(毛|什么)啊|什么鬼|[Ss]hen[Mm]e[Gg]ui</item> <item enabled="true">t=(?#【屏蔽刷日期A】)[①②③④⑤⑥⑦⑧⑨01234567890-9 〇一二两俩三仨四五六七八九十零百千万亿Ww]{2,4}[:|/| |,|\.|。|:|年|-][①②③④⑤⑥⑦⑧⑨01234567890-9 〇一二两俩三仨四五六七八九十零百千万亿Ww](?!hy){1,2}[:|/| |,|\.|。|:|月|-]([①②③④⑤⑥⑦⑧⑨01234567890-9 〇一二两俩三仨四五六七八九十零百千万亿Ww](?!hy){1,2})?</item> <item enabled="true">t=(?#【屏蔽刷日期B】)[①②③④⑤⑥⑦⑧⑨01234567890-9 〇一二两俩三仨四五六七八九十零百千万亿Ww]{1,2}[:|/| |,|\.|。|:|-][①②③④⑤⑥⑦⑧⑨01234567890-9 〇一二两俩三仨四五六七八九十零百千万亿Ww](?!hy){1,2}([:|/| |,|\.|。|:|-][①②③④⑤⑥⑦⑧⑨01234567890-9 〇一二两俩三仨四五六七八九十零百千万亿Ww](?!hy){0,2})?</item> <item enabled="true">t=(?#【地名】)[妖帝魔伪]都|辽宁|吉林|黑龙江|河北|山西|陕西|甘肃|青海|山东|安徽|江苏|浙江|河南|湖北|湖南|江西|台[湾灣]|福建|云南|海南|四川|贵州|广东|内蒙古|新疆|广西|西藏|宁夏|北京|上海|天津|重庆|香港|澳[门門]|深圳|广州|成都</item> <item enabled="true">t=(?#【火钳刘明】)[火][前钳]|[流留刘][名铭明]|要火|万火留</item> <item enabled="true">t=(?#【独享吾王成功】)独享(.){0,}(失败|成功)</item> <item enabled="true">t=(?#【剧透类】)剧透|剧透|透剧|透剧|人干的|人干事</item> <item enabled="true">t=(?#【符号刷屏】)厂下广卞廿|十一卉半与|屮|艸|芔|茻|●~|←↖↑↗→↘↓↙|▂|▅|▆|▇|█|★═|▄|︻</item> <item enabled="true">t=(?#【根本把持不住,处女币】)把持不住</item> <item enabled="true">t=(?#【XXXby2b】)by|BY|By</item> <item enabled="true">t=(?#【会员是什么】)[什么怎啥].*会员|会员.*[什么怎啥啊]|会员.*世界</item> <item enabled="true">t=(?#【xxx我知道你再看】)我知道你.{0,1}[在再能]看|[我只唯][宣爱]</item> <item enabled="true">t=(?#【大天使之剑!!】)战舰世界|大天使之剑|战舰少女</item> <item enabled="true">t=(?#【毁我大XX】)毁我.*|毁在</item> <item enabled="true">t=(?#【你MB,CNM】)[你我他她它老泥尼拟死][母马妈妹奶娘煤](?!妈|奶|娘|亲|呀)|NMB|nmb|Nmb|NIMABI|nimabi|C.{0,5}N.{0,5}M|c.{0,5}n.{0,5}m|fuck|FUCK|Fuck</item> <item enabled="true">t=(?#【你老婆的本子我都看过】)老婆(的){0,}本子|女((朋){0,}友|人|票)(的){0,}本子</item> <item enabled="true">t=(?#【3倍速,怎么变色】)变色|倍速|发光</item> <item enabled="true">t=(?#【祥瑞玉兔】)祥瑞玉兔|家宅平安|羊踹玉兔|玉兔喊疼</item> <item enabled="true">t=(?#【国人就是这样】)[国國]耻|[国國]人就|[老劳][子资資]|[国國]界|[[滚滾]|滾](.{0,5}[吧粗出]|\s|!)|[国國]产|日元|奴性|你[国國]|大[陆陸]</item> <item enabled="true">t=(?#【汉奸,纳粹】)汉[奸J]|纳粹|法西斯</item> <item enabled="true">t=(?#【SB,煞笔】)[傻煞渣死二烧][逼笔哔碧比屄饼]|脑残|下限|智商|人渣|去死|2B|2b|SB|sb|Sb|S13|s13|NC|^.{0,4}nc.{0,4}$|Nc|nC</item> <item enabled="true">t=(?#【优越XXX】)(优越|果断)([滚滾]|撤退|离开|右上|感|狗)|素质|(请|不[愿想]看([滚滾]|撤退|离开|右上)|散了吧</item> <item enabled="true">t=(?#【你是XXX】)[你我他她它泥尼拟]是(猪|牛|马|基(佬){0,}|鸡|猴|羊|百合|同性恋|GAY|gay|Gay)</item> <item enabled="true">t=(?#【丢雷楼某】)丢[你泥尼拟雷累类][老楼漏][母某]|扑街</item> <item enabled="true">t=(?#【我真是日了整个动物园了】)日了(狗|up(主){0,}|.*动物园)|日日</item> <item enabled="true">t=(?#【灵车飘移,坟圈爆炸】)灵车|坟[圈头]|棺材</item> <item enabled="true">t=(?#【我裤子都脱了】)裤子.*脱|脱.*裤子</item> <item enabled="true">t=(?#【五毛滚粗,河蟹】)五毛|美分|自干五|政.{0,3}治|郑智|症治|和[諧谐]|河蟹|民.{0,3}主|皿煮|滋油</item> <item enabled="true">t=(?#【你够了】)[你尼泥拟].{0,3}够了</item> <item enabled="true">t=(?#【OOXX】)[Oo]{1,}[Xx]{1,}|活塞运动</item> <item enabled="true">t=(?#【偷偷承包】)([被由]我|偷偷|悄悄|被)(来){0,}承包|休想|承包.{0,5}</item> <item enabled="true">t=(?#【见X[滚|滾]】)(我{0,}就|我就{0,}).{0,3}来了|^来了$|见(.){0,}[滚|滾|进]</item> <item enabled="true">t=(?#【此生XX,来世XX】)[此今]生|来世</item> <item enabled="true">t=(?#【你行你上】)你行你上|[Yy]ou can you up|can('t|t).*[Bb逼哔]</item> <item enabled="true">t=(?#【爱的自杀】)爱的(供[养氧]|自杀)|再问(供[养氧]|自杀)</item> <item enabled="true">t=(?#【由我来组成!】)由我(来){0,}([守保]护|捍卫|改[写变])</item> <item enabled="true">t=(?#【抢老婆】)我老婆|我(的){0,}女((朋){0,}友|人|票)|我(的){0,}男神|^.{2,6}我的|拔[刀剑]|.{1,}嫁.我|我[的哒]$|表白.{2,}|喜欢你|爱着你|你们.{0,3}分</item> <item enabled="true">t=(?#【完结撒花】)完结撒花</item> <item enabled="true">t=(?#【啪啪啪】)(PA|Pa|pa|啪帕拍){3,}|割鸡|小丁丁|[鸡Jj][巴吧8Bb]</item> <item enabled="true">t=(?#【@人名】)^@.{1,3}$|若风|老E|老e|纯黑|bishi|鼻屎|碧诗|姥爷|aoao|AOAO|敖|厂长|老[滚|滾]|伊丽莎白鼠|吃素的狮子|八尾妖[姬基鸡]</item> <item enabled="true">t=(?#【三次元人名】)张杰|郭德[纲肛]|汪[峰涵]|头条</item> <item enabled="true">t=(?#【XX分钟的XX】)分钟的(人生|鬼畜|精神污染)</item> <item enabled="true">t=(?#【我是世界第几帅】)告诉我.*[帅酷]</item> <item enabled="true">t=(?#【另外X个观众你们好】)(其他|另|另外).{1,5}(个|位|名|铭|明).*[好嚎耗豪]|你们好|大家好</item> <item enabled="true">t=(?#【豆腐脑】)豆腐脑|甜党|咸党</item> <item enabled="true">t=(?#【憋跑】)你在[哪那]里|[别憋鳖][跑走]|等我</item> <item enabled="true">t=(?#【小说党漫画党】)原作|(小说|漫画)党</item> <item enabled="true">t=(?#【争论相关】)闭嘴|打脸|素质|键盘侠|键盘大手|喷子</item> <item enabled="true">t=(?#【脸不给看】)脸不.{0,1}给.{0,1}看|[当档挡].*脸</item> <item enabled="true">t=(?#【破鞋,婊】)破[鞋处處]|[处處][女男]|[绿綠]茶|[马玛瑪]丽苏|婊</item> <item enabled="true">t=(?#【小学生】).[學学穴]生</item> <item enabled="true">t=(?#【硬币相关】)处女[币幣B]|[硬投][币幣]送上</item> <item enabled="true">t=(?#【空降相关】)空降(成功|失败|完美)|(成功|失败|完美)空降</item> <item enabled="true">t=(?#【舔pr】)舔舔|([Pp][Rr]){2,}|舔屏幕|舔[手脚腿]|屏幕[下有]毒</item> <item enabled="true">t=(?#【百度XX吧】)百度.*吧</item> <item enabled="true">t=(?#【放开那个XX】)放开.*我[来上干]|放开[这那哪我]</item> <item enabled="true">t=(?#【XX棒XX杯】)[振震]动棒|飞机杯|跳蛋</item> <item enabled="true">t=◎以下为P版本内容-----------------</item> <item enabled="true">t=(?#XX【前方高能,FBI】)(前方|全程)高能|非战斗人员.{0,1}迅速撤离|[Ff][Bb][Ii]|[Ww]arning</item> <item enabled="true">t=(?#XX【233666www】)([23]){8,}|[Ww]{8,}|[6六溜]{8,}</item> <item enabled="true">t=(?#X【不明觉厉】)不明觉厉</item> <item enabled="true">t=(?#X【开口跪】)开口.{1,}|张嘴{1,}</item> <item enabled="true">t=(?#X【硬币相关】)硬[币幣]</item> <item enabled="true">t=(?#X【生日快乐】)生日快乐|生快</item> <item enabled="true">t=(?#X【AV号】)10492|[Aa][Vv][①②③④⑤⑥⑦⑧⑨01234567890-9 〇一二两俩三仨四五六七八九十零百千万亿Ww]{3,}</item> <item enabled="true">t=(?#X【虐狗】)虐.*狗|([单双]身|恩爱)狗</item> <item enabled="true">t=(?#X【暂停】)暂停(成功|失败)</item> <item enabled="true">t=(?#X【壮哉我大】)壮哉.*大|再战.*年|永垂不朽|长存</item> <item enabled="true">t=(?#X【一上线】)[已一以]上线|[您你]的好友</item> <item enabled="true">t=(?#X【美如画一生推】)美如画|一生推</item> <item enabled="true">t=(?#X【12,450】)Q12Q|q12q|Q12q|12dog|12DOG|12Dog|12dora|12Dora|12DORA|M12|m12|450</item> <item enabled="true">t=(?#【狼牙路私立断罪小学】).*(小学|附小|中学|初中|高中|附中|中职|高职|职业学院|学院|大学)</item> <item enabled="true">t=(?#【弹幕护体】)弹.{0,3}幕.{0,3}护.{0,3}体|恶.{0,3}灵.{0,3}退.{0,3}散|精神污染</item> <item enabled="true">t=(?#【你不是一个人】)你(们){0,}不是\S{1,}个人|\S{1,}字你\S{1,}</item> <item enabled="true">t=(?#【逝者安息】)逝者安息|无意冒犯</item> <item enabled="true">t=(?#【伏笔,FLAG】)伏笔|Flag|FLAG|flag|[树竖立]旗|怪我</item> <item enabled="true">t=(?#【发来核电】)发来\S{2,}|[贺核]电</item> <item enabled="true">t=(?#【以上企业均】)均已(破产|倒闭)|\S{2,}赞助</item> <item enabled="true">t=(?#【XXX.avi】)avi|rmvb|AVI|Avi|RMVB|Player|player|WMV|Wmv|wmv|快播</item> <item enabled="true">t=(?#【滴,穴深卡】)老司机|.{2,}卡|带带我</item> <item enabled="true">t=(?#【MM你XX】)你听我解释|默默[带戴]上耳机|问.*跪</item> <item enabled="true">t=(?#【存货确认】)^.{0,4}阵亡|^存[活货]|^幸存</item> <item enabled="true">t=(?#【交出BGM还是好朋友】)(要|交出|求|问).*(BGM|Bgm|bgm|图包|[音配]乐|歌曲|地址|软件|动漫|封面)|(BGM|Bgm|bgm|图包|[音配]乐|歌曲|地址|软件|动漫|封面).{0,3}(啥|什么)|还是好朋友</item> <item enabled="true">t=(?#【失踪人口回归,挖坟】)(失踪|死亡)(人[口员]|up(主){0,})|考古|挖坟|巨坟|有生之年|洛阳铲|李敏镐</item> <item enabled="true">t=(?#【音乐鬼畜区输了】)(音乐|鬼畜)区.*(战|投降|输|赢)</item> <item enabled="true">t=(?#【镇站之宝】)镇[站区店]之宝|万恶之源</item> <item enabled="true">t=(?#【这不科学】)不(科学|魔法)</item> <item enabled="true">t=(?#【耳朵怀孕】)[眼耳].*(瞎|聋|怀孕)</item> <item enabled="true">t=(?#【自动变黄】)^\S{0,4}[红黄蓝篮绿黑青白紫橙粉][子字色]\S{0,4}$|变[红黄蓝篮绿黑青白紫橙粉]</item> <item enabled="true">t=(?#【哈哈哈哈】)红红火火恍恍惚惚|[哈嘿呵Hh]{5,}</item> <item enabled="true">t=(?#【丑哭,帅炸】)[丑帅][哭爆炸掉]</item> <item enabled="true">t=(?#【维和感】)(维和|违和)感</item> <item enabled="true">t=(?#【我开始方了】)(好|开始)[慌方放]</item> <item enabled="true">t=(?#【药丸,要完】)[吃迟][早枣][要药妖][完玩丸]|B站[要药妖][完玩丸]</item> <item enabled="true">t=(?#【有毒系列】)[下有中].*毒</item> <item enabled="true">t=(?#【进度条相关】)看进度条|进度条\W*|进度条.{1,}([肿怎]么|超神|一半|挺住)|讲.{0,3}鬼故事</item> <item enabled="true">t=(?#【拿原版骗人】)原[版板].*骗|忘.{1,6}原[版板]</item> <item enabled="true">t=(?#【钓鱼相关】)好大的鱼|虎纹鲨鱼|钓鱼|鱼钩.*直|鱼饵.*[腥臭]</item> <item enabled="true">t=(?#【Disco】)[Dd][Ii][Ss][Cc][Oo]</item> <item enabled="true">t=(?#【QQ号】)[①②③④⑤⑥⑦⑧⑨01234567890-9 〇一二两俩三仨四五六七八九十零百千万亿Ww]{9,16}</item> <item enabled="true">t=(?#【其他短语】)也是醉|一颗赛艇|腿.*玩|生[孩猴][子字]</item> <item enabled="true">t=(?#【停不下来】)停不下来|[出粗]不去|欢迎回来</item> <item enabled="true">t=(?#【漫长的XXX】)漫长的</item> <item enabled="true">t=(?#【灵魂XXX】)灵魂.{1,4}[手师员]</item> <item enabled="true">t=(?#【表示清白】)[单双][手脚].*(打字|键盘|之间|胯下|裆部)</item> <item enabled="true">t=(?#【其他词语】)前列腺|白带</item> <item enabled="true">t=(?#【我选择死亡】)选择.{0,3}死亡</item> <item enabled="true">t=(?#【真当XX不上XX】)(真当|当真).{1,7}不上</item> <item enabled="true">t=(?#【报警】)110|120|119|报警|举报|[妖药腰][妖药腰][灵零令]</item> <item enabled="true">t=(?#【三次元神器合集】)板砖|诺基亚|[Gg][Tt][Xx][①②③④⑤⑥⑦⑧⑨01234567890-9 〇一二两俩三仨四五六七八九十零百千万亿Ww]{1,3}</item> <item enabled="true">t=(?#【CCTV相关】)走近.{0,2}(科学|魔法)|CCTV|cctv|Cctv|CCAV|ccav|Ccav|新闻联播|中央台|春晚</item> <item enabled="true">t=(?#【查水表,送快递】)快递|(水|电|气)表|送温暖</item> <item enabled="true">t=(?#【你瞅啥瞅你咋地】)你瞅啥|瞅你咋地</item> <item enabled="true">t=(?#【德玛西亚】)德玛西亚|马来西亚之力</item> <item enabled="true">t=(?#【腾讯游戏】)CF|cf|Cf|cF|穿越火线|腾讯|[3三]亿.*鼠标|lol|LOL|马化腾|麻花疼</item> <item enabled="true">t=(?#【TF男孩】)TF|tf|Tf|[掏淘吃拔捅舔吃食][粪屎翔]</item> <item enabled="true">t=(?#【牛头人】)ntr|NTR|Ntr|NTL|ntl|Ntl|NTRS|ntrs|Ntrs|牛头人</item> <item enabled="true">t=(?#【地球OL】)地球OL|([Vv][Ii][Pp]|[Rr][Mm][Bb])玩家</item> <item enabled="true">t=(?#【我保证】)保证(不打死|打不死)</item> <item enabled="true">t=(?#【二次元神器合集】)(EX|Ex|ex)咖喱棒|物理学圣剑|撬棍|贤者之石|死海文书</item> <item enabled="true">t=(?#【教练我想学】)教练.*(不会|学)</item> <item enabled="true">t=(?#【XX的错】)世界|圆盘|时[臣辰晨])的错</item> <item enabled="true">t=(?#【骑士团】)骑士团|参见|^.王$</item> </filters>
{ "pile_set_name": "Github" }
// @flow import styled from 'styled-components' import * as React from 'react' type Props = { size: number, src: string, style?: Object, className?: string, color?: string, } const StyledAvater = styled.img` user-select: none; display: inline-flex; align-items: center; justify-content: center; border-radius: 5px; width: ${props => props.size}px; height: ${props => props.size}px; color: ${props => props.color || '#fff'}; ` const Avater = (props: Props) => <StyledAvater {...props} /> export default Avater
{ "pile_set_name": "Github" }
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2012 Désiré Nuentsa-Wakam <[email protected]> // Copyright (C) 2012 Gael Guennebaud <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef EIGEN_SPARSELU_SUPERNODAL_MATRIX_H #define EIGEN_SPARSELU_SUPERNODAL_MATRIX_H namespace Eigen { namespace internal { /** \ingroup SparseLU_Module * \brief a class to manipulate the L supernodal factor from the SparseLU factorization * * This class contain the data to easily store * and manipulate the supernodes during the factorization and solution phase of Sparse LU. * Only the lower triangular matrix has supernodes. * * NOTE : This class corresponds to the SCformat structure in SuperLU * */ /* TODO * InnerIterator as for sparsematrix * SuperInnerIterator to iterate through all supernodes * Function for triangular solve */ template <typename _Scalar, typename _StorageIndex> class MappedSuperNodalMatrix { public: typedef _Scalar Scalar; typedef _StorageIndex StorageIndex; typedef Matrix<StorageIndex,Dynamic,1> IndexVector; typedef Matrix<Scalar,Dynamic,1> ScalarVector; public: MappedSuperNodalMatrix() { } MappedSuperNodalMatrix(Index m, Index n, ScalarVector& nzval, IndexVector& nzval_colptr, IndexVector& rowind, IndexVector& rowind_colptr, IndexVector& col_to_sup, IndexVector& sup_to_col ) { setInfos(m, n, nzval, nzval_colptr, rowind, rowind_colptr, col_to_sup, sup_to_col); } ~MappedSuperNodalMatrix() { } /** * Set appropriate pointers for the lower triangular supernodal matrix * These infos are available at the end of the numerical factorization * FIXME This class will be modified such that it can be use in the course * of the factorization. */ void setInfos(Index m, Index n, ScalarVector& nzval, IndexVector& nzval_colptr, IndexVector& rowind, IndexVector& rowind_colptr, IndexVector& col_to_sup, IndexVector& sup_to_col ) { m_row = m; m_col = n; m_nzval = nzval.data(); m_nzval_colptr = nzval_colptr.data(); m_rowind = rowind.data(); m_rowind_colptr = rowind_colptr.data(); m_nsuper = col_to_sup(n); m_col_to_sup = col_to_sup.data(); m_sup_to_col = sup_to_col.data(); } /** * Number of rows */ Index rows() { return m_row; } /** * Number of columns */ Index cols() { return m_col; } /** * Return the array of nonzero values packed by column * * The size is nnz */ Scalar* valuePtr() { return m_nzval; } const Scalar* valuePtr() const { return m_nzval; } /** * Return the pointers to the beginning of each column in \ref valuePtr() */ StorageIndex* colIndexPtr() { return m_nzval_colptr; } const StorageIndex* colIndexPtr() const { return m_nzval_colptr; } /** * Return the array of compressed row indices of all supernodes */ StorageIndex* rowIndex() { return m_rowind; } const StorageIndex* rowIndex() const { return m_rowind; } /** * Return the location in \em rowvaluePtr() which starts each column */ StorageIndex* rowIndexPtr() { return m_rowind_colptr; } const StorageIndex* rowIndexPtr() const { return m_rowind_colptr; } /** * Return the array of column-to-supernode mapping */ StorageIndex* colToSup() { return m_col_to_sup; } const StorageIndex* colToSup() const { return m_col_to_sup; } /** * Return the array of supernode-to-column mapping */ StorageIndex* supToCol() { return m_sup_to_col; } const StorageIndex* supToCol() const { return m_sup_to_col; } /** * Return the number of supernodes */ Index nsuper() const { return m_nsuper; } class InnerIterator; template<typename Dest> void solveInPlace( MatrixBase<Dest>&X) const; protected: Index m_row; // Number of rows Index m_col; // Number of columns Index m_nsuper; // Number of supernodes Scalar* m_nzval; //array of nonzero values packed by column StorageIndex* m_nzval_colptr; //nzval_colptr[j] Stores the location in nzval[] which starts column j StorageIndex* m_rowind; // Array of compressed row indices of rectangular supernodes StorageIndex* m_rowind_colptr; //rowind_colptr[j] stores the location in rowind[] which starts column j StorageIndex* m_col_to_sup; // col_to_sup[j] is the supernode number to which column j belongs StorageIndex* m_sup_to_col; //sup_to_col[s] points to the starting column of the s-th supernode private : }; /** * \brief InnerIterator class to iterate over nonzero values of the current column in the supernodal matrix L * */ template<typename Scalar, typename StorageIndex> class MappedSuperNodalMatrix<Scalar,StorageIndex>::InnerIterator { public: InnerIterator(const MappedSuperNodalMatrix& mat, Index outer) : m_matrix(mat), m_outer(outer), m_supno(mat.colToSup()[outer]), m_idval(mat.colIndexPtr()[outer]), m_startidval(m_idval), m_endidval(mat.colIndexPtr()[outer+1]), m_idrow(mat.rowIndexPtr()[mat.supToCol()[mat.colToSup()[outer]]]), m_endidrow(mat.rowIndexPtr()[mat.supToCol()[mat.colToSup()[outer]]+1]) {} inline InnerIterator& operator++() { m_idval++; m_idrow++; return *this; } inline Scalar value() const { return m_matrix.valuePtr()[m_idval]; } inline Scalar& valueRef() { return const_cast<Scalar&>(m_matrix.valuePtr()[m_idval]); } inline Index index() const { return m_matrix.rowIndex()[m_idrow]; } inline Index row() const { return index(); } inline Index col() const { return m_outer; } inline Index supIndex() const { return m_supno; } inline operator bool() const { return ( (m_idval < m_endidval) && (m_idval >= m_startidval) && (m_idrow < m_endidrow) ); } protected: const MappedSuperNodalMatrix& m_matrix; // Supernodal lower triangular matrix const Index m_outer; // Current column const Index m_supno; // Current SuperNode number Index m_idval; // Index to browse the values in the current column const Index m_startidval; // Start of the column value const Index m_endidval; // End of the column value Index m_idrow; // Index to browse the row indices Index m_endidrow; // End index of row indices of the current column }; /** * \brief Solve with the supernode triangular matrix * */ template<typename Scalar, typename Index_> template<typename Dest> void MappedSuperNodalMatrix<Scalar,Index_>::solveInPlace( MatrixBase<Dest>&X) const { /* Explicit type conversion as the Index type of MatrixBase<Dest> may be wider than Index */ // eigen_assert(X.rows() <= NumTraits<Index>::highest()); // eigen_assert(X.cols() <= NumTraits<Index>::highest()); Index n = int(X.rows()); Index nrhs = Index(X.cols()); const Scalar * Lval = valuePtr(); // Nonzero values Matrix<Scalar,Dynamic,Dest::ColsAtCompileTime, ColMajor> work(n, nrhs); // working vector work.setZero(); for (Index k = 0; k <= nsuper(); k ++) { Index fsupc = supToCol()[k]; // First column of the current supernode Index istart = rowIndexPtr()[fsupc]; // Pointer index to the subscript of the current column Index nsupr = rowIndexPtr()[fsupc+1] - istart; // Number of rows in the current supernode Index nsupc = supToCol()[k+1] - fsupc; // Number of columns in the current supernode Index nrow = nsupr - nsupc; // Number of rows in the non-diagonal part of the supernode Index irow; //Current index row if (nsupc == 1 ) { for (Index j = 0; j < nrhs; j++) { InnerIterator it(*this, fsupc); ++it; // Skip the diagonal element for (; it; ++it) { irow = it.row(); X(irow, j) -= X(fsupc, j) * it.value(); } } } else { // The supernode has more than one column Index luptr = colIndexPtr()[fsupc]; Index lda = colIndexPtr()[fsupc+1] - luptr; // Triangular solve Map<const Matrix<Scalar,Dynamic,Dynamic, ColMajor>, 0, OuterStride<> > A( &(Lval[luptr]), nsupc, nsupc, OuterStride<>(lda) ); Map< Matrix<Scalar,Dynamic,Dest::ColsAtCompileTime, ColMajor>, 0, OuterStride<> > U (&(X(fsupc,0)), nsupc, nrhs, OuterStride<>(n) ); U = A.template triangularView<UnitLower>().solve(U); // Matrix-vector product new (&A) Map<const Matrix<Scalar,Dynamic,Dynamic, ColMajor>, 0, OuterStride<> > ( &(Lval[luptr+nsupc]), nrow, nsupc, OuterStride<>(lda) ); work.topRows(nrow).noalias() = A * U; //Begin Scatter for (Index j = 0; j < nrhs; j++) { Index iptr = istart + nsupc; for (Index i = 0; i < nrow; i++) { irow = rowIndex()[iptr]; X(irow, j) -= work(i, j); // Scatter operation work(i, j) = Scalar(0); iptr++; } } } } } } // end namespace internal } // end namespace Eigen #endif // EIGEN_SPARSELU_MATRIX_H
{ "pile_set_name": "Github" }
<resources> <!-- Default screen margins, per the Android Design guidelines. --> <dimen name="activity_horizontal_margin">16dp</dimen> <dimen name="activity_vertical_margin">16dp</dimen> <dimen name="avatar_width">80dp</dimen> <dimen name="avatar_height">80dp</dimen> <dimen name="appbar_layout_height">260dp</dimen> <!-- item --> <dimen name="item_tv_title">16sp</dimen> <dimen name="item_tv_content">14sp</dimen> <dimen name="item_tv_date">12sp</dimen> <dimen name="item_tv_tag">12sp</dimen> <dimen name="item_tv_author">12sp</dimen> <dimen name="item_tv_via">12sp</dimen> <dimen name="item_content_padding">10dp</dimen> <dimen name="item_img_width">120dp</dimen> <dimen name="item_img_height">90dp</dimen> <dimen name="textSize_small_10">10sp</dimen> <dimen name="textSize_small">12sp</dimen> <dimen name="textSize_content">14sp</dimen> <dimen name="textSize_titleSmall">16sp</dimen> <dimen name="textSize_title">18sp</dimen> <!-- dp --> <dimen name="dp_05">0.5dp</dimen> <dimen name="dp_1">1dp</dimen> <dimen name="dp_2">2dp</dimen> <dimen name="dp_3">3dp</dimen> <dimen name="dp_4">4dp</dimen> <dimen name="dp_5">5dp</dimen> <dimen name="dp_6">6dp</dimen> <dimen name="dp_8">8dp</dimen> <dimen name="dp_10">10dp</dimen> <dimen name="dp_12">12dp</dimen> <dimen name="dp_16">16dp</dimen> <dimen name="dp_18">18dp</dimen> <dimen name="dp_20">20dp</dimen> <dimen name="dp_24">24dp</dimen> <dimen name="dp_26">26dp</dimen> <dimen name="dp_28">28dp</dimen> <dimen name="dp_30">30dp</dimen> <dimen name="dp_36">36dp</dimen> <dimen name="dp_46">46dp</dimen> <dimen name="dp_50">50dp</dimen> <dimen name="dp_54">54dp</dimen> <dimen name="dp_60">60dp</dimen> <dimen name="dp_80">80dp</dimen> <dimen name="dp_90">90dp</dimen> <dimen name="dp_100">100dp</dimen> <dimen name="dp_110">110dp</dimen> <dimen name="dp_168">168dp</dimen> <dimen name="dp_180">180dp</dimen> <dimen name="dp_200">200dp</dimen> <dimen name="dp_230">230dp</dimen> <dimen name="dp_240">240dp</dimen> <dimen name="dp_260">260dp</dimen> <dimen name="dp_280">280dp</dimen> <dimen name="dp_300">300dp</dimen> <!-- sp --> <dimen name="sp_8">8sp</dimen> <dimen name="sp_9">9sp</dimen> <dimen name="sp_10">10sp</dimen> <dimen name="sp_12">12sp</dimen> <dimen name="sp_13">13sp</dimen> <dimen name="sp_14">14sp</dimen> <dimen name="sp_15">15sp</dimen> <dimen name="sp_16">16sp</dimen> <dimen name="sp_17">17sp</dimen> <dimen name="sp_18">18sp</dimen> <dimen name="sp_20">20sp</dimen> <dimen name="sp_22">22sp</dimen> <dimen name="sp_24">24sp</dimen> <dimen name="sp_40">40sp</dimen> <dimen name="sp_50">50sp</dimen> <!--BottomNavigationView 的选中没有选中的字体大小--> <dimen name="design_bottom_navigation_active_text_size">@dimen/sp_13</dimen> <dimen name="design_bottom_navigation_text_size">@dimen/sp_12</dimen> </resources>
{ "pile_set_name": "Github" }
>* 原文链接 : [Vectors For All (slight return)](https://blog.stylingandroid.com/vectors-for-all-slight-return/) * 原文作者 : [stylingandroid](https://blog.stylingandroid.com) * 译文出自 : [掘金翻译计划](https://github.com/xitu/gold-miner) * 译者 : [huanglizhuo](https://github.com/huanglizhuo) * 校对者: [circlelove](https://github.com/circlelove) , [edvardHua](https://github.com/edvardHua) # Vector For All (slight return) 大多数 Styling Android 的读者都知道我特别喜欢 _VectorDrawable_ 和 _AnimatedVectorDrawable_。 然而(在我写这篇文章时)我们仍然在期待 _VectorDrawableCompat_ 发布,现在我们现在只能在 API 21 (Lollipop) 以及更高的版本上使用。 然而,Android Studio 添加了一些向后兼容的构建工具,这样我们就能在 Lolipop 之前的版本中使用 _VectorDrawable_ 。这篇文章中会讲它是怎么工作的。 [![svg_logo2](https://i0.wp.com/blog.stylingandroid.com/wp-content/uploads/2015/12/svg_logo2.png?w=300%20300w,%20https://i0.wp.com/blog.stylingandroid.com/wp-content/uploads/2015/12/svg_logo2.png?resize=150%2C150%20150w)](https://i0.wp.com/blog.stylingandroid.com/wp-content/uploads/2015/12/svg_logo2.png?ssl=1) 在[之前的文章](https://blog.stylingandroid.com/vectors-for-all-almost/) 中我们知道 _VectorDrawable_ 的支持是在 Android Studio 1.4 时添加的,并且发现他缺少一些关键部分区域。首先 SVG 导入工具并不能很好的导入 SVG 素材;其次,为 API21 之前设备准备的自动将 SVG 转为 PNG 的工具会导致我们的图片错位。 随着 Android Studio 2.0 预览版的到来(写这篇文章的时候谷歌刚好开放了下载链接),我们再回头来看看这个工具是否有了改进。 和以前一样,我们将使用官方 SVG logo 作为我们的基准,因为它用了 SVG 很多方面来避免渐变(事实上因为性能问题而获得支持不太可能。) 如果我们通过 `New|Vector Asset|Local SVG File` 引入这个 logo (可以在 [SVG 论坛](http://www.w3.org/Icons/SVG/svg-logo-v.svg) 找到),在引入时不会有解析错误,但引入的东西却并不正确: [![](http://ww3.sinaimg.cn/large/a490147fgw1f3qdvqii2ej208c08c745.jpg)](https://i0.wp.com/blog.stylingandroid.com/wp-content/uploads/2015/12/svg_logo3.png?ssl=1) 因为一个未支持的 SVG 特性导致这个问题,那就是本地 IRI 引用未支持。本地 IRI 应用允许特定的形状定义一次,然后在文档中多次使用,不论是笔画,填充,或是转换。官方的 SVG logo 定义了一个哑铃型的形状(一条线两端是圆)并用黑色和黄色填充,加上大量旋转形成像花一样的 SVG logo。类似的字母 ‘S’,‘V’,& ‘G’ 也是用同样的方法定义,导致也没有渲染出来。 退一步来讲,手动编辑 SVG 源文件然后将本地的 IRI 引用替换成形状定义并不是很难,但却是一个繁重的工作。 为了完整性我也尝试用 [Juraj Novák’s 在线转换工具](http://inloop.github.io/svg2android/), 做过转换,估计不会有更好的了-因为有本地 IRI 引用: [![](http://ww3.sinaimg.cn/large/a490147fgw1f3qdwanyr0j208c08ca9z.jpg)](https://i1.wp.com/blog.stylingandroid.com/wp-content/uploads/2015/12/svg_logo4.png?ssl=1) 因此导入和转换 SVG 资料作为 VectorDrawable 还是有问题的。但公平来讲比上次我尝试的时候已经有很大的进步了。上次,我只得到了一堆没有意义的错误信息并不能帮助我定位问题。我猜对于不依赖本地 IRI 引用的 SVG 材料会有很大的概率成功-也就是说确实有提升。 那么把注意力放在工具链的另一部分:在编译时期将 _VectorDrawable_ 生成 PNG 文件。重述一下:如果你将 minSDKVersion 设为 21 以下,这将是构建工具的一部分,VectorDrawable 会自动生成对应的PNG 文件。当你的 APK 运行在 API 21 或者之后的设备上将会使用 VectorDrawable,在之前的设备上将会使用对应的 PNG 文件。换句话说,你只需要添加 VectorDrawable 文件编译工具会需要的时候自动帮你转换。 之前当我尝试这个的时候,我发现 _VectorDrawable_ 中的 `<group></group>` 元素会被忽略,因此很多应用在 group 级的转译也会被忽略,最后 PNG 图片不会被正确渲染。 我现在可以激动的宣布这个问题已经被解决了,前面那张图经过我手工转换(去除本地 IRI 引用)之后可以完美的呈现出来了(这是我真实编译后的 PNG ) [![](http://ww1.sinaimg.cn/large/a490147fgw1f3qdwqyc6nj208c08caaj.jpg)](https://i0.wp.com/blog.stylingandroid.com/wp-content/uploads/2015/12/svg_logo2.png?ssl=1) 不得不说我在写上一篇关于众多问题文章的时候相当失望,当时这些问题折腾了很久才勉强得出这个工具不能真正的用在工程当中。现在这些问题很多都已经解决了,而且很多工具我可以用在实际的工程当中。但是还存在很多导入和转换的问题,但总会有像 SVG 格式这样的问题会出现 - 没有两个 SVG 作者(不管是人还是软件)会用同一种方式做事情。但是如果这个工具以这种速度优化和完善的话或许能解决这些问题,但是谁又知道呢? 这篇文章并没有真正写代码,但前一篇的代码可以在 [这](https://github.com/StylingAndroid/Vectors4All/tree/master) 找到。
{ "pile_set_name": "Github" }
2008-12-05 Antti S. Lankila <[email protected]> * Sync against V27 patch version. Filter updates described below. * Reduce Q maximum to 2.2 or so. This may still be slightly too much, but it's hard to say exactly... * Arrange for about 3 dB boost of lowpass output that is independent of state variable mixing or other feedback. This seems to produce the right kind of sounds for songs like AMJ's Blasphemy. * Assume that bp is slightly louder than bp (= more distorted). This seems to help against very large number of songs which sport lead sounds and effects distorted in a smooth, bassy way. * Parameter tuneup. 2008-10-31 Antti S. Lankila <[email protected]> * Sync against V25 patch version. Filter updates described below. * Tweak filter algorithm to do some state variable mixing in the 6581 code path. This corresponds with assumed output impedance of the SID "amplifiers", and is separate effect to the output strip backmixing. * Retire the V24 attempt of dynamically adjusting BP distortion threshold. It doesn't really seem to work. * Increase Q value maximum to 2.5. This may be too much, but it sounds fine to me. * JT's Star Ball was very distorted when played by V24. This related to the hardclipping I had assumed to occur in the filter output amp, but maybe that theory is incorrect. I now only add distortion to the unfiltered voice path, but I'm not happy about it. 2008-08-29 Antti S. Lankila <[email protected]> * Optimized resampling to be about 2x faster through using aliasing to increase passband width and hence reduce FIR length. * Fixed some valgrind warnings. * Added nuke_denormals() method to periodically flush these to zero, as this can only be done for SSE registers by the FPU and we can't use any in order to support CPUs older than P3. * Marco, Hannu and me developed a runtime switching system that detects SSE from cpuinfo and calls some SSE routines when they are compiled in and the CPU can support them. We lost only very little performance, but gained compatibility to very, very old hardware. * The old code for ST_lockup proved unnecessary, so it is now removed. 2008-08-21 Antti S. Lankila <[email protected]> * Fixed a bug where nonlinearity setting appeared to get lost, and kenchis discovered further bugs in it. Oh well. * I removed a lot of code associated with the lower quality modes of ReSID, and only left the 1 MHz clock routines. Analysis shows that the filter code is a major culprit, but the digital side emulation is not completely cheap, either. I already added some small hacks to optimize it, and I now think about reinjecting pieces of those clocking modes that run the analog parts with reduced accuracy. * I defined type4 filters based on equation of straight line. These are characterized by parameters k and b, and the equation is freq = k * fc. Strictly speaking, straight line is not 100 % accurate, and a 2nd degree component would help, but based on measurements against two of Trurl's 8580s, the maximum error introduced using linear approximation is mere 3 %. 2008-08-10 Antti S. Lankila <[email protected]> * I ripped off Type1 definitions from the filter, and the spline.h and PointPlotter were unnecessary and so removed. * I also added a bit of hardclipping in the output that seems to be required to get Fred Gray's Break Thru. This might not occur so strongly on all chips, so it should probably be added as a proper tunable. For now, I just settled for a slight effect to collect feedback. 2008-07-15 Antti S. Lankila <[email protected]> * This release is a bit slower than usual. The culprit is the changes in voice.h where a new kinked-dac style calculation is used to simulate the nonlinear shape of the waveform outputs. The cost of the new calculation varies by song as I was lazy and only cached the result of previous calculation, so speed depends on the pitch of the waveforms and the precise waveform chosen. * exp() is back, but this time it is implemented as an integer calculation according to Schraudolph's paper "A Fast, Compact Approximation of the Exponential Function". Using near-proper exp() simplified the distortion algorithm. I think it all sounds much better now. * A new effect where I mix bp-hp and lp-bp together by their difference to simulate a small resistor between them appears to improve SidRiders and several other songs, largerly eliminating some types of hard distortion sounds that do not occur on the chip. It also helped Mechanicus. I am trying to understand where this term comes from... 2008-07-09 Antti S. Lankila <[email protected]> * I now have somewhat less arbitrary values for the distortion tunables. They are now related to the relative signal levels in the simulation. I'm still sorting out the particulars of the values I ended up with ("why 128 instead of 256"). 2008-03-02 Antti S. Lankila <[email protected]> * Exposed the filter at sid.cc to callers through get_filter() method, and fixed a few types. 2008-02-19 Antti S. Lankila <[email protected]> * For some reason ReSID code adjusted the external filter frequency based on calculated passband, while in the real C64 the filter is fixed to about 16 kHz. 2008-02-06 Antti S. Lankila <[email protected]> * I got interested to improve ReSID after chatting with Kevtris. He is aiming to replicate the filter using analog hardware. He has the EE experience that I have sorely lacked and made an infinitely valuable contribution by telling me exactly how the distortion works. 2004-06-11 Dag Lem <[email protected]> * Version 0.16 released. (From this point forwards, read ../resid/ChangeLog.)
{ "pile_set_name": "Github" }
/* * linux/arch/alpha/kernel/core_mcpcia.c * * Based on code written by David A Rusling ([email protected]). * * Code common to all MCbus-PCI Adaptor core logic chipsets */ #define __EXTERN_INLINE inline #include <asm/io.h> #include <asm/core_mcpcia.h> #undef __EXTERN_INLINE #include <linux/types.h> #include <linux/pci.h> #include <linux/sched.h> #include <linux/init.h> #include <linux/delay.h> #include <asm/ptrace.h> #include "proto.h" #include "pci_impl.h" /* * NOTE: Herein lie back-to-back mb instructions. They are magic. * One plausible explanation is that the i/o controller does not properly * handle the system transaction. Another involves timing. Ho hum. */ /* * BIOS32-style PCI interface: */ #define DEBUG_CFG 0 #if DEBUG_CFG # define DBG_CFG(args) printk args #else # define DBG_CFG(args) #endif /* * Given a bus, device, and function number, compute resulting * configuration space address and setup the MCPCIA_HAXR2 register * accordingly. It is therefore not safe to have concurrent * invocations to configuration space access routines, but there * really shouldn't be any need for this. * * Type 0: * * 3 3|3 3 2 2|2 2 2 2|2 2 2 2|1 1 1 1|1 1 1 1|1 1 * 3 2|1 0 9 8|7 6 5 4|3 2 1 0|9 8 7 6|5 4 3 2|1 0 9 8|7 6 5 4|3 2 1 0 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | | |D|D|D|D|D|D|D|D|D|D|D|D|D|D|D|D|D|D|D|D|D|F|F|F|R|R|R|R|R|R|0|0| * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * 31:11 Device select bit. * 10:8 Function number * 7:2 Register number * * Type 1: * * 3 3|3 3 2 2|2 2 2 2|2 2 2 2|1 1 1 1|1 1 1 1|1 1 * 3 2|1 0 9 8|7 6 5 4|3 2 1 0|9 8 7 6|5 4 3 2|1 0 9 8|7 6 5 4|3 2 1 0 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | | | | | | | | | | |B|B|B|B|B|B|B|B|D|D|D|D|D|F|F|F|R|R|R|R|R|R|0|1| * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * 31:24 reserved * 23:16 bus number (8 bits = 128 possible buses) * 15:11 Device number (5 bits) * 10:8 function number * 7:2 register number * * Notes: * The function number selects which function of a multi-function device * (e.g., SCSI and Ethernet). * * The register selects a DWORD (32 bit) register offset. Hence it * doesn't get shifted by 2 bits as we want to "drop" the bottom two * bits. */ static unsigned int conf_read(unsigned long addr, unsigned char type1, struct pci_controller *hose) { unsigned long flags; unsigned long mid = MCPCIA_HOSE2MID(hose->index); unsigned int stat0, value, cpu; cpu = smp_processor_id(); local_irq_save(flags); DBG_CFG(("conf_read(addr=0x%lx, type1=%d, hose=%d)\n", addr, type1, mid)); /* Reset status register to avoid losing errors. */ stat0 = *(vuip)MCPCIA_CAP_ERR(mid); *(vuip)MCPCIA_CAP_ERR(mid) = stat0; mb(); *(vuip)MCPCIA_CAP_ERR(mid); DBG_CFG(("conf_read: MCPCIA_CAP_ERR(%d) was 0x%x\n", mid, stat0)); mb(); draina(); mcheck_expected(cpu) = 1; mcheck_taken(cpu) = 0; mcheck_extra(cpu) = mid; mb(); /* Access configuration space. */ value = *((vuip)addr); mb(); mb(); /* magic */ if (mcheck_taken(cpu)) { mcheck_taken(cpu) = 0; value = 0xffffffffU; mb(); } mcheck_expected(cpu) = 0; mb(); DBG_CFG(("conf_read(): finished\n")); local_irq_restore(flags); return value; } static void conf_write(unsigned long addr, unsigned int value, unsigned char type1, struct pci_controller *hose) { unsigned long flags; unsigned long mid = MCPCIA_HOSE2MID(hose->index); unsigned int stat0, cpu; cpu = smp_processor_id(); local_irq_save(flags); /* avoid getting hit by machine check */ /* Reset status register to avoid losing errors. */ stat0 = *(vuip)MCPCIA_CAP_ERR(mid); *(vuip)MCPCIA_CAP_ERR(mid) = stat0; mb(); *(vuip)MCPCIA_CAP_ERR(mid); DBG_CFG(("conf_write: MCPCIA CAP_ERR(%d) was 0x%x\n", mid, stat0)); draina(); mcheck_expected(cpu) = 1; mcheck_extra(cpu) = mid; mb(); /* Access configuration space. */ *((vuip)addr) = value; mb(); mb(); /* magic */ *(vuip)MCPCIA_CAP_ERR(mid); /* read to force the write */ mcheck_expected(cpu) = 0; mb(); DBG_CFG(("conf_write(): finished\n")); local_irq_restore(flags); } static int mk_conf_addr(struct pci_bus *pbus, unsigned int devfn, int where, struct pci_controller *hose, unsigned long *pci_addr, unsigned char *type1) { u8 bus = pbus->number; unsigned long addr; DBG_CFG(("mk_conf_addr(bus=%d,devfn=0x%x,hose=%d,where=0x%x," " pci_addr=0x%p, type1=0x%p)\n", bus, devfn, hose->index, where, pci_addr, type1)); /* Type 1 configuration cycle for *ALL* busses. */ *type1 = 1; if (!pbus->parent) /* No parent means peer PCI bus. */ bus = 0; addr = (bus << 16) | (devfn << 8) | (where); addr <<= 5; /* swizzle for SPARSE */ addr |= hose->config_space_base; *pci_addr = addr; DBG_CFG(("mk_conf_addr: returning pci_addr 0x%lx\n", addr)); return 0; } static int mcpcia_read_config(struct pci_bus *bus, unsigned int devfn, int where, int size, u32 *value) { struct pci_controller *hose = bus->sysdata; unsigned long addr, w; unsigned char type1; if (mk_conf_addr(bus, devfn, where, hose, &addr, &type1)) return PCIBIOS_DEVICE_NOT_FOUND; addr |= (size - 1) * 8; w = conf_read(addr, type1, hose); switch (size) { case 1: *value = __kernel_extbl(w, where & 3); break; case 2: *value = __kernel_extwl(w, where & 3); break; case 4: *value = w; break; } return PCIBIOS_SUCCESSFUL; } static int mcpcia_write_config(struct pci_bus *bus, unsigned int devfn, int where, int size, u32 value) { struct pci_controller *hose = bus->sysdata; unsigned long addr; unsigned char type1; if (mk_conf_addr(bus, devfn, where, hose, &addr, &type1)) return PCIBIOS_DEVICE_NOT_FOUND; addr |= (size - 1) * 8; value = __kernel_insql(value, where & 3); conf_write(addr, value, type1, hose); return PCIBIOS_SUCCESSFUL; } struct pci_ops mcpcia_pci_ops = { .read = mcpcia_read_config, .write = mcpcia_write_config, }; void mcpcia_pci_tbi(struct pci_controller *hose, dma_addr_t start, dma_addr_t end) { wmb(); *(vuip)MCPCIA_SG_TBIA(MCPCIA_HOSE2MID(hose->index)) = 0; mb(); } static int __init mcpcia_probe_hose(int h) { int cpu = smp_processor_id(); int mid = MCPCIA_HOSE2MID(h); unsigned int pci_rev; /* Gotta be REAL careful. If hose is absent, we get an mcheck. */ mb(); mb(); draina(); wrmces(7); mcheck_expected(cpu) = 2; /* indicates probing */ mcheck_taken(cpu) = 0; mcheck_extra(cpu) = mid; mb(); /* Access the bus revision word. */ pci_rev = *(vuip)MCPCIA_REV(mid); mb(); mb(); /* magic */ if (mcheck_taken(cpu)) { mcheck_taken(cpu) = 0; pci_rev = 0xffffffff; mb(); } mcheck_expected(cpu) = 0; mb(); return (pci_rev >> 16) == PCI_CLASS_BRIDGE_HOST; } static void __init mcpcia_new_hose(int h) { struct pci_controller *hose; struct resource *io, *mem, *hae_mem; int mid = MCPCIA_HOSE2MID(h); hose = alloc_pci_controller(); if (h == 0) pci_isa_hose = hose; io = alloc_resource(); mem = alloc_resource(); hae_mem = alloc_resource(); hose->io_space = io; hose->mem_space = hae_mem; hose->sparse_mem_base = MCPCIA_SPARSE(mid) - IDENT_ADDR; hose->dense_mem_base = MCPCIA_DENSE(mid) - IDENT_ADDR; hose->sparse_io_base = MCPCIA_IO(mid) - IDENT_ADDR; hose->dense_io_base = 0; hose->config_space_base = MCPCIA_CONF(mid); hose->index = h; io->start = MCPCIA_IO(mid) - MCPCIA_IO_BIAS; io->end = io->start + 0xffff; io->name = pci_io_names[h]; io->flags = IORESOURCE_IO; mem->start = MCPCIA_DENSE(mid) - MCPCIA_MEM_BIAS; mem->end = mem->start + 0xffffffff; mem->name = pci_mem_names[h]; mem->flags = IORESOURCE_MEM; hae_mem->start = mem->start; hae_mem->end = mem->start + MCPCIA_MEM_MASK; hae_mem->name = pci_hae0_name; hae_mem->flags = IORESOURCE_MEM; if (request_resource(&ioport_resource, io) < 0) printk(KERN_ERR "Failed to request IO on hose %d\n", h); if (request_resource(&iomem_resource, mem) < 0) printk(KERN_ERR "Failed to request MEM on hose %d\n", h); if (request_resource(mem, hae_mem) < 0) printk(KERN_ERR "Failed to request HAE_MEM on hose %d\n", h); } static void mcpcia_pci_clr_err(int mid) { *(vuip)MCPCIA_CAP_ERR(mid); *(vuip)MCPCIA_CAP_ERR(mid) = 0xffffffff; /* Clear them all. */ mb(); *(vuip)MCPCIA_CAP_ERR(mid); /* Re-read for force write. */ } static void __init mcpcia_startup_hose(struct pci_controller *hose) { int mid = MCPCIA_HOSE2MID(hose->index); unsigned int tmp; mcpcia_pci_clr_err(mid); /* * Set up error reporting. */ tmp = *(vuip)MCPCIA_CAP_ERR(mid); tmp |= 0x0006; /* master/target abort */ *(vuip)MCPCIA_CAP_ERR(mid) = tmp; mb(); tmp = *(vuip)MCPCIA_CAP_ERR(mid); /* * Set up the PCI->physical memory translation windows. * * Window 0 is scatter-gather 8MB at 8MB (for isa) * Window 1 is scatter-gather (up to) 1GB at 1GB (for pci) * Window 2 is direct access 2GB at 2GB */ hose->sg_isa = iommu_arena_new(hose, 0x00800000, 0x00800000, 0); hose->sg_pci = iommu_arena_new(hose, 0x40000000, size_for_memory(0x40000000), 0); __direct_map_base = 0x80000000; __direct_map_size = 0x80000000; *(vuip)MCPCIA_W0_BASE(mid) = hose->sg_isa->dma_base | 3; *(vuip)MCPCIA_W0_MASK(mid) = (hose->sg_isa->size - 1) & 0xfff00000; *(vuip)MCPCIA_T0_BASE(mid) = virt_to_phys(hose->sg_isa->ptes) >> 8; *(vuip)MCPCIA_W1_BASE(mid) = hose->sg_pci->dma_base | 3; *(vuip)MCPCIA_W1_MASK(mid) = (hose->sg_pci->size - 1) & 0xfff00000; *(vuip)MCPCIA_T1_BASE(mid) = virt_to_phys(hose->sg_pci->ptes) >> 8; *(vuip)MCPCIA_W2_BASE(mid) = __direct_map_base | 1; *(vuip)MCPCIA_W2_MASK(mid) = (__direct_map_size - 1) & 0xfff00000; *(vuip)MCPCIA_T2_BASE(mid) = 0; *(vuip)MCPCIA_W3_BASE(mid) = 0x0; mcpcia_pci_tbi(hose, 0, -1); *(vuip)MCPCIA_HBASE(mid) = 0x0; mb(); *(vuip)MCPCIA_HAE_MEM(mid) = 0U; mb(); *(vuip)MCPCIA_HAE_MEM(mid); /* read it back. */ *(vuip)MCPCIA_HAE_IO(mid) = 0; mb(); *(vuip)MCPCIA_HAE_IO(mid); /* read it back. */ } void __init mcpcia_init_arch(void) { /* With multiple PCI busses, we play with I/O as physical addrs. */ ioport_resource.end = ~0UL; /* Allocate hose 0. That's the one that all the ISA junk hangs off of, from which we'll be registering stuff here in a bit. Other hose detection is done in mcpcia_init_hoses, which is called from init_IRQ. */ mcpcia_new_hose(0); } /* This is called from init_IRQ, since we cannot take interrupts before then. Which means we cannot do this in init_arch. */ void __init mcpcia_init_hoses(void) { struct pci_controller *hose; int hose_count; int h; /* First, find how many hoses we have. */ hose_count = 0; for (h = 0; h < MCPCIA_MAX_HOSES; ++h) { if (mcpcia_probe_hose(h)) { if (h != 0) mcpcia_new_hose(h); hose_count++; } } printk("mcpcia_init_hoses: found %d hoses\n", hose_count); /* Now do init for each hose. */ for (hose = hose_head; hose; hose = hose->next) mcpcia_startup_hose(hose); } static void mcpcia_print_uncorrectable(struct el_MCPCIA_uncorrected_frame_mcheck *logout) { struct el_common_EV5_uncorrectable_mcheck *frame; int i; frame = &logout->procdata; /* Print PAL fields */ for (i = 0; i < 24; i += 2) { printk(" paltmp[%d-%d] = %16lx %16lx\n", i, i+1, frame->paltemp[i], frame->paltemp[i+1]); } for (i = 0; i < 8; i += 2) { printk(" shadow[%d-%d] = %16lx %16lx\n", i, i+1, frame->shadow[i], frame->shadow[i+1]); } printk(" Addr of excepting instruction = %16lx\n", frame->exc_addr); printk(" Summary of arithmetic traps = %16lx\n", frame->exc_sum); printk(" Exception mask = %16lx\n", frame->exc_mask); printk(" Base address for PALcode = %16lx\n", frame->pal_base); printk(" Interrupt Status Reg = %16lx\n", frame->isr); printk(" CURRENT SETUP OF EV5 IBOX = %16lx\n", frame->icsr); printk(" I-CACHE Reg %s parity error = %16lx\n", (frame->ic_perr_stat & 0x800L) ? "Data" : "Tag", frame->ic_perr_stat); printk(" D-CACHE error Reg = %16lx\n", frame->dc_perr_stat); if (frame->dc_perr_stat & 0x2) { switch (frame->dc_perr_stat & 0x03c) { case 8: printk(" Data error in bank 1\n"); break; case 4: printk(" Data error in bank 0\n"); break; case 20: printk(" Tag error in bank 1\n"); break; case 10: printk(" Tag error in bank 0\n"); break; } } printk(" Effective VA = %16lx\n", frame->va); printk(" Reason for D-stream = %16lx\n", frame->mm_stat); printk(" EV5 SCache address = %16lx\n", frame->sc_addr); printk(" EV5 SCache TAG/Data parity = %16lx\n", frame->sc_stat); printk(" EV5 BC_TAG_ADDR = %16lx\n", frame->bc_tag_addr); printk(" EV5 EI_ADDR: Phys addr of Xfer = %16lx\n", frame->ei_addr); printk(" Fill Syndrome = %16lx\n", frame->fill_syndrome); printk(" EI_STAT reg = %16lx\n", frame->ei_stat); printk(" LD_LOCK = %16lx\n", frame->ld_lock); } static void mcpcia_print_system_area(unsigned long la_ptr) { struct el_common *frame; struct pci_controller *hose; struct IOD_subpacket { unsigned long base; unsigned int whoami; unsigned int rsvd1; unsigned int pci_rev; unsigned int cap_ctrl; unsigned int hae_mem; unsigned int hae_io; unsigned int int_ctl; unsigned int int_reg; unsigned int int_mask0; unsigned int int_mask1; unsigned int mc_err0; unsigned int mc_err1; unsigned int cap_err; unsigned int rsvd2; unsigned int pci_err1; unsigned int mdpa_stat; unsigned int mdpa_syn; unsigned int mdpb_stat; unsigned int mdpb_syn; unsigned int rsvd3; unsigned int rsvd4; unsigned int rsvd5; } *iodpp; frame = (struct el_common *)la_ptr; iodpp = (struct IOD_subpacket *) (la_ptr + frame->sys_offset); for (hose = hose_head; hose; hose = hose->next, iodpp++) { printk("IOD %d Register Subpacket - Bridge Base Address %16lx\n", hose->index, iodpp->base); printk(" WHOAMI = %8x\n", iodpp->whoami); printk(" PCI_REV = %8x\n", iodpp->pci_rev); printk(" CAP_CTRL = %8x\n", iodpp->cap_ctrl); printk(" HAE_MEM = %8x\n", iodpp->hae_mem); printk(" HAE_IO = %8x\n", iodpp->hae_io); printk(" INT_CTL = %8x\n", iodpp->int_ctl); printk(" INT_REG = %8x\n", iodpp->int_reg); printk(" INT_MASK0 = %8x\n", iodpp->int_mask0); printk(" INT_MASK1 = %8x\n", iodpp->int_mask1); printk(" MC_ERR0 = %8x\n", iodpp->mc_err0); printk(" MC_ERR1 = %8x\n", iodpp->mc_err1); printk(" CAP_ERR = %8x\n", iodpp->cap_err); printk(" PCI_ERR1 = %8x\n", iodpp->pci_err1); printk(" MDPA_STAT = %8x\n", iodpp->mdpa_stat); printk(" MDPA_SYN = %8x\n", iodpp->mdpa_syn); printk(" MDPB_STAT = %8x\n", iodpp->mdpb_stat); printk(" MDPB_SYN = %8x\n", iodpp->mdpb_syn); } } void mcpcia_machine_check(unsigned long vector, unsigned long la_ptr) { struct el_MCPCIA_uncorrected_frame_mcheck *mchk_logout; unsigned int cpu = smp_processor_id(); int expected; mchk_logout = (struct el_MCPCIA_uncorrected_frame_mcheck *)la_ptr; expected = mcheck_expected(cpu); mb(); mb(); /* magic */ draina(); switch (expected) { case 0: { /* FIXME: how do we figure out which hose the error was on? */ struct pci_controller *hose; for (hose = hose_head; hose; hose = hose->next) mcpcia_pci_clr_err(MCPCIA_HOSE2MID(hose->index)); break; } case 1: mcpcia_pci_clr_err(mcheck_extra(cpu)); break; default: /* Otherwise, we're being called from mcpcia_probe_hose and there's no hose clear an error from. */ break; } wrmces(0x7); mb(); process_mcheck_info(vector, la_ptr, "MCPCIA", expected != 0); if (!expected && vector != 0x620 && vector != 0x630) { mcpcia_print_uncorrectable(mchk_logout); mcpcia_print_system_area(la_ptr); } }
{ "pile_set_name": "Github" }
(bug-reference-github :fetcher github :repo "arnested/bug-reference-github")
{ "pile_set_name": "Github" }
/* * Copyright 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "GLESv2Decoder.h" #include <EGL/egl.h> #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> static inline void* SafePointerFromUInt(GLuint value) { return (void*)(uintptr_t)value; } GLESv2Decoder::GLESv2Decoder() { m_contextData = NULL; m_GL2library = NULL; } GLESv2Decoder::~GLESv2Decoder() { delete m_GL2library; } void *GLESv2Decoder::s_getProc(const char *name, void *userData) { GLESv2Decoder *ctx = (GLESv2Decoder *) userData; if (ctx == NULL || ctx->m_GL2library == NULL) { return NULL; } void *func = NULL; #ifdef USE_EGL_GETPROCADDRESS func = (void *) eglGetProcAddress(name); #endif if (func == NULL) { func = (void *) ctx->m_GL2library->findSymbol(name); } return func; } int GLESv2Decoder::initGL(get_proc_func_t getProcFunc, void *getProcFuncData) { this->initDispatchByName(getProcFunc, getProcFuncData); glGetCompressedTextureFormats = s_glGetCompressedTextureFormats; glVertexAttribPointerData = s_glVertexAttribPointerData; glVertexAttribPointerOffset = s_glVertexAttribPointerOffset; glDrawElementsOffset = s_glDrawElementsOffset; glDrawElementsData = s_glDrawElementsData; glShaderString = s_glShaderString; glFinishRoundTrip = s_glFinishRoundTrip; return 0; } int GLESv2Decoder::s_glFinishRoundTrip(void *self) { GLESv2Decoder *ctx = (GLESv2Decoder *)self; ctx->glFinish(); return 0; } void GLESv2Decoder::s_glGetCompressedTextureFormats(void *self, int count, GLint *formats) { GLESv2Decoder *ctx = (GLESv2Decoder *) self; int nFormats; ctx->glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &nFormats); if (nFormats > count) { fprintf(stderr, "%s: GetCompressedTextureFormats: The requested number of formats does not match the number that is reported by OpenGL\n", __FUNCTION__); } else { ctx->glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, formats); } } void GLESv2Decoder::s_glVertexAttribPointerData(void *self, GLuint indx, GLint size, GLenum type, GLboolean normalized, GLsizei stride, void * data, GLuint datalen) { GLESv2Decoder *ctx = (GLESv2Decoder *) self; if (ctx->m_contextData != NULL) { ctx->m_contextData->storePointerData(indx, data, datalen); // note - the stride of the data is always zero when it comes out of the codec. // See gl2.attrib for the packing function call. ctx->glVertexAttribPointer(indx, size, type, normalized, 0, ctx->m_contextData->pointerData(indx)); } } void GLESv2Decoder::s_glVertexAttribPointerOffset(void *self, GLuint indx, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLuint data) { GLESv2Decoder *ctx = (GLESv2Decoder *) self; ctx->glVertexAttribPointer(indx, size, type, normalized, stride, SafePointerFromUInt(data)); } void GLESv2Decoder::s_glDrawElementsData(void *self, GLenum mode, GLsizei count, GLenum type, void * data, GLuint datalen) { GLESv2Decoder *ctx = (GLESv2Decoder *)self; ctx->glDrawElements(mode, count, type, data); } void GLESv2Decoder::s_glDrawElementsOffset(void *self, GLenum mode, GLsizei count, GLenum type, GLuint offset) { GLESv2Decoder *ctx = (GLESv2Decoder *)self; ctx->glDrawElements(mode, count, type, SafePointerFromUInt(offset)); } void GLESv2Decoder::s_glShaderString(void *self, GLuint shader, const GLchar* string, GLsizei len) { GLESv2Decoder *ctx = (GLESv2Decoder *)self; ctx->glShaderSource(shader, 1, &string, NULL); }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2007, 2008 Apple 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. * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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. */ #import "WebNodeHighlight.h" #import "WebNodeHighlightView.h" #import "WebNSViewExtras.h" #import <WebCore/InspectorController.h> #import <wtf/Assertions.h> #if PLATFORM(IOS) #import "WebFramePrivate.h" #import "WebHTMLView.h" #import "WebView.h" #import <QuartzCore/CALayerPrivate.h> #import <WebCore/WAKWindow.h> #endif using namespace WebCore; #if !PLATFORM(IOS) @interface WebNodeHighlight (FileInternal) - (NSRect)_computeHighlightWindowFrame; - (void)_repositionHighlightWindow; @end #endif #if PLATFORM(IOS) @implementation WebHighlightLayer - (id)initWithHighlightView:(WebNodeHighlightView *)view webView:(WebView *)webView { self = [super init]; if (!self) return nil; _view = view; _webView = webView; return self; } - (void)layoutSublayers { CGFloat documentScale = [[[_webView mainFrame] documentView] scale]; [self setTransform:CATransform3DMakeScale(documentScale, documentScale, 1.0)]; [_view layoutSublayers:self]; } - (id<CAAction>)actionForKey:(NSString *)key { return nil; // Disable all default actions. } @end #endif @implementation WebNodeHighlight - (id)initWithTargetView:(NSView *)targetView inspectorController:(InspectorController*)inspectorController { self = [super init]; if (!self) return nil; _targetView = [targetView retain]; _inspectorController = inspectorController; #if !PLATFORM(IOS) int styleMask = NSBorderlessWindowMask; NSRect contentRect = [NSWindow contentRectForFrameRect:[self _computeHighlightWindowFrame] styleMask:styleMask]; _highlightWindow = [[NSWindow alloc] initWithContentRect:contentRect styleMask:styleMask backing:NSBackingStoreBuffered defer:NO]; [_highlightWindow setBackgroundColor:[NSColor clearColor]]; [_highlightWindow setOpaque:NO]; [_highlightWindow setIgnoresMouseEvents:YES]; [_highlightWindow setReleasedWhenClosed:NO]; _highlightView = [[WebNodeHighlightView alloc] initWithWebNodeHighlight:self]; [_highlightWindow setContentView:_highlightView]; [_highlightView release]; #else ASSERT([_targetView isKindOfClass:[WebView class]]); WebView *webView = (WebView *)targetView; _highlightView = [[WebNodeHighlightView alloc] initWithWebNodeHighlight:self]; _highlightLayer = [[WebHighlightLayer alloc] initWithHighlightView:_highlightView webView:webView]; [_highlightLayer setContentsScale:[[_targetView window] screenScale]]; // HiDPI. [_highlightLayer setCanDrawConcurrently:NO]; #endif return self; } - (void)dealloc { #if !PLATFORM(IOS) ASSERT(!_highlightWindow); #else ASSERT(!_highlightLayer); #endif ASSERT(!_targetView); ASSERT(!_highlightView); [super dealloc]; } - (void)attach { ASSERT(_targetView); ASSERT([_targetView window]); #if !PLATFORM(IOS) ASSERT(_highlightWindow); if (!_highlightWindow || !_targetView || ![_targetView window]) return; [[_targetView window] addChildWindow:_highlightWindow ordered:NSWindowAbove]; // Observe both frame-changed and bounds-changed notifications because either one could leave // the highlight incorrectly positioned with respect to the target view. We need to do this for // the entire superview hierarchy to handle scrolling, bars coming and going, etc. // (without making concrete assumptions about the view hierarchy). NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; for (NSView *v = _targetView; v; v = [v superview]) { [notificationCenter addObserver:self selector:@selector(_repositionHighlightWindow) name:NSViewFrameDidChangeNotification object:v]; [notificationCenter addObserver:self selector:@selector(_repositionHighlightWindow) name:NSViewBoundsDidChangeNotification object:v]; } #else ASSERT(_highlightLayer); WAKWindow *window = [_targetView window]; [[window hostLayer] addSublayer:_highlightLayer]; [self setNeedsDisplay]; #endif if (_delegate && [_delegate respondsToSelector:@selector(didAttachWebNodeHighlight:)]) [_delegate didAttachWebNodeHighlight:self]; } - (id)delegate { return _delegate; } - (void)detach { #if !PLATFORM(IOS) if (!_highlightWindow) { #else if (!_highlightLayer) { #endif ASSERT(!_targetView); return; } if (_delegate && [_delegate respondsToSelector:@selector(willDetachWebNodeHighlight:)]) [_delegate willDetachWebNodeHighlight:self]; #if !PLATFORM(IOS) NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; [notificationCenter removeObserver:self name:NSViewFrameDidChangeNotification object:nil]; [notificationCenter removeObserver:self name:NSViewBoundsDidChangeNotification object:nil]; [[_highlightWindow parentWindow] removeChildWindow:_highlightWindow]; [_highlightWindow release]; _highlightWindow = nil; #else [_highlightLayer removeFromSuperlayer]; [_highlightLayer release]; _highlightLayer = nil; #endif [_targetView release]; _targetView = nil; // We didn't retain _highlightView, but we do need to tell it to forget about us, so it doesn't // try to send our delegate messages after we've been dealloc'ed, e.g. [_highlightView detachFromWebNodeHighlight]; #if PLATFORM(IOS) // iOS did retain the highlightView, and we should release it here. [_highlightView release]; #endif _highlightView = nil; } - (WebNodeHighlightView *)highlightView { return _highlightView; } - (void)setDelegate:(id)delegate { // The delegate is not retained, as usual in Cocoa. _delegate = delegate; } #if !PLATFORM(IOS) - (void)setNeedsUpdateInTargetViewRect:(NSRect)rect { ASSERT(_targetView); [[_targetView window] disableScreenUpdatesUntilFlush]; // Mark the whole highlight view as needing display since we don't know what areas // need updated, since the highlight can be larger than the element to show margins. [_highlightView setNeedsDisplay:YES]; // Redraw highlight view immediately so it updates in sync with the target view. // This is especially visible when resizing the window, scrolling or with DHTML. [_highlightView displayIfNeeded]; } #else - (void)setNeedsDisplay { [_highlightLayer setNeedsLayout]; [_highlightLayer setNeedsDisplay]; [_highlightLayer displayIfNeeded]; } #endif - (NSView *)targetView { return _targetView; } - (InspectorController*)inspectorController { return _inspectorController; } @end #if !PLATFORM(IOS) @implementation WebNodeHighlight (FileInternal) - (NSRect)_computeHighlightWindowFrame { ASSERT(_targetView); ASSERT([_targetView window]); NSRect highlightWindowFrame = [_targetView convertRect:[_targetView visibleRect] toView:nil]; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" highlightWindowFrame.origin = [[_targetView window] convertBaseToScreen:highlightWindowFrame.origin]; #pragma clang diagnostic pop return highlightWindowFrame; } - (void)_repositionHighlightWindow { // This assertion fires in cases where a new tab is created while the highlight // is showing (<http://bugs.webkit.org/show_bug.cgi?id=14254>) ASSERT([_targetView window]); // Until that bug is fixed, bail out to avoid worse problems where the highlight // moves to a nonsense location. if (![_targetView window]) return; // Disable screen updates so the highlight moves in sync with the view. [[_targetView window] disableScreenUpdatesUntilFlush]; [_highlightWindow setFrame:[self _computeHighlightWindowFrame] display:YES]; } @end #endif
{ "pile_set_name": "Github" }
<http://www.w3.org/2013/TurtleTests/s> <http://www.w3.org/2013/TurtleTests/p> "a\U00000020b" .
{ "pile_set_name": "Github" }
<!--|This file generated by command(leetcode description); DO NOT EDIT. |--> <!--+----------------------------------------------------------------------+--> <!--|@author openset <[email protected]> |--> <!--|@link https://github.com/openset |--> <!--|@home https://github.com/openset/leetcode |--> <!--+----------------------------------------------------------------------+--> [< Previous](../min-stack "Min Stack")                  [Next >](../read-n-characters-given-read4 "Read N Characters Given Read4") ## [156. Binary Tree Upside Down (Medium)](https://leetcode.com/problems/binary-tree-upside-down "上下翻转二叉树") <p>Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root.</p> <p><strong>Example:</strong></p> <pre> <strong>Input: </strong>[1,2,3,4,5] 1 / \ 2 3 / \ 4 5 <strong>Output:</strong> return the root of the binary tree [4,5,2,#,#,3,1] 4 / \ 5 2 / \ 3 1 </pre> <p><strong>Clarification:</strong></p> <p>Confused what <code>[4,5,2,#,#,3,1<font face="monospace">]</font></code>&nbsp;means? Read more below on how binary tree is serialized on OJ.</p> <p>The serialization of a binary tree follows a level order traversal, where &#39;#&#39; signifies a path terminator where no node exists below.</p> <p>Here&#39;s an example:</p> <pre> 1 / \ 2 3 / 4 \ 5 </pre> <p>The above binary tree is serialized as <code>[1,2,3,#,#,4,#,#,5]</code>.</p> ### Related Topics [[Tree](../../tag/tree/README.md)] ### Similar Questions 1. [Reverse Linked List](../reverse-linked-list) (Easy)
{ "pile_set_name": "Github" }
# Copyright (C) 2017 FireEye, Inc. All Rights Reserved. import os import yaml import pytest import viv_utils import floss.main as floss_main import floss.identification_manager as im import floss.stackstrings as stackstrings def extract_strings(vw): """ Deobfuscate strings from vivisect workspace """ decoding_functions_candidates = identify_decoding_functions(vw) decoded_strings = floss_main.decode_strings(vw, decoding_functions_candidates, 4) selected_functions = floss_main.select_functions(vw, None) decoded_stackstrings = stackstrings.extract_stackstrings(vw, selected_functions, 4) decoded_strings.extend(decoded_stackstrings) return [ds.s for ds in decoded_strings] def identify_decoding_functions(vw): selected_functions = floss_main.select_functions(vw, None) selected_plugin_names = floss_main.select_plugins(None) selected_plugins = filter(lambda p: str(p) in selected_plugin_names, floss_main.get_all_plugins()) decoding_functions_candidates = im.identify_decoding_functions(vw, selected_plugins, selected_functions) return decoding_functions_candidates def pytest_collect_file(parent, path): if path.basename == "test.yml": return YamlFile(path, parent) class YamlFile(pytest.File): def collect(self): spec = yaml.safe_load(self.fspath.open()) test_dir = os.path.dirname(str(self.fspath)) for platform, archs in spec["Output Files"].items(): for arch, filename in archs.items(): # TODO specify max runtime via command line option MAX_RUNTIME = 30.0 try: runtime_raw = spec["FLOSS running time"] runtime = float(runtime_raw.split(" ")[0]) if runtime > MAX_RUNTIME: # skip this test continue except KeyError: pass except ValueError: pass filepath = os.path.join(test_dir, filename) if os.path.exists(filepath): yield FLOSSTest(self, platform, arch, filename, spec) class FLOSSTestError(Exception): def __init__(self, expected, got): self.expected = expected self.got = got class FLOSSStringsNotExtracted(FLOSSTestError): pass class FLOSSDecodingFunctionNotFound(Exception): pass class FLOSSTest(pytest.Item): def __init__(self, path, platform, arch, filename, spec): name = "{name:s}::{platform:s}::{arch:s}".format( name=spec["Test Name"], platform=platform, arch=arch) super(FLOSSTest, self).__init__(name, path) self.spec = spec self.platform = platform self.arch = arch self.filename = filename def _test_strings(self, test_path): expected_strings = set(self.spec["Decoded strings"]) if not expected_strings: return test_shellcode = self.spec.get("Test shellcode") if test_shellcode: with open(test_path, "rb") as f: shellcode_data = f.read() vw = viv_utils.getShellcodeWorkspace(shellcode_data) # TODO provide arch from test.yml found_strings = set(extract_strings(vw)) else: vw = viv_utils.getWorkspace(test_path) found_strings = set(extract_strings(vw)) if not (expected_strings <= found_strings): raise FLOSSStringsNotExtracted(expected_strings, found_strings) def _test_detection(self, test_path): try: expected_functions = set(self.spec["Decoding routines"][self.platform][self.arch]) except KeyError: expected_functions = set([]) if not expected_functions: return vw = viv_utils.getWorkspace(test_path) fs = map(lambda p: p[0], identify_decoding_functions(vw).get_top_candidate_functions()) found_functions = set(fs) if not (expected_functions <= found_functions): raise FLOSSDecodingFunctionNotFound(expected_functions, found_functions) def runtest(self): xfail = self.spec.get("Xfail", {}) if "all" in xfail: pytest.xfail("unsupported test case (known issue)") if "{0.platform:s}-{0.arch:s}".format(self) in xfail: pytest.xfail("unsupported platform&arch test case (known issue)") spec_path = self.location[0] test_dir = os.path.dirname(spec_path) test_path = os.path.join(test_dir, self.filename) self._test_detection(test_path) self._test_strings(test_path) def reportinfo(self): return self.fspath, 0, "usecase: %s" % self.name def repr_failure(self, excinfo): if isinstance(excinfo.value, FLOSSStringsNotExtracted): expected = excinfo.value.expected got = excinfo.value.got return "\n".join([ "FLOSS extraction failed:", " expected: %s" % str(expected), " got: %s" % str(got), " expected-got: %s" % str(set(expected) - set(got)), " got-expected: %s" % str(set(got) - set(expected)), ])
{ "pile_set_name": "Github" }
********************************************************************** Worktrees ********************************************************************** .. automethod:: pygit2.Repository.add_worktree .. automethod:: pygit2.Repository.list_worktrees .. automethod:: pygit2.Repository.lookup_worktree .. autoclass:: pygit2.Worktree :members:
{ "pile_set_name": "Github" }
[ { "op": "add", "path": "/config/shipUpgrades/maxFuel", "value": 10000 } ]
{ "pile_set_name": "Github" }
/* - p(max(a, b)<=x) + p(min(a, b)<=x) = p(a<=x) + p(b<=x) - p(a<=x)*p(b<=x) = p(max(a, b)<=x) - Solve quadratic to find probabilities - You can prove that if there is a solution (as given guaranteed by the problem) then you can just assign the smaller roots to a and the bigger roots to b - Calculations can be close to 0 and there are precision errors so use sqrt(max(x, 0)) instead of sqrt(x) */ #include <bits/stdc++.h> using namespace std; const int mxN=1e5; int n; double smx[mxN+1], smn[mxN+1], s1, pa[mxN+1], pb[mxN+1]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n; for(int i=0; i<n; ++i) cin >> smx[i+1], smx[i+1]+=smx[i]; cout << fixed << setprecision(9); for(int i=0; i<n; ++i) { cin >> smn[i+1], smn[i+1]+=smn[i]; s1=smx[i+1]+smn[i+1]; pa[i+1]=(s1-sqrt(max(s1*s1-4*smx[i+1], 0.0)))/2; pb[i+1]=(s1+sqrt(max(s1*s1-4*smx[i+1], 0.0)))/2; cout << pa[i+1]-pa[i] << " "; } cout << "\n"; for(int i=0; i<n; ++i) cout << pb[i+1]-pb[i] << " "; }
{ "pile_set_name": "Github" }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { TPromise } from 'vs/base/common/winjs.base'; import * as objects from 'vs/base/common/objects'; import * as arrays from 'vs/base/common/arrays'; import * as strings from 'vs/base/common/strings'; import * as types from 'vs/base/common/types'; import { Registry } from 'vs/platform/registry/common/platform'; import { Action } from 'vs/base/common/actions'; import { Mode, IEntryRunContext, IAutoFocus, IModel, IQuickNavigateConfiguration } from 'vs/base/parts/quickopen/common/quickOpen'; import { QuickOpenEntry, QuickOpenEntryGroup } from 'vs/base/parts/quickopen/browser/quickOpenModel'; import { EditorOptions, EditorInput, IEditorInput } from 'vs/workbench/common/editor'; import { IResourceInput, IEditorOptions } from 'vs/platform/editor/common/editor'; import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen'; import { IConstructorSignature0, IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IEditorService, SIDE_GROUP, ACTIVE_GROUP } from 'vs/workbench/services/editor/common/editorService'; import { CancellationToken } from 'vs/base/common/cancellation'; export const CLOSE_ON_FOCUS_LOST_CONFIG = 'workbench.quickOpen.closeOnFocusLost'; export const PRESERVE_INPUT_CONFIG = 'workbench.quickOpen.preserveInput'; export const SEARCH_EDITOR_HISTORY = 'search.quickOpen.includeHistory'; export interface IWorkbenchQuickOpenConfiguration { workbench: { commandPalette: { history: number; preserveInput: boolean; } }; } export class QuickOpenHandler { /** * A quick open handler returns results for a given input string. The resolved promise * returns an instance of quick open model. It is up to the handler to keep and reuse an * instance of the same model across multiple calls. This helps in situations where the user is * narrowing down a search and the model is just filtering some items out. * * As such, returning the same model instance across multiple searches will yield best * results in terms of performance when many items are shown. */ getResults(searchValue: string, token: CancellationToken): TPromise<IModel<any>> { return Promise.resolve(null); } /** * The ARIA label to apply when this quick open handler is active in quick open. */ getAriaLabel(): string { return null; } /** * Extra CSS class name to add to the quick open widget to do custom styling of entries. */ getClass(): string { return null; } /** * Indicates if the handler can run in the current environment. Return a string if the handler cannot run but has * a good message to show in this case. */ canRun(): boolean | string { return true; } /** * Hints to the outside that this quick open handler typically returns results fast. */ hasShortResponseTime(): boolean { return false; } /** * Indicates if the handler wishes the quick open widget to automatically select the first result entry or an entry * based on a specific prefix match. */ getAutoFocus(searchValue: string, context: { model: IModel<QuickOpenEntry>, quickNavigateConfiguration?: IQuickNavigateConfiguration }): IAutoFocus { return {}; } /** * Indicates to the handler that the quick open widget has been opened. */ onOpen(): void { return; } /** * Indicates to the handler that the quick open widget has been closed. Allows to free up any resources as needed. * The parameter canceled indicates if the quick open widget was closed with an entry being run or not. */ onClose(canceled: boolean): void { return; } /** * Allows to return a label that will be placed to the side of the results from this handler or null if none. */ getGroupLabel(): string { return null; } /** * Allows to return a label that will be used when there are no results found */ getEmptyLabel(searchString: string): string { if (searchString.length > 0) { return nls.localize('noResultsMatching', "No results matching"); } return nls.localize('noResultsFound2', "No results found"); } } export interface QuickOpenHandlerHelpEntry { prefix: string; description: string; needsEditor: boolean; } /** * A lightweight descriptor of a quick open handler. */ export class QuickOpenHandlerDescriptor { prefix: string; description: string; contextKey: string; helpEntries: QuickOpenHandlerHelpEntry[]; instantProgress: boolean; private id: string; private ctor: IConstructorSignature0<QuickOpenHandler>; constructor(ctor: IConstructorSignature0<QuickOpenHandler>, id: string, prefix: string, contextKey: string, description: string, instantProgress?: boolean); constructor(ctor: IConstructorSignature0<QuickOpenHandler>, id: string, prefix: string, contextKey: string, helpEntries: QuickOpenHandlerHelpEntry[], instantProgress?: boolean); constructor(ctor: IConstructorSignature0<QuickOpenHandler>, id: string, prefix: string, contextKey: string, param: any, instantProgress: boolean = false) { this.ctor = ctor; this.id = id; this.prefix = prefix; this.contextKey = contextKey; this.instantProgress = instantProgress; if (types.isString(param)) { this.description = param; } else { this.helpEntries = param; } } getId(): string { return this.id; } instantiate(instantiationService: IInstantiationService): QuickOpenHandler { return instantiationService.createInstance(this.ctor); } } export const Extensions = { Quickopen: 'workbench.contributions.quickopen' }; export interface IQuickOpenRegistry { /** * Registers a quick open handler to the platform. */ registerQuickOpenHandler(descriptor: QuickOpenHandlerDescriptor): void; /** * Registers a default quick open handler to fallback to. */ registerDefaultQuickOpenHandler(descriptor: QuickOpenHandlerDescriptor): void; /** * Get all registered quick open handlers */ getQuickOpenHandlers(): QuickOpenHandlerDescriptor[]; /** * Get a specific quick open handler for a given prefix. */ getQuickOpenHandler(prefix: string): QuickOpenHandlerDescriptor; /** * Returns the default quick open handler. */ getDefaultQuickOpenHandler(): QuickOpenHandlerDescriptor; } class QuickOpenRegistry implements IQuickOpenRegistry { private handlers: QuickOpenHandlerDescriptor[] = []; private defaultHandler: QuickOpenHandlerDescriptor; registerQuickOpenHandler(descriptor: QuickOpenHandlerDescriptor): void { this.handlers.push(descriptor); // sort the handlers by decreasing prefix length, such that longer // prefixes take priority: 'ext' vs 'ext install' - the latter should win this.handlers.sort((h1, h2) => h2.prefix.length - h1.prefix.length); } registerDefaultQuickOpenHandler(descriptor: QuickOpenHandlerDescriptor): void { this.defaultHandler = descriptor; } getQuickOpenHandlers(): QuickOpenHandlerDescriptor[] { return this.handlers.slice(0); } getQuickOpenHandler(text: string): QuickOpenHandlerDescriptor { return text ? arrays.first(this.handlers, h => strings.startsWith(text, h.prefix), null) : null; } getDefaultQuickOpenHandler(): QuickOpenHandlerDescriptor { return this.defaultHandler; } } Registry.add(Extensions.Quickopen, new QuickOpenRegistry()); export interface IEditorQuickOpenEntry { /** * The editor input used for this entry when opening. */ getInput(): IResourceInput | IEditorInput; /** * The editor options used for this entry when opening. */ getOptions(): IEditorOptions; } /** * A subclass of quick open entry that will open an editor with input and options when running. */ export class EditorQuickOpenEntry extends QuickOpenEntry implements IEditorQuickOpenEntry { constructor(private _editorService: IEditorService) { super(); } get editorService() { return this._editorService; } getInput(): IResourceInput | IEditorInput { return null; } getOptions(): IEditorOptions { return null; } run(mode: Mode, context: IEntryRunContext): boolean { const hideWidget = (mode === Mode.OPEN); if (mode === Mode.OPEN || mode === Mode.OPEN_IN_BACKGROUND) { const sideBySide = context.keymods.ctrlCmd; let openOptions: IEditorOptions; if (mode === Mode.OPEN_IN_BACKGROUND) { openOptions = { pinned: true, preserveFocus: true }; } else if (context.keymods.alt) { openOptions = { pinned: true }; } const input = this.getInput(); if (input instanceof EditorInput) { let opts = this.getOptions(); if (opts) { opts = objects.mixin(opts, openOptions, true); } else if (openOptions) { opts = EditorOptions.create(openOptions); } this.editorService.openEditor(input, opts, sideBySide ? SIDE_GROUP : ACTIVE_GROUP); } else { const resourceInput = <IResourceInput>input; if (openOptions) { resourceInput.options = objects.assign(resourceInput.options || Object.create(null), openOptions); } this.editorService.openEditor(resourceInput, sideBySide ? SIDE_GROUP : ACTIVE_GROUP); } } return hideWidget; } } /** * A subclass of quick open entry group that provides access to editor input and options. */ export class EditorQuickOpenEntryGroup extends QuickOpenEntryGroup implements IEditorQuickOpenEntry { getInput(): IEditorInput | IResourceInput { return null; } getOptions(): IEditorOptions { return null; } } export class QuickOpenAction extends Action { private prefix: string; constructor( id: string, label: string, prefix: string, @IQuickOpenService private quickOpenService: IQuickOpenService ) { super(id, label); this.prefix = prefix; this.enabled = !!this.quickOpenService; } run(context?: any): TPromise<void> { // Show with prefix this.quickOpenService.show(this.prefix); return Promise.resolve(null); } }
{ "pile_set_name": "Github" }
/** * Get information about the paging settings that DataTables is currently * using to display each page, including the number of records shown, start * and end points in the data set etc. * * DataTables 1.10+ provides the `dt-api page.info()` method, built-in, provide * the same information as this method. As such this method is marked * deprecated, but is available for use with legacy version of DataTables. * Please use the new API if you are used DataTables 1.10 or newer. * * @name fnPagingInfo * @summary Get information about the paging state of the table * @author [Allan Jardine](http://sprymedia.co.uk) * @deprecated * * @example * $(document).ready(function() { * $('#example').dataTable( { * "fnDrawCallback": function () { * alert( 'Now on page'+ this.fnPagingInfo().iPage ); * } * } ); * } ); */ jQuery.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings ) { return { "iStart": oSettings._iDisplayStart, "iEnd": oSettings.fnDisplayEnd(), "iLength": oSettings._iDisplayLength, "iTotal": oSettings.fnRecordsTotal(), "iFilteredTotal": oSettings.fnRecordsDisplay(), "iPage": oSettings._iDisplayLength === -1 ? 0 : Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ), "iTotalPages": oSettings._iDisplayLength === -1 ? 0 : Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength ) }; };
{ "pile_set_name": "Github" }
// Copyright (C) 2005-2013 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. #include <ostream> #include <streambuf> #include <sstream> #include <testsuite_hooks.h> #include <testsuite_io.h> using namespace std; void test5() { bool test __attribute__((unused)) = true; __gnu_test::fail_wstreambuf bob; wostream stream(&bob); wstringbuf sbuf(L"Foo, bar, qux", ios_base::in); stream << &sbuf; VERIFY( stream.rdstate() & ios_base::failbit ); VERIFY( (stream.rdstate() & ios_base::badbit) == 0 ); } void test7() { bool test __attribute__((unused)) = true; wostringstream stream; __gnu_test::fail_wstreambuf bib; stream << &bib; VERIFY( stream.rdstate() & ios_base::failbit ); VERIFY( (stream.rdstate() & ios_base::badbit) == 0 ); } // libstdc++/9371 int main() { test5(); test7(); return 0; }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef B2_MATH_H #define B2_MATH_H #include <Box2D/Common/b2Settings.h> #include <cmath> #include <cfloat> #include <cstddef> #include <limits> /// This function is used to ensure that a floating point number is /// not a NaN or infinity. inline bool b2IsValid(float32 x) { if (x != x) { // NaN. return false; } float32 infinity = std::numeric_limits<float32>::infinity(); return -infinity < x && x < infinity; } /// This is a approximate yet fast inverse square-root. inline float32 b2InvSqrt(float32 x) { union { float32 x; int32 i; } convert; convert.x = x; float32 xhalf = 0.5f * x; convert.i = 0x5f3759df - (convert.i >> 1); x = convert.x; x = x * (1.5f - xhalf * x * x); return x; } #define b2Sqrt(x) std::sqrt(x) #define b2Atan2(y, x) std::atan2(y, x) /// A 2D column vector. struct b2Vec2 { /// Default constructor does nothing (for performance). b2Vec2() {} /// Construct using coordinates. b2Vec2(float32 x, float32 y) : x(x), y(y) {} /// Set this vector to all zeros. void SetZero() { x = 0.0f; y = 0.0f; } /// Set this vector to some specified coordinates. void Set(float32 x_, float32 y_) { x = x_; y = y_; } /// Negate this vector. b2Vec2 operator -() const { b2Vec2 v; v.Set(-x, -y); return v; } /// Read from and indexed element. float32 operator () (int32 i) const { return (&x)[i]; } /// Write to an indexed element. float32& operator () (int32 i) { return (&x)[i]; } /// Add a vector to this vector. void operator += (const b2Vec2& v) { x += v.x; y += v.y; } /// Subtract a vector from this vector. void operator -= (const b2Vec2& v) { x -= v.x; y -= v.y; } /// Multiply this vector by a scalar. void operator *= (float32 a) { x *= a; y *= a; } /// Get the length of this vector (the norm). float32 Length() const { return b2Sqrt(x * x + y * y); } /// Get the length squared. For performance, use this instead of /// b2Vec2::Length (if possible). float32 LengthSquared() const { return x * x + y * y; } /// Convert this vector into a unit vector. Returns the length. float32 Normalize() { float32 length = Length(); if (length < b2_epsilon) { return 0.0f; } float32 invLength = 1.0f / length; x *= invLength; y *= invLength; return length; } /// Does this vector contain finite coordinates? bool IsValid() const { return b2IsValid(x) && b2IsValid(y); } /// Get the skew vector such that dot(skew_vec, other) == cross(vec, other) b2Vec2 Skew() const { return b2Vec2(-y, x); } float32 x, y; }; /// A 2D column vector with 3 elements. struct b2Vec3 { /// Default constructor does nothing (for performance). b2Vec3() {} /// Construct using coordinates. b2Vec3(float32 x, float32 y, float32 z) : x(x), y(y), z(z) {} /// Set this vector to all zeros. void SetZero() { x = 0.0f; y = 0.0f; z = 0.0f; } /// Set this vector to some specified coordinates. void Set(float32 x_, float32 y_, float32 z_) { x = x_; y = y_; z = z_; } /// Negate this vector. b2Vec3 operator -() const { b2Vec3 v; v.Set(-x, -y, -z); return v; } /// Add a vector to this vector. void operator += (const b2Vec3& v) { x += v.x; y += v.y; z += v.z; } /// Subtract a vector from this vector. void operator -= (const b2Vec3& v) { x -= v.x; y -= v.y; z -= v.z; } /// Multiply this vector by a scalar. void operator *= (float32 s) { x *= s; y *= s; z *= s; } float32 x, y, z; }; /// A 2-by-2 matrix. Stored in column-major order. struct b2Mat22 { /// The default constructor does nothing (for performance). b2Mat22() {} /// Construct this matrix using columns. b2Mat22(const b2Vec2& c1, const b2Vec2& c2) { ex = c1; ey = c2; } /// Construct this matrix using scalars. b2Mat22(float32 a11, float32 a12, float32 a21, float32 a22) { ex.x = a11; ex.y = a21; ey.x = a12; ey.y = a22; } /// Initialize this matrix using columns. void Set(const b2Vec2& c1, const b2Vec2& c2) { ex = c1; ey = c2; } /// Set this to the identity matrix. void SetIdentity() { ex.x = 1.0f; ey.x = 0.0f; ex.y = 0.0f; ey.y = 1.0f; } /// Set this matrix to all zeros. void SetZero() { ex.x = 0.0f; ey.x = 0.0f; ex.y = 0.0f; ey.y = 0.0f; } b2Mat22 GetInverse() const { float32 a = ex.x, b = ey.x, c = ex.y, d = ey.y; b2Mat22 B; float32 det = a * d - b * c; if (det != 0.0f) { det = 1.0f / det; } B.ex.x = det * d; B.ey.x = -det * b; B.ex.y = -det * c; B.ey.y = det * a; return B; } /// Solve A * x = b, where b is a column vector. This is more efficient /// than computing the inverse in one-shot cases. b2Vec2 Solve(const b2Vec2& b) const { float32 a11 = ex.x, a12 = ey.x, a21 = ex.y, a22 = ey.y; float32 det = a11 * a22 - a12 * a21; if (det != 0.0f) { det = 1.0f / det; } b2Vec2 x; x.x = det * (a22 * b.x - a12 * b.y); x.y = det * (a11 * b.y - a21 * b.x); return x; } b2Vec2 ex, ey; }; /// A 3-by-3 matrix. Stored in column-major order. struct b2Mat33 { /// The default constructor does nothing (for performance). b2Mat33() {} /// Construct this matrix using columns. b2Mat33(const b2Vec3& c1, const b2Vec3& c2, const b2Vec3& c3) { ex = c1; ey = c2; ez = c3; } /// Set this matrix to all zeros. void SetZero() { ex.SetZero(); ey.SetZero(); ez.SetZero(); } /// Solve A * x = b, where b is a column vector. This is more efficient /// than computing the inverse in one-shot cases. b2Vec3 Solve33(const b2Vec3& b) const; /// Solve A * x = b, where b is a column vector. This is more efficient /// than computing the inverse in one-shot cases. Solve only the upper /// 2-by-2 matrix equation. b2Vec2 Solve22(const b2Vec2& b) const; b2Vec3 ex, ey, ez; }; /// Rotation struct b2Rot { b2Rot() {} /// Initialize from an angle in radians explicit b2Rot(float32 angle) { /// TODO_ERIN optimize s = sinf(angle); c = cosf(angle); } /// Set using an angle in radians. void Set(float32 angle) { /// TODO_ERIN optimize s = sinf(angle); c = cosf(angle); } /// Set to the identity rotation void SetIdentity() { s = 0.0f; c = 1.0f; } /// Get the angle in radians float32 GetAngle() const { return b2Atan2(s, c); } /// Get the x-axis b2Vec2 GetXAxis() const { return b2Vec2(c, s); } /// Get the u-axis b2Vec2 GetYAxis() const { return b2Vec2(-s, c); } /// Sine and cosine float32 s, c; }; /// A transform contains translation and rotation. It is used to represent /// the position and orientation of rigid frames. struct b2Transform { /// The default constructor does nothing. b2Transform() {} /// Initialize using a position vector and a rotation. b2Transform(const b2Vec2& position, const b2Rot& rotation) : p(position), q(rotation) {} /// Set this to the identity transform. void SetIdentity() { p.SetZero(); q.SetIdentity(); } /// Set this based on the position and angle. void Set(const b2Vec2& position, float32 angle) { p = position; q.Set(angle); } b2Vec2 p; b2Rot q; }; /// This describes the motion of a body/shape for TOI computation. /// Shapes are defined with respect to the body origin, which may /// no coincide with the center of mass. However, to support dynamics /// we must interpolate the center of mass position. struct b2Sweep { /// Get the interpolated transform at a specific time. /// @param beta is a factor in [0,1], where 0 indicates alpha0. void GetTransform(b2Transform* xfb, float32 beta) const; /// Advance the sweep forward, yielding a new initial state. /// @param alpha the new initial time. void Advance(float32 alpha); /// Normalize the angles. void Normalize(); b2Vec2 localCenter; ///< local center of mass position b2Vec2 c0, c; ///< center world positions float32 a0, a; ///< world angles /// Fraction of the current time step in the range [0,1] /// c0 and a0 are the positions at alpha0. float32 alpha0; }; /// Useful constant extern const b2Vec2 b2Vec2_zero; /// Perform the dot product on two vectors. inline float32 b2Dot(const b2Vec2& a, const b2Vec2& b) { return a.x * b.x + a.y * b.y; } /// Perform the cross product on two vectors. In 2D this produces a scalar. inline float32 b2Cross(const b2Vec2& a, const b2Vec2& b) { return a.x * b.y - a.y * b.x; } /// Perform the cross product on a vector and a scalar. In 2D this produces /// a vector. inline b2Vec2 b2Cross(const b2Vec2& a, float32 s) { return b2Vec2(s * a.y, -s * a.x); } /// Perform the cross product on a scalar and a vector. In 2D this produces /// a vector. inline b2Vec2 b2Cross(float32 s, const b2Vec2& a) { return b2Vec2(-s * a.y, s * a.x); } /// Multiply a matrix times a vector. If a rotation matrix is provided, /// then this transforms the vector from one frame to another. inline b2Vec2 b2Mul(const b2Mat22& A, const b2Vec2& v) { return b2Vec2(A.ex.x * v.x + A.ey.x * v.y, A.ex.y * v.x + A.ey.y * v.y); } /// Multiply a matrix transpose times a vector. If a rotation matrix is provided, /// then this transforms the vector from one frame to another (inverse transform). inline b2Vec2 b2MulT(const b2Mat22& A, const b2Vec2& v) { return b2Vec2(b2Dot(v, A.ex), b2Dot(v, A.ey)); } /// Add two vectors component-wise. inline b2Vec2 operator + (const b2Vec2& a, const b2Vec2& b) { return b2Vec2(a.x + b.x, a.y + b.y); } /// Subtract two vectors component-wise. inline b2Vec2 operator - (const b2Vec2& a, const b2Vec2& b) { return b2Vec2(a.x - b.x, a.y - b.y); } inline b2Vec2 operator * (float32 s, const b2Vec2& a) { return b2Vec2(s * a.x, s * a.y); } inline bool operator == (const b2Vec2& a, const b2Vec2& b) { return a.x == b.x && a.y == b.y; } inline float32 b2Distance(const b2Vec2& a, const b2Vec2& b) { b2Vec2 c = a - b; return c.Length(); } inline float32 b2DistanceSquared(const b2Vec2& a, const b2Vec2& b) { b2Vec2 c = a - b; return b2Dot(c, c); } inline b2Vec3 operator * (float32 s, const b2Vec3& a) { return b2Vec3(s * a.x, s * a.y, s * a.z); } /// Add two vectors component-wise. inline b2Vec3 operator + (const b2Vec3& a, const b2Vec3& b) { return b2Vec3(a.x + b.x, a.y + b.y, a.z + b.z); } /// Subtract two vectors component-wise. inline b2Vec3 operator - (const b2Vec3& a, const b2Vec3& b) { return b2Vec3(a.x - b.x, a.y - b.y, a.z - b.z); } /// Perform the dot product on two vectors. inline float32 b2Dot(const b2Vec3& a, const b2Vec3& b) { return a.x * b.x + a.y * b.y + a.z * b.z; } /// Perform the cross product on two vectors. inline b2Vec3 b2Cross(const b2Vec3& a, const b2Vec3& b) { return b2Vec3(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x); } inline b2Mat22 operator + (const b2Mat22& A, const b2Mat22& B) { return b2Mat22(A.ex + B.ex, A.ey + B.ey); } // A * B inline b2Mat22 b2Mul(const b2Mat22& A, const b2Mat22& B) { return b2Mat22(b2Mul(A, B.ex), b2Mul(A, B.ey)); } // A^T * B inline b2Mat22 b2MulT(const b2Mat22& A, const b2Mat22& B) { b2Vec2 c1(b2Dot(A.ex, B.ex), b2Dot(A.ey, B.ex)); b2Vec2 c2(b2Dot(A.ex, B.ey), b2Dot(A.ey, B.ey)); return b2Mat22(c1, c2); } /// Multiply a matrix times a vector. inline b2Vec3 b2Mul(const b2Mat33& A, const b2Vec3& v) { return v.x * A.ex + v.y * A.ey + v.z * A.ez; } /// Multiply two rotations: q * r inline b2Rot b2Mul(const b2Rot& q, const b2Rot& r) { // [qc -qs] * [rc -rs] = [qc*rc-qs*rs -qc*rs-qs*rc] // [qs qc] [rs rc] [qs*rc+qc*rs -qs*rs+qc*rc] // s = qs * rc + qc * rs // c = qc * rc - qs * rs b2Rot qr; qr.s = q.s * r.c + q.c * r.s; qr.c = q.c * r.c - q.s * r.s; return qr; } /// Transpose multiply two rotations: qT * r inline b2Rot b2MulT(const b2Rot& q, const b2Rot& r) { // [ qc qs] * [rc -rs] = [qc*rc-qs*rs -qc*rs-qs*rc] // [-qs qc] [rs rc] [qs*rc+qc*rs -qs*rs+qc*rc] // s = qs * rc + qc * rs // c = qc * rc - qs * rs b2Rot qr; qr.s = q.s * r.c + q.c * r.s; qr.c = q.c * r.c - q.s * r.s; return qr; } /// Rotate a vector inline b2Vec2 b2Mul(const b2Rot& q, const b2Vec2& v) { return b2Vec2(q.c * v.x - q.s * v.y, q.s * v.x + q.c * v.y); } /// Inverse rotate a vector inline b2Vec2 b2MulT(const b2Rot& q, const b2Vec2& v) { return b2Vec2(q.c * v.x + q.s * v.y, -q.s * v.x + q.c * v.y); } inline b2Vec2 b2Mul(const b2Transform& T, const b2Vec2& v) { float32 x = (T.q.c * v.x - T.q.s * v.y) + T.p.x; float32 y = (T.q.s * v.x + T.q.c * v.y) + T.p.y; return b2Vec2(x, y); } inline b2Vec2 b2MulT(const b2Transform& T, const b2Vec2& v) { float32 px = v.x - T.p.x; float32 py = v.y - T.p.y; float32 x = (T.q.c * px + T.q.s * py); float32 y = (-T.q.s * px + T.q.c * py); return b2Vec2(x, y); } // v2 = A.q.Rot(B.q.Rot(v1) + B.p) + A.p // = (A.q * B.q).Rot(v1) + A.q.Rot(B.p) + A.p inline b2Transform b2Mul(const b2Transform& A, const b2Transform& B) { b2Transform C; C.q = b2Mul(A.q, B.q); C.p = b2Mul(A.q, B.p) + A.p; return C; } // v2 = A.q' * (B.q * v1 + B.p - A.p) // = A.q' * B.q * v1 + A.q' * (B.p - A.p) inline b2Transform b2MulT(const b2Transform& A, const b2Transform& B) { b2Transform C; C.q = b2MulT(A.q, B.q); C.p = b2MulT(A.q, B.p - A.p); return C; } template <typename T> inline T b2Abs(T a) { return a > T(0) ? a : -a; } inline b2Vec2 b2Abs(const b2Vec2& a) { return b2Vec2(b2Abs(a.x), b2Abs(a.y)); } inline b2Mat22 b2Abs(const b2Mat22& A) { return b2Mat22(b2Abs(A.ex), b2Abs(A.ey)); } template <typename T> inline T b2Min(T a, T b) { return a < b ? a : b; } inline b2Vec2 b2Min(const b2Vec2& a, const b2Vec2& b) { return b2Vec2(b2Min(a.x, b.x), b2Min(a.y, b.y)); } template <typename T> inline T b2Max(T a, T b) { return a > b ? a : b; } inline b2Vec2 b2Max(const b2Vec2& a, const b2Vec2& b) { return b2Vec2(b2Max(a.x, b.x), b2Max(a.y, b.y)); } template <typename T> inline T b2Clamp(T a, T low, T high) { return b2Max(low, b2Min(a, high)); } inline b2Vec2 b2Clamp(const b2Vec2& a, const b2Vec2& low, const b2Vec2& high) { return b2Max(low, b2Min(a, high)); } template<typename T> inline void b2Swap(T& a, T& b) { T tmp = a; a = b; b = tmp; } /// "Next Largest Power of 2 /// Given a binary integer value x, the next largest power of 2 can be computed by a SWAR algorithm /// that recursively "folds" the upper bits into the lower bits. This process yields a bit vector with /// the same most significant 1 as x, but all 1's below it. Adding 1 to that value yields the next /// largest power of 2. For a 32-bit value:" inline uint32 b2NextPowerOfTwo(uint32 x) { x |= (x >> 1); x |= (x >> 2); x |= (x >> 4); x |= (x >> 8); x |= (x >> 16); return x + 1; } inline bool b2IsPowerOfTwo(uint32 x) { bool result = x > 0 && (x & (x - 1)) == 0; return result; } inline void b2Sweep::GetTransform(b2Transform* xf, float32 beta) const { xf->p = (1.0f - beta) * c0 + beta * c; float32 angle = (1.0f - beta) * a0 + beta * a; xf->q.Set(angle); // Shift to origin xf->p -= b2Mul(xf->q, localCenter); } inline void b2Sweep::Advance(float32 alpha) { b2Assert(alpha0 < 1.0f); float32 beta = (alpha - alpha0) / (1.0f - alpha0); c0 = (1.0f - beta) * c0 + beta * c; a0 = (1.0f - beta) * a0 + beta * a; alpha0 = alpha; } /// Normalize an angle in radians to be between -pi and pi inline void b2Sweep::Normalize() { float32 twoPi = 2.0f * b2_pi; float32 d = twoPi * floorf(a0 / twoPi); a0 -= d; a -= d; } #endif
{ "pile_set_name": "Github" }
#include <opencp.hpp> using namespace std; using namespace cv; using namespace cp; void SLICTestSegment2Vector(Mat& src) { Mat seg; SLIC(src, seg, 16, 30, 0.1, 20); vector<vector<Point>> pts; SLICSegment2Vector(seg, pts); Mat segout; SLICVector2Segment(pts, src.size(), segout); if (getMSE(seg, segout) == 0.0)cout << "segmentation seg2vec test:OK\n"; } void guiSLICTest(Mat& src) { Mat dest, dest2; string wname = "SLIC"; namedWindow(wname); int a = 50; createTrackbar("a", wname, &a, 100); int S = 16; createTrackbar("S", wname, &S, 200); int m = 30; createTrackbar("m", wname, &m, 800); int mrs = 10; createTrackbar("ratio of min region size", wname, &mrs, 100); int iter = 20; createTrackbar("iteration", wname, &iter, 1000); int key = 0; Mat seg; Mat lab; while (key != 'q') { Mat show; { Timer t("slic all"); cvtColor(src, lab, COLOR_BGR2Lab); SLIC(lab, seg, S, (float)m, mrs / 100.0f, iter); } drawSLIC(src, seg, dest, true, true, Scalar(255, 255, 0)); Mat dest2; SLIC(lab, seg, S * 2, (float)m, mrs / 100.f, iter); drawSLIC(src, seg, dest2, true, true, Scalar(255, 255, 0)); dissolveSlideBlend(dest, dest2, show); alphaBlend(src, show, a / 100.0, show); imshow(wname, show); key = waitKey(1); if (key == 't') { SLICTestSegment2Vector(src); } } }
{ "pile_set_name": "Github" }
export * from './static-website'; export * from './website-bucket'; export * from './website-alias-record';
{ "pile_set_name": "Github" }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ const React = require('react') const ReactDOM = require('react-dom') const {StyleSheet, css} = require('aphrodite/no-important') // Components const ReduxComponent = require('../reduxComponent') const Tab = require('./tab') // Actions const appActions = require('../../../../js/actions/appActions') const windowActions = require('../../../../js/actions/windowActions') // Store const windowStore = require('../../../../js/stores/windowStore') // Constants const dragTypes = require('../../../../js/constants/dragTypes') const globalStyles = require('../styles/global') // Utils const dnd = require('../../../../js/dnd') const dndData = require('../../../../js/dndData') const frameStateUtil = require('../../../../js/state/frameStateUtil') const {isIntermediateAboutPage} = require('../../../../js/lib/appUrlUtil') const {getCurrentWindowId} = require('../../currentWindow') class PinnedTabs extends React.Component { constructor (props) { super(props) this.onDragOver = this.onDragOver.bind(this) this.onDrop = this.onDrop.bind(this) } dropFrame (frameKey) { return windowStore.getFrame(frameKey) } onDrop (e) { const clientX = e.clientX const sourceDragData = dndData.getDragData(e.dataTransfer, dragTypes.TAB) const location = sourceDragData.get('location') if (location === 'about:blank' || location === 'about:newtab' || isIntermediateAboutPage(location)) { return } // This must be executed async because the state change that this causes // will cause the onDragEnd to never run setTimeout(() => { const key = sourceDragData.get('key') let droppedOnTab = dnd.closestFromXOffset(this.tabRefs.filter((node) => node && node.props.frameKey !== key), clientX).selectedRef if (droppedOnTab) { const isLeftSide = dnd.isLeftSide(ReactDOM.findDOMNode(droppedOnTab), clientX) const sourceIsPinned = sourceDragData.get('pinnedLocation') // TODO: pass in needs-pinning in moveTab, and do nothing else here windowActions.moveTab(key, droppedOnTab.props.frameKey, isLeftSide) if (!sourceIsPinned) { appActions.tabPinned(sourceDragData.get('tabId'), true) } } }, 0) } onDragOver (e) { e.dataTransfer.dropEffect = 'move' e.preventDefault() } mergeProps (state, ownProps) { const currentWindow = state.get('currentWindow') const pinnedFrames = frameStateUtil.getPinnedFrames(currentWindow) .filter(frame => frame.get('tabStripWindowId') === getCurrentWindowId()) const previewFrameKey = frameStateUtil.getPreviewFrameKey(currentWindow) const props = {} // used in renderer props.pinnedTabs = pinnedFrames.map((frame) => frame.get('key')) props.isPreviewingPinnedTab = previewFrameKey && props.pinnedTabs.some(key => key === previewFrameKey) return props } render () { this.tabRefs = [] return <div className={css( styles.pinnedTabs, this.props.isPreviewingPinnedTab && styles.pinnedTabs_previewing )} data-test-id='pinnedTabs' onDragOver={this.onDragOver} onDrop={this.onDrop} > { this.props.pinnedTabs .map((frameKey) => <Tab key={'tab-' + frameKey} ref={(node) => this.tabRefs.push(node)} frameKey={frameKey} /> ) } </div> } } const styles = StyleSheet.create({ pinnedTabs: { height: '-webkit-fill-available', display: 'flex', alignItems: 'stretch', boxSizing: 'border-box', position: 'relative', marginLeft: 0, marginTop: 0 }, pinnedTabs_previewing: { zIndex: globalStyles.zindex.zindexTabs + 1 } }) module.exports = ReduxComponent.connect(PinnedTabs)
{ "pile_set_name": "Github" }
#include "main.h" #include "bot.h" #include "mainctrl.h" #include "smtp_logic.h" #include "utility.h" #include "config.h" char *g_szSectionName=SECTION_NAME; list<scriptcmd> g_lScriptCmds; bool ParseScript(const char *szScript) { CString sScript(szScript); bool bGetScript=false; unsigned long lScriptType; int iLineNum=0; CString sCurLine=sScript.Token(iLineNum, "\n"); while(sCurLine.Compare("")) { if(sCurLine.GetLength()) if(!bGetScript) { if(!sCurLine.Token(0, " ").CompareNoCase("onstart")) { // If there is no { after the script name, dont parse if(!sCurLine.Token(1, " ").Compare("{")) { bGetScript=true; lScriptType=SCRIPT_ONSTART; } } else if(!sCurLine.Token(0, " ").CompareNoCase("onconnect")) { if(!sCurLine.Token(1, " ").Compare("{")) { bGetScript=true; lScriptType=SCRIPT_ONCONNECT; } } else if(!sCurLine.Token(0, " ").CompareNoCase("onjoin")) { if(!sCurLine.Token(1, " ").Compare("{")) { bGetScript=true; lScriptType=SCRIPT_ONJOIN; } } else if(!sCurLine.Token(0, " ").CompareNoCase("onlogin")) { if(!sCurLine.Token(1, " ").Compare("{")) { bGetScript=true; lScriptType=SCRIPT_ONLOGIN; } } else if(!sCurLine.Token(0, " ").CompareNoCase("ondisconnect")) { if(!sCurLine.Token(1, " ").Compare("{")) { bGetScript=true; lScriptType=SCRIPT_ONDISCON; } } else if(!sCurLine.Token(0, " ").CompareNoCase("onremove")) { if(!sCurLine.Token(1, " ").Compare("{")) { bGetScript=true; lScriptType=SCRIPT_ONREMOVE; } } else if(!sCurLine.Token(0, " ").CompareNoCase("onspread")) { if(!sCurLine.Token(1, " ").Compare("{")) { bGetScript=true; lScriptType=SCRIPT_ONSPREAD; } } else if(!sCurLine.Token(0, " ").CompareNoCase("ondebugeractive")) { if(!sCurLine.Token(1, " ").Compare("{")) { bGetScript=true; lScriptType=SCRIPT_ONDEBUG; } } else if(!sCurLine.Token(0, " ").CompareNoCase("onstartupfin")) { if(!sCurLine.Token(1, " ").Compare("{")) { bGetScript=true; lScriptType=SCRIPT_ONSTARTUPFIN; } } else if(!sCurLine.Token(0, " ").CompareNoCase("ontimer")) { // Not implemented yet } } else { // End script on } on a single line if(!sCurLine.Token(0, " ").Compare("}")) { bGetScript=false; } else { // Skip tabs while(sCurLine.operator [](0)=='\t') { CString sTemp=sCurLine.Mid(1); sCurLine.Assign(sTemp); } scriptcmd cmd; cmd.lScriptType=lScriptType; cmd.sScriptCmd=sCurLine; g_lScriptCmds.push_back(cmd); } } iLineNum++; sCurLine=sScript.Token(iLineNum, "\n"); } return true; } bool CheckMD5(const char *szMD5In, const char *szValue) { // If the md5 isn't empty if(strcmp(szMD5In, "")) { // Calculate the md5 of the value md5::MD5_CTX md5; md5::MD5Init(&md5); unsigned char szMD5[16]; md5::MD5Update(&md5, (unsigned char*)szValue, strlen(szValue)); md5::MD5Final(szMD5, &md5); // Compare the values if(!memcmp(szMD5In, szMD5, sizeof(szMD5))) return true; else return false; } else return true; return false; } void CBot::RunScript(unsigned long lEvent) { list<scriptcmd>::iterator isc; for(isc=g_lScriptCmds.begin(); isc!=g_lScriptCmds.end(); isc++) { if((*isc).lScriptType!=lEvent) continue; CMessage mFakeMsg; mFakeMsg.bNotice=false; mFakeMsg.bSilent=false; mFakeMsg.sChatString.Assign((*isc).sScriptCmd); mFakeMsg.sCmd.Assign((*isc).sScriptCmd.Token(0, " ").Mid(1)); mFakeMsg.sDest.Assign(g_pMainCtrl->m_cBot.si_mainchan.sValue); mFakeMsg.sHost.Assign("AutoStart.Net"); mFakeMsg.sIdentd.Assign("AutoStart"); mFakeMsg.sReplyTo.Assign(g_pMainCtrl->m_cBot.si_mainchan.sValue); mFakeMsg.sSrc.Assign("AutoStart"); g_pMainCtrl->m_cBot.HandleMsgInt(&mFakeMsg); } } void CBot::Config() { int i=0; ParseScript(g_szScript); list<scriptcmd>::iterator isc; for(isc=g_lScriptCmds.begin(); isc!=g_lScriptCmds.end(); isc++) { char *szBla=(*isc).sScriptCmd; } int iNumCVars=sizeof(g_aCVars)/sizeof(conf_cvar); int iNumUsers=sizeof(g_aUsers)/sizeof(conf_user); for(i=0; i<iNumCVars; i++) { // Find the cvar cvar *pCVar=g_pMainCtrl->m_cCVar.FindCvarByName(g_aCVars[i].szName, true); // Skip to the next cvar if none is registered if(!pCVar) continue; // Copy the values of the cvars over g_pMainCtrl->m_cCVar.SetCVar(pCVar, g_aCVars[i].szValue, g_aCVars[i].szCryptKey); // Check the hash if(!CheckMD5(g_aCVars[i].szMD5, g_aCVars[i].szValue)) g_pMainCtrl->m_bHashCheckFailed=true; } for(i=0; i<iNumUsers; i++) { cvar *pTempUser=g_pMainCtrl->m_cCVar.TempCvar(g_aUsers[i].cUsername.szName, g_aUsers[i].cUsername.szValue, g_aUsers[i].cUsername.szCryptKey); cvar *pTempPass=g_pMainCtrl->m_cCVar.TempCvar(g_aUsers[i].cPasswordMD5.szName, g_aUsers[i].cPasswordMD5.szValue, g_aUsers[i].cPasswordMD5.szCryptKey); cvar *pTempHost=g_pMainCtrl->m_cCVar.TempCvar(g_aUsers[i].cHostmask.szName, g_aUsers[i].cHostmask.szValue, g_aUsers[i].cHostmask.szCryptKey); cvar *pTempIdentd=g_pMainCtrl->m_cCVar.TempCvar(g_aUsers[i].cIdentdmask.szName, g_aUsers[i].cIdentdmask.szValue, g_aUsers[i].cIdentdmask.szCryptKey); if(!CheckMD5(g_aUsers[i].cUsername.szMD5, g_aUsers[i].cUsername.szValue)) g_pMainCtrl->m_bHashCheckFailed=true; if(!CheckMD5(g_aUsers[i].cPasswordMD5.szMD5, g_aUsers[i].cPasswordMD5.szValue)) g_pMainCtrl->m_bHashCheckFailed=true; if(!CheckMD5(g_aUsers[i].cHostmask.szMD5, g_aUsers[i].cHostmask.szValue)) g_pMainCtrl->m_bHashCheckFailed=true; if(!CheckMD5(g_aUsers[i].cIdentdmask.szMD5, g_aUsers[i].cIdentdmask.szValue)) g_pMainCtrl->m_bHashCheckFailed=true; ADDUSER(pTempUser->sValue, pTempPass->sValue, pTempHost->sValue, pTempIdentd->sValue); } } void CBot::Autostart() { int i=0; int iNumServers=sizeof(g_aServers)/sizeof(conf_server); for(i=0; i<iNumServers; i++) { irc_server *pServer=new irc_server; pServer->si_chanpass=g_pMainCtrl->m_cCVar.TempCvar(g_aServers[i].cChanPass.szName, g_aServers[i].cChanPass.szValue, g_aServers[i].cChanPass.szCryptKey); pServer->si_mainchan=g_pMainCtrl->m_cCVar.TempCvar(g_aServers[i].cMainChan.szName, g_aServers[i].cMainChan.szValue, g_aServers[i].cMainChan.szCryptKey); pServer->si_nickprefix=g_pMainCtrl->m_cCVar.TempCvar(g_aServers[i].cNickPrefix.szName, g_aServers[i].cNickPrefix.szValue, g_aServers[i].cNickPrefix.szCryptKey); pServer->si_port=g_pMainCtrl->m_cCVar.TempCvar(g_aServers[i].cPort.szName, g_aServers[i].cPort.szValue, g_aServers[i].cPort.szCryptKey); pServer->si_server=g_pMainCtrl->m_cCVar.TempCvar(g_aServers[i].cServer.szName, g_aServers[i].cServer.szValue, g_aServers[i].cServer.szCryptKey); pServer->si_servpass=g_pMainCtrl->m_cCVar.TempCvar(g_aServers[i].cServPass.szName, g_aServers[i].cServPass.szValue, g_aServers[i].cServPass.szCryptKey); pServer->si_usessl=g_pMainCtrl->m_cCVar.TempCvar(g_aServers[i].cUseSSL.szName, g_aServers[i].cUseSSL.szValue, g_aServers[i].cUseSSL.szCryptKey); if(!CheckMD5(g_aServers[i].cChanPass.szMD5, g_aServers[i].cChanPass.szValue)) g_pMainCtrl->m_bHashCheckFailed=true; if(!CheckMD5(g_aServers[i].cMainChan.szMD5, g_aServers[i].cMainChan.szValue)) g_pMainCtrl->m_bHashCheckFailed=true; if(!CheckMD5(g_aServers[i].cNickPrefix.szMD5, g_aServers[i].cNickPrefix.szValue)) g_pMainCtrl->m_bHashCheckFailed=true; if(!CheckMD5(g_aServers[i].cServer.szMD5, g_aServers[i].cServer.szValue)) g_pMainCtrl->m_bHashCheckFailed=true; if(!CheckMD5(g_aServers[i].cServPass.szMD5, g_aServers[i].cServPass.szValue)) g_pMainCtrl->m_bHashCheckFailed=true; g_pMainCtrl->m_cIRC.m_vServers.push_back(pServer); } // TODO: Add Autostart here } #ifdef WIN32 #pragma warning(disable:4068) #pragma data_seg(SECTION_NAME) // You can try smaller size here. This will make the bot smaller, // but make it so the encoder still fits in, else no polymorph will // be done. __declspec(allocate(SECTION_NAME)) char szBuf[16384]; #endif // WIN32
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ --> <tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> <test name="StorefrontCheckoutDisabledBundleProductTest"> <annotations> <features value="Checkout"/> <stories value="Disabled bundle product is preventing customer to checkout for the first attempt"/> <title value="Customer should be able to checkout if there is at least one available product in the cart"/> <description value="Customer should be able to checkout if there is at least one available product in the cart"/> <severity value="MINOR"/> <testCaseId value="MC-29105"/> <group value="checkout"/> </annotations> <before> <!-- Create category and simple product --> <createData entity="SimpleSubCategory" stepKey="createCategory"/> <createData entity="_defaultProduct" stepKey="createSimpleProduct"> <requiredEntity createDataKey="createCategory"/> </createData> <!-- Create bundle product --> <createData entity="ApiBundleProductPriceViewRange" stepKey="createBundleDynamicProduct"> <requiredEntity createDataKey="createCategory"/> </createData> <createData entity="DropDownBundleOption" stepKey="bundleOption"> <requiredEntity createDataKey="createBundleDynamicProduct"/> </createData> <createData entity="ApiBundleLink" stepKey="createNewBundleLink"> <requiredEntity createDataKey="createBundleDynamicProduct"/> <requiredEntity createDataKey="bundleOption"/> <requiredEntity createDataKey="createSimpleProduct"/> </createData> <magentoCLI command="indexer:reindex" stepKey="reindex"/> <magentoCLI command="cache:flush" stepKey="cacheFlush"/> </before> <after> <!-- Delete category --> <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> <!-- Delete bundle product data --> <deleteData createDataKey="createSimpleProduct" stepKey="deleteSimpleProduct"/> <deleteData createDataKey="createBundleDynamicProduct" stepKey="deleteBundleProduct"/> </after> <!-- Add simple product to the cart --> <actionGroup ref="AddSimpleProductToCart" stepKey="cartAddSimpleProductToCart"> <argument name="product" value="$$createSimpleProduct$$"/> <argument name="productCount" value="1"/> </actionGroup> <!-- Go to bundle product page --> <amOnPage url="{{StorefrontProductPage.url($$createBundleDynamicProduct.custom_attributes[url_key]$$)}}" stepKey="navigateToProductPage"/> <waitForPageLoad stepKey="waitForPageLoad"/> <!-- Add bundle product to the cart --> <click selector="{{StorefrontBundleProductActionSection.customizeAndAddToCartButton}}" stepKey="clickCustomizeAndAddToCart"/> <actionGroup ref="addToCartFromStorefrontProductPage" stepKey="addProductToCart"> <argument name="productName" value="$$createBundleDynamicProduct.name$$"/> </actionGroup> <!-- Login to admin panel --> <openNewTab stepKey="openNewTab"/> <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> <!-- Find the first simple product that we just created using the product grid and go to its page--> <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="visitAdminProductPage"/> <!-- Disabled bundle product from grid --> <actionGroup ref="ChangeStatusProductUsingProductGridActionGroup" stepKey="disabledProductFromGrid"> <argument name="product" value="$$createBundleDynamicProduct$$"/> <argument name="status" value="Disable"/> </actionGroup> <closeTab stepKey="closeTab"/> <!-- Go to cart page--> <actionGroup ref="StorefrontOpenCartPageActionGroup" stepKey="openCartPage"/> <!-- Assert checkout button exists on the page--> <seeElement selector="{{CheckoutCartSummarySection.proceedToCheckout}}" stepKey="seeCheckoutButton"/> <!-- Assert no error message is not shown on the page--> <dontSee userInput="Some of the products are out of stock." stepKey="seeNoItemsInShoppingCart"/> </test> </tests>
{ "pile_set_name": "Github" }
#!/bin/bash set -e -o pipefail function usage() { echo "USAGE: $0 /path/to/hledger.journal [web|bash|hledger [hledger-args]]" } journal=$(readlink -f "$1") shift [ -f "$journal" ] || { usage; exit 1; } dir=$(dirname $journal) file=$(basename $journal) cmd="$1" shift case "$cmd" in web) extra_args="" ;; bash) extra_args="bash" ;; hledger) extra_args="hledger" ;; *)usage; exit 1 ;; esac docker container run --rm -it --volume "$dir:/data" \ --env HLEDGER_FILE_NAME=/data/$file \ --env LEDGER_FILE=/data/$file \ -p 5000:5000 -p 5001:5001 \ hledger $extra_args "$@"
{ "pile_set_name": "Github" }
Name: %{_cross_os}libxcrypt Version: 4.4.16 Release: 1%{?dist} Summary: Extended crypt library for descrypt, md5crypt, bcrypt, and others License: LGPL-2.1-or-later URL: https://github.com/besser82/libxcrypt Source0: https://github.com/besser82/libxcrypt/archive/v%{version}/libxcrypt-%{version}.tar.gz BuildRequires: %{_cross_os}glibc-devel %description %{summary}. %package devel Summary: Files for development using the extended crypt library for descrypt, md5crypt, bcrypt, and others Requires: %{name} %description devel %{summary}. %prep %autosetup -n libxcrypt-%{version} -p1 ./autogen.sh %build %cross_configure \ --disable-failure-tokens \ --disable-valgrind \ --disable-silent-rules \ --enable-hashes=all \ --enable-obsolete-api=no \ --enable-obsolete-api-enosys=no \ --enable-shared \ --enable-static \ --with-pkgconfigdir=%{_cross_pkgconfigdir} \ %make_build %install %make_install %files %license LICENSING COPYING.LIB %{_cross_attribution_file} %{_cross_libdir}/*.so.* %exclude %{_cross_mandir} %files devel %{_cross_libdir}/*.a %{_cross_libdir}/*.so %{_cross_includedir}/*.h %{_cross_pkgconfigdir}/*.pc %exclude %{_cross_libdir}/*.la %changelog
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <!-- For more information on using web.config transformation visit http://go.microsoft.com/fwlink/?LinkId=125889 --> <configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> <connectionStrings> <add name="Raven" connectionString="Url=http://localhost:8080;Database=Demo.Production" xdt:Transform="SetAttributes" xdt:Locator="Match(name)" /> <add name="Elastic" connectionString="Url=http://localhost:9200;DefaultIndex=demo.production" xdt:Transform="SetAttributes" xdt:Locator="Match(name)" /> </connectionStrings> <MessageForwardingInCaseOfFaultConfig ErrorQueue="error.production" xdt:Transform="SetAttributes(ErrorQueue)" /> <UnicastBusConfig> <MessageEndpointMappings xdt:Transform="Replace"> <add Assembly="Domain.Accounting.Messages" Endpoint="domain.production" /> <add Assembly="Domain.Authentication.Messages" Endpoint="domain.production" /> <add Assembly="Domain.Configuration.Messages" Endpoint="domain.production" /> <add Assembly="Domain.HumanResources.Messages" Endpoint="domain.production" /> <add Assembly="Domain.Relations.Messages" Endpoint="domain.production" /> <add Assembly="Domain.Warehouse.Messages" Endpoint="domain.production" /> </MessageEndpointMappings> </UnicastBusConfig> <AuditConfig QueueName="audit.production" xdt:Transform="SetAttributes(QueueName)" /> <appSettings> <add key="endpoint" value="seed.production" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" /> <add key="destination" value="domain.production" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" /> </appSettings> </configuration>
{ "pile_set_name": "Github" }
'use strict'; import Replace from './Replace'; import * as replaceOptions from './ReplaceOptions'; import { forEach } from 'min-dash'; /** * This module is an element agnostic replace menu provider for the popup menu. */ export default function ReplaceMenuProvider(modeling) { this._dsReplace = new Replace(modeling); this._modeling = modeling; } ReplaceMenuProvider.$inject = ['modeling']; /** * Get all entries from replaceOptions for the given element and apply filters * on them. Get for example only elements, which are different from the current one. * * @param {djs.model.Base} element * * @return {Array<Object>} a list of menu entry items */ ReplaceMenuProvider.prototype.getEntries = function(element) { let entries; if (element.type.includes('actor')) { entries = replaceOptions.actorReplaceOptions(element.type); } else if (element.type.includes('workObject')) { entries = replaceOptions.workObjectReplaceOptions(element.type); } return this._createEntries(element, entries); }; /** * Creates an array of menu entry objects for a given element and filters the replaceOptions * according to a filter function. * * @param {djs.model.Base} element * @param {Object} replaceOptions * * @return {Array<Object>} a list of menu items */ ReplaceMenuProvider.prototype._createEntries = function(element, replaceOptions) { let menuEntries = []; let self = this; forEach(replaceOptions, function(definition) { let entry = self._createMenuEntry(definition, element); menuEntries.push(entry); }); return menuEntries; }; /** * Creates and returns a single menu entry item. * * @param {Object} definition a single replace options definition object * @param {djs.model.Base} element * @param {Function} [action] an action callback function which gets called when * the menu entry is being triggered. * * @return {Object} menu entry item */ ReplaceMenuProvider.prototype._createMenuEntry = function(definition, element, action) { let replaceElement = this._dsReplace.replaceElement; let modeling = this._modeling; let replaceAction = function() { return replaceElement(element, definition.target, modeling); }; action = action || replaceAction; let menuEntry = { label: definition.label, className: definition.className, id: definition.actionName, action: action }; return menuEntry; };
{ "pile_set_name": "Github" }
<?php /** * @version SVN $Id: default_media_details.php 224 2012-03-01 22:09:22Z dhorsfall $ * @package hwdMediaShare * @copyright Copyright (C) 2012 Highwood Design Limited. All rights reserved. * @license GNU General Public License http://www.gnu.org/copyleft/gpl.html * @author Dave Horsfall * @since 08-Jan-2012 12:19:24 */ // No direct access to this file defined('_JEXEC') or die('Restricted access'); $this->items = $this->media; $this->view_item = 'media'; $this->elementType = 1; $this->elementName = 'Media'; $listOrder = $this->escape($this->state->get('list.ordering')); $listDirn = $this->escape($this->state->get('list.direction')); $user = JFactory::getUser(); $row=0; $counter=0; $leadingcount=0; $introcount=0; ?> <!-- View Container --> <div class="media-details-view"> <?php foreach ($this->items as $id => &$item) : $id= ($id-$leadingcount)+1; $rowcount=( ((int)$id-1) % (int) $this->columns) +1; $row = $counter / $this->columns ; $item->slug = $item->alias ? ($item->id . ':' . $item->alias) : $item->id; $canEdit = ($user->authorise('core.edit', 'com_hwdmediashare.media.'.$item->id) || ($user->authorise('core.edit.own', 'com_hwdmediashare.media.'.$item->id) && ($item->created_user_id == $user->id))); $canEditState = ($user->authorise('core.edit.state', 'com_hwdmediashare.album.'.$item->id) || ($user->authorise('core.edit.own', 'com_hwdmediashare') && ($item->created_user_id == $user->id))); $canDelete = ($user->authorise('core.delete', 'com_hwdmediashare.media.'.$item->id) || ($user->authorise('core.edit.own', 'com_hwdmediashare') && ($item->created_user_id == $user->id))); ?> <!-- Row --> <?php if ($rowcount == 1) : ?> <div class="row-fluid items-row cols-<?php echo (int) $this->columns;?> <?php echo 'row-'.$row ; ?>"> <?php endif; ?> <!-- Column --> <div class="item column-<?php echo $rowcount;?><?php echo ($item->published != '1' ? ' system-unpublished' : false); ?> span<?php echo round((12/$this->columns));?>"> <!-- Cell --> <?php if ($item->published != '1') : ?> <div class="system-unpublished"> <?php endif; ?> <?php if ($this->params->get('global_list_meta_title') != 'hide') :?> <h3> <a href="<?php echo JRoute::_(hwdMediaShareHelperRoute::getMediaItemRoute($item->slug)); ?>"> <?php echo $this->escape(JHtmlString::truncate($item->title, $this->params->get('global_list_title_truncate'))); ?> </a> </h3> <?php endif; ?> <!-- Thumbnail Image --> <div class="thumbnail media-item"> <?php if ($canEdit || $canDelete): ?> <!-- Actions --> <ul class="media-nav"> <li><a href="#" class="pagenav-manage"><?php echo JText::_('COM_HWDMS_MANAGE'); ?> </a> <ul class="media-subnav"> <?php if ($canEdit) : ?> <li><?php echo JHtml::_('hwdicon.edit', 'media', $item, $this->params); ?></li> <?php endif; ?> <?php if ($canEditState) : ?> <?php if ($item->published != '1') : ?> <li><?php echo JHtml::_('hwdicon.publish', 'media', $item, $this->params); ?></li> <?php else : ?> <li><?php echo JHtml::_('hwdicon.unpublish', 'media', $item, $this->params); ?></li> <?php endif; ?> <?php endif; ?> <?php if ($canDelete) : ?> <li><?php echo JHtml::_('hwdicon.delete', 'media', $item, $this->params); ?></li> <?php endif; ?> </ul> </li> </ul> <?php endif; ?> <!-- Media Type --> <?php if ($this->params->get('global_list_meta_thumbnail') != 'hide') :?> <div class="media-item-format-1-<?php echo $item->media_type; ?>"> <img src="<?php echo JHtml::_('hwdicon.overlay', '1-'.$item->media_type, $item); ?>" alt="<?php echo JText::_('COM_HWDMS_MEDIA_TYPE'); ?>" /> </div> <?php if ($item->duration > 0) :?> <div class="media-duration"> <?php echo hwdMediaShareMedia::secondsToTime($item->duration); ?> </div> <?php endif; ?> <a href="<?php echo JRoute::_(hwdMediaShareHelperRoute::getMediaItemRoute($item->slug)); ?>"> <img src="<?php echo JRoute::_(hwdMediaShareDownloads::thumbnail($item)); ?>" border="0" alt="<?php echo $this->escape(JHtmlString::truncate($item->title, $this->params->get('global_list_title_truncate'))); ?>" style="max-width:100%;" /> </a> <?php endif; ?> </div> <!-- Clears Item and Information --> <div class="clear"></div> <!-- Item Meta --> <ul class="unstyled"> <li class="article-info-term"><?php echo JText::_('COM_HWDMS_DETAILS'); ?> </li> <?php if ($this->params->get('global_list_meta_author') != 'hide') :?> <li class="media-info-createdby"> <?php echo JText::sprintf('COM_HWDMS_CREATED_BY', '<a href="#">'.htmlspecialchars($item->author, ENT_COMPAT, 'UTF-8').'</a>'); ?></li> <?php endif; ?> <?php if ($this->params->get('global_list_meta_created') != 'hide') :?> <li class="media-info-created"> <?php echo JText::sprintf('COM_HWDMS_CREATED_ON', JHtml::_('date', $item->created, $this->params->get('global_list_date_format'))); ?></li> <?php endif; ?> <?php if ($this->params->get('global_list_meta_likes') != 'hide') :?> <li class="media-info-like"> <a href="<?php echo JRoute::_('index.php?option=com_hwdmediashare&task=album.like&id=' . $item->id . '&return=' . $this->return . '&tmpl=component'); ?>"><?php echo JText::_('COM_HWDMS_LIKE'); ?></a> (<?php echo $this->escape($item->likes); ?>) <a href="<?php echo JRoute::_('index.php?option=com_hwdmediashare&task=album.dislike&id=' . $item->id . '&return=' . $this->return . '&tmpl=component'); ?>"><?php echo JText::_('COM_HWDMS_DISLIKE'); ?></a> (<?php echo $this->escape($item->dislikes); ?>) </li> <?php endif; ?> <?php if ($this->params->get('global_list_meta_hits') != 'hide') :?> <li class="media-info-hits"> <?php echo JText::_('COM_HWDMS_VIEWS'); ?> (<?php echo (int) $item->hits; ?>)</li> <?php endif; ?> </ul> <?php if ($item->published != '1') : ?> </div> <?php endif; ?> <div class="item-separator"></div> </div> <?php if (($rowcount == $this->columns) or (($counter + 1) == count($this->items))): ?> <span class="row-separator"></span> </div> <?php endif; ?> <?php $counter++; ?> <?php endforeach; ?> </div>
{ "pile_set_name": "Github" }
/** * MIT License * * Copyright (c) 2010 - 2020 The OSHI Project Contributors: https://github.com/oshi/oshi/graphs/contributors * * 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. */ package oshi.driver.windows.wmi; import com.sun.jna.platform.win32.COM.WbemcliUtil.WmiQuery; //NOSONAR squid:S1191 import com.sun.jna.platform.win32.COM.WbemcliUtil.WmiResult; import oshi.annotation.concurrent.ThreadSafe; import oshi.util.platform.windows.WmiQueryHandler; /** * Utility to query WMI class {@code Win32_USBController} */ @ThreadSafe public final class Win32USBController { private static final String WIN32_USB_CONTROLLER = "Win32_USBController"; /** * USB Controller properties */ public enum USBControllerProperty { PNPDEVICEID; } private Win32USBController() { } /** * Queries the USB Controller device IDs * * @return Information regarding each disk drive. */ public static WmiResult<USBControllerProperty> queryUSBControllers() { WmiQuery<USBControllerProperty> usbControllerQuery = new WmiQuery<>(WIN32_USB_CONTROLLER, USBControllerProperty.class); return WmiQueryHandler.createInstance().queryWMI(usbControllerQuery); } }
{ "pile_set_name": "Github" }
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.WafV2.Outputs { [OutputType] public sealed class RuleGroupRuleStatementNotStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryString { [OutputConstructor] private RuleGroupRuleStatementNotStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryString() { } } }
{ "pile_set_name": "Github" }
pkg_repo=a2 pkg_name=a1-migration-data-minimal pkg_description="Minimal Automate 1 Migration Data -- For use with the --self-test flag. No ES2 data." pkg_origin=devchef pkg_version=${A1_MIGRATION_DATA_VERSION:-0.0.1} pkg_maintainer="Chef Software Inc. <[email protected]>" pkg_license=('UNLICENSED') pkg_upstream_url="http://github.com/chef/automate/components/automate-deployment/a1-migration/a1-migration-data-minimal" pkg_deps=( core/bash core/rsync ) pkg_build_deps=( core/coreutils core/rsync ) pkg_svc_user=root pkg_svc_group=root do_build() { return 0 } do_strip() { return 0 } do_install() { build_line "Copying A1 configuration and data..." mkdir -p ${pkg_prefix}/etc mkdir -p ${pkg_prefix}/var/opt/delivery/a1_pg_export mkdir -p ${pkg_prefix}/var/opt/delivery/elasticsearch/data mkdir -p ${pkg_prefix}/var/opt/delivery/compliance/profiles mkdir -p ${pkg_prefix}/var/opt/delivery/notifications rsync -chaz /src/etc/delivery/ ${pkg_prefix}/etc/delivery/ rsync -chaz /src/var/opt/delivery/a1_pg_export/ ${pkg_prefix}/var/opt/delivery/a1_pg_export rsync -chaz /src/var/opt/delivery/elasticsearch/data/ ${pkg_prefix}/var/opt/delivery/elasticsearch/data rsync -chaz /src/var/opt/delivery/delivery/ ${pkg_prefix}/var/opt/delivery/delivery rsync -chaz /src/var/opt/delivery/compliance/profiles/ ${pkg_prefix}/var/opt/delivery/compliance/profiles rsync -chaz /src/var/opt/delivery/notifications/ ${pkg_prefix}/var/opt/delivery/notifications rsync -chaz /src/var/opt/delivery/delivery/git_repos/ ${pkg_prefix}/var/opt/delivery/delivery/git_repos if [ -d /src/etc/opscode ]; then mkdir -p ${pkg_prefix}/etc/opscode/ mkdir -p ${pkg_prefix}/var/opt/opscode/upgrades rsync -chaz /src/etc/opscode/ ${pkg_prefix}/etc/opscode rsync -chaz /src/var/opt/opscode/upgrades/ ${pkg_prefix}/var/opt/opscode/upgrades touch ${pkg_prefix}/var/opt/opscode/bootstrapped fi }
{ "pile_set_name": "Github" }
/* Part of SWI-Prolog Author: Jan Wielemaker E-mail: [email protected] WWW: http://www.swi-prolog.org Copyright (c) 2020, VU University Amsterdam CWI, Amsterdam 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ :- module(hashtable, [ ht_new/1, % --HT ht_is_hashtable/1, % @HT ht_size/2, % +HT, -Size ht_put/3, % !HT, +Key, +Value ht_update/4, % +HT, +Key, ?Old, +New ht_put_new/3, % !HT, +Key, +Value ht_put/5, % !HT, +Key, +Value, +IfNew, -Old ht_del/3, % !HT, +Key, -Value ht_get/3, % +HT, +Key, -Value ht_gen/3, % +HT, ?Key, ?Value ht_pairs/2, % ?HT, ?Pairs ht_keys/2 % +HT, -Keys ]). :- autoload(library(error), [must_be/2]). /** <module> Hash tables Hash tables are one of the many key-value representations available to SWI-Prolog. This module implements a hash table as a _mutable_ and _backtrackable_ data structure. The hash table is implemented as a _closed hash table_, where the _buckets_ array is implemented using an unbounded arity compound term. Elements in this array are manipulated using setarg/3. Hash tables allow for any Prolog data types as keys or values, except that the key cannot be a variable. Applications that require a plain variable as key can do so by wrapping all keys in a compound, e.g., k(Var). */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Data structure ht(Load, Size, Table) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ %! ht_new(--HT) % % Create a new hash table. ht_new(ht(0,0,[](_))). %! ht_is_hashtable(@HT) is semidet. % % True when HT is a hash table. ht_is_hashtable(HT) :- nonvar(HT), HT = ht(Load, Size, Buckets), integer(Load), integer(Size), compound_name_arity(Buckets, [], Arity), Arity =:= Size*2+1. %! ht_size(+HT, -Count) is det. % % True when Size is the number of key-value pairs in HT. ht_size(ht(Count, _Size, _Buckets), Count). %! ht_put(!HT, +Key, +Value) is det. % % Add a Key-Value to HT. The binding is undone on backtracking. ht_put(HT, Key, Value) :- must_be(nonvar, Key), ht_put(HT, Key, Value, _, _, _). %! ht_put_new(!HT, +Key, +Value) is semidet. % % As ht_put/3, but fails if Key is already in HT instead of updating % the associated value. ht_put_new(HT, Key, Value) :- must_be(nonvar, Key), ht_put(HT, Key, Value, _, _, true). %! ht_update(+HT, +Key, ?Old, +New) is semidet. % % True when HT holds Key-Old before and Key-New after this call. Note % that it is possible to update to a variable and the instantiate % this. For example, a word-count update could be implemented as: % % ``` % update_word_count(HT, Word) :- % ( ht_update(HT, Word, Old, New) % -> New is Old+1 % ; ht_put(HT, Word, 1) % ). % ``` ht_update(HT, Key, Old, New) :- must_be(nonvar, Key), ht_put(HT, Key, New, _, Old, false). %! ht_put(!HT, +Key, +Value, +IfNew, -Old) is det. % % Add Key-Value to HT. Old is unified with the old value associated % with Key or, if Key is new, with IfNew. This can be used to % bootstrap managing a list of values, e.g. % % ht_put_list(HT, Key, Value) :- % ht_put(HT, Key, [Value|Tail], [], Tail). ht_put(HT, Key, Value, IfNew, Old) :- must_be(nonvar, Key), ht_put(HT, Key, Value, IfNew, Old, _). ht_put(HT, Key, Value, IfNew, Old, IsNew) :- HT = ht(Load, Size, Buckets), ( Load >= Size//2 -> ht_resize(HT), ht_put(HT, Key, Value, IfNew, Old, IsNew) ; variant_hash(Key, I0), I is I0 mod Size, put_(Buckets, I, Size, Key, Old, IfNew, Value, IsNew), ( IsNew == true -> Load2 is Load+1, setarg(1, HT, Load2) ; true ) ). put_(Buckets, I, Size, Key, Old, IfNew, Value, IsNew) :- ht_kv(Buckets, I, K, V), ( var(K) -> IsNew = true, Old = IfNew, K = Key, V = Value ; K == Key -> IsNew = false, Old = V, ht_put_v(Buckets, I, Value) ; I2 is (I+1) mod Size, put_(Buckets, I2, Size, Key, Old, IfNew, Value, IsNew) ). ht_resize(HT) :- HT = ht(_Load, Size, Buckets), NewSize is max(4, Size*2), NewArity is NewSize*2+1, compound_name_arity(NewBuckets, [], NewArity), copy_members(0, Size, Buckets, NewSize, NewBuckets), setarg(2, HT, NewSize), setarg(3, HT, NewBuckets). copy_members(I, OSize, OBuckets, NSize, NBuckets) :- I < OSize, !, ht_kv(OBuckets, I, K, V), ( nonvar(K) -> variant_hash(K, I0), NI is I0 mod NSize, copy_(NBuckets, NI, NSize, K, V) ; true ), I2 is I+1, copy_members(I2, OSize, OBuckets, NSize, NBuckets). copy_members(_, _, _, _, _). copy_(Buckets, I, Size, Key, Value) :- ht_kv(Buckets, I, K, V), ( var(K) -> K = Key, V = Value ; I2 is (I+1) mod Size, copy_(Buckets, I2, Size, Key, Value) ). %! ht_del(!HT, +Key, -Value) is semidet. % % Delete Key-Value from HT. Fails if Key does not appear in HT or % Value does not unify with the old associated value. ht_del(HT, Key, Value) :- must_be(nonvar, Key), HT = ht(Load, Size, Buckets), Load > 0, variant_hash(Key, I0), I is I0 mod Size, del_(Buckets, I, Size, Key, Value), Load2 is Load - 1, setarg(1, HT, Load2). del_(Buckets, I, Size, Key, Value) :- ht_kv(Buckets, I, K, V), ( var(K) -> fail ; K == Key -> V = Value, ht_put_kv(Buckets, I, _, _), del_shift(Buckets, I, I, Size) ; I2 is (I+1) mod Size, del_(Buckets, I2, Size, Key, Value) ). del_shift(Buckets, I0, J, Size) :- I is (I0+1) mod Size, ht_kv(Buckets, I, K, V), ( var(K) -> true ; variant_hash(K, Hash), R is Hash mod Size, ( ( I >= R, R > J ; R > J, J > I ; J > I, I >= R ) -> del_shift(Buckets, I, J, Size) ; ht_put_kv(Buckets, J, K, V), ht_put_kv(Buckets, I, _, _), del_shift(Buckets, I, I, Size) ) ). %! ht_get(+HT, +Key, -Value) is semidet. % % True when Key is in HT and associated with Value. ht_get(ht(Load, Size, Buckets), Key, Value) :- Load > 0, must_be(nonvar, Key), variant_hash(Key, I0), I is I0 mod Size, get_(Buckets, I, Size, Key, Value). get_(Buckets, I, Size, Key, Value) :- ht_kv(Buckets, I, K, V), ( Key == K -> Value = V ; nonvar(K) -> I2 is (I+1) mod Size, get_(Buckets, I2, Size, Key, Value) ). ht_k(Buckets, I, K) :- IK is I*2+1, arg(IK, Buckets, K). ht_kv(Buckets, I, K, V) :- IK is I*2+1, IV is IK+1, arg(IK, Buckets, K), arg(IV, Buckets, V). ht_put_kv(Buckets, I, K, V) :- IK is I*2+1, IV is IK+1, setarg(IK, Buckets, K), setarg(IV, Buckets, V). ht_put_v(Buckets, I, V) :- IV is I*2+2, setarg(IV, Buckets, V). %! ht_gen(+HT, ?Key, ?Value) is nondet. % % True when Key-Value is in HT. Pairs are enumerated on backtracking % using the hash table order. ht_gen(HT, Key, Value) :- HT = ht(_, Size, Buckets), End is Size - 1, between(0, End, I), ht_kv(Buckets, I, K, V), nonvar(K), K = Key, V = Value. %! ht_pairs(?HT, ?Pairs) is det. % % True when Pairs and HT represent the same association. When used in % mode (+,-), Pairs is an ordered set. ht_pairs(HT, Pairs) :- ht_is_hashtable(HT), !, HT = ht(_Load, Size, Buckets), pairs_(0, Size, Buckets, Pairs0), sort(Pairs0, Pairs). ht_pairs(HT, Pairs) :- must_be(list(pair), Pairs), ht_new(HT), ht_fill(Pairs, HT). pairs_(I, Size, Buckets, Pairs) :- ( I < Size -> ht_kv(Buckets, I, K, V), ( nonvar(K) -> Pairs = [K-V|T], I2 is I+1, pairs_(I2, Size, Buckets, T) ; I2 is I+1, pairs_(I2, Size, Buckets, Pairs) ) ; Pairs = [] ). ht_fill([], _). ht_fill([K-V|T], HT) :- ht_put(HT, K, V), ht_fill(T, HT). %! ht_keys(+HT, -Keys) is det. % % True when Keys is an ordered set of all keys in HT. ht_keys(HT, Keys) :- HT = ht(_Load, Size, Buckets), keys_(0, Size, Buckets, Keys0), sort(Keys0, Keys). keys_(I, Size, Buckets, Keys) :- ( I < Size -> ht_k(Buckets, I, K), ( nonvar(K) -> Keys = [K|T], I2 is I+1, keys_(I2, Size, Buckets, T) ; I2 is I+1, keys_(I2, Size, Buckets, Keys) ) ; Keys = [] ).
{ "pile_set_name": "Github" }
package com.example.nanchen.aiyaschoolpush.ui.activity; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import com.example.nanchen.aiyaschoolpush.App; import com.example.nanchen.aiyaschoolpush.AppService; import com.example.nanchen.aiyaschoolpush.R; import com.example.nanchen.aiyaschoolpush.config.Consts; import com.example.nanchen.aiyaschoolpush.db.DemoDBManager; import com.example.nanchen.aiyaschoolpush.helper.DemoHelper; import com.example.nanchen.aiyaschoolpush.helper.QiYuCloudServerHelper; import com.example.nanchen.aiyaschoolpush.model.User; import com.example.nanchen.aiyaschoolpush.net.okgo.JsonCallback; import com.example.nanchen.aiyaschoolpush.net.okgo.LslResponse; import com.example.nanchen.aiyaschoolpush.ui.view.IcomoonTextView; import com.example.nanchen.aiyaschoolpush.utils.IntentUtil; import com.example.nanchen.aiyaschoolpush.utils.UIUtil; import com.hyphenate.EMCallBack; import com.hyphenate.chat.EMClient; import com.hyphenate.easeui.utils.EaseCommonUtils; import com.xiaomi.mipush.sdk.MiPushClient; import java.util.List; import okhttp3.Call; import okhttp3.Response; public class LoginActivity extends ActivityBase implements OnClickListener { private EditText mEditUserName; private EditText mEditPwd; private Button mBtnLogin; private LinearLayout mLinearRegister; private IcomoonTextView mTextFindPwd; private boolean autoLogin = false; private static final String TAG = "LoginActivity"; private SharedPreferences sp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); List<String> stringList = MiPushClient.getAllAlias(App.getAppContext()); Log.e("pushtest", "run: size:"+stringList.size() ); for (int i = 0; i < stringList.size(); i++) { Log.e("pushtest", "stringList,"+i +"=> "+stringList.get(i) ); } sp = getSharedPreferences("user.temp",MODE_PRIVATE); if (DemoHelper.getInstance().isLoggedIn()) { autoLogin = true; String username = sp.getString("username",""); String password = sp.getString("password",""); AppService.getInstance().loginAsync(username, password, new JsonCallback<LslResponse<User>>() { @Override public void onSuccess(LslResponse<User> userLslResponse, Call call, Response response) { if (userLslResponse.code == LslResponse.RESPONSE_OK){ setUserInfo(userLslResponse.data); IntentUtil.newIntent(LoginActivity.this, MainActivity.class); LoginActivity.this.finish(); return; } UIUtil.showToast("当前用户登录信息已过期,请重新登录!"); } }); } setContentView(R.layout.activity_login); bindView(); setListener(); } private void setListener() { mBtnLogin.setOnClickListener(this); mLinearRegister.setOnClickListener(this); mTextFindPwd.setOnClickListener(this); } private void bindView() { mEditUserName = (EditText) findViewById(R.id.login_edt_username); mEditPwd = (EditText) findViewById(R.id.login_edt_pwd); mBtnLogin = (Button) findViewById(R.id.login_btn_login); mLinearRegister = (LinearLayout) findViewById(R.id.linear_layout_btn_register); mTextFindPwd = (IcomoonTextView) findViewById(R.id.login_find_pwd); // if user changed, clear the password mEditUserName.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { mEditPwd.setText(null); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { } }); if (DemoHelper.getInstance().getCurrentUserName() != null) { mEditUserName.setText(DemoHelper.getInstance().getCurrentUserName()); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.login_btn_login: login(); break; case R.id.linear_layout_btn_register: IntentUtil.newIntent(this, RegisterActivity.class); // String phone1 = mEditUserName.getText().toString().trim(); // Intent intent1 = new Intent(this,RegisterActivity2.class); // intent1.putExtra("phone",phone1); // startActivity(intent1); break; case R.id.login_find_pwd: // UIUtil.showToast(this,"你点击了找回密码!"); String phone = mEditUserName.getText().toString().trim(); Intent intent = new Intent(this, ResetPwdActivity.class); intent.putExtra("phone", phone); startActivity(intent); break; } } private void login() { if (!EaseCommonUtils.isNetWorkConnected(this)) { UIUtil.showToast("网络连接不可用,请检查!"); return; } final String currentUsername = mEditUserName.getText().toString().trim(); final String currentPassword = mEditPwd.getText().toString().trim(); Log.e(TAG,"得到的用户名和密码:"+currentUsername+" --- "+currentPassword); if (TextUtils.isEmpty(currentUsername)) { UIUtil.showToast("用户名不能为空!"); return; } if (TextUtils.isEmpty(currentPassword)) { UIUtil.showToast("密码不能为空!"); return; } showLoading(this); AppService.getInstance().loginAsync(currentUsername, currentPassword, new JsonCallback<LslResponse<User>>() { @Override public void onSuccess(LslResponse<User> userLslResponse, Call call, Response response) { if (userLslResponse.code == LslResponse.RESPONSE_ERROR){ UIUtil.showToast(userLslResponse.msg); stopLoading(); }else{ setUserInfo(userLslResponse.data); Log.e(TAG,"登陆爱吖服务器成功!"); loginXin(currentUsername,currentPassword); } } }); } /** * 把信息存储起来 * @param data */ @SuppressWarnings("ConstantConditions") private void setUserInfo(User data) { Log.e(TAG,"username:"+data.username); Log.e(TAG,"password:"+data.password); Log.e(TAG,"birthday:"+data.birthday); Log.e(TAG,"nickname:"+data.nickname); Log.e(TAG,"type:"+data.type); Log.e(TAG,"classid:"+data.classid); Log.e(TAG,"address:"+data.address); Log.e(TAG,"childName:"+data.childName); if (!TextUtils.isEmpty(data.icon)){ data.icon = Consts.API_SERVICE_HOST+data.icon; } Log.e(TAG,"avatar:"+ data.icon); if (!TextUtils.isEmpty(data.childAvatar)){ data.childAvatar = Consts.API_SERVICE_HOST+data.childAvatar; } Log.e(TAG,"childAvatar:"+data.childAvatar); AppService.getInstance().setCurrentUser(data); MiPushClient.subscribe(App.getAppContext(),data.classid+"",null); MiPushClient.setAlias(App.getAppContext(),data.classid+"",null); Editor editor = sp.edit(); editor.putString("username",data.username); editor.putString("password",data.password); editor.putString("classid",data.classid+""); editor.apply(); } /** * 登录环信即时通讯需要 * @param currentUsername 当前输入的用户名 * @param currentPassword 密码 */ private void loginXin(String currentUsername,String currentPassword){ // After logout,the DemoDB may still be accessed due to async callback, so the DemoDB will be re-opened again. // close it before login to make sure DemoDB not overlap DemoDBManager.getInstance().closeDB(); // reset current user name before login DemoHelper.getInstance().setCurrentUserName(currentUsername); boolean flag = EMClient.getInstance().isLoggedInBefore(); Log.e(TAG, flag + " --------"); if (flag) { // 如果已经有登录用户,先调用登出 EMClient.getInstance().logout(false); } // go login 环信 EMClient.getInstance().login(currentUsername, currentPassword, new EMCallBack() { @Override public void onSuccess() { Log.d(TAG, "login: onSuccess"); // ** manually load all local groups and conversation EMClient.getInstance().groupManager().loadAllGroups(); EMClient.getInstance().chatManager().loadAllConversations(); // update current user's display name for APNs boolean updatenick = EMClient.getInstance().updateCurrentUserNick( App.currentUserNick.trim()); if (!updatenick) { Log.e("LoginActivity", "update current user nick fail"); } // get user's info (this should be get from App's server or 3rd party service) DemoHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo(); runOnUiThread(new Runnable() { @Override public void run() { UIUtil.showToast("登录成功!"); stopLoading(); } }); IntentUtil.newIntent(LoginActivity.this,MainActivity.class); finish(); } @Override public void onError(final int code, final String message) { Log.d(TAG, "login: onError: " + code); runOnUiThread(new Runnable() { @Override public void run() { stopLoading(); UIUtil.showToast("登陆IM失败:"+message+",code:"+code); } }); } @Override public void onProgress(final int code, final String message) { Log.d(TAG, "login: onProgress"); } }); } @Override protected void onResume() { super.onResume(); // 未登录状态下,清空用户信息 QiYuCloudServerHelper.setUserInfo(false); if (autoLogin){ return; } } }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rkr.simplekeyboard.inputmethod.latin.settings; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Color; import android.graphics.PorterDuff; import android.preference.DialogPreference; import android.util.AttributeSet; import android.view.View; import android.widget.SeekBar; import android.widget.TextView; import rkr.simplekeyboard.inputmethod.R; public final class ColorDialogPreference extends DialogPreference implements SeekBar.OnSeekBarChangeListener { public interface ValueProxy { int readValue(final String key); void writeDefaultValue(final String key); void writeValue(final int value, final String key); } private TextView mValueView; private SeekBar mSeekBarRed; private SeekBar mSeekBarGreen; private SeekBar mSeekBarBlue; private ValueProxy mValueProxy; public ColorDialogPreference(final Context context, final AttributeSet attrs) { super(context, attrs); setDialogLayoutResource(R.layout.color_dialog); } public void setInterface(final ValueProxy proxy) { mValueProxy = proxy; } @Override protected View onCreateDialogView() { final View view = super.onCreateDialogView(); mSeekBarRed = (SeekBar)view.findViewById(R.id.seek_bar_dialog_bar_red); mSeekBarRed.setMax(255); mSeekBarRed.setOnSeekBarChangeListener(this); mSeekBarRed.getProgressDrawable().setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN); mSeekBarRed.getThumb().setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN); mSeekBarGreen = (SeekBar)view.findViewById(R.id.seek_bar_dialog_bar_green); mSeekBarGreen.setMax(255); mSeekBarGreen.setOnSeekBarChangeListener(this); mSeekBarGreen.getThumb().setColorFilter(Color.GREEN, PorterDuff.Mode.SRC_IN); mSeekBarGreen.getProgressDrawable().setColorFilter(Color.GREEN, PorterDuff.Mode.SRC_IN); mSeekBarBlue = (SeekBar)view.findViewById(R.id.seek_bar_dialog_bar_blue); mSeekBarBlue.setMax(255); mSeekBarBlue.setOnSeekBarChangeListener(this); mSeekBarBlue.getThumb().setColorFilter(Color.BLUE, PorterDuff.Mode.SRC_IN); mSeekBarBlue.getProgressDrawable().setColorFilter(Color.BLUE, PorterDuff.Mode.SRC_IN); mValueView = (TextView)view.findViewById(R.id.seek_bar_dialog_value); return view; } @Override protected void onBindDialogView(final View view) { final int color = mValueProxy.readValue(getKey()); mSeekBarRed.setProgress(Color.red(color)); mSeekBarGreen.setProgress(Color.green(color)); mSeekBarBlue.setProgress(Color.blue(color)); setHeaderText(color); } @Override protected void onPrepareDialogBuilder(final AlertDialog.Builder builder) { builder.setPositiveButton(android.R.string.ok, this) .setNegativeButton(android.R.string.cancel, this) .setNeutralButton(R.string.button_default, this); } @Override public void onClick(final DialogInterface dialog, final int which) { super.onClick(dialog, which); final String key = getKey(); if (which == DialogInterface.BUTTON_POSITIVE) { super.onClick(dialog, which); final int value = Color.rgb( mSeekBarRed.getProgress(), mSeekBarGreen.getProgress(), mSeekBarBlue.getProgress()); mValueProxy.writeValue(value, key); return; } if (which == DialogInterface.BUTTON_NEUTRAL) { super.onClick(dialog, which); mValueProxy.writeDefaultValue(key); return; } } @Override public void onProgressChanged(final SeekBar seekBar, final int progress, final boolean fromUser) { int color = Color.rgb( mSeekBarRed.getProgress(), mSeekBarGreen.getProgress(), mSeekBarBlue.getProgress()); setHeaderText(color); if (!fromUser) { seekBar.setProgress(progress); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } private void setHeaderText(int color) { mValueView.setText(getValueText(color)); boolean bright = Color.red(color) + Color.green(color) + Color.blue(color) > 128 * 3; mValueView.setTextColor(bright ? Color.BLACK : Color.WHITE); mValueView.setBackgroundColor(color); } private String getValueText(final int value) { String temp = Integer.toHexString(value); for (; temp.length() < 8; temp = "0" + temp); return temp.substring(2).toUpperCase(); } }
{ "pile_set_name": "Github" }
<?php /** * PHPExcel * * Copyright (c) 2006 - 2014 PHPExcel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * @category PHPExcel * @package PHPExcel_Calculation * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL * @version ##VERSION##, ##DATE## */ /** PHPExcel root directory */ if (!defined('PHPEXCEL_ROOT')) { /** * @ignore */ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); } /** * PHPExcel_Calculation_Database * * @category PHPExcel * @package PHPExcel_Calculation * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) */ class PHPExcel_Calculation_Database { /** * __fieldExtract * * Extracts the column ID to use for the data field. * * @access private * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param mixed $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @return string|NULL * */ private static function __fieldExtract($database,$field) { $field = strtoupper(PHPExcel_Calculation_Functions::flattenSingleValue($field)); $fieldNames = array_map('strtoupper',array_shift($database)); if (is_numeric($field)) { $keys = array_keys($fieldNames); return $keys[$field-1]; } $key = array_search($field,$fieldNames); return ($key) ? $key : NULL; } /** * __filter * * Parses the selection criteria, extracts the database rows that match those criteria, and * returns that subset of rows. * * @access private * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * @return array of mixed * */ private static function __filter($database,$criteria) { $fieldNames = array_shift($database); $criteriaNames = array_shift($criteria); // Convert the criteria into a set of AND/OR conditions with [:placeholders] $testConditions = $testValues = array(); $testConditionsCount = 0; foreach($criteriaNames as $key => $criteriaName) { $testCondition = array(); $testConditionCount = 0; foreach($criteria as $row => $criterion) { if ($criterion[$key] > '') { $testCondition[] = '[:'.$criteriaName.']'.PHPExcel_Calculation_Functions::_ifCondition($criterion[$key]); $testConditionCount++; } } if ($testConditionCount > 1) { $testConditions[] = 'OR('.implode(',',$testCondition).')'; $testConditionsCount++; } elseif($testConditionCount == 1) { $testConditions[] = $testCondition[0]; $testConditionsCount++; } } if ($testConditionsCount > 1) { $testConditionSet = 'AND('.implode(',',$testConditions).')'; } elseif($testConditionsCount == 1) { $testConditionSet = $testConditions[0]; } // Loop through each row of the database foreach($database as $dataRow => $dataValues) { // Substitute actual values from the database row for our [:placeholders] $testConditionList = $testConditionSet; foreach($criteriaNames as $key => $criteriaName) { $k = array_search($criteriaName,$fieldNames); if (isset($dataValues[$k])) { $dataValue = $dataValues[$k]; $dataValue = (is_string($dataValue)) ? PHPExcel_Calculation::_wrapResult(strtoupper($dataValue)) : $dataValue; $testConditionList = str_replace('[:'.$criteriaName.']',$dataValue,$testConditionList); } } // evaluate the criteria against the row data $result = PHPExcel_Calculation::getInstance()->_calculateFormulaValue('='.$testConditionList); // If the row failed to meet the criteria, remove it from the database if (!$result) { unset($database[$dataRow]); } } return $database; } /** * DAVERAGE * * Averages the values in a column of a list or database that match conditions you specify. * * Excel Function: * DAVERAGE(database,field,criteria) * * @access public * @category Database Functions * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param string|integer $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * @return float * */ public static function DAVERAGE($database,$field,$criteria) { $field = self::__fieldExtract($database,$field); if (is_null($field)) { return NULL; } // reduce the database to a set of rows that match all the criteria $database = self::__filter($database,$criteria); // extract an array of values for the requested column $colData = array(); foreach($database as $row) { $colData[] = $row[$field]; } // Return return PHPExcel_Calculation_Statistical::AVERAGE($colData); } // function DAVERAGE() /** * DCOUNT * * Counts the cells that contain numbers in a column of a list or database that match conditions * that you specify. * * Excel Function: * DCOUNT(database,[field],criteria) * * Excel Function: * DAVERAGE(database,field,criteria) * * @access public * @category Database Functions * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param string|integer $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * @return integer * * @TODO The field argument is optional. If field is omitted, DCOUNT counts all records in the * database that match the criteria. * */ public static function DCOUNT($database,$field,$criteria) { $field = self::__fieldExtract($database,$field); if (is_null($field)) { return NULL; } // reduce the database to a set of rows that match all the criteria $database = self::__filter($database,$criteria); // extract an array of values for the requested column $colData = array(); foreach($database as $row) { $colData[] = $row[$field]; } // Return return PHPExcel_Calculation_Statistical::COUNT($colData); } // function DCOUNT() /** * DCOUNTA * * Counts the nonblank cells in a column of a list or database that match conditions that you specify. * * Excel Function: * DCOUNTA(database,[field],criteria) * * @access public * @category Database Functions * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param string|integer $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * @return integer * * @TODO The field argument is optional. If field is omitted, DCOUNTA counts all records in the * database that match the criteria. * */ public static function DCOUNTA($database,$field,$criteria) { $field = self::__fieldExtract($database,$field); if (is_null($field)) { return NULL; } // reduce the database to a set of rows that match all the criteria $database = self::__filter($database,$criteria); // extract an array of values for the requested column $colData = array(); foreach($database as $row) { $colData[] = $row[$field]; } // Return return PHPExcel_Calculation_Statistical::COUNTA($colData); } // function DCOUNTA() /** * DGET * * Extracts a single value from a column of a list or database that matches conditions that you * specify. * * Excel Function: * DGET(database,field,criteria) * * @access public * @category Database Functions * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param string|integer $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * @return mixed * */ public static function DGET($database,$field,$criteria) { $field = self::__fieldExtract($database,$field); if (is_null($field)) { return NULL; } // reduce the database to a set of rows that match all the criteria $database = self::__filter($database,$criteria); // extract an array of values for the requested column $colData = array(); foreach($database as $row) { $colData[] = $row[$field]; } // Return if (count($colData) > 1) { return PHPExcel_Calculation_Functions::NaN(); } return $colData[0]; } // function DGET() /** * DMAX * * Returns the largest number in a column of a list or database that matches conditions you that * specify. * * Excel Function: * DMAX(database,field,criteria) * * @access public * @category Database Functions * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param string|integer $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * @return float * */ public static function DMAX($database,$field,$criteria) { $field = self::__fieldExtract($database,$field); if (is_null($field)) { return NULL; } // reduce the database to a set of rows that match all the criteria $database = self::__filter($database,$criteria); // extract an array of values for the requested column $colData = array(); foreach($database as $row) { $colData[] = $row[$field]; } // Return return PHPExcel_Calculation_Statistical::MAX($colData); } // function DMAX() /** * DMIN * * Returns the smallest number in a column of a list or database that matches conditions you that * specify. * * Excel Function: * DMIN(database,field,criteria) * * @access public * @category Database Functions * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param string|integer $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * @return float * */ public static function DMIN($database,$field,$criteria) { $field = self::__fieldExtract($database,$field); if (is_null($field)) { return NULL; } // reduce the database to a set of rows that match all the criteria $database = self::__filter($database,$criteria); // extract an array of values for the requested column $colData = array(); foreach($database as $row) { $colData[] = $row[$field]; } // Return return PHPExcel_Calculation_Statistical::MIN($colData); } // function DMIN() /** * DPRODUCT * * Multiplies the values in a column of a list or database that match conditions that you specify. * * Excel Function: * DPRODUCT(database,field,criteria) * * @access public * @category Database Functions * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param string|integer $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * @return float * */ public static function DPRODUCT($database,$field,$criteria) { $field = self::__fieldExtract($database,$field); if (is_null($field)) { return NULL; } // reduce the database to a set of rows that match all the criteria $database = self::__filter($database,$criteria); // extract an array of values for the requested column $colData = array(); foreach($database as $row) { $colData[] = $row[$field]; } // Return return PHPExcel_Calculation_MathTrig::PRODUCT($colData); } // function DPRODUCT() /** * DSTDEV * * Estimates the standard deviation of a population based on a sample by using the numbers in a * column of a list or database that match conditions that you specify. * * Excel Function: * DSTDEV(database,field,criteria) * * @access public * @category Database Functions * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param string|integer $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * @return float * */ public static function DSTDEV($database,$field,$criteria) { $field = self::__fieldExtract($database,$field); if (is_null($field)) { return NULL; } // reduce the database to a set of rows that match all the criteria $database = self::__filter($database,$criteria); // extract an array of values for the requested column $colData = array(); foreach($database as $row) { $colData[] = $row[$field]; } // Return return PHPExcel_Calculation_Statistical::STDEV($colData); } // function DSTDEV() /** * DSTDEVP * * Calculates the standard deviation of a population based on the entire population by using the * numbers in a column of a list or database that match conditions that you specify. * * Excel Function: * DSTDEVP(database,field,criteria) * * @access public * @category Database Functions * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param string|integer $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * @return float * */ public static function DSTDEVP($database,$field,$criteria) { $field = self::__fieldExtract($database,$field); if (is_null($field)) { return NULL; } // reduce the database to a set of rows that match all the criteria $database = self::__filter($database,$criteria); // extract an array of values for the requested column $colData = array(); foreach($database as $row) { $colData[] = $row[$field]; } // Return return PHPExcel_Calculation_Statistical::STDEVP($colData); } // function DSTDEVP() /** * DSUM * * Adds the numbers in a column of a list or database that match conditions that you specify. * * Excel Function: * DSUM(database,field,criteria) * * @access public * @category Database Functions * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param string|integer $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * @return float * */ public static function DSUM($database,$field,$criteria) { $field = self::__fieldExtract($database,$field); if (is_null($field)) { return NULL; } // reduce the database to a set of rows that match all the criteria $database = self::__filter($database,$criteria); // extract an array of values for the requested column $colData = array(); foreach($database as $row) { $colData[] = $row[$field]; } // Return return PHPExcel_Calculation_MathTrig::SUM($colData); } // function DSUM() /** * DVAR * * Estimates the variance of a population based on a sample by using the numbers in a column * of a list or database that match conditions that you specify. * * Excel Function: * DVAR(database,field,criteria) * * @access public * @category Database Functions * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param string|integer $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * @return float * */ public static function DVAR($database,$field,$criteria) { $field = self::__fieldExtract($database,$field); if (is_null($field)) { return NULL; } // reduce the database to a set of rows that match all the criteria $database = self::__filter($database,$criteria); // extract an array of values for the requested column $colData = array(); foreach($database as $row) { $colData[] = $row[$field]; } // Return return PHPExcel_Calculation_Statistical::VARFunc($colData); } // function DVAR() /** * DVARP * * Calculates the variance of a population based on the entire population by using the numbers * in a column of a list or database that match conditions that you specify. * * Excel Function: * DVARP(database,field,criteria) * * @access public * @category Database Functions * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param string|integer $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * @return float * */ public static function DVARP($database,$field,$criteria) { $field = self::__fieldExtract($database,$field); if (is_null($field)) { return NULL; } // reduce the database to a set of rows that match all the criteria $database = self::__filter($database,$criteria); // extract an array of values for the requested column $colData = array(); foreach($database as $row) { $colData[] = $row[$field]; } // Return return PHPExcel_Calculation_Statistical::VARP($colData); } // function DVARP() } // class PHPExcel_Calculation_Database
{ "pile_set_name": "Github" }