text
stringlengths
2
100k
meta
dict
**To list account aliases** The following ``list-account-aliases`` command lists the aliases for the current account:: aws iam list-account-aliases Output:: "AccountAliases": [ "mycompany" ] For more information, see `Using an Alias for Your AWS Account ID`_ in the *Using IAM* guide. .. _`Using an Alias for Your AWS Account ID`: http://docs.aws.amazon.com/IAM/latest/UserGuide/AccountAlias.html
{ "pile_set_name": "Github" }
/* Copyright (C) 2017 Intel Corporation * * This program 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. * This file has been designated as subject to the "Classpath" * exception as provided in the LICENSE file that accompanied * this code. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License version 2 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 program; if not, write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ package lib.util.persistent.types; import lib.util.persistent.AnyPersistent; import lib.util.persistent.Bytes; import java.util.ArrayList; import java.util.HashMap; // public class BytesType extends ValueType { public class BytesType extends DirectValueObjectType<Bytes> { private static final HashMap<Long, BytesType> instances = new HashMap<>(); private long size; public static BytesType forSize(long size) { BytesType ans = instances.get(size); if (ans == null) { ans = new BytesType(size); instances.put(size, ans); System.out.println("added " + ans); } return ans; } public BytesType(long size) { // super(new ArrayList<>(), new long[0], size); super(Bytes.class, new ArrayList<>(), new long[0], size); this.size = size; } public long size() {return allocationSize();} public long allocationSize() { return size; } public long getByteCount() { return size; } public long offset(long index) { return index; } @Override public String toString() { return "BytesType(" + size() + ")"; } }
{ "pile_set_name": "Github" }
// Choreo version 1 actor "!target1" { channel "Audio" { } channel "lookAt" { event lookat "!player" { time 0.115384 3.282051 param "!player" event_ramp { 0.4300 0.8496 0.6880 1.0000 "curve_easein_to_curve_easeout" 2.0162 1.0000 2.3834 1.0000 "curve_easein_to_curve_easeout" 2.5937 0.8929 3.0697 0.0867 } } } channel "moveTo" { } channel "faceTo" { event face "!player" { time 0.217949 3.179488 param "!player" event_ramp { 0.3735 0.1438 "curve_catmullrom_normalize_x_to_curve_catmullrom_normalize_x" 1.3320 0.1750 "curve_easein_to_curve_easeout" 2.2415 0.1688 } lockbodyfacing } } channel "postures" { } channel "seq" { } channel "body" { } channel "gestures" { event gesture "g_weld_down" { time 0.038461 3.287181 param "g_weld_down" absolutetags playback_time { "in" 0.064430 "loop" 0.161076 "end" 0.689026 "out" 0.858330 } absolutetags shifted_time { "in" 0.147059 "loop" 0.367647 "end" 0.735294 "out" 0.955882 } sequenceduration 2.300000 } } channel "head" { } channel "facial" { } channel "trigger" { event firetrigger "1. spark off" { time 0.128205 -1.000000 param "1" } event firetrigger "2. spark on" { time 3.128205 -1.000000 param "2" } } } scalesettings { "SceneRampTool" "100" "RampTool" "58" "GestureTool" "100" "ExpressionTool" "100" "CChoreoView" "52" } fps 60 snap off ignorePhonemes off
{ "pile_set_name": "Github" }
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Copyright (c) 1997-2010 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge 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. ----------------------------------------------------------------------------- */ /* This module contains a PCRE private debugging function for printing out the internal form of a compiled regular expression, along with some supporting local functions. This source file is used in two places: (1) It is #included by pcre_compile.c when it is compiled in debugging mode (PCRE_DEBUG defined in pcre_internal.h). It is not included in production compiles. (2) It is always #included by pcretest.c, which can be asked to print out a compiled regex for debugging purposes. */ /* Macro that decides whether a character should be output as a literal or in hexadecimal. We don't use isprint() because that can vary from system to system (even without the use of locales) and we want the output always to be the same, for testing purposes. This macro is used in pcretest as well as in this file. */ #ifdef EBCDIC #define PRINTABLE(c) ((c) >= 64 && (c) < 255) #else #define PRINTABLE(c) ((c) >= 32 && (c) < 127) #endif /* The table of operator names. */ static const char *OP_names[] = { OP_NAME_LIST }; /************************************************* * Print single- or multi-byte character * *************************************************/ static int print_char(FILE *f, uschar *ptr, BOOL utf8) { int c = *ptr; #ifndef SUPPORT_UTF8 utf8 = utf8; /* Avoid compiler warning */ if (PRINTABLE(c)) fprintf(f, "%c", c); else fprintf(f, "\\x%02x", c); return 0; #else if (!utf8 || (c & 0xc0) != 0xc0) { if (PRINTABLE(c)) fprintf(f, "%c", c); else fprintf(f, "\\x%02x", c); return 0; } else { int i; int a = _pcre_utf8_table4[c & 0x3f]; /* Number of additional bytes */ int s = 6*a; c = (c & _pcre_utf8_table3[a]) << s; for (i = 1; i <= a; i++) { /* This is a check for malformed UTF-8; it should only occur if the sanity check has been turned off. Rather than swallow random bytes, just stop if we hit a bad one. Print it with \X instead of \x as an indication. */ if ((ptr[i] & 0xc0) != 0x80) { fprintf(f, "\\X{%x}", c); return i - 1; } /* The byte is OK */ s -= 6; c |= (ptr[i] & 0x3f) << s; } if (c < 128) fprintf(f, "\\x%02x", c); else fprintf(f, "\\x{%x}", c); return a; } #endif } /************************************************* * Find Unicode property name * *************************************************/ static const char * get_ucpname(int ptype, int pvalue) { #ifdef SUPPORT_UCP int i; for (i = _pcre_utt_size - 1; i >= 0; i--) { if (ptype == _pcre_utt[i].type && pvalue == _pcre_utt[i].value) break; } return (i >= 0)? _pcre_utt_names + _pcre_utt[i].name_offset : "??"; #else /* It gets harder and harder to shut off unwanted compiler warnings. */ ptype = ptype * pvalue; return (ptype == pvalue)? "??" : "??"; #endif } /************************************************* * Print compiled regex * *************************************************/ /* Make this function work for a regex with integers either byte order. However, we assume that what we are passed is a compiled regex. The print_lengths flag controls whether offsets and lengths of items are printed. They can be turned off from pcretest so that automatic tests on bytecode can be written that do not depend on the value of LINK_SIZE. */ static void pcre_printint(pcre *external_re, FILE *f, BOOL print_lengths) { real_pcre *re = (real_pcre *)external_re; uschar *codestart, *code; BOOL utf8; unsigned int options = re->options; int offset = re->name_table_offset; int count = re->name_count; int size = re->name_entry_size; if (re->magic_number != MAGIC_NUMBER) { offset = ((offset << 8) & 0xff00) | ((offset >> 8) & 0xff); count = ((count << 8) & 0xff00) | ((count >> 8) & 0xff); size = ((size << 8) & 0xff00) | ((size >> 8) & 0xff); options = ((options << 24) & 0xff000000) | ((options << 8) & 0x00ff0000) | ((options >> 8) & 0x0000ff00) | ((options >> 24) & 0x000000ff); } code = codestart = (uschar *)re + offset + count * size; utf8 = (options & PCRE_UTF8) != 0; for(;;) { uschar *ccode; int c; int extra = 0; if (print_lengths) fprintf(f, "%3d ", (int)(code - codestart)); else fprintf(f, " "); switch(*code) { /* ========================================================================== */ /* These cases are never obeyed. This is a fudge that causes a compile- time error if the vectors OP_names or _pcre_OP_lengths, which are indexed by opcode, are not the correct length. It seems to be the only way to do such a check at compile time, as the sizeof() operator does not work in the C preprocessor. We do this while compiling pcretest, because that #includes pcre_tables.c, which holds _pcre_OP_lengths. We can't do this when building pcre_compile.c with PCRE_DEBUG set, because it doesn't then know the size of _pcre_OP_lengths. */ #ifdef COMPILING_PCRETEST case OP_TABLE_LENGTH: case OP_TABLE_LENGTH + ((sizeof(OP_names)/sizeof(const char *) == OP_TABLE_LENGTH) && (sizeof(_pcre_OP_lengths) == OP_TABLE_LENGTH)): break; #endif /* ========================================================================== */ case OP_END: fprintf(f, " %s\n", OP_names[*code]); fprintf(f, "------------------------------------------------------------------\n"); return; case OP_OPT: fprintf(f, " %.2x %s", code[1], OP_names[*code]); break; case OP_CHAR: fprintf(f, " "); do { code++; code += 1 + print_char(f, code, utf8); } while (*code == OP_CHAR); fprintf(f, "\n"); continue; case OP_CHARNC: fprintf(f, " NC "); do { code++; code += 1 + print_char(f, code, utf8); } while (*code == OP_CHARNC); fprintf(f, "\n"); continue; case OP_CBRA: case OP_SCBRA: if (print_lengths) fprintf(f, "%3d ", GET(code, 1)); else fprintf(f, " "); fprintf(f, "%s %d", OP_names[*code], GET2(code, 1+LINK_SIZE)); break; case OP_BRA: case OP_SBRA: case OP_KETRMAX: case OP_KETRMIN: case OP_ALT: case OP_KET: case OP_ASSERT: case OP_ASSERT_NOT: case OP_ASSERTBACK: case OP_ASSERTBACK_NOT: case OP_ONCE: case OP_COND: case OP_SCOND: case OP_REVERSE: if (print_lengths) fprintf(f, "%3d ", GET(code, 1)); else fprintf(f, " "); fprintf(f, "%s", OP_names[*code]); break; case OP_CLOSE: fprintf(f, " %s %d", OP_names[*code], GET2(code, 1)); break; case OP_CREF: case OP_NCREF: fprintf(f, "%3d %s", GET2(code,1), OP_names[*code]); break; case OP_RREF: c = GET2(code, 1); if (c == RREF_ANY) fprintf(f, " Cond recurse any"); else fprintf(f, " Cond recurse %d", c); break; case OP_NRREF: c = GET2(code, 1); if (c == RREF_ANY) fprintf(f, " Cond nrecurse any"); else fprintf(f, " Cond nrecurse %d", c); break; case OP_DEF: fprintf(f, " Cond def"); break; case OP_STAR: case OP_MINSTAR: case OP_POSSTAR: case OP_PLUS: case OP_MINPLUS: case OP_POSPLUS: case OP_QUERY: case OP_MINQUERY: case OP_POSQUERY: case OP_TYPESTAR: case OP_TYPEMINSTAR: case OP_TYPEPOSSTAR: case OP_TYPEPLUS: case OP_TYPEMINPLUS: case OP_TYPEPOSPLUS: case OP_TYPEQUERY: case OP_TYPEMINQUERY: case OP_TYPEPOSQUERY: fprintf(f, " "); if (*code >= OP_TYPESTAR) { fprintf(f, "%s", OP_names[code[1]]); if (code[1] == OP_PROP || code[1] == OP_NOTPROP) { fprintf(f, " %s ", get_ucpname(code[2], code[3])); extra = 2; } } else extra = print_char(f, code+1, utf8); fprintf(f, "%s", OP_names[*code]); break; case OP_EXACT: case OP_UPTO: case OP_MINUPTO: case OP_POSUPTO: fprintf(f, " "); extra = print_char(f, code+3, utf8); fprintf(f, "{"); if (*code != OP_EXACT) fprintf(f, "0,"); fprintf(f, "%d}", GET2(code,1)); if (*code == OP_MINUPTO) fprintf(f, "?"); else if (*code == OP_POSUPTO) fprintf(f, "+"); break; case OP_TYPEEXACT: case OP_TYPEUPTO: case OP_TYPEMINUPTO: case OP_TYPEPOSUPTO: fprintf(f, " %s", OP_names[code[3]]); if (code[3] == OP_PROP || code[3] == OP_NOTPROP) { fprintf(f, " %s ", get_ucpname(code[4], code[5])); extra = 2; } fprintf(f, "{"); if (*code != OP_TYPEEXACT) fprintf(f, "0,"); fprintf(f, "%d}", GET2(code,1)); if (*code == OP_TYPEMINUPTO) fprintf(f, "?"); else if (*code == OP_TYPEPOSUPTO) fprintf(f, "+"); break; case OP_NOT: c = code[1]; if (PRINTABLE(c)) fprintf(f, " [^%c]", c); else fprintf(f, " [^\\x%02x]", c); break; case OP_NOTSTAR: case OP_NOTMINSTAR: case OP_NOTPOSSTAR: case OP_NOTPLUS: case OP_NOTMINPLUS: case OP_NOTPOSPLUS: case OP_NOTQUERY: case OP_NOTMINQUERY: case OP_NOTPOSQUERY: c = code[1]; if (PRINTABLE(c)) fprintf(f, " [^%c]", c); else fprintf(f, " [^\\x%02x]", c); fprintf(f, "%s", OP_names[*code]); break; case OP_NOTEXACT: case OP_NOTUPTO: case OP_NOTMINUPTO: case OP_NOTPOSUPTO: c = code[3]; if (PRINTABLE(c)) fprintf(f, " [^%c]{", c); else fprintf(f, " [^\\x%02x]{", c); if (*code != OP_NOTEXACT) fprintf(f, "0,"); fprintf(f, "%d}", GET2(code,1)); if (*code == OP_NOTMINUPTO) fprintf(f, "?"); else if (*code == OP_NOTPOSUPTO) fprintf(f, "+"); break; case OP_RECURSE: if (print_lengths) fprintf(f, "%3d ", GET(code, 1)); else fprintf(f, " "); fprintf(f, "%s", OP_names[*code]); break; case OP_REF: fprintf(f, " \\%d", GET2(code,1)); ccode = code + _pcre_OP_lengths[*code]; goto CLASS_REF_REPEAT; case OP_CALLOUT: fprintf(f, " %s %d %d %d", OP_names[*code], code[1], GET(code,2), GET(code, 2 + LINK_SIZE)); break; case OP_PROP: case OP_NOTPROP: fprintf(f, " %s %s", OP_names[*code], get_ucpname(code[1], code[2])); break; /* OP_XCLASS can only occur in UTF-8 mode. However, there's no harm in having this code always here, and it makes it less messy without all those #ifdefs. */ case OP_CLASS: case OP_NCLASS: case OP_XCLASS: { int i, min, max; BOOL printmap; fprintf(f, " ["); if (*code == OP_XCLASS) { extra = GET(code, 1); ccode = code + LINK_SIZE + 1; printmap = (*ccode & XCL_MAP) != 0; if ((*ccode++ & XCL_NOT) != 0) fprintf(f, "^"); } else { printmap = TRUE; ccode = code + 1; } /* Print a bit map */ if (printmap) { for (i = 0; i < 256; i++) { if ((ccode[i/8] & (1 << (i&7))) != 0) { int j; for (j = i+1; j < 256; j++) if ((ccode[j/8] & (1 << (j&7))) == 0) break; if (i == '-' || i == ']') fprintf(f, "\\"); if (PRINTABLE(i)) fprintf(f, "%c", i); else fprintf(f, "\\x%02x", i); if (--j > i) { if (j != i + 1) fprintf(f, "-"); if (j == '-' || j == ']') fprintf(f, "\\"); if (PRINTABLE(j)) fprintf(f, "%c", j); else fprintf(f, "\\x%02x", j); } i = j; } } ccode += 32; } /* For an XCLASS there is always some additional data */ if (*code == OP_XCLASS) { int ch; while ((ch = *ccode++) != XCL_END) { if (ch == XCL_PROP) { int ptype = *ccode++; int pvalue = *ccode++; fprintf(f, "\\p{%s}", get_ucpname(ptype, pvalue)); } else if (ch == XCL_NOTPROP) { int ptype = *ccode++; int pvalue = *ccode++; fprintf(f, "\\P{%s}", get_ucpname(ptype, pvalue)); } else { ccode += 1 + print_char(f, ccode, TRUE); if (ch == XCL_RANGE) { fprintf(f, "-"); ccode += 1 + print_char(f, ccode, TRUE); } } } } /* Indicate a non-UTF8 class which was created by negation */ fprintf(f, "]%s", (*code == OP_NCLASS)? " (neg)" : ""); /* Handle repeats after a class or a back reference */ CLASS_REF_REPEAT: switch(*ccode) { case OP_CRSTAR: case OP_CRMINSTAR: case OP_CRPLUS: case OP_CRMINPLUS: case OP_CRQUERY: case OP_CRMINQUERY: fprintf(f, "%s", OP_names[*ccode]); extra += _pcre_OP_lengths[*ccode]; break; case OP_CRRANGE: case OP_CRMINRANGE: min = GET2(ccode,1); max = GET2(ccode,3); if (max == 0) fprintf(f, "{%d,}", min); else fprintf(f, "{%d,%d}", min, max); if (*ccode == OP_CRMINRANGE) fprintf(f, "?"); extra += _pcre_OP_lengths[*ccode]; break; /* Do nothing if it's not a repeat; this code stops picky compilers warning about the lack of a default code path. */ default: break; } } break; case OP_MARK: case OP_PRUNE_ARG: case OP_SKIP_ARG: fprintf(f, " %s %s", OP_names[*code], code + 2); extra += code[1]; break; case OP_THEN: if (print_lengths) fprintf(f, " %s %d", OP_names[*code], GET(code, 1)); else fprintf(f, " %s", OP_names[*code]); break; case OP_THEN_ARG: if (print_lengths) fprintf(f, " %s %d %s", OP_names[*code], GET(code, 1), code + 2 + LINK_SIZE); else fprintf(f, " %s %s", OP_names[*code], code + 2 + LINK_SIZE); extra += code[1+LINK_SIZE]; break; /* Anything else is just an item with no data*/ default: fprintf(f, " %s", OP_names[*code]); break; } code += _pcre_OP_lengths[*code] + extra; fprintf(f, "\n"); } } /* End of pcre_printint.src */
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <project name="TypeSDK" default="help"> <property file="local.properties" /> <property file="ant.properties" /> <property environment="env" /> <condition property="sdk.dir" value="${env.ANDROID_HOME}"> <isset property="env.ANDROID_HOME" /> </condition> <import file="replace_key.xml" optional="true" /> <loadproperties srcFile="project.properties" /> <fail message="sdk.dir is missing. Make sure to generate local.properties using 'android update project' or to inject it through the ANDROID_HOME environment variable." unless="sdk.dir" /> <import file="custom_rules.xml" optional="true" /> <import file="${sdk.dir}/tools/ant/build.xml" /> </project>
{ "pile_set_name": "Github" }
using Microsoft.VisualStudio.TestTools.UnitTesting; using SPMeta2.BuiltInDefinitions; using SPMeta2.Containers; using SPMeta2.Containers.Standard; using SPMeta2.Regression.Tests.Base; using SPMeta2.Regression.Tests.Impl.Scenarios.Base; using SPMeta2.Utils; using System; using System.Collections.Generic; using System.Linq; using System.Text; using SPMeta2.Containers.Services; using SPMeta2.Regression.Tests.Utils; using SPMeta2.Standard.Definitions.Taxonomy; using SPMeta2.Standard.Syntax; using SPMeta2.Syntax.Default; using SPMeta2.Syntax.Default.Modern; using ReflectionUtils = SPMeta2.Utils.ReflectionUtils; namespace SPMeta2.Regression.Tests.Impl.Scenarios { [TestClass] public class TaxonomyTermScenariousTest : SPMeta2RegresionScenarioTestBase { #region internal [ClassInitializeAttribute] public static void Init(TestContext context) { InternalInit(); } [ClassCleanupAttribute] public static void Cleanup() { InternalCleanup(); } #endregion #region default [TestCategory("Regression.Scenarios.Taxonomy.Term.CustomProperties")] [TestMethod] public void CanDeploy_TaxonomyTerms_WithCustomProperties() { var term = ModelGeneratorService.GetRandomDefinition<TaxonomyTermDefinition>(def => { def.CustomProperties.Add(new TaxonomyTermCustomProperty { Name = Rnd.String(), Value = Rnd.String() }); def.CustomProperties.Add(new TaxonomyTermCustomProperty { Name = Rnd.String(), Value = Rnd.HttpUrl() }); def.CustomProperties.Add(new TaxonomyTermCustomProperty { Name = Rnd.Int().ToString(), Value = Rnd.Int().ToString() }); }); var subTerm = ModelGeneratorService.GetRandomDefinition<TaxonomyTermDefinition>(def => { def.CustomProperties.Add(new TaxonomyTermCustomProperty { Name = Rnd.String(), Value = Rnd.String() }); def.CustomProperties.Add(new TaxonomyTermCustomProperty { Name = Rnd.String(), Value = Rnd.HttpUrl() }); def.CustomProperties.Add(new TaxonomyTermCustomProperty { Name = Rnd.Int().ToString(), Value = Rnd.Int().ToString() }); }); var model = SPMeta2Model .NewSiteModel(site => { site .AddRandomTermStore(store => { store.AddRandomTermGroup(group => { group.AddRandomTermSet(termSet => { termSet.AddTaxonomyTerm(term, t => { t.AddTaxonomyTerm(subTerm); }); }); }); }); }); TestModel(model); } [TestCategory("Regression.Scenarios.Taxonomy.Term")] [TestMethod] public void CanDeploy_TaxonomyTermByName() { var term = ModelGeneratorService.GetRandomDefinition<TaxonomyTermDefinition>(def => { }); var model = SPMeta2Model .NewSiteModel(site => { site .AddRandomTermStore(store => { store.AddRandomTermGroup(group => { group.AddRandomTermSet(termSet => { termSet.AddTaxonomyTerm(term); }); }); }); }); TestModel(model); } [TestCategory("Regression.Scenarios.Taxonomy.Term")] [TestMethod] public void CanDeploy_TaxonomyTermByNameAndId() { var term = ModelGeneratorService.GetRandomDefinition<TaxonomyTermDefinition>(def => { def.Id = Guid.NewGuid(); }); var model = SPMeta2Model .NewSiteModel(site => { site .AddRandomTermStore(store => { store.AddRandomTermGroup(group => { group.AddRandomTermSet(termSet => { termSet.AddTaxonomyTerm(term); }); }); }); }); TestModel(model); } #endregion #region special chars [TestCategory("Regression.Scenarios.Taxonomy.Term.SpecialChars")] [TestMethod] public void CanDeploy_TaxonomyTerm_With_Ampersand_And_DoubleQuotes() { var term1 = ModelGeneratorService.GetRandomDefinition<TaxonomyTermDefinition>(def => { def.Name = string.Format("1 - \"{0}\" & \"{1}\"", Rnd.String(), Rnd.String()); }); var term2 = ModelGeneratorService.GetRandomDefinition<TaxonomyTermDefinition>(def => { def.Name = string.Format("2 - \"{0}\" & \"{1}\"", Rnd.String(), Rnd.String()); }); var term3 = ModelGeneratorService.GetRandomDefinition<TaxonomyTermDefinition>(def => { def.Name = string.Format("3 - \"{0}\" & \"{1}\"", Rnd.String(), Rnd.String()); }); var term4 = ModelGeneratorService.GetRandomDefinition<TaxonomyTermDefinition>(def => { def.Name = string.Format("4 - \"{0} & \"{1}\"", Rnd.String(), Rnd.String()); }); var term5 = ModelGeneratorService.GetRandomDefinition<TaxonomyTermDefinition>(def => { def.Name = string.Format("5 - \"{0}\" & \"{1}\"", Rnd.String(), Rnd.String()); }); var isSameTerm = true; var model = SPMeta2Model .NewSiteModel(site => { site .AddRandomTermStore(store => { store.AddRandomTermGroup(group => { group.AddRandomTermSet(termSet => { termSet.AddTaxonomyTerm(term1); termSet.AddTaxonomyTerm(term2); termSet.AddTaxonomyTerm(term3, t3 => { t3.AddTaxonomyTerm(term4); t3.AddTaxonomyTerm(term5); }); }); }); }); }); TestModel(model); } #endregion } }
{ "pile_set_name": "Github" }
/* GStreamer * Copyright (C) 2007 David Schleef <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301, USA. */ /** * SECTION:element-appsrc * @title: appsrc * * The appsrc element can be used by applications to insert data into a * GStreamer pipeline. Unlike most GStreamer elements, Appsrc provides * external API functions. * * For the documentation of the API, please see the * <link linkend="gst-plugins-base-libs-appsrc">libgstapp</link> section in the * GStreamer Plugins Base Libraries documentation. */ /** * SECTION:element-appsink * @title: appsink * * Appsink is a sink plugin that supports many different methods for making * the application get a handle on the GStreamer data in a pipeline. Unlike * most GStreamer elements, Appsink provides external API functions. * * For the documentation of the API, please see the * <link linkend="gst-plugins-base-libs-appsink">libgstapp</link> section in * the GStreamer Plugins Base Libraries documentation. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <gst/gst.h> #include <gst/app/gstappsrc.h> #include <gst/app/gstappsink.h> #ifdef GSTREAMER_LITE gboolean plugin_init_app (GstPlugin * plugin) #else // GSTREAMER_LITE static gboolean plugin_init (GstPlugin * plugin) #endif // GSTREAMER_LITE { #ifndef GSTREAMER_LITE gst_element_register (plugin, "appsrc", GST_RANK_NONE, GST_TYPE_APP_SRC); #endif // GSTREAMER_LITE gst_element_register (plugin, "appsink", GST_RANK_NONE, GST_TYPE_APP_SINK); return TRUE; } #ifndef GSTREAMER_LITE GST_PLUGIN_DEFINE (GST_VERSION_MAJOR, GST_VERSION_MINOR, app, "Elements used to communicate with applications", plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN) #endif // GSTREAMER_LITE
{ "pile_set_name": "Github" }
#!/bin/sh # # docker-unikernel: Container side, using a rumprun unikernel as an example. # # Wait for host to configure network echo "INFO: Waiting for network..." inotifywait -e create -t 60 /dev if [ $? -ne 0 -o ! -c /dev/tap0 ]; then echo "ERROR: timed out waiting for network or no /dev/tap0 found" 1>&2 exit 1 fi # Check configuration. Verifies that the interface is in sync with that of # docker-unikernel. VTAPDEV=$(echo /sys/devices/virtual/net/vtap*) if [ \( ! -d "${VTAPDEV}" \) -o \( ! -f "${VTAPDEV}/address" \) ]; then echo "ERROR: macvtap device not found on container side" 1>&2 exit 1 fi if [ \( ! -f /ip \) -o \( ! -f /mask \) -o \( ! -f /gw \) ]; then echo "ERROR: interface mismatch (missing network config)" 1>&2 exit 1 fi # Rumprun unikernel configuration using host-provided ip, mask and gw. # If we have a resolv.conf, use its resolver via rumprun-setdns. NAMESERVER= [ -f /etc/resolv.conf ] && \ NAMESERVER=$(grep nameserver /etc/resolv.conf | cut -d ' ' -f2 | head -1) if [ -n "${NAMESERVER}" ]; then RUMPENV="\"env\": \"RUMPRUN_RESOLVER=${NAMESERVER}\"," else RUMPENV= fi RUMPENV=${RUMPENV}"\"env\": \"PHP_FCGI_MAX_REQUESTS=0\"," RUMPCONFIG=$(cat <<EOM { ${RUMPENV} "rc": [ { "bin": "rumprun-setdns", "argv": [ ] }, { "bin": "php", "argv": [ "-d", "session.save_path=/tmp", "-b", "8000" ] } ], "net": { "if": "vioif0", "type": "inet", "method": "static", "addr": "$(cat /ip)", "mask": "$(cat /mask)", "gw": "$(cat /gw)" }, "blk": { "source": "dev", "path": "/dev/ld0a", "fstype": "blk", "mountpoint": "/etc", }, "blk": { "source": "dev", "path": "/dev/ld1a", "fstype": "blk", "mountpoint": "/data", } } EOM ) RUMPCONFIG=$(echo "${RUMPCONFIG}" | sed -e 's/,/,,/g' | tr '\n' ' ') MAC=$(cat ${VTAPDEV}/address) # Run the unikernel. exec qemu-system-x86_64 \ -m 256M \ -enable-kvm \ -cpu host,migratable=no,+invtsc \ -vga none -nographic \ -kernel ./php.bin \ -net nic,model=virtio,macaddr=${MAC} \ -net tap,fd=3 \ -drive if=virtio,file=etc.iso,format=raw \ -drive if=virtio,file=data.ffs,format=raw \ -append "${RUMPCONFIG}" \ 3<>/dev/tap0
{ "pile_set_name": "Github" }
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck {struct y{struct a{class B{typealias e=c}}struct c<T where T:b enum a{func b func b<T:T.a
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html> <!-- Copyright 2010 The Closure Library Authors. All Rights Reserved. Use of this source code is governed by the Apache License, Version 2.0. See the COPYING file for details. --> <head> <title>goog.ui.Select &amp; goog.ui.Option</title> <script src="../base.js"></script> <script> goog.require('goog.array'); goog.require('goog.debug.DivConsole'); goog.require('goog.debug.LogManager'); goog.require('goog.events'); goog.require('goog.events.EventType'); goog.require('goog.log'); goog.require('goog.object'); goog.require('goog.ui.Component.EventType'); goog.require('goog.ui.FlatMenuButtonRenderer'); goog.require('goog.ui.Option'); goog.require('goog.ui.Select'); goog.require('goog.ui.Separator'); goog.require('goog.ui.decorate'); </script> <link rel="stylesheet" href="css/demo.css"> <link rel="stylesheet" href="../css/menubutton.css"> <link rel="stylesheet" href="../css/menu.css"> <link rel="stylesheet" href="../css/menuitem.css"> <link rel="stylesheet" href="../css/menuseparator.css"> <link rel="stylesheet" href="../css/flatmenubutton.css"> <style> .good { color: #080; vertical-align: middle; } .bad { color: #800; vertical-align: middle; } </style> </head> <body> <h1>goog.ui.Select &amp; goog.ui.Option</h1> <fieldset> <legend>Demo of the <strong>goog.ui.Select</strong> component:</legend> <br> <label id="select1">The best movie of all time is </label>&nbsp; <span class="good" id="value1"></span> <br> <br> <label id="select2">The worst movie of all time is </label>&nbsp; <span class="bad" id="value2"></span> <br> <br> <label id="select3">The <strong>Select</strong> component for worst movie is </label>&nbsp;<i>(This control doesn't auto-highlight; it only dispatches ENTER and LEAVE events.)</i> <br> <br> <a id="add" href="#">Click here</a> to add a new option for the best movie, <a id="hide" href="#">here</a> to hide/show the select component for the best movie, or <a id="worst" href="#">here</a> to set the worst movie of all time to "Catwoman." <br> </fieldset> <br> <fieldset> <legend>This <strong>goog.ui.Select</strong> was decorated:</legend> <br> <label> My favorite Sergio Leone character is <div id="spaghetti" class="goog-select"> Make your choice... <ul class="goog-menu"> <li class="goog-menuitem">the Good</li> <li class="goog-menuitem">the Bad</li> <li class="goog-menuitem">the Ugly</li> <li class="goog-menuitem">the Man with the Harmonica</li> </ul> </div> </label>&nbsp; <span class="good" id="value4"></span> <br> <br> </fieldset> <br> <br> <fieldset> <legend> Demo of <strong>goog.ui.Select</strong> using <strong>goog.ui.FlatMenuButtonRenderer</strong>: </legend> <br> <label id="flat-select1">The best Arnold movie is </label>&nbsp; <span class="good" id="flat-value1"></span> <br> <br> <label id="flat-select2">The worst Arnold movie is </label>&nbsp; <span class="bad" id="flat-value2"></span> <br> <br> <label id="flat-select3"> The <strong>Select</strong> component for worst movie is </label>&nbsp;<i>(This control doesn't auto-highlight; it only dispatches ENTER and LEAVE events.)</i> <br> <br> <a id="flat-add" href="#">Click here</a> to add a new option for the best Arnold movie, <a id="flat-hide" href="#">here</a> to hide/show the select component for the best Arnold movie, or <a id="flat-worst" href="#">here</a> to set the worst Arnold movie to "Jingle All the Way." <br> </fieldset> <br> <fieldset> <legend>This Flat <strong>goog.ui.Select</strong> was decorated:</legend> <br> <label> My favorite Will Ferrell character is <div id="flat-ferrell" class="goog-flat-menu-button"> Make your choice... <ul class="goog-menu"> <li class="goog-menuitem">Ron Burgundy</li> <li class="goog-menuitem">Chazz Reinhold</li> <li class="goog-menuitem">Chazz Michael Michaels</li> <li class="goog-menuitem">Ricky Bobby</li> </ul> </div> </label>&nbsp; <span class="good" id="flat-value4"></span> <br> <br> </fieldset> <br> <br> <!-- Event log. --> <fieldset class="goog-debug-panel"> <legend>Event Log</legend> <div id="log"></div> </fieldset> <br> <div id="perf"></div> <script> var timer = goog.now(); // Set up a logger. goog.debug.LogManager.getRoot().setLevel(goog.log.Level.ALL); var logger = goog.log.getLogger('demo'); var logconsole = new goog.debug.DivConsole(goog.dom.getElement('log')); logconsole.setCapturing(true); var EVENTS = goog.object.getValues(goog.ui.Component.EventType); goog.log.fine(logger, 'Listening for: ' + EVENTS.join(', ') + '.'); function logEvent(e) { var component = e.target; var caption = (typeof component.getCaption == 'function') ? component.getCaption() : component.getId(); goog.log.info(logger, '"' + caption + '" dispatched: ' + e.type); } var select1 = new goog.ui.Select(); select1.addItem(new goog.ui.MenuItem('Blade Runner')); select1.addItem(new goog.ui.MenuItem('Godfather Part II')); select1.addItem(new goog.ui.MenuItem('Citizen Kane')); select1.setSelectedIndex(0); select1.render(goog.dom.getElement('select1')); var select2 = new goog.ui.Select(); var disabledItem; select2.addItem(new goog.ui.Option('Transformers')); select2.addItem(new goog.ui.Option('Spider-Man 3')); select2.addItem(disabledItem = new goog.ui.Option('Howard the Duck')); select2.addItem(new goog.ui.Option('Catwoman')); disabledItem.setEnabled(false); select2.setValue('Spider-Man 3'); select2.render(goog.dom.getElement('select2')); var select3 = new goog.ui.Select('Click to select'); // Turn off auto-highlighting, just for fun. select3.setAutoStates(goog.ui.Component.State.HOVER, false); select3.addItem(new goog.ui.Option('enabled', true)); select3.addItem(new goog.ui.Option('disabled', false)); select3.render(goog.dom.getElement('select3')); select3.setSelectedIndex(0); goog.events.listen(select1, goog.ui.Component.EventType.ACTION, function(e) { var select = e.target; var value = 'Yay ' + select.getValue() + '!'; goog.dom.setTextContent(goog.dom.getElement('value1'), value); goog.dom.setTextContent(goog.dom.getElement('value2'), ''); }); goog.events.listen(select2, goog.ui.Component.EventType.ACTION, function(e) { var select = e.target; var value = 'Boo ' + select.getValue() + '...'; goog.dom.setTextContent(goog.dom.getElement('value2'), value); goog.dom.setTextContent(goog.dom.getElement('value1'), ''); }); goog.events.listen(select3, goog.ui.Component.EventType.ACTION, function(e) { var select = e.target; select2.setEnabled(select.getValue()); }); goog.events.listen(goog.dom.getElement('add'), goog.events.EventType.CLICK, function(e) { var good = prompt('What\'s another good movie...?'); if (select1.getItemCount() == 3) { select1.addItem(new goog.ui.Separator()); } select1.addItem(new goog.ui.MenuItem(good)); }); goog.events.listen(goog.dom.getElement('hide'), goog.events.EventType.CLICK, function(e) { select1.setVisible(!select1.isVisible()); }); goog.events.listen(goog.dom.getElement('worst'), goog.events.EventType.CLICK, function(e) { select2.setValue('Catwoman'); }); // Decorate an element with a Select control. var select4 = goog.ui.decorate(goog.dom.getElement('spaghetti')); goog.events.listen(select1, EVENTS, logEvent); goog.events.listen(select2, EVENTS, logEvent); goog.events.listen(select3, EVENTS, logEvent); goog.events.listen(select4, EVENTS, logEvent); // goog.ui.Select using goog.ui.FlatMenuButtonRenderer var flatSelect1 = new goog.ui.Select(null, null, goog.ui.FlatMenuButtonRenderer.getInstance()); flatSelect1.addItem(new goog.ui.MenuItem('Total Recall')); flatSelect1.addItem(new goog.ui.MenuItem('Kindergarten Cop')); flatSelect1.addItem(new goog.ui.MenuItem('Predator')); flatSelect1.setSelectedIndex(0); flatSelect1.render(goog.dom.getElement('flat-select1')); var flatSelect2 = new goog.ui.Select(null, null, goog.ui.FlatMenuButtonRenderer.getInstance()); var flatDisabledItem; flatSelect2.addItem(new goog.ui.Option('Conan the Barbarian')); flatSelect2.addItem(new goog.ui.Option('Last Action Hero')); flatSelect2.addItem( flatDisabledItem = new goog.ui.Option('Eraser')); flatSelect2.addItem(new goog.ui.Option('Jingle All the Way')); flatDisabledItem.setEnabled(false); flatSelect2.setValue('Last Action Hero'); flatSelect2.render(goog.dom.getElement('flat-select2')); var flatSelect3 = new goog.ui.Select('Click to select', null, goog.ui.FlatMenuButtonRenderer.getInstance()); // Turn off auto-highlighting, just for fun. flatSelect3.setAutoStates(goog.ui.Component.State.HOVER, false); flatSelect3.addItem(new goog.ui.Option('enabled', true)); flatSelect3.addItem(new goog.ui.Option('disabled', false)); flatSelect3.render(goog.dom.getElement('flat-select3')); flatSelect3.setSelectedIndex(0); goog.events.listen(flatSelect1, goog.ui.Component.EventType.ACTION, function(e) { var select = e.target; var value = 'Yay ' + select.getValue() + '!'; goog.dom.setTextContent(goog.dom.getElement('flat-value1'), value); goog.dom.setTextContent(goog.dom.getElement('flat-value2'), ''); }); goog.events.listen(flatSelect2, goog.ui.Component.EventType.ACTION, function(e) { var select = e.target; var value = 'Boo ' + select.getValue() + '...'; goog.dom.setTextContent(goog.dom.getElement('flat-value2'), value); goog.dom.setTextContent(goog.dom.getElement('flat-value1'), ''); }); goog.events.listen(flatSelect3, goog.ui.Component.EventType.ACTION, function(e) { var select = e.target; flatSelect2.setEnabled(select.getValue()); }); goog.events.listen(goog.dom.getElement('flat-add'), goog.events.EventType.CLICK, function(e) { var good = prompt('What\'s another good Arnold movie...?'); if (flatSelect1.getItemCount() == 3) { flatSelect1.addItem(new goog.ui.Separator()); } flatSelect1.addItem(new goog.ui.MenuItem(good)); }); goog.events.listen(goog.dom.getElement('flat-hide'), goog.events.EventType.CLICK, function(e) { flatSelect1.setVisible(!flatSelect1.isVisible()); }); goog.events.listen(goog.dom.getElement('flat-worst'), goog.events.EventType.CLICK, function(e) { flatSelect2.setValue('Jingle All the Way'); }); // Decorate an element with a Select control using FlatMenuButtonRenderer. var flatSelect4 = new goog.ui.Select(null, null, goog.ui.FlatMenuButtonRenderer.getInstance()); flatSelect4.decorate(goog.dom.getElement('flat-ferrell')); goog.events.listen(flatSelect1, EVENTS, logEvent); goog.events.listen(flatSelect2, EVENTS, logEvent); goog.events.listen(flatSelect3, EVENTS, logEvent); goog.events.listen(flatSelect4, EVENTS, logEvent); goog.dom.setTextContent(goog.dom.getElement('perf'), (goog.now() - timer) + 'ms'); </script> </body> </html>
{ "pile_set_name": "Github" }
/*- * #%L * jasmine-maven-plugin * %% * Copyright (C) 2010 - 2017 Justin Searls * %% * 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. * #L% */ package com.github.searls.jasmine.mojo; import com.github.searls.jasmine.config.JasmineConfiguration; import com.github.searls.jasmine.config.ServerConfiguration; import com.github.searls.jasmine.model.FileSystemReporter; import com.github.searls.jasmine.model.Reporter; import com.github.searls.jasmine.runner.ReporterType; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.MavenProject; import org.assertj.core.api.Assertions; import org.codehaus.plexus.resource.loader.FileResourceCreationException; import org.codehaus.plexus.resource.loader.ResourceNotFoundException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Optional; import static com.github.searls.jasmine.mojo.AbstractJasmineMojo.CUSTOM_RUNNER_CONFIGURATION_PARAM; import static com.github.searls.jasmine.mojo.AbstractJasmineMojo.CUSTOM_RUNNER_TEMPLATE_PARAM; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.equalTo; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.isNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class AbstractJasmineMojoTest { private static final String ENCODING = "UTF-8"; private static final String CUSTOM_RUNNER_TEMPLATE = "/my/super/sweet/template"; private static final String CUSTOM_RUNNER_CONFIGURATION = "/my/fancy/pants/config"; @Rule public ExpectedException expectedException = ExpectedException.none(); @Mock private File baseDir; @Mock private File targetDir; @Mock private File projectFile; @Mock private File parentProjectFile; @Mock private File sourceDirectory; @Mock private File specDirectory; @Mock private File customRunnerConfiguration; @Mock private MavenProject mavenProject; @Mock private ResourceRetriever resourceRetriever; @Mock private ReporterRetriever reporterRetriever; @InjectMocks private MockJasmineMojo mojo; @Before public void before() throws MojoExecutionException { mojo.setJsSrcDir(sourceDirectory); mojo.setJsTestSrcDir(specDirectory); mojo.setJasmineTargetDir(targetDir); mojo.setSourceEncoding(ENCODING); when(mavenProject.getBasedir()).thenReturn(baseDir); when(resourceRetriever.getResourceAsFile(anyString(), isNull(), eq(mavenProject))) .thenReturn(Optional.empty()); } @Test public void rethrowsMojoFailureExceptions() throws Exception { MojoFailureException mojoException = new MojoFailureException("mock exception"); mojo.setExceptionToThrow(mojoException); this.expectedException.expect(equalTo(mojoException)); mojo.execute(); } @Test public void wrapsNonMojoFailureExceptions() throws Exception { IOException ioException = new IOException("mock exception"); mojo.setExceptionToThrow(ioException); this.expectedException.expect(MojoExecutionException.class); this.expectedException.expectMessage("The jasmine-maven-plugin encountered an exception:"); this.expectedException.expectCause(equalTo(ioException)); mojo.execute(); } @Test public void setsSourceIncludes() throws Exception { mojo.execute(); assertThat(getJasmineConfig().getSources().getIncludes()).contains("**" + File.separator + "*.js"); } @Test public void setsSourceExcludes() throws Exception { mojo.execute(); assertThat(getJasmineConfig().getSources().getExcludes()).isEmpty(); } @Test public void setsSpecIncludes() throws Exception { mojo.execute(); assertThat(getJasmineConfig().getSpecs().getIncludes()).contains("**" + File.separator + "*.js"); } @Test public void setsSpecExcludes() throws Exception { mojo.execute(); assertThat(getJasmineConfig().getSpecs().getExcludes()).isEmpty(); } @Test public void testGetSourceEncoding() throws MojoFailureException, MojoExecutionException { mojo.execute(); assertThat(getJasmineConfig().getSourceEncoding()).isEqualTo(ENCODING); } @Test public void testGetCustomRunnerConfiguration() throws ResourceNotFoundException, MojoExecutionException, MojoFailureException, FileResourceCreationException { File configFile = mock(File.class); mojo.setCustomRunnerConfiguration(CUSTOM_RUNNER_CONFIGURATION); when(resourceRetriever.getResourceAsFile( CUSTOM_RUNNER_CONFIGURATION_PARAM, CUSTOM_RUNNER_CONFIGURATION, mavenProject )).thenReturn(Optional.of(configFile)); mojo.execute(); assertThat(getJasmineConfig().getCustomRunnerConfiguration()) .isPresent() .contains(configFile); } @Test public void testGetCustomRunnerTemplate() throws Exception { File templateFile = mock(File.class); mojo.setCustomRunnerTemplate(CUSTOM_RUNNER_TEMPLATE); when(resourceRetriever.getResourceAsFile(CUSTOM_RUNNER_TEMPLATE_PARAM, CUSTOM_RUNNER_TEMPLATE, mavenProject)) .thenReturn(Optional.of(templateFile)); mojo.execute(); assertThat(getJasmineConfig().getCustomRunnerTemplate()) .isPresent() .contains(templateFile); } @Test public void testGetReporters() throws ResourceNotFoundException, MojoExecutionException, MojoFailureException, FileResourceCreationException { List<Reporter> reporters = Collections.singletonList(mock(Reporter.class)); mojo.setReporters(reporters); when(reporterRetriever.retrieveReporters(reporters, mavenProject)).thenReturn(reporters); mojo.execute(); assertThat(getJasmineConfig().getReporters()).isEqualTo(reporters); } @Test public void testGetFileSystemReporters() throws ResourceNotFoundException, MojoExecutionException, MojoFailureException, FileResourceCreationException { List<FileSystemReporter> fsReporters = Collections.singletonList(mock(FileSystemReporter.class)); mojo.setFileSystemReporters(fsReporters); when(reporterRetriever.retrieveFileSystemReporters(fsReporters, targetDir, mavenProject)).thenReturn(fsReporters); mojo.execute(); assertThat(getJasmineConfig().getFileSystemReporters()).isEqualTo(fsReporters); } @Test public void testGetBaseDir() throws MojoFailureException, MojoExecutionException { when(this.mavenProject.getBasedir()).thenReturn(this.baseDir); mojo.execute(); assertThat(getJasmineConfig().getBasedir()).isEqualTo(this.baseDir); } @Test public void testGetMavenProject() { Assertions.assertThat(mojo.getProject()).isEqualTo(this.mavenProject); } @Test public void testGetAutoRefreshInterval() throws MojoFailureException, MojoExecutionException { mojo.setAutoRefreshInterval(5); mojo.execute(); Assertions.assertThat(getJasmineConfig().getAutoRefreshInterval()).isEqualTo(5); } private JasmineConfiguration getJasmineConfig() { return mojo.getJasmineConfiguration(); } static class MockJasmineMojo extends AbstractJasmineMojo { private ServerConfiguration serverConfiguration; private JasmineConfiguration jasmineConfiguration; private Exception exceptionToThrow; protected MockJasmineMojo(MavenProject mavenProject, ResourceRetriever resourceRetriever, ReporterRetriever reporterRetriever) { super(mavenProject, ReporterType.HtmlReporter, resourceRetriever, reporterRetriever); } @Override public void run(ServerConfiguration serverConfiguration, JasmineConfiguration jasmineConfiguration) throws Exception { this.serverConfiguration = serverConfiguration; this.jasmineConfiguration = jasmineConfiguration; if (this.exceptionToThrow != null) { throw this.exceptionToThrow; } } public MavenProject getProject() { return this.getMavenProject(); } public ServerConfiguration getServerConfiguration() { return serverConfiguration; } public JasmineConfiguration getJasmineConfiguration() { return this.jasmineConfiguration; } public void setExceptionToThrow(Exception exceptionToThrow) { this.exceptionToThrow = exceptionToThrow; } } }
{ "pile_set_name": "Github" }
/* Driver for Realtek PCI-Express card reader * * Copyright(c) 2009-2013 Realtek Semiconductor Corp. All rights reserved. * * 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, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see <http://www.gnu.org/licenses/>. * * Author: * Wei WANG ([email protected]) * Micky Ching ([email protected]) */ #include <linux/blkdev.h> #include <linux/kthread.h> #include <linux/sched.h> #include <linux/workqueue.h> #include <linux/kernel.h> #include "rtsx.h" #include "sd.h" #include "xd.h" #include "ms.h" void do_remaining_work(struct rtsx_chip *chip) { struct sd_info *sd_card = &(chip->sd_card); #ifdef XD_DELAY_WRITE struct xd_info *xd_card = &(chip->xd_card); #endif struct ms_info *ms_card = &(chip->ms_card); if (chip->card_ready & SD_CARD) { if (sd_card->seq_mode) { rtsx_set_stat(chip, RTSX_STAT_RUN); sd_card->cleanup_counter++; } else { sd_card->cleanup_counter = 0; } } #ifdef XD_DELAY_WRITE if (chip->card_ready & XD_CARD) { if (xd_card->delay_write.delay_write_flag) { rtsx_set_stat(chip, RTSX_STAT_RUN); xd_card->cleanup_counter++; } else { xd_card->cleanup_counter = 0; } } #endif if (chip->card_ready & MS_CARD) { if (CHK_MSPRO(ms_card)) { if (ms_card->seq_mode) { rtsx_set_stat(chip, RTSX_STAT_RUN); ms_card->cleanup_counter++; } else { ms_card->cleanup_counter = 0; } } else { #ifdef MS_DELAY_WRITE if (ms_card->delay_write.delay_write_flag) { rtsx_set_stat(chip, RTSX_STAT_RUN); ms_card->cleanup_counter++; } else { ms_card->cleanup_counter = 0; } #endif } } if (sd_card->cleanup_counter > POLLING_WAIT_CNT) sd_cleanup_work(chip); if (xd_card->cleanup_counter > POLLING_WAIT_CNT) xd_cleanup_work(chip); if (ms_card->cleanup_counter > POLLING_WAIT_CNT) ms_cleanup_work(chip); } void try_to_switch_sdio_ctrl(struct rtsx_chip *chip) { u8 reg1 = 0, reg2 = 0; rtsx_read_register(chip, 0xFF34, &reg1); rtsx_read_register(chip, 0xFF38, &reg2); dev_dbg(rtsx_dev(chip), "reg 0xFF34: 0x%x, reg 0xFF38: 0x%x\n", reg1, reg2); if ((reg1 & 0xC0) && (reg2 & 0xC0)) { chip->sd_int = 1; rtsx_write_register(chip, SDIO_CTRL, 0xFF, SDIO_BUS_CTRL | SDIO_CD_CTRL); rtsx_write_register(chip, PWR_GATE_CTRL, LDO3318_PWR_MASK, LDO_ON); } } #ifdef SUPPORT_SDIO_ASPM void dynamic_configure_sdio_aspm(struct rtsx_chip *chip) { u8 buf[12], reg; int i; for (i = 0; i < 12; i++) rtsx_read_register(chip, 0xFF08 + i, &buf[i]); rtsx_read_register(chip, 0xFF25, &reg); if ((memcmp(buf, chip->sdio_raw_data, 12) != 0) || (reg & 0x03)) { chip->sdio_counter = 0; chip->sdio_idle = 0; } else { if (!chip->sdio_idle) { chip->sdio_counter++; if (chip->sdio_counter >= SDIO_IDLE_COUNT) { chip->sdio_counter = 0; chip->sdio_idle = 1; } } } memcpy(chip->sdio_raw_data, buf, 12); if (chip->sdio_idle) { if (!chip->sdio_aspm) { dev_dbg(rtsx_dev(chip), "SDIO enter ASPM!\n"); rtsx_write_register(chip, ASPM_FORCE_CTL, 0xFC, 0x30 | (chip->aspm_level[1] << 2)); chip->sdio_aspm = 1; } } else { if (chip->sdio_aspm) { dev_dbg(rtsx_dev(chip), "SDIO exit ASPM!\n"); rtsx_write_register(chip, ASPM_FORCE_CTL, 0xFC, 0x30); chip->sdio_aspm = 0; } } } #endif void do_reset_sd_card(struct rtsx_chip *chip) { int retval; dev_dbg(rtsx_dev(chip), "%s: %d, card2lun = 0x%x\n", __func__, chip->sd_reset_counter, chip->card2lun[SD_CARD]); if (chip->card2lun[SD_CARD] >= MAX_ALLOWED_LUN_CNT) { clear_bit(SD_NR, &(chip->need_reset)); chip->sd_reset_counter = 0; chip->sd_show_cnt = 0; return; } chip->rw_fail_cnt[chip->card2lun[SD_CARD]] = 0; rtsx_set_stat(chip, RTSX_STAT_RUN); rtsx_write_register(chip, SDIO_CTRL, 0xFF, 0); retval = reset_sd_card(chip); if (chip->need_release & SD_CARD) return; if (retval == STATUS_SUCCESS) { clear_bit(SD_NR, &(chip->need_reset)); chip->sd_reset_counter = 0; chip->sd_show_cnt = 0; chip->card_ready |= SD_CARD; chip->card_fail &= ~SD_CARD; chip->rw_card[chip->card2lun[SD_CARD]] = sd_rw; } else { if (chip->sd_io || (chip->sd_reset_counter >= MAX_RESET_CNT)) { clear_bit(SD_NR, &(chip->need_reset)); chip->sd_reset_counter = 0; chip->sd_show_cnt = 0; } else { chip->sd_reset_counter++; } chip->card_ready &= ~SD_CARD; chip->card_fail |= SD_CARD; chip->capacity[chip->card2lun[SD_CARD]] = 0; chip->rw_card[chip->card2lun[SD_CARD]] = NULL; rtsx_write_register(chip, CARD_OE, SD_OUTPUT_EN, 0); if (!chip->ft2_fast_mode) card_power_off(chip, SD_CARD); if (chip->sd_io) { chip->sd_int = 0; try_to_switch_sdio_ctrl(chip); } else { disable_card_clock(chip, SD_CARD); } } } void do_reset_xd_card(struct rtsx_chip *chip) { int retval; dev_dbg(rtsx_dev(chip), "%s: %d, card2lun = 0x%x\n", __func__, chip->xd_reset_counter, chip->card2lun[XD_CARD]); if (chip->card2lun[XD_CARD] >= MAX_ALLOWED_LUN_CNT) { clear_bit(XD_NR, &(chip->need_reset)); chip->xd_reset_counter = 0; chip->xd_show_cnt = 0; return; } chip->rw_fail_cnt[chip->card2lun[XD_CARD]] = 0; rtsx_set_stat(chip, RTSX_STAT_RUN); rtsx_write_register(chip, SDIO_CTRL, 0xFF, 0); retval = reset_xd_card(chip); if (chip->need_release & XD_CARD) return; if (retval == STATUS_SUCCESS) { clear_bit(XD_NR, &(chip->need_reset)); chip->xd_reset_counter = 0; chip->card_ready |= XD_CARD; chip->card_fail &= ~XD_CARD; chip->rw_card[chip->card2lun[XD_CARD]] = xd_rw; } else { if (chip->xd_reset_counter >= MAX_RESET_CNT) { clear_bit(XD_NR, &(chip->need_reset)); chip->xd_reset_counter = 0; chip->xd_show_cnt = 0; } else { chip->xd_reset_counter++; } chip->card_ready &= ~XD_CARD; chip->card_fail |= XD_CARD; chip->capacity[chip->card2lun[XD_CARD]] = 0; chip->rw_card[chip->card2lun[XD_CARD]] = NULL; rtsx_write_register(chip, CARD_OE, XD_OUTPUT_EN, 0); if (!chip->ft2_fast_mode) card_power_off(chip, XD_CARD); disable_card_clock(chip, XD_CARD); } } void do_reset_ms_card(struct rtsx_chip *chip) { int retval; dev_dbg(rtsx_dev(chip), "%s: %d, card2lun = 0x%x\n", __func__, chip->ms_reset_counter, chip->card2lun[MS_CARD]); if (chip->card2lun[MS_CARD] >= MAX_ALLOWED_LUN_CNT) { clear_bit(MS_NR, &(chip->need_reset)); chip->ms_reset_counter = 0; chip->ms_show_cnt = 0; return; } chip->rw_fail_cnt[chip->card2lun[MS_CARD]] = 0; rtsx_set_stat(chip, RTSX_STAT_RUN); rtsx_write_register(chip, SDIO_CTRL, 0xFF, 0); retval = reset_ms_card(chip); if (chip->need_release & MS_CARD) return; if (retval == STATUS_SUCCESS) { clear_bit(MS_NR, &(chip->need_reset)); chip->ms_reset_counter = 0; chip->card_ready |= MS_CARD; chip->card_fail &= ~MS_CARD; chip->rw_card[chip->card2lun[MS_CARD]] = ms_rw; } else { if (chip->ms_reset_counter >= MAX_RESET_CNT) { clear_bit(MS_NR, &(chip->need_reset)); chip->ms_reset_counter = 0; chip->ms_show_cnt = 0; } else { chip->ms_reset_counter++; } chip->card_ready &= ~MS_CARD; chip->card_fail |= MS_CARD; chip->capacity[chip->card2lun[MS_CARD]] = 0; chip->rw_card[chip->card2lun[MS_CARD]] = NULL; rtsx_write_register(chip, CARD_OE, MS_OUTPUT_EN, 0); if (!chip->ft2_fast_mode) card_power_off(chip, MS_CARD); disable_card_clock(chip, MS_CARD); } } static void release_sdio(struct rtsx_chip *chip) { if (chip->sd_io) { rtsx_write_register(chip, CARD_STOP, SD_STOP | SD_CLR_ERR, SD_STOP | SD_CLR_ERR); if (chip->chip_insert_with_sdio) { chip->chip_insert_with_sdio = 0; if (CHECK_PID(chip, 0x5288)) rtsx_write_register(chip, 0xFE5A, 0x08, 0x00); else rtsx_write_register(chip, 0xFE70, 0x80, 0x00); } rtsx_write_register(chip, SDIO_CTRL, SDIO_CD_CTRL, 0); chip->sd_io = 0; } } void rtsx_power_off_card(struct rtsx_chip *chip) { if ((chip->card_ready & SD_CARD) || chip->sd_io) { sd_cleanup_work(chip); sd_power_off_card3v3(chip); } if (chip->card_ready & XD_CARD) { xd_cleanup_work(chip); xd_power_off_card3v3(chip); } if (chip->card_ready & MS_CARD) { ms_cleanup_work(chip); ms_power_off_card3v3(chip); } } void rtsx_release_cards(struct rtsx_chip *chip) { chip->int_reg = rtsx_readl(chip, RTSX_BIPR); if ((chip->card_ready & SD_CARD) || chip->sd_io) { if (chip->int_reg & SD_EXIST) sd_cleanup_work(chip); release_sd_card(chip); } if (chip->card_ready & XD_CARD) { if (chip->int_reg & XD_EXIST) xd_cleanup_work(chip); release_xd_card(chip); } if (chip->card_ready & MS_CARD) { if (chip->int_reg & MS_EXIST) ms_cleanup_work(chip); release_ms_card(chip); } } void rtsx_reset_cards(struct rtsx_chip *chip) { if (!chip->need_reset) return; rtsx_set_stat(chip, RTSX_STAT_RUN); rtsx_force_power_on(chip, SSC_PDCTL | OC_PDCTL); rtsx_disable_aspm(chip); if ((chip->need_reset & SD_CARD) && chip->chip_insert_with_sdio) clear_bit(SD_NR, &(chip->need_reset)); if (chip->need_reset & XD_CARD) { chip->card_exist |= XD_CARD; if (chip->xd_show_cnt >= MAX_SHOW_CNT) do_reset_xd_card(chip); else chip->xd_show_cnt++; } if (CHECK_PID(chip, 0x5288) && CHECK_BARO_PKG(chip, QFN)) { if (chip->card_exist & XD_CARD) { clear_bit(SD_NR, &(chip->need_reset)); clear_bit(MS_NR, &(chip->need_reset)); } } if (chip->need_reset & SD_CARD) { chip->card_exist |= SD_CARD; if (chip->sd_show_cnt >= MAX_SHOW_CNT) { rtsx_write_register(chip, RBCTL, RB_FLUSH, RB_FLUSH); do_reset_sd_card(chip); } else { chip->sd_show_cnt++; } } if (chip->need_reset & MS_CARD) { chip->card_exist |= MS_CARD; if (chip->ms_show_cnt >= MAX_SHOW_CNT) do_reset_ms_card(chip); else chip->ms_show_cnt++; } } void rtsx_reinit_cards(struct rtsx_chip *chip, int reset_chip) { rtsx_set_stat(chip, RTSX_STAT_RUN); rtsx_force_power_on(chip, SSC_PDCTL | OC_PDCTL); if (reset_chip) rtsx_reset_chip(chip); chip->int_reg = rtsx_readl(chip, RTSX_BIPR); if ((chip->int_reg & SD_EXIST) && (chip->need_reinit & SD_CARD)) { release_sdio(chip); release_sd_card(chip); wait_timeout(100); chip->card_exist |= SD_CARD; do_reset_sd_card(chip); } if ((chip->int_reg & XD_EXIST) && (chip->need_reinit & XD_CARD)) { release_xd_card(chip); wait_timeout(100); chip->card_exist |= XD_CARD; do_reset_xd_card(chip); } if ((chip->int_reg & MS_EXIST) && (chip->need_reinit & MS_CARD)) { release_ms_card(chip); wait_timeout(100); chip->card_exist |= MS_CARD; do_reset_ms_card(chip); } chip->need_reinit = 0; } #ifdef DISABLE_CARD_INT void card_cd_debounce(struct rtsx_chip *chip, unsigned long *need_reset, unsigned long *need_release) { u8 release_map = 0, reset_map = 0; chip->int_reg = rtsx_readl(chip, RTSX_BIPR); if (chip->card_exist) { if (chip->card_exist & XD_CARD) { if (!(chip->int_reg & XD_EXIST)) release_map |= XD_CARD; } else if (chip->card_exist & SD_CARD) { if (!(chip->int_reg & SD_EXIST)) release_map |= SD_CARD; } else if (chip->card_exist & MS_CARD) { if (!(chip->int_reg & MS_EXIST)) release_map |= MS_CARD; } } else { if (chip->int_reg & XD_EXIST) reset_map |= XD_CARD; else if (chip->int_reg & SD_EXIST) reset_map |= SD_CARD; else if (chip->int_reg & MS_EXIST) reset_map |= MS_CARD; } if (reset_map) { int xd_cnt = 0, sd_cnt = 0, ms_cnt = 0; int i; for (i = 0; i < (DEBOUNCE_CNT); i++) { chip->int_reg = rtsx_readl(chip, RTSX_BIPR); if (chip->int_reg & XD_EXIST) xd_cnt++; else xd_cnt = 0; if (chip->int_reg & SD_EXIST) sd_cnt++; else sd_cnt = 0; if (chip->int_reg & MS_EXIST) ms_cnt++; else ms_cnt = 0; wait_timeout(30); } reset_map = 0; if (!(chip->card_exist & XD_CARD) && (xd_cnt > (DEBOUNCE_CNT-1))) reset_map |= XD_CARD; if (!(chip->card_exist & SD_CARD) && (sd_cnt > (DEBOUNCE_CNT-1))) reset_map |= SD_CARD; if (!(chip->card_exist & MS_CARD) && (ms_cnt > (DEBOUNCE_CNT-1))) reset_map |= MS_CARD; } if (CHECK_PID(chip, 0x5288) && CHECK_BARO_PKG(chip, QFN)) rtsx_write_register(chip, HOST_SLEEP_STATE, 0xC0, 0x00); if (need_reset) *need_reset = reset_map; if (need_release) *need_release = release_map; } #endif void rtsx_init_cards(struct rtsx_chip *chip) { if (RTSX_TST_DELINK(chip) && (rtsx_get_stat(chip) != RTSX_STAT_SS)) { dev_dbg(rtsx_dev(chip), "Reset chip in polling thread!\n"); rtsx_reset_chip(chip); RTSX_CLR_DELINK(chip); } #ifdef DISABLE_CARD_INT card_cd_debounce(chip, &(chip->need_reset), &(chip->need_release)); #endif if (chip->need_release) { if (CHECK_PID(chip, 0x5288) && CHECK_BARO_PKG(chip, QFN)) { if (chip->int_reg & XD_EXIST) { clear_bit(SD_NR, &(chip->need_release)); clear_bit(MS_NR, &(chip->need_release)); } } if (!(chip->card_exist & SD_CARD) && !chip->sd_io) clear_bit(SD_NR, &(chip->need_release)); if (!(chip->card_exist & XD_CARD)) clear_bit(XD_NR, &(chip->need_release)); if (!(chip->card_exist & MS_CARD)) clear_bit(MS_NR, &(chip->need_release)); dev_dbg(rtsx_dev(chip), "chip->need_release = 0x%x\n", (unsigned int)(chip->need_release)); #ifdef SUPPORT_OCP if (chip->need_release) { if (chip->ocp_stat & (CARD_OC_NOW | CARD_OC_EVER)) rtsx_write_register(chip, OCPCLR, CARD_OC_INT_CLR | CARD_OC_CLR, CARD_OC_INT_CLR | CARD_OC_CLR); chip->ocp_stat = 0; } #endif if (chip->need_release) { rtsx_set_stat(chip, RTSX_STAT_RUN); rtsx_force_power_on(chip, SSC_PDCTL | OC_PDCTL); } if (chip->need_release & SD_CARD) { clear_bit(SD_NR, &(chip->need_release)); chip->card_exist &= ~SD_CARD; chip->card_ejected &= ~SD_CARD; chip->card_fail &= ~SD_CARD; CLR_BIT(chip->lun_mc, chip->card2lun[SD_CARD]); chip->rw_fail_cnt[chip->card2lun[SD_CARD]] = 0; rtsx_write_register(chip, RBCTL, RB_FLUSH, RB_FLUSH); release_sdio(chip); release_sd_card(chip); } if (chip->need_release & XD_CARD) { clear_bit(XD_NR, &(chip->need_release)); chip->card_exist &= ~XD_CARD; chip->card_ejected &= ~XD_CARD; chip->card_fail &= ~XD_CARD; CLR_BIT(chip->lun_mc, chip->card2lun[XD_CARD]); chip->rw_fail_cnt[chip->card2lun[XD_CARD]] = 0; release_xd_card(chip); if (CHECK_PID(chip, 0x5288) && CHECK_BARO_PKG(chip, QFN)) rtsx_write_register(chip, HOST_SLEEP_STATE, 0xC0, 0xC0); } if (chip->need_release & MS_CARD) { clear_bit(MS_NR, &(chip->need_release)); chip->card_exist &= ~MS_CARD; chip->card_ejected &= ~MS_CARD; chip->card_fail &= ~MS_CARD; CLR_BIT(chip->lun_mc, chip->card2lun[MS_CARD]); chip->rw_fail_cnt[chip->card2lun[MS_CARD]] = 0; release_ms_card(chip); } dev_dbg(rtsx_dev(chip), "chip->card_exist = 0x%x\n", chip->card_exist); if (!chip->card_exist) turn_off_led(chip, LED_GPIO); } if (chip->need_reset) { dev_dbg(rtsx_dev(chip), "chip->need_reset = 0x%x\n", (unsigned int)(chip->need_reset)); rtsx_reset_cards(chip); } if (chip->need_reinit) { dev_dbg(rtsx_dev(chip), "chip->need_reinit = 0x%x\n", (unsigned int)(chip->need_reinit)); rtsx_reinit_cards(chip, 0); } } int switch_ssc_clock(struct rtsx_chip *chip, int clk) { int retval; u8 N = (u8)(clk - 2), min_N, max_N; u8 mcu_cnt, div, max_div, ssc_depth, ssc_depth_mask; int sd_vpclk_phase_reset = 0; if (chip->cur_clk == clk) return STATUS_SUCCESS; min_N = 60; max_N = 120; max_div = CLK_DIV_4; dev_dbg(rtsx_dev(chip), "Switch SSC clock to %dMHz (cur_clk = %d)\n", clk, chip->cur_clk); if ((clk <= 2) || (N > max_N)) { rtsx_trace(chip); return STATUS_FAIL; } mcu_cnt = (u8)(125/clk + 3); if (mcu_cnt > 7) mcu_cnt = 7; div = CLK_DIV_1; while ((N < min_N) && (div < max_div)) { N = (N + 2) * 2 - 2; div++; } dev_dbg(rtsx_dev(chip), "N = %d, div = %d\n", N, div); if (chip->ssc_en) { ssc_depth = 0x01; N -= 2; } else { ssc_depth = 0; } ssc_depth_mask = 0x03; dev_dbg(rtsx_dev(chip), "ssc_depth = %d\n", ssc_depth); rtsx_init_cmd(chip); rtsx_add_cmd(chip, WRITE_REG_CMD, CLK_CTL, CLK_LOW_FREQ, CLK_LOW_FREQ); rtsx_add_cmd(chip, WRITE_REG_CMD, CLK_DIV, 0xFF, (div << 4) | mcu_cnt); rtsx_add_cmd(chip, WRITE_REG_CMD, SSC_CTL1, SSC_RSTB, 0); rtsx_add_cmd(chip, WRITE_REG_CMD, SSC_CTL2, ssc_depth_mask, ssc_depth); rtsx_add_cmd(chip, WRITE_REG_CMD, SSC_DIV_N_0, 0xFF, N); rtsx_add_cmd(chip, WRITE_REG_CMD, SSC_CTL1, SSC_RSTB, SSC_RSTB); if (sd_vpclk_phase_reset) { rtsx_add_cmd(chip, WRITE_REG_CMD, SD_VPCLK0_CTL, PHASE_NOT_RESET, 0); rtsx_add_cmd(chip, WRITE_REG_CMD, SD_VPCLK0_CTL, PHASE_NOT_RESET, PHASE_NOT_RESET); } retval = rtsx_send_cmd(chip, 0, WAIT_TIME); if (retval < 0) { rtsx_trace(chip); return STATUS_ERROR; } udelay(10); retval = rtsx_write_register(chip, CLK_CTL, CLK_LOW_FREQ, 0); if (retval) { rtsx_trace(chip); return retval; } chip->cur_clk = clk; return STATUS_SUCCESS; } int switch_normal_clock(struct rtsx_chip *chip, int clk) { int retval; u8 sel, div, mcu_cnt; int sd_vpclk_phase_reset = 0; if (chip->cur_clk == clk) return STATUS_SUCCESS; switch (clk) { case CLK_20: dev_dbg(rtsx_dev(chip), "Switch clock to 20MHz\n"); sel = SSC_80; div = CLK_DIV_4; mcu_cnt = 7; break; case CLK_30: dev_dbg(rtsx_dev(chip), "Switch clock to 30MHz\n"); sel = SSC_120; div = CLK_DIV_4; mcu_cnt = 7; break; case CLK_40: dev_dbg(rtsx_dev(chip), "Switch clock to 40MHz\n"); sel = SSC_80; div = CLK_DIV_2; mcu_cnt = 7; break; case CLK_50: dev_dbg(rtsx_dev(chip), "Switch clock to 50MHz\n"); sel = SSC_100; div = CLK_DIV_2; mcu_cnt = 6; break; case CLK_60: dev_dbg(rtsx_dev(chip), "Switch clock to 60MHz\n"); sel = SSC_120; div = CLK_DIV_2; mcu_cnt = 6; break; case CLK_80: dev_dbg(rtsx_dev(chip), "Switch clock to 80MHz\n"); sel = SSC_80; div = CLK_DIV_1; mcu_cnt = 5; break; case CLK_100: dev_dbg(rtsx_dev(chip), "Switch clock to 100MHz\n"); sel = SSC_100; div = CLK_DIV_1; mcu_cnt = 5; break; case CLK_120: dev_dbg(rtsx_dev(chip), "Switch clock to 120MHz\n"); sel = SSC_120; div = CLK_DIV_1; mcu_cnt = 5; break; case CLK_150: dev_dbg(rtsx_dev(chip), "Switch clock to 150MHz\n"); sel = SSC_150; div = CLK_DIV_1; mcu_cnt = 4; break; case CLK_200: dev_dbg(rtsx_dev(chip), "Switch clock to 200MHz\n"); sel = SSC_200; div = CLK_DIV_1; mcu_cnt = 4; break; default: dev_dbg(rtsx_dev(chip), "Try to switch to an illegal clock (%d)\n", clk); rtsx_trace(chip); return STATUS_FAIL; } retval = rtsx_write_register(chip, CLK_CTL, 0xFF, CLK_LOW_FREQ); if (retval) { rtsx_trace(chip); return retval; } if (sd_vpclk_phase_reset) { retval = rtsx_write_register(chip, SD_VPCLK0_CTL, PHASE_NOT_RESET, 0); if (retval) { rtsx_trace(chip); return retval; } retval = rtsx_write_register(chip, SD_VPCLK1_CTL, PHASE_NOT_RESET, 0); if (retval) { rtsx_trace(chip); return retval; } } retval = rtsx_write_register(chip, CLK_DIV, 0xFF, (div << 4) | mcu_cnt); if (retval) { rtsx_trace(chip); return retval; } retval = rtsx_write_register(chip, CLK_SEL, 0xFF, sel); if (retval) { rtsx_trace(chip); return retval; } if (sd_vpclk_phase_reset) { udelay(200); retval = rtsx_write_register(chip, SD_VPCLK0_CTL, PHASE_NOT_RESET, PHASE_NOT_RESET); if (retval) { rtsx_trace(chip); return retval; } retval = rtsx_write_register(chip, SD_VPCLK1_CTL, PHASE_NOT_RESET, PHASE_NOT_RESET); if (retval) { rtsx_trace(chip); return retval; } udelay(200); } retval = rtsx_write_register(chip, CLK_CTL, 0xFF, 0); if (retval) { rtsx_trace(chip); return retval; } chip->cur_clk = clk; return STATUS_SUCCESS; } void trans_dma_enable(enum dma_data_direction dir, struct rtsx_chip *chip, u32 byte_cnt, u8 pack_size) { if (pack_size > DMA_1024) pack_size = DMA_512; rtsx_add_cmd(chip, WRITE_REG_CMD, IRQSTAT0, DMA_DONE_INT, DMA_DONE_INT); rtsx_add_cmd(chip, WRITE_REG_CMD, DMATC3, 0xFF, (u8)(byte_cnt >> 24)); rtsx_add_cmd(chip, WRITE_REG_CMD, DMATC2, 0xFF, (u8)(byte_cnt >> 16)); rtsx_add_cmd(chip, WRITE_REG_CMD, DMATC1, 0xFF, (u8)(byte_cnt >> 8)); rtsx_add_cmd(chip, WRITE_REG_CMD, DMATC0, 0xFF, (u8)byte_cnt); if (dir == DMA_FROM_DEVICE) { rtsx_add_cmd(chip, WRITE_REG_CMD, DMACTL, 0x03 | DMA_PACK_SIZE_MASK, DMA_DIR_FROM_CARD | DMA_EN | pack_size); } else { rtsx_add_cmd(chip, WRITE_REG_CMD, DMACTL, 0x03 | DMA_PACK_SIZE_MASK, DMA_DIR_TO_CARD | DMA_EN | pack_size); } rtsx_add_cmd(chip, WRITE_REG_CMD, CARD_DATA_SOURCE, 0x01, RING_BUFFER); } int enable_card_clock(struct rtsx_chip *chip, u8 card) { int retval; u8 clk_en = 0; if (card & XD_CARD) clk_en |= XD_CLK_EN; if (card & SD_CARD) clk_en |= SD_CLK_EN; if (card & MS_CARD) clk_en |= MS_CLK_EN; retval = rtsx_write_register(chip, CARD_CLK_EN, clk_en, clk_en); if (retval) { rtsx_trace(chip); return retval; } return STATUS_SUCCESS; } int disable_card_clock(struct rtsx_chip *chip, u8 card) { int retval; u8 clk_en = 0; if (card & XD_CARD) clk_en |= XD_CLK_EN; if (card & SD_CARD) clk_en |= SD_CLK_EN; if (card & MS_CARD) clk_en |= MS_CLK_EN; retval = rtsx_write_register(chip, CARD_CLK_EN, clk_en, 0); if (retval) { rtsx_trace(chip); return retval; } return STATUS_SUCCESS; } int card_power_on(struct rtsx_chip *chip, u8 card) { int retval; u8 mask, val1, val2; if (CHECK_LUN_MODE(chip, SD_MS_2LUN) && (card == MS_CARD)) { mask = MS_POWER_MASK; val1 = MS_PARTIAL_POWER_ON; val2 = MS_POWER_ON; } else { mask = SD_POWER_MASK; val1 = SD_PARTIAL_POWER_ON; val2 = SD_POWER_ON; } rtsx_init_cmd(chip); rtsx_add_cmd(chip, WRITE_REG_CMD, CARD_PWR_CTL, mask, val1); retval = rtsx_send_cmd(chip, 0, 100); if (retval != STATUS_SUCCESS) { rtsx_trace(chip); return STATUS_FAIL; } udelay(chip->pmos_pwr_on_interval); rtsx_init_cmd(chip); rtsx_add_cmd(chip, WRITE_REG_CMD, CARD_PWR_CTL, mask, val2); retval = rtsx_send_cmd(chip, 0, 100); if (retval != STATUS_SUCCESS) { rtsx_trace(chip); return STATUS_FAIL; } return STATUS_SUCCESS; } int card_power_off(struct rtsx_chip *chip, u8 card) { int retval; u8 mask, val; if (CHECK_LUN_MODE(chip, SD_MS_2LUN) && (card == MS_CARD)) { mask = MS_POWER_MASK; val = MS_POWER_OFF; } else { mask = SD_POWER_MASK; val = SD_POWER_OFF; } retval = rtsx_write_register(chip, CARD_PWR_CTL, mask, val); if (retval) { rtsx_trace(chip); return retval; } return STATUS_SUCCESS; } int card_rw(struct scsi_cmnd *srb, struct rtsx_chip *chip, u32 sec_addr, u16 sec_cnt) { int retval; unsigned int lun = SCSI_LUN(srb); int i; if (chip->rw_card[lun] == NULL) { rtsx_trace(chip); return STATUS_FAIL; } for (i = 0; i < 3; i++) { chip->rw_need_retry = 0; retval = chip->rw_card[lun](srb, chip, sec_addr, sec_cnt); if (retval != STATUS_SUCCESS) { if (rtsx_check_chip_exist(chip) != STATUS_SUCCESS) { rtsx_release_chip(chip); rtsx_trace(chip); return STATUS_FAIL; } if (detect_card_cd(chip, chip->cur_card) != STATUS_SUCCESS) { rtsx_trace(chip); return STATUS_FAIL; } if (!chip->rw_need_retry) { dev_dbg(rtsx_dev(chip), "RW fail, but no need to retry\n"); break; } } else { chip->rw_need_retry = 0; break; } dev_dbg(rtsx_dev(chip), "Retry RW, (i = %d)\n", i); } return retval; } int card_share_mode(struct rtsx_chip *chip, int card) { int retval; u8 mask, value; if (CHECK_PID(chip, 0x5208)) { mask = CARD_SHARE_MASK; if (card == SD_CARD) value = CARD_SHARE_48_SD; else if (card == MS_CARD) value = CARD_SHARE_48_MS; else if (card == XD_CARD) value = CARD_SHARE_48_XD; else { rtsx_trace(chip); return STATUS_FAIL; } } else if (CHECK_PID(chip, 0x5288)) { mask = 0x03; if (card == SD_CARD) value = CARD_SHARE_BAROSSA_SD; else if (card == MS_CARD) value = CARD_SHARE_BAROSSA_MS; else if (card == XD_CARD) value = CARD_SHARE_BAROSSA_XD; else { rtsx_trace(chip); return STATUS_FAIL; } } else { rtsx_trace(chip); return STATUS_FAIL; } retval = rtsx_write_register(chip, CARD_SHARE_MODE, mask, value); if (retval) { rtsx_trace(chip); return retval; } return STATUS_SUCCESS; } int select_card(struct rtsx_chip *chip, int card) { int retval; if (chip->cur_card != card) { u8 mod; if (card == SD_CARD) mod = SD_MOD_SEL; else if (card == MS_CARD) mod = MS_MOD_SEL; else if (card == XD_CARD) mod = XD_MOD_SEL; else if (card == SPI_CARD) mod = SPI_MOD_SEL; else { rtsx_trace(chip); return STATUS_FAIL; } retval = rtsx_write_register(chip, CARD_SELECT, 0x07, mod); if (retval) { rtsx_trace(chip); return retval; } chip->cur_card = card; retval = card_share_mode(chip, card); if (retval != STATUS_SUCCESS) { rtsx_trace(chip); return STATUS_FAIL; } } return STATUS_SUCCESS; } void toggle_gpio(struct rtsx_chip *chip, u8 gpio) { u8 temp_reg; rtsx_read_register(chip, CARD_GPIO, &temp_reg); temp_reg ^= (0x01 << gpio); rtsx_write_register(chip, CARD_GPIO, 0xFF, temp_reg); } void turn_on_led(struct rtsx_chip *chip, u8 gpio) { if (CHECK_PID(chip, 0x5288)) rtsx_write_register(chip, CARD_GPIO, (u8)(1 << gpio), (u8)(1 << gpio)); else rtsx_write_register(chip, CARD_GPIO, (u8)(1 << gpio), 0); } void turn_off_led(struct rtsx_chip *chip, u8 gpio) { if (CHECK_PID(chip, 0x5288)) rtsx_write_register(chip, CARD_GPIO, (u8)(1 << gpio), 0); else rtsx_write_register(chip, CARD_GPIO, (u8)(1 << gpio), (u8)(1 << gpio)); } int detect_card_cd(struct rtsx_chip *chip, int card) { u32 card_cd, status; if (card == SD_CARD) { card_cd = SD_EXIST; } else if (card == MS_CARD) { card_cd = MS_EXIST; } else if (card == XD_CARD) { card_cd = XD_EXIST; } else { dev_dbg(rtsx_dev(chip), "Wrong card type: 0x%x\n", card); rtsx_trace(chip); return STATUS_FAIL; } status = rtsx_readl(chip, RTSX_BIPR); if (!(status & card_cd)) { rtsx_trace(chip); return STATUS_FAIL; } return STATUS_SUCCESS; } int check_card_exist(struct rtsx_chip *chip, unsigned int lun) { if (chip->card_exist & chip->lun2card[lun]) return 1; return 0; } int check_card_ready(struct rtsx_chip *chip, unsigned int lun) { if (chip->card_ready & chip->lun2card[lun]) return 1; return 0; } int check_card_wp(struct rtsx_chip *chip, unsigned int lun) { if (chip->card_wp & chip->lun2card[lun]) return 1; return 0; } u8 get_lun_card(struct rtsx_chip *chip, unsigned int lun) { if ((chip->card_ready & chip->lun2card[lun]) == XD_CARD) return (u8)XD_CARD; else if ((chip->card_ready & chip->lun2card[lun]) == SD_CARD) return (u8)SD_CARD; else if ((chip->card_ready & chip->lun2card[lun]) == MS_CARD) return (u8)MS_CARD; return 0; } void eject_card(struct rtsx_chip *chip, unsigned int lun) { do_remaining_work(chip); if ((chip->card_ready & chip->lun2card[lun]) == SD_CARD) { release_sd_card(chip); chip->card_ejected |= SD_CARD; chip->card_ready &= ~SD_CARD; chip->capacity[lun] = 0; } else if ((chip->card_ready & chip->lun2card[lun]) == XD_CARD) { release_xd_card(chip); chip->card_ejected |= XD_CARD; chip->card_ready &= ~XD_CARD; chip->capacity[lun] = 0; } else if ((chip->card_ready & chip->lun2card[lun]) == MS_CARD) { release_ms_card(chip); chip->card_ejected |= MS_CARD; chip->card_ready &= ~MS_CARD; chip->capacity[lun] = 0; } }
{ "pile_set_name": "Github" }
'use strict'; // mock to test functionality in a command unrelated matter // this mean that not e.g. googleDeploy but the more abstract googleCommand can be used class GoogleCommand { constructor(serverless, options, testSubject) { this.options = options; this.serverless = serverless; this.provider = this.serverless.getProvider('google'); Object.assign(this, testSubject); } } module.exports = GoogleCommand;
{ "pile_set_name": "Github" }
[Rank] Feria Secunda infra Hebdomadam IV post Epiiphaniam;;Feria;;1;;vide Epi4-0 [Rule] vide Epi4-0 Suffragium=Maria2;Papa,Ecclesia;;
{ "pile_set_name": "Github" }
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.views.art; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.DashPathEffect; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.graphics.Shader; import androidx.annotation.Nullable; import com.facebook.common.logging.FLog; import com.facebook.react.bridge.JSApplicationIllegalArgumentException; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.common.ReactConstants; import com.facebook.react.uimanager.annotations.ReactProp; /** Shadow node for virtual ARTShape view */ public class ARTShapeShadowNode extends ARTVirtualNode { private static final int CAP_BUTT = 0; private static final int CAP_ROUND = 1; private static final int CAP_SQUARE = 2; private static final int JOIN_BEVEL = 2; private static final int JOIN_MITER = 0; private static final int JOIN_ROUND = 1; private static final int PATH_TYPE_ARC = 4; private static final int PATH_TYPE_CLOSE = 1; private static final int PATH_TYPE_CURVETO = 3; private static final int PATH_TYPE_LINETO = 2; private static final int PATH_TYPE_MOVETO = 0; // For color type JS and ObjectiveC definitions counterparts // refer to ReactNativeART.js and RCTConvert+ART.m private static final int COLOR_TYPE_SOLID_COLOR = 0; private static final int COLOR_TYPE_LINEAR_GRADIENT = 1; private static final int COLOR_TYPE_RADIAL_GRADIENT = 2; private static final int COLOR_TYPE_PATTERN = 3; protected @Nullable Path mPath; private @Nullable float[] mStrokeColor; private @Nullable float[] mBrushData; private @Nullable float[] mStrokeDash; private float mStrokeWidth = 1; private int mStrokeCap = CAP_ROUND; private int mStrokeJoin = JOIN_ROUND; public ARTShapeShadowNode() {} @ReactProp(name = "d") public void setShapePath(@Nullable ReadableArray shapePath) { float[] pathData = PropHelper.toFloatArray(shapePath); mPath = createPath(pathData); markUpdated(); } @ReactProp(name = "stroke") public void setStroke(@Nullable ReadableArray strokeColors) { mStrokeColor = PropHelper.toFloatArray(strokeColors); markUpdated(); } @ReactProp(name = "strokeDash") public void setStrokeDash(@Nullable ReadableArray strokeDash) { mStrokeDash = PropHelper.toFloatArray(strokeDash); markUpdated(); } @ReactProp(name = "fill") public void setFill(@Nullable ReadableArray fillColors) { mBrushData = PropHelper.toFloatArray(fillColors); markUpdated(); } @ReactProp(name = "strokeWidth", defaultFloat = 1f) public void setStrokeWidth(float strokeWidth) { mStrokeWidth = strokeWidth; markUpdated(); } @ReactProp(name = "strokeCap", defaultInt = CAP_ROUND) public void setStrokeCap(int strokeCap) { mStrokeCap = strokeCap; markUpdated(); } @ReactProp(name = "strokeJoin", defaultInt = JOIN_ROUND) public void setStrokeJoin(int strokeJoin) { mStrokeJoin = strokeJoin; markUpdated(); } @Override public void draw(Canvas canvas, Paint paint, float opacity) { opacity *= mOpacity; if (opacity > MIN_OPACITY_FOR_DRAW) { saveAndSetupCanvas(canvas); if (mPath == null) { throw new JSApplicationIllegalArgumentException("Shapes should have a valid path (d) prop"); } if (setupFillPaint(paint, opacity)) { canvas.drawPath(mPath, paint); } if (setupStrokePaint(paint, opacity)) { canvas.drawPath(mPath, paint); } restoreCanvas(canvas); } markUpdateSeen(); } /** * Sets up {@link #mPaint} according to the props set on a shadow view. Returns {@code true} if * the stroke should be drawn, {@code false} if not. */ protected boolean setupStrokePaint(Paint paint, float opacity) { if (mStrokeWidth == 0 || mStrokeColor == null || mStrokeColor.length == 0) { return false; } paint.reset(); paint.setFlags(Paint.ANTI_ALIAS_FLAG); paint.setStyle(Paint.Style.STROKE); switch (mStrokeCap) { case CAP_BUTT: paint.setStrokeCap(Paint.Cap.BUTT); break; case CAP_SQUARE: paint.setStrokeCap(Paint.Cap.SQUARE); break; case CAP_ROUND: paint.setStrokeCap(Paint.Cap.ROUND); break; default: throw new JSApplicationIllegalArgumentException( "strokeCap " + mStrokeCap + " unrecognized"); } switch (mStrokeJoin) { case JOIN_MITER: paint.setStrokeJoin(Paint.Join.MITER); break; case JOIN_BEVEL: paint.setStrokeJoin(Paint.Join.BEVEL); break; case JOIN_ROUND: paint.setStrokeJoin(Paint.Join.ROUND); break; default: throw new JSApplicationIllegalArgumentException( "strokeJoin " + mStrokeJoin + " unrecognized"); } paint.setStrokeWidth(mStrokeWidth * mScale); paint.setARGB( (int) (mStrokeColor.length > 3 ? mStrokeColor[3] * opacity * 255 : opacity * 255), (int) (mStrokeColor[0] * 255), (int) (mStrokeColor[1] * 255), (int) (mStrokeColor[2] * 255)); if (mStrokeDash != null && mStrokeDash.length > 0) { paint.setPathEffect(new DashPathEffect(mStrokeDash, 0)); } return true; } /** * Sets up {@link #mPaint} according to the props set on a shadow view. Returns {@code true} if * the fill should be drawn, {@code false} if not. */ protected boolean setupFillPaint(Paint paint, float opacity) { if (mBrushData != null && mBrushData.length > 0) { paint.reset(); paint.setFlags(Paint.ANTI_ALIAS_FLAG); paint.setStyle(Paint.Style.FILL); int colorType = (int) mBrushData[0]; switch (colorType) { case COLOR_TYPE_SOLID_COLOR: paint.setARGB( (int) (mBrushData.length > 4 ? mBrushData[4] * opacity * 255 : opacity * 255), (int) (mBrushData[1] * 255), (int) (mBrushData[2] * 255), (int) (mBrushData[3] * 255)); break; case COLOR_TYPE_LINEAR_GRADIENT: // For mBrushData format refer to LinearGradient and insertColorStopsIntoArray functions // in ReactNativeART.js if (mBrushData.length < 5) { FLog.w( ReactConstants.TAG, "[ARTShapeShadowNode setupFillPaint] expects 5 elements, received " + mBrushData.length); return false; } float gradientStartX = mBrushData[1] * mScale; float gradientStartY = mBrushData[2] * mScale; float gradientEndX = mBrushData[3] * mScale; float gradientEndY = mBrushData[4] * mScale; int stops = (mBrushData.length - 5) / 5; int[] colors = null; float[] positions = null; if (stops > 0) { colors = new int[stops]; positions = new float[stops]; for (int i = 0; i < stops; i++) { positions[i] = mBrushData[5 + 4 * stops + i]; int r = (int) (255 * mBrushData[5 + 4 * i + 0]); int g = (int) (255 * mBrushData[5 + 4 * i + 1]); int b = (int) (255 * mBrushData[5 + 4 * i + 2]); int a = (int) (255 * mBrushData[5 + 4 * i + 3]); colors[i] = Color.argb(a, r, g, b); } } paint.setShader( new LinearGradient( gradientStartX, gradientStartY, gradientEndX, gradientEndY, colors, positions, Shader.TileMode.CLAMP)); break; case COLOR_TYPE_RADIAL_GRADIENT: // TODO(6352048): Support radial gradient etc. case COLOR_TYPE_PATTERN: // TODO(6352048): Support patterns etc. default: FLog.w(ReactConstants.TAG, "ART: Color type " + colorType + " not supported!"); } return true; } return false; } /** * Returns the floor modulus of the float arguments. Java modulus will return a negative remainder * when the divisor is negative. Modulus should always be positive. This mimics the behavior of * Math.floorMod, introduced in Java 8. */ private float modulus(float x, float y) { float remainder = x % y; float modulus = remainder; if (remainder < 0) { modulus += y; } return modulus; } /** * Creates a {@link Path} from an array of instructions constructed by JS (see * ARTSerializablePath.js). Each instruction starts with a type (see PATH_TYPE_*) followed by * arguments for that instruction. For example, to create a line the instruction will be 2 * (PATH_LINE_TO), x, y. This will draw a line from the last draw point (or 0,0) to x,y. * * @param data the array of instructions * @return the {@link Path} that can be drawn to a canvas */ private Path createPath(float[] data) { Path path = new Path(); path.moveTo(0, 0); int i = 0; while (i < data.length) { int type = (int) data[i++]; switch (type) { case PATH_TYPE_MOVETO: path.moveTo(data[i++] * mScale, data[i++] * mScale); break; case PATH_TYPE_CLOSE: path.close(); break; case PATH_TYPE_LINETO: path.lineTo(data[i++] * mScale, data[i++] * mScale); break; case PATH_TYPE_CURVETO: path.cubicTo( data[i++] * mScale, data[i++] * mScale, data[i++] * mScale, data[i++] * mScale, data[i++] * mScale, data[i++] * mScale); break; case PATH_TYPE_ARC: { float x = data[i++] * mScale; float y = data[i++] * mScale; float r = data[i++] * mScale; float start = (float) Math.toDegrees(data[i++]); float end = (float) Math.toDegrees(data[i++]); boolean counterClockwise = !(data[i++] == 1f); float sweep = end - start; if (Math.abs(sweep) >= 360) { path.addCircle(x, y, r, counterClockwise ? Path.Direction.CCW : Path.Direction.CW); } else { sweep = modulus(sweep, 360); if (counterClockwise && sweep < 360) { // Counter-clockwise sweeps are negative sweep = -1 * (360 - sweep); } RectF oval = new RectF(x - r, y - r, x + r, y + r); path.arcTo(oval, start, sweep); } break; } default: throw new JSApplicationIllegalArgumentException( "Unrecognized drawing instruction " + type); } } return path; } }
{ "pile_set_name": "Github" }
Template.author.helpers({ "options" : function() { return { "sort" : { date : -1 } }; }, "rendered" : function() { } }); Template.author.events({}); Paging.apply(Template.author, "allEPFsByAuthor", function() { return [ this._id ]; });
{ "pile_set_name": "Github" }
{ "cells": [ { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "5wFF5JFyD2Ki" }, "source": [ "#### Copyright 2019 The TensorFlow Hub Authors.\n", "\n", "Licensed under the Apache License, Version 2.0 (the \"License\");" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "Uf6NouXxDqGk" }, "outputs": [], "source": [ "# Copyright 2019 The TensorFlow Hub Authors. All Rights Reserved.\n", "#\n", "# Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", "# http://www.apache.org/licenses/LICENSE-2.0\n", "#\n", "# Unless required by applicable law or agreed to in writing, software\n", "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", "# See the License for the specific language governing permissions and\n", "# limitations under the License.\n", "# ==============================================================================" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "ORy-KvWXGXBo" }, "source": [ "# Exploring the TF-Hub CORD-19 Swivel Embeddings\n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "MfBg1C5NB3X0" }, "source": [ "\u003ctable class=\"tfo-notebook-buttons\" align=\"left\"\u003e\n", " \u003ctd\u003e\n", " \u003ca target=\"_blank\" href=\"https://www.tensorflow.org/hub/tutorials/cord_19_embeddings_keras\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" /\u003eView on TensorFlow.org\u003c/a\u003e\n", " \u003c/td\u003e\n", " \u003ctd\u003e\n", " \u003ca target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/hub/blob/master/examples/colab/cord_19_embeddings_keras.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /\u003eRun in Google Colab\u003c/a\u003e\n", " \u003c/td\u003e\n", " \u003ctd\u003e\n", " \u003ca target=\"_blank\" href=\"https://github.com/tensorflow/hub/blob/master/examples/colab/cord_19_embeddings_keras.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /\u003eView source on GitHub\u003c/a\u003e\n", " \u003c/td\u003e\n", " \u003ctd\u003e\n", " \u003ca href=\"https://storage.googleapis.com/tensorflow_docs/hub/examples/colab/cord_19_embeddings_keras.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/download_logo_32px.png\" /\u003eDownload notebook\u003c/a\u003e\n", " \u003c/td\u003e\n", "\u003c/table\u003e" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "yI6Mh3-P0_Pk" }, "source": [ "The CORD-19 Swivel text embedding module from TF-Hub (https://tfhub.dev/tensorflow/cord-19/swivel-128d/3)\n", " was built to support researchers analyzing natural languages text related to COVID-19.\n", "These embeddings were trained on the titles, authors, abstracts, body texts, and\n", "reference titles of articles in the [CORD-19 dataset](https://pages.semanticscholar.org/coronavirus-research).\n", "\n", "In this colab we will:\n", "- Analyze semantically similar words in the embedding space\n", "- Train a classifier on the SciCite dataset using the CORD-19 embeddings\n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "gVWOrccw0_Pl" }, "source": [ "## Setup\n" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "Ym2nXOPuPV__" }, "outputs": [], "source": [ "import functools\n", "import itertools\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "import seaborn as sns\n", "import pandas as pd\n", "\n", "import tensorflow as tf\n", "\n", "import tensorflow_datasets as tfds\n", "import tensorflow_hub as hub\n", "\n", "from tqdm import trange" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "_VgRRf2I7tER" }, "source": [ "# Analyze the embeddings\n", "\n", "Let's start off by analyzing the embedding by calculating and plotting a correlation matrix between different terms. If the embedding learned to successfully capture the meaning of different words, the embedding vectors of semantically similar words should be close together. Let's take a look at some COVID-19 related terms." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "HNN_9bBKSLHU" }, "outputs": [], "source": [ "# Use the inner product between two embedding vectors as the similarity measure\n", "def plot_correlation(labels, features):\n", " corr = np.inner(features, features)\n", " corr /= np.max(corr)\n", " sns.heatmap(corr, xticklabels=labels, yticklabels=labels)\n", "\n", "# Generate embeddings for some terms\n", "queries = [\n", " # Related viruses\n", " 'coronavirus', 'SARS', 'MERS',\n", " # Regions\n", " 'Italy', 'Spain', 'Europe',\n", " # Symptoms\n", " 'cough', 'fever', 'throat'\n", "]\n", "\n", "module = hub.load('https://tfhub.dev/tensorflow/cord-19/swivel-128d/3')\n", "embeddings = module(queries)\n", "\n", "plot_correlation(queries, embeddings)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "Bg-PGqtm8B7K" }, "source": [ "We can see that the embedding successfully captured the meaning of the different terms. Each word is similar to the other words of its cluster (i.e. \"coronavirus\" highly correlates with \"SARS\" and \"MERS\"), while they are different from terms of other clusters (i.e. the similarity between \"SARS\" and \"Spain\" is close to 0).\n", "\n", "Now let's see how we can use these embeddings to solve a specific task." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "idJ1jFmH7xMa" }, "source": [ "## SciCite: Citation Intent Classification\n", "\n", "This section shows how one can use the embedding for downstream tasks such as text classification. We'll use the [SciCite dataset](https://www.tensorflow.org/datasets/catalog/scicite) from TensorFlow Datasets to classify citation intents in academic papers. Given a sentence with a citation from an academic paper, classify whether the main intent of the citation is as background information, use of methods, or comparing results." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "Ghc-CzT8DDaZ" }, "outputs": [], "source": [ "builder = tfds.builder(name='scicite')\n", "builder.download_and_prepare()\n", "train_data, validation_data, test_data = builder.as_dataset(\n", " split=('train', 'validation', 'test'),\n", " as_supervised=True)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "cellView": "both", "colab": {}, "colab_type": "code", "id": "CVjyBD0ZPh4Z" }, "outputs": [], "source": [ "#@title Let's take a look at a few labeled examples from the training set\n", "NUM_EXAMPLES = 10#@param {type:\"integer\"}\n", "\n", "TEXT_FEATURE_NAME = builder.info.supervised_keys[0]\n", "LABEL_NAME = builder.info.supervised_keys[1]\n", "\n", "def label2str(numeric_label):\n", " m = builder.info.features[LABEL_NAME].names\n", " return m[numeric_label]\n", "\n", "data = next(iter(train_data.batch(NUM_EXAMPLES)))\n", "\n", "\n", "pd.DataFrame({\n", " TEXT_FEATURE_NAME: [ex.numpy().decode('utf8') for ex in data[0]],\n", " LABEL_NAME: [label2str(x) for x in data[1]]\n", "})" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "65s9UpYJ_1ct" }, "source": [ "## Training a citaton intent classifier\n", "\n", "We'll train a classifier on the [SciCite dataset](https://www.tensorflow.org/datasets/catalog/scicite) using Keras. Let's build a model which use the CORD-19 embeddings with a classification layer on top." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "cellView": "both", "colab": {}, "colab_type": "code", "id": "yZUclu8xBYlj" }, "outputs": [], "source": [ "#@title Hyperparameters { run: \"auto\" }\n", "\n", "EMBEDDING = 'https://tfhub.dev/tensorflow/cord-19/swivel-128d/3' #@param {type: \"string\"}\n", "TRAINABLE_MODULE = False #@param {type: \"boolean\"}\n", "\n", "hub_layer = hub.KerasLayer(EMBEDDING, input_shape=[], \n", " dtype=tf.string, trainable=TRAINABLE_MODULE)\n", "\n", "model = tf.keras.Sequential()\n", "model.add(hub_layer)\n", "model.add(tf.keras.layers.Dense(3))\n", "model.summary()\n", "model.compile(optimizer='adam',\n", " loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n", " metrics=['accuracy'])" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "weZKWK-pLBll" }, "source": [ "## Train and evaluate the model\n", "\n", "Let's train and evaluate the model to see the performance on the SciCite task" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "cO1FWkZW2WS9" }, "outputs": [], "source": [ "EPOCHS = 35#@param {type: \"integer\"}\n", "BATCH_SIZE = 32#@param {type: \"integer\"}\n", "\n", "history = model.fit(train_data.shuffle(10000).batch(BATCH_SIZE),\n", " epochs=EPOCHS,\n", " validation_data=validation_data.batch(BATCH_SIZE),\n", " verbose=1)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "2sKE7kEyLJQZ" }, "outputs": [], "source": [ "from matplotlib import pyplot as plt\n", "def display_training_curves(training, validation, title, subplot):\n", " if subplot%10==1: # set up the subplots on the first call\n", " plt.subplots(figsize=(10,10), facecolor='#F0F0F0')\n", " plt.tight_layout()\n", " ax = plt.subplot(subplot)\n", " ax.set_facecolor('#F8F8F8')\n", " ax.plot(training)\n", " ax.plot(validation)\n", " ax.set_title('model '+ title)\n", " ax.set_ylabel(title)\n", " ax.set_xlabel('epoch')\n", " ax.legend(['train', 'valid.'])" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "nnQfxevhLKld" }, "outputs": [], "source": [ "display_training_curves(history.history['accuracy'], history.history['val_accuracy'], 'accuracy', 211)\n", "display_training_curves(history.history['loss'], history.history['val_loss'], 'loss', 212)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "BjvtOw72Lpyw" }, "source": [ "## Evaluate the model\n", "\n", "And let's see how the model performs. Two values will be returned. Loss (a number which represents our error, lower values are better), and accuracy." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "y0ExC8D0LX8m" }, "outputs": [], "source": [ "results = model.evaluate(test_data.batch(512), verbose=2)\n", "\n", "for name, value in zip(model.metrics_names, results):\n", " print('%s: %.3f' % (name, value))" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "dWp5OWeTL2EW" }, "source": [ "We can see that the loss quickly decreases while especially the accuracy rapidly increases. Let's plot some examples to check how the prediction relates to the true labels:" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "VzHzAOaaOVC0" }, "outputs": [], "source": [ "prediction_dataset = next(iter(test_data.batch(20)))\n", "\n", "prediction_texts = [ex.numpy().decode('utf8') for ex in prediction_dataset[0]]\n", "prediction_labels = [label2str(x) for x in prediction_dataset[1]]\n", "\n", "predictions = [label2str(x) for x in model.predict_classes(prediction_texts)]\n", "\n", "\n", "pd.DataFrame({\n", " TEXT_FEATURE_NAME: prediction_texts,\n", " LABEL_NAME: prediction_labels,\n", " 'prediction': predictions\n", "})" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "OSGcrkE069_Q" }, "source": [ "We can see that for this random sample, the model predicts the correct label most of the times, indicating that it can embed scientific sentences pretty well." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "oLE0kCfO5CIA" }, "source": [ "# What's next?\n", "\n", "Now that you've gotten to know a bit more about the CORD-19 Swivel embeddings from TF-Hub, we encourage you to participate in the CORD-19 Kaggle competition to contribute to gaining scientific insights from COVID-19 related academic texts.\n", "\n", "* Participate in the [CORD-19 Kaggle Challenge](https://www.kaggle.com/allen-institute-for-ai/CORD-19-research-challenge)\n", "* Learn more about the [COVID-19 Open Research Dataset (CORD-19)](https://pages.semanticscholar.org/coronavirus-research)\n", "* See documentation and more about the TF-Hub embeddings at https://tfhub.dev/tensorflow/cord-19/swivel-128d/3\n", "* Explore the CORD-19 embedding space with the [TensorFlow Embedding Projector](http://projector.tensorflow.org/?config=https://storage.googleapis.com/tfhub-examples/tensorflow/cord-19/swivel-128d/3/tensorboard/projector_config.json)" ] } ], "metadata": { "colab": { "collapsed_sections": [], "name": "Exploring the TF-Hub CORD-19 Swivel Embeddings", "private_outputs": true, "provenance": [], "toc_visible": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 0 }
{ "pile_set_name": "Github" }
/* GIMP - The GNU Image Manipulation Program * Copyright (C) 1995 Spencer Kimball and Peter Mattis * * gimpfgbgview.c * Copyright (C) 2005 Sven Neumann <[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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "config.h" #include <string.h> #include <gegl.h> #include <gtk/gtk.h> #include "libgimpbase/gimpbase.h" #include "libgimpcolor/gimpcolor.h" #include "libgimpwidgets/gimpwidgets.h" #include "widgets-types.h" #include "config/gimpcoreconfig.h" #include "core/gimp.h" #include "core/gimpcontext.h" #include "core/gimpmarshal.h" #include "gimpdnd.h" #include "gimpfgbgview.h" enum { PROP_0, PROP_CONTEXT }; static void gimp_fg_bg_view_dispose (GObject *object); static void gimp_fg_bg_view_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); static void gimp_fg_bg_view_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); static gboolean gimp_fg_bg_view_draw (GtkWidget *widget, cairo_t *cr); static void gimp_fg_bg_view_create_transform (GimpFgBgView *view); static void gimp_fg_bg_view_destroy_transform (GimpFgBgView *view); G_DEFINE_TYPE (GimpFgBgView, gimp_fg_bg_view, GTK_TYPE_WIDGET) #define parent_class gimp_fg_bg_view_parent_class static void gimp_fg_bg_view_class_init (GimpFgBgViewClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass); object_class->dispose = gimp_fg_bg_view_dispose; object_class->set_property = gimp_fg_bg_view_set_property; object_class->get_property = gimp_fg_bg_view_get_property; widget_class->draw = gimp_fg_bg_view_draw; g_object_class_install_property (object_class, PROP_CONTEXT, g_param_spec_object ("context", NULL, NULL, GIMP_TYPE_CONTEXT, GIMP_PARAM_READWRITE)); gtk_widget_class_set_css_name (widget_class, "GimpFgBgView"); } static void gimp_fg_bg_view_init (GimpFgBgView *view) { gtk_widget_set_has_window (GTK_WIDGET (view), FALSE); gimp_widget_track_monitor (GTK_WIDGET (view), G_CALLBACK (gimp_fg_bg_view_destroy_transform), NULL, NULL); } static void gimp_fg_bg_view_dispose (GObject *object) { GimpFgBgView *view = GIMP_FG_BG_VIEW (object); if (view->context) gimp_fg_bg_view_set_context (view, NULL); G_OBJECT_CLASS (parent_class)->dispose (object); } static void gimp_fg_bg_view_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { GimpFgBgView *view = GIMP_FG_BG_VIEW (object); switch (property_id) { case PROP_CONTEXT: gimp_fg_bg_view_set_context (view, g_value_get_object (value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); break; } } static void gimp_fg_bg_view_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { GimpFgBgView *view = GIMP_FG_BG_VIEW (object); switch (property_id) { case PROP_CONTEXT: g_value_set_object (value, view->context); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); break; } } static gboolean gimp_fg_bg_view_draw (GtkWidget *widget, cairo_t *cr) { GimpFgBgView *view = GIMP_FG_BG_VIEW (widget); GtkStyleContext *style = gtk_widget_get_style_context (widget); GtkAllocation allocation; GtkBorder border; GtkBorder padding; GdkRectangle rect; GimpRGB color; gtk_widget_get_allocation (widget, &allocation); gtk_style_context_save (style); gtk_style_context_get_border (style, gtk_style_context_get_state (style), &border); gtk_style_context_get_padding (style, gtk_style_context_get_state (style), &padding); border.left += padding.left; border.right += padding.right; border.top += padding.top; border.bottom += padding.bottom; rect.width = (allocation.width - border.left - border.right) * 3 / 4; rect.height = (allocation.height - border.top - border.bottom) * 3 / 4; if (! view->transform) gimp_fg_bg_view_create_transform (view); /* draw the background area */ rect.x = allocation.width - rect.width - border.right; rect.y = allocation.height - rect.height - border.bottom; if (view->context) { gimp_context_get_background (view->context, &color); if (view->transform) gimp_color_transform_process_pixels (view->transform, babl_format ("R'G'B'A double"), &color, babl_format ("R'G'B'A double"), &color, 1); gimp_cairo_set_source_rgb (cr, &color); cairo_rectangle (cr, rect.x, rect.y, rect.width, rect.height); cairo_fill (cr); } gtk_style_context_add_class (style, GTK_STYLE_CLASS_FRAME); gtk_render_frame (style, cr, rect.x, rect.y, rect.width, rect.height); /* draw the foreground area */ rect.x = border.left; rect.y = border.top; if (view->context) { gimp_context_get_foreground (view->context, &color); if (view->transform) gimp_color_transform_process_pixels (view->transform, babl_format ("R'G'B'A double"), &color, babl_format ("R'G'B'A double"), &color, 1); gimp_cairo_set_source_rgb (cr, &color); cairo_rectangle (cr, rect.x, rect.y, rect.width, rect.height); cairo_fill (cr); } gtk_render_frame (style, cr, rect.x, rect.y, rect.width, rect.height); gtk_style_context_restore (style); return TRUE; } static void gimp_fg_bg_view_create_transform (GimpFgBgView *view) { if (view->color_config) { static GimpColorProfile *profile = NULL; if (G_UNLIKELY (! profile)) profile = gimp_color_profile_new_rgb_srgb (); view->transform = gimp_widget_get_color_transform (GTK_WIDGET (view), view->color_config, profile, babl_format ("R'G'B'A double"), babl_format ("R'G'B'A double")); } } static void gimp_fg_bg_view_destroy_transform (GimpFgBgView *view) { g_clear_object (&view->transform); gtk_widget_queue_draw (GTK_WIDGET (view)); } /* public functions */ GtkWidget * gimp_fg_bg_view_new (GimpContext *context) { g_return_val_if_fail (context == NULL || GIMP_IS_CONTEXT (context), NULL); return g_object_new (GIMP_TYPE_FG_BG_VIEW, "context", context, NULL); } void gimp_fg_bg_view_set_context (GimpFgBgView *view, GimpContext *context) { g_return_if_fail (GIMP_IS_FG_BG_VIEW (view)); g_return_if_fail (context == NULL || GIMP_IS_CONTEXT (context)); if (context != view->context) { if (view->context) { g_signal_handlers_disconnect_by_func (view->context, gtk_widget_queue_draw, view); g_clear_object (&view->context); g_signal_handlers_disconnect_by_func (view->color_config, gimp_fg_bg_view_destroy_transform, view); g_clear_object (&view->color_config); } view->context = context; if (context) { g_object_ref (context); g_signal_connect_swapped (context, "foreground-changed", G_CALLBACK (gtk_widget_queue_draw), view); g_signal_connect_swapped (context, "background-changed", G_CALLBACK (gtk_widget_queue_draw), view); view->color_config = g_object_ref (context->gimp->config->color_management); g_signal_connect_swapped (view->color_config, "notify", G_CALLBACK (gimp_fg_bg_view_destroy_transform), view); } gimp_fg_bg_view_destroy_transform (view); g_object_notify (G_OBJECT (view), "context"); } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?><definitions xmlns="http://ws.apache.org/ns/synapse"> <registry provider="org.wso2.carbon.mediation.registry.WSO2Registry"> <parameter name="cachableDuration">15000</parameter> </registry> <proxy name="aggregateMediatorTestProxy" transports="https http" startOnLoad="true" trace="disable"> <description/> <target> <inSequence> <iterate xmlns:ns="http://org.apache.synapse/xsd" xmlns:ns3="http://org.apache.synapse/xsd" xmlns:m0="http://services.samples" id="iterate1" preservePayload="true" attachPath="//m0:getQuotes" expression="//m0:getQuotes/m0:getQuote" sequential="true"> <target> <sequence> <log level="full" category="DEBUG"> <property name="target1" value="************After 1st Iterate before 2nd Iterate*************"/> </log> <iterate id="iterate2" preservePayload="true" attachPath="//m0:getQuote" expression="//m0:getQuotes/m0:getQuote/m0:request"> <target sequence="anon"> <sequence> <log level="full" category="DEBUG"/> <payloadFactory> <format> <m0:getQuote> <m0:request> <m0:symbol>$1</m0:symbol> </m0:request> </m0:getQuote> </format> <args> <arg expression="//m0:getQuotes/m0:getQuote/m0:request/m0:symbol"/> </args> </payloadFactory> <log level="full" category="DEBUG"> <property name="target1" value="************after payload factory*************"/> </log> <send> <endpoint> <address uri="http://localhost:9000/services/SimpleStockQuoteService"/> </endpoint> </send> </sequence> </target> </iterate> </sequence> </target> </iterate> </inSequence> <outSequence> <aggregate id="iterate2"> <completeCondition> <messageCount min="50" max="-1"/> </completeCondition> <onComplete xmlns:ns="http://org.apache.synapse/xsd" xmlns:ns3="http://org.apache.synapse/xsd" xmlns:m0="http://services.samples" expression="//m0:getQuoteResponse"> <log level="custom"> <property name="messageLog" value="*****Aggregating*****"/> </log> <send/> </onComplete> </aggregate> </outSequence> </target> </proxy> <sequence name="fault"> <log level="full"> <property name="MESSAGE" value="Executing default 'fault' sequence"/> <property name="ERROR_CODE" expression="get-property('ERROR_CODE')"/> <property name="ERROR_MESSAGE" expression="get-property('ERROR_MESSAGE')"/> </log> <drop/> </sequence> <sequence name="main"> <in> <sequence key="IterateMediatorSequence"/> </in> <out> <sequence key="IteratorAggregateSequence"/> </out> </sequence> </definitions>
{ "pile_set_name": "Github" }
{if !$status} {include file="$template/includes/alert.tpl" type="warning" msg=$LANG.sslinvalidlink textcenter=true} <p class="text-center"><input type="button" value="{$LANG.clientareabacklink}" onclick="history.go(-1)" class="btn btn-primary" /></p> {else} {if $errormessage} {include file="$template/includes/alert.tpl" type="error" errorshtml=$errormessage} {/if} {if $status eq "Awaiting Configuration"} <form method="post" action="{$smarty.server.PHP_SELF}?cert={$cert}&step=2"> {include file="$template/includes/subheader.tpl" title=$LANG.sslserverinfo} <p>{$LANG.sslserverinfodetails}</p> <div class="form-group"> <label for="inputServerType">{$LANG.sslservertype}</label> <select name="servertype" id="inputServerType" class="form-control"> <option value="" selected>{$LANG.pleasechooseone}</option> {foreach from=$webservertypes key=webservertypeid item=webservertype} <option value="{$webservertypeid}"{if $servertype eq $webservertypeid} selected{/if}> {$webservertype} </option> {/foreach} </select> </div> <div class="form-group"> <label for="inputCsr">{$LANG.sslcsr}</label> <textarea name="csr" id="inputCsr" rows="7" class="form-control">{if $csr}{$csr}{else}-----BEGIN CERTIFICATE REQUEST----- -----END CERTIFICATE REQUEST-----{/if}</textarea> </div> {foreach from=$additionalfields key=heading item=fields} <p><strong>{$heading}</strong></p> <fieldset class="form-horizontal"> {foreach from=$fields item=vals} <div class="form-group"> <label class="col-md-4 control-label" for="inputAdditionalField">{$vals.name}</label> <div class="col-md-8"> {$vals.input} {$vals.description} </div> </div> {/foreach} </fieldset> {/foreach} {include file="$template/includes/subheader.tpl" title=$LANG.ssladmininfo} <p>{$LANG.ssladmininfodetails}</p> <fieldset class="form-horizontal"> <div class="form-group"> <label class="col-sm-4 control-label" for="inputFirstName">{$LANG.clientareafirstname}</label> <div class="col-sm-8"> <input type="text" class="form-control" name="firstname" id="inputFirstName" value="{$firstname}" /> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label" for="inputLastName">{$LANG.clientarealastname}</label> <div class="col-sm-8"> <input type="text" class="form-control" name="lastname" id="inputLastName" value="{$lastname}" /> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label" for="inputOrgName">{$LANG.organizationname}</label> <div class="col-sm-8"> <input type="text" class="form-control" name="orgname" id="inputOrgName" value="{$orgname}" /> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label" for="inputJobTitle">{$LANG.jobtitle}</label> <div class="col-sm-8"> <input type="text" class="form-control" name="jobtitle" id="inputJobTitle" value="{$jobtitle}" /> <p class="help-block">{$LANG.jobtitlereqforcompany}</p> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label" for="inputEmail">{$LANG.clientareaemail}</label> <div class="col-sm-8"> <input type="text" class="form-control" name="email" id="inputEmail" value="{$email}" /> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label" for="inputAddress1">{$LANG.clientareaaddress1}</label> <div class="col-sm-8"> <input type="text" class="form-control" name="address1" id="inputAddress1" value="{$address1}" /> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label" for="inputAddress2">{$LANG.clientareaaddress2}</label> <div class="col-sm-8"> <input type="text" class="form-control" name="address2" id="inputAddress2" value="{$address2}" /> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label" for="inputCity">{$LANG.clientareacity}</label> <div class="col-sm-8"> <input type="text" class="form-control" name="city" id="inputCity" value="{$city}" /> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label" for="inputState">{$LANG.clientareastate}</label> <div class="col-sm-8"> <input type="text" class="form-control" name="state" id="inputState" value="{$state}" /> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label" for="inputPostcode">{$LANG.clientareapostcode}</label> <div class="col-sm-8"> <input type="text" class="form-control" name="postcode" id="inputPostcode" value="{$postcode}" /> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label" for="inputCountry">{$LANG.clientareacountry}</label> <div class="col-sm-8"> <select name="country" id="inputCountry" class="form-control"> {foreach from=$clientcountries item=thisCountryName key=thisCountryCode} <option value="{$thisCountryCode}" {if $thisCountryCode eq $country}selected="selected"{/if}>{$thisCountryName}</option> {/foreach} </select> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label" for="inputPhoneNumber">{$LANG.clientareaphonenumber}</label> <div class="col-sm-8"> <input type="tel" class="form-control" name="phonenumber" id="inputPhoneNumber" value="{$phonenumber}" /> </div> </div> </fieldset> <p class="text-center"> <input type="submit" value="{$LANG.ordercontinuebutton}" class="btn btn-primary" /> </p> </form> {else} {include file="$template/includes/alert.tpl" type="info" msg=$LANG.sslnoconfigurationpossible textcenter=true} <form method="post" action="clientarea.php?action=productdetails"> <input type="hidden" name="id" value="{$serviceid}" /> <p> <input type="submit" value="{$LANG.invoicesbacktoclientarea}" class="btn btn-default" /></p> </form> {/if} {/if}
{ "pile_set_name": "Github" }
Cropper.TEMPLATE = ( '<div class="cropper-container">' + '<div class="cropper-wrap-box">' + '<div class="cropper-canvas"></div>' + '</div>' + '<div class="cropper-drag-box"></div>' + '<div class="cropper-crop-box">' + '<span class="cropper-view-box"></span>' + '<span class="cropper-dashed dashed-h"></span>' + '<span class="cropper-dashed dashed-v"></span>' + '<span class="cropper-center"></span>' + '<span class="cropper-face"></span>' + '<span class="cropper-line line-e" data-action="e"></span>' + '<span class="cropper-line line-n" data-action="n"></span>' + '<span class="cropper-line line-w" data-action="w"></span>' + '<span class="cropper-line line-s" data-action="s"></span>' + '<span class="cropper-point point-e" data-action="e"></span>' + '<span class="cropper-point point-n" data-action="n"></span>' + '<span class="cropper-point point-w" data-action="w"></span>' + '<span class="cropper-point point-s" data-action="s"></span>' + '<span class="cropper-point point-ne" data-action="ne"></span>' + '<span class="cropper-point point-nw" data-action="nw"></span>' + '<span class="cropper-point point-sw" data-action="sw"></span>' + '<span class="cropper-point point-se" data-action="se"></span>' + '</div>' + '</div>' );
{ "pile_set_name": "Github" }
namespace HslControlsDemo { partial class FormHslTitle { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose( bool disposing ) { if (disposing && (components != null)) { components.Dispose( ); } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent( ) { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.hslTitle5 = new HslControls.HslTitle(); this.hslTitle4 = new HslControls.HslTitle(); this.hslTitle3 = new HslControls.HslTitle(); this.hslTitle2 = new HslControls.HslTitle(); this.hslTitle1 = new HslControls.HslTitle(); this.label6 = new System.Windows.Forms.Label(); this.hslTitle6 = new HslControls.HslTitle(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(224, 77); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(65, 12); this.label1.TabIndex = 1; this.label1.Text = "默认的标题"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(709, 77); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(77, 12); this.label2.TabIndex = 3; this.label2.Text = "双边设置为空"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(476, 218); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(53, 12); this.label3.TabIndex = 5; this.label3.Text = "字号调整"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(448, 355); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(125, 12); this.label4.TabIndex = 7; this.label4.Text = "调整小中间的宽度信息"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(419, 490); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(209, 12); this.label5.TabIndex = 9; this.label5.Text = "一个示例效果,两端的文字都调整了。"; // // hslTitle5 // this.hslTitle5.Font = new System.Drawing.Font("华文新魏", 25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.hslTitle5.FontLeft = null; this.hslTitle5.FontRight = new System.Drawing.Font("Berlin Sans FB Demi", 25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.hslTitle5.Location = new System.Drawing.Point(24, 393); this.hslTitle5.Margin = new System.Windows.Forms.Padding(9); this.hslTitle5.Name = "hslTitle5"; this.hslTitle5.Size = new System.Drawing.Size(968, 88); this.hslTitle5.TabIndex = 8; this.hslTitle5.Text = "KanBan System"; this.hslTitle5.Click += new System.EventHandler(this.HslTitle1_Click); // // hslTitle4 // this.hslTitle4.Font = new System.Drawing.Font("宋体", 21F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.hslTitle4.FontLeft = null; this.hslTitle4.FontRight = null; this.hslTitle4.Location = new System.Drawing.Point(24, 250); this.hslTitle4.Margin = new System.Windows.Forms.Padding(7); this.hslTitle4.Name = "hslTitle4"; this.hslTitle4.Size = new System.Drawing.Size(968, 82); this.hslTitle4.TabIndex = 6; this.hslTitle4.Text = "hslTitle4"; this.hslTitle4.WidthPercent = 0.3F; this.hslTitle4.Click += new System.EventHandler(this.HslTitle1_Click); // // hslTitle3 // this.hslTitle3.Font = new System.Drawing.Font("宋体", 21F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.hslTitle3.FontLeft = null; this.hslTitle3.FontRight = null; this.hslTitle3.Location = new System.Drawing.Point(24, 112); this.hslTitle3.Margin = new System.Windows.Forms.Padding(7); this.hslTitle3.Name = "hslTitle3"; this.hslTitle3.Size = new System.Drawing.Size(968, 82); this.hslTitle3.TabIndex = 4; this.hslTitle3.Text = "hslTitle3"; this.hslTitle3.Click += new System.EventHandler(this.HslTitle1_Click); // // hslTitle2 // this.hslTitle2.FontLeft = null; this.hslTitle2.FontRight = null; this.hslTitle2.Location = new System.Drawing.Point(516, 19); this.hslTitle2.Name = "hslTitle2"; this.hslTitle2.Size = new System.Drawing.Size(476, 41); this.hslTitle2.TabIndex = 2; this.hslTitle2.Text = "hslTitle2"; this.hslTitle2.TextLeft = ""; this.hslTitle2.TextRight = ""; this.hslTitle2.Click += new System.EventHandler(this.HslTitle1_Click); // // hslTitle1 // this.hslTitle1.FontLeft = null; this.hslTitle1.FontRight = null; this.hslTitle1.Location = new System.Drawing.Point(24, 19); this.hslTitle1.Name = "hslTitle1"; this.hslTitle1.Size = new System.Drawing.Size(459, 41); this.hslTitle1.TabIndex = 0; this.hslTitle1.Text = "hslTitle1"; this.hslTitle1.Click += new System.EventHandler(this.HslTitle1_Click); // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(448, 619); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(113, 12); this.label6.TabIndex = 11; this.label6.Text = "调整调整颜色信息。"; // // hslTitle6 // this.hslTitle6.EdgeColor = System.Drawing.Color.Lavender; this.hslTitle6.Font = new System.Drawing.Font("华文新魏", 25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.hslTitle6.FontLeft = null; this.hslTitle6.FontRight = new System.Drawing.Font("Berlin Sans FB Demi", 25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.hslTitle6.LeftRightEdgeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64))))); this.hslTitle6.Location = new System.Drawing.Point(24, 522); this.hslTitle6.Margin = new System.Windows.Forms.Padding(9); this.hslTitle6.Name = "hslTitle6"; this.hslTitle6.Size = new System.Drawing.Size(968, 88); this.hslTitle6.TabIndex = 10; this.hslTitle6.Text = "KanBan System"; this.hslTitle6.Click += new System.EventHandler(this.HslTitle1_Click); // // FormHslTitle // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScroll = true; this.ClientSize = new System.Drawing.Size(1004, 645); this.Controls.Add(this.label6); this.Controls.Add(this.hslTitle6); this.Controls.Add(this.label5); this.Controls.Add(this.hslTitle5); this.Controls.Add(this.label4); this.Controls.Add(this.hslTitle4); this.Controls.Add(this.label3); this.Controls.Add(this.hslTitle3); this.Controls.Add(this.label2); this.Controls.Add(this.hslTitle2); this.Controls.Add(this.label1); this.Controls.Add(this.hslTitle1); this.Name = "FormHslTitle"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "FormHslTitle"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private HslControls.HslTitle hslTitle1; private System.Windows.Forms.Label label1; private HslControls.HslTitle hslTitle2; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private HslControls.HslTitle hslTitle3; private System.Windows.Forms.Label label4; private HslControls.HslTitle hslTitle4; private System.Windows.Forms.Label label5; private HslControls.HslTitle hslTitle5; private System.Windows.Forms.Label label6; private HslControls.HslTitle hslTitle6; } }
{ "pile_set_name": "Github" }
import warnings import matplotlib.pyplot as plt import mmcv import numpy as np import pycocotools.mask as maskUtils import torch from mmcv.parallel import collate, scatter from mmcv.runner import load_checkpoint from mmdet.core import get_classes from mmdet.datasets.pipelines import Compose from mmdet.models import build_detector def init_detector(config, checkpoint=None, device='cuda:0'): """Initialize a detector from config file. Args: config (str or :obj:`mmcv.Config`): Config file path or the config object. checkpoint (str, optional): Checkpoint path. If left as None, the model will not load any weights. Returns: nn.Module: The constructed detector. """ if isinstance(config, str): config = mmcv.Config.fromfile(config) elif not isinstance(config, mmcv.Config): raise TypeError('config must be a filename or Config object, ' 'but got {}'.format(type(config))) config.model.pretrained = None model = build_detector(config.model, test_cfg=config.test_cfg) if checkpoint is not None: checkpoint = load_checkpoint(model, checkpoint) if 'CLASSES' in checkpoint['meta']: model.CLASSES = checkpoint['meta']['CLASSES'] else: warnings.warn('Class names are not saved in the checkpoint\'s ' 'meta data, use COCO classes by default.') model.CLASSES = get_classes('coco') model.cfg = config # save the config in the model for convenience model.to(device) model.eval() return model class LoadImage(object): def __call__(self, results): if isinstance(results['img'], str): results['filename'] = results['img'] else: results['filename'] = None img = mmcv.imread(results['img']) results['img'] = img results['img_shape'] = img.shape results['ori_shape'] = img.shape return results def inference_detector(model, img): """Inference image(s) with the detector. Args: model (nn.Module): The loaded detector. imgs (str/ndarray or list[str/ndarray]): Either image files or loaded images. Returns: If imgs is a str, a generator will be returned, otherwise return the detection results directly. """ cfg = model.cfg device = next(model.parameters()).device # model device # build the data pipeline test_pipeline = [LoadImage()] + cfg.data.test.pipeline[1:] test_pipeline = Compose(test_pipeline) # prepare data data = dict(img=img) data = test_pipeline(data) data = scatter(collate([data], samples_per_gpu=1), [device])[0] # forward the model with torch.no_grad(): result = model(return_loss=False, rescale=True, **data) return result # TODO: merge this method with the one in BaseDetector def show_result(img, result, class_names, score_thr=0.3, wait_time=0, show=True, out_file=None): """Visualize the detection results on the image. Args: img (str or np.ndarray): Image filename or loaded image. result (tuple[list] or list): The detection result, can be either (bbox, segm) or just bbox. class_names (list[str] or tuple[str]): A list of class names. score_thr (float): The threshold to visualize the bboxes and masks. wait_time (int): Value of waitKey param. show (bool, optional): Whether to show the image with opencv or not. out_file (str, optional): If specified, the visualization result will be written to the out file instead of shown in a window. Returns: np.ndarray or None: If neither `show` nor `out_file` is specified, the visualized image is returned, otherwise None is returned. """ assert isinstance(class_names, (tuple, list)) img = mmcv.imread(img) img = img.copy() if isinstance(result, tuple): bbox_result, segm_result = result else: bbox_result, segm_result = result, None bboxes = np.vstack(bbox_result) # draw segmentation masks if segm_result is not None: segms = mmcv.concat_list(segm_result) inds = np.where(bboxes[:, -1] > score_thr)[0] for i in inds: color_mask = np.random.randint(0, 256, (1, 3), dtype=np.uint8) mask = maskUtils.decode(segms[i]).astype(np.bool) img[mask] = img[mask] * 0.5 + color_mask * 0.5 # draw bounding boxes labels = [ np.full(bbox.shape[0], i, dtype=np.int32) for i, bbox in enumerate(bbox_result) ] labels = np.concatenate(labels) mmcv.imshow_det_bboxes( img, bboxes, labels, class_names=class_names, score_thr=score_thr, show=show, wait_time=wait_time, out_file=out_file) if not (show or out_file): return img def show_result_pyplot(img, result, class_names, score_thr=0.3, fig_size=(15, 10)): """Visualize the detection results on the image. Args: img (str or np.ndarray): Image filename or loaded image. result (tuple[list] or list): The detection result, can be either (bbox, segm) or just bbox. class_names (list[str] or tuple[str]): A list of class names. score_thr (float): The threshold to visualize the bboxes and masks. fig_size (tuple): Figure size of the pyplot figure. out_file (str, optional): If specified, the visualization result will be written to the out file instead of shown in a window. """ img = show_result( img, result, class_names, score_thr=score_thr, show=False) plt.figure(figsize=fig_size) plt.imshow(mmcv.bgr2rgb(img))
{ "pile_set_name": "Github" }
with import <nixpkgs> {}; stdenv.mkDerivation rec { name = "env"; env = buildEnv { name = name; paths = buildInputs; }; buildInputs = [ ghc zlib ]; shellHook = '' export LD_LIBRARY_PATH="${zlib}/lib/" ''; }
{ "pile_set_name": "Github" }
// Package managedvirtualnetwork implements the Azure ARM Managedvirtualnetwork service API version 2019-06-01-preview. // // package managedvirtualnetwork // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "github.com/Azure/go-autorest/autorest" ) const ( // DefaultSynapseDNSSuffix is the default value for synapse dns suffix DefaultSynapseDNSSuffix = "dev.azuresynapse.net" ) // BaseClient is the base client for Managedvirtualnetwork. type BaseClient struct { autorest.Client SynapseDNSSuffix string } // New creates an instance of the BaseClient client. func New() BaseClient { return NewWithoutDefaults(DefaultSynapseDNSSuffix) } // NewWithoutDefaults creates an instance of the BaseClient client. func NewWithoutDefaults(synapseDNSSuffix string) BaseClient { return BaseClient{ Client: autorest.NewClientWithUserAgent(UserAgent()), SynapseDNSSuffix: synapseDNSSuffix, } }
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: e0a407f61ed4ada47b1fedf8e860493e folderAsset: yes DefaultImporter: userData:
{ "pile_set_name": "Github" }
/* Copyright (C) 2019, 2020 Monomax Software Pty Ltd * * This file is part of Dnote. * * Dnote is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Dnote is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Dnote. If not, see <https://www.gnu.org/licenses/>. */ import React from 'react'; import { NoteData } from 'jslib/operations/types'; import Time from '../../Common/Time'; import formatTime from '../../../helpers/time/format'; import { timeAgo } from '../../../helpers/time'; import styles from './Note.scss'; function formatAddedOn(ms: number): string { const d = new Date(ms); return formatTime(d, '%MMMM %DD, %YYYY'); } interface Props { note: NoteData; useTimeAgo: boolean; collapsed?: boolean; actions?: React.ReactElement; } const Footer: React.FunctionComponent<Props> = ({ collapsed, actions, note, useTimeAgo }) => { if (collapsed) { return null; } const updatedAt = new Date(note.updatedAt).getTime(); let timeText; if (useTimeAgo) { timeText = timeAgo(updatedAt); } else { timeText = formatAddedOn(updatedAt); } return ( <footer className={styles.footer}> <div className={styles.ts}> <span className={styles['ts-lead']}>Last edit: </span> <Time id="note-ts" text={timeText} ms={updatedAt} tooltipAlignment="left" tooltipDirection="bottom" /> </div> {actions} </footer> ); }; export default Footer;
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_74) on Mon Mar 05 13:43:59 PST 2018 --> <title>InterfaceStability (kafka 1.0.1 API)</title> <meta name="date" content="2018-03-05"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="InterfaceStability (kafka 1.0.1 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li><a href="../../../../../org/apache/kafka/common/annotation/InterfaceStability.Evolving.html" title="annotation in org.apache.kafka.common.annotation"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/kafka/common/annotation/InterfaceStability.html" target="_top">Frames</a></li> <li><a href="InterfaceStability.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested.class.summary">Nested</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#methods.inherited.from.class.java.lang.Object">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.apache.kafka.common.annotation</div> <h2 title="Class InterfaceStability" class="title">Class InterfaceStability</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>org.apache.kafka.common.annotation.InterfaceStability</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre><a href="../../../../../org/apache/kafka/common/annotation/InterfaceStability.Evolving.html" title="annotation in org.apache.kafka.common.annotation">@InterfaceStability.Evolving</a> public class <span class="typeNameLabel">InterfaceStability</span> extends java.lang.Object</pre> <div class="block">Annotation to inform users of how much to rely on a particular package, class or method not changing over time. Currently the stability can be <a href="../../../../../org/apache/kafka/common/annotation/InterfaceStability.Stable.html" title="annotation in org.apache.kafka.common.annotation"><code>InterfaceStability.Stable</code></a>, <a href="../../../../../org/apache/kafka/common/annotation/InterfaceStability.Evolving.html" title="annotation in org.apache.kafka.common.annotation"><code>InterfaceStability.Evolving</code></a> or <a href="../../../../../org/apache/kafka/common/annotation/InterfaceStability.Unstable.html" title="annotation in org.apache.kafka.common.annotation"><code>InterfaceStability.Unstable</code></a>.</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== NESTED CLASS SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="nested.class.summary"> <!-- --> </a> <h3>Nested Class Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Nested Class Summary table, listing nested classes, and an explanation"> <caption><span>Nested Classes</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static interface&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/apache/kafka/common/annotation/InterfaceStability.Evolving.html" title="annotation in org.apache.kafka.common.annotation">InterfaceStability.Evolving</a></span></code> <div class="block">Compatibility may be broken at minor release (i.e.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static interface&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/apache/kafka/common/annotation/InterfaceStability.Stable.html" title="annotation in org.apache.kafka.common.annotation">InterfaceStability.Stable</a></span></code> <div class="block">Compatibility is maintained in major, minor and patch releases with one exception: compatibility may be broken in a major release (i.e.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static interface&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/apache/kafka/common/annotation/InterfaceStability.Unstable.html" title="annotation in org.apache.kafka.common.annotation">InterfaceStability.Unstable</a></span></code> <div class="block">No guarantee is provided as to reliability or stability across any level of release granularity.</div> </td> </tr> </table> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../../org/apache/kafka/common/annotation/InterfaceStability.html#InterfaceStability--">InterfaceStability</a></span>()</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="InterfaceStability--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>InterfaceStability</h4> <pre>public&nbsp;InterfaceStability()</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li><a href="../../../../../org/apache/kafka/common/annotation/InterfaceStability.Evolving.html" title="annotation in org.apache.kafka.common.annotation"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/kafka/common/annotation/InterfaceStability.html" target="_top">Frames</a></li> <li><a href="InterfaceStability.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested.class.summary">Nested</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#methods.inherited.from.class.java.lang.Object">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 0e50ca2fea619b54ca82c4d766808f87 folderAsset: yes DefaultImporter: userData:
{ "pile_set_name": "Github" }
# ---------------------------------------------------- # This file is generated by the Qt Visual Studio Add-in. # ------------------------------------------------------ # This is a reminder that you are using a generated .pro file. # Remove it when you are finished editing this file. message("You are running qmake on a generated .pro file. This may not work!") HEADERS += ./resource.h \ ./pedollc.h \ ./PeDollcCore.h \ ../Grammar/Cube_Grammar.h \ ../Lexer/Cube_Lexer.h \ ../PainterEngineSubPacket/network/inc/Cube_AsynIO.h \ ../PainterEngineSubPacket/network/inc/Cube_SocketHeader.h \ ../PainterEngineSubPacket/network/inc/Cube_SocketTCP.h \ ../PainterEngineSubPacket/network/inc/Cube_SocketUDP.h \ ../PainterEngineSubPacket/network/inc/Cube_TCPFastIO.h \ ../PainterEngineSubPacket/network/inc/Cube_Thread.h SOURCES += ./main.cpp \ ./pedollc.cpp \ ./PeDollcCore.cpp \ ../Lexer/Cube_Lexer.cpp \ ../PainterEngineSubPacket/network/src/Cube_SocketTCP.cpp \ ../PainterEngineSubPacket/network/src/Cube_SocketUDP.cpp \ ../PainterEngineSubPacket/network/src/Cube_TCPFastIO.cpp \ ../PainterEngineSubPacket/network/src/Cube_Thread.cpp FORMS += ./pedollc.ui \ ./Connector.ui \ ./Register.ui TRANSLATIONS += ./pedollc_zh.ts RESOURCES += pedollc.qrc
{ "pile_set_name": "Github" }
/** * This example demonstrate how we can use peg_parser::parser to define a * command-line calculator and use a visitor pattern to evaluate the result. */ #include <peg_parser/generator.h> #include <cmath> #include <iostream> #include <unordered_map> int main() { using namespace std; struct Visitor; using Expression = peg_parser::Interpreter<void, Visitor &>::Expression; struct Visitor { float result; unordered_map<string, float> variables; float getValue(Expression e) { e.evaluate(*this); return result; } void visitAddition(Expression l, Expression r) { result = getValue(l) + getValue(r); } void visitSubtraction(Expression l, Expression r) { result = getValue(l) - getValue(r); } void visitMultiplication(Expression l, Expression r) { result = getValue(l) * getValue(r); } void visitDivision(Expression l, Expression r) { result = getValue(l) / getValue(r); } void visitPower(Expression l, Expression r) { result = pow(getValue(l), getValue(r)); } void visitVariable(Expression name) { result = variables[name.string()]; } void visitAssignment(Expression name, Expression value) { result = (variables[name.string()] = getValue(value)); } void visitNumber(Expression value) { result = stod(value.string()); } }; peg_parser::ParserGenerator<void, Visitor &> calculator; auto &g = calculator; g.setSeparator(g["Whitespace"] << "[\t ]"); g["Expression"] << "Assign | Sum"; g["Assign"] << "Name '=' Sum" >> [](auto e, auto &v) { v.visitAssignment(e[0], e[1]); }; g["Sum"] << "Add | Subtract | Product"; g["Product"] << "Multiply | Divide | Exponent"; g["Exponent"] << "Power | Atomic"; g["Atomic"] << "Number | Brackets | Variable"; g["Brackets"] << "'(' Sum ')'"; g["Add"] << "Sum '+' Product" >> [](auto e, auto &v) { v.visitAddition(e[0], e[1]); }; g["Subtract"] << "Sum '-' Product" >> [](auto e, auto &v) { v.visitSubtraction(e[0], e[1]); }; g["Multiply"] << "Product '*' Exponent" >> [](auto e, auto &v) { v.visitMultiplication(e[0], e[1]); }; g["Divide"] << "Product '/' Exponent" >> [](auto e, auto &v) { v.visitDivision(e[0], e[1]); }; g["Power"] << "Atomic ('^' Exponent)" >> [](auto e, auto &v) { v.visitPower(e[0], e[1]); }; g["Variable"] << "Name" >> [](auto e, auto &v) { v.visitVariable(e); }; g["Name"] << "[a-zA-Z] [a-zA-Z0-9]*"; g["Number"] << "'-'? [0-9]+ ('.' [0-9]+)?" >> [](auto e, auto &v) { v.visitNumber(e); }; g.setStart(g["Expression"]); cout << "Enter an expression to be evaluated.\n"; while (true) { string str; cout << "> "; getline(cin, str); if (str == "q" || str == "quit") { break; } try { Visitor visitor; calculator.run(str, visitor); cout << str << " = " << visitor.result << endl; } catch (peg_parser::SyntaxError &error) { auto syntax = error.syntax; cout << " "; cout << string(syntax->begin, ' '); cout << string(syntax->length(), '~'); cout << "^\n"; cout << " " << "Syntax error while parsing " << syntax->rule->name << endl; } } return 0; }
{ "pile_set_name": "Github" }
#ifndef RECOLOCALTRACKER_SISTRIPCLUSTERIZER_SISTRIPRECHITMATCH_H #define RECOLOCALTRACKER_SISTRIPCLUSTERIZER_SISTRIPRECHITMATCH_H #include "DataFormats/TrackerRecHit2D/interface/SiStripRecHit2D.h" #include "DataFormats/TrackerRecHit2D/interface/SiStripRecHit2DCollection.h" #include "DataFormats/TrackerRecHit2D/interface/SiStripMatchedRecHit2D.h" #include "DataFormats/TrackerRecHit2D/interface/SiStripMatchedRecHit2DCollection.h" #include "DataFormats/DetId/interface/DetId.h" #include "Geometry/CommonDetUnit/interface/GeomDet.h" #include "Geometry/CommonTopologies/interface/StripTopology.h" #include "DataFormats/CLHEP/interface/AlgebraicObjects.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "TrackingTools/TransientTrackingRecHit/interface/HelpertRecHit2DLocalPos.h" class GluedGeomDet; #include <cfloat> #include <functional> #include <memory> class SiStripRecHitMatcher { public: // may become a template argument typedef SiStripMatchedRecHit2DCollectionNew::FastFiller CollectorMatched; typedef SiStripRecHit2DCollectionNew::DetSet::const_iterator RecHitIterator; typedef std::vector<const SiStripRecHit2D*> SimpleHitCollection; typedef SimpleHitCollection::const_iterator SimpleHitIterator; typedef std::function<void(SiStripMatchedRecHit2D const&)> Collector; typedef std::pair<LocalPoint, LocalPoint> StripPosition; SiStripRecHitMatcher(const edm::ParameterSet& conf); SiStripRecHitMatcher(const double theScale); bool preFilter() const { return preFilter_; } inline static float sigmaPitch(LocalPoint const& pos, LocalError const& err, const StripTopology& topol) { MeasurementError error = topol.measurementError(pos, err); auto pitch = topol.localPitch(pos); return error.uu() * pitch * pitch; } // optimized matching iteration (the algo is the same, just recoded) template <typename MonoIterator, typename StereoIterator, typename CollectorHelper> void doubleMatch(MonoIterator monoRHiter, MonoIterator monoRHend, StereoIterator seconditer, StereoIterator seconditerend, const GluedGeomDet* gluedDet, LocalVector trdir, CollectorHelper& collectorHelper) const; //match a single hit std::unique_ptr<SiStripMatchedRecHit2D> match(const SiStripRecHit2D* monoRH, const SiStripRecHit2D* stereoRH, const GluedGeomDet* gluedDet, LocalVector trackdirection, bool force) const; // this is the one used by the RecHitConverter void match(const SiStripRecHit2D* monoRH, RecHitIterator begin, RecHitIterator end, CollectorMatched& collector, const GluedGeomDet* gluedDet, LocalVector trackdirection) const; void match(const SiStripRecHit2D* monoRH, SimpleHitIterator begin, SimpleHitIterator end, CollectorMatched& collector, const GluedGeomDet* gluedDet, LocalVector trackdirection) const; // project strip coordinates on Glueddet StripPosition project(const GeomDetUnit* det, const GluedGeomDet* glueddet, StripPosition strip, LocalVector trackdirection) const; // needed by the obsolete version still in use on some architectures void match(const SiStripRecHit2D* monoRH, SimpleHitIterator begin, SimpleHitIterator end, edm::OwnVector<SiStripMatchedRecHit2D>& collector, const GluedGeomDet* gluedDet, LocalVector trackdirection) const; void match(const SiStripRecHit2D* monoRH, SimpleHitIterator begin, SimpleHitIterator end, std::vector<SiStripMatchedRecHit2D*>& collector, const GluedGeomDet* gluedDet, LocalVector trackdirection) const; /// the actual implementation void match(const SiStripRecHit2D* monoRH, SimpleHitIterator begin, SimpleHitIterator end, Collector& collector, const GluedGeomDet* gluedDet, LocalVector trackdirection) const; float scale_; bool preFilter_ = false; }; #include "DataFormats/GeometryVector/interface/Basic3DVector.h" #if defined(USE_SSEVECT) || defined(USE_EXTVECT) #define DOUBLE_MATCH #endif #ifdef DOUBLE_MATCH #if defined(USE_SSEVECT) using mathSSE::Rot3F; using mathSSE::Vec2D; using mathSSE::Vec3D; using mathSSE::Vec3F; #endif #include "Geometry/CommonDetUnit/interface/GluedGeomDet.h" #include "TrackingTools/TransientTrackingRecHit/interface/HelpertRecHit2DLocalPos.h" namespace matcherDetails { struct StereoInfo { Vec2D c1vec; const SiStripRecHit2D* secondHit; float sigmap22; double m10, m11; }; } // namespace matcherDetails template <typename MonoIterator, typename StereoIterator, typename CollectorHelper> void SiStripRecHitMatcher::doubleMatch(MonoIterator monoRHiter, MonoIterator monoRHend, StereoIterator seconditer, StereoIterator seconditerend, const GluedGeomDet* gluedDet, LocalVector trdir, CollectorHelper& collectorHelper) const { using matcherDetails::StereoInfo; typedef GloballyPositioned<float> ToGlobal; typedef typename GloballyPositioned<float>::ToLocal ToLocal; // hits in both mono and stero // match bool notk = trdir.mag2() < float(FLT_MIN); // FIXME we shall find a faster approximation for trdir: not useful to compute it each time for each strip // stripdet = mono // partnerstripdet = stereo const GeomDetUnit* stripdet = gluedDet->monoDet(); const GeomDetUnit* partnerstripdet = gluedDet->stereoDet(); const StripTopology& topol = (const StripTopology&)stripdet->topology(); const StripTopology& partnertopol = (const StripTopology&)partnerstripdet->topology(); // toGlobal is fast, toLocal is slow ToGlobal const& stripDetTrans = stripdet->surface(); ToGlobal const& partnerStripDetTrans = partnerstripdet->surface(); ToLocal gluedDetInvTrans(gluedDet->surface()); std::vector<StereoInfo> cache(std::distance(seconditer, seconditerend)); //iterate on stereo rechits // fill cache with relevant info int cacheSize = 0; for (; seconditer != seconditerend; ++seconditer) { const SiStripRecHit2D& secondHit = CollectorHelper::stereoHit(seconditer); float sigmap22 = sigmaPitch(secondHit.localPosition(), secondHit.localPositionError(), partnertopol); // assert (sigmap22>=0); auto STEREOpointX = partnertopol.measurementPosition(secondHit.localPositionFast()).x(); MeasurementPoint STEREOpointini(STEREOpointX, -0.5f); MeasurementPoint STEREOpointend(STEREOpointX, 0.5f); LocalPoint locp1 = partnertopol.localPosition(STEREOpointini); LocalPoint locp2 = partnertopol.localPosition(STEREOpointend); GlobalPoint globalpointini = partnerStripDetTrans.toGlobal(locp1); GlobalPoint globalpointend = partnerStripDetTrans.toGlobal(locp2); // position of the initial and final point of the strip in glued local coordinates LocalPoint positiononGluedini = gluedDetInvTrans.toLocal(globalpointini); LocalPoint positiononGluedend = gluedDetInvTrans.toLocal(globalpointend); // in case of no track hypothesis assume a track from the origin through the center of the strip if (notk) { const LocalPoint& lcenterofstrip = secondHit.localPositionFast(); GlobalPoint gcenterofstrip = partnerStripDetTrans.toGlobal(lcenterofstrip); GlobalVector gtrackdirection = gcenterofstrip - GlobalPoint(0, 0, 0); trdir = gluedDetInvTrans.toLocal(gtrackdirection); } Vec3F offset = trdir.basicVector().v * positiononGluedini.z() / trdir.z(); Vec3F ret1 = positiononGluedini.basicVector().v - offset; Vec3F ret2 = positiononGluedend.basicVector().v - offset; double m10 = -(ret2[1] - ret1[1]); double m11 = ret2[0] - ret1[0]; double dd = m11 * ret1[1] + m10 * ret1[0]; Vec2D c1vec{dd, dd}; // store StereoInfo info = {c1vec, &secondHit, sigmap22, m10, m11}; cache[cacheSize++] = info; } for (; monoRHiter != monoRHend; ++monoRHiter) { SiStripRecHit2D const& monoRH = CollectorHelper::monoHit(monoRHiter); // position of the initial and final point of the strip (RPHI cluster) in local strip coordinates auto RPHIpointX = topol.measurementPosition(monoRH.localPositionFast()).x(); MeasurementPoint RPHIpointini(RPHIpointX, -0.5f); MeasurementPoint RPHIpointend(RPHIpointX, 0.5f); // position of the initial and final point of the strip in local coordinates (mono det) //StripPosition stripmono=StripPosition(topol.localPosition(RPHIpointini),topol.localPosition(RPHIpointend)); LocalPoint locp1o = topol.localPosition(RPHIpointini); LocalPoint locp2o = topol.localPosition(RPHIpointend); // in case of no track hypothesis assume a track from the origin through the center of the strip if (notk) { const LocalPoint& lcenterofstrip = monoRH.localPositionFast(); GlobalPoint gcenterofstrip = stripDetTrans.toGlobal(lcenterofstrip); GlobalVector gtrackdirection = gcenterofstrip - GlobalPoint(0, 0, 0); trdir = gluedDetInvTrans.toLocal(gtrackdirection); } //project mono hit on glued det //StripPosition projectedstripmono=project(stripdet,gluedDet,stripmono,trackdirection); GlobalPoint globalpointini = stripDetTrans.toGlobal(locp1o); GlobalPoint globalpointend = stripDetTrans.toGlobal(locp2o); // position of the initial and final point of the strip in glued local coordinates LocalPoint positiononGluedini = gluedDetInvTrans.toLocal(globalpointini); LocalPoint positiononGluedend = gluedDetInvTrans.toLocal(globalpointend); Vec3F offset = trdir.basicVector().v * positiononGluedini.z() / trdir.z(); Vec3F projini = positiononGluedini.basicVector().v - offset; Vec3F projend = positiononGluedend.basicVector().v - offset; // ret1o = ret1o + (trdir * (ret1o.getSimd(2) / trdirz)); // ret2o = ret2o + (trdir * (ret2o.getSimd(2) / trdirz)); double m00 = -(projend[1] - projini[1]); //-(projectedstripmono.second.y()-projectedstripmono.first.y()); double m01 = (projend[0] - projini[0]); // (projectedstripmono.second.x()-projectedstripmono.first.x()); double c0 = m01 * projini[1] + m00 * projini[0]; //m01*projectedstripmono.first.y() + m00*projectedstripmono.first.x(); Vec2D c0vec{c0, c0}; Vec2D minv00{-m01, m00}; //error calculation (the part that depends on mono RH only) double c1 = -m00; double s1 = -m01; double l1 = 1. / (c1 * c1 + s1 * s1); float sigmap12 = sigmaPitch(monoRH.localPosition(), monoRH.localPositionError(), topol); // float sigmap12 = monoRH.sigmaPitch(); // assert(sigmap12>=0); //float code float fc1(c1), fs1(s1); Vec3F scc1{fs1, fc1, fc1, 0.f}; Vec3F ssc1{fs1, fs1, fc1, 0.f}; const Vec3F cslsimd = scc1 * ssc1 * float(l1); for (int i = 0; i != cacheSize; ++i) { StereoInfo const si = cache[i]; // match Vec2D minv10{si.m11, -si.m10}; double mult = 1. / (m00 * si.m11 - m01 * si.m10); Vec2D resultmatmul = mult * (minv10 * c0vec + minv00 * si.c1vec); Local2DPoint position(resultmatmul[0], resultmatmul[1]); // LocalError tempError (100,0,100); if (!((gluedDet->surface()).bounds().inside(position, 10.f * scale_))) continue; double c2 = -si.m10; double s2 = -si.m11; double l2 = 1. / (c2 * c2 + s2 * s2); double diff = (c1 * s2 - c2 * s1); double invdet2 = 1. / (diff * diff * l1 * l2); float fc2(c2), fs2(s2), fid2(invdet2); Vec3F invdet2simd{fid2, -fid2, fid2, 0.f}; Vec3F ccssimd{fs2, fc2, fc2, 0.f}; Vec3F csssimd{fs2, fs2, fc2, 0.f}; Vec3F result = invdet2simd * (si.sigmap22 * cslsimd + sigmap12 * ccssimd * csssimd * float(l2)); LocalError error(result[0], result[1], result[2]); if ((gluedDet->surface()).bounds().inside(position, error, scale_)) { //if it is inside the gluedet bonds //Change NSigmaInside in the configuration file to accept more hits //...and add it to the Rechit collection collectorHelper.collector()( SiStripMatchedRecHit2D(LocalPoint(position), error, *gluedDet, &monoRH, si.secondHit)); } } // loop on cache info collectorHelper.closure(monoRHiter); } // loop on mono hit } #endif //DOUBLE_MATCH #endif // RECOLOCALTRACKER_SISTRIPCLUSTERIZER_SISTRIPRECHITMATCH_H
{ "pile_set_name": "Github" }
package com.mscharhag.methodvalidation; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.validation.beanvalidation.MethodValidationPostProcessor; @SpringBootApplication public class ExampleApplication { @Bean public MethodValidationPostProcessor methodValidationPostProcessor() { return new MethodValidationPostProcessor(); } public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(ExampleApplication.class); UserService userService = context.getBean(UserService.class); userService.getUser("123"); // the following to lines will fail the validation and raise a ConstraintViolationException // userService.getUser(""); // userService.getUser(null); userService.createUser(new User("John")); // the following to lines will fail the validation and raise a ConstraintViolationException // userService.createUser(new User("")); // userService.createUser(new User(null)); } }
{ "pile_set_name": "Github" }
# Mantid Repository : https://github.com/mantidproject/mantid # # Copyright &copy; 2019 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source, # Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS # SPDX - License - Identifier: GPL - 3.0 + from ISISReflectometryWorkflowBase import * import systemtesting class ISISReflectometryWorkflowSlicingTest(systemtesting.MantidSystemTest, ISISReflectometryWorkflowBase): ''' Test the ISIS Reflectometry workflow algorithms with event slicing done internally in the workflow algorithm ''' run_numbers = ['45222'] first_transmission_runs = ['45226'] second_transmission_runs = ['45227'] transmission_workspace_name = ['TRANS'] input_workspaces_file = 'ISISReflectometryEventTestRuns.nxs' reference_file = 'ISISReflectometryWorkflowSlicingResult.nxs' def __init__(self): super(ISISReflectometryWorkflowSlicingTest, self).__init__() self.tolerance = 1e-6 def requiredFiles(self): return [self.reference_file, self.input_workspaces_file] def validate(self): return (self.result_workspace_name, self.reference_file) def runTest(self): self.setupTest() reduceRun(self.run_numbers[0], 0.5, self.first_transmission_runs, self.second_transmission_runs, time_interval=60) # Delete the interim transmission workspaces. These are currently output # for input groups (i.e. when we're slicing) even when Debug is not on. DeleteWorkspace('TRANS_LAM_45226') DeleteWorkspace('TRANS_LAM_45227') self.finaliseResults() @staticmethod def regenerateReferenceFileByReducing(): setupInstrument() test = ISISReflectometryWorkflowSlicingTest() test.runTest() SaveNexus(InputWorkspace=self.result_workspace_name, Filename=self.reference_file)
{ "pile_set_name": "Github" }
#Tue Feb 17 18:35:42 CET 2009 eclipse.preferences.version=1 encoding/<project>=UTF-8
{ "pile_set_name": "Github" }
'use strict'; var assertRecord = require('../helpers/assertRecord'); var Type = require('./Type'); // https://www.ecma-international.org/ecma-262/6.0/#sec-frompropertydescriptor module.exports = function FromPropertyDescriptor(Desc) { if (typeof Desc === 'undefined') { return Desc; } assertRecord(Type, 'Property Descriptor', 'Desc', Desc); var obj = {}; if ('[[Value]]' in Desc) { obj.value = Desc['[[Value]]']; } if ('[[Writable]]' in Desc) { obj.writable = Desc['[[Writable]]']; } if ('[[Get]]' in Desc) { obj.get = Desc['[[Get]]']; } if ('[[Set]]' in Desc) { obj.set = Desc['[[Set]]']; } if ('[[Enumerable]]' in Desc) { obj.enumerable = Desc['[[Enumerable]]']; } if ('[[Configurable]]' in Desc) { obj.configurable = Desc['[[Configurable]]']; } return obj; };
{ "pile_set_name": "Github" }
/* * Flare * -------------- * Copyright (C) 2008-2014 GREE, Inc. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * queue_node_sync.cc * * implementation of gree::flare::queue_node_sync * * @author Masaki Fujimoto <[email protected]> * * $Id$ */ #include "queue_node_sync.h" #include "op_node_sync.h" namespace gree { namespace flare { // {{{ ctor/dtor /** * ctor for queue_node_sync */ queue_node_sync::queue_node_sync(cluster* cl): thread_queue("node_sync"), _cluster(cl) { this->_node_vector = this->_cluster->get_node(); this->_node_map_version = this->_cluster->get_node_map_version(); } /** * dtor for queue_node_sync */ queue_node_sync::~queue_node_sync() { } // }}} // {{{ operator overloads // }}} // {{{ public methods int queue_node_sync::run(shared_connection c) { op_node_sync* p = new op_node_sync(c, this->_cluster); if (p->run_client(this->_node_vector, this->_node_map_version) < 0) { delete p; return -1; } delete p; return 0; } // }}} // {{{ protected methods // }}} // {{{ private methods // }}} } // namespace flare } // namespace gree // vim: foldmethod=marker tabstop=2 shiftwidth=2 autoindent
{ "pile_set_name": "Github" }
/* Copyright 2015 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 transport import ( "net" "net/http" ) // Config holds various options for establishing a transport. type Config struct { // UserAgent is an optional field that specifies the caller of this // request. UserAgent string // The base TLS configuration for this transport. TLS TLSConfig // Username and password for basic authentication Username string Password string // Bearer token for authentication BearerToken string // Impersonate is the config that this Config will impersonate using Impersonate ImpersonationConfig // Transport may be used for custom HTTP behavior. This attribute may // not be specified with the TLS client certificate options. Use // WrapTransport for most client level operations. Transport http.RoundTripper // WrapTransport will be invoked for custom HTTP behavior after the // underlying transport is initialized (either the transport created // from TLSClientConfig, Transport, or http.DefaultTransport). The // config may layer other RoundTrippers on top of the returned // RoundTripper. WrapTransport func(rt http.RoundTripper) http.RoundTripper // Dial specifies the dial function for creating unencrypted TCP connections. Dial func(network, addr string) (net.Conn, error) } // ImpersonationConfig has all the available impersonation options type ImpersonationConfig struct { // UserName matches user.Info.GetName() UserName string // Groups matches user.Info.GetGroups() Groups []string // Extra matches user.Info.GetExtra() Extra map[string][]string } // HasCA returns whether the configuration has a certificate authority or not. func (c *Config) HasCA() bool { return len(c.TLS.CAData) > 0 || len(c.TLS.CAFile) > 0 } // HasBasicAuth returns whether the configuration has basic authentication or not. func (c *Config) HasBasicAuth() bool { return len(c.Username) != 0 } // HasTokenAuth returns whether the configuration has token authentication or not. func (c *Config) HasTokenAuth() bool { return len(c.BearerToken) != 0 } // HasCertAuth returns whether the configuration has certificate authentication or not. func (c *Config) HasCertAuth() bool { return len(c.TLS.CertData) != 0 || len(c.TLS.CertFile) != 0 } // TLSConfig holds the information needed to set up a TLS transport. type TLSConfig struct { CAFile string // Path of the PEM-encoded server trusted root certificates. CertFile string // Path of the PEM-encoded client certificate. KeyFile string // Path of the PEM-encoded client key. Insecure bool // Server should be accessed without verifying the certificate. For testing only. ServerName string // Override for the server name passed to the server for SNI and used to verify certificates. CAData []byte // Bytes of the PEM-encoded server trusted root certificates. Supercedes CAFile. CertData []byte // Bytes of the PEM-encoded client certificate. Supercedes CertFile. KeyData []byte // Bytes of the PEM-encoded client key. Supercedes KeyFile. }
{ "pile_set_name": "Github" }
/** ****************************************************************************** * @file stm32f10x_adc.c * @author MCD Application Team * @version V3.5.0 * @date 11-March-2011 * @brief This file provides all the ADC firmware functions. ****************************************************************************** * @attention * * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. * * <h2><center>&copy; COPYRIGHT 2011 STMicroelectronics</center></h2> ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32f10x_adc.h" #include "stm32f10x_rcc.h" /** @addtogroup STM32F10x_StdPeriph_Driver * @{ */ /** @defgroup ADC * @brief ADC driver modules * @{ */ /** @defgroup ADC_Private_TypesDefinitions * @{ */ /** * @} */ /** @defgroup ADC_Private_Defines * @{ */ /* ADC DISCNUM mask */ #define CR1_DISCNUM_Reset ((uint32_t)0xFFFF1FFF) /* ADC DISCEN mask */ #define CR1_DISCEN_Set ((uint32_t)0x00000800) #define CR1_DISCEN_Reset ((uint32_t)0xFFFFF7FF) /* ADC JAUTO mask */ #define CR1_JAUTO_Set ((uint32_t)0x00000400) #define CR1_JAUTO_Reset ((uint32_t)0xFFFFFBFF) /* ADC JDISCEN mask */ #define CR1_JDISCEN_Set ((uint32_t)0x00001000) #define CR1_JDISCEN_Reset ((uint32_t)0xFFFFEFFF) /* ADC AWDCH mask */ #define CR1_AWDCH_Reset ((uint32_t)0xFFFFFFE0) /* ADC Analog watchdog enable mode mask */ #define CR1_AWDMode_Reset ((uint32_t)0xFF3FFDFF) /* CR1 register Mask */ #define CR1_CLEAR_Mask ((uint32_t)0xFFF0FEFF) /* ADC ADON mask */ #define CR2_ADON_Set ((uint32_t)0x00000001) #define CR2_ADON_Reset ((uint32_t)0xFFFFFFFE) /* ADC DMA mask */ #define CR2_DMA_Set ((uint32_t)0x00000100) #define CR2_DMA_Reset ((uint32_t)0xFFFFFEFF) /* ADC RSTCAL mask */ #define CR2_RSTCAL_Set ((uint32_t)0x00000008) /* ADC CAL mask */ #define CR2_CAL_Set ((uint32_t)0x00000004) /* ADC SWSTART mask */ #define CR2_SWSTART_Set ((uint32_t)0x00400000) /* ADC EXTTRIG mask */ #define CR2_EXTTRIG_Set ((uint32_t)0x00100000) #define CR2_EXTTRIG_Reset ((uint32_t)0xFFEFFFFF) /* ADC Software start mask */ #define CR2_EXTTRIG_SWSTART_Set ((uint32_t)0x00500000) #define CR2_EXTTRIG_SWSTART_Reset ((uint32_t)0xFFAFFFFF) /* ADC JEXTSEL mask */ #define CR2_JEXTSEL_Reset ((uint32_t)0xFFFF8FFF) /* ADC JEXTTRIG mask */ #define CR2_JEXTTRIG_Set ((uint32_t)0x00008000) #define CR2_JEXTTRIG_Reset ((uint32_t)0xFFFF7FFF) /* ADC JSWSTART mask */ #define CR2_JSWSTART_Set ((uint32_t)0x00200000) /* ADC injected software start mask */ #define CR2_JEXTTRIG_JSWSTART_Set ((uint32_t)0x00208000) #define CR2_JEXTTRIG_JSWSTART_Reset ((uint32_t)0xFFDF7FFF) /* ADC TSPD mask */ #define CR2_TSVREFE_Set ((uint32_t)0x00800000) #define CR2_TSVREFE_Reset ((uint32_t)0xFF7FFFFF) /* CR2 register Mask */ #define CR2_CLEAR_Mask ((uint32_t)0xFFF1F7FD) /* ADC SQx mask */ #define SQR3_SQ_Set ((uint32_t)0x0000001F) #define SQR2_SQ_Set ((uint32_t)0x0000001F) #define SQR1_SQ_Set ((uint32_t)0x0000001F) /* SQR1 register Mask */ #define SQR1_CLEAR_Mask ((uint32_t)0xFF0FFFFF) /* ADC JSQx mask */ #define JSQR_JSQ_Set ((uint32_t)0x0000001F) /* ADC JL mask */ #define JSQR_JL_Set ((uint32_t)0x00300000) #define JSQR_JL_Reset ((uint32_t)0xFFCFFFFF) /* ADC SMPx mask */ #define SMPR1_SMP_Set ((uint32_t)0x00000007) #define SMPR2_SMP_Set ((uint32_t)0x00000007) /* ADC JDRx registers offset */ #define JDR_Offset ((uint8_t)0x28) /* ADC1 DR register base address */ #define DR_ADDRESS ((uint32_t)0x4001244C) /** * @} */ /** @defgroup ADC_Private_Macros * @{ */ /** * @} */ /** @defgroup ADC_Private_Variables * @{ */ /** * @} */ /** @defgroup ADC_Private_FunctionPrototypes * @{ */ /** * @} */ /** @defgroup ADC_Private_Functions * @{ */ /** * @brief Deinitializes the ADCx peripheral registers to their default reset values. * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @retval None */ void ADC_DeInit(ADC_TypeDef* ADCx) { /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); if (ADCx == ADC1) { /* Enable ADC1 reset state */ RCC_APB2PeriphResetCmd(RCC_APB2Periph_ADC1, ENABLE); /* Release ADC1 from reset state */ RCC_APB2PeriphResetCmd(RCC_APB2Periph_ADC1, DISABLE); } else if (ADCx == ADC2) { /* Enable ADC2 reset state */ RCC_APB2PeriphResetCmd(RCC_APB2Periph_ADC2, ENABLE); /* Release ADC2 from reset state */ RCC_APB2PeriphResetCmd(RCC_APB2Periph_ADC2, DISABLE); } else { if (ADCx == ADC3) { /* Enable ADC3 reset state */ RCC_APB2PeriphResetCmd(RCC_APB2Periph_ADC3, ENABLE); /* Release ADC3 from reset state */ RCC_APB2PeriphResetCmd(RCC_APB2Periph_ADC3, DISABLE); } } } /** * @brief Initializes the ADCx peripheral according to the specified parameters * in the ADC_InitStruct. * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @param ADC_InitStruct: pointer to an ADC_InitTypeDef structure that contains * the configuration information for the specified ADC peripheral. * @retval None */ void ADC_Init(ADC_TypeDef* ADCx, ADC_InitTypeDef* ADC_InitStruct) { uint32_t tmpreg1 = 0; uint8_t tmpreg2 = 0; /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); assert_param(IS_ADC_MODE(ADC_InitStruct->ADC_Mode)); assert_param(IS_FUNCTIONAL_STATE(ADC_InitStruct->ADC_ScanConvMode)); assert_param(IS_FUNCTIONAL_STATE(ADC_InitStruct->ADC_ContinuousConvMode)); assert_param(IS_ADC_EXT_TRIG(ADC_InitStruct->ADC_ExternalTrigConv)); assert_param(IS_ADC_DATA_ALIGN(ADC_InitStruct->ADC_DataAlign)); assert_param(IS_ADC_REGULAR_LENGTH(ADC_InitStruct->ADC_NbrOfChannel)); /*---------------------------- ADCx CR1 Configuration -----------------*/ /* Get the ADCx CR1 value */ tmpreg1 = ADCx->CR1; /* Clear DUALMOD and SCAN bits */ tmpreg1 &= CR1_CLEAR_Mask; /* Configure ADCx: Dual mode and scan conversion mode */ /* Set DUALMOD bits according to ADC_Mode value */ /* Set SCAN bit according to ADC_ScanConvMode value */ tmpreg1 |= (uint32_t)(ADC_InitStruct->ADC_Mode | ((uint32_t)ADC_InitStruct->ADC_ScanConvMode << 8)); /* Write to ADCx CR1 */ ADCx->CR1 = tmpreg1; /*---------------------------- ADCx CR2 Configuration -----------------*/ /* Get the ADCx CR2 value */ tmpreg1 = ADCx->CR2; /* Clear CONT, ALIGN and EXTSEL bits */ tmpreg1 &= CR2_CLEAR_Mask; /* Configure ADCx: external trigger event and continuous conversion mode */ /* Set ALIGN bit according to ADC_DataAlign value */ /* Set EXTSEL bits according to ADC_ExternalTrigConv value */ /* Set CONT bit according to ADC_ContinuousConvMode value */ tmpreg1 |= (uint32_t)(ADC_InitStruct->ADC_DataAlign | ADC_InitStruct->ADC_ExternalTrigConv | ((uint32_t)ADC_InitStruct->ADC_ContinuousConvMode << 1)); /* Write to ADCx CR2 */ ADCx->CR2 = tmpreg1; /*---------------------------- ADCx SQR1 Configuration -----------------*/ /* Get the ADCx SQR1 value */ tmpreg1 = ADCx->SQR1; /* Clear L bits */ tmpreg1 &= SQR1_CLEAR_Mask; /* Configure ADCx: regular channel sequence length */ /* Set L bits according to ADC_NbrOfChannel value */ tmpreg2 |= (uint8_t) (ADC_InitStruct->ADC_NbrOfChannel - (uint8_t)1); tmpreg1 |= (uint32_t)tmpreg2 << 20; /* Write to ADCx SQR1 */ ADCx->SQR1 = tmpreg1; } /** * @brief Fills each ADC_InitStruct member with its default value. * @param ADC_InitStruct : pointer to an ADC_InitTypeDef structure which will be initialized. * @retval None */ void ADC_StructInit(ADC_InitTypeDef* ADC_InitStruct) { /* Reset ADC init structure parameters values */ /* Initialize the ADC_Mode member */ ADC_InitStruct->ADC_Mode = ADC_Mode_Independent; /* initialize the ADC_ScanConvMode member */ ADC_InitStruct->ADC_ScanConvMode = DISABLE; /* Initialize the ADC_ContinuousConvMode member */ ADC_InitStruct->ADC_ContinuousConvMode = DISABLE; /* Initialize the ADC_ExternalTrigConv member */ ADC_InitStruct->ADC_ExternalTrigConv = ADC_ExternalTrigConv_T1_CC1; /* Initialize the ADC_DataAlign member */ ADC_InitStruct->ADC_DataAlign = ADC_DataAlign_Right; /* Initialize the ADC_NbrOfChannel member */ ADC_InitStruct->ADC_NbrOfChannel = 1; } /** * @brief Enables or disables the specified ADC peripheral. * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @param NewState: new state of the ADCx peripheral. * This parameter can be: ENABLE or DISABLE. * @retval None */ void ADC_Cmd(ADC_TypeDef* ADCx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Set the ADON bit to wake up the ADC from power down mode */ ADCx->CR2 |= CR2_ADON_Set; } else { /* Disable the selected ADC peripheral */ ADCx->CR2 &= CR2_ADON_Reset; } } /** * @brief Enables or disables the specified ADC DMA request. * @param ADCx: where x can be 1 or 3 to select the ADC peripheral. * Note: ADC2 hasn't a DMA capability. * @param NewState: new state of the selected ADC DMA transfer. * This parameter can be: ENABLE or DISABLE. * @retval None */ void ADC_DMACmd(ADC_TypeDef* ADCx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_ADC_DMA_PERIPH(ADCx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the selected ADC DMA request */ ADCx->CR2 |= CR2_DMA_Set; } else { /* Disable the selected ADC DMA request */ ADCx->CR2 &= CR2_DMA_Reset; } } /** * @brief Enables or disables the specified ADC interrupts. * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @param ADC_IT: specifies the ADC interrupt sources to be enabled or disabled. * This parameter can be any combination of the following values: * @arg ADC_IT_EOC: End of conversion interrupt mask * @arg ADC_IT_AWD: Analog watchdog interrupt mask * @arg ADC_IT_JEOC: End of injected conversion interrupt mask * @param NewState: new state of the specified ADC interrupts. * This parameter can be: ENABLE or DISABLE. * @retval None */ void ADC_ITConfig(ADC_TypeDef* ADCx, uint16_t ADC_IT, FunctionalState NewState) { uint8_t itmask = 0; /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); assert_param(IS_ADC_IT(ADC_IT)); /* Get the ADC IT index */ itmask = (uint8_t)ADC_IT; if (NewState != DISABLE) { /* Enable the selected ADC interrupts */ ADCx->CR1 |= itmask; } else { /* Disable the selected ADC interrupts */ ADCx->CR1 &= (~(uint32_t)itmask); } } /** * @brief Resets the selected ADC calibration registers. * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @retval None */ void ADC_ResetCalibration(ADC_TypeDef* ADCx) { /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); /* Resets the selected ADC calibration registers */ ADCx->CR2 |= CR2_RSTCAL_Set; } /** * @brief Gets the selected ADC reset calibration registers status. * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @retval The new state of ADC reset calibration registers (SET or RESET). */ FlagStatus ADC_GetResetCalibrationStatus(ADC_TypeDef* ADCx) { FlagStatus bitstatus = RESET; /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); /* Check the status of RSTCAL bit */ if ((ADCx->CR2 & CR2_RSTCAL_Set) != (uint32_t)RESET) { /* RSTCAL bit is set */ bitstatus = SET; } else { /* RSTCAL bit is reset */ bitstatus = RESET; } /* Return the RSTCAL bit status */ return bitstatus; } /** * @brief Starts the selected ADC calibration process. * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @retval None */ void ADC_StartCalibration(ADC_TypeDef* ADCx) { /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); /* Enable the selected ADC calibration process */ ADCx->CR2 |= CR2_CAL_Set; } /** * @brief Gets the selected ADC calibration status. * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @retval The new state of ADC calibration (SET or RESET). */ FlagStatus ADC_GetCalibrationStatus(ADC_TypeDef* ADCx) { FlagStatus bitstatus = RESET; /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); /* Check the status of CAL bit */ if ((ADCx->CR2 & CR2_CAL_Set) != (uint32_t)RESET) { /* CAL bit is set: calibration on going */ bitstatus = SET; } else { /* CAL bit is reset: end of calibration */ bitstatus = RESET; } /* Return the CAL bit status */ return bitstatus; } /** * @brief Enables or disables the selected ADC software start conversion . * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @param NewState: new state of the selected ADC software start conversion. * This parameter can be: ENABLE or DISABLE. * @retval None */ void ADC_SoftwareStartConvCmd(ADC_TypeDef* ADCx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the selected ADC conversion on external event and start the selected ADC conversion */ ADCx->CR2 |= CR2_EXTTRIG_SWSTART_Set; } else { /* Disable the selected ADC conversion on external event and stop the selected ADC conversion */ ADCx->CR2 &= CR2_EXTTRIG_SWSTART_Reset; } } /** * @brief Gets the selected ADC Software start conversion Status. * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @retval The new state of ADC software start conversion (SET or RESET). */ FlagStatus ADC_GetSoftwareStartConvStatus(ADC_TypeDef* ADCx) { FlagStatus bitstatus = RESET; /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); /* Check the status of SWSTART bit */ if ((ADCx->CR2 & CR2_SWSTART_Set) != (uint32_t)RESET) { /* SWSTART bit is set */ bitstatus = SET; } else { /* SWSTART bit is reset */ bitstatus = RESET; } /* Return the SWSTART bit status */ return bitstatus; } /** * @brief Configures the discontinuous mode for the selected ADC regular * group channel. * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @param Number: specifies the discontinuous mode regular channel * count value. This number must be between 1 and 8. * @retval None */ void ADC_DiscModeChannelCountConfig(ADC_TypeDef* ADCx, uint8_t Number) { uint32_t tmpreg1 = 0; uint32_t tmpreg2 = 0; /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); assert_param(IS_ADC_REGULAR_DISC_NUMBER(Number)); /* Get the old register value */ tmpreg1 = ADCx->CR1; /* Clear the old discontinuous mode channel count */ tmpreg1 &= CR1_DISCNUM_Reset; /* Set the discontinuous mode channel count */ tmpreg2 = Number - 1; tmpreg1 |= tmpreg2 << 13; /* Store the new register value */ ADCx->CR1 = tmpreg1; } /** * @brief Enables or disables the discontinuous mode on regular group * channel for the specified ADC * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @param NewState: new state of the selected ADC discontinuous mode * on regular group channel. * This parameter can be: ENABLE or DISABLE. * @retval None */ void ADC_DiscModeCmd(ADC_TypeDef* ADCx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the selected ADC regular discontinuous mode */ ADCx->CR1 |= CR1_DISCEN_Set; } else { /* Disable the selected ADC regular discontinuous mode */ ADCx->CR1 &= CR1_DISCEN_Reset; } } /** * @brief Configures for the selected ADC regular channel its corresponding * rank in the sequencer and its sample time. * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @param ADC_Channel: the ADC channel to configure. * This parameter can be one of the following values: * @arg ADC_Channel_0: ADC Channel0 selected * @arg ADC_Channel_1: ADC Channel1 selected * @arg ADC_Channel_2: ADC Channel2 selected * @arg ADC_Channel_3: ADC Channel3 selected * @arg ADC_Channel_4: ADC Channel4 selected * @arg ADC_Channel_5: ADC Channel5 selected * @arg ADC_Channel_6: ADC Channel6 selected * @arg ADC_Channel_7: ADC Channel7 selected * @arg ADC_Channel_8: ADC Channel8 selected * @arg ADC_Channel_9: ADC Channel9 selected * @arg ADC_Channel_10: ADC Channel10 selected * @arg ADC_Channel_11: ADC Channel11 selected * @arg ADC_Channel_12: ADC Channel12 selected * @arg ADC_Channel_13: ADC Channel13 selected * @arg ADC_Channel_14: ADC Channel14 selected * @arg ADC_Channel_15: ADC Channel15 selected * @arg ADC_Channel_16: ADC Channel16 selected * @arg ADC_Channel_17: ADC Channel17 selected * @param Rank: The rank in the regular group sequencer. This parameter must be between 1 to 16. * @param ADC_SampleTime: The sample time value to be set for the selected channel. * This parameter can be one of the following values: * @arg ADC_SampleTime_1Cycles5: Sample time equal to 1.5 cycles * @arg ADC_SampleTime_7Cycles5: Sample time equal to 7.5 cycles * @arg ADC_SampleTime_13Cycles5: Sample time equal to 13.5 cycles * @arg ADC_SampleTime_28Cycles5: Sample time equal to 28.5 cycles * @arg ADC_SampleTime_41Cycles5: Sample time equal to 41.5 cycles * @arg ADC_SampleTime_55Cycles5: Sample time equal to 55.5 cycles * @arg ADC_SampleTime_71Cycles5: Sample time equal to 71.5 cycles * @arg ADC_SampleTime_239Cycles5: Sample time equal to 239.5 cycles * @retval None */ void ADC_RegularChannelConfig(ADC_TypeDef* ADCx, uint8_t ADC_Channel, uint8_t Rank, uint8_t ADC_SampleTime) { uint32_t tmpreg1 = 0, tmpreg2 = 0; /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); assert_param(IS_ADC_CHANNEL(ADC_Channel)); assert_param(IS_ADC_REGULAR_RANK(Rank)); assert_param(IS_ADC_SAMPLE_TIME(ADC_SampleTime)); /* if ADC_Channel_10 ... ADC_Channel_17 is selected */ if (ADC_Channel > ADC_Channel_9) { /* Get the old register value */ tmpreg1 = ADCx->SMPR1; /* Calculate the mask to clear */ tmpreg2 = SMPR1_SMP_Set << (3 * (ADC_Channel - 10)); /* Clear the old channel sample time */ tmpreg1 &= ~tmpreg2; /* Calculate the mask to set */ tmpreg2 = (uint32_t)ADC_SampleTime << (3 * (ADC_Channel - 10)); /* Set the new channel sample time */ tmpreg1 |= tmpreg2; /* Store the new register value */ ADCx->SMPR1 = tmpreg1; } else /* ADC_Channel include in ADC_Channel_[0..9] */ { /* Get the old register value */ tmpreg1 = ADCx->SMPR2; /* Calculate the mask to clear */ tmpreg2 = SMPR2_SMP_Set << (3 * ADC_Channel); /* Clear the old channel sample time */ tmpreg1 &= ~tmpreg2; /* Calculate the mask to set */ tmpreg2 = (uint32_t)ADC_SampleTime << (3 * ADC_Channel); /* Set the new channel sample time */ tmpreg1 |= tmpreg2; /* Store the new register value */ ADCx->SMPR2 = tmpreg1; } /* For Rank 1 to 6 */ if (Rank < 7) { /* Get the old register value */ tmpreg1 = ADCx->SQR3; /* Calculate the mask to clear */ tmpreg2 = SQR3_SQ_Set << (5 * (Rank - 1)); /* Clear the old SQx bits for the selected rank */ tmpreg1 &= ~tmpreg2; /* Calculate the mask to set */ tmpreg2 = (uint32_t)ADC_Channel << (5 * (Rank - 1)); /* Set the SQx bits for the selected rank */ tmpreg1 |= tmpreg2; /* Store the new register value */ ADCx->SQR3 = tmpreg1; } /* For Rank 7 to 12 */ else if (Rank < 13) { /* Get the old register value */ tmpreg1 = ADCx->SQR2; /* Calculate the mask to clear */ tmpreg2 = SQR2_SQ_Set << (5 * (Rank - 7)); /* Clear the old SQx bits for the selected rank */ tmpreg1 &= ~tmpreg2; /* Calculate the mask to set */ tmpreg2 = (uint32_t)ADC_Channel << (5 * (Rank - 7)); /* Set the SQx bits for the selected rank */ tmpreg1 |= tmpreg2; /* Store the new register value */ ADCx->SQR2 = tmpreg1; } /* For Rank 13 to 16 */ else { /* Get the old register value */ tmpreg1 = ADCx->SQR1; /* Calculate the mask to clear */ tmpreg2 = SQR1_SQ_Set << (5 * (Rank - 13)); /* Clear the old SQx bits for the selected rank */ tmpreg1 &= ~tmpreg2; /* Calculate the mask to set */ tmpreg2 = (uint32_t)ADC_Channel << (5 * (Rank - 13)); /* Set the SQx bits for the selected rank */ tmpreg1 |= tmpreg2; /* Store the new register value */ ADCx->SQR1 = tmpreg1; } } /** * @brief Enables or disables the ADCx conversion through external trigger. * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @param NewState: new state of the selected ADC external trigger start of conversion. * This parameter can be: ENABLE or DISABLE. * @retval None */ void ADC_ExternalTrigConvCmd(ADC_TypeDef* ADCx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the selected ADC conversion on external event */ ADCx->CR2 |= CR2_EXTTRIG_Set; } else { /* Disable the selected ADC conversion on external event */ ADCx->CR2 &= CR2_EXTTRIG_Reset; } } /** * @brief Returns the last ADCx conversion result data for regular channel. * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @retval The Data conversion value. */ uint16_t ADC_GetConversionValue(ADC_TypeDef* ADCx) { /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); /* Return the selected ADC conversion value */ return (uint16_t) ADCx->DR; } /** * @brief Returns the last ADC1 and ADC2 conversion result data in dual mode. * @retval The Data conversion value. */ uint32_t ADC_GetDualModeConversionValue(void) { /* Return the dual mode conversion value */ return (*(__IO uint32_t *) DR_ADDRESS); } /** * @brief Enables or disables the selected ADC automatic injected group * conversion after regular one. * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @param NewState: new state of the selected ADC auto injected conversion * This parameter can be: ENABLE or DISABLE. * @retval None */ void ADC_AutoInjectedConvCmd(ADC_TypeDef* ADCx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the selected ADC automatic injected group conversion */ ADCx->CR1 |= CR1_JAUTO_Set; } else { /* Disable the selected ADC automatic injected group conversion */ ADCx->CR1 &= CR1_JAUTO_Reset; } } /** * @brief Enables or disables the discontinuous mode for injected group * channel for the specified ADC * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @param NewState: new state of the selected ADC discontinuous mode * on injected group channel. * This parameter can be: ENABLE or DISABLE. * @retval None */ void ADC_InjectedDiscModeCmd(ADC_TypeDef* ADCx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the selected ADC injected discontinuous mode */ ADCx->CR1 |= CR1_JDISCEN_Set; } else { /* Disable the selected ADC injected discontinuous mode */ ADCx->CR1 &= CR1_JDISCEN_Reset; } } /** * @brief Configures the ADCx external trigger for injected channels conversion. * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @param ADC_ExternalTrigInjecConv: specifies the ADC trigger to start injected conversion. * This parameter can be one of the following values: * @arg ADC_ExternalTrigInjecConv_T1_TRGO: Timer1 TRGO event selected (for ADC1, ADC2 and ADC3) * @arg ADC_ExternalTrigInjecConv_T1_CC4: Timer1 capture compare4 selected (for ADC1, ADC2 and ADC3) * @arg ADC_ExternalTrigInjecConv_T2_TRGO: Timer2 TRGO event selected (for ADC1 and ADC2) * @arg ADC_ExternalTrigInjecConv_T2_CC1: Timer2 capture compare1 selected (for ADC1 and ADC2) * @arg ADC_ExternalTrigInjecConv_T3_CC4: Timer3 capture compare4 selected (for ADC1 and ADC2) * @arg ADC_ExternalTrigInjecConv_T4_TRGO: Timer4 TRGO event selected (for ADC1 and ADC2) * @arg ADC_ExternalTrigInjecConv_Ext_IT15_TIM8_CC4: External interrupt line 15 or Timer8 * capture compare4 event selected (for ADC1 and ADC2) * @arg ADC_ExternalTrigInjecConv_T4_CC3: Timer4 capture compare3 selected (for ADC3 only) * @arg ADC_ExternalTrigInjecConv_T8_CC2: Timer8 capture compare2 selected (for ADC3 only) * @arg ADC_ExternalTrigInjecConv_T8_CC4: Timer8 capture compare4 selected (for ADC3 only) * @arg ADC_ExternalTrigInjecConv_T5_TRGO: Timer5 TRGO event selected (for ADC3 only) * @arg ADC_ExternalTrigInjecConv_T5_CC4: Timer5 capture compare4 selected (for ADC3 only) * @arg ADC_ExternalTrigInjecConv_None: Injected conversion started by software and not * by external trigger (for ADC1, ADC2 and ADC3) * @retval None */ void ADC_ExternalTrigInjectedConvConfig(ADC_TypeDef* ADCx, uint32_t ADC_ExternalTrigInjecConv) { uint32_t tmpreg = 0; /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); assert_param(IS_ADC_EXT_INJEC_TRIG(ADC_ExternalTrigInjecConv)); /* Get the old register value */ tmpreg = ADCx->CR2; /* Clear the old external event selection for injected group */ tmpreg &= CR2_JEXTSEL_Reset; /* Set the external event selection for injected group */ tmpreg |= ADC_ExternalTrigInjecConv; /* Store the new register value */ ADCx->CR2 = tmpreg; } /** * @brief Enables or disables the ADCx injected channels conversion through * external trigger * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @param NewState: new state of the selected ADC external trigger start of * injected conversion. * This parameter can be: ENABLE or DISABLE. * @retval None */ void ADC_ExternalTrigInjectedConvCmd(ADC_TypeDef* ADCx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the selected ADC external event selection for injected group */ ADCx->CR2 |= CR2_JEXTTRIG_Set; } else { /* Disable the selected ADC external event selection for injected group */ ADCx->CR2 &= CR2_JEXTTRIG_Reset; } } /** * @brief Enables or disables the selected ADC start of the injected * channels conversion. * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @param NewState: new state of the selected ADC software start injected conversion. * This parameter can be: ENABLE or DISABLE. * @retval None */ void ADC_SoftwareStartInjectedConvCmd(ADC_TypeDef* ADCx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the selected ADC conversion for injected group on external event and start the selected ADC injected conversion */ ADCx->CR2 |= CR2_JEXTTRIG_JSWSTART_Set; } else { /* Disable the selected ADC conversion on external event for injected group and stop the selected ADC injected conversion */ ADCx->CR2 &= CR2_JEXTTRIG_JSWSTART_Reset; } } /** * @brief Gets the selected ADC Software start injected conversion Status. * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @retval The new state of ADC software start injected conversion (SET or RESET). */ FlagStatus ADC_GetSoftwareStartInjectedConvCmdStatus(ADC_TypeDef* ADCx) { FlagStatus bitstatus = RESET; /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); /* Check the status of JSWSTART bit */ if ((ADCx->CR2 & CR2_JSWSTART_Set) != (uint32_t)RESET) { /* JSWSTART bit is set */ bitstatus = SET; } else { /* JSWSTART bit is reset */ bitstatus = RESET; } /* Return the JSWSTART bit status */ return bitstatus; } /** * @brief Configures for the selected ADC injected channel its corresponding * rank in the sequencer and its sample time. * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @param ADC_Channel: the ADC channel to configure. * This parameter can be one of the following values: * @arg ADC_Channel_0: ADC Channel0 selected * @arg ADC_Channel_1: ADC Channel1 selected * @arg ADC_Channel_2: ADC Channel2 selected * @arg ADC_Channel_3: ADC Channel3 selected * @arg ADC_Channel_4: ADC Channel4 selected * @arg ADC_Channel_5: ADC Channel5 selected * @arg ADC_Channel_6: ADC Channel6 selected * @arg ADC_Channel_7: ADC Channel7 selected * @arg ADC_Channel_8: ADC Channel8 selected * @arg ADC_Channel_9: ADC Channel9 selected * @arg ADC_Channel_10: ADC Channel10 selected * @arg ADC_Channel_11: ADC Channel11 selected * @arg ADC_Channel_12: ADC Channel12 selected * @arg ADC_Channel_13: ADC Channel13 selected * @arg ADC_Channel_14: ADC Channel14 selected * @arg ADC_Channel_15: ADC Channel15 selected * @arg ADC_Channel_16: ADC Channel16 selected * @arg ADC_Channel_17: ADC Channel17 selected * @param Rank: The rank in the injected group sequencer. This parameter must be between 1 and 4. * @param ADC_SampleTime: The sample time value to be set for the selected channel. * This parameter can be one of the following values: * @arg ADC_SampleTime_1Cycles5: Sample time equal to 1.5 cycles * @arg ADC_SampleTime_7Cycles5: Sample time equal to 7.5 cycles * @arg ADC_SampleTime_13Cycles5: Sample time equal to 13.5 cycles * @arg ADC_SampleTime_28Cycles5: Sample time equal to 28.5 cycles * @arg ADC_SampleTime_41Cycles5: Sample time equal to 41.5 cycles * @arg ADC_SampleTime_55Cycles5: Sample time equal to 55.5 cycles * @arg ADC_SampleTime_71Cycles5: Sample time equal to 71.5 cycles * @arg ADC_SampleTime_239Cycles5: Sample time equal to 239.5 cycles * @retval None */ void ADC_InjectedChannelConfig(ADC_TypeDef* ADCx, uint8_t ADC_Channel, uint8_t Rank, uint8_t ADC_SampleTime) { uint32_t tmpreg1 = 0, tmpreg2 = 0, tmpreg3 = 0; /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); assert_param(IS_ADC_CHANNEL(ADC_Channel)); assert_param(IS_ADC_INJECTED_RANK(Rank)); assert_param(IS_ADC_SAMPLE_TIME(ADC_SampleTime)); /* if ADC_Channel_10 ... ADC_Channel_17 is selected */ if (ADC_Channel > ADC_Channel_9) { /* Get the old register value */ tmpreg1 = ADCx->SMPR1; /* Calculate the mask to clear */ tmpreg2 = SMPR1_SMP_Set << (3*(ADC_Channel - 10)); /* Clear the old channel sample time */ tmpreg1 &= ~tmpreg2; /* Calculate the mask to set */ tmpreg2 = (uint32_t)ADC_SampleTime << (3*(ADC_Channel - 10)); /* Set the new channel sample time */ tmpreg1 |= tmpreg2; /* Store the new register value */ ADCx->SMPR1 = tmpreg1; } else /* ADC_Channel include in ADC_Channel_[0..9] */ { /* Get the old register value */ tmpreg1 = ADCx->SMPR2; /* Calculate the mask to clear */ tmpreg2 = SMPR2_SMP_Set << (3 * ADC_Channel); /* Clear the old channel sample time */ tmpreg1 &= ~tmpreg2; /* Calculate the mask to set */ tmpreg2 = (uint32_t)ADC_SampleTime << (3 * ADC_Channel); /* Set the new channel sample time */ tmpreg1 |= tmpreg2; /* Store the new register value */ ADCx->SMPR2 = tmpreg1; } /* Rank configuration */ /* Get the old register value */ tmpreg1 = ADCx->JSQR; /* Get JL value: Number = JL+1 */ tmpreg3 = (tmpreg1 & JSQR_JL_Set)>> 20; /* Calculate the mask to clear: ((Rank-1)+(4-JL-1)) */ tmpreg2 = JSQR_JSQ_Set << (5 * (uint8_t)((Rank + 3) - (tmpreg3 + 1))); /* Clear the old JSQx bits for the selected rank */ tmpreg1 &= ~tmpreg2; /* Calculate the mask to set: ((Rank-1)+(4-JL-1)) */ tmpreg2 = (uint32_t)ADC_Channel << (5 * (uint8_t)((Rank + 3) - (tmpreg3 + 1))); /* Set the JSQx bits for the selected rank */ tmpreg1 |= tmpreg2; /* Store the new register value */ ADCx->JSQR = tmpreg1; } /** * @brief Configures the sequencer length for injected channels * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @param Length: The sequencer length. * This parameter must be a number between 1 to 4. * @retval None */ void ADC_InjectedSequencerLengthConfig(ADC_TypeDef* ADCx, uint8_t Length) { uint32_t tmpreg1 = 0; uint32_t tmpreg2 = 0; /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); assert_param(IS_ADC_INJECTED_LENGTH(Length)); /* Get the old register value */ tmpreg1 = ADCx->JSQR; /* Clear the old injected sequnence lenght JL bits */ tmpreg1 &= JSQR_JL_Reset; /* Set the injected sequnence lenght JL bits */ tmpreg2 = Length - 1; tmpreg1 |= tmpreg2 << 20; /* Store the new register value */ ADCx->JSQR = tmpreg1; } /** * @brief Set the injected channels conversion value offset * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @param ADC_InjectedChannel: the ADC injected channel to set its offset. * This parameter can be one of the following values: * @arg ADC_InjectedChannel_1: Injected Channel1 selected * @arg ADC_InjectedChannel_2: Injected Channel2 selected * @arg ADC_InjectedChannel_3: Injected Channel3 selected * @arg ADC_InjectedChannel_4: Injected Channel4 selected * @param Offset: the offset value for the selected ADC injected channel * This parameter must be a 12bit value. * @retval None */ void ADC_SetInjectedOffset(ADC_TypeDef* ADCx, uint8_t ADC_InjectedChannel, uint16_t Offset) { __IO uint32_t tmp = 0; /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); assert_param(IS_ADC_INJECTED_CHANNEL(ADC_InjectedChannel)); assert_param(IS_ADC_OFFSET(Offset)); tmp = (uint32_t)ADCx; tmp += ADC_InjectedChannel; /* Set the selected injected channel data offset */ *(__IO uint32_t *) tmp = (uint32_t)Offset; } /** * @brief Returns the ADC injected channel conversion result * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @param ADC_InjectedChannel: the converted ADC injected channel. * This parameter can be one of the following values: * @arg ADC_InjectedChannel_1: Injected Channel1 selected * @arg ADC_InjectedChannel_2: Injected Channel2 selected * @arg ADC_InjectedChannel_3: Injected Channel3 selected * @arg ADC_InjectedChannel_4: Injected Channel4 selected * @retval The Data conversion value. */ uint16_t ADC_GetInjectedConversionValue(ADC_TypeDef* ADCx, uint8_t ADC_InjectedChannel) { __IO uint32_t tmp = 0; /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); assert_param(IS_ADC_INJECTED_CHANNEL(ADC_InjectedChannel)); tmp = (uint32_t)ADCx; tmp += ADC_InjectedChannel + JDR_Offset; /* Returns the selected injected channel conversion data value */ return (uint16_t) (*(__IO uint32_t*) tmp); } /** * @brief Enables or disables the analog watchdog on single/all regular * or injected channels * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @param ADC_AnalogWatchdog: the ADC analog watchdog configuration. * This parameter can be one of the following values: * @arg ADC_AnalogWatchdog_SingleRegEnable: Analog watchdog on a single regular channel * @arg ADC_AnalogWatchdog_SingleInjecEnable: Analog watchdog on a single injected channel * @arg ADC_AnalogWatchdog_SingleRegOrInjecEnable: Analog watchdog on a single regular or injected channel * @arg ADC_AnalogWatchdog_AllRegEnable: Analog watchdog on all regular channel * @arg ADC_AnalogWatchdog_AllInjecEnable: Analog watchdog on all injected channel * @arg ADC_AnalogWatchdog_AllRegAllInjecEnable: Analog watchdog on all regular and injected channels * @arg ADC_AnalogWatchdog_None: No channel guarded by the analog watchdog * @retval None */ void ADC_AnalogWatchdogCmd(ADC_TypeDef* ADCx, uint32_t ADC_AnalogWatchdog) { uint32_t tmpreg = 0; /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); assert_param(IS_ADC_ANALOG_WATCHDOG(ADC_AnalogWatchdog)); /* Get the old register value */ tmpreg = ADCx->CR1; /* Clear AWDEN, AWDENJ and AWDSGL bits */ tmpreg &= CR1_AWDMode_Reset; /* Set the analog watchdog enable mode */ tmpreg |= ADC_AnalogWatchdog; /* Store the new register value */ ADCx->CR1 = tmpreg; } /** * @brief Configures the high and low thresholds of the analog watchdog. * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @param HighThreshold: the ADC analog watchdog High threshold value. * This parameter must be a 12bit value. * @param LowThreshold: the ADC analog watchdog Low threshold value. * This parameter must be a 12bit value. * @retval None */ void ADC_AnalogWatchdogThresholdsConfig(ADC_TypeDef* ADCx, uint16_t HighThreshold, uint16_t LowThreshold) { /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); assert_param(IS_ADC_THRESHOLD(HighThreshold)); assert_param(IS_ADC_THRESHOLD(LowThreshold)); /* Set the ADCx high threshold */ ADCx->HTR = HighThreshold; /* Set the ADCx low threshold */ ADCx->LTR = LowThreshold; } /** * @brief Configures the analog watchdog guarded single channel * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @param ADC_Channel: the ADC channel to configure for the analog watchdog. * This parameter can be one of the following values: * @arg ADC_Channel_0: ADC Channel0 selected * @arg ADC_Channel_1: ADC Channel1 selected * @arg ADC_Channel_2: ADC Channel2 selected * @arg ADC_Channel_3: ADC Channel3 selected * @arg ADC_Channel_4: ADC Channel4 selected * @arg ADC_Channel_5: ADC Channel5 selected * @arg ADC_Channel_6: ADC Channel6 selected * @arg ADC_Channel_7: ADC Channel7 selected * @arg ADC_Channel_8: ADC Channel8 selected * @arg ADC_Channel_9: ADC Channel9 selected * @arg ADC_Channel_10: ADC Channel10 selected * @arg ADC_Channel_11: ADC Channel11 selected * @arg ADC_Channel_12: ADC Channel12 selected * @arg ADC_Channel_13: ADC Channel13 selected * @arg ADC_Channel_14: ADC Channel14 selected * @arg ADC_Channel_15: ADC Channel15 selected * @arg ADC_Channel_16: ADC Channel16 selected * @arg ADC_Channel_17: ADC Channel17 selected * @retval None */ void ADC_AnalogWatchdogSingleChannelConfig(ADC_TypeDef* ADCx, uint8_t ADC_Channel) { uint32_t tmpreg = 0; /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); assert_param(IS_ADC_CHANNEL(ADC_Channel)); /* Get the old register value */ tmpreg = ADCx->CR1; /* Clear the Analog watchdog channel select bits */ tmpreg &= CR1_AWDCH_Reset; /* Set the Analog watchdog channel */ tmpreg |= ADC_Channel; /* Store the new register value */ ADCx->CR1 = tmpreg; } /** * @brief Enables or disables the temperature sensor and Vrefint channel. * @param NewState: new state of the temperature sensor. * This parameter can be: ENABLE or DISABLE. * @retval None */ void ADC_TempSensorVrefintCmd(FunctionalState NewState) { /* Check the parameters */ assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the temperature sensor and Vrefint channel*/ ADC1->CR2 |= CR2_TSVREFE_Set; } else { /* Disable the temperature sensor and Vrefint channel*/ ADC1->CR2 &= CR2_TSVREFE_Reset; } } /** * @brief Checks whether the specified ADC flag is set or not. * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @param ADC_FLAG: specifies the flag to check. * This parameter can be one of the following values: * @arg ADC_FLAG_AWD: Analog watchdog flag * @arg ADC_FLAG_EOC: End of conversion flag * @arg ADC_FLAG_JEOC: End of injected group conversion flag * @arg ADC_FLAG_JSTRT: Start of injected group conversion flag * @arg ADC_FLAG_STRT: Start of regular group conversion flag * @retval The new state of ADC_FLAG (SET or RESET). */ FlagStatus ADC_GetFlagStatus(ADC_TypeDef* ADCx, uint8_t ADC_FLAG) { FlagStatus bitstatus = RESET; /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); assert_param(IS_ADC_GET_FLAG(ADC_FLAG)); /* Check the status of the specified ADC flag */ if ((ADCx->SR & ADC_FLAG) != (uint8_t)RESET) { /* ADC_FLAG is set */ bitstatus = SET; } else { /* ADC_FLAG is reset */ bitstatus = RESET; } /* Return the ADC_FLAG status */ return bitstatus; } /** * @brief Clears the ADCx's pending flags. * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @param ADC_FLAG: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg ADC_FLAG_AWD: Analog watchdog flag * @arg ADC_FLAG_EOC: End of conversion flag * @arg ADC_FLAG_JEOC: End of injected group conversion flag * @arg ADC_FLAG_JSTRT: Start of injected group conversion flag * @arg ADC_FLAG_STRT: Start of regular group conversion flag * @retval None */ void ADC_ClearFlag(ADC_TypeDef* ADCx, uint8_t ADC_FLAG) { /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); assert_param(IS_ADC_CLEAR_FLAG(ADC_FLAG)); /* Clear the selected ADC flags */ ADCx->SR = ~(uint32_t)ADC_FLAG; } /** * @brief Checks whether the specified ADC interrupt has occurred or not. * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @param ADC_IT: specifies the ADC interrupt source to check. * This parameter can be one of the following values: * @arg ADC_IT_EOC: End of conversion interrupt mask * @arg ADC_IT_AWD: Analog watchdog interrupt mask * @arg ADC_IT_JEOC: End of injected conversion interrupt mask * @retval The new state of ADC_IT (SET or RESET). */ ITStatus ADC_GetITStatus(ADC_TypeDef* ADCx, uint16_t ADC_IT) { ITStatus bitstatus = RESET; uint32_t itmask = 0, enablestatus = 0; /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); assert_param(IS_ADC_GET_IT(ADC_IT)); /* Get the ADC IT index */ itmask = ADC_IT >> 8; /* Get the ADC_IT enable bit status */ enablestatus = (ADCx->CR1 & (uint8_t)ADC_IT) ; /* Check the status of the specified ADC interrupt */ if (((ADCx->SR & itmask) != (uint32_t)RESET) && enablestatus) { /* ADC_IT is set */ bitstatus = SET; } else { /* ADC_IT is reset */ bitstatus = RESET; } /* Return the ADC_IT status */ return bitstatus; } /** * @brief Clears the ADCx's interrupt pending bits. * @param ADCx: where x can be 1, 2 or 3 to select the ADC peripheral. * @param ADC_IT: specifies the ADC interrupt pending bit to clear. * This parameter can be any combination of the following values: * @arg ADC_IT_EOC: End of conversion interrupt mask * @arg ADC_IT_AWD: Analog watchdog interrupt mask * @arg ADC_IT_JEOC: End of injected conversion interrupt mask * @retval None */ void ADC_ClearITPendingBit(ADC_TypeDef* ADCx, uint16_t ADC_IT) { uint8_t itmask = 0; /* Check the parameters */ assert_param(IS_ADC_ALL_PERIPH(ADCx)); assert_param(IS_ADC_IT(ADC_IT)); /* Get the ADC IT index */ itmask = (uint8_t)(ADC_IT >> 8); /* Clear the selected ADC interrupt pending bits */ ADCx->SR = ~(uint32_t)itmask; } /** * @} */ /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
{ "pile_set_name": "Github" }
/* * Copyright (C) 2014 Dell, 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. */ package com.dell.doradus.search.iterator; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import com.dell.doradus.common.FieldDefinition; import com.dell.doradus.core.ObjectID; import com.dell.doradus.core.ServerParams; import com.dell.doradus.service.spider.SpiderHelper; import com.dell.doradus.service.spider.SpiderService; public class LinksIterable implements Iterable<ObjectID> { private FieldDefinition m_link; private List<Integer> m_shards; private ObjectID m_continuation; private boolean m_inclusive; private Iterable<ObjectID> m_keys; public LinksIterable(FieldDefinition link, List<Integer> shards, ObjectID continuation, boolean inclusive, Iterable<ObjectID> keys) { m_link = link; m_shards = shards; if(m_shards == null) { m_shards = new ArrayList<Integer>(1); m_shards.add(0); if(link.isSharded()) m_shards.addAll(SpiderService.instance().getShards(link.getInverseTableDef()).keySet()); } m_continuation = continuation; m_inclusive = inclusive; m_keys = keys; } @Override public Iterator<ObjectID> iterator() { if(m_shards.size() == 0) return NoneIterator.instance; int maxobjects = 64; int maxmaxobjects = 64 * 1024; int count = ServerParams.instance().getModuleParamInt("DoradusServer", "dbesoptions_linkBuffer", 1000); List<ObjectID> keys = new ArrayList<ObjectID>(); for(ObjectID key : m_keys) { keys.add(key); } if(keys.size() == 0) return NoneIterator.instance; if(keys.size() * m_shards.size() == 1) { List<ObjectID> lst = SpiderHelper.getLinks(m_link, m_shards.get(0), keys.get(0), m_continuation, m_inclusive, count); return new LinkIterator(m_link, m_shards.get(0), keys.get(0), count, lst); } if(keys.size() <= maxobjects) { OrIterable or = new OrIterable(m_shards.size() * keys.size()); for(Integer shard : m_shards) { Map<ObjectID, List<ObjectID>> map = SpiderHelper.getLinks(m_link, shard, keys, m_continuation, m_inclusive, count); for(Map.Entry<ObjectID, List<ObjectID>> e : map.entrySet()) { if(e.getValue().size() == 0) continue; or.add(new LinkIterable(m_link, shard, e.getKey(), count, e.getValue())); } } return or.iterator(); } if(keys.size() <= maxmaxobjects) { OrIterable or = new OrIterable(keys.size()); for(Integer shard : m_shards) { for(ObjectID key : keys) { List<ObjectID> lst = SpiderHelper.getLinks(m_link, shard, key, m_continuation, m_inclusive, count); or.add(new LinkIterable(m_link, shard, key, count, lst)); } } return or.iterator(); } Set<ObjectID> set = new HashSet<ObjectID>(); for(Integer shard : m_shards) { for(ObjectID key : keys) { List<ObjectID> lst = SpiderHelper.getLinks(m_link, shard, key, m_continuation, m_inclusive, count); Iterable<ObjectID> iterator = new LinkIterable(m_link, shard, key, count, lst); for(ObjectID obj : iterator) set.add(obj); } } List<ObjectID> result = new ArrayList<ObjectID>(set.size()); result.addAll(set); Collections.sort(result); return result.iterator(); } }
{ "pile_set_name": "Github" }
<?php /** * Licensed under The GPL-3.0 License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @since 2.0.0 * @author Christopher Castro <[email protected]> * @link http://www.quickappscms.org * @license http://opensource.org/licenses/gpl-3.0.html GPL-3.0 License */ ?> <div class="row"> <div class="col-md-12"> <?= $this->Form->create($comment); ?> <fieldset> <legend><?= __d('comment', 'Editing Comment'); ?></legend> <?php if (!$comment->user_id): ?> <?= $this->Form->input('author_name', [ 'label' => ($this->Comment->config('anonymous_name_required') ? __d('comment', 'Author Name *') : __d('comment', 'Author Name')), ]); ?> <?= $this->Form->input('author_email', [ 'label' => ($this->Comment->config('anonymous_email_required') ? __d('comment', 'Author e-Mail *') : __d('comment', 'Author e-Mail')), ]); ?> <?= $this->Form->input('author_web', [ 'label' => ($this->Comment->config('anonymous_web_required') ? __d('comment', 'Author Website *') : __d('comment', 'Author Website')), ]); ?> <?php else: ?> <div class="media"> <?= $this->Html->image($comment->author->avatar, ['width' => 80, 'class' => 'media-object pull-left']); ?> <div class="media-body"> <strong><?= $comment->author->name; ?></strong><br /> email: <?= $comment->author->email; ?><br /> web: <?= $comment->author->web; ?><br /> ip: <?= $comment->author->ip; ?> </div> </div> <?php endif; ?> <hr /> <?= $this->Form->input('subject', ['label' => __d('comment', 'Subject')]); ?> <?= $this->Form->input('status', [ 'type' => 'select', 'label' => __d('comment', 'Status'), 'options' => [ 'approved' => __d('comment', 'Approved'), 'pending' => __d('comment', 'Pending'), 'spam' => __d('comment', 'Spam'), 'trash' => __d('comment', 'Trash'), ] ]); ?> <?= $this->Form->input('body', [ 'type' => 'textarea', 'label' => __d('comment', 'Message') ]); ?> <?= $this->Form->submit(__d('comment', 'Save')); ?> </fieldset> <?= $this->Form->end(); ?> </div> </div>
{ "pile_set_name": "Github" }
exclude :test_ignore_invalid_line, "needs investigation"
{ "pile_set_name": "Github" }
<template> <div class="about"> <h1>This is an about page</h1> </div> </template>
{ "pile_set_name": "Github" }
// Protocol Buffers for Go with Gadgets // // Copyright (c) 2013, The GoGo Authors. All rights reserved. // http://github.com/gogo/protobuf // // 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. // // 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. // +build !appengine,!js // This file contains the implementation of the proto field accesses using package unsafe. package proto import ( "reflect" "unsafe" ) func structPointer_InterfaceAt(p structPointer, f field, t reflect.Type) interface{} { point := unsafe.Pointer(uintptr(p) + uintptr(f)) r := reflect.NewAt(t, point) return r.Interface() } func structPointer_InterfaceRef(p structPointer, f field, t reflect.Type) interface{} { point := unsafe.Pointer(uintptr(p) + uintptr(f)) r := reflect.NewAt(t, point) if r.Elem().IsNil() { return nil } return r.Elem().Interface() } func copyUintPtr(oldptr, newptr uintptr, size int) { oldbytes := make([]byte, 0) oldslice := (*reflect.SliceHeader)(unsafe.Pointer(&oldbytes)) oldslice.Data = oldptr oldslice.Len = size oldslice.Cap = size newbytes := make([]byte, 0) newslice := (*reflect.SliceHeader)(unsafe.Pointer(&newbytes)) newslice.Data = newptr newslice.Len = size newslice.Cap = size copy(newbytes, oldbytes) } func structPointer_Copy(oldptr structPointer, newptr structPointer, size int) { copyUintPtr(uintptr(oldptr), uintptr(newptr), size) } func appendStructPointer(base structPointer, f field, typ reflect.Type) structPointer { size := typ.Elem().Size() oldHeader := structPointer_GetSliceHeader(base, f) oldSlice := reflect.NewAt(typ, unsafe.Pointer(oldHeader)).Elem() newLen := oldHeader.Len + 1 newSlice := reflect.MakeSlice(typ, newLen, newLen) reflect.Copy(newSlice, oldSlice) bas := toStructPointer(newSlice) oldHeader.Data = uintptr(bas) oldHeader.Len = newLen oldHeader.Cap = newLen return structPointer(unsafe.Pointer(uintptr(unsafe.Pointer(bas)) + uintptr(uintptr(newLen-1)*size))) } func structPointer_FieldPointer(p structPointer, f field) structPointer { return structPointer(unsafe.Pointer(uintptr(p) + uintptr(f))) } func structPointer_GetRefStructPointer(p structPointer, f field) structPointer { return structPointer((*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f)))) } func structPointer_GetSliceHeader(p structPointer, f field) *reflect.SliceHeader { return (*reflect.SliceHeader)(unsafe.Pointer(uintptr(p) + uintptr(f))) } func structPointer_Add(p structPointer, size field) structPointer { return structPointer(unsafe.Pointer(uintptr(p) + uintptr(size))) } func structPointer_Len(p structPointer, f field) int { return len(*(*[]interface{})(unsafe.Pointer(structPointer_GetRefStructPointer(p, f)))) } func structPointer_StructRefSlice(p structPointer, f field, size uintptr) *structRefSlice { return &structRefSlice{p: p, f: f, size: size} } // A structRefSlice represents a slice of structs (themselves submessages or groups). type structRefSlice struct { p structPointer f field size uintptr } func (v *structRefSlice) Len() int { return structPointer_Len(v.p, v.f) } func (v *structRefSlice) Index(i int) structPointer { ss := structPointer_GetStructPointer(v.p, v.f) ss1 := structPointer_GetRefStructPointer(ss, 0) return structPointer_Add(ss1, field(uintptr(i)*v.size)) }
{ "pile_set_name": "Github" }
.. _file-parser: Parser ------ The first thing we need is a parser that can take the file and turn it into usable ``ol.Feature`` instances. .. literalinclude:: src/plugin/georss/georssparser.js :caption: ``src/plugin/georss/georssparser.js`` :linenos: :language: javascript Whew. That was a lot for one step. It is not exhaustive, and a full implementation would want to support RSS in addition to Atom as well as the ``<georss:elev>`` tag. However, it still would not be complete without some tests. .. literalinclude:: test/plugin/georss/georssparser.test.js :caption: ``test/plugin/georss/georssparser.test.js`` :linenos: :language: javascript There. Now we can fully test our parser with ``yarn test``.
{ "pile_set_name": "Github" }
/* * 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.aliyuncs.sgw.model.v20180511; import java.util.List; import com.aliyuncs.AcsResponse; import com.aliyuncs.sgw.transform.v20180511.DescribeGatewaysTagsResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class DescribeGatewaysTagsResponse extends AcsResponse { private String requestId; private Boolean success; private String code; private String message; private List<GatewayTag> gatewayTags; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public Boolean getSuccess() { return this.success; } public void setSuccess(Boolean success) { this.success = success; } public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } public List<GatewayTag> getGatewayTags() { return this.gatewayTags; } public void setGatewayTags(List<GatewayTag> gatewayTags) { this.gatewayTags = gatewayTags; } public static class GatewayTag { private String gatewayId; private List<Tag> tags; public String getGatewayId() { return this.gatewayId; } public void setGatewayId(String gatewayId) { this.gatewayId = gatewayId; } public List<Tag> getTags() { return this.tags; } public void setTags(List<Tag> tags) { this.tags = tags; } public static class Tag { private String tagKey; private String tagValue; public String getTagKey() { return this.tagKey; } public void setTagKey(String tagKey) { this.tagKey = tagKey; } public String getTagValue() { return this.tagValue; } public void setTagValue(String tagValue) { this.tagValue = tagValue; } } } @Override public DescribeGatewaysTagsResponse getInstance(UnmarshallerContext context) { return DescribeGatewaysTagsResponseUnmarshaller.unmarshall(this, context); } }
{ "pile_set_name": "Github" }
root:x:0: daemon:x:1: bin:x:2: sys:x:3: adm:x:4: tty:x:5: disk:x:6: lp:x:7: mail:x:8: news:x:9: uucp:x:10: man:x:12: proxy:x:13: kmem:x:15: dialout:x:20: fax:x:21: voice:x:22: cdrom:x:24: floppy:x:25: tape:x:26: sudo:x:27: audio:x:29: dip:x:30: www-data:x:33: backup:x:34: operator:x:37: list:x:38: irc:x:39: src:x:40: gnats:x:41: shadow:x:42: utmp:x:43: video:x:44: sasl:x:45: plugdev:x:46: staff:x:50: games:x:60: users:x:100: nogroup:x:65534: crontab:x:101: Debian-exim:x:102:
{ "pile_set_name": "Github" }
/* * Scilab ( http://www.scilab.org/ ) - This file is part of Scilab * Copyright (C) 2012 - Scilab Enterprises - Calixte DENIZET * * Copyright (C) 2012 - 2016 - Scilab Enterprises * * This file is hereby licensed under the terms of the GNU GPL v2.0, * pursuant to article 5.3.4 of the CeCILL v.2.1. * This file was originally licensed under the terms of the CeCILL v2.1, * and continues to be available under such terms. * For more information, see the COPYING file which you should have received * along with this program. * */ #include <set> #include <string> extern "C" { #include "gw_hdf5.h" #include "Scierror.h" #include "api_scilab.h" #include "localization.h" #include "expandPathVariable.h" } #include "HDF5Scilab.hxx" #include "H5File.hxx" using namespace org_modules_hdf5; /* Test object existence Scilab prototype: - h5exists(obj, location) - h5exists(obj, location, attrName) - h5exists(filename, location) - h5exists(filename, location, attrName) */ /*--------------------------------------------------------------------------*/ int sci_h5exists(char *fname, int* pvApiCtx) { H5Object * hobj = 0; SciErr err; int * addr = 0; char * str = 0; char ** locations = 0; char ** attrNames = 0; char * expandedPath = 0; std::string filename; int rowl, coll; int rowa, cola; int size; int * ret = 0; const int nbIn = nbInputArgument(pvApiCtx); CheckOutputArgument(pvApiCtx, 0, 1); CheckInputArgument(pvApiCtx, 2, 3); err = getVarAddressFromPosition(pvApiCtx, 1, &addr); if (err.iErr) { printError(&err, 0); Scierror(999, _("%s: Can not read input argument #%d.\n"), fname, 1); return 0; } if (HDF5Scilab::isH5Object(addr, pvApiCtx)) { hobj = HDF5Scilab::getH5Object(addr, pvApiCtx); if (!hobj) { Scierror(999, _("%s: Invalid H5Object.\n"), fname); return 0; } } else { if (!isStringType(pvApiCtx, addr) || !checkVarDimension(pvApiCtx, addr, 1, 1)) { Scierror(999, _("%s: Wrong type for input argument #%d: string expected.\n"), fname, 1); return 0; } if (getAllocatedSingleString(pvApiCtx, addr, &str) != 0) { Scierror(999, _("%s: No more memory.\n"), fname); return 0; } expandedPath = expandPathVariable(str); filename = std::string(expandedPath); FREE(expandedPath); freeAllocatedSingleString(str); } err = getVarAddressFromPosition(pvApiCtx, 2, &addr); if (err.iErr) { printError(&err, 0); Scierror(999, _("%s: Can not read input argument #%d.\n"), fname, 2); return 0; } if (!isStringType(pvApiCtx, addr)) { Scierror(999, _("%s: Wrong type for input argument #%d: string expected.\n"), fname, 2); return 0; } if (getAllocatedMatrixOfString(pvApiCtx, addr, &rowl, &coll, &locations) != 0) { Scierror(999, _("%s: No more memory.\n"), fname); return 0; } if (nbIn == 3 && (rowl != 1 || coll != 1)) { freeAllocatedMatrixOfString(rowl, coll, locations); Scierror(999, _("%s: Wrong size for argument #%d: string expected.\n"), fname, 2); return 0; } size = rowl * coll; if (nbIn == 3) { err = getVarAddressFromPosition(pvApiCtx, 3, &addr); if (err.iErr) { freeAllocatedMatrixOfString(rowl, coll, locations); printError(&err, 0); Scierror(999, _("%s: Can not read input argument #%d.\n"), fname, 3); return 0; } if (!isStringType(pvApiCtx, addr)) { freeAllocatedMatrixOfString(rowl, coll, locations); Scierror(999, _("%s: Wrong type for input argument #%d: string expected.\n"), fname, 3); return 0; } if (getAllocatedMatrixOfString(pvApiCtx, addr, &rowa, &cola, &attrNames) != 0) { freeAllocatedMatrixOfString(rowl, coll, locations); Scierror(999, _("%s: No more memory.\n"), fname); return 0; } size = rowa * cola; } try { if (hobj) { ret = HDF5Scilab::exists(*hobj, size, const_cast<const char **>(locations), const_cast<const char **>(attrNames)); } else { ret = HDF5Scilab::exists(filename, size, const_cast<const char **>(locations), const_cast<const char **>(attrNames)); } freeAllocatedMatrixOfString(rowl, coll, locations); if (attrNames) { freeAllocatedMatrixOfString(rowa, cola, attrNames); } } catch (const std::exception & e) { freeAllocatedMatrixOfString(rowl, coll, locations); if (attrNames) { freeAllocatedMatrixOfString(rowa, cola, attrNames); } Scierror(999, _("%s: %s\n"), fname, e.what()); return 0; } if (attrNames) { err = createMatrixOfBoolean(pvApiCtx, nbIn + 1, rowa, cola, ret); } else { err = createMatrixOfBoolean(pvApiCtx, nbIn + 1, rowl, coll, ret); } delete[] ret; if (err.iErr) { Scierror(999, _("%s: Can not create output argument.\n"), fname); return 0; } AssignOutputVariable(pvApiCtx, 1) = nbIn + 1; ReturnArguments(pvApiCtx); return 0; } /*--------------------------------------------------------------------------*/
{ "pile_set_name": "Github" }
CellWidth CellHeight 220 250
{ "pile_set_name": "Github" }
package org.atnos.site import org.atnos.site.snippets._ import tutorial._ object Tutorial extends UserGuidePage { def is = "Tutorial".title ^ s2""" This tutorial is intentionally structured like the [Free monad tutorial for cats](https://typelevel.org/cats/datatypes/freemonad.html) so that a side-by-side comparison of the 2 approaches is possible. ### Study your topic Let's imagine that we want to create a DSL for a key-value store. We want to be able to do three things with keys: - put a value into the store, associated with its key. - get a value from the store given its key. - delete a value from the store given its key. <p/> The idea is to write a sequence of these operations in the embedded DSL as a "program", interpret the "program", and finally execute the "program" to interact with the actual key-value store. For example: ``` put("toto", 3) get("toto") // returns 3 delete("toto") ``` But we want: - the computation to be represented as a pure, immutable value - to separate the creation and execution of the program - to be able to support many different methods of execution ### Create an ADT representing your grammar ADT stands for "Algebraic Data Type". In this context, it refers to a closed set of types which can be combined to build up complex, recursive values. We need to create an ADT to represent our key-value operations: ${definition[AdtSnippet]} ### Free your ADT There are four basic steps to "freeing" the ADT: 1. Create smart constructors for `KVStore[_]` using `Eff.send` 1. Build a program out of key-value DSL operations 1. Build an interpreter for programs of DSL operations 1. Execute our interpreted program 1. [optional] add some syntax for the interpreter ### Create smart constructors using `Eff.send` These methods will let you create `Eff` values for your key-value store "Effect":${definition[AdtCreationSnippet]} Each method requires the `KVStore` effect to be a member of an "effect stack" `R`. The return values are of type `Eff[R, A]` where `R` is a stack of effects possibly containing other effects than key-value store operations and yielding values of type `A`. ### Build a program Now that we can construct values with `KVStore` effects we can use our DSL to write "programs" using a for-comprehension: ${definition[AdtUsageSnippet]} This looks like a monadic flow. However, it just builds a recursive data structure representing the sequence of operations. ### Write an interpreter for your program As you may have understood now, `Eff` is used to create an embedded DSL. By itself, this DSL only represents a sequence of operations (defined by a recursive data structure); it doesn't produce anything. `Eff` is a programming language inside your programming language! So, like any other programming language, we need to interpret our abstract language into concrete values. To do this, we will use an interpreter transforming our `KVStore` effects using a simple mutable map: ${definition[AdtInterpreterSnippet]} Please note this interpreter is impure -- it mutates `kvs` and also produces logging output using `println`. The whole purpose of functional programming isn't to prevent side-effects, it is just to push side-effects to the boundaries of your system in a well-known and controlled way. We can also interpret `KVStore` effects differently and delegate the results to other effects in the same stack: - `State` for maintaining the map of values - `Writer` for logging - `E Either *` for type errors <p/> ${definition[AdtInterpreterSafeSnippet]} `Eff` is just a recursive structure that can be seen as sequence of operations producing other operations, with potentially other effects. In this way it is similar to folding a `List`. We often use folds (e.g. `foldRight`) to obtain a single value from a list; this recurses over the structure, combining its contents. The idea behind an `Eff` interpreter is exactly the same. We "fold" the recursive structure by: - consuming each operation - compiling the operation into a target language - computing next operation <p/> An important aspect of interpreters is stack-safety. An interpreter evaluates each step of a computation on the stack then calls itself to evaluate the other steps. The `org.atnos.eff.interpreter` object provides various methods helping you write a stack-safe interpreter: - `interpretUnsafe` makes you define a `SideEffect` trait to return a value `X` from an effect `T[X]` - `translate` makes you define a `Translate` trait to "translate" your effect into other effects in the same stack - both are specialized version of `interpret1` which makes you define a `Recurse` trait to either return a value `X` from an effect or produce another `Eff` computation ### Run your program The final step is naturally running your program after interpreting it to another `Eff` value. We need to - specify a concrete stack of effects containing the effect we want to interpret `Fx.fx1[KVStore]` (just one effect in the stack) - call our interpreter to get a `Eff[NoFx, A]` value - call a final `run` to get an `A` value <p/> Like this: ${snippet{ // 8<--- import AdtSnippet._ import AdtUsageSnippet._ import AdtInterpreterSnippet._ // 8<--- import org.atnos.eff._, syntax.all._ // run the program with the unsafe interpreter runKVStoreUnsafe(program[Fx.fx1[KVStore]]).run }.eval} With the safe interpreter, the process is the same and we need to - specify an effect stack definition with all the effects - call our "safe" interpreter - call interpreters for all the other effects, including the final `NoFx` effect with `run` <p/> Like that: ${snippet{ // 8<--- import AdtSnippet._ import AdtUsageSnippet._ import AdtInterpreterSafeSnippet._ // 8<--- import org.atnos.eff._, syntax.all._ import cats._, data._ // run the program with the safe interpreter type Stack = Fx.fx4[KVStore, Throwable Either *, State[Map[String, Any], *], Writer[String, *]] val (result, logs) = runKVStore(program[Stack]).runEither.evalState(Map.empty[String, Any]).runWriter.run (result.toString +: logs).mkString("\n") }.eval} ### Add some syntax It is nice to be able to "chain" `run` methods with this additional piece of syntax: ${snippet { // 8<--- import AdtSnippet._ import AdtUsageSnippet._ import AdtInterpreterSafeSnippet._ import org.atnos.eff._, all._, syntax.all._ import cats._, data._ type _writerString[R] = Writer[String, *] |= R type _stateMap[R] = State[Map[String, Any], *] |= R type Stack = Fx.fx4[KVStore, Throwable Either *, State[Map[String, Any], *], Writer[String, *]] // 8<--- implicit class KVStoreOps[R, A](effects: Eff[R, A]) { def runStore[U](implicit m: Member.Aux[KVStore, R, U], throwable:_throwableEither[U], writer:_writerString[U], state:_stateMap[U]): Eff[U, A] = runKVStore(effects) } val (result, logs) = program[Stack].runStore.runEither.evalState(Map.empty[String, Any]).runWriter.run (result.toString +: logs).mkString("\n") }.eval} ### Composing ADTs with the Eff monad Real world applications often time combine different algebras. The typelevel set of effects `R` in `Eff[R, A]` lets us compose different algebras in the context of `Eff`. Let's see a trivial example of unrelated ADT's getting composed that can form a more complex program. First you define your ADTs with smart constructors:${definition[UserInteractionSnippet]} Then you simply require your program to have `MemberIn` instances for those effects:${definition[UserInteractionProgramSnippet]} Finally we write one interpreter per ADT:${definition[UserInteractionInterpretersSnippet]} Now if we run our program for a Stack combining both effects and type in "snuggles" when prompted, we see something like this:${snippet{ // 8<-- import UserInteractionSnippet._ import UserInteractionInterpretersSnippet._ import UserInteractionProgramSnippet._ import org.atnos.eff._ // 8<-- type Stack = Fx.fx2[Interact, DataOp] runInteract(runDataOp(program[Stack])) }} ``` What's the kitty's name? Current cats: snuggles ``` """ }
{ "pile_set_name": "Github" }
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) using System; using System.IO; using NUnit.Framework; using ICSharpCode.NRefactory.VB.Parser; namespace ICSharpCode.NRefactory.VB.Tests.Lexer { [TestFixture] public class CustomLexerTests { VBLexer GenerateLexer(StringReader sr) { return new VBLexer(sr); } [Test] public void TestSingleEOLForMulitpleLines() { VBLexer lexer = GenerateLexer(new StringReader("Stop\n\n\nEnd")); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Stop)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOL)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.End)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOL)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOF)); } [Test] public void TestSingleEOLForMulitpleLinesWithContinuation() { VBLexer lexer = GenerateLexer(new StringReader("Stop\n _\n\nEnd")); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Stop)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOL)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.End)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOL)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOF)); } [Test] public void EscapedIdentifier() { VBLexer lexer = GenerateLexer(new StringReader("[Stop]")); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Identifier)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOL)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOF)); } [Test] public void IdentifierWithTypeCharacter() { VBLexer lexer = GenerateLexer(new StringReader("Stop$")); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Identifier)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOL)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOF)); } [Test] public void ExclamationMarkIsTypeCharacter() { VBLexer lexer = GenerateLexer(new StringReader("a!=b")); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Identifier)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Assign)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Identifier)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOL)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOF)); } [Test] public void ExclamationMarkIsTypeCharacter2() { VBLexer lexer = GenerateLexer(new StringReader("a! b")); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Identifier)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Identifier)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOL)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOF)); } [Test] public void ExclamationMarkIsIdentifier() { VBLexer lexer = GenerateLexer(new StringReader("a!b")); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Identifier)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.ExclamationMark)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Identifier)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOL)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOF)); } [Test] public void ExclamationMarkIsIdentifier2() { VBLexer lexer = GenerateLexer(new StringReader("a![b]")); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Identifier)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.ExclamationMark)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Identifier)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOL)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOF)); } [Test] public void RemCommentTest() { VBLexer lexer = GenerateLexer(new StringReader("a rem b")); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Identifier)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOL)); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOF)); } [Test] public void RemCommentTest2() { VBLexer lexer = GenerateLexer(new StringReader("REM c")); Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOF)); } } }
{ "pile_set_name": "Github" }
package csm type metricException interface { Exception() string Message() string } type requestException struct { exception string message string } func (e requestException) Exception() string { return e.exception } func (e requestException) Message() string { return e.message } type awsException struct { requestException } type sdkException struct { requestException }
{ "pile_set_name": "Github" }
CodeMirror.defineMode("xml", function(config, parserConfig) { var indentUnit = config.indentUnit; var multilineTagIndentFactor = parserConfig.multilineTagIndentFactor || 1; var multilineTagIndentPastTag = parserConfig.multilineTagIndentPastTag || true; var Kludges = parserConfig.htmlMode ? { autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true, 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true, 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, 'track': true, 'wbr': true}, implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true, 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true, 'th': true, 'tr': true}, contextGrabbers: { 'dd': {'dd': true, 'dt': true}, 'dt': {'dd': true, 'dt': true}, 'li': {'li': true}, 'option': {'option': true, 'optgroup': true}, 'optgroup': {'optgroup': true}, 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true, 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true, 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true, 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true, 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true}, 'rp': {'rp': true, 'rt': true}, 'rt': {'rp': true, 'rt': true}, 'tbody': {'tbody': true, 'tfoot': true}, 'td': {'td': true, 'th': true}, 'tfoot': {'tbody': true}, 'th': {'td': true, 'th': true}, 'thead': {'tbody': true, 'tfoot': true}, 'tr': {'tr': true} }, doNotIndent: {"pre": true}, allowUnquoted: true, allowMissing: true } : { autoSelfClosers: {}, implicitlyClosed: {}, contextGrabbers: {}, doNotIndent: {}, allowUnquoted: false, allowMissing: false }; var alignCDATA = parserConfig.alignCDATA; // Return variables for tokenizers var tagName, type; function inText(stream, state) { function chain(parser) { state.tokenize = parser; return parser(stream, state); } var ch = stream.next(); if (ch == "<") { if (stream.eat("!")) { if (stream.eat("[")) { if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>")); else return null; } else if (stream.match("--")) { return chain(inBlock("comment", "-->")); } else if (stream.match("DOCTYPE", true, true)) { stream.eatWhile(/[\w\._\-]/); return chain(doctype(1)); } else { return null; } } else if (stream.eat("?")) { stream.eatWhile(/[\w\._\-]/); state.tokenize = inBlock("meta", "?>"); return "meta"; } else { var isClose = stream.eat("/"); tagName = ""; var c; while ((c = stream.eat(/[^\s\u00a0=<>\"\'\/?]/))) tagName += c; if (!tagName) return "tag error"; type = isClose ? "closeTag" : "openTag"; state.tokenize = inTag; return "tag"; } } else if (ch == "&") { var ok; if (stream.eat("#")) { if (stream.eat("x")) { ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";"); } else { ok = stream.eatWhile(/[\d]/) && stream.eat(";"); } } else { ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";"); } return ok ? "atom" : "error"; } else { stream.eatWhile(/[^&<]/); return null; } } function inTag(stream, state) { var ch = stream.next(); if (ch == ">" || (ch == "/" && stream.eat(">"))) { state.tokenize = inText; type = ch == ">" ? "endTag" : "selfcloseTag"; return "tag"; } else if (ch == "=") { type = "equals"; return null; } else if (ch == "<") { state.tokenize = inText; var next = state.tokenize(stream, state); return next ? next + " error" : "error"; } else if (/[\'\"]/.test(ch)) { state.tokenize = inAttribute(ch); state.stringStartCol = stream.column(); return state.tokenize(stream, state); } else { stream.eatWhile(/[^\s\u00a0=<>\"\']/); return "word"; } } function inAttribute(quote) { var closure = function(stream, state) { while (!stream.eol()) { if (stream.next() == quote) { state.tokenize = inTag; break; } } return "string"; }; closure.isInAttribute = true; return closure; } function inBlock(style, terminator) { return function(stream, state) { while (!stream.eol()) { if (stream.match(terminator)) { state.tokenize = inText; break; } stream.next(); } return style; }; } function doctype(depth) { return function(stream, state) { var ch; while ((ch = stream.next()) != null) { if (ch == "<") { state.tokenize = doctype(depth + 1); return state.tokenize(stream, state); } else if (ch == ">") { if (depth == 1) { state.tokenize = inText; break; } else { state.tokenize = doctype(depth - 1); return state.tokenize(stream, state); } } } return "meta"; }; } var curState, curStream, setStyle; function pass() { for (var i = arguments.length - 1; i >= 0; i--) curState.cc.push(arguments[i]); } function cont() { pass.apply(null, arguments); return true; } function pushContext(tagName, startOfLine) { var noIndent = Kludges.doNotIndent.hasOwnProperty(tagName) || (curState.context && curState.context.noIndent); curState.context = { prev: curState.context, tagName: tagName, indent: curState.indented, startOfLine: startOfLine, noIndent: noIndent }; } function popContext() { if (curState.context) curState.context = curState.context.prev; } function element(type) { if (type == "openTag") { curState.tagName = tagName; curState.tagStart = curStream.column(); return cont(attributes, endtag(curState.startOfLine)); } else if (type == "closeTag") { var err = false; if (curState.context) { if (curState.context.tagName != tagName) { if (Kludges.implicitlyClosed.hasOwnProperty(curState.context.tagName.toLowerCase())) { popContext(); } err = !curState.context || curState.context.tagName != tagName; } } else { err = true; } if (err) setStyle = "error"; return cont(endclosetag(err)); } return cont(); } function endtag(startOfLine) { return function(type) { var tagName = curState.tagName; curState.tagName = curState.tagStart = null; if (type == "selfcloseTag" || (type == "endTag" && Kludges.autoSelfClosers.hasOwnProperty(tagName.toLowerCase()))) { maybePopContext(tagName.toLowerCase()); return cont(); } if (type == "endTag") { maybePopContext(tagName.toLowerCase()); pushContext(tagName, startOfLine); return cont(); } return cont(); }; } function endclosetag(err) { return function(type) { if (err) setStyle = "error"; if (type == "endTag") { popContext(); return cont(); } setStyle = "error"; return cont(arguments.callee); }; } function maybePopContext(nextTagName) { var parentTagName; while (true) { if (!curState.context) { return; } parentTagName = curState.context.tagName.toLowerCase(); if (!Kludges.contextGrabbers.hasOwnProperty(parentTagName) || !Kludges.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) { return; } popContext(); } } function attributes(type) { if (type == "word") {setStyle = "attribute"; return cont(attribute, attributes);} if (type == "endTag" || type == "selfcloseTag") return pass(); setStyle = "error"; return cont(attributes); } function attribute(type) { if (type == "equals") return cont(attvalue, attributes); if (!Kludges.allowMissing) setStyle = "error"; else if (type == "word") {setStyle = "attribute"; return cont(attribute, attributes);} return (type == "endTag" || type == "selfcloseTag") ? pass() : cont(); } function attvalue(type) { if (type == "string") return cont(attvaluemaybe); if (type == "word" && Kludges.allowUnquoted) {setStyle = "string"; return cont();} setStyle = "error"; return (type == "endTag" || type == "selfCloseTag") ? pass() : cont(); } function attvaluemaybe(type) { if (type == "string") return cont(attvaluemaybe); else return pass(); } return { startState: function() { return {tokenize: inText, cc: [], indented: 0, startOfLine: true, tagName: null, tagStart: null, context: null}; }, token: function(stream, state) { if (!state.tagName && stream.sol()) { state.startOfLine = true; state.indented = stream.indentation(); } if (stream.eatSpace()) return null; setStyle = type = tagName = null; var style = state.tokenize(stream, state); state.type = type; if ((style || type) && style != "comment") { curState = state; curStream = stream; while (true) { var comb = state.cc.pop() || element; if (comb(type || style)) break; } } state.startOfLine = false; if (setStyle) style = setStyle == "error" ? style + " error" : setStyle; return style; }, indent: function(state, textAfter, fullLine) { var context = state.context; // Indent multi-line strings (e.g. css). if (state.tokenize.isInAttribute) { return state.stringStartCol + 1; } if ((state.tokenize != inTag && state.tokenize != inText) || context && context.noIndent) return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0; // Indent the starts of attribute names. if (state.tagName) { if (multilineTagIndentPastTag) return state.tagStart + state.tagName.length + 2; else return state.tagStart + indentUnit * multilineTagIndentFactor; } if (alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0; if (context && /^<\//.test(textAfter)) context = context.prev; while (context && !context.startOfLine) context = context.prev; if (context) return context.indent + indentUnit; else return 0; }, electricChars: "/", blockCommentStart: "<!--", blockCommentEnd: "-->", configuration: parserConfig.htmlMode ? "html" : "xml", helperType: parserConfig.htmlMode ? "html" : "xml" }; }); CodeMirror.defineMIME("text/xml", "xml"); CodeMirror.defineMIME("application/xml", "xml"); if (!CodeMirror.mimeModes.hasOwnProperty("text/html")) CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
{ "pile_set_name": "Github" }
<DocMatCard></DocMatCard> <h5 class="mat-h5">Example</h5> <DemoContainer> <Content> <style> .demo-mat-card { max-width: 400px; } .demo-mat-card-content { padding: 1rem; } .demo-mat-card-clean-margin { margin: 0px; } </style> <MatCard class="demo-mat-card"> <MatCardContent> <MatCardMedia Wide="true" ImageUrl="https://material-components.github.io/material-components-web-catalog/static/media/photos/3x2/2.jpg"></MatCardMedia> <div class="demo-mat-card-content"> <MatHeadline6 class="demo-mat-card-clean-margin"> Our Changing Planet </MatHeadline6> <MatSubtitle2 class="demo-mat-card-clean-margin"> by Kurt Wagner </MatSubtitle2> </div> <MatBody2 class="demo-mat-card-content demo-mat-card-clean-margin"> Visit ten places on our planet that are undergoing the biggest changes today. </MatBody2> </MatCardContent> </MatCard> </Content> <SourceContent> <BlazorFiddle Template="MatBlazor" Code=@(@" <style> .demo-mat-card { max-width: 400px; } .demo-mat-card-content { padding: 1rem; } .demo-mat-card-clean-margin { margin: 0px; } </style> <MatCard class=""demo-mat-card""> <MatCardContent> <MatCardMedia Wide=""true"" ImageUrl=""https://material-components.github.io/material-components-web-catalog/static/media/photos/3x2/2.jpg""></MatCardMedia> <div class=""demo-mat-card-content""> <MatHeadline6 class=""demo-mat-card-clean-margin""> Our Changing Planet </MatHeadline6> <MatSubtitle2 class=""demo-mat-card-clean-margin""> by Kurt Wagner </MatSubtitle2> </div> <MatBody2 class=""demo-mat-card-content demo-mat-card-clean-margin""> Visit ten places on our planet that are undergoing the biggest changes today. </MatBody2> </MatCardContent> </MatCard> ")></BlazorFiddle> </SourceContent> </DemoContainer> <MatH5>Material Design Card example with actions</MatH5> <DemoContainer> <Content> <style> </style> <MatCard class="demo-mat-card"> <MatCardContent> <MatCardMedia Wide="true" ImageUrl="https://material-components.github.io/material-components-web-catalog/static/media/photos/3x2/2.jpg"></MatCardMedia> <div class="demo-mat-card-content"> <MatHeadline6 class="demo-mat-card-clean-margin"> Our Changing Planet </MatHeadline6> <MatSubtitle2 class="demo-mat-card-clean-margin"> by Kurt Wagner </MatSubtitle2> </div> <MatBody2 class="demo-mat-card-content demo-mat-card-clean-margin"> Visit ten places on our planet that are undergoing the biggest changes today. </MatBody2> </MatCardContent> <MatCardActions> <MatButton>Read</MatButton> <MatButton>Bookmark</MatButton> </MatCardActions> </MatCard> </Content> <SourceContent> <BlazorFiddle Template="MatBlazor" Code=@(@" <style> </style> <MatCard class=""demo-mat-card""> <MatCardContent> <MatCardMedia Wide=""true"" ImageUrl=""https://material-components.github.io/material-components-web-catalog/static/media/photos/3x2/2.jpg""></MatCardMedia> <div class=""demo-mat-card-content""> <MatHeadline6 class=""demo-mat-card-clean-margin""> Our Changing Planet </MatHeadline6> <MatSubtitle2 class=""demo-mat-card-clean-margin""> by Kurt Wagner </MatSubtitle2> </div> <MatBody2 class=""demo-mat-card-content demo-mat-card-clean-margin""> Visit ten places on our planet that are undergoing the biggest changes today. </MatBody2> </MatCardContent> <MatCardActions> <MatButton>Read</MatButton> <MatButton>Bookmark</MatButton> </MatCardActions> </MatCard> ")></BlazorFiddle> </SourceContent> </DemoContainer> <MatH5>Material Design Card example with action buttons and icons</MatH5> <DemoContainer> <Content> <style> </style> <MatCard class="demo-mat-card"> <MatCardContent> <MatCardMedia Wide="true" ImageUrl="https://material-components.github.io/material-components-web-catalog/static/media/photos/3x2/2.jpg"></MatCardMedia> <div class="demo-mat-card-content"> <MatHeadline6 class="demo-mat-card-clean-margin"> Our Changing Planet </MatHeadline6> <MatSubtitle2 class="demo-mat-card-clean-margin"> by Kurt Wagner </MatSubtitle2> </div> <MatBody2 class="demo-mat-card-content demo-mat-card-clean-margin"> Visit ten places on our planet that are undergoing the biggest changes today. </MatBody2> </MatCardContent> <MatCardActions> <MatCardActionButtons> <MatButton>Read</MatButton> <MatButton>Bookmark</MatButton> </MatCardActionButtons> <MatCardActionIcons> <MatIconButton Icon="@MatIconNames.Favorite"></MatIconButton> <MatIconButton Icon="@MatIconNames.Dashboard"></MatIconButton> </MatCardActionIcons> </MatCardActions> </MatCard> </Content> <SourceContent> <BlazorFiddle Template="MatBlazor" Code=@(@" <style> </style> <MatCard class=""demo-mat-card""> <MatCardContent> <MatCardMedia Wide=""true"" ImageUrl=""https://material-components.github.io/material-components-web-catalog/static/media/photos/3x2/2.jpg""></MatCardMedia> <div class=""demo-mat-card-content""> <MatHeadline6 class=""demo-mat-card-clean-margin""> Our Changing Planet </MatHeadline6> <MatSubtitle2 class=""demo-mat-card-clean-margin""> by Kurt Wagner </MatSubtitle2> </div> <MatBody2 class=""demo-mat-card-content demo-mat-card-clean-margin""> Visit ten places on our planet that are undergoing the biggest changes today. </MatBody2> </MatCardContent> <MatCardActions> <MatCardActionButtons> <MatButton>Read</MatButton> <MatButton>Bookmark</MatButton> </MatCardActionButtons> <MatCardActionIcons> <MatIconButton Icon=""@MatIconNames.Favorite""></MatIconButton> <MatIconButton Icon=""@MatIconNames.Dashboard""></MatIconButton> </MatCardActionIcons> </MatCardActions> </MatCard> ")></BlazorFiddle> </SourceContent> </DemoContainer> <MatH5>Material Design Card example with text over media</MatH5> <DemoContainer> <Content> <MatCard class="demo-mat-card"> <MatCardContent> <MatCardMedia Wide="true" ImageUrl="https://material-components.github.io/material-components-web-catalog/static/media/photos/3x2/2.jpg"> <div class="demo-mat-card-content" style="color: white;"> <MatHeadline6 class="demo-mat-card-clean-margin"> Our Changing Planet </MatHeadline6> <MatSubtitle2 class="demo-mat-card-clean-margin"> by Kurt Wagner </MatSubtitle2> </div> </MatCardMedia> <MatBody2 class="demo-mat-card-content demo-mat-card-clean-margin"> Visit ten places on our planet that are undergoing the biggest changes today. </MatBody2> </MatCardContent> <MatCardActions> <MatCardActionButtons> <MatButton>Read</MatButton> <MatButton>Bookmark</MatButton> </MatCardActionButtons> <MatCardActionIcons> <MatIconButton Icon="@MatIconNames.Favorite"></MatIconButton> <MatIconButton Icon="@MatIconNames.Dashboard"></MatIconButton> </MatCardActionIcons> </MatCardActions> </MatCard> </Content> <SourceContent> <BlazorFiddle Template="MatBlazor" Code=@(@" <MatCard class=""demo-mat-card""> <MatCardContent> <MatCardMedia Wide=""true"" ImageUrl=""https://material-components.github.io/material-components-web-catalog/static/media/photos/3x2/2.jpg""> <div class=""demo-mat-card-content"" style=""color: white;""> <MatHeadline6 class=""demo-mat-card-clean-margin""> Our Changing Planet </MatHeadline6> <MatSubtitle2 class=""demo-mat-card-clean-margin""> by Kurt Wagner </MatSubtitle2> </div> </MatCardMedia> <MatBody2 class=""demo-mat-card-content demo-mat-card-clean-margin""> Visit ten places on our planet that are undergoing the biggest changes today. </MatBody2> </MatCardContent> <MatCardActions> <MatCardActionButtons> <MatButton>Read</MatButton> <MatButton>Bookmark</MatButton> </MatCardActionButtons> <MatCardActionIcons> <MatIconButton Icon=""@MatIconNames.Favorite""></MatIconButton> <MatIconButton Icon=""@MatIconNames.Dashboard""></MatIconButton> </MatCardActionIcons> </MatCardActions> </MatCard> ")></BlazorFiddle> </SourceContent> </DemoContainer> <MatH5>Material Design Card example with header</MatH5> <DemoContainer> <Content> <MatCard class="demo-mat-card"> <div class="demo-mat-card-content"> <MatHeadline6 class="demo-mat-card-clean-margin"> Our Changing Planet </MatHeadline6> <MatSubtitle2 class="demo-mat-card-clean-margin"> by Kurt Wagner </MatSubtitle2> </div> <MatCardContent> <MatCardMedia Wide="true" ImageUrl="https://material-components.github.io/material-components-web-catalog/static/media/photos/3x2/2.jpg"></MatCardMedia> <MatBody2 class="demo-mat-card-content demo-mat-card-clean-margin"> Visit ten places on our planet that are undergoing the biggest changes today. </MatBody2> </MatCardContent> <MatCardActions> <MatCardActionButtons> <MatButton>Read</MatButton> <MatButton>Bookmark</MatButton> </MatCardActionButtons> <MatCardActionIcons> <MatIconButton Icon="@MatIconNames.Favorite"></MatIconButton> <MatIconButton Icon="@MatIconNames.Dashboard"></MatIconButton> </MatCardActionIcons> </MatCardActions> </MatCard> </Content> <SourceContent> <BlazorFiddle Template="MatBlazor" Code=@(@" <MatCard class=""demo-mat-card""> <div class=""demo-mat-card-content""> <MatHeadline6 class=""demo-mat-card-clean-margin""> Our Changing Planet </MatHeadline6> <MatSubtitle2 class=""demo-mat-card-clean-margin""> by Kurt Wagner </MatSubtitle2> </div> <MatCardContent> <MatCardMedia Wide=""true"" ImageUrl=""https://material-components.github.io/material-components-web-catalog/static/media/photos/3x2/2.jpg""></MatCardMedia> <MatBody2 class=""demo-mat-card-content demo-mat-card-clean-margin""> Visit ten places on our planet that are undergoing the biggest changes today. </MatBody2> </MatCardContent> <MatCardActions> <MatCardActionButtons> <MatButton>Read</MatButton> <MatButton>Bookmark</MatButton> </MatCardActionButtons> <MatCardActionIcons> <MatIconButton Icon=""@MatIconNames.Favorite""></MatIconButton> <MatIconButton Icon=""@MatIconNames.Dashboard""></MatIconButton> </MatCardActionIcons> </MatCardActions> </MatCard> ")></BlazorFiddle> </SourceContent> </DemoContainer>
{ "pile_set_name": "Github" }
from collections import namedtuple # depth always stores the absolute depth values (not inverse depth) # image is a PIL.Image with the same dimensions as depth # depth_metric should always be 'camera_z' # K corresponds to the width and height of image/depth # R, t is the world to camera transform View = namedtuple('View',['R','t','K','image','depth','depth_metric']) # stores a camera pose # R, t is the world to camera transform Pose = namedtuple('Pose',['R','t']) from minieigen import Matrix3, Vector3 from .rotation_conversion import * import numpy as np class Frame: def __init__(self, image, pose=None, depth=None): self.image = image self.pose = pose self.depth =depth def Pose_identity(): """Returns the identity pose""" return Pose(R = Matrix3.Identity, t = Vector3.Zero) class SeqPy: """This class is used for handling sequence data in format of python """ def __init__(self,seq_len): """Initialize an empty sequence seq_len: int sequence length """ self.depth_list = [None] * seq_len self.image_list = [None] * seq_len self.flow_list = [None] * seq_len self.pose_list = [None] * seq_len self.intrinsics = None self.seq_len = seq_len def set_pose_list(self, translation_list, rotation_list): """Set pose list translation_list: a list of numpy array rotation_list: a list of numpy array """ assert(len(translation_list) == self.seq_len), 'cannot initialize pose from translation list. sequence length is not compatible' assert(len(rotation_list) == self.seq_len), 'cannot initialize pose from rotation list. sequence length is not compatible' for frame in range(self.seq_len): rot = rotation_list[frame].squeeze() trans = translation_list[frame].squeeze() R = Matrix3(angleaxis_to_rotation_matrix(numpy_to_Vector3(rot))) t = numpy_to_Vector3(trans) pose = Pose(R=R,t=t) self.pose_list[frame] = pose def set_flow_list(self, flow_list): """Set flow list flow_list: a list of numpy array """ assert(len(flow_list) == self.seq_len), 'cannot initialize pose from flow list. sequence length is not compatible' for frame in range(self.seq_len): self.flow_list[frame] = flow_list[frame] def set_flow_from_depth(self): """Set flow list using depth and camera pose """ for frame in range(self.seq_len): self.flow_list[frame] = self.compute_flow_from_depth(0,frame) def set_image_list(self, image_list): """Set image list image_list: a list of numpy array """ assert(len(image_list) == self.seq_len), 'cannot initialize pose from image list. sequence length is not compatible' for frame in range(self.seq_len): self.image_list[frame] = image_list[frame] def set_intrinsics(self, intrinsics): """Set intrinsics intrinsics: numpy array """ self.intrinsics = intrinsics def set_depth_list(self, depth_list): """Set depth list depth_list: a list of numpy array """ for frame in range(len(depth_list)): self.depth_list[frame] = depth_list[frame] def get_rotation(self, frame, rotation_format='ANGLEAXIS'): """Get rotation at certain frame frame: int rotation_format: str 'ANGLEAXIS','ROTATION_MATRIX' """ if rotation_format == 'ROTATION_MATRIX': return np.array(self.pose_list[frame].R) elif rotation_format == 'ANGLEAXIS': angleaxis = rotation_matrix_to_angleaxis(self.pose_list[frame].R) return angleaxis def get_translation(self, frame, normalize=False): """Get translation at certain frame frame: int normalize: bool """ if normalize: trans = self.pose_list[frame].t / self.pose_list[frame].t.norm() else: trans = self.pose_list[frame].t return np.array(trans) def get_flow(self, frame): """Get flow at certain frame frame: int """ return self.flow_list[frame] def get_image(self, frame): """Get image at certain frame frame: int """ return self.image_list[frame] def get_K(self, normalize=False): """Get camera intrinsics matrix K normalize: bool """ if normalize: width = 1 height = 1 else: if self.get_depth(0) is not None: width = self.get_depth(0).shape[-1] height = self.get_depth(0).shape[-2] fx = self.intrinsics[0]*width fy = self.intrinsics[1]*height cx = self.intrinsics[2]*width cy = self.intrinsics[3]*height return np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]], dtype=np.float64) def get_depth(self, frame, inverse=False): """Get depth at certain frame frame: int inverse: bool inverse the depth """ if inverse: return 1/self.depth_list[frame] else: return self.depth_list[frame] def adjust_pose_wrt_ref(self, ref): """Adjust the poses with respect to the reference frame. ref: int """ assert(self.pose_list[0]), 'pose list does not exist' adjusted_poses = [None]*len(self.pose_list) pose_ref = self.pose_list[ref] R_ref = pose_ref.R t_ref = pose_ref.t for ind, pose in enumerate(self.pose_list): if ind == ref: adjusted_poses[ind] = Pose(R = Matrix3.Identity, t = Vector3.Zero) else: R_adjusted = pose.R * R_ref.transpose() t_adjusted = pose.t - R_adjusted*t_ref adjusted_poses[ind] = Pose(R = R_adjusted, t= t_adjusted) self.pose_list = adjusted_poses def offset_pose(self, offset): """Offset the pose list with a certain pose. inc_pose: Pose """ offseted_poses = [None]*len(self.pose_list) for frame in range(self.seq_len): new_R = self.pose_list[frame].R * offset.R new_t = self.pose_list[frame].R * offset.t+self.pose_list[frame].t offseted_poses[frame] = Pose(R=new_R,t=new_t) # self.pose_list = offseted_poses return offseted_poses class SubSeqPy(SeqPy): def __init__(self, sequence, start_frame=0, seq_len=2): self.seq_len = seq_len self.image_list = sequence.image_list[start_frame:start_frame+seq_len] self.depth_list = sequence.depth_list[start_frame:start_frame+seq_len] self.flow_list = [None] * seq_len self.pose_list = sequence.pose_list[start_frame:start_frame+seq_len] self.intrinsics = sequence.intrinsics def generate_sub_seq_list_py(sequence, sub_seq_len=2): """Generate sub sequence list sequence: SeqPy class sub_seq_len: int Returns a list of SubSeqPy class object(aligned with the first frame of the subseq) and a list of View tuple(aligned with the first frame of sequence) """ sub_seq_list = [] total_seq_len = sequence.seq_len seq_start = 0 key_view_list = [] while(seq_start <= total_seq_len - sub_seq_len): sub_seq = SubSeqPy(sequence, seq_start, sub_seq_len) sub_seq.adjust_pose_wrt_ref(0) view = View(R=sequence.get_rotation(frame=seq_start,rotation_format='ROTATION_MATRIX'), t=sequence.get_translation(frame=seq_start), K=sequence.get_K(normalize=False), image=convert_image(sequence.get_image(frame=seq_start).squeeze()), depth=sequence.get_depth(frame=seq_start,inverse=True).squeeze(), depth_metric='camera_z') key_view_list.append(view) seq_start = seq_start + sub_seq_len - 1 sub_seq_list.append(sub_seq) return sub_seq_list, key_view_list
{ "pile_set_name": "Github" }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.ML.Data; namespace Microsoft.ML.Functional.Tests.Datasets { internal sealed class MnistOneClass { private const int _featureLength = 783; public float Label { get; set; } public float[] Features { get; set; } public static TextLoader GetTextLoader(MLContext mlContext, bool hasHeader, char separatorChar) { return mlContext.Data.CreateTextLoader( new[] { new TextLoader.Column("Label", DataKind.Single, 0), new TextLoader.Column("Features", DataKind.Single, 1, 1 + _featureLength) }, separatorChar: separatorChar, hasHeader: hasHeader, allowSparse: true); } } }
{ "pile_set_name": "Github" }
<!doctype html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"> <head> <title> Comment voulez-vous aborder 2019 ? </title> <!--[if !mso]><!-- --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!--<![endif]--> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <style type="text/css"> #outlook a { padding:0; } .ReadMsgBody { width:100%; } .ExternalClass { width:100%; } .ExternalClass * { line-height:100%; } body { margin:0;padding:0;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%; } table, td { border-collapse:collapse;mso-table-lspace:0pt;mso-table-rspace:0pt; } img { border:0;height:auto;line-height:100%; outline:none;text-decoration:none;-ms-interpolation-mode:bicubic; } p { display:block;margin:13px 0; } </style> <!--[if !mso]><!--> <style type="text/css"> @media only screen and (max-width:480px) { @-ms-viewport { width:320px; } @viewport { width:320px; } } </style> <!--<![endif]--> <!--[if mso]> <xml> <o:OfficeDocumentSettings> <o:AllowPNG/> <o:PixelsPerInch>96</o:PixelsPerInch> </o:OfficeDocumentSettings> </xml> <![endif]--> <!--[if lte mso 11]> <style type="text/css"> .outlook-group-fix { width:100% !important; } </style> <![endif]--> <!--[if !mso]><!--> <link href="https://fonts.googleapis.com/css?family=Lato:300,400,500,700" rel="stylesheet" type="text/css"> <style type="text/css"> @import url(https://fonts.googleapis.com/css?family=Lato:300,400,500,700); </style> <!--<![endif]--> <style type="text/css"> @media only screen and (min-width:480px) { .mj-column-per-100 { width:100% !important; max-width: 100%; } } </style> <style type="text/css"> [owa] .mj-column-per-100 { width:100% !important; max-width: 100%; } </style> <style type="text/css"> @media only screen and (max-width:480px) { table.full-width-mobile { width: 100% !important; } td.full-width-mobile { width: auto !important; } } </style> </head> <body style="background-color:#ffffff;"> <div style="background-color:#ffffff;" > <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="background:transparent;background-color:transparent;width:100%;" > <tbody> <tr> <td> <!--[if mso | IE]> <table align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600" > <tr> <td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"> <![endif]--> <div style="Margin:0px auto;max-width:600px;"> <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;" > <tbody> <tr> <td style="direction:ltr;font-size:0px;padding:20px 0px 20px 0px;padding-bottom:12px;padding-top:12px;text-align:center;vertical-align:top;" > <!--[if mso | IE]> <table role="presentation" border="0" cellpadding="0" cellspacing="0"> <tr> <td class="" style="vertical-align:top;width:600px;" > <![endif]--> <div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;" > <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%" > <tr> <td align="left" style="font-size:0px;padding:0px 25px 0px 25px;padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px;word-break:break-word;" > <div style="font-family:Arial, sans-serif;font-size:13px;line-height:22px;text-align:left;color:#55575d;" > <style></style><p style="line-height: 1.38; margin: 10px 0;"><span style="font-family:Lato,Helvetica,Arial,sans-serif"><span style="font-size:14px"><span style="color:#000000; text-decoration:none">Hello {{var:firstName:"Élise"}},</span>&nbsp;</span></span></p> </div> </td> </tr> </table> </div> <!--[if mso | IE]> </td> </tr> </table> <![endif]--> </td> </tr> </tbody> </table> </div> <!--[if mso | IE]> </td> </tr> </table> <![endif]--> </td> </tr> </tbody> </table> <!--[if mso | IE]> <table align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600" > <tr> <td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"> <![endif]--> <div style="Margin:0px auto;max-width:600px;"> <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;" > <tbody> <tr> <td style="direction:ltr;font-size:0px;padding:20px 0;padding-bottom:0px;padding-top:0px;text-align:center;vertical-align:top;" > <!--[if mso | IE]> <table role="presentation" border="0" cellpadding="0" cellspacing="0"> <tr> <td class="" style="vertical-align:top;width:600px;" > <![endif]--> <div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;" > <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%" > <tr> <td align="left" style="font-size:0px;padding:10px 25px;padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px;word-break:break-word;" > <div style="font-family:Arial, sans-serif;font-size:13px;line-height:22px;text-align:left;color:#55575d;" > <style></style><p style="line-height: 1.38; margin: 10px 0;"><span style="font-family:Lato,Helvetica,Arial,sans-serif"><span style="color:#000000; font-size:11pt; text-decoration:none">Je voudrais vous souhaiter une excellente fin d’année.</span></span></p> </div> </td> </tr> </table> </div> <!--[if mso | IE]> </td> </tr> </table> <![endif]--> </td> </tr> </tbody> </table> </div> <!--[if mso | IE]> </td> </tr> </table> <table align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600" > <tr> <td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"> <![endif]--> <div style="Margin:0px auto;max-width:600px;"> <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;" > <tbody> <tr> <td style="direction:ltr;font-size:0px;padding:20px 0;padding-bottom:0px;padding-top:0px;text-align:center;vertical-align:top;" > <!--[if mso | IE]> <table role="presentation" border="0" cellpadding="0" cellspacing="0"> <tr> <td class="" style="vertical-align:top;width:600px;" > <![endif]--> <div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;" > <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%" > <tr> <td align="left" style="font-size:0px;padding:10px 25px;padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px;word-break:break-word;" > <div style="font-family:Arial, sans-serif;font-size:13px;line-height:22px;text-align:left;color:#55575d;" > <style></style><p style="line-height: 1.38; margin: 10px 0;"><span style="font-family:Lato,Helvetica,Arial,sans-serif"><span style="color:#000000; font-size:11pt; text-decoration:none">Que vous fêtiez Hanoucca, Noël, rien du tout ou autre chose </span></span>—&nbsp;<span style="font-family:Lato,Helvetica,Arial,sans-serif"><span style="color:#000000; font-size:11pt; text-decoration:none">&nbsp;les vacances, la nouvelle année, le changement de saison, l'arrivée du froid ou de la neige </span></span>—<span style="font-family:Lato,Helvetica,Arial,sans-serif"><span style="color:#000000; font-size:11pt; text-decoration:none">&nbsp;nous vous souhaitons de bien terminer 2018&nbsp;et de vous lancer heureu{%if var:gender:"" == "FEMININE"%}se{%else%}x{%endif%}</span><span style="color:#000000; font-size:11pt; text-decoration:none">&nbsp;et confian</span><span style="color:#000000; font-size:11pt; text-decoration:none">t{%if var:gender:"" == "FEMININE"%}e{%endif%} dans 2019. La fin d'année est le moment de faire attention à soi, de se recentrer sur ce qui est important et de s'entourer de ceux qui comptent. C'est tout ce que je vous souhaite. </span></span></p> </div> </td> </tr> </table> </div> <!--[if mso | IE]> </td> </tr> </table> <![endif]--> </td> </tr> </tbody> </table> </div> <!--[if mso | IE]> </td> </tr> </table> <table align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600" > <tr> <td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"> <![endif]--> <div style="Margin:0px auto;max-width:600px;"> <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;" > <tbody> <tr> <td style="direction:ltr;font-size:0px;padding:20px 0;padding-bottom:0px;padding-top:0px;text-align:center;vertical-align:top;" > <!--[if mso | IE]> <table role="presentation" border="0" cellpadding="0" cellspacing="0"> <tr> <td class="" style="vertical-align:top;width:600px;" > <![endif]--> <div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;" > <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%" > <tr> <td align="left" style="font-size:0px;padding:10px 25px;padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px;word-break:break-word;" > <div style="font-family:Arial, sans-serif;font-size:13px;line-height:22px;text-align:left;color:#55575d;" > <style></style><p style="line-height: 1.38; margin: 10px 0;"><span style="font-family:Lato,Helvetica,Arial,sans-serif"><span style="color:#000000; font-size:11pt; text-decoration:none">En décembre, tout le monde ne parle que de faire des bilans, mais de mon côté je préfère me poser ces questions :</span></span></p><ul><li style="line-height:1.38"><span style="font-family:Lato,Helvetica,Arial,sans-serif"><span style="color:#000000; font-size:11pt; text-decoration:none">✌️ Comment est-ce que je me sens dans ma vie ?</span></span></li><li style="line-height:1.38"><span style="font-family:Lato,Helvetica,Arial,sans-serif"><span style="color:#000000; font-size:11pt; text-decoration:none">🔮 De quoi ai-je envie pour l'avenir ? </span></span></li><li style="line-height:1.38"><span style="font-family:Lato,Helvetica,Arial,sans-serif"><span style="color:#000000; font-size:11pt; text-decoration:none">🍀 Y a-t-il des choses que je pourrais faire pour être plus épanouie ?</span></span></li></ul> </div> </td> </tr> </table> </div> <!--[if mso | IE]> </td> </tr> </table> <![endif]--> </td> </tr> </tbody> </table> </div> <!--[if mso | IE]> </td> </tr> </table> <table align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600" > <tr> <td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"> <![endif]--> <div style="Margin:0px auto;max-width:600px;"> <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;" > <tbody> <tr> <td style="direction:ltr;font-size:0px;padding:20px 0;padding-bottom:0px;padding-top:0px;text-align:center;vertical-align:top;" > <!--[if mso | IE]> <table role="presentation" border="0" cellpadding="0" cellspacing="0"> <tr> <td class="" style="vertical-align:top;width:600px;" > <![endif]--> <div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;" > <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%" > <tr> <td align="left" style="font-size:0px;padding:10px 25px;padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px;word-break:break-word;" > <div style="font-family:Arial, sans-serif;font-size:13px;line-height:22px;text-align:left;color:#55575d;" > <style></style><p style="margin: 10px 0;"><span style="font-family:Lato,Helvetica,Arial,sans-serif"><span style="color:#000000; font-size:11pt; text-decoration:none">Je {%if var:startedSearchingSince:"" != ""%}sais que vous vous êtes lancé{%if var:gender:"" == "FEMININE"%}e{%endif%}&nbsp;dans votre recherche {{var:startedSearchingSince:"depuis peu"}}, et je{%endif%} pense que la fin d'année pourrait être le bon moment pour remettre les compteurs à zéro, vous inspirer et ouvrir de nouveaux horizons.</span></span></p> </div> </td> </tr> <tr> <td align="left" style="font-size:0px;padding:10px 25px;padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px;word-break:break-word;" > <div style="font-family:Arial, sans-serif;font-size:13px;line-height:22px;text-align:left;color:#55575d;" > <style></style><p style="line-height: 1.38; margin: 10px 0;"><span style="font-family:Lato,Helvetica,Arial,sans-serif"><span style="color:#000000; font-size:11pt; text-decoration:none">Quelques questions pour commencer...</span></span></p><ul><li style="line-height:1.38"><span style="font-family:Lato,Helvetica,Arial,sans-serif"><span style="color:#000000; font-size:11pt; text-decoration:none">🔧 Et si j'apprenais quelque chose de nouveau ?</span></span></li><li style="line-height:1.38"><span style="font-family:Lato,Helvetica,Arial,sans-serif"><span style="color:#000000; font-size:11pt; text-decoration:none">{%if var:inCommuteCity:"" != ""%}📍 <a target="_blank" href="{{var:adviceUrlCommute:"https://www.bob-emploi.fr/"}}">Et si je travaillais {{var:inCommuteCity:""}} ?</a></span></span></li><li style="line-height:1.38"><span style="font-family:Lato,Helvetica,Arial,sans-serif"><span style="color:#000000; font-size:11pt; text-decoration:none">{%endif%}{%if var:inRelocateDepartement:"" != ""%}🌍 <a target="_blank" href="{{var:adviceUrlRelocate:"https://www.bob-emploi.fr/"}}">Et si je déménageais {{var:inRelocateDepartement:""}} ?</a></span></span></li><li style="line-height:1.38"><span style="font-family:Lato,Helvetica,Arial,sans-serif"><span style="color:#000000; font-size:11pt; text-decoration:none">{%endif%}🔦 Et si j'explorais cette piste que j'avais mise de côté ?</span></span></li><li style="line-height:1.38"><span style="font-family:Lato,Helvetica,Arial,sans-serif"><span style="color:#000000; font-size:11pt; text-decoration:none">{%if var:couldFreelance:"" == "True"%}🎒 <a target="_blank" href="{{var:adviceUrlCreateYourCompany:"https://www.bob-emploi.fr/"}}">Et si je me lançais à mon compte ?</a></span></span></li><li style="line-height:1.38"><span style="font-family:Lato,Helvetica,Arial,sans-serif"><span style="color:#000000; font-size:11pt; text-decoration:none">{%endif%}💡 Et si je faisais ce métier qui m'a toujours fait rêver ? </span></span></li>{%if var:adviceUrlBodyLanguage:"" != ""%}<li style="line-height:1.38"><span style="font-family:Lato,Helvetica,Arial,sans-serif"><span style="color:#000000; font-size:11pt; text-decoration:none">⭐️&nbsp;<a target="_blank" href="{{var:adviceUrlBodyLanguage:"https://www.bob-emploi.fr/"}}">Et si je développais&nbsp;ma confiance en moi ?</a></span></span></li>{%endif%}<li style="line-height:1.38"><span style="font-family:Lato,Helvetica,Arial,sans-serif"><span style="color:#000000; font-size:11pt; text-decoration:none">🤝&nbsp;Et si je donnais un coup de main à une association ?</span></span></li></ul><p style="line-height: 1.38; margin: 10px 0;"><span style="font-family:Lato,Helvetica,Arial,sans-serif"><span style="color:#000000; font-size:11pt; text-decoration:none">(Plein d'autres questions sur votre page Bob : </span><a target="_blank" style="text-decoration:none" href="http://www.bob-emploi.fr?email={{var:emailInUrl}}"><u style="color:#1155cc; font-family:Arial; font-size:11pt; text-decoration:underline">www.bob-emploi.fr</u></a><span style="color:#000000; font-size:11pt; text-decoration:none">)</span></span></p> </div> </td> </tr> <tr> <td align="left" style="font-size:0px;padding:10px 25px;padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px;word-break:break-word;" > <div style="font-family:Arial, sans-serif;font-size:13px;line-height:22px;text-align:left;color:#55575d;" > <style></style><p style="line-height: 1.38; margin: 10px 0;"><span style="font-family:Lato,Helvetica,Arial,sans-serif"><span style="color:#000000; font-size:11pt; text-decoration:none">Ce n'est pas forcément le moment de se lancer dans l'action : pas de précipitation. Considérez simplement ces possibilités, et prenez le temps de les laisser mûrir. Qui sait où elles vous mèneront ?</span></span></p><p style="line-height: 1.38; margin: 10px 0;"><span style="font-family:Lato,Helvetica,Arial,sans-serif"><span style="color:#000000; font-size:11pt; text-decoration:none">Si vous avez des questionnements ou des avancées à partager, répondez simplement à ce mail.</span></span></p> </div> </td> </tr> </table> </div> <!--[if mso | IE]> </td> </tr> </table> <![endif]--> </td> </tr> </tbody> </table> </div> <!--[if mso | IE]> </td> </tr> </table> <![endif]--> <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="background:#ffffff;background-color:#ffffff;width:100%;" > <tbody> <tr> <td> <!--[if mso | IE]> <table align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600" > <tr> <td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"> <![endif]--> <div style="Margin:0px auto;max-width:600px;"> <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;" > <tbody> <tr> <td style="direction:ltr;font-size:0px;padding:20px 0;padding-bottom:0px;padding-top:0px;text-align:center;vertical-align:top;" > <!--[if mso | IE]> <table role="presentation" border="0" cellpadding="0" cellspacing="0"> <tr> <td class="" style="vertical-align:top;width:600px;" > <![endif]--> <div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;" > <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%" > <tr> <td align="left" style="font-size:0px;padding:10px 25px;padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px;word-break:break-word;" > <div style="font-family:Arial, sans-serif;font-size:13px;line-height:22px;text-align:left;color:#55575d;" > <style></style><p style="line-height: 1.38; margin: 10px 0;"><span style="font-family:Lato,Helvetica,Arial,sans-serif"><span style="color:#000000; font-size:11pt; text-decoration:none">Bonne fin d'année, {{var:firstName:"Élise"}}. </span></span></p><p style="line-height: 1.38; margin: 10px 0;"><span style="font-family:Lato,Helvetica,Arial,sans-serif"><span style="color:#000000; font-size:11pt; text-decoration:none">Plein de bonnes choses,</span></span></p> </div> </td> </tr> <tr> <td align="left" style="font-size:0px;padding:10px 25px;padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px;word-break:break-word;" > <div style="font-family:Arial, sans-serif;font-size:13px;line-height:22px;text-align:left;color:#55575d;" > <style></style><p style="line-height: 1.38; margin: 10px 0;"><span style="color:#000000"><span style="font-size:14.6667px">Joanna de Bob&nbsp;</span></span></p> </div> </td> </tr> <tr> <td align="left" style="font-size:0px;padding:10px 25px;padding-top:0px;padding-left:0px;word-break:break-word;" > <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="border-collapse:collapse;border-spacing:0px;" > <tbody> <tr> <td style="width:142px;"> <img alt="www.bob-emploi.fr" height="auto" src="http://r.bob-emploi.fr/tplimg/6u2u/b/44ky/2vvvu.png" style="border:none;display:block;outline:none;text-decoration:none;height:auto;width:100%;" title="" width="142" /> </td> </tr> </tbody> </table> </td> </tr> <tr> <td align="left" style="font-size:0px;padding:10px 25px;padding-top:15px;padding-right:0px;padding-bottom:0px;padding-left:0px;word-break:break-word;" > <div style="font-family:Arial, sans-serif;font-size:13px;line-height:22px;text-align:left;color:#55575d;" > <style></style><p style="margin: 10px 0;"><span style="font-family:Lato,Helvetica,Arial,sans-serif"><span style="color:#000000; font-size:11pt; text-decoration:none"><span style="color:#242323">&nbsp;<span style="font-size:14px">PS : Si vous souhaitez faire un don&nbsp;à Bob à l'occasion de la fin d'année, </span></span><span style="font-size:14px"><a target="_blank" style="color:#242323" href="https://www.helloasso.com/associations/bayes-impact-france"><span style="color:#242323">vous pouvez le faire via notre page sur Hello Asso</span></a></span></span><span style="font-size:14px"><span style="color:#242323">. Les dons aux associations sont défiscalisables à 66% 👍</span></span></span></p> </div> </td> </tr> <tr> <td align="left" style="font-size:0px;padding:10px 25px;padding-top:15px;padding-right:0px;padding-bottom:0px;padding-left:0px;word-break:break-word;" > <div style="font-family:Arial, sans-serif;font-size:13px;line-height:22px;text-align:left;color:#55575d;" > <style></style><p style="margin: 10px 0;"><span style="font-size:11px">Vous recevez cet email car vous êtes inscrit sur <a target="_blank" href="https://www.bob-emploi.fr">Bob</a>. <a target="_blank" href="{{var:unsubscribeLink}}"><u>Cliquez ici</u></a> si vous souhaitez vous désinscrire.</span></p> </div> </td> </tr> </table> </div> <!--[if mso | IE]> </td> </tr> </table> <![endif]--> </td> </tr> </tbody> </table> </div> <!--[if mso | IE]> </td> </tr> </table> <![endif]--> </td> </tr> </tbody> </table> </div> </body> </html>
{ "pile_set_name": "Github" }
/* * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. * 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. */ /* * A class to track key AT instance info from the JavaAccessBridge */ #include "AccessBridgeDebug.h" #include "AccessBridgeATInstance.h" #include "AccessBridgeMessages.h" #include <windows.h> #include <winbase.h> /** * AccessBridgeATInstance constructor */ AccessBridgeATInstance::AccessBridgeATInstance(HWND ourABWindow, HWND winABWindow, char *memoryFilename, AccessBridgeATInstance *next) { ourAccessBridgeWindow = ourABWindow; winAccessBridgeWindow = winABWindow; nextATInstance = next; javaEventMask = 0; accessibilityEventMask = 0; strncpy(memoryMappedFileName, memoryFilename, cMemoryMappedNameSize); } /** * AccessBridgeATInstance descructor */ AccessBridgeATInstance::~AccessBridgeATInstance() { PrintDebugString("[INFO]: in AccessBridgeATInstance::~AccessBridgeATInstance"); // if IPC memory mapped file view is valid, unmap it if (memoryMappedView != (char *) 0) { PrintDebugString("[INFO]: unmapping memoryMappedView; view = %p", memoryMappedView); UnmapViewOfFile(memoryMappedView); memoryMappedView = (char *) 0; } // if IPC memory mapped file handle map is open, close it if (memoryMappedFileMapHandle != (HANDLE) 0) { PrintDebugString("[INFO]: closing memoryMappedFileMapHandle; handle = %p", memoryMappedFileMapHandle); CloseHandle(memoryMappedFileMapHandle); memoryMappedFileMapHandle = (HANDLE) 0; } } /** * Sets up the memory-mapped file to do IPC messaging * 1 files is created: to handle requests for information * initiated from Windows AT. The package is placed into * the memory-mapped file (char *memoryMappedView), * and then a special SendMessage() is sent. When the * JavaDLL returns from SendMessage() processing, the * data will be in memoryMappedView. The SendMessage() * return value tells us if all is right with the world. * * The set-up proces involves creating the memory-mapped * file, and writing a special string to it so that the * WindowsDLL so it knows about it as well. */ LRESULT AccessBridgeATInstance::initiateIPC() { DWORD errorCode; PrintDebugString("[INFO]: In AccessBridgeATInstance::initiateIPC()"); // open Windows-initiated IPC filemap & map it to a ptr memoryMappedFileMapHandle = OpenFileMapping(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, memoryMappedFileName); if (memoryMappedFileMapHandle == NULL) { errorCode = GetLastError(); PrintDebugString("[ERROR]: Failed to CreateFileMapping for %s, error: %X", memoryMappedFileName, errorCode); return errorCode; } else { PrintDebugString("[INFO]: CreateFileMapping worked - filename: %s", memoryMappedFileName); } memoryMappedView = (char *) MapViewOfFile(memoryMappedFileMapHandle, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0); if (memoryMappedView == NULL) { errorCode = GetLastError(); PrintDebugString("[ERROR]: Failed to MapViewOfFile for %s, error: %X", memoryMappedFileName, errorCode); return errorCode; } else { PrintDebugString("[INFO]: MapViewOfFile worked - view: %p", memoryMappedView); } // look for the JavaDLL's answer to see if it could read the file if (strcmp(memoryMappedView, AB_MEMORY_MAPPED_FILE_OK_QUERY) != 0) { PrintDebugString("[ERROR]: JavaVM failed to write to memory mapped file %s", memoryMappedFileName); return -1; } else { PrintDebugString("[INFO]: JavaVM successfully wrote to file!"); } // write some data to the memory mapped file for WindowsDLL to verify strcpy(memoryMappedView, AB_MEMORY_MAPPED_FILE_OK_ANSWER); return 0; } typedef struct EVENT_STRUCT { char *buffer; int bufsize; ABHWND64 winAccessBridgeWindow; ABHWND64 ourAccessBridgeWindow; }EVENT_STRUCT; #include <process.h> #define THREAD_PROC unsigned int __stdcall typedef unsigned int (__stdcall *THREAD_ROUTINE)(LPVOID lpThreadParameter); static HANDLE BeginThread(THREAD_ROUTINE thread_func,DWORD *id,DWORD param) { HANDLE ret; ret = (HANDLE) _beginthreadex(NULL,0,thread_func,(void *)param,0,(unsigned int *)id); if(ret == INVALID_HANDLE_VALUE) ret = NULL; return(ret); } DWORD JavaBridgeThreadId = 0; static THREAD_PROC JavaBridgeThread(LPVOID param1) { MSG msg; DWORD rc = 0; while (GetMessage(&msg, // message structure NULL, // handle of window receiving the message 0, // lowest message to examine 0)) // highest message to examine { if(msg.message == WM_USER) { EVENT_STRUCT *event_struct = (EVENT_STRUCT *)msg.wParam; COPYDATASTRUCT toCopy; toCopy.dwData = 0; // 32-bits we could use for something... toCopy.cbData = event_struct->bufsize; toCopy.lpData = event_struct->buffer; LRESULT ret = SendMessage((HWND)ABLongToHandle(event_struct->winAccessBridgeWindow), WM_COPYDATA, (WPARAM)event_struct->ourAccessBridgeWindow, (LPARAM) &toCopy); delete event_struct->buffer; delete event_struct; } if(msg.message == (WM_USER+1)) PostQuitMessage(0); } JavaBridgeThreadId = 0; return(0); } /* * Handles one event */ static void do_event(char *buffer, int bufsize,HWND ourAccessBridgeWindow,HWND winAccessBridgeWindow) { EVENT_STRUCT *event_struct = new EVENT_STRUCT; event_struct->bufsize = bufsize; event_struct->buffer = new char[bufsize]; memcpy(event_struct->buffer,buffer,bufsize); event_struct->ourAccessBridgeWindow = ABHandleToLong(ourAccessBridgeWindow); event_struct->winAccessBridgeWindow = ABHandleToLong(winAccessBridgeWindow); if(!JavaBridgeThreadId) { HANDLE JavaBridgeThreadHandle = BeginThread(JavaBridgeThread,&JavaBridgeThreadId,(DWORD)event_struct); CloseHandle(JavaBridgeThreadHandle); } PostThreadMessage(JavaBridgeThreadId,WM_USER,(WPARAM)event_struct,0); } /** * sendJavaEventPackage - uses SendMessage(WM_COPYDATA) to do * IPC messaging with the Java AccessBridge DLL * to propogate events to those ATs that want 'em * */ LRESULT AccessBridgeATInstance::sendJavaEventPackage(char *buffer, int bufsize, long eventID) { PrintDebugString("[INFO]: AccessBridgeATInstance::sendJavaEventPackage() eventID = %X", eventID); PrintDebugString("[INFO]: AccessBridgeATInstance::sendJavaEventPackage() (using PostMessage) eventID = %X", eventID); if (eventID & javaEventMask) { do_event(buffer,bufsize,ourAccessBridgeWindow,winAccessBridgeWindow); return(0); } else { return -1; } } /** * uses SendMessage(WM_COPYDATA) to do * IPC messaging with the Java AccessBridge DLL * to propogate events to those ATs that want 'em * */ LRESULT AccessBridgeATInstance::sendAccessibilityEventPackage(char *buffer, int bufsize, long eventID) { PrintDebugString("[INFO]: AccessBridgeATInstance::sendAccessibilityEventPackage() eventID = %X", eventID); if (eventID & accessibilityEventMask) { do_event(buffer,bufsize,ourAccessBridgeWindow,winAccessBridgeWindow); return(0); } else { return -1; } } /** * findABATInstanceFromATHWND - walk through linked list from * where we are. Return the * AccessBridgeATInstance * of the ABATInstance that * matches the passed in vmID; * no match: return 0 */ AccessBridgeATInstance * AccessBridgeATInstance::findABATInstanceFromATHWND(HWND window) { // no need to recurse really if (winAccessBridgeWindow == window) { return this; } else { AccessBridgeATInstance *current = nextATInstance; while (current != (AccessBridgeATInstance *) 0) { if (current->winAccessBridgeWindow == window) { return current; } current = current->nextATInstance; } } return (AccessBridgeATInstance *) 0; }
{ "pile_set_name": "Github" }
T0 segment 0 4 Nord T1 segment 5 11 Stream T2 segment 12 14 AG T3 segment 15 17 is T4 segment 18 19 a T5 segment 20 30 consortium T6 segment 31 34 for T7 segment 35 47 construction T8 segment 48 51 and T9 segment 52 61 operation T10 segment 62 64 of T11 segment 65 68 the T12 segment 69 73 Nord T13 segment 74 80 Stream T14 segment 81 90 submarine T15 segment 91 99 pipeline T16 segment 100 107 between T17 segment 108 114 Vyborg T18 segment 115 117 in T19 segment 118 124 Russia T20 segment 125 128 and T21 segment 129 139 Greifswald T22 segment 140 142 in T23 segment 143 150 Germany T24 segment 150 151 , T25 segment 152 153 a T26 segment 154 161 project T27 segment 162 171 initially T28 segment 172 180 promoted T29 segment 181 183 by T30 segment 184 194 Chancellor T31 segment 195 202 Gerhard T32 segment 203 211 Schröder T33 segment 212 215 and T34 segment 216 225 President T35 segment 226 234 Vladimir T36 segment 235 240 Putin T37 segment 241 242 . R0 s_p Arg1:T2 Arg2:T3 R1 compound Arg1:T2 Arg2:T0 R2 compound Arg1:T2 Arg2:T1 R3 p_o Arg1:T3 Arg2:T5 R4 is-specialized-by Arg1:T5 Arg2:T22 R5 is-specialized-by Arg1:T5 Arg2:T6 R6 c_co Arg1:T6 Arg2:T7 R7 is-specialized-by Arg1:T7 Arg2:T16 R8 is-specialized-by Arg1:T7 Arg2:T10 R9 c_co Arg1:T10 Arg2:T15 R10 compound Arg1:T15 Arg2:T12 R11 compound Arg1:T15 Arg2:T13 R12 is-specialized-by Arg1:T15 Arg2:T14 R13 c_co Arg1:T16 Arg2:T17 R14 is-specialized-by Arg1:T17 Arg2:T18 R15 c_co Arg1:T18 Arg2:T19 R16 c_co Arg1:T22 Arg2:T23 R17 is-specialized-by Arg1:T28 Arg2:T27 R18 is-specialized-by Arg1:T28 Arg2:T29 R19 c_co Arg1:T29 Arg2:T32 R20 compound Arg1:T32 Arg2:T30 R21 compound Arg1:T32 Arg2:T31 R22 compound Arg1:T36 Arg2:T35 R23 compound Arg1:T36 Arg2:T34
{ "pile_set_name": "Github" }
module.exports = promzard promzard.PromZard = PromZard var fs = require('fs') var vm = require('vm') var util = require('util') var files = {} var crypto = require('crypto') var EventEmitter = require('events').EventEmitter var read = require('read') var Module = require('module').Module var path = require('path') function promzard (file, ctx, cb) { if (typeof ctx === 'function') cb = ctx, ctx = null; if (!ctx) ctx = {}; var pz = new PromZard(file, ctx) pz.on('error', cb) pz.on('data', function (data) { cb(null, data) }) } promzard.fromBuffer = function (buf, ctx, cb) { var filename = 0 do { filename = '\0' + Math.random(); } while (files[filename]) files[filename] = buf var ret = promzard(filename, ctx, cb) delete files[filename] return ret } function PromZard (file, ctx) { if (!(this instanceof PromZard)) return new PromZard(file, ctx) EventEmitter.call(this) this.file = file this.ctx = ctx this.unique = crypto.randomBytes(8).toString('hex') this.load() } PromZard.prototype = Object.create( EventEmitter.prototype, { constructor: { value: PromZard, readable: true, configurable: true, writable: true, enumerable: false } } ) PromZard.prototype.load = function () { if (files[this.file]) return this.loaded() fs.readFile(this.file, 'utf8', function (er, d) { if (er && this.backupFile) { this.file = this.backupFile delete this.backupFile return this.load() } if (er) return this.emit('error', this.error = er) files[this.file] = d this.loaded() }.bind(this)) } PromZard.prototype.loaded = function () { this.ctx.prompt = this.makePrompt() this.ctx.__filename = this.file this.ctx.__dirname = path.dirname(this.file) this.ctx.__basename = path.basename(this.file) var mod = this.ctx.module = this.makeModule() this.ctx.require = function (path) { return mod.require(path) } this.ctx.require.resolve = function(path) { return Module._resolveFilename(path, mod); } this.ctx.exports = mod.exports this.script = this.wrap(files[this.file]) var fn = vm.runInThisContext(this.script, this.file) var args = Object.keys(this.ctx).map(function (k) { return this.ctx[k] }.bind(this)) try { var res = fn.apply(this.ctx, args) } catch (er) { this.emit('error', er) } if (res && typeof res === 'object' && exports === mod.exports && Object.keys(exports).length === 1) { this.result = res } else { this.result = mod.exports } this.walk() } PromZard.prototype.makeModule = function () { var mod = new Module(this.file, module) mod.loaded = true mod.filename = this.file mod.id = this.file mod.paths = Module._nodeModulePaths(path.dirname(this.file)) return mod } PromZard.prototype.wrap = function (body) { var s = '(function( %s ) { %s\n })' var args = Object.keys(this.ctx).join(', ') return util.format(s, args, body) } PromZard.prototype.makePrompt = function () { this.prompts = [] return prompt.bind(this) function prompt () { var p, d, t for (var i = 0; i < arguments.length; i++) { var a = arguments[i] if (typeof a === 'string' && p) d = a else if (typeof a === 'string') p = a else if (typeof a === 'function') t = a else if (a && typeof a === 'object') { p = a.prompt || p d = a.default || d t = a.transform || t } } try { return this.unique + '-' + this.prompts.length } finally { this.prompts.push([p, d, t]) } } } PromZard.prototype.walk = function (o, cb) { o = o || this.result cb = cb || function (er, res) { if (er) return this.emit('error', this.error = er) this.result = res return this.emit('data', res) } cb = cb.bind(this) var keys = Object.keys(o) var i = 0 var len = keys.length L.call(this) function L () { if (this.error) return while (i < len) { var k = keys[i] var v = o[k] i++ if (v && typeof v === 'object') { return this.walk(v, function (er, res) { if (er) return cb(er) o[k] = res L.call(this) }.bind(this)) } else if (v && typeof v === 'string' && v.indexOf(this.unique) === 0) { var n = +v.substr(this.unique.length + 1) var prompt = this.prompts[n] if (isNaN(n) || !prompt) continue // default to the key if (undefined === prompt[0]) prompt[0] = k // default to the ctx value, if there is one if (undefined === prompt[1]) prompt[1] = this.ctx[k] return this.prompt(prompt, function (er, res) { if (er) { if (!er.notValid) { return this.emit('error', this.error = er); } console.log(er.message) i -- return L.call(this) } o[k] = res L.call(this) }.bind(this)) } else if (typeof v === 'function') { try { return v.call(this.ctx, function (er, res) { if (er) return this.emit('error', this.error = er) o[k] = res // back up so that we process this one again. // this is because it might return a prompt() call in the cb. i -- L.call(this) }.bind(this)) } catch (er) { this.emit('error', er) } } } // made it to the end of the loop, maybe if (i >= len) return cb(null, o) } } PromZard.prototype.prompt = function (pdt, cb) { var prompt = pdt[0] var def = pdt[1] var tx = pdt[2] if (tx) { cb = function (cb) { return function (er, data) { try { var res = tx(data) if (!er && res instanceof Error && !!res.notValid) { return cb(res, null) } return cb(er, res) } catch (er) { this.emit('error', er) } }}(cb).bind(this) } read({ prompt: prompt + ':' , default: def }, cb) }
{ "pile_set_name": "Github" }
from . import DIGSBY_STATS_COUNTER_NS from pyxmpp.objects import StanzaPayloadObject from pyxmpp.utils import from_utf8, to_utf8 from pyxmpp.xmlextra import common_doc, get_node_ns_uri import libxml2 SYNC_PROTOS = frozenset(['myspace', 'twitter', 'linkedin', 'facebook', 'gmail', 'ymail', 'hotmail', 'aolmail', 'pop', 'imap']) WHITELISTED_TYPES = set([ 'link_post', 'im_sent', 'im_received', 'emoticon_box_viewed', 'emoticon_chosen', 'video_chat_requested', 'sms_sent', 'log_viewed', 'prefs.prefs_opened', 'imwin.imwin_created', 'imwin.imwin_engage', 'contact_added', 'ui.dialogs.add_contact.created', 'ui.select_status', 'infobox.shown', 'feed_ad.citygrid.click_cents', 'research.run_time', ]) class Action(StanzaPayloadObject): xml_element_name = 'action' xml_element_namespace = DIGSBY_STATS_COUNTER_NS def __init__(self, xmlnode_or_type=None, initial=None, value=None, result=None): # from an incoming XML node if isinstance(xmlnode_or_type, libxml2.xmlNode): return self.__from_xml(xmlnode_or_type) else: self.type = xmlnode_or_type self.initial = initial self.value = value self.result = result if self.type not in WHITELISTED_TYPES: raise ValueError("valid type required! (got %r)" % self.type) def __repr__(self): return '<Digsby.Action %s %r:%r:%r>' % (self.type, self.initial, self.value, self.result) def __from_xml(self, node): '''A libxml2 node to a digsby.action''' if node.type!="element": raise ValueError,"XML node is not an action element (not en element)" ns = get_node_ns_uri(node) if ns and ns != DIGSBY_STATS_COUNTER_NS or node.name != "action": raise ValueError,"XML node is not an action element" type = node.prop("type") self.type = from_utf8(type) if type is not None else None initial = node.prop("initial") self.initial = int(from_utf8(initial)) if initial is not None else None value = node.prop("value") self.value = int(from_utf8(value)) if value is not None else None result = node.prop("result") self.result = int(from_utf8(result)) if result is not None else None def complete_xml_element(self, xmlnode, _unused): 'to xml' setProp(xmlnode, 'type', self.type) setProp(xmlnode, 'initial', self.initial) setProp(xmlnode, 'value', self.value) setProp(xmlnode, 'result', self.result) def __str__(self): n=self.as_xml(doc=common_doc) r=n.serialize() n.unlinkNode() n.freeNode() return r def setProp(xmlnode, attr, value): if value is not None: xmlnode.setProp(attr, to_utf8(value))
{ "pile_set_name": "Github" }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #ifndef MXNET_STORAGE_CPU_SHARED_STORAGE_MANAGER_H_ #define MXNET_STORAGE_CPU_SHARED_STORAGE_MANAGER_H_ #if MXNET_USE_CUDA #include <cuda_runtime.h> #endif // MXNET_USE_CUDA #include <mxnet/base.h> #ifndef _WIN32 #include <sys/mman.h> #include <sys/fcntl.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #endif // _WIN32 #include <unordered_map> #include <vector> #include <atomic> #include <iostream> #include <mutex> #include <new> #include <string> #include <limits> #include "./storage_manager.h" #include "../common/cuda_utils.h" namespace mxnet { namespace storage { /*! * \brief Storage manager for cpu shared memory */ class CPUSharedStorageManager final : public StorageManager { public: /*! * \brief Default constructor. */ CPUSharedStorageManager() : rand_gen_(std::random_device()()) {} /*! * \brief Default destructor. */ ~CPUSharedStorageManager() { for (const auto& kv : pool_) { FreeImpl(kv.second); } } void Alloc(Storage::Handle* handle) override; void Free(Storage::Handle handle) override { pool_.erase(handle.dptr); FreeImpl(handle); } void DirectFree(Storage::Handle handle) override { Free(handle); } void IncrementRefCount(const Storage::Handle& handle) { std::atomic<int>* counter = reinterpret_cast<std::atomic<int>*>( static_cast<char*>(handle.dptr) - alignment_); ++(*counter); } int DecrementRefCount(const Storage::Handle& handle) { std::atomic<int>* counter = reinterpret_cast<std::atomic<int>*>( static_cast<char*>(handle.dptr) - alignment_); return --(*counter); } private: static constexpr size_t alignment_ = 16; std::mutex mutex_; std::mt19937 rand_gen_; std::unordered_map<void*, Storage::Handle> pool_; void FreeImpl(const Storage::Handle& handle); std::string SharedHandleToString(int shared_pid, int shared_id) { std::stringstream name; name << "/mx_" << std::hex << shared_pid << "_" << std::hex << shared_id; return name.str(); } DISALLOW_COPY_AND_ASSIGN(CPUSharedStorageManager); }; // class CPUSharedStorageManager void CPUSharedStorageManager::Alloc(Storage::Handle* handle) { std::lock_guard<std::mutex> lock(mutex_); std::uniform_int_distribution<> dis(0, std::numeric_limits<int>::max()); int fid = -1; bool is_new = false; size_t size = handle->size + alignment_; void* ptr = nullptr; #ifdef _WIN32 LOG(FATAL) << "Shared memory is not supported on Windows yet."; #else if (handle->shared_id == -1 && handle->shared_pid == -1) { is_new = true; handle->shared_pid = getpid(); for (int i = 0; i < 10; ++i) { handle->shared_id = dis(rand_gen_); auto filename = SharedHandleToString(handle->shared_pid, handle->shared_id); fid = shm_open(filename.c_str(), O_EXCL|O_CREAT|O_RDWR, 0666); if (fid != -1) break; } } else { auto filename = SharedHandleToString(handle->shared_pid, handle->shared_id); fid = shm_open(filename.c_str(), O_RDWR, 0666); } if (fid == -1) { LOG(FATAL) << "Failed to open shared memory. shm_open failed with error " << strerror(errno); } if (is_new) CHECK_EQ(ftruncate(fid, size), 0); ptr = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, fid, 0); CHECK_NE(ptr, MAP_FAILED) << "Failed to map shared memory. mmap failed with error " << strerror(errno); #endif // _WIN32 if (is_new) { new (ptr) std::atomic<int>(1); } handle->dptr = static_cast<char*>(ptr) + alignment_; pool_[handle->dptr] = *handle; } void CPUSharedStorageManager::FreeImpl(const Storage::Handle& handle) { int count = DecrementRefCount(handle); CHECK_GE(count, 0); #ifdef _WIN32 LOG(FATAL) << "Shared memory is not supported on Windows yet."; #else CHECK_EQ(munmap(static_cast<char*>(handle.dptr) - alignment_, handle.size + alignment_), 0) << "Failed to unmap shared memory. munmap failed with error " << strerror(errno); if (count == 0) { auto filename = SharedHandleToString(handle.shared_pid, handle.shared_id); CHECK_EQ(shm_unlink(filename.c_str()), 0) << "Failed to unlink shared memory. shm_unlink failed with error " << strerror(errno); } #endif // _WIN32 } } // namespace storage } // namespace mxnet #endif // MXNET_STORAGE_CPU_SHARED_STORAGE_MANAGER_H_
{ "pile_set_name": "Github" }
package com.jaeger.ninegridimgdemo.activity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.View; import com.jaeger.ninegridimageview.NineGridImageView; import com.jaeger.ninegridimgdemo.R; import com.jaeger.ninegridimgdemo.adapter.PostAdapter; import com.jaeger.ninegridimgdemo.entity.Post; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by Jaeger on 16/2/24. * * Email: [email protected] * GitHub: https://github.com/laobie */ public class GridStyleActivity extends BaseActivity { private RecyclerView mRvPostLister; private PostAdapter mNineImageAdapter; private List<Post> mPostList; private String[] IMG_URL_LIST = { "http://ac-QYgvX1CC.clouddn.com/36f0523ee1888a57.jpg", "http://ac-QYgvX1CC.clouddn.com/07915a0154ac4a64.jpg", "http://ac-QYgvX1CC.clouddn.com/9ec4bc44bfaf07ed.jpg", "http://ac-QYgvX1CC.clouddn.com/fa85037f97e8191f.jpg", "http://ac-QYgvX1CC.clouddn.com/de13315600ba1cff.jpg", "http://ac-QYgvX1CC.clouddn.com/15c5c50e941ba6b0.jpg", "http://ac-QYgvX1CC.clouddn.com/10762c593798466a.jpg", "http://ac-QYgvX1CC.clouddn.com/eaf1c9d55c5f9afd.jpg", "http://ac-QYgvX1CC.clouddn.com/ad99de83e1e3f7d4.jpg", "http://ac-QYgvX1CC.clouddn.com/233a5f70512befcc.jpg", }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.getWindow().setBackgroundDrawableResource(android.R.color.transparent); setContentView(R.layout.activity_recycler); setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); mRvPostLister = (RecyclerView) findViewById(R.id.rv_post_list); final LinearLayoutManager manager = new LinearLayoutManager(this); mRvPostLister.setLayoutManager(manager); mPostList = new ArrayList<>(); for (int i = 0; i < 18; i++) { List<String> imgUrls = new ArrayList<>(); imgUrls.addAll(Arrays.asList(IMG_URL_LIST).subList(0, i % 9)); Post post = new Post("Am I handsome? Am I handsome? Am I handsome?", imgUrls); mPostList.add(post); } mNineImageAdapter = new PostAdapter(this, mPostList, NineGridImageView.STYLE_GRID); mRvPostLister.setAdapter(mNineImageAdapter); manager.scrollToPositionWithOffset(5, 0); mRvPostLister.post(new Runnable() { @Override public void run() { View view = manager.findViewByPosition(1); if (view != null) System.out.println(view.getMeasuredHeight()); } }); } }
{ "pile_set_name": "Github" }
#include <stdio.h> #define LOW_BOUND 0 #define HIGH_BOUND 3 #define h 0.125 double f(double x, double y); int main () { int a = (int)((HIGH_BOUND - LOW_BOUND) / h) + 1; double x[a], y[a]; int i; x[0] = 0.0; y[0] = 1.0; for (i = 0; i < a; i++){ x[i + 1] = x[i] + h; y[i + 1] = y[i] + h * f(x[i], y[i]); } printf("x[i]\ty[i]\n"); for (i = 0; i < a; i++) printf("%.4f\t%.4f\n", x[i], y[i]); return 0; } double f(double x, double y) { return(3 * (x + y)); }
{ "pile_set_name": "Github" }
{ "_comment": "DO NOT EDIT: FILE GENERATED AUTOMATICALLY BY PTERODACTYL PANEL - PTERODACTYL.IO", "meta": { "version": "PTDL_v1" }, "exported_at": "2017-11-03T22:20:03-05:00", "name": "Sponge (SpongeVanilla)", "author": "[email protected]", "description": "SpongeVanilla is the SpongeAPI implementation for Vanilla Minecraft.", "image": "quay.io\/pterodactyl\/core:java-glibc", "startup": "java -Xms128M -Xmx{{SERVER_MEMORY}}M -jar {{SERVER_JARFILE}}", "config": { "files": "{\r\n \"server.properties\": {\r\n \"parser\": \"properties\",\r\n \"find\": {\r\n \"server-ip\": \"0.0.0.0\",\r\n \"enable-query\": \"true\",\r\n \"server-port\": \"{{server.build.default.port}}\",\r\n \"query.port\": \"{{server.build.default.port}}\"\r\n }\r\n }\r\n}", "startup": "{\r\n \"done\": \")! For help, type \",\r\n \"userInteraction\": [\r\n \"Go to eula.txt for more info.\"\r\n ]\r\n}", "logs": "{\r\n \"custom\": false,\r\n \"location\": \"logs\/latest.log\"\r\n}", "stop": "stop" }, "scripts": { "installation": { "script": "#!\/bin\/ash\n# Sponge Installation Script\n#\n# Server Files: \/mnt\/server\n\napk update\napk add curl\n\ncd \/mnt\/server\n\ncurl -sSL \"https:\/\/repo.spongepowered.org\/maven\/org\/spongepowered\/spongevanilla\/${SPONGE_VERSION}\/spongevanilla-${SPONGE_VERSION}.jar\" -o ${SERVER_JARFILE}", "container": "alpine:3.9", "entrypoint": "ash" } }, "variables": [ { "name": "Sponge Version", "description": "The version of SpongeVanilla to download and use.", "env_variable": "SPONGE_VERSION", "default_value": "1.11.2-6.1.0-BETA-21", "user_viewable": 1, "user_editable": 0, "rules": "required|regex:\/^([a-zA-Z0-9.\\-_]+)$\/" }, { "name": "Server Jar File", "description": "The name of the Jarfile to use when running SpongeVanilla.", "env_variable": "SERVER_JARFILE", "default_value": "server.jar", "user_viewable": 1, "user_editable": 1, "rules": "required|regex:\/^([\\w\\d._-]+)(\\.jar)$\/" } ] }
{ "pile_set_name": "Github" }
[config] command = record args = --no-bpf-event -c 123 kill >/dev/null 2>&1 ret = 1 [event:base-record] sample_period=123 sample_type=7 freq=0
{ "pile_set_name": "Github" }
/* Copyright (C) 2013 Google 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. */ PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xA0]+/,null,"\t\n\r \u00a0"]],[["com",/^#!(?:.*)/],["kwd",/^\b(?:import|library|part of|part|as|show|hide)\b/i],["com",/^\/\/(?:.*)/],["com",/^\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\//],["kwd",/^\b(?:class|interface)\b/i],["kwd",/^\b(?:assert|async|await|break|case|catch|continue|default|do|else|finally|for|if|in|is|new|return|super|switch|sync|this|throw|try|while)\b/i],["kwd",/^\b(?:abstract|const|extends|factory|final|get|implements|native|operator|set|static|typedef|var)\b/i], ["typ",/^\b(?:bool|double|Dynamic|int|num|Object|String|void)\b/i],["kwd",/^\b(?:false|null|true)\b/i],["str",/^r?[\']{3}[\s|\S]*?[^\\][\']{3}/],["str",/^r?[\"]{3}[\s|\S]*?[^\\][\"]{3}/],["str",/^r?\'(\'|(?:[^\n\r\f])*?[^\\]\')/],["str",/^r?\"(\"|(?:[^\n\r\f])*?[^\\]\")/],["typ",/^[A-Z]\w*/],["pln",/^[a-z_$][a-z0-9_]*/i],["pun",/^[~!%^&*+=|?:<>/-]/],["lit",/^\b0x[0-9a-f]+/i],["lit",/^\b\d+(?:\.\d*)?(?:e[+-]?\d+)?/i],["lit", /^\b\.\d+(?:e[+-]?\d+)?/i],["pun",/^[(){}\[\],.;]/]]),["dart"]);
{ "pile_set_name": "Github" }
from re import compile as re_compile from functools import lru_cache from contextlib import contextmanager from typing import Iterable, Hashable, TypeVar, Dict, Tuple __all__ = ("clean", "filter_items", "to_id") _URI_RE = re_compile(r"^.*:([a-zA-Z0-9]+)$") _OPEN_RE = re_compile(r"http[s]?:\/\/open\.spotify\.com\/(.*)\/(.*)") @contextmanager def clean(mapping: dict, *keys: Iterable[Hashable]): """A helper context manager that defers mutating a mapping.""" yield for key in keys: mapping.pop(key) K = TypeVar("K") # pylint: disable=invalid-name V = TypeVar("V") # pylint: disable=invalid-name @lru_cache(maxsize=1024) def _cached_filter_items(data: Tuple[Tuple[K, V], ...]) -> Dict[K, V]: data_ = {} for key, value in data: if value is not None: data_[key] = value return data_ def filter_items(data: Dict[K, V]) -> Dict[K, V]: """Filter the items of a dict where the value is not None.""" return _cached_filter_items((*data.items(),)) def to_id(value: str) -> str: """Get a spotify ID from a URI or open.spotify URL. Paramters --------- value : :class:`str` The value to operate on. Returns ------- id : :class:`str` The Spotify ID from the value. """ value = value.strip() match = _URI_RE.match(value) if match is None: match = _OPEN_RE.match(value) if match is None: return value return match.group(2) return match.group(1)
{ "pile_set_name": "Github" }
-- 26.02.2016 15:32 -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_EntityType (AD_Client_ID,AD_EntityType_ID,AD_Org_ID,Created,CreatedBy,EntityType,IsActive,IsDisplayed,ModelPackage,Name,Processing,Updated,UpdatedBy) VALUES (0,5378,0,TO_TIMESTAMP('2016-02-26 15:32:49','YYYY-MM-DD HH24:MI:SS'),100,'de.metas.procurement','Y','Y','de.metas.procurement.base.model','de.metas.procurement','N',TO_TIMESTAMP('2016-02-26 15:32:49','YYYY-MM-DD HH24:MI:SS'),100) ;
{ "pile_set_name": "Github" }
/******************************************************************************* * HellFirePvP / Astral Sorcery 2020 * * All rights reserved. * The source code is available on github: https://github.com/HellFirePvP/AstralSorcery * For further details, see the License file there. ******************************************************************************/ package hellfirepvp.astralsorcery.datagen.data.loot; import com.google.common.collect.Lists; import com.mojang.datafixers.util.Pair; import net.minecraft.data.DataGenerator; import net.minecraft.data.LootTableProvider; import net.minecraft.util.ResourceLocation; import net.minecraft.world.storage.loot.*; import java.util.List; import java.util.Map; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Supplier; /** * This class is part of the Astral Sorcery Mod * The complete source code for this mod can be found on github. * Class: AstralLootTableProvider * Created by HellFirePvP * Date: 06.03.2020 / 21:42 */ public final class AstralLootTableProvider extends LootTableProvider { public AstralLootTableProvider(DataGenerator dataGeneratorIn) { super(dataGeneratorIn); } @Override protected List<Pair<Supplier<Consumer<BiConsumer<ResourceLocation, LootTable.Builder>>>, LootParameterSet>> getTables() { return Lists.newArrayList( Pair.of(BlockLootTableProvider::new, LootParameterSets.BLOCK), Pair.of(EntityLootTableProvider::new, LootParameterSets.ENTITY), Pair.of(ChestLootTableProvider::new, LootParameterSets.CHEST) ); } @Override protected void validate(Map<ResourceLocation, LootTable> map, ValidationTracker validationtracker) { map.forEach((key, lootTable) -> LootTableManager.func_227508_a_(validationtracker, key, lootTable)); } }
{ "pile_set_name": "Github" }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\HttpKernel\CacheWarmer; /** * Interface for classes able to warm up the cache. * * @author Fabien Potencier <[email protected]> */ interface CacheWarmerInterface extends WarmableInterface { /** * Checks whether this warmer is optional or not. * * Optional warmers can be ignored on certain conditions. * * A warmer should return true if the cache can be * generated incrementally and on-demand. * * @return Boolean true if the warmer is optional, false otherwise */ public function isOptional(); }
{ "pile_set_name": "Github" }
/// Generated by expo-google-fonts/generator /// Do not edit by hand unless you know what you are doing /// export { useFonts } from './useFonts'; export const __metdata__: Any; export const CormorantInfant_300Light: number; export const CormorantInfant_300Light_Italic: number; export const CormorantInfant_400Regular: number; export const CormorantInfant_400Regular_Italic: number; export const CormorantInfant_500Medium: number; export const CormorantInfant_500Medium_Italic: number; export const CormorantInfant_600SemiBold: number; export const CormorantInfant_600SemiBold_Italic: number; export const CormorantInfant_700Bold: number; export const CormorantInfant_700Bold_Italic: number;
{ "pile_set_name": "Github" }
<?php /** * This class has two purposes: * + Handle the custom metadata post, i.e. "Book Information". There should only be one metadata post per book. * + Perform upgrades on individual books as Pressbooks evolves. * * @author Pressbooks <[email protected]> * @license GPLv3 (or any later version) */ namespace Pressbooks; class Metadata implements \JsonSerializable { /** * The value for option: pressbooks_metadata_version * * @see upgrade() * @var int */ const VERSION = 13; /** * Deprecated meta keys represented by checkboxes in the GUI. * We need to upgrade these for compatibility with custom_metdata(). * * @var array */ public $upgradeCheckboxes = [ 'chapter-export' => 1, 'front-matter-export' => 1, 'back-matter-export' => 1, 'show-title' => 1, ]; /** */ public function __construct() { } /** * Returns the latest "metadata" post ID. There should be only one per book. * * @return int */ public function getMetaPostId() { $args = [ 'post_type' => 'metadata', 'posts_per_page' => 1, 'post_status' => 'publish', 'orderby' => 'modified', 'no_found_rows' => true, 'cache_results' => true, 'fields' => 'ids', ]; $q = new \WP_Query(); $results = $q->query( $args ); if ( empty( $results ) ) { return 0; } return $results[0]; } /** * Returns the latest "metadata" post. There should be only one per book. * * @return \WP_Post|bool */ public function getMetaPost() { $args = [ 'post_type' => 'metadata', 'posts_per_page' => 1, 'post_status' => 'publish', 'orderby' => 'modified', 'no_found_rows' => true, 'cache_results' => true, ]; $q = new \WP_Query(); $results = $q->query( $args ); if ( empty( $results ) ) { return false; } return $results[0]; } /** * Return metadata attached to the latest "metadata" post. * * @return array */ public function getMetaPostMetadata() { $meta_post = $this->getMetaPost(); if ( ! $meta_post ) { return []; } return get_post_meta( $meta_post->ID ); } /** * Return a database ID for a given meta key. * * @param int $post_id * @param string $meta_key * * @return int|bool */ public function getMidByKey( $post_id, $meta_key ) { /** @var \wpdb $wpdb */ global $wpdb; $mid = $wpdb->get_var( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s LIMIT 1 ", $post_id, $meta_key ) ); if ( ! empty( $mid ) ) { return absint( $mid ); } return false; } /** * Returns a JSON object of the book information which can be posted to an API. * * @since 4.0.0 * * @return array */ public function jsonSerialize() { $request = new \WP_REST_Request( 'GET', '/pressbooks/v2/metadata' ); $meta = new \Pressbooks\Api\Endpoints\Controller\Metadata(); $metadata = $meta ->get_item( $request ) ->get_data(); return apply_filters( 'pb_json_metadata', $metadata ); } // ---------------------------------------------------------------------------------------------------------------- // Upgrades // ---------------------------------------------------------------------------------------------------------------- /** * Upgrade metadata. * * @param int $version */ public function upgrade( $version ) { if ( $version < 1 ) { // Upgrade from version 0 (closed source service) to version 1 (initial open source offering) $this->upgradeEcommerce(); $this->upgradeBookInformation(); $this->upgradeBook(); } if ( $version < 3 ) { \Pressbooks\CustomCss::upgradeCustomCss(); } if ( $version < 4 ) { $this->fixDoubleSlashBug(); } if ( $version < 5 ) { $this->changeDefaultBookCover(); } if ( $version < 6 || $version < 7 ) { $this->makeThumbnailsForBookCover(); } if ( $version < 8 ) { $this->resetLandingPage(); } if ( $version < 10 ) { $taxonomy = Taxonomy::init(); $taxonomy->insertTerms(); flush_rewrite_rules( false ); } if ( $version < 11 ) { $this->migratePartContentToEditor(); } if ( $version < 12 ) { Container::get( 'Styles' )->initPosts(); } if ( $version < 13 ) { $this->upgradeToPressbooksFive(); } } /** * Upgrade Ecommerce metadata - from version 0 (closed source) to version 1 (first open source version, february 2013) * * @deprecated */ public function upgradeEcommerce() { $options = get_option( 'ecomm-url' ); $compare = $this->getDeprecatedComparisonTable( 'ecommerce' ); $new_options = []; if ( $options ) { foreach ( $options as $meta_key => $meta_value ) { $new_meta_key = ( isset( $compare[ $meta_key ] ) ) ? $compare[ $meta_key ] : false; if ( $new_meta_key ) { $new_options[ $new_meta_key ] = $meta_value; } } } update_option( 'pressbooks_ecommerce_links', $new_options ); delete_option( 'ecomm-url' ); } /** * Upgrade book information - from version 0 (closed source) to version 1 (first open source version, february 2013) * * @deprecated */ public function upgradeBookInformation() { // Metadata $meta_post = $this->getMetaPost(); if ( ! $meta_post ) { return; // Do nothing } $metadata = $this->getMetaPostMetadata(); $compare = $this->getDeprecatedComparisonTable( 'metadata' ); foreach ( $metadata as $meta_key => $meta_value ) { $new_meta_key = ( isset( $compare[ $meta_key ] ) ) ? $compare[ $meta_key ] : false; if ( $new_meta_key ) { $meta_id = $this->getMidByKey( $meta_post->ID, $meta_key ); if ( $meta_id ) { if ( isset( $this->upgradeCheckboxes[ $meta_key ] ) ) { $meta_value = 'on'; } elseif ( is_array( $meta_value ) ) { $meta_value = array_values( $meta_value ); $meta_value = array_pop( $meta_value ); } // Overrides if ( 'pb_language' === $new_meta_key ) { $meta_value = substr( strtolower( $meta_value ), 0, 2 ); } if ( 'pb_publication_date' === $new_meta_key ) { $meta_value = strtotime( $meta_value ); } // Update the original $meta_key to the $new_meta_key update_metadata_by_mid( 'post', $meta_id, $meta_value, $new_meta_key ); } } } // Force title change update_metadata( 'post', $meta_post->ID, 'pb_title', get_bloginfo( 'name' ) ); } /** * Upgrade book metadata - from version 0 (closed source) to version 1 (first open source version, february 2013) * * @deprecated */ public function upgradeBook() { $book_structure = Book::getBookStructure(); foreach ( $book_structure['__order'] as $post_id => $_ ) { $meta = get_post_meta( $post_id ); $compare = $this->getDeprecatedComparisonTable( get_post_type( $post_id ) ); foreach ( $meta as $meta_key => $meta_value ) { $new_meta_key = ( isset( $compare[ $meta_key ] ) ) ? $compare[ $meta_key ] : false; if ( $new_meta_key ) { $meta_id = $this->getMidByKey( $post_id, $meta_key ); if ( $meta_id ) { if ( isset( $this->upgradeCheckboxes[ $meta_key ] ) ) { $meta_value = 'on'; } elseif ( is_array( $meta_value ) ) { $meta_value = array_values( $meta_value ); $meta_value = array_pop( $meta_value ); } // Update the original $meta_key to the $new_meta_key update_metadata_by_mid( 'post', $meta_id, $meta_value, $new_meta_key ); } } } } } /** * Upgrade from version 0 (closed source) to version 1 (first open source version, february 2013) * * @deprecated * * @param string $table * @param bool $new_as_keys * * @return array */ public function getDeprecatedComparisonTable( $table, $new_as_keys = false ) { if ( 'chapter' === $table ) { // Chapter $metadata = [ 'short-title' => 'pb_short_title', 'subtitle' => 'pb_subtitle', 'chap_author' => 'pb_section_author', 'chapter-export' => 'pb_export', 'show-title' => 'pb_show_title', ]; } elseif ( 'front-matter' === $table ) { // Front Matter $metadata = [ 'short-title' => 'pb_short_title', 'subtitle' => 'pb_subtitle', 'chap_author' => 'pb_section_author', 'front-matter-export' => 'pb_export', 'show-title' => 'pb_show_title', ]; } elseif ( 'back-matter' === $table ) { // Back Matter $metadata = [ 'back-matter-export' => 'pb_export', 'show-title' => 'pb_show_title', ]; } elseif ( 'ecommerce' === $table ) { // Ecommerce $metadata = [ 'url1' => 'amazon', 'url2' => 'oreilly', 'url3' => 'barnesandnoble', 'url4' => 'kobo', 'url5' => 'ibooks', 'url6' => 'otherservice', ]; } elseif ( 'metadata' === $table ) { // Book Information $metadata = [ 'Title' => 'pb_title', 'Short Title' => 'pb_short_title', 'Subtitle' => 'pb_subtitle', 'Author' => 'pb_author', 'Author, file as' => 'pb_author_file_as', 'Publisher' => 'pb_publisher', 'Publication Date' => 'pb_publication_date', 'Publisher City' => 'pb_publisher_city', 'Cover Image' => 'pb_cover_image', 'Copyright Year' => 'pb_copyright_year', 'Copyright Holder' => 'pb_copyright_holder', 'Copyright Extra Info' => 'pb_custom_copyright', 'About (140 characters)' => 'pb_about_140', 'About (50 words)' => 'pb_about_50', 'About (Unlimited)' => 'pb_about_unlimited', 'Series Title' => 'pb_series_title', 'Series Number' => 'pb_series_number', 'Editor' => 'pb_editor', 'Translator' => 'pb_translator', 'Keywords/Tags' => 'pb_keywords_tags', 'Hashtag' => 'pb_hashtag', 'Print ISBN' => 'pb_print_isbn', 'Ebook ISBN' => 'pb_ebook_isbn', 'Language' => 'pb_language', 'List Price (Print)' => 'pb_list_price_print', 'List Price (PDF)' => 'pb_list_price_pdf', 'List Price (ePub)' => 'pb_list_price_epub', 'List Price (Web)' => 'pb_list_price_web', 'Bisac Subject 1' => 'pb_bisac_subject', 'Bisac Regional Theme' => 'pb_bisac_regional_theme', 'catalogue_order' => 'pb_catalogue_order', ]; } else { $metadata = []; } if ( $new_as_keys ) { $metadata = array_flip( $metadata ); } return $metadata; } /** * Fix a double slash bug by reactivating theme with new settings. * * @see \Pressbooks\Pressbooks::registerThemeDirectories */ public function fixDoubleSlashBug() { $theme = wp_get_theme(); if ( ! $theme->exists() || ! $theme->is_allowed() ) { return; // Do nothing } else { switch_theme( $theme->get_stylesheet() ); } } /** * Change default book cover from PNG to JPG */ public function changeDefaultBookCover() { $post = $this->getMetaPost(); if ( $post ) { $pb_cover_image = get_post_meta( $post->ID, 'pb_cover_image', true ); if ( preg_match( '~assets/images/default-book-cover\.png$~', $pb_cover_image ) ) { update_post_meta( $post->ID, 'pb_cover_image', \Pressbooks\Image\default_cover_url() ); Book::deleteBookObjectCache(); } } } /** * Generate thumbnails for a user uploaded cover */ public function makeThumbnailsForBookCover() { $post = $this->getMetaPost(); if ( $post ) { $pb_cover_image = get_post_meta( $post->ID, 'pb_cover_image', true ); if ( $pb_cover_image && ! \Pressbooks\Image\is_default_cover( $pb_cover_image ) ) { $path = \Pressbooks\Utility\get_media_path( $pb_cover_image ); $type = wp_check_filetype( $path ); $type = $type['type']; // Insert new image, create thumbnails $args = [ 'post_mime_type' => $type, 'post_title' => __( 'Cover Image', 'pressbooks' ), 'post_content' => '', 'post_status' => 'inherit', ]; include_once( ABSPATH . 'wp-admin/includes/image.php' ); $id = wp_insert_attachment( $args, $path, $post->ID ); wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $path ) ); Book::deleteBookObjectCache(); } } } /** * Fix broken landing page */ public function resetLandingPage() { /** @var $wpdb \wpdb */ global $wpdb; update_option( 'show_on_front', 'page' ); $id = $wpdb->get_var( "SELECT ID FROM {$wpdb->posts} WHERE post_name = 'cover' AND post_type = 'page' AND post_status = 'publish' " ); if ( $id ) { update_option( 'page_on_front', $id ); } $id = $wpdb->get_var( "SELECT ID FROM {$wpdb->posts} WHERE post_name = 'table-of-contents' AND post_type = 'page' AND post_status = 'publish' " ); if ( $id ) { update_option( 'page_for_posts', $id ); } } /** * Migrate part content to content editor */ public function migratePartContentToEditor() { /** @var $wpdb \wpdb */ global $wpdb; $parts = $wpdb->get_results( "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'part' AND post_status = 'publish' " ); foreach ( $parts as $part ) { $pb_part_content = trim( get_post_meta( $part->ID, 'pb_part_content', true ) ); if ( $pb_part_content ) { $success = wp_update_post( [ 'ID' => $part->ID, 'post_content' => $pb_part_content, 'comment_status' => 'closed', ] ); if ( $success === $part->ID ) { delete_post_meta( $part->ID, 'pb_part_content' ); } } } Book::deleteBookObjectCache(); } /** * @since 5.0.0 */ public function upgradeToPressbooksFive() { // Get all parts from the book global $wpdb; $r1 = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_status FROM {$wpdb->posts} WHERE post_type IN (%s, %s, %s, %s)", [ 'front-matter', 'part', 'chapter', 'back-matter' ] ), ARRAY_A ); // Update post statii $wpdb->query( 'START TRANSACTION' ); foreach ( $r1 as $val ) { // Get pb_export for single post in a book $r2 = $wpdb->get_row( $wpdb->prepare( "SELECT meta_value FROM {$wpdb->postmeta} WHERE meta_key = %s AND post_id = %d", 'pb_export', $val['ID'] ), ARRAY_A ); $status = $val['post_status']; $pb_export = ( isset( $r2['meta_value'] ) && $r2['meta_value'] === 'on' ); $new_status = $this->postStatiiConversion( $status, $pb_export ); if ( ! $new_status !== $status ) { $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->posts} SET post_status = %s WHERE ID = %d", $new_status, $val['ID'] ) ); } } $wpdb->query( 'COMMIT' ); wp_cache_flush(); // Update contributors $contributor = new Contributors(); foreach ( $r1 as $val ) { $contributor->getAll( $val['ID'], false ); // Triggers contributor upgrade } $contributor->getAll( $this->getMetaPostId(), false ); // Triggers contributor upgrade // Once upon a time we were updating 'pressbooks_taxonomy_version' with Metadata::VERSION instead of Taxonomy::VERSION // Some books might be in a weird state (bug?) Rerun the Taxonomy upgrade function from version zero, outside of itself, just in-case Taxonomy::init()->upgrade( 0 ); update_option( 'pressbooks_taxonomy_version', Taxonomy::VERSION ); } /** * @since 5.0.0 * * @param string $status * @param bool $pb_export * * @return string */ public function postStatiiConversion( $status, $pb_export ) { if ( ! is_bool( $pb_export ) ) { return $status; // Doing it wrong... } if ( $pb_export ) { // When pb_export = true and post_status = draft, new post_status = private if ( $status === 'draft' ) { return 'private'; } // When pb_export = true and post_status = publish, new post_status = publish if ( $status === 'publish' ) { return 'publish'; } } else { // When pb_export = false and post_status = draft, new post_status = draft if ( $status === 'draft' ) { return 'draft'; } // When pb_export = false and post_status = publish, new post_status = web-only if ( $status === 'publish' ) { return 'web-only'; } } return $status; // No change } }
{ "pile_set_name": "Github" }
import javax.swing.*; import java.awt.*; import java.awt.geom.Ellipse2D; import java.awt.geom.Rectangle2D; import java.lang.InterruptedException; public class AlgoVisHelper { private AlgoVisHelper(){} public static final Color Red = new Color(0xF44336); public static final Color Pink = new Color(0xE91E63); public static final Color Purple = new Color(0x9C27B0); public static final Color DeepPurple = new Color(0x673AB7); public static final Color Indigo = new Color(0x3F51B5); public static final Color Blue = new Color(0x2196F3); public static final Color LightBlue = new Color(0x03A9F4); public static final Color Cyan = new Color(0x00BCD4); public static final Color Teal = new Color(0x009688); public static final Color Green = new Color(0x4CAF50); public static final Color LightGreen = new Color(0x8BC34A); public static final Color Lime = new Color(0xCDDC39); public static final Color Yellow = new Color(0xFFEB3B); public static final Color Amber = new Color(0xFFC107); public static final Color Orange = new Color(0xFF9800); public static final Color DeepOrange = new Color(0xFF5722); public static final Color Brown = new Color(0x795548); public static final Color Grey = new Color(0x9E9E9E); public static final Color BlueGrey = new Color(0x607D8B); public static final Color Black = new Color(0x000000); public static final Color White = new Color(0xFFFFFF); public static void strokeCircle(Graphics2D g, int x, int y, int r){ Ellipse2D circle = new Ellipse2D.Double(x-r, y-r, 2*r, 2*r); g.draw(circle); } public static void fillCircle(Graphics2D g, int x, int y, int r){ Ellipse2D circle = new Ellipse2D.Double(x-r, y-r, 2*r, 2*r); g.fill(circle); } public static void strokeRectangle(Graphics2D g, int x, int y, int w, int h){ Rectangle2D rectangle = new Rectangle2D.Double(x, y, w, h); g.draw(rectangle); } public static void fillRectangle(Graphics2D g, int x, int y, int w, int h){ Rectangle2D rectangle = new Rectangle2D.Double(x, y, w, h); g.fill(rectangle); } public static void setColor(Graphics2D g, Color color){ g.setColor(color); } public static void setStrokeWidth(Graphics2D g, int w){ int strokeWidth = w; g.setStroke(new BasicStroke(strokeWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); } public static void pause(int t) { try { Thread.sleep(t); } catch (InterruptedException e) { System.out.println("Error sleeping"); } } public static void putImage(Graphics2D g, int x, int y, String imageURL){ ImageIcon icon = new ImageIcon(imageURL); Image image = icon.getImage(); g.drawImage(image, x, y, null); } }
{ "pile_set_name": "Github" }
/* This file is part of Darling. Copyright (C) 2019 Lubos Dolezel Darling is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Darling 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 Darling. If not, see <http://www.gnu.org/licenses/>. */ #import <EventKit/EKFrozenCalendarProposeNewTimeNotification.h> @implementation EKFrozenCalendarProposeNewTimeNotification - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector { return [NSMethodSignature signatureWithObjCTypes: "v@:"]; } - (void)forwardInvocation:(NSInvocation *)anInvocation { NSLog(@"Stub called: %@ in %@", NSStringFromSelector([anInvocation selector]), [self class]); } @end
{ "pile_set_name": "Github" }
<capabilities> <host> <cpu> <arch>x86_64</arch> </cpu> <power_management/> <iommu support='no'/> <migration_features> <live/> </migration_features> <topology> <cells num='2'> <cell id='0'> <memory unit='KiB'>1048576</memory> <pages unit='KiB' size='4'>2048</pages> <pages unit='KiB' size='2048'>4096</pages> <pages unit='KiB' size='1048576'>6144</pages> <cpus num='6'> <cpu id='0' socket_id='0' die_id='0' core_id='0' siblings='0'/> <cpu id='1' socket_id='0' die_id='0' core_id='1' siblings='1'/> <cpu id='2' socket_id='0' die_id='0' core_id='2' siblings='2'/> <cpu id='3' socket_id='0' die_id='0' core_id='3' siblings='3'/> <cpu id='4' socket_id='0' die_id='0' core_id='4' siblings='4'/> <cpu id='5' socket_id='0' die_id='0' core_id='5' siblings='5'/> </cpus> </cell> <cell id='1'> <memory unit='KiB'>2097152</memory> <pages unit='KiB' size='4'>4096</pages> <pages unit='KiB' size='2048'>6144</pages> <pages unit='KiB' size='1048576'>8192</pages> <cpus num='6'> <cpu id='6' socket_id='1' die_id='0' core_id='0' siblings='6'/> <cpu id='7' socket_id='1' die_id='0' core_id='1' siblings='7'/> <cpu id='8' socket_id='1' die_id='0' core_id='2' siblings='8'/> <cpu id='9' socket_id='1' die_id='0' core_id='3' siblings='9'/> <cpu id='10' socket_id='1' die_id='0' core_id='4' siblings='10'/> <cpu id='11' socket_id='1' die_id='0' core_id='5' siblings='11'/> </cpus> </cell> </cells> </topology> <cache> <bank id='0' level='3' type='both' size='15' unit='MiB' cpus='0-5'> <control granularity='768' min='1536' unit='KiB' type='both' maxAllocs='4'/> </bank> <bank id='1' level='3' type='both' size='15' unit='MiB' cpus='6-11'> <control granularity='768' min='1536' unit='KiB' type='both' maxAllocs='4'/> </bank> <monitor level='3' reuseThreshold='270336' maxMonitors='176'> <feature name='llc_occupancy'/> </monitor> </cache> <memory_bandwidth> <node id='0' cpus='0-5'> <control granularity='10' min ='10' maxAllocs='4'/> </node> <node id='1' cpus='6-11'> <control granularity='10' min ='10' maxAllocs='4'/> </node> <monitor maxMonitors='176'> <feature name='mbm_total_bytes'/> <feature name='mbm_local_bytes'/> </monitor> </memory_bandwidth> </host> </capabilities>
{ "pile_set_name": "Github" }
[ { "type": "snippet", "category": "note", "text": [ "This is not the world I have chosen. They even took my CDs!.." ] } ]
{ "pile_set_name": "Github" }
var Galleries = Galleries || { }; (function() { function findElem(parent, tagName, className) { var elemToSearch = (parent) ? parent : document.body; var tagMatch = elemToSearch.getElementsByTagName(tagName); var evaluator = function(elem) { return (className) ? (elem.className.indexOf(className) > -1) : true; }; return findArrayElem(tagMatch, evaluator); } function findArrayElem(array, evaluator) { var newArray = new Array(); for (var count = 0; count < array.length; count++) { if (evaluator(array[count])) { newArray.push(array[count]); } } return newArray; } function iterateElem(elems, delegate) { for(var count = 0; count < elems.length; count++) { delegate(count, elems[count]); } } function isHidden(elem) { return (elem.offsetHeight === 0 && elem.offsetWidth === 0) || elem.style && elem.style.display === "none"; } function onWindowLoad(callback) { attachEventHandler(null, 'load', callback); } function attachEventHandler(elem, event, callback) { var elemToAttach = (elem) ? elem : window; if (document.addEventListener) { elemToAttach.addEventListener(event, callback, false); } else if ( document.attachEvent ) { elemToAttach.attachEvent('on' + event, callback); } } Galleries.findElem = findElem; Galleries.iterateElem = iterateElem; Galleries.attachEventHandler = attachEventHandler; Galleries.onWindowLoad = onWindowLoad; })();
{ "pile_set_name": "Github" }
/* Date: 17.V.2011 Author: pumbur <[email protected]> */ .hljs { display: block; overflow-x: auto; padding: 0.5em; background: #222; } .hljs, .hljs-subst { color: #aaa; } .hljs-section { color: #fff; } .hljs-comment, .hljs-quote, .hljs-meta { color: #444; } .hljs-string, .hljs-symbol, .hljs-bullet, .hljs-regexp { color: #ffcc33; } .hljs-number, .hljs-addition { color: #00cc66; } .hljs-built_in, .hljs-builtin-name, .hljs-literal, .hljs-type, .hljs-template-variable, .hljs-attribute, .hljs-link { color: #32aaee; } .hljs-keyword, .hljs-selector-tag, .hljs-name, .hljs-selector-id, .hljs-selector-class { color: #6644aa; } .hljs-title, .hljs-variable, .hljs-deletion, .hljs-template-tag { color: #bb1166; } .hljs-section, .hljs-doctag, .hljs-strong { font-weight: bold; } .hljs-emphasis { font-style: italic; }
{ "pile_set_name": "Github" }
// Array Expression Operators: https://docs.mongodb.com/manual/reference/operator/aggregation/#array-expression-operators import { computeValue, Options } from '../../../core' import { assert, isArray, isNil } from '../../../util' /** * Returns the element at the specified array index. * * @param {Object} obj * @param {*} expr * @return {*} */ export function $arrayElemAt(obj: object, expr: any, options: Options): any { let args = computeValue(obj, expr, null, options) assert(isArray(args) && args.length === 2, '$arrayElemAt expression must resolve to array(2)') if (args.some(isNil)) return null let index = args[1] let arr = args[0] if (index < 0 && Math.abs(index) <= arr.length) { return arr[(index + arr.length) % arr.length] } else if (index >= 0 && index < arr.length) { return arr[index] } return undefined }
{ "pile_set_name": "Github" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "AForge.Video.VFW" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "AForge" )] [assembly: AssemblyProduct( "AForge.NET" )] [assembly: AssemblyCopyright( "AForge © 2012" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "cf141ece-8e71-4d2c-885d-8451b032a618" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "2.2.4.0" )] [assembly: AssemblyFileVersion( "2.2.4.0" )]
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Flat UI</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Loading Bootstrap --> <link href="./assets/css/bootstrap.css" rel="stylesheet"> <!-- Loading Flat UI --> <link href="./assets/css/flat-ui.css" rel="stylesheet"> <link href="./assets/css/github.css" rel="stylesheet"> <link rel="shortcut icon" href="./assets/images/favicon.ico"> <!-- HTML5 shim, for IE6-8 support of HTML5 elements. All other JS at the end of file. --> <!--[if lt IE 9]> <script src="js/html5shiv.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="demo-headline"> <h1 class="demo-logo">Lettuce <small>Behaviour Driven Development for python</small></h1> </div> <div class="row"> <div class="span4"> <div class="sidebar-nav"> <ul class="share mrl"> <div class="btn btn-primary btn-block btn-large"> <h3>Sections</h3> </div> <a class="btn btn-inverse btn-block btn-large" href="#lettuce-documentation-contents"> Lettuce documentation contents </a> <a class="btn btn-inverse btn-block btn-large" href="#indices--glossary-and-tables"> Indices, glossary and tables </a> </ul> </div> </div> <div class="span8"> <h1 id="lettuce-documentation-contents" name="lettuce-documentation-contents"><a href="#lettuce-documentation-contents">Lettuce documentation contents</a></h1><h2 id="indices--glossary-and-tables" name="indices--glossary-and-tables"><a href="#indices--glossary-and-tables">Indices, glossary and tables</a></h2> <ul> <li> :ref:genindex</li> <li> :ref:modindex</li> </ul> </div> </div> </div> <!-- /container --> <footer> <div class="container"> <div class="row"> <div class="span7"> <h3 class="footer-title">Lettuce</h3> <p>Lettuce is maintained by gabrielfalcao. <br /> This documentation was generated automatically by <a href="http://octomarks.io/gabrielfalcao/markment">Markment</a>. </p> <p> This theme was written by Gabriel Falcão using the <a href="http://designmodo.github.io/Flat-UI/">Flat-UI</a> library by <a class="footer-brand" href="http://designmodo.com" target="_blank"> <img src="./assets/images/footer/logo.png" alt="Designmodo.com"> </a> </p> </div> <!-- /span8 --> <div class="span5"> <div class="footer-banner"> <h3 class="footer-title">Table of contents</h3> <ul> <li> <a href="./contents.html"> contents.md </a> </li> <li> <a href="./index.html"> index.md </a> </li> <li> <a href="./dev/documentation.html"> documentation.md </a> </li> <li> <a href="./dev/index.html"> index.md </a> </li> <li> <a href="./dev/install-debian-squeeze.html"> install-debian-squeeze.md </a> </li> <li> <a href="./dev/install.html"> install.md </a> </li> <li> <a href="./dev/testing.html"> testing.md </a> </li> <li> <a href="./intro/install.html"> install.md </a> </li> <li> <a href="./intro/overview.html"> overview.md </a> </li> <li> <a href="./intro/wtf.html"> wtf.md </a> </li> <li> <a href="./recipes/django-lxml.html"> django-lxml.md </a> </li> <li> <a href="./recipes/nose.html"> nose.md </a> </li> <li> <a href="./reference/cli.html"> cli.md </a> </li> <li> <a href="./reference/features.html"> features.md </a> </li> <li> <a href="./reference/languages.html"> languages.md </a> </li> <li> <a href="./reference/terrain.html"> terrain.md </a> </li> <li> <a href="./tutorial/django.html"> django.md </a> </li> <li> <a href="./tutorial/multiline.html"> multiline.md </a> </li> <li> <a href="./tutorial/scenario-outlines.html"> scenario-outlines.md </a> </li> <li> <a href="./tutorial/simple.html"> simple.md </a> </li> <li> <a href="./tutorial/steps-from-step-definitions.html"> steps-from-step-definitions.md </a> </li> <li> <a href="./tutorial/tables.html"> tables.md </a> </li> </ul> </div> </div> </div> </div> </footer> </body> </html>
{ "pile_set_name": "Github" }
.\" $OpenBSD: unclosed.in,v 1.2 2017/07/04 14:53:25 schwarze Exp $ .Dd $Mdocdate: July 4 2017 $ .Dt EO-UNCLOSED 1 .Os .Sh NAME .Nm Eo-unclosed .Nd unclosed custom enclosure block .Sh DESCRIPTION before block .Eo <<
{ "pile_set_name": "Github" }
#ifdef __OBJC__ #import <UIKit/UIKit.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif FOUNDATION_EXPORT double Pods_ExampleVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_ExampleVersionString[];
{ "pile_set_name": "Github" }
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop"> <PropertyGroup> <TargetFramework>netcoreapp3.1</TargetFramework> <UseWpf>true</UseWpf> <UseWindowsForms>true</UseWindowsForms> <EnableDefaultItems>false</EnableDefaultItems> </PropertyGroup> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProjectGuid>{9645F8D8-C438-4302-BB7A-8F3EE0C683BE}</ProjectGuid> <OutputType>WinExe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>NotificationIcon</RootNamespace> <AssemblyName>NotificationIcon</AssemblyName> <FileAlignment>512</FileAlignment> <WarningLevel>4</WarningLevel> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PlatformTarget>AnyCPU</PlatformTarget> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PlatformTarget>AnyCPU</PlatformTarget> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> </ItemGroup> <ItemGroup> <ApplicationDefinition Include="App.xaml"> <Generator>MSBuild:Compile</Generator> <SubType>Designer</SubType> </ApplicationDefinition> <Page Include="MainWindow.xaml"> <Generator>MSBuild:Compile</Generator> <SubType>Designer</SubType> </Page> <Compile Include="App.cs"> <DependentUpon>App.xaml</DependentUpon> <SubType>Code</SubType> </Compile> <Compile Include="MainWindow.cs"> <DependentUpon>MainWindow.xaml</DependentUpon> <SubType>Code</SubType> </Compile> </ItemGroup> <ItemGroup> <Compile Include="Properties\Resources.Designer.cs"> <AutoGen>True</AutoGen> <DesignTime>True</DesignTime> <DependentUpon>Resources.resx</DependentUpon> </Compile> <Compile Include="Properties\Settings.Designer.cs"> <AutoGen>True</AutoGen> <DependentUpon>Settings.settings</DependentUpon> <DesignTimeSharedInput>True</DesignTimeSharedInput> </Compile> <EmbeddedResource Include="Properties\Resources.resx"> <Generator>ResXFileCodeGenerator</Generator> <LastGenOutput>Resources.Designer.cs</LastGenOutput> </EmbeddedResource> <None Include="Properties\Settings.settings"> <Generator>SettingsSingleFileGenerator</Generator> <LastGenOutput>Settings.Designer.cs</LastGenOutput> </None> <AppDesigner Include="Properties\" /> </ItemGroup> <ItemGroup> <None Include="App.config" /> </ItemGroup> <ItemGroup> <Content Include="NotifyIcon.ico"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> </ItemGroup> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
{ "pile_set_name": "Github" }
/************************************************************* * * MathJax/jax/output/HTML-CSS/fonts/STIX/General/BoldItalic/ControlPictures.js * * Copyright (c) 2009-2015 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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. * */ MathJax.Hub.Insert( MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['STIXGeneral-bold-italic'], { 0x2423: [31,120,500,40,460] // stix-round space indicator } ); MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir + "/General/BoldItalic/ControlPictures.js");
{ "pile_set_name": "Github" }
define(function(require, exports, module) { "use strict"; var Emojis = require("./emojis"); exports.emoji = function(text, staticPrefix) { return text.replace(/([\ue001-\ue999])/g, function(str, p1) { return p1.charCodeAt(0).toString(16).toUpperCase().replace( /^([\da-f]+)$/i, "<img class='emoji' src=\"" + staticPrefix + "/emoji/emoji-$1.png\" alt=\"emoji\" />" ); }); }; exports.toEmojiUnicode = function(text) { function toUnicode(str, p1) { return Emojis.reverse[p1] ? eval('"\\u' + Emojis.reverse[p1] + '"') : str; } text = text.replace(/(:[\w_\-\+]*:)/g, toUnicode); specialEmojis.forEach(function (emot) { text = text.replace(emot[0], toUnicode(emot[1], emot[1])); }); return text; }; var specialEmojis = [ [/:-*\)/g, ':blush:'], [/:-*o/gi, ':scream:'], [/(:|;)-*\]/g, ':smirk:'], [/(:|;)-*d/gi, ':smile:'], [/xd/gi, ':stuck_out_tongue_closed_eyes:'], [/:-*p/gi, ':stuck_out_tongue:'], [/:-*(\[|@)/g, ':rage:'], [/:-*\(/g, ':disappointed:'], [/:-*\*/g, ':kissing_heart:'], [/;-*\)/g, ':wink:'], // [/:-*\//g, ':pensive:'], - contradicsts with clickable links in the chat text [/:-*s/gi, ':confounded:'], [/:-*\|/g, ':flushed:'], [/:-*\$/g, ':relaxed:'], [/:-*x/gi, ':mask:'], [/&lt;3/g, ':heart:'], [/&lt;\/3/g, ':broken_heart:'], [/:('|’)-*\(/g, ':sob:'] ]; });
{ "pile_set_name": "Github" }
/*Copyright (c) 2017 Marios Michailidis 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 manipulate.operate; import java.util.ArrayList; import exceptions.NullObjectException; /** * * @author marios *<p> Purpose of the class is to provide a runnable class for array's operations */ public class OperateRunnable implements Runnable{ /** * 1d Array to operate to */ double array1d[]; /** * 1d Array to operates from */ double array1dtopass[]; /** * 2d Array to operate to */ double array2d[][]; /** * 2d Array tto operate from */ double array2dtopass[][]; /** * 2d Arraylist to to operate to */ ArrayList<ArrayList<Double>> arraylist1d2d; /** * 2d Arraylist to to operate from */ ArrayList<ArrayList<Double>> arraylist1d2dtopass; /** * defines the operation type and can be any of "add, sub, mul, div" */ String type; /** * start location of the loop */ int s=0; /** * end location of the loop */ int e=0; /** * * @param array The array to process (by reference) * @param array_topass The array to operate with (by reference) * @param start The start location * @param end The end location * @param types The type operation can be "add, sub, mul, div" for addition, subtraction, multiplication, division * Basic constructor with arrays' operations for 1d arrays */ OperateRunnable(double array [],double array_topass[], int start, int end, String types) { array1d=array; array1dtopass=array_topass; s=start; e=end; type=types; }; /** * * @param array The 2d array to process (by reference) * @param array_topass The 2d array to operate values to (by reference) * @param start The start location * @param end The end location * @param types The type operation can be "add, sub, mul, div" for addition, subtraction, multiplication, division * Basic constructor with operations for 2d arrays */ OperateRunnable(double array [][],double array_topass [][], int start, int end, String types) { array2d=array; array2dtopass=array_topass; s=start; e=end; type=types; }; /** * * @param array The arraylist to process (by reference) * @param array_topass The 2d arraylist to operate values to (by reference) * @param start The start location * @param end The end location * @param types The type operation can be "add, sub, mul, div" for addition, subtraction, multiplication, division * Basic constructor with operations for 2d arraylists */ OperateRunnable( ArrayList<ArrayList<Double>> array,ArrayList<ArrayList<Double>> array_topass, int start, int end, String types) { arraylist1d2d=array; arraylist1d2dtopass=array_topass; s=start; e=end; type=types; }; @Override public void run() { //make some sensible checks if (s>e){ throw new IllegalStateException(" The start of the loop in the scalar operation cannot be less/equal than the end"); } // first define the method if (array1d!=null && array1dtopass!=null && array1d.length==array1dtopass.length){ if (type.equals("add")){ for (int i=s; i < e; i++) { array1d[i]+=array1dtopass[i]; } // end of addition } else if (type.equals("sub")){ for (int i=s; i < e; i++) { array1d[i]-=array1dtopass[i]; } // end of substraction }else if (type.equals("mul")){ for (int i=s; i < e; i++) { array1d[i]*=array1dtopass[i]; } // end of multiplication } else if (type.equals("div")){ for (int i=s; i < e; i++) { array1d[i]/=array1dtopass[i]; } // end of division } else { // all object are null, throw error throw new NullObjectException (" operation type-String for scalar operation cannot be null "); } // end of array 1d } else if (array2d!=null&& array2dtopass!=null && array2d.length==array2dtopass.length ) { if (type.equals("add")){ for (int i=s; i < e; i++) { for (int j=0; j < array2d[i].length; j++) { array2d[i][j]+=array2dtopass[i][j]; } } // end of addition } else if (type.equals("sub")){ for (int i=s; i < e; i++) { for (int j=0; j < array2d[i].length; j++) { array2d[i][j]-=array2dtopass[i][j]; } } // end of substraction }else if (type.equals("mul")){ for (int i=s; i < e; i++) { for (int j=0; j < array2d[i].length; j++) { array2d[i][j]*=array2dtopass[i][j]; } } // end of multiplication } else if (type.equals("div")){ for (int i=s; i < e; i++) { for (int j=0; j < array2d[i].length; j++) { array2d[i][j]/=array2dtopass[i][j]; } } // end of division } else { // all object are null, throw error throw new NullObjectException (" operation type-String for scalar operation cannot be null "); } // end of array2d } else if (arraylist1d2d!=null && arraylist1d2dtopass!=null && arraylist1d2d.size()==arraylist1d2dtopass.size()) { if (type.equals("add")){ for (int i=s; i < e; i++) { for (int j=0; j < arraylist1d2d.get(i).size(); j++) { arraylist1d2d.get(i).set(j,arraylist1d2d.get(i).get(j) + arraylist1d2d.get(i).get(j)); } } // end of addition } else if (type.equals("sub")){ for (int i=s; i < e; i++) { for (int j=0; j < arraylist1d2d.get(i).size(); j++) { arraylist1d2d.get(i).set(j,arraylist1d2d.get(i).get(j) - arraylist1d2d.get(i).get(j)); } } // end of substraction }else if (type.equals("mul")){ for (int i=s; i < e; i++) { for (int j=0; j < arraylist1d2d.get(i).size(); j++) { arraylist1d2d.get(i).set(j, arraylist1d2d.get(i).get(j) * arraylist1d2d.get(i).get(j)); } } // end of multiplication } else if (type.equals("div")){ for (int i=s; i < e; i++) { for (int j=0; j < arraylist1d2d.get(i).size(); j++) { arraylist1d2d.get(i).set(j, arraylist1d2d.get(i).get(j) / arraylist1d2d.get(i).get(j)); } } // end of division } else { // all object are null, throw error throw new NullObjectException (" operation type-String for scalar operation cannot be null "); } // end of arraylist 2d } else { // all object are null, throw error throw new NullObjectException (" copy operation failed as either the copy-to or copy-from (or both) container-objects were null or of differebr sizes"); } // TODO Auto-generated method stub } }
{ "pile_set_name": "Github" }
package aws import ( "fmt" "strconv" "strings" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/elb" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" ) func resourceAwsLoadBalancerBackendServerPolicies() *schema.Resource { return &schema.Resource{ Create: resourceAwsLoadBalancerBackendServerPoliciesCreate, Read: resourceAwsLoadBalancerBackendServerPoliciesRead, Update: resourceAwsLoadBalancerBackendServerPoliciesCreate, Delete: resourceAwsLoadBalancerBackendServerPoliciesDelete, Schema: map[string]*schema.Schema{ "load_balancer_name": { Type: schema.TypeString, Required: true, }, "policy_names": { Type: schema.TypeSet, Elem: &schema.Schema{Type: schema.TypeString}, Optional: true, Set: schema.HashString, }, "instance_port": { Type: schema.TypeInt, Required: true, }, }, } } func resourceAwsLoadBalancerBackendServerPoliciesCreate(d *schema.ResourceData, meta interface{}) error { elbconn := meta.(*AWSClient).elbconn loadBalancerName := d.Get("load_balancer_name") policyNames := []*string{} if v, ok := d.GetOk("policy_names"); ok { policyNames = expandStringList(v.(*schema.Set).List()) } setOpts := &elb.SetLoadBalancerPoliciesForBackendServerInput{ LoadBalancerName: aws.String(loadBalancerName.(string)), InstancePort: aws.Int64(int64(d.Get("instance_port").(int))), PolicyNames: policyNames, } if _, err := elbconn.SetLoadBalancerPoliciesForBackendServer(setOpts); err != nil { return fmt.Errorf("Error setting LoadBalancerPoliciesForBackendServer: %s", err) } d.SetId(fmt.Sprintf("%s:%s", *setOpts.LoadBalancerName, strconv.FormatInt(*setOpts.InstancePort, 10))) return resourceAwsLoadBalancerBackendServerPoliciesRead(d, meta) } func resourceAwsLoadBalancerBackendServerPoliciesRead(d *schema.ResourceData, meta interface{}) error { elbconn := meta.(*AWSClient).elbconn loadBalancerName, instancePort := resourceAwsLoadBalancerBackendServerPoliciesParseId(d.Id()) describeElbOpts := &elb.DescribeLoadBalancersInput{ LoadBalancerNames: []*string{aws.String(loadBalancerName)}, } describeResp, err := elbconn.DescribeLoadBalancers(describeElbOpts) if err != nil { if ec2err, ok := err.(awserr.Error); ok { if ec2err.Code() == "LoadBalancerNotFound" { d.SetId("") return fmt.Errorf("LoadBalancerNotFound: %s", err) } } return fmt.Errorf("Error retrieving ELB description: %s", err) } if len(describeResp.LoadBalancerDescriptions) != 1 { return fmt.Errorf("Unable to find ELB: %#v", describeResp.LoadBalancerDescriptions) } lb := describeResp.LoadBalancerDescriptions[0] policyNames := []*string{} for _, backendServer := range lb.BackendServerDescriptions { if instancePort != strconv.Itoa(int(*backendServer.InstancePort)) { continue } policyNames = append(policyNames, backendServer.PolicyNames...) } d.Set("load_balancer_name", loadBalancerName) d.Set("instance_port", instancePort) d.Set("policy_names", flattenStringList(policyNames)) return nil } func resourceAwsLoadBalancerBackendServerPoliciesDelete(d *schema.ResourceData, meta interface{}) error { elbconn := meta.(*AWSClient).elbconn loadBalancerName, instancePort := resourceAwsLoadBalancerBackendServerPoliciesParseId(d.Id()) instancePortInt, err := strconv.ParseInt(instancePort, 10, 64) if err != nil { return fmt.Errorf("Error parsing instancePort as integer: %s", err) } setOpts := &elb.SetLoadBalancerPoliciesForBackendServerInput{ LoadBalancerName: aws.String(loadBalancerName), InstancePort: aws.Int64(instancePortInt), PolicyNames: []*string{}, } if _, err := elbconn.SetLoadBalancerPoliciesForBackendServer(setOpts); err != nil { return fmt.Errorf("Error setting LoadBalancerPoliciesForBackendServer: %s", err) } return nil } func resourceAwsLoadBalancerBackendServerPoliciesParseId(id string) (string, string) { parts := strings.SplitN(id, ":", 2) return parts[0], parts[1] }
{ "pile_set_name": "Github" }
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- // Everything inside the loop except for the assignment to 'a' should get hoisted function test0() { var a; for(var i = 0; i < 1; ++i) a = (0x40000000 | 0) % 3; return a; } WScript.Echo("test0: " + test0()); // The '-f' bails out, and the Neg is hoisted outside the loop. The multiplication is not type-specialized, so 'f' is converted // to var and that conversion is also hoisted outside the loop. The conversion to var happens after the bailout, so the value of // the var sym for 'f' is not valid at the time of bailout. So, bailout should use the int sym for 'f' to restore its value. function test1() { var c = 1; var f = (1 !== 0); f = f & 21037030; var g; for(var __loopvar1 = 0; c < (g = (((-f) ? (f * i32[(1) % 256]) : 1))) && __loopvar1 < 3; c++ + __loopvar1++) { } return g; } WScript.Echo("test1: " + test1()); // In 'o.p &= 1', 'o' is converted to var. 'o' was const-propped with '0' though, so an LdC_A_I4 is created and hoisted to the // outer loop's landing pad. LdC_A_I4 should be considered a type-spec conversion here, so while making the var version of the // sym live, it should also preserve the int version of the sym as live. function test2() { for(var i = 0; i < 1; ++i) { var o = 0; for(var j = 0; j < 1; ++j) o.p &= 1; } } WScript.Echo("test2: " + test2()); // When hoisting an invariant with a new dst, value type of the old dst should be copied over to the new dst. function test3() { var func1 = function () { return '6' + '\xb5!%$' + 'caller'; }; var func2 = function () { return '6' + '\xb5!%$' + 'caller'; }; var ary = Array(); func1(); for (var v1 = 0; v1 < 8; v1++) { WScript.Echo(func2()); } WScript.Echo('subset_of_ary = ' + ary.slice()); } test3();
{ "pile_set_name": "Github" }
// Copyright (C) 2017 Google 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. package memory import ( "context" "reflect" "github.com/google/gapid/core/data/endian" "github.com/google/gapid/core/data/slice" "github.com/google/gapid/core/os/device" ) // LoadSlice loads the slice elements from s into a go-slice of the slice type. func LoadSlice(ctx context.Context, s Slice, pools Pools, l *device.MemoryLayout) (interface{}, error) { pool := pools.MustGet(s.Pool()) rng := Range{s.Base(), s.Size()} ioR := pool.Slice(rng).NewReader(ctx) binR := endian.Reader(ioR, l.GetEndian()) d := NewDecoder(binR, l) count := int(s.Count()) sli := slice.New(reflect.SliceOf(s.ElementType()), count, count) Read(d, sli.Addr().Interface()) if err := binR.Error(); err != nil { return nil, err } return sli.Interface(), nil } // LoadPointer loads the element from p. func LoadPointer(ctx context.Context, p Pointer, pools Pools, l *device.MemoryLayout) (interface{}, error) { ioR := pools.ApplicationPool().At(p.Address()).NewReader(ctx) binR := endian.Reader(ioR, l.GetEndian()) d := NewDecoder(binR, l) elPtr := reflect.New(p.ElementType()) Read(d, elPtr.Interface()) if err := binR.Error(); err != nil { return nil, err } return elPtr.Elem().Interface(), nil }
{ "pile_set_name": "Github" }
/* * 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.aliyuncs.bssopenapi.model.v20171214; import com.aliyuncs.RpcAcsRequest; import com.aliyuncs.http.MethodType; import com.aliyuncs.bssopenapi.Endpoint; /** * @author auto create * @version */ public class QueryCustomerAddressListRequest extends RpcAcsRequest<QueryCustomerAddressListResponse> { private Long ownerId; public QueryCustomerAddressListRequest() { super("BssOpenApi", "2017-12-14", "QueryCustomerAddressList"); setMethod(MethodType.POST); try { com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap); com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType); } catch (Exception e) {} } public Long getOwnerId() { return this.ownerId; } public void setOwnerId(Long ownerId) { this.ownerId = ownerId; if(ownerId != null){ putQueryParameter("OwnerId", ownerId.toString()); } } @Override public Class<QueryCustomerAddressListResponse> getResponseClass() { return QueryCustomerAddressListResponse.class; } }
{ "pile_set_name": "Github" }
// (C) Copyright Edward Diener 2011,2012 // 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). /* The succeeding comments in this file are in doxygen format. */ /** \file */ #if !defined(BOOST_TTI_HAS_TEMPLATE_HPP) #define BOOST_TTI_HAS_TEMPLATE_HPP #include <boost/config.hpp> #include <boost/tti/gen/has_template_gen.hpp> #include <boost/preprocessor/config/config.hpp> #include <boost/preprocessor/control/iif.hpp> #if BOOST_PP_VARIADICS #include <boost/preprocessor/comparison/equal.hpp> #include <boost/preprocessor/variadic/elem.hpp> #include <boost/preprocessor/variadic/size.hpp> #include <boost/tti/detail/dvm_template_params.hpp> /// Expands to a metafunction which tests whether an inner class template with a particular name exists. /** trait = the name of the metafunction. ... = variadic parameters. The first variadic parameter is the inner class template name. Following variadic parameters are optional. If no following variadic parameters exist, then the inner class template being introspected must be all template type parameters ( template parameters starting with `class` or `typename` ) and any number of template type parameters can occur. If the second variadic parameter is BOOST_PP_NIL and no other variadic parameter is given, then just as in the previous case the inner class template being introspected must be all template type parameters ( template parameters starting with `class` or `typename` ) and any number of template type parameters can occur. This form is allowed in order to be consistent with using the non-variadic form of this macro. If the second variadic parameter is a Boost preprocessor library array and no other variadic parameter is given, then the inner class template must have its template parameters matching the sequence in the tuple portion of the Boost PP array. This form is allowed in order to be consistent with using the non-variadic form of this macro. Otherwise the inner class template must have its template parameters matching the sequence of the optional variadic parameters. generates a metafunction called "trait" where 'trait' is the first macro parameter. template<class BOOST_TTI_TP_T> struct trait { static const value = unspecified; typedef mpl::bool_<true-or-false> type; }; The metafunction types and return: BOOST_TTI_TP_T = the enclosing type in which to look for our 'name'. returns = 'value' is true if the 'name' template exists within the enclosing type, otherwise 'value' is false. Examples: 1) Search for an inner class template called 'MyTemplate', with all template type parameters, nested within the class 'MyClass' using a metafunction name of 'MyMeta'. BOOST_TTI_TRAIT_HAS_TEMPLATE(MyMeta,MyTemplate) or BOOST_TTI_TRAIT_HAS_TEMPLATE(MyMeta,MyTemplate,BOOST_PP_NIL) // Non-variadic macro form MyMeta<MyClass>::value is a compile time boolean constant which is either 'true' or 'false' if the nested template exists. 2) Search for an inner class template called 'MyTemplate', with template parameters of 'class T,int x,template<class> class U', nested within the class 'MyClass' using a metafunction name of 'MyMeta'. BOOST_TTI_TRAIT_HAS_TEMPLATE(MyMeta,MyTemplate,class,int,template<class> class) or BOOST_TTI_TRAIT_HAS_TEMPLATE(MyMeta,MyTemplate,(3,(class,int,template<class> class))) // Non-variadic macro form MyMeta<MyClass>::value is a compile time boolean constant which is either 'true' or 'false' if the nested template exists. */ #define BOOST_TTI_TRAIT_HAS_TEMPLATE(trait,...) \ BOOST_PP_IIF \ ( \ BOOST_PP_EQUAL \ ( \ BOOST_PP_VARIADIC_SIZE(__VA_ARGS__), \ 1 \ ), \ BOOST_TTI_DETAIL_VM_TRAIT_HAS_TEMPLATE, \ BOOST_TTI_DETAIL_VM_CHECK_MORE_THAN_TWO \ ) \ (trait,__VA_ARGS__) \ /**/ /// Expands to a metafunction which tests whether an inner class template with a particular name exists. /** ... = variadic parameters. The first variadic parameter is the inner class template name. Following variadic parameters are optional. If no following variadic parameters exist, then the inner class template being introspected must be all template type parameters ( template parameters starting with `class` or `typename` ) and any number of template type parameters can occur. If the second variadic parameter is BOOST_PP_NIL and no other variadic parameter is given, then just as in the previous case the inner class template being introspected must be all template type parameters ( template parameters starting with `class` or `typename` ) and any number of template type parameters can occur. This form is allowed in order to be consistent with using the non-variadic form of this macro. If the second variadic parameter is a Boost preprocessor library array and no other variadic parameter is given, then the inner class template must have its template parameters matching the sequence in the tuple portion of the Boost PP array. This form is allowed in order to be consistent with using the non-variadic form of this macro. Otherwise the inner class template must have its template parameters matching the sequence of the optional variadic parameters. generates a metafunction called "has_template_'name'" where 'name' is the first variadic parameter. template<class BOOST_TTI_TP_T> struct has_template_'name' { static const value = unspecified; typedef mpl::bool_<true-or-false> type; }; The metafunction types and return: BOOST_TTI_TP_T = the enclosing type in which to look for our 'name'. returns = 'value' is true if the 'name' template exists within the enclosing type, otherwise 'value' is false. Examples: 1) Search for an inner class template called 'MyTemplate', with all template type parameters, nested within the class 'MyClass'. BOOST_TTI_HAS_TEMPLATE(MyTemplate) or BOOST_TTI_HAS_TEMPLATE(MyTemplate,BOOST_PP_NIL) // Non-variadic macro form has_template_MyTemplate<MyClass>::value is a compile time boolean constant which is either 'true' or 'false' if the nested template exists. 2) Search for an inner class template called 'MyTemplate' with template parameters of 'class T,int x,template<class> class U' nested within the class 'MyClass'. BOOST_TTI_HAS_TEMPLATE(MyTemplate,class,int,template<class> class) or BOOST_TTI_HAS_TEMPLATE(MyTemplate,(3,(class,int,template<class> class))) // Non-variadic macro form has_template_MyTemplate<MyClass>::value is a compile time boolean constant which is either 'true' or 'false' if the nested template exists. */ #define BOOST_TTI_HAS_TEMPLATE(...) \ BOOST_TTI_TRAIT_HAS_TEMPLATE \ ( \ BOOST_TTI_HAS_TEMPLATE_GEN \ ( \ BOOST_PP_VARIADIC_ELEM(0,__VA_ARGS__) \ ), \ __VA_ARGS__ \ ) \ /**/ #else // !BOOST_PP_VARIADICS #include <boost/preprocessor/detail/is_binary.hpp> #include <boost/tti/detail/dtemplate.hpp> #include <boost/tti/detail/dtemplate_params.hpp> /// Expands to a metafunction which tests whether an inner class template with a particular name exists. /** trait = the name of the metafunction. name = the inner class template name. params = If the parameter is BOOST_PP_NIL the inner class template being introspected must be all template type parameters ( template parameters starting with `class` or `typename` ) and any number of template type parameters can occur. If the parameter is a Boost preprocessor library array, then the inner class template must have its template parameters matching the sequence in the tuple portion of the Boost PP array. Otherwise a compiler error occurs. generates a metafunction called "trait" where 'trait' is the first macro parameter. template<class BOOST_TTI_TP_T> struct trait { static const value = unspecified; typedef mpl::bool_<true-or-false> type; }; The metafunction types and return: BOOST_TTI_TP_T = the enclosing type in which to look for our 'name'. returns = 'value' is true if the 'name' template exists within the enclosing type, otherwise 'value' is false. Examples: 1) Search for an inner class template called 'MyTemplate', with all template type parameters, nested within the class 'MyClass' using a metafunction name of 'MyMeta'. BOOST_TTI_TRAIT_HAS_TEMPLATE(MyMeta,MyTemplate,BOOST_PP_NIL) MyMeta<MyClass>::value is a compile time boolean constant which is either 'true' or 'false' if the nested template exists. 2) Search for an inner class template called 'MyTemplate', with template parameters of 'class T,int x,template<class> class U', nested within the class 'MyClass' using a metafunction name of 'MyMeta'. BOOST_TTI_TRAIT_HAS_TEMPLATE(MyMeta,MyTemplate,(3,(class,int,template<class> class))) MyMeta<MyClass>::value is a compile time boolean constant which is either 'true' or 'false' if the nested template exists. */ #define BOOST_TTI_TRAIT_HAS_TEMPLATE(trait,name,params) \ BOOST_PP_IIF \ ( \ BOOST_PP_IS_BINARY(params), \ BOOST_TTI_DETAIL_TRAIT_HAS_TEMPLATE_CHECK_PARAMS, \ BOOST_TTI_DETAIL_TRAIT_CHECK_IS_NIL \ ) \ (trait,name,params) \ /**/ /// Expands to a metafunction which tests whether an inner class template with a particular name exists. /** name = the inner class template name. params = If the parameter is BOOST_PP_NIL the inner class template being introspected must be all template type parameters ( template parameters starting with `class` or `typename` ) and any number of template type parameters can occur. If the parameter is a Boost preprocessor library array, then the inner class template must have its template parameters matching the sequence in the tuple portion of the Boost PP array. Otherwise a compiler error occurs. generates a metafunction called "has_template_'name'" where 'name' is the first macro parameter. template<class BOOST_TTI_TP_T> struct trait { static const value = unspecified; typedef mpl::bool_<true-or-false> type; }; The metafunction types and return: BOOST_TTI_TP_T = the enclosing type in which to look for our 'name'. returns = 'value' is true if the 'name' template exists within the enclosing type, otherwise 'value' is false. Examples: 1) Search for an inner class template called 'MyTemplate', with all template type parameters, nested within the class 'MyClass'. BOOST_TTI_HAS_TEMPLATE(MyTemplate,BOOST_PP_NIL) has_template_MyTemplate<MyClass>::value is a compile time boolean constant which is either 'true' or 'false' if the nested template exists. 2) Search for an inner class template called 'MyTemplate' with template parameters of 'class T,int x,template<class> class U' nested within the class 'MyClass'. BOOST_TTI_HAS_TEMPLATE(MyTemplate,(3,(class,int,template<class> class))) has_template_MyTemplate<MyClass>::value is a compile time boolean constant which is either 'true' or 'false' if the nested template exists. */ #define BOOST_TTI_HAS_TEMPLATE(name,params) \ BOOST_TTI_TRAIT_HAS_TEMPLATE \ ( \ BOOST_TTI_HAS_TEMPLATE_GEN(name), \ name, \ params \ ) \ /**/ #endif // BOOST_PP_VARIADICS #endif // BOOST_TTI_HAS_TEMPLATE_HPP
{ "pile_set_name": "Github" }
/* Google Code style (c) Aahan Krish <[email protected]> */ .hljs { display: block; overflow-x: auto; padding: 0.5em; background: white; color: black; } .hljs-comment, .hljs-quote { color: #800; } .hljs-keyword, .hljs-selector-tag, .hljs-section, .hljs-title, .hljs-name { color: #008; } .hljs-variable, .hljs-template-variable { color: #660; } .hljs-string, .hljs-selector-attr, .hljs-selector-pseudo, .hljs-regexp { color: #080; } .hljs-literal, .hljs-symbol, .hljs-bullet, .hljs-meta, .hljs-number, .hljs-link { color: #066; } .hljs-title, .hljs-doctag, .hljs-type, .hljs-attr, .hljs-built_in, .hljs-builtin-name, .hljs-params { color: #606; } .hljs-attribute, .hljs-subst { color: #000; } .hljs-formula { background-color: #eee; font-style: italic; } .hljs-selector-id, .hljs-selector-class { color: #9B703F } .hljs-addition { background-color: #baeeba; } .hljs-deletion { background-color: #ffc8bd; } .hljs-doctag, .hljs-strong { font-weight: bold; } .hljs-emphasis { font-style: italic; }
{ "pile_set_name": "Github" }
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class WebEnvironmentPlugin { constructor(inputFileSystem, outputFileSystem) { this.inputFileSystem = inputFileSystem; this.outputFileSystem = outputFileSystem; } apply(compiler) { compiler.outputFileSystem = this.outputFileSystem; } } module.exports = WebEnvironmentPlugin;
{ "pile_set_name": "Github" }
#include QMK_KEYBOARD_H // Each layer gets a name for readability, which is then used in the keymap matrix below. // The underscores don't mean anything - you can have a layer called STUFF or any other name. // Layer names don't all need to be of the same length, obviously, and you can also skip them // entirely and just use numbers. #define _QW 0 #define _RS 1 #define _LW 2 const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = { [_QW] = LAYOUT( /* Qwerty */ KC_Q, KC_W, KC_E, KC_R, KC_T, KC_Y, KC_U, KC_I, KC_O, KC_P , KC_A, KC_S, KC_D, KC_F, KC_G, KC_H, KC_J, KC_K, KC_L, KC_SCLN , KC_Z, KC_X, KC_C, KC_V, KC_B, KC_N, KC_M, KC_COMM, KC_DOT, KC_SLSH , KC_ESC, KC_TAB, KC_LGUI, KC_LSFT, KC_BSPC, KC_LCTL, KC_LALT, KC_SPC, MO(_RS), KC_MINS, KC_QUOT, KC_ENT ), [_RS] = LAYOUT( /* [> RAISE <] */ KC_EXLM, KC_AT, KC_LCBR, KC_RCBR, KC_PIPE, KC_PGUP, KC_7, KC_8, KC_9, KC_ASTR , KC_HASH, KC_DLR, KC_LPRN, KC_RPRN, KC_GRV, KC_PGDN, KC_4, KC_5, KC_6, KC_PLUS , KC_PERC, KC_CIRC, KC_LBRC, KC_RBRC, KC_TILD, KC_AMPR, KC_1, KC_2, KC_3, KC_BSLS , TG(_LW), KC_INS, KC_LGUI, KC_LSFT, KC_BSPC, KC_LCTL, KC_LALT, KC_SPC, KC_TRNS, KC_DOT, KC_0, KC_EQL ), [_LW] = LAYOUT( /* [> LOWER <] */ KC_INS, KC_HOME, KC_UP, KC_END, KC_PGUP, KC_UP, KC_F7, KC_F8, KC_F9, KC_F10 , KC_DEL, KC_LEFT, KC_DOWN, KC_RGHT, KC_DOWN, KC_DOWN, KC_F4, KC_F5, KC_F6, KC_F11 , KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_F1, KC_F2, KC_F3, KC_F12 , KC_TRNS, KC_TRNS, KC_LGUI, KC_LSFT, KC_BSPC, KC_LCTL, KC_LALT, KC_SPC, DF(_QW), KC_TRNS, KC_TRNS, RESET ), }; const macro_t *action_get_macro(keyrecord_t *record, uint8_t id, uint8_t opt) { // MACRODOWN only works in this function switch(id) { case 0: if (record->event.pressed) { register_code(KC_RSFT); } else { unregister_code(KC_RSFT); } break; } return MACRO_NONE; };
{ "pile_set_name": "Github" }
// Copyright 2015 PingCAP, 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, // See the License for the specific language governing permissions and // limitations under the License. package stringutil import ( "strings" "unicode/utf8" "github.com/juju/errors" ) // ErrSyntax indicates that a value does not have the right syntax for the target type. var ErrSyntax = errors.New("invalid syntax") // Reverse returns its argument string reversed rune-wise left to right. func Reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) } // UnquoteChar decodes the first character or byte in the escaped string // or character literal represented by the string s. // It returns four values: // //1) value, the decoded Unicode code point or byte value; //2) multibyte, a boolean indicating whether the decoded character requires a multibyte UTF-8 representation; //3) tail, the remainder of the string after the character; and //4) an error that will be nil if the character is syntactically valid. // // The second argument, quote, specifies the type of literal being parsed // and therefore which escaped quote character is permitted. // If set to a single quote, it permits the sequence \' and disallows unescaped '. // If set to a double quote, it permits \" and disallows unescaped ". // If set to zero, it does not permit either escape and allows both quote characters to appear unescaped. // Different with strconv.UnquoteChar, it permits unnecessary backslash. func UnquoteChar(s string, quote byte) (value []byte, tail string, err error) { // easy cases switch c := s[0]; { case c == quote: err = errors.Trace(ErrSyntax) return case c >= utf8.RuneSelf: r, size := utf8.DecodeRuneInString(s) if r == utf8.RuneError { value = append(value, c) return value, s[1:], nil } value = append(value, string(r)...) return value, s[size:], nil case c != '\\': value = append(value, c) return value, s[1:], nil } // hard case: c is backslash if len(s) <= 1 { err = errors.Trace(ErrSyntax) return } c := s[1] s = s[2:] switch c { case 'b': value = append(value, '\b') case 'n': value = append(value, '\n') case 'r': value = append(value, '\r') case 't': value = append(value, '\t') case 'Z': value = append(value, '\032') case '0': value = append(value, '\000') case '_', '%': value = append(value, '\\') value = append(value, c) case '\\': value = append(value, '\\') case '\'', '"': value = append(value, c) default: value = append(value, c) } tail = s return } // Unquote interprets s as a single-quoted, double-quoted, // or backquoted Go string literal, returning the string value // that s quotes. For example: test=`"\"\n"` (hex: 22 5c 22 5c 6e 22) // should be converted to `"\n` (hex: 22 0a). func Unquote(s string) (t string, err error) { n := len(s) if n < 2 { return "", errors.Trace(ErrSyntax) } quote := s[0] if quote != s[n-1] { return "", errors.Trace(ErrSyntax) } s = s[1 : n-1] if quote != '"' && quote != '\'' { return "", errors.Trace(ErrSyntax) } // Avoid allocation. No need to convert if there is no '\' if strings.IndexByte(s, '\\') == -1 && strings.IndexByte(s, quote) == -1 { return s, nil } buf := make([]byte, 0, 3*len(s)/2) // Try to avoid more allocations. for len(s) > 0 { mb, ss, err := UnquoteChar(s, quote) if err != nil { return "", errors.Trace(err) } s = ss buf = append(buf, mb...) } return string(buf), nil }
{ "pile_set_name": "Github" }
/* A Bison parser, made from dfgparser.y, by GNU bison 1.75. */ /* Skeleton parser for Yacc-like parsing with Bison, Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002 Free Software Foundation, Inc. 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, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* As a special exception, when this file is copied by Bison into a Bison output file, you may use that output file without restriction. This special exception was added by the Free Software Foundation in version 1.24 of Bison. */ #ifndef BISON_DFGPARSER_H # define BISON_DFGPARSER_H /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ enum yytokentype { DFG_AND = 258, DFG_AUTHOR = 259, DFG_AXIOMS = 260, DFG_BEGPROB = 261, DFG_BY = 262, DFG_CLAUSE = 263, DFG_CLOSEBRACE = 264, DFG_CLSLIST = 265, DFG_CNF = 266, DFG_CONJECS = 267, DFG_DATE = 268, DFG_DECLLIST = 269, DFG_DESC = 270, DFG_DESCLIST = 271, DFG_DNF = 272, DFG_DOMPRED = 273, DFG_ENDLIST = 274, DFG_ENDPROB = 275, DFG_EQUAL = 276, DFG_EQUIV = 277, DFG_EXISTS = 278, DFG_FALSE = 279, DFG_FORMLIST = 280, DFG_FORMULA = 281, DFG_FORALL = 282, DFG_FREELY = 283, DFG_FUNC = 284, DFG_GENERATED = 285, DFG_GENSET = 286, DFG_HYPOTH = 287, DFG_IMPLIED = 288, DFG_IMPLIES = 289, DFG_LOGIC = 290, DFG_NAME = 291, DFG_NOT = 292, DFG_OPENBRACE = 293, DFG_OPERAT = 294, DFG_OR = 295, DFG_PREC = 296, DFG_PRED = 297, DFG_PRDICAT = 298, DFG_PRFLIST = 299, DFG_QUANTIF = 300, DFG_SATIS = 301, DFG_SETFLAG = 302, DFG_SETTINGS = 303, DFG_SYMLIST = 304, DFG_SORT = 305, DFG_SORTS = 306, DFG_STATUS = 307, DFG_STEP = 308, DFG_SUBSORT = 309, DFG_TERMLIST = 310, DFG_TRUE = 311, DFG_UNKNOWN = 312, DFG_UNSATIS = 313, DFG_VERSION = 314, DFG_NUM = 315, DFG_MINUS1 = 316, DFG_ID = 317, DFG_TEXT = 318 }; #endif #define DFG_AND 258 #define DFG_AUTHOR 259 #define DFG_AXIOMS 260 #define DFG_BEGPROB 261 #define DFG_BY 262 #define DFG_CLAUSE 263 #define DFG_CLOSEBRACE 264 #define DFG_CLSLIST 265 #define DFG_CNF 266 #define DFG_CONJECS 267 #define DFG_DATE 268 #define DFG_DECLLIST 269 #define DFG_DESC 270 #define DFG_DESCLIST 271 #define DFG_DNF 272 #define DFG_DOMPRED 273 #define DFG_ENDLIST 274 #define DFG_ENDPROB 275 #define DFG_EQUAL 276 #define DFG_EQUIV 277 #define DFG_EXISTS 278 #define DFG_FALSE 279 #define DFG_FORMLIST 280 #define DFG_FORMULA 281 #define DFG_FORALL 282 #define DFG_FREELY 283 #define DFG_FUNC 284 #define DFG_GENERATED 285 #define DFG_GENSET 286 #define DFG_HYPOTH 287 #define DFG_IMPLIED 288 #define DFG_IMPLIES 289 #define DFG_LOGIC 290 #define DFG_NAME 291 #define DFG_NOT 292 #define DFG_OPENBRACE 293 #define DFG_OPERAT 294 #define DFG_OR 295 #define DFG_PREC 296 #define DFG_PRED 297 #define DFG_PRDICAT 298 #define DFG_PRFLIST 299 #define DFG_QUANTIF 300 #define DFG_SATIS 301 #define DFG_SETFLAG 302 #define DFG_SETTINGS 303 #define DFG_SYMLIST 304 #define DFG_SORT 305 #define DFG_SORTS 306 #define DFG_STATUS 307 #define DFG_STEP 308 #define DFG_SUBSORT 309 #define DFG_TERMLIST 310 #define DFG_TRUE 311 #define DFG_UNKNOWN 312 #define DFG_UNSATIS 313 #define DFG_VERSION 314 #define DFG_NUM 315 #define DFG_MINUS1 316 #define DFG_ID 317 #define DFG_TEXT 318 #ifndef YYSTYPE #line 165 "dfgparser.y" typedef union { int number; char* string; SYMBOL symbol; SPROPERTY property; TERM term; LIST list; DFG_STATE state; BOOL bool; } yystype; /* Line 1281 of /opt/gnu//share/bison/yacc.c. */ #line 177 "dfgparser.h" # define YYSTYPE yystype #endif extern YYSTYPE dfg_lval; #endif /* not BISON_DFGPARSER_H */
{ "pile_set_name": "Github" }
@import "./src/components/base/fn"; .weui-uploader{} .weui-uploader__hd{ display: flex; padding-bottom: @weuiCellGapV; align-items: center; } .weui-uploader__title{ flex: 1; } .weui-uploader__info{ color: @weuiTextColorTips; } .weui-uploader__bd{ margin-bottom: @weuiCellGapH - (@weuiCellGapV + @weuiUploaderFileSpacing); margin-right: -@weuiUploaderFileSpacing; overflow: hidden; } .weui-uploader__files{ list-style: none; } .weui-uploader__file{ float: left; margin-right: @weuiUploaderFileSpacing; margin-bottom: @weuiUploaderFileSpacing; width: @weuiUploaderSize; height: @weuiUploaderSize; background: no-repeat center center; background-size: cover; } .weui-uploader__file_status{ position: relative; &:before{ content: " "; position: absolute; top: 0; right: 0; bottom: 0; left: 0; background-color: rgba(0, 0, 0, .5); } .weui-uploader__file-content{ display: block; } } .weui-uploader__file-content{ display: none; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); color: #FFFFFF; .weui-icon-warn{ display: inline-block; } } .weui-uploader__input-box{ float:left; position: relative; margin-right: @weuiUploaderFileSpacing; margin-bottom: @weuiUploaderFileSpacing; width: @weuiUploaderSize - @weuiUploaderBorderWidth * 2; height: @weuiUploaderSize - @weuiUploaderBorderWidth * 2; border: @weuiUploaderBorderWidth solid @weuiUploaderBorderColor; &:before, &:after{ content: " "; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: @weuiUploaderBorderColor; } &:before{ width: @weuiUploaderBorderWidth + 1; height: @weuiUploaderSize / 2; } &:after{ width: @weuiUploaderSize / 2; height: @weuiUploaderBorderWidth + 1; } &:active{ border-color: @weuiUploaderActiveBorderColor; &:before, &:after{ background-color: @weuiUploaderActiveBorderColor; } } } .weui-uploader__input{ position: absolute; z-index: 1; top: 0; left: 0; width: 100%; height: 100%; opacity: 0; .setTapColor(); }
{ "pile_set_name": "Github" }
/*============================================================================= Copyright (c) 2001-2011 Joel de Guzman 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) ==============================================================================*/ #if !defined(BOOST_SPIRIT_SUPPORT_SEPTEMBER_26_2008_0340AM) #define BOOST_SPIRIT_SUPPORT_SEPTEMBER_26_2008_0340AM #if defined(_MSC_VER) #pragma once #endif #include<boost/spirit/home/support/assert_msg.hpp> #include<boost/spirit/home/support/action_dispatch.hpp> #include<boost/spirit/home/support/argument.hpp> #include<boost/spirit/home/support/attributes.hpp> #include<boost/spirit/home/support/char_class.hpp> #include<boost/spirit/home/support/common_terminals.hpp> #include<boost/spirit/home/support/container.hpp> #include<boost/spirit/home/support/context.hpp> #include<boost/spirit/home/support/info.hpp> #include<boost/spirit/home/support/lazy.hpp> #include<boost/spirit/home/support/make_component.hpp> #include<boost/spirit/home/support/meta_compiler.hpp> #include<boost/spirit/home/support/modify.hpp> #include<boost/spirit/home/support/sequence_base_id.hpp> #include<boost/spirit/home/support/string_traits.hpp> #include<boost/spirit/home/support/terminal.hpp> #include<boost/spirit/home/support/unused.hpp> #include<boost/spirit/home/support/utf8.hpp> #endif
{ "pile_set_name": "Github" }