text
stringlengths 2
100k
| meta
dict |
---|---|
<!doctype html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<meta http-equiv="content-style-type" content="text/css">
<link rel="stylesheet" type="text/css" href="style.css">
<title>ProGuard Downloads</title>
</head>
<body>
<h2>Downloads</h2>
<b>ProGuard</b> is distributed under the terms of the GNU General Public
License. Please consult the <a href="license.html">license page</a> for more
details.
<p>
<b>ProGuard</b> is written in Java, so it requires a Java Runtime Environment
(JRE 1.4 or higher).
<p>
You can download the latest release (containing the program jar, the
documentation you're reading now, examples, and the source code) from this
location:
<p>
<center><a href="http://sourceforge.net/project/showfiles.php?group_id=54750"
target="other">Download section</a> (at <a
href="http://sourceforge.net/projects/proguard/"
target="other">SourceForge</a>)</center>
<p>
If you're still working with an older version of <b>ProGuard</b>, check out
the summary of changes below, to see if you're missing something essential.
Better look at the up-to-date <a
href="http://proguard.sourceforge.net/downloads.html">on-line version</a> if
you're reading a local copy of this page.
<p>
The download section may also contain updates with sub-minor version numbers.
These versions are typically released shortly after their parent versions, for
applying emergency fixes. Please make sure to look at those if you are
encountering any problems with recent releases.
<p>
Finally, there may be beta versions of upcoming releases. They may be of
interest too, because they typically contain any less urgent bug fixes
collected since the previous release.
<p>
<h3><div>Jul 2009</div> Version 4.4</h3>
<ul>
<li>Added new peephole optimizations.
<li>Added option <code>-optimizations</code> for fine-grained configuration of
optimizations.
<li>Added option <code>-adaptclassstrings</code> for adapting string constants
that correspond to obfuscated classes.
<li>Added option <code>-keeppackagenames</code> for keeping specified package
names from being obfuscated.
<li>Added option <code>-keepdirectories</code> for keeping specified directory
entries in output jars.
<li>Extended options <code>-dontnote</code> and <code>-dontwarn</code> for
fine-grained configuration of notes and warnings.
<li>Added option <code>-regex</code> in ReTrace, for specifying alternative
regular expressions to parse stack traces.
<li>Extended renaming of resource files based on obfuscation.
<li>Improved inlining of constant parameters and removal of unused parameters.
<li>Avoiding bug in IBM's JVM for JSE, in optimization step.
<li>Avoiding ArrayIndexOutOfBoundsException in optimization step.
<li>Fixed configuration with annotations that are not preserved themselves.
<li>Fixed preverification of invocations of super constructors with arguments
containing ternary operators.
<li>Fixed processing of unreachable exception handlers.
<li>Fixed merging of exception classes.
<li>Fixed repeated method inlining.
<li>Fixed inlining of finally blocks surrounded by large try blocks, compiled
with JDK 1.4 or earlier.
<li>Fixed optimization of complex finally blocks, compiled with JDK 1.4 or
earlier.
<li>Fixed obfuscation of anonymous class names, if <code>EnclosingMethod</code>
attributes are being kept.
<li>Fixed obfuscation of inner class names in generic types.
<li>Fixed decoding of UTF-8 strings containing special characters.
<li>Fixed copying of debug information and annotations when merging classes.
<li>Fixed writing out of unknown attributes.
<li>Fixed updating manifest files with split lines.
<li>Updated documentation and examples.
</ul>
<h3><div>Dec 2008</div> Version 4.3</h3>
<ul>
<li>Added class merging.
<li>Added static single assignment analysis.
<li>Added support for annotation and enumeration class types in configuration.
<li>Refined shrinking of fields in case of unusual
<code>-keepclassmembers</code> options.
<li>Added simplification of tail recursion calls.
<li>Added new peephole optimizations.
<li>Fixed optimization of unused variable initializations causing negative
stack sizes.
<li>Fixed optimization of unusual initialization code causing
NullPointerExceptions.
<li>Fixed optimization of half-used long and double parameters.
<li>Fixed processing of complex generics signatures.
<li>Working around suspected java compiler bug with parameter annotations on
constructors of non-static inner classes.
<li>Fixed obfuscation of classes with inner classes whose names are preserved.
<li>Fixed access of protected methods in repackaged classes.
<li>Added options <code>-classobfuscationdictionary</code> and
<code>-packageobfuscationdictionary</code>.
<li>Adapting more types of resource file names based on obfuscation.
<li>Extended warnings about incorrect dependencies.
<li>Added start-up scripts and build scripts.
<li>Updated documentation and examples.
</ul>
<h3><div>Mar 2008</div> Version 4.2</h3>
<ul>
<li>Refined data flow analysis in optimization step.
<li>Fixed handling of exceptions when inlining subroutines.
<li>Fixed inlining of incompatible code constructs between different java
versions.
<li>Fixed computation of local variable frame size.
<li>Fixed optimization of infinite loops.
<li>Fixed optimization of subroutine invocations.
<li>Fixed optimization of floating point remainder computations.
<li>Fixed removal of unused parameters in method descriptors containing arrays
of longs or doubles.
<li>Added undocumented java system properties
<code>maximum.inlined.code.length</code> (default is 8) and
<code>maximum.resulting.code.length</code> (defaults are 8000 for JSE and
2000 for JME), for expert users who read release notes.
<li>Fixed processing of generic types in Signature attributes in shrinking and
optimization steps.
<li>Fixed processing of inner class names in Signature attributes in obfuscation
step.
<li>Improved adapting resource file names following obfuscated class names.
<li>Fixed interpretation of package names in GUI.
<li>Fixed default settings for Xlets in GUI.
<li>Updated documentation and examples.
</ul>
<h3><div>Dec 2007</div> Version 4.1</h3>
<ul>
<li>Fixed shrinking of default annotation element values.
<li>Fixed optimization of invocations of methods in same class that are
accessed through extensions.
<li>Fixed optimization of invocations of synchronized methods without other
side-effects.
<li>Fixed optimization of some non-returning subroutines.
<li>Fixed handling of local variable debug information when inlining methods.
<li>Avoiding StackOverflowErrors during optimization of complex methods.
<li>Fixed obfuscation of potentially ambiguous non-primitive constants in
interfaces.
<li>Fixed preverification of some code constructs involving String, Class, and
exception types.
<li>The Ant task now allows empty <code><injars></code> and
<code><libraryjars></code> elements.
<li>Updated documentation and examples.
</ul>
<h3><div>Sep 2007</div> Version 4.0</h3>
<ul>
<li>Added preverifier for Java 6 and Java Micro Edition, with new options
<code>-microedition</code> and <code>-dontpreverify</code>.
<li>Added new option <code>-target</code> to modify java version of processed
class files.
<li>Made <code>-keep</code> options more orthogonal and flexible, with option
modifiers <code>allowshrinking</code>, <code>allowoptimization</code>, and
<code>allowobfuscation</code>.
<li>Added new wildcards for class member descriptors: "<code>***</code>",
matching any type, and "<code>...</code>", matching any number of
arguments.
<li>Added support for configuration by means of annotations.
<li>Improved shrinking of unused annotations.
<li>Added check on modification times of input and output, to avoid unnecessary
processing, with new option <code>-forceprocessing</code>.
<li>Added new options <code>-flattenpackagehierarchy</code> and
<code>-repackageclasses</code> (replacing <code>-defaultpackage</code>) to
control obfuscation of package names.
<li>Added new options <code>-adaptresourcefilenames</code> and
<code>-adaptresourcefilecontents</code>, with file filters, to update
resource files corresponding to obfuscated class names.
<li>Added detection of dynamically accessed fields and methods.
<li>Now treating <code>Exceptions</code> attributes as optional.
<li>Now respecting naming rule for nested class names
(<code>EnclosingClass$InnerClass</code>) in obfuscation step, if
<code>InnerClasses</code> attributes or <code>EnclosingMethod</code>
attributes are being kept.
<li>Added new inter-procedural optimizations: method inlining and propagation
of constant fields, constant arguments, and constant return values.
<li>Added optimized local variable allocation.
<li>Added more than 250 new peephole optimizations.
<li>Improved making classes and class members public or protected.
<li>Now printing notes on suspiciously unkept classes in parameters of
specified methods.
<li>Now printing notes for class names that don't seem to be fully qualified.
<li>Added support for uppercase filename extensions.
<li>Added tool tips to the GUI.
<li>Rewritten class file I/O code.
<li>Updated documentation and examples.
</ul>
Upgrade considerations:
<ul>
<li>Since ProGuard now treats the <code>Exceptions</code> attribute as
optional, you may have to specify <code>-keepattributes Exceptions</code>,
notably when processing code that is to be used as a library.
<li>ProGuard now preverifies code for Java Micro Edition, if you specify the
option <code>-microedition</code>. You then no longer need to process the
code with an external preverifier.
<li>You should preferably specify <code>-repackageclasses</code> instead of the
old option name <code>-defaultpackage</code>.
</ul>
<h3><div>Dec 2007</div> Version 3.11</h3>
<ul>
<li>Fixed optimization of invocations of methods in same class that are
accessed through extensions.
<li>Fixed optimization of invocations of synchronized methods without other
side-effects.
<li>Updated documentation and examples.
</ul>
<h3><div>Aug 2007</div> Version 3.10</h3>
<ul>
<li>Now handling mixed-case input class names when
<code>-dontusemixedcaseclassnames</code> is specified.
<li>Fixed optimization of synchronization on classes, as compiled by Eclipse
and Jikes.
<li>Fixed optimization of switch statements with unreachable cases.
<li>Avoiding merging subsequent identically named files.
<li>Updated documentation and examples.
</ul>
<h3><div>Jun 2007</div> Version 3.9</h3>
<ul>
<li>Fixed processing of .class constructs in Java 6.
<li>Fixed repeated processing of .class constructs.
<li>Fixed possible division by 0 in optimization step.
<li>Fixed handling of variable instructions with variable indices larger than
255.
<li>Updated documentation and examples.
</ul>
<h3><div>Mar 2007</div> Version 3.8</h3>
<ul>
<li>Fixed optimization of parameters used as local variables.
<li>Fixed obfuscation with conflicting class member names.
<li>Fixed incremental obfuscation with incomplete mapping file for library jars.
<li>Updated documentation and examples.
</ul>
<h3><div>Dec 2006</div> Version 3.7</h3>
<ul>
<li>Now accepting Java 6 class files.
<li>Fixed shrinking of partially used annotations.
<li>Improved incremental obfuscation, with new option
<code>-useuniqueclassmembernames</code>.
<li>Printing more information in case of conflicting configuration and input.
<li>Fixed optimization of repeated array length instruction.
<li>Fixed optimization of subsequent try/catch/finally blocks with return
statements.
<li>Fixed optimization of complex stack operations.
<li>Fixed optimization of simple infinite loops.
<li>Fixed optimization of expressions with constant doubles.
<li>Tuned optimization to improve size reduction after preverification.
<li>Fixed overflows of offsets in long code blocks.
<li>Now allowing class names containing dashes.
<li>Updated documentation and examples.
</ul>
<h3><div>May 2006</div> Version 3.6</h3>
<ul>
<li>No longer automatically keeping classes in parameters of specified methods
from obfuscation and optimization (introduced in version 3.4).
<li>Fixed inlining of interfaces that are used in .class constructs.
<li>Fixed removal of busy-waiting loops reading volatile fields.
<li>Fixed optimization of comparisons of known integers.
<li>Fixed optimization of known branches.
<li>Fixed optimization of method calls on arrays of interfaces.
<li>Fixed optimization of method calls without side-effects.
<li>Fixed optimization of nested try/catch/finally blocks with return
statements.
<li>Fixed initialization of library classes that only appear in descriptors.
<li>Fixed matching of primitive type wildcards in configuration.
<li>Fixed the boilerplate specification for enumerations in the GUI.
<li>Updated documentation and examples.
</ul>
<h3><div>Jan 2006</div> Version 3.5</h3>
<ul>
<li>Fixed obfuscation of class members with complex visibility.
<li>Fixed optimization bugs causing stack verification errors.
<li>Fixed optimization bug causing overridden methods to be finalized.
<li>Fixed optimization bug causing abstract method errors for retro-fitted
library methods.
<li>Fixed optimization bug evaluating code with constant long values.
<li>Fixed bug in updating of optional local variable table attributes and local
variable type table attributes after optimization.
<li>Fixed interpretation of comma-separated class names without wildcards.
<li>Updated documentation and examples.
</ul>
<h3><div>Oct 2005</div> Version 3.4</h3>
<ul>
<li>Extended optimizations: removing duplicate code within methods.
<li>Extended regular expressions for class names to comma-separated lists.
<li>Now automatically keeping classes in descriptors of kept class members.
<li>Added verbose statistics for optimizations.
<li>Added boilerplate Number optimizations in GUI.
<li>Fixed <code>Class.forName</code> detection.
<li>Fixed incremental obfuscation bug.
<li>Fixed optimization bug causing stack verification errors.
<li>Fixed optimization bugs related to removal of unused parameters.
<li>Fixed exception when optimizing code with many local variables.
<li>Fixed exception when saving configuration with initializers in GUI.
<li>Updated documentation and examples.
</ul>
<h3><div>Jun 2005</div> Version 3.3</h3>
<ul>
<li>Extended optimizations: making methods private and static when possible,
making classes static when possible, removing unused parameters.
<li>Made file names relative to the configuration files in which they are
specified. Added <code>-basedirectory</code> option.
<li>Added <code>-whyareyoukeeping</code> option to get details on why given
classes and class members are being kept.
<li>Added warnings for misplaced class files.
<li>Improved printing of notes for <code>Class.forName</code> constructs.
<li>Implemented '<code>assumenosideeffects</code>' nested element in Ant task.
<li>Improved processing of annotations.
<li>Fixed reading and writing of parameter annotations.
<li>Fixed various optimization bugs.
<li>Fixed wildcards not matching '-' character.
<li>Fixed wildcard bug and checkbox bugs in GUI.
<li>Setting file chooser defaults in GUI.
<li>Leaving room for growBox in GUI on Mac OS X.
<li>Properly closing configuration files.
<li>Updated documentation and examples.
</ul>
<h3><div>Dec 2004</div> Version 3.2</h3>
<ul>
<li>Fixed JDK5.0 processing bugs.
<li>Fixed optimization bugs.
<li>Fixed relative paths in Ant task.
<li>Improved speed of shrinking step.
<li>Updated documentation and examples.
</ul>
<h3><div>Nov 2004</div> Version 3.1</h3>
<ul>
<li>Improved obfuscation and shrinking of private class members.
<li>Added inlining of interfaces with single implementations.
<li>Added option to specify obfuscation dictionary.
<li>Added option to read package visible library class members.
<li>Extended support for JDK5.0 attributes.
<li>Fixed various optimization bugs.
<li>Modified Ant task to accept paths instead of filesets.
<li>Fixed two Ant task bugs.
<li>Updated documentation and examples.
</ul>
<h3><div>Aug 2004</div> Version 3.0</h3>
<ul>
<li>Added bytecode optimization step, between shrinking step and obfuscation
step.
<li>Generalized filtered recursive reading and writing of jars, wars, ears,
zips, and directories.
<li>Added support for grouping input and output jars, wars, ears, zips, and
directories.
<li>Added support for applying mapping files to library classes.
<li>Removed <code>-resourcejars</code> option. Resources should now be read
using regular <code>-injars</code> options, using filters if necessary.
<li>Rewrote Ant task. Input and output modification dates are not checked at
the moment. Minor changes in XML schema:
<ul>
<li>Filters now specified using attributes.
<li>'<code>outjars</code>' now nested element instead of attribute.
<li>'<code>type</code>' attribute of <code><method></code> element no
longer defaults to '<code>void</code>'.
<li><code><</code> and <code>></code> characters now have to be
encoded in embedded configurations.
<li><code><proguardconfiguration></code> task no longer accepts
attributes.
</ul>
<li>Updated J2ME WTK plugin, now customizable through configuration file.
<li>Updated GUI.
<li>Fixed various processing bugs.
<li>Fixed ReTrace parsing bugs.
<li>Improved jar compression.
<li>Updated documentation and examples.
</ul>
<h3><div>Mar 2004</div> Version 2.1</h3>
<ul>
<li>Added support for JDK1.5 classes.
<li>Added additional wildcard for matching primitive types.
<li>Added possibility to switch off notes about duplicate class definitions.
<li>Fixed use of multiple filters on output jars.
<li>Fixed option to keep all attributes.
<li>Fixed various Ant task bugs.
<li>Updated documentation and examples.
</ul>
<h3><div>Dec 2003</div> Version 2.0</h3>
<ul>
<li>Added a graphical user interface for ProGuard and ReTrace.
<li>Added <code>-applymapping</code> option for incremental obfuscation.
<li>Added support for filtering input and output files.
<li>Added support for the J++ <code>SourceDir</code> attribute.
<li>Improved detection of <code>.class</code> constructs.
<li>Improved handling of misplaced manifest files.
<li>Improved implementation of ReTrace.
<li>Worked around String UTF-8 encoding bug affecting foreign characters.
<li>Fixed exception when ignoring warnings.
<li>Fixed various Ant task bugs.
<li>Updated documentation and examples.
</ul>
<h3><div>Aug 2003</div> Version 1.7</h3>
<ul>
<li>Fixed various Ant task bugs.
<li>Fixed ClassCastException due to explicitly used abstract classes with
implicitly used interfaces targeted at JRE1.2 (the default in JDK1.4).
<li>Fixed <code>-defaultpackage</code> bug for protected classes and class
members.
<li>Fixed ReTrace bug when retracing without line number tables.
<li>Worked around zip package problems with duplicate out entries and rogue
manifest files.
<li>Added work-around for handling malformed legacy interface class files.
<li>Updated documentation and examples.
</ul>
<h3><div>May 2003</div> Version 1.6</h3>
<ul>
<li>Added support for Ant.
<li>Added support for the J2ME Wireless Toolkit.
<li>Added support for reading and writing directory hierarchies.
<li>Added option for specifying resource jars and directories.
<li>Added support for wildcards in class member specifications.
<li>Improved handling of the <code>-defaultpackage</code> option.
<li>Improved stack trace parsing in ReTrace tool.
<li>Fixed processing of libraries containing public as well as non-public
extensions of non-public classes.
<li>Fixed examples for processing libraries, midlets, and serializable code.
<li>Updated documentation and examples.
</ul>
<h3><div>Jan 2003</div> Version 1.5</h3>
<ul>
<li>Fixed processing of retrofitted library interfaces.
<li>Fixed processing of <code>.class</code> constructs in internal classes
targeted at JRE1.2 (the default in JDK1.4).
<li>Fixed <code>-dump</code> option when <code>-outjar</code> option is not
present.
<li>Updated documentation and examples.
</ul>
<h3><div>Nov 2002</div> Version 1.4</h3>
<ul>
<li>Now copying resource files over from the input jars to the output jar.
<li>Added option to obfuscate using lower-case class names only.
<li>Added better option for obfuscating native methods.
<li>Added option not to ignore non-public library classes.
<li>Added automatic <code>.class</code> detection for classes compiled with
Jikes.
<li>Updated documentation and examples.
</ul>
<h3><div>Sep 2002</div> Version 1.3</h3>
<ul>
<li>Added support for wildcards in class names.
<li>Added tool to de-obfuscate stack traces.
<li>Added options to print processing information to files.
<li>Added option to rename source file attributes.
<li>Fixed processing of implicitly used interfaces targeted at JRE1.2 (the
default in JDK1.4)
<li>Fixed processing of configurations with negated access modifiers.
<li>Fixed duplicate class entry bug.
<li>Updated documentation and examples.
</ul>
<h3><div>Aug 2002</div> Version 1.2</h3>
<ul>
<li>Improved speed.
<li>Fixed processing of classes targeted at JRE1.2 (the default in JDK1.4)
with references to their own subclasses.
<li>Fixed processing of static initializers in J2ME MIDP applications.
<li>Fixed processing of retrofitted interfaces (again).
<li>Added more flexible handling of white space in configuration.
<li>Updated documentation.
</ul>
<h3><div>Jul 2002</div> Version 1.1</h3>
<ul>
<li>Added automatic detection of <code>Class.forName("MyClass")</code>,
<code>MyClass.class</code>, and
<code>(MyClass)Class.forName(variable).newInstance()</code> constructs.
This greatly simplifies configuration.
<li>Added options to keep class names and class member names without affecting
any shrinking. They are mostly useful for native methods and serializable
classes.
<li>Fixed processing of retrofitted interfaces.
<li>Added handling of missing/invalid manifest file in input jar.
<li>Updated documentation and examples.
</ul>
<h3><div>Jun 2002</div> Version 1.0</h3>
<ul>
<li>First public release, based on class parsing code from Mark Welsh's
<b>RetroGuard</b>.
</ul>
<hr>
<address>
Copyright © 2002-2009
<a href="http://www.graphics.cornell.edu/~eric/">Eric Lafortune</a>.
</address>
</body>
</html>
| {
"pile_set_name": "Github"
} |
// This is a generated file from running the "createIcons" script. This file should not be updated manually.
import React, { forwardRef } from "react";
import { SVGIcon, SVGIconProps } from "@react-md/icon";
export const DoNotDisturbAltSVGIcon = forwardRef<SVGSVGElement, SVGIconProps>(
function DoNotDisturbAltSVGIcon(props, ref) {
return (
<SVGIcon {...props} ref={ref}>
<path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zM4 12c0-4.4 3.6-8 8-8 1.8 0 3.5.6 4.9 1.7L5.7 16.9C4.6 15.5 4 13.8 4 12zm8 8c-1.8 0-3.5-.6-4.9-1.7L18.3 7.1C19.4 8.5 20 10.2 20 12c0 4.4-3.6 8-8 8z" />
</SVGIcon>
);
}
);
| {
"pile_set_name": "Github"
} |
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.mail.internal;
import org.xwiki.mail.MailStatusResult;
/**
* Extension of {@link MailStatusResult} to make it updateable; more specifically to update the number of mails to
* send (which can be known only on the Prepare Thread when all mails have been iterated over and prepared) and also
* to increment the number of mails sent (successfully or not).
*
* @version $Id: 65d2df3fed71ef7d4ade67c69bfa27c1babcd3e8 $
* @since 7.1M2
*/
public interface UpdateableMailStatusResult extends MailStatusResult
{
/**
* @param totalSize the number of mails to send
*/
void setTotalSize(long totalSize);
/**
* Increment by one the number of mails sent (successfully or not).
*/
void incrementCurrentSize();
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="com.fangxuele.tool.push.ui.form.msg.MaSubscribeMsgForm">
<grid id="27dc6" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="20" y="20" width="500" height="400"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<grid id="b0ec9" binding="templateMsgPanel" layout-manager="GridLayoutManager" row-count="2" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="10" left="15" bottom="0" right="0"/>
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="7" hsize-policy="7" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="empty" title="小程序-订阅消息编辑">
<font style="1"/>
</border>
<children>
<grid id="4d00f" binding="templateMsgDataPanel" layout-manager="GridLayoutManager" row-count="3" column-count="4" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="10" left="0" bottom="0" right="0"/>
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="7" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="etched" title="模板变量(可使用"$ENTER$"作为换行符)">
<font style="1"/>
</border>
<children>
<component id="e84d1" class="javax.swing.JTextField" binding="templateDataNameTextField">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="7" anchor="8" fill="1" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
<properties>
<toolTipText value="当消息类型是模板消息时的示例:first或者keyword1或者remark之类的"/>
</properties>
</component>
<component id="514d7" class="javax.swing.JTextField" binding="templateDataValueTextField">
<constraints>
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="7" anchor="8" fill="1" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
<properties/>
</component>
<component id="d59db" class="javax.swing.JTextField" binding="templateDataColorTextField">
<constraints>
<grid row="1" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="7" anchor="8" fill="1" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
<properties>
<toolTipText value="示例值:FF0000"/>
</properties>
</component>
<component id="26b48" class="javax.swing.JButton" binding="templateMsgDataAddButton">
<constraints>
<grid row="1" column="3" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<icon value="icon/add.png"/>
<text value=""/>
</properties>
</component>
<component id="585df" class="javax.swing.JTable" binding="templateMsgDataTable">
<constraints>
<grid row="2" column="0" row-span="1" col-span="4" vsize-policy="7" hsize-policy="7" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<autoCreateColumnsFromModel value="true"/>
<autoCreateRowSorter value="true"/>
<gridColor color="-12236470"/>
<rowHeight value="36"/>
</properties>
</component>
<component id="ad3ea" class="javax.swing.JLabel" binding="templateMsgNameLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<labelFor value="e84d1"/>
<text value="name"/>
<toolTipText value="当消息类型是模板消息时的示例:first或者keyword1或者remark之类的"/>
</properties>
</component>
<component id="623c9" class="javax.swing.JLabel" binding="templateMsgValueLabel">
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<labelFor value="514d7"/>
<text value="value"/>
</properties>
</component>
<component id="6dfe1" class="javax.swing.JLabel" binding="templateMsgColorLabel">
<constraints>
<grid row="0" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<labelFor value="d59db"/>
<text value="color"/>
<toolTipText value="示例值:FF0000"/>
</properties>
</component>
</children>
</grid>
<grid id="622c0" layout-manager="GridLayoutManager" row-count="2" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="5" right="0"/>
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="bacc8" class="javax.swing.JLabel" binding="templateIdLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<labelFor value="fa9e4"/>
<text value="模板ID *"/>
</properties>
</component>
<component id="fa9e4" class="javax.swing.JTextField" binding="msgTemplateIdTextField">
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="7" anchor="8" fill="1" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
<properties/>
</component>
<component id="19629" class="javax.swing.JLabel" binding="templateUrlLabel">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<labelFor value="11d29"/>
<text value="跳转页面"/>
</properties>
</component>
<component id="11d29" class="javax.swing.JTextField" binding="msgTemplateUrlTextField">
<constraints>
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="7" anchor="8" fill="1" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
<properties/>
</component>
</children>
</grid>
</children>
</grid>
</children>
</grid>
</form>
| {
"pile_set_name": "Github"
} |
///////////////////////////////////////////////////////////////////////////////
// Name: src/common/accelcmn.cpp
// Purpose: implementation of platform-independent wxAcceleratorEntry parts
// Author: Vadim Zeitlin
// Created: 2007-05-05
// Copyright: (c) 2007 Vadim Zeitlin <[email protected]>
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// for compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#if wxUSE_ACCEL
#ifndef WX_PRECOMP
#include "wx/accel.h"
#include "wx/string.h"
#include "wx/intl.h"
#include "wx/log.h"
#include "wx/crt.h"
#endif //WX_PRECOMP
wxAcceleratorTable wxNullAcceleratorTable;
// ============================================================================
// wxAcceleratorEntry implementation
// ============================================================================
wxGCC_WARNING_SUPPRESS(missing-field-initializers)
static const struct wxKeyName
{
wxKeyCode code;
const char *name;
const char *display_name;
} wxKeyNames[] =
{
{ WXK_DELETE, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Delete") },
{ WXK_DELETE, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Del") },
{ WXK_BACK, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Back"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Backspace") },
{ WXK_INSERT, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Insert") },
{ WXK_INSERT, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Ins") },
{ WXK_RETURN, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Enter") },
{ WXK_RETURN, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Return") },
{ WXK_PAGEUP, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("PageUp"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Page Up") },
{ WXK_PAGEDOWN, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("PageDown"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Page Down") },
{ WXK_PAGEUP, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("PgUp") },
{ WXK_PAGEDOWN, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("PgDn") },
{ WXK_LEFT, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Left"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Left") },
{ WXK_RIGHT, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Right"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Right") },
{ WXK_UP, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Up"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Up") },
{ WXK_DOWN, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Down"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Down") },
{ WXK_HOME, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Home") },
{ WXK_END, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("End") },
{ WXK_SPACE, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Space") },
{ WXK_TAB, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Tab") },
{ WXK_ESCAPE, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Esc") },
{ WXK_ESCAPE, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Escape") },
{ WXK_CANCEL, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Cancel") },
{ WXK_CLEAR, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Clear") },
{ WXK_MENU, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Menu") },
{ WXK_PAUSE, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Pause") },
{ WXK_CAPITAL, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Capital") },
{ WXK_SELECT, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Select") },
{ WXK_PRINT, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Print") },
{ WXK_EXECUTE, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Execute") },
{ WXK_SNAPSHOT, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Snapshot") },
{ WXK_HELP, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Help") },
{ WXK_ADD, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Add") },
{ WXK_SEPARATOR, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Separator") },
{ WXK_SUBTRACT, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Subtract") },
{ WXK_DECIMAL, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Decimal") },
{ WXK_DIVIDE, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Divide") },
{ WXK_NUMLOCK, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Num_lock"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Num Lock") },
{ WXK_SCROLL, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Scroll_lock"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Scroll Lock") },
{ WXK_NUMPAD_SPACE, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("KP_Space"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Num Space") },
{ WXK_NUMPAD_TAB, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("KP_Tab"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Num Tab") },
{ WXK_NUMPAD_ENTER, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("KP_Enter"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Num Enter") },
{ WXK_NUMPAD_HOME, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("KP_Home"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Num Home") },
{ WXK_NUMPAD_LEFT, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("KP_Left"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Num left") },
{ WXK_NUMPAD_UP, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("KP_Up"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Num Up") },
{ WXK_NUMPAD_RIGHT, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("KP_Right"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Num Right") },
{ WXK_NUMPAD_DOWN, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("KP_Down"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Num Down") },
{ WXK_NUMPAD_PAGEUP, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("KP_PageUp"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Num Page Up") },
{ WXK_NUMPAD_PAGEDOWN, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("KP_PageDown"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Num Page Down") },
{ WXK_NUMPAD_PAGEUP, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("KP_Prior") },
{ WXK_NUMPAD_PAGEDOWN, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("KP_Next") },
{ WXK_NUMPAD_END, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("KP_End"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Num End") },
{ WXK_NUMPAD_BEGIN, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("KP_Begin"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Num Begin") },
{ WXK_NUMPAD_INSERT, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("KP_Insert"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Num Insert") },
{ WXK_NUMPAD_DELETE, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("KP_Delete"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Num Delete") },
{ WXK_NUMPAD_EQUAL, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("KP_Equal"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Num =") },
{ WXK_NUMPAD_MULTIPLY, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("KP_Multiply"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Num *") },
{ WXK_NUMPAD_ADD, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("KP_Add"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Num +") },
{ WXK_NUMPAD_SEPARATOR, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("KP_Separator"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Num ,") },
{ WXK_NUMPAD_SUBTRACT, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("KP_Subtract"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Num -") },
{ WXK_NUMPAD_DECIMAL, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("KP_Decimal"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Num .") },
{ WXK_NUMPAD_DIVIDE, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("KP_Divide"), /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Num /") },
{ WXK_WINDOWS_LEFT, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Windows_Left") },
{ WXK_WINDOWS_RIGHT, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Windows_Right") },
{ WXK_WINDOWS_MENU, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Windows_Menu") },
{ WXK_COMMAND, /*TRANSLATORS: Name of keyboard key*/ wxTRANSLATE("Command") },
};
wxGCC_WARNING_RESTORE(missing-field-initializers)
// return true if the 2 strings refer to the same accel
//
// as accels can be either translated or not, check for both possibilities and
// also compare case-insensitively as the key names case doesn't count
static inline bool CompareAccelString(const wxString& str, const char *accel)
{
return str.CmpNoCase(accel) == 0
#if wxUSE_INTL
|| str.CmpNoCase(wxGetTranslation(accel)) == 0
#endif
;
}
// return prefixCode+number if the string is of the form "<prefix><number>" and
// 0 if it isn't
//
// first and last parameter specify the valid domain for "number" part
static int IsNumberedAccelKey(const wxString& str,
const char *prefix,
wxKeyCode prefixCode,
unsigned first,
unsigned last)
{
const size_t lenPrefix = wxStrlen(prefix);
if ( !CompareAccelString(str.Left(lenPrefix), prefix) )
return 0;
unsigned long num;
if ( !str.Mid(lenPrefix).ToULong(&num) )
return 0;
if ( num < first || num > last )
{
// this must be a mistake, chances that this is a valid name of another
// key are vanishingly small
wxLogDebug(wxT("Invalid key string \"%s\""), str.c_str());
return 0;
}
return prefixCode + num - first;
}
/* static */
bool
wxAcceleratorEntry::ParseAccel(const wxString& text, int *flagsOut, int *keyOut)
{
// the parser won't like trailing spaces
wxString label = text;
label.Trim(true);
// For compatibility with the old wx versions which accepted (and actually
// even required) a TAB character in the string passed to this function we
// ignore anything up to the first TAB. Notice however that the correct
// input consists of just the accelerator itself and nothing else, this is
// done for compatibility and compatibility only.
int posTab = label.Find(wxT('\t'));
if ( posTab == wxNOT_FOUND )
posTab = 0;
else
posTab++;
// parse the accelerator string
int accelFlags = wxACCEL_NORMAL;
wxString current;
for ( size_t n = (size_t)posTab; n < label.length(); n++ )
{
if ( (label[n] == '+') || (label[n] == '-') )
{
if ( CompareAccelString(current, wxTRANSLATE("ctrl")) )
accelFlags |= wxACCEL_CTRL;
else if ( CompareAccelString(current, wxTRANSLATE("alt")) )
accelFlags |= wxACCEL_ALT;
else if ( CompareAccelString(current, wxTRANSLATE("shift")) )
accelFlags |= wxACCEL_SHIFT;
else if ( CompareAccelString(current, wxTRANSLATE("rawctrl")) )
accelFlags |= wxACCEL_RAW_CTRL;
else // not a recognized modifier name
{
// we may have "Ctrl-+", for example, but we still want to
// catch typos like "Crtl-A" so only give the warning if we
// have something before the current '+' or '-', else take
// it as a literal symbol
if ( current.empty() )
{
current += label[n];
// skip clearing it below
continue;
}
else
{
wxLogDebug(wxT("Unknown accel modifier: '%s'"),
current.c_str());
}
}
current.clear();
}
else // not special character
{
current += (wxChar) wxTolower(label[n]);
}
}
int keyCode;
const size_t len = current.length();
switch ( len )
{
case 0:
wxLogDebug(wxT("No accel key found, accel string ignored."));
return false;
case 1:
// it's just a letter
keyCode = current[0U];
// ...or maybe not. A translation may be single character too (e.g.
// Chinese), but if it's a Latin character, that's unlikely
if ( keyCode < 128 )
{
// if the key is used with any modifiers, make it an uppercase one
// because Ctrl-A and Ctrl-a are the same; but keep it as is if it's
// used alone as 'a' and 'A' are different
if ( accelFlags != wxACCEL_NORMAL )
keyCode = wxToupper(keyCode);
break;
}
wxFALLTHROUGH;
default:
keyCode = IsNumberedAccelKey(current, wxTRANSLATE("F"),
WXK_F1, 1, 12);
if ( !keyCode )
{
for ( size_t n = 0; n < WXSIZEOF(wxKeyNames); n++ )
{
const wxKeyName& kn = wxKeyNames[n];
if ( CompareAccelString(current, kn.name) )
{
keyCode = kn.code;
break;
}
}
}
if ( !keyCode )
keyCode = IsNumberedAccelKey(current, wxTRANSLATE("KP_"),
WXK_NUMPAD0, 0, 9);
if ( !keyCode )
keyCode = IsNumberedAccelKey(current, wxTRANSLATE("SPECIAL"),
WXK_SPECIAL1, 1, 20);
if ( !keyCode )
{
wxLogDebug(wxT("Unrecognized accel key '%s', accel string ignored."),
current.c_str());
return false;
}
}
wxASSERT_MSG( keyCode, wxT("logic error: should have key code here") );
if ( flagsOut )
*flagsOut = accelFlags;
if ( keyOut )
*keyOut = keyCode;
return true;
}
/* static */
wxAcceleratorEntry *wxAcceleratorEntry::Create(const wxString& str)
{
const wxString accelStr = str.AfterFirst('\t');
if ( accelStr.empty() )
{
// It's ok to pass strings not containing any accelerators at all to
// this function, wxMenuItem code does it and we should just return
// NULL in this case.
return NULL;
}
int flags,
keyCode;
if ( !ParseAccel(accelStr, &flags, &keyCode) )
return NULL;
return new wxAcceleratorEntry(flags, keyCode);
}
bool wxAcceleratorEntry::FromString(const wxString& str)
{
return ParseAccel(str, &m_flags, &m_keyCode);
}
namespace
{
wxString PossiblyLocalize(const wxString& str, bool localize)
{
return localize ? wxGetTranslation(str) : str;
}
}
wxString wxAcceleratorEntry::AsPossiblyLocalizedString(bool localized) const
{
wxString text;
int flags = GetFlags();
if ( flags & wxACCEL_ALT )
text += PossiblyLocalize(wxTRANSLATE("Alt+"), localized);
if ( flags & wxACCEL_CTRL )
text += PossiblyLocalize(wxTRANSLATE("Ctrl+"), localized);
if ( flags & wxACCEL_SHIFT )
text += PossiblyLocalize(wxTRANSLATE("Shift+"), localized);
#if defined(__WXMAC__) || defined(__WXCOCOA__)
if ( flags & wxACCEL_RAW_CTRL )
text += PossiblyLocalize(wxTRANSLATE("RawCtrl+"), localized);
#endif
const int code = GetKeyCode();
if ( code >= WXK_F1 && code <= WXK_F12 )
text << PossiblyLocalize(wxTRANSLATE("F"), localized)
<< code - WXK_F1 + 1;
else if ( code >= WXK_NUMPAD0 && code <= WXK_NUMPAD9 )
text << PossiblyLocalize(wxTRANSLATE("KP_"), localized)
<< code - WXK_NUMPAD0;
else if ( code >= WXK_SPECIAL1 && code <= WXK_SPECIAL20 )
text << PossiblyLocalize(wxTRANSLATE("SPECIAL"), localized)
<< code - WXK_SPECIAL1 + 1;
else // check the named keys
{
size_t n;
for ( n = 0; n < WXSIZEOF(wxKeyNames); n++ )
{
const wxKeyName& kn = wxKeyNames[n];
if ( code == kn.code )
{
text << PossiblyLocalize(kn.display_name ? kn.display_name : kn.name, localized);
break;
}
}
if ( n == WXSIZEOF(wxKeyNames) )
{
// must be a simple key
if (
#if !wxUSE_UNICODE
// we can't call wxIsalnum() for non-ASCII characters in ASCII
// build as they're only defined for the ASCII range (or EOF)
wxIsascii(code) &&
#endif // ANSI
wxIsprint(code) )
{
text << (wxChar)code;
}
else
{
wxFAIL_MSG( wxT("unknown keyboard accelerator code") );
}
}
}
return text;
}
wxAcceleratorEntry *wxGetAccelFromString(const wxString& label)
{
return wxAcceleratorEntry::Create(label);
}
#endif // wxUSE_ACCEL
| {
"pile_set_name": "Github"
} |
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.jsdt.internal.corext.fix;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.eclipse.wst.jsdt.core.dom.rewrite.ITrackedNodePosition;
import org.eclipse.wst.jsdt.internal.corext.fix.LinkedProposalPositionGroup.PositionInformation;
public class LinkedProposalModel {
private Map/*<String, PositionGroup>*/ fPositionGroups;
private LinkedProposalPositionGroup.PositionInformation fEndPosition;
public void addPositionGroup(LinkedProposalPositionGroup positionGroup) {
if (positionGroup == null) {
throw new IllegalArgumentException("positionGroup must not be null"); //$NON-NLS-1$
}
if (fPositionGroups == null) {
fPositionGroups= new HashMap();
}
fPositionGroups.put(positionGroup.getGroupId(), positionGroup);
}
public LinkedProposalPositionGroup getPositionGroup(String groupId, boolean createIfNotExisting) {
LinkedProposalPositionGroup group= fPositionGroups != null ? (LinkedProposalPositionGroup) fPositionGroups.get(groupId) : null;
if (createIfNotExisting && group == null) {
group= new LinkedProposalPositionGroup(groupId);
addPositionGroup(group);
}
return group;
}
public Iterator getPositionGroupIterator() {
if (fPositionGroups == null) {
return new Iterator() {
public boolean hasNext() {return false;}
public Object next() {return null;}
public void remove() {}
};
}
return fPositionGroups.values().iterator();
}
/**
* Sets the end position of the linked mode to the end of the passed range.
* @param position The position that describes the end position of the linked mode.
*/
public void setEndPosition(PositionInformation position) {
fEndPosition= position;
}
public void setEndPosition(ITrackedNodePosition position) {
setEndPosition(LinkedProposalPositionGroup.createPositionInformation(position, false));
}
public PositionInformation getEndPosition() {
return fEndPosition;
}
public boolean hasLinkedPositions() {
return fPositionGroups != null && !fPositionGroups.isEmpty();
}
public void clear() {
fPositionGroups= null;
fEndPosition= null;
}
}
| {
"pile_set_name": "Github"
} |
News
====
2.0.15 (2014-04-17)
-------------------
- Fixed #73. Python < 2.6.5 does not support unicode as keyword arguments names.
[Stepan Kolesnik]
- Fixed #84 Application cookies for localhost are no longer ignored
[gawel]
- Fixed #89 remove WSGIWarning: You are not supposed to send a body in a DELETE
request because we now have a good reason for that. See http://bit.ly/1tb3yxW
[gawel]
- Fixed #92 You can now override TestApp.JSONEncoder to use a custom encoder
[gawel]
- Fixed #93 Support basic authentication
[gawel]
- Fixed #103 Broken "Edit me on GitHub" links in documentation
[gawel]
- Fixed #106 Make wrapping the app in the lint middleware optional
[dmlayton]
- Fixed #107 Explicit error message when WSGIProxy2 is not installer
[gawel]
- Fixed #108 cgi.parse_qsl is pending deprecation
[gawel]
2.0.14 (2014-01-23)
-------------------
- Allow `.select()` on <select>s and <select multiple>s.
[Markus Bertheau]
2.0.13 (2014-01-23)
-------------------
- Allow selecting <select> options by text
[Markus Bertheau]
2.0.12 (2014-01-17)
-------------------
- Ignore the `value` attribute of file inputs
[Markus Bertheau]
- Allow selecting the form submit button by its value
[Markus Bertheau]
2.0.11 (2013-12-29)
-------------------
- Depend on `unittest2` only for Python versions lower than 2.7
[iElectric]
- Add an optional parameter to `TestApp`, allowing the user to specify the
parser used by BeautifulSoup
[lyndsysimon]
2.0.10 (2013-11-14)
-------------------
- Make StopableWSGIServer thread daemonic
[lrowe]
2.0.9 (2013-09-18)
------------------
- Make sure Upload.content_type is not ignored
https://github.com/Pylons/webtest/pull/88
[Marius Gedminas]
2.0.8 (2013-09-17)
------------------
- Allow checking/unchecking a set of same-named checkboxes by assigning a list of values.
[carljm]
- fix "AttributeError: 'InputWrapper' object has no attribute 'seek'"
[iElectric]
- Added `xhr=True` parameter to `TestApp.get`, `TestApp.post`, `TestApp.head`, `TestApp.delete`
[kharandziuk]
- Remove old (and broken?) casperjs/selenium backward compat imports. Fix
https://github.com/gawel/webtest-selenium/issues/9
[gawel]
- Allow optionally specifying the MIME type of an uploaded form file. Fixes #86
[Marius Gedminas]
2.0.7 (2013-08-07)
------------------
- Detect JSON if mimetype ends with +json, such as application/vnd.webtest+json
[homm]
- Fixed #72. Use WSGIServer new api even if there waitress has backward compat.
[gawel]
- Fixed #50. Corrected default value for the delete params argument.
[noonat]
- Be sure to decode the content if it is gziped before returning it
[Alexis Métaireau]
2.0.6 (2013-05-23)
------------------
- fixed #64. cookiejar api has changed in python3.3 [gawel]
- allow to use a fixed StopableWSGIServer [gawel]
- Do not alter the BeautifulSoup object when parsing forms. [Georges
Dubus]
- Remove first newline while parse textarea block, how modern browsers does.
[Victor Safronovich] pull #69
2.0.5 (2013-04-12)
------------------
* Ignore select.error (not socket.error) following
StopableWSGIServer.shutdown. [Laurence Rowe]
* Handle the short form of <select multiple> [Marius Gedminas]
2.0.4 (2013-03-28)
------------------
* Correctly handle <option> elements with no value attribute
[Marius Gedminas]
* Ignore socket.error following StopableWSGIServer.shutdown. [Laurence Rowe]
* <button> without type='submit' attribute is treated as Submit
control [Andrey Lebedev].
* Support for redirects having relative "Location" header [Andrey Lebedev]
2.0.3 (2013-03-19)
------------------
* Treat strings in the WSGI environment as native strings, compliant with
PEP-3333. [wosc]
2.0.2 (2013-03-15)
------------------
* Allow TestResponse.click() to match HTML content again. [ender672]
* Support secure cookies [Andrey Lebedev]
2.0.1 (2013-03-05)
------------------
* Added Pasword field [diarmuidbourke]
* re-allow to use unknow field type. Like ``type="email"``. [gawel]
* Don't let BeautifulSoup use lxml. Fix GH-51 [kmike]
* added :meth:`webtest.response.TestResponse.maybe_follow` method [kmike]
2.0 (2013-02-25)
----------------
* drop zc.buildout usage for development, now using only virtualenv
[Domen Kožar]
* Backward incompatibility : Removed the ``anchor`` argument of
:meth:`webtest.response.TestResponse.click` and the ``button`` argument of
:meth:`webtest.response.TestResponse.clickbutton`. It is for the greater good.
[madjar]
* Rewrote API documentation [Domen Kožar]
* Added `wsgiproxy` support to do HTTP request to an URL [gawel]
* Use BeautifulSoup4 to parse forms [gawel]
* Added `webtest.app.TestApp.patch_json` [gawel]
* Implement `webtest.app.TestApp.cookiejar` support and kindof keep
`webtest.app.TestApp.cookies` functionality. `webtest.app.TestApp.cookies`
should be treated as read-only.
[Domen Kožar]
* Split Selenium integration into separate package webtest-selenium
[gawel]
* Split casperjs integration into separate package webtest-casperjs
[gawel]
* Test coverage improvements [harobed, cdevienne, arthru, Domen Kožar, gawel]
* Fully implement decoding of HTML entities
* Fix tox configuration
1.4.2
-----
* fix tests error due to CLRF in a tarball
1.4.1
-----
* add travis-ci
* migrate repository to https://github.com/Pylons/webtest
* Fix a typo in apps.py: selectedIndicies
* Preserve field order during parsing (support for deform and such)
* allow equals sign in the cookie by spliting name-value-string pairs on
the first '=' sign as per
http://tools.ietf.org/html/rfc6265#section-5.2
* fix an error when you use AssertionError(response) with unicode chars in
response
1.4.0
-----
* added webtest.ext - allow to use casperjs
1.3.6
------
* fix `#42 <https://bitbucket.org/ianb/webtest/issue/42>`_ Check uppercase
method.
* fix `#36 <https://bitbucket.org/ianb/webtest/issue/36>`_ Radio can use forced
value.
* fix `#24 <https://bitbucket.org/ianb/webtest/issue/24>`_ Include test
fixtures.
* fix bug when trying to print a response which contain some unicode chars
1.3.5
------
* fix `#39 <https://bitbucket.org/ianb/webtest/issue/39>`_ Add PATCH to
acceptable methods.
1.3.4
-----
* fix `#33 <https://bitbucket.org/ianb/webtest/issue/33>`_ Remove
CaptureStdout. Do nothing and break pdb
* use OrderedDict to store fields in form. See
`#31 <https://bitbucket.org/ianb/webtest/issue/31>`_
* fix `#38 <https://bitbucket.org/ianb/webtest/issue/38>`_ Allow to post falsey
values.
* fix `#37 <https://bitbucket.org/ianb/webtest/issue/37>`_ Allow
Content-Length: 0 without Content-Type
* `fix #30 <https://bitbucket.org/ianb/webtest/issue/30>`_ bad link to pyquery
documentation
* Never catch NameError during iteration
1.3.3
-----
* added ``post_json``, ``put_json``, ``delete_json``
* fix `#25 <https://bitbucket.org/ianb/webtest/issue/25>`_ params dictionary of
webtest.AppTest.post() does not support unicode values
1.3.2
-----
* improve showbrowser. fixed `#23 <https://bitbucket.org/ianb/webtest/issue/23>`_
* print_stderr fail with unicode string on python2
1.3.1
-----
* Added .option() `#20 <https://bitbucket.org/ianb/webtest/issue/20>`_
* Fix #21
* Full python3 compat
1.3
---
* Moved TestApp to app.py
* Added selenium testing framework. See :mod:`~webtest.sel` module.
1.2.4
------
* Accept lists for ``app.post(url, params=[...])``
* Allow to use url that starts with the SCRIPT_NAME found in extra_environ
* Fix `#16 <https://bitbucket.org/ianb/webtest/issue/16>`_ Default
content-type is now correctly set to `application/octet-stream`
* Fix `#14 and #18 <https://bitbucket.org/ianb/webtest/issue/18>`_ Allow to use
`.delete(params={})`
* Fix `#12 <https://bitbucket.org/ianb/webtest/issue/12>`_
1.2.3
-----
* Fix `#10
<http://bitbucket.org/ianb/webtest/issue/10/testapprequest-method-overwrites-specifics-with-testapp-scoped>`_,
now `TestApp.extra_environ` doesn't take precedence over a WSGI
environment passed in through the request.
* Removed stray print
1.2.2
-----
* Revert change to cookies that would add ``"`` around cookie values.
* Added property :meth:`webtest.Response.pyquery` which returns a
`PyQuery <http://pyquery.org/>`_ object.
* Set base_url on ``resp.lxml``
* Include tests and docs in tarball.
* Fix sending in webob.Request (or webtest.TestRequest) objects.
* Fix handling forms with file uploads, when no file is selected.
* Added ``extra_environ`` argument to :meth:`webtest.TestResponse.click`.
* Fixed/added wildcard statuses, like ``status="4*"``
* Fix file upload fields in forms: allow upload field to be empty.
* Added support for single-quoted html attributes.
* `TestResponse` now has unicode support. It is turned on by default
for all responses with charset information. **This is backward
incompatible change** if you rely (e.g. in doctests) on parsed
form fields or responses returned by `json` and `lxml` methods
being encoded strings when charset header is in response. In order
to switch to old behaviour pass `use_unicode=False` flag to
`TestApp` constructor.
1.2.1
-----
* Added method :meth:`TestApp.request`, which can be used for
sending requests with different methods (e.g., ``MKCOL``). This
method sends all its keyword arguments to
:meth:`webtest.TestRequest.blank` and then executes the request.
The parameters are somewhat different than other methods (like
:meth:`webtest.TestApp.get`), as they match WebOb's attribute
names exactly (the other methods were written before WebOb existed).
* Removed the copying of stdout to stderr during requests.
* Fix file upload fields in forms (`#340
<http://trac.pythonpaste.org/pythonpaste/ticket/340>`_) -- you could
upload files with :meth:`webtest.TestApp.post`, but if you use
``resp.form`` file upload fields would not work (from rcs-comp.com
and Matthew Desmarais).
1.2
---
* Fix form inputs; text inputs always default to the empty string, and
unselected radio inputs default to nothing at all. From Daniele
Paolella.
* Fix following links with fragments (these fragments should not be
sent to the WSGI application). From desmaj.
* Added ``force_value`` to select fields, like
``res.form['select'].force_value("new_value")``. This makes it
possible to simulate forms that are dynamically updated. From
Matthew Desmarais.
* Fixed :meth:`webtest.Response.mustcontain` when you pass in a
``no=[strings]`` argument.
1.1
---
* Changed the ``__str__`` of responses to make them more doctest
friendly:
- All headers are displayed capitalized, like Content-Type
- Headers are sorted alphabetically
* Changed ``__repr__`` to only show the body length if the complete
body is not shown (for short bodies the complete body is in the
repr)
* Note: **these are backward incompatible changes** if you are using
doctest (you'll have to update your doctests with the new format).
* Fixed exception in the ``.delete`` method.
* Added a ``content_type`` argument to ``app.post`` and ``app.put``,
which sets the ``Content-Type`` of the request. This is more
convenient when testing REST APIs.
* Skip links in ``<script>...</script>`` tags (since that's not real
markup).
1.0.2
-----
* Don't submit unnamed form fields.
* Checkboxes with no explicit ``value`` send ``on`` (previously they
sent ``checked``, which isn't what browsers send).
* Support for ``<select multiple>`` fields (from Matthew Desmarais)
1.0.1
---
* Fix the ``TestApp`` validator's InputWrapper lacking support for
readline with an argument as needed by the cgi module.
1.0
---
* Keep URLs in-tact in cases such as
``app.get('http://www.python.org')`` (so HTTP_HOST=www.python.org,
etc).
* Fix ``lxml.html`` import, so lxml 2.0 users can get HTML lxml
objects from ``resp.lxml``
* Treat ``<input type="image">`` like a submit button.
* Use ``BaseCookie`` instead of ``SimpleCookie`` for storing cookies
(avoids quoting cookie values).
* Accept any ``params`` argument that has an ``items`` method (like
MultiDict)
0.9
---
Initial release
| {
"pile_set_name": "Github"
} |
Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build
| {
"pile_set_name": "Github"
} |
### 八卦:Dropbox有可能成为第一个Rust推动的IPO公司
彭博社在谈论Dropbox有可能是第一个YC孵化器里实现IPO的公司,它们用Rust :D
---
### Pythoner到Rustacean的快速入门指南
[py2rs](https://github.com/rochacbruno/py2rs)
---
### 为什么Rust是机器人的未来?
[Why Rust is the future of robotics](https://medium.com/pollenrobotics/why-rust-is-the-future-of-robotics-81d7fb68fe37)
是初创公司[Pollen Robotics](https://www.pollen-robotics.com/)联合创始人的一篇文章,他十分看好Rust,并致力于Rust在嵌入式领域尤其是机器人领域的发展。
[luos](https://github.com/pollen-robotics/luos/)
---
### 如何在Go中近零成本调用Rust
[rustgo](https://blog.filippo.io/rustgo/)
为什么不使用cgo? 调用成本太高。
---
### cargo remote ,远程编译工具
[cargo remote](https://www.reddit.com/r/rust/comments/7pn6pa/cargo_remote_build_server_support_for_cargo/)
---
### 社区反思贴集合:
请求实现支持无分支代码(branchless)编写
[Branchless Rust](https://bluejekyll.github.io/blog/rust/2018/01/10/branchless-rust.html)
对SMID及其他不稳定功能的反思
[SIMD and other neglected unstable features](https://hsivonen.fi/rust2018/)
---
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2005-2008 Apple Computer, Inc. All rights reserved.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. The rights granted to you under the License
* may not be used to create, or enable the creation or redistribution of,
* unlawful or unlicensed copies of an Apple operating system, or to
* circumvent, violate, or enable the circumvention or violation of, any
* terms of an Apple operating system software license agreement.
*
* Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_END@
*/
#define MACH__POSIX_C_SOURCE_PRIVATE 1 /* pulls in suitable savearea from
* mach/ppc/thread_status.h */
#include <arm/caches_internal.h>
#include <arm/proc_reg.h>
#include <kern/thread.h>
#include <mach/thread_status.h>
#include <stdarg.h>
#include <string.h>
#include <sys/malloc.h>
#include <sys/time.h>
#include <sys/systm.h>
#include <sys/proc.h>
#include <sys/proc_internal.h>
#include <sys/kauth.h>
#include <sys/dtrace.h>
#include <sys/dtrace_impl.h>
#include <libkern/OSAtomic.h>
#include <kern/simple_lock.h>
#include <kern/sched_prim.h> /* for thread_wakeup() */
#include <kern/thread_call.h>
#include <kern/task.h>
#include <miscfs/devfs/devfs.h>
#include <mach/vm_param.h>
extern struct arm_saved_state *find_kern_regs(thread_t);
extern dtrace_id_t dtrace_probeid_error; /* special ERROR probe */
typedef arm_saved_state_t savearea_t;
extern lck_attr_t *dtrace_lck_attr;
extern lck_grp_t *dtrace_lck_grp;
int dtrace_arm_condition_true(int condition, int cpsr);
/*
* Atomicity and synchronization
*/
inline void
dtrace_membar_producer(void)
{
#if __ARM_SMP__
__asm__ volatile("dmb ish" : : : "memory");
#else
__asm__ volatile("nop" : : : "memory");
#endif
}
inline void
dtrace_membar_consumer(void)
{
#if __ARM_SMP__
__asm__ volatile("dmb ish" : : : "memory");
#else
__asm__ volatile("nop" : : : "memory");
#endif
}
/*
* Interrupt manipulation
* XXX dtrace_getipl() can be called from probe context.
*/
int
dtrace_getipl(void)
{
/*
* XXX Drat, get_interrupt_level is MACH_KERNEL_PRIVATE
* in osfmk/kern/cpu_data.h
*/
/* return get_interrupt_level(); */
return (ml_at_interrupt_context() ? 1 : 0);
}
#if __ARM_SMP__
/*
* MP coordination
*/
decl_lck_mtx_data(static, dt_xc_lock);
static uint32_t dt_xc_sync;
typedef struct xcArg {
processorid_t cpu;
dtrace_xcall_t f;
void *arg;
} xcArg_t;
static void
xcRemote(void *foo)
{
xcArg_t *pArg = (xcArg_t *) foo;
if (pArg->cpu == CPU->cpu_id || pArg->cpu == DTRACE_CPUALL)
(pArg->f) (pArg->arg);
if (hw_atomic_sub(&dt_xc_sync, 1) == 0)
thread_wakeup((event_t) &dt_xc_sync);
}
#endif
/*
* dtrace_xcall() is not called from probe context.
*/
void
dtrace_xcall(processorid_t cpu, dtrace_xcall_t f, void *arg)
{
#if __ARM_SMP__
/* Only one dtrace_xcall in flight allowed */
lck_mtx_lock(&dt_xc_lock);
xcArg_t xcArg;
xcArg.cpu = cpu;
xcArg.f = f;
xcArg.arg = arg;
cpu_broadcast_xcall(&dt_xc_sync, TRUE, xcRemote, (void*) &xcArg);
lck_mtx_unlock(&dt_xc_lock);
return;
#else
#pragma unused(cpu)
/* On uniprocessor systems, the cpu should always be either ourselves or all */
ASSERT(cpu == CPU->cpu_id || cpu == DTRACE_CPUALL);
(*f)(arg);
return;
#endif
}
/*
* Initialization
*/
void
dtrace_isa_init(void)
{
#if __ARM_SMP__
lck_mtx_init(&dt_xc_lock, dtrace_lck_grp, dtrace_lck_attr);
#endif
return;
}
/*
* Runtime and ABI
*/
uint64_t
dtrace_getreg(struct regs * savearea, uint_t reg)
{
struct arm_saved_state *regs = (struct arm_saved_state *) savearea;
if (regs == NULL) {
DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
return (0);
}
/* beyond register limit? */
if (reg > ARM_SAVED_STATE32_COUNT - 1) {
DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
return (0);
}
return (uint64_t) ((unsigned int *) (&(regs->r)))[reg];
}
#define RETURN_OFFSET 4
static int
dtrace_getustack_common(uint64_t * pcstack, int pcstack_limit, user_addr_t pc,
user_addr_t sp)
{
int ret = 0;
ASSERT(pcstack == NULL || pcstack_limit > 0);
while (pc != 0) {
ret++;
if (pcstack != NULL) {
*pcstack++ = (uint64_t) pc;
pcstack_limit--;
if (pcstack_limit <= 0)
break;
}
if (sp == 0)
break;
pc = dtrace_fuword32((sp + RETURN_OFFSET));
sp = dtrace_fuword32(sp);
}
return (ret);
}
void
dtrace_getupcstack(uint64_t * pcstack, int pcstack_limit)
{
thread_t thread = current_thread();
savearea_t *regs;
user_addr_t pc, sp;
volatile uint16_t *flags = (volatile uint16_t *) & cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
int n;
if (*flags & CPU_DTRACE_FAULT)
return;
if (pcstack_limit <= 0)
return;
/*
* If there's no user context we still need to zero the stack.
*/
if (thread == NULL)
goto zero;
regs = (savearea_t *) find_user_regs(thread);
if (regs == NULL)
goto zero;
*pcstack++ = (uint64_t)dtrace_proc_selfpid();
pcstack_limit--;
if (pcstack_limit <= 0)
return;
pc = regs->pc;
sp = regs->sp;
if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_ENTRY)) {
*pcstack++ = (uint64_t) pc;
pcstack_limit--;
if (pcstack_limit <= 0)
return;
pc = regs->lr;
}
n = dtrace_getustack_common(pcstack, pcstack_limit, pc, regs->r[7]);
ASSERT(n >= 0);
ASSERT(n <= pcstack_limit);
pcstack += n;
pcstack_limit -= n;
zero:
while (pcstack_limit-- > 0)
*pcstack++ = 0ULL;
}
int
dtrace_getustackdepth(void)
{
thread_t thread = current_thread();
savearea_t *regs;
user_addr_t pc, sp;
int n = 0;
if (thread == NULL)
return 0;
if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
return (-1);
regs = (savearea_t *) find_user_regs(thread);
if (regs == NULL)
return 0;
pc = regs->pc;
sp = regs->sp;
if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_ENTRY)) {
n++;
pc = regs->lr;
}
/*
* Note that unlike ppc, the arm code does not use
* CPU_DTRACE_USTACK_FP. This is because arm always
* traces from the sp, even in syscall/profile/fbt
* providers.
*/
n += dtrace_getustack_common(NULL, 0, pc, regs->r[7]);
return (n);
}
void
dtrace_getufpstack(uint64_t * pcstack, uint64_t * fpstack, int pcstack_limit)
{
/* XXX ARMTODO 64vs32 */
thread_t thread = current_thread();
savearea_t *regs;
user_addr_t pc, sp;
volatile uint16_t *flags = (volatile uint16_t *) & cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
#if 0
uintptr_t oldcontext;
size_t s1, s2;
#endif
if (*flags & CPU_DTRACE_FAULT)
return;
if (pcstack_limit <= 0)
return;
/*
* If there's no user context we still need to zero the stack.
*/
if (thread == NULL)
goto zero;
regs = (savearea_t *) find_user_regs(thread);
if (regs == NULL)
goto zero;
*pcstack++ = (uint64_t)dtrace_proc_selfpid();
pcstack_limit--;
if (pcstack_limit <= 0)
return;
pc = regs->pc;
sp = regs->sp;
#if 0 /* XXX signal stack crawl */
oldcontext = lwp->lwp_oldcontext;
if (p->p_model == DATAMODEL_NATIVE) {
s1 = sizeof(struct frame) + 2 * sizeof(long);
s2 = s1 + sizeof(siginfo_t);
} else {
s1 = sizeof(struct frame32) + 3 * sizeof(int);
s2 = s1 + sizeof(siginfo32_t);
}
#endif
if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_ENTRY)) {
*pcstack++ = (uint64_t) pc;
*fpstack++ = 0;
pcstack_limit--;
if (pcstack_limit <= 0)
return;
pc = dtrace_fuword32(sp);
}
while (pc != 0 && sp != 0) {
*pcstack++ = (uint64_t) pc;
*fpstack++ = sp;
pcstack_limit--;
if (pcstack_limit <= 0)
break;
#if 0 /* XXX signal stack crawl */
if (oldcontext == sp + s1 || oldcontext == sp + s2) {
if (p->p_model == DATAMODEL_NATIVE) {
ucontext_t *ucp = (ucontext_t *) oldcontext;
greg_t *gregs = ucp->uc_mcontext.gregs;
sp = dtrace_fulword(&gregs[REG_FP]);
pc = dtrace_fulword(&gregs[REG_PC]);
oldcontext = dtrace_fulword(&ucp->uc_link);
} else {
ucontext_t *ucp = (ucontext_t *) oldcontext;
greg_t *gregs = ucp->uc_mcontext.gregs;
sp = dtrace_fuword32(&gregs[EBP]);
pc = dtrace_fuword32(&gregs[EIP]);
oldcontext = dtrace_fuword32(&ucp->uc_link);
}
} else
#endif
{
pc = dtrace_fuword32((sp + RETURN_OFFSET));
sp = dtrace_fuword32(sp);
}
#if 0
/* XXX ARMTODO*/
/*
* This is totally bogus: if we faulted, we're going to clear
* the fault and break. This is to deal with the apparently
* broken Java stacks on x86.
*/
if (*flags & CPU_DTRACE_FAULT) {
*flags &= ~CPU_DTRACE_FAULT;
break;
}
#endif
}
zero:
while (pcstack_limit-- > 0)
*pcstack++ = 0ULL;
}
void
dtrace_getpcstack(pc_t * pcstack, int pcstack_limit, int aframes,
uint32_t * intrpc)
{
struct frame *fp = (struct frame *) __builtin_frame_address(0);
struct frame *nextfp, *minfp, *stacktop;
int depth = 0;
int on_intr;
int last = 0;
uintptr_t pc;
uintptr_t caller = CPU->cpu_dtrace_caller;
if ((on_intr = CPU_ON_INTR(CPU)) != 0)
stacktop = (struct frame *) dtrace_get_cpu_int_stack_top();
else
stacktop = (struct frame *) (dtrace_get_kernel_stack(current_thread()) + kernel_stack_size);
minfp = fp;
aframes++;
if (intrpc != NULL && depth < pcstack_limit)
pcstack[depth++] = (pc_t) intrpc;
while (depth < pcstack_limit) {
nextfp = *(struct frame **) fp;
pc = *(uintptr_t *) (((uint32_t) fp) + RETURN_OFFSET);
if (nextfp <= minfp || nextfp >= stacktop) {
if (on_intr) {
/*
* Hop from interrupt stack to thread stack.
*/
arm_saved_state_t *arm_kern_regs = (arm_saved_state_t *) find_kern_regs(current_thread());
if (arm_kern_regs) {
nextfp = (struct frame *)arm_kern_regs->r[7];
vm_offset_t kstack_base = dtrace_get_kernel_stack(current_thread());
minfp = (struct frame *)kstack_base;
stacktop = (struct frame *)(kstack_base + kernel_stack_size);
on_intr = 0;
if (nextfp <= minfp || nextfp >= stacktop) {
last = 1;
}
} else {
/*
* If this thread was on the interrupt stack, but did not
* take an interrupt (i.e, the idle thread), there is no
* explicit saved state for us to use.
*/
last = 1;
}
} else {
/*
* This is the last frame we can process; indicate
* that we should return after processing this frame.
*/
last = 1;
}
}
if (aframes > 0) {
if (--aframes == 0 && caller != (uintptr_t)NULL) {
/*
* We've just run out of artificial frames,
* and we have a valid caller -- fill it in
* now.
*/
ASSERT(depth < pcstack_limit);
pcstack[depth++] = (pc_t) caller;
caller = (uintptr_t)NULL;
}
} else {
if (depth < pcstack_limit)
pcstack[depth++] = (pc_t) pc;
}
if (last) {
while (depth < pcstack_limit)
pcstack[depth++] = (pc_t) NULL;
return;
}
fp = nextfp;
minfp = fp;
}
}
int
dtrace_instr_size(uint32_t instr, int thumb_mode)
{
if (thumb_mode) {
uint16_t instr16 = *(uint16_t*) &instr;
if (((instr16 >> 11) & 0x1F) > 0x1C)
return 4;
else
return 2;
} else {
return 4;
}
}
uint64_t
dtrace_getarg(int arg, int aframes, dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
{
#pragma unused(arg, aframes, mstate, vstate)
#if 0
/* XXX ARMTODO */
uint64_t val;
uintptr_t *fp = (uintptr_t *)__builtin_frame_address(0);
uintptr_t *stack;
uintptr_t pc;
int i;
for (i = 1; i <= aframes; i++) {
fp = fp[0];
pc = fp[1];
if (dtrace_invop_callsite_pre != NULL
&& pc > (uintptr_t)dtrace_invop_callsite_pre
&& pc <= (uintptr_t)dtrace_invop_callsite_post) {
/*
* If we pass through the invalid op handler, we will
* use the pointer that it passed to the stack as the
* second argument to dtrace_invop() as the pointer to
* the frame we're hunting for.
*/
stack = (uintptr_t *)&fp[1]; /* Find marshalled arguments */
fp = (struct frame *)stack[1]; /* Grab *second* argument */
stack = (uintptr_t *)&fp[1]; /* Find marshalled arguments */
DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
val = (uint64_t)(stack[arg]);
DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
return val;
}
}
/*
* Arrive here when provider has called dtrace_probe directly.
*/
stack = (uintptr_t *)&fp[1]; /* Find marshalled arguments */
stack++; /* Advance past probeID */
DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
val = *(((uint64_t *)stack) + arg); /* dtrace_probe arguments arg0 .. arg4 are 64bits wide */
DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
return (val);
#endif
return 0xfeedfacedeafbeadLL;
}
void
dtrace_probe_error(dtrace_state_t *state, dtrace_epid_t epid, int which,
int fltoffs, int fault, uint64_t illval)
{
/* XXX ARMTODO */
/*
* For the case of the error probe firing lets
* stash away "illval" here, and special-case retrieving it in DIF_VARIABLE_ARG.
*/
state->dts_arg_error_illval = illval;
dtrace_probe( dtrace_probeid_error, (uint64_t)(uintptr_t)state, epid, which, fltoffs, fault );
}
void
dtrace_toxic_ranges(void (*func)(uintptr_t base, uintptr_t limit))
{
/* XXX ARMTODO check copied from ppc/x86*/
/*
* "base" is the smallest toxic address in the range, "limit" is the first
* VALID address greater than "base".
*/
func(0x0, VM_MIN_KERNEL_ADDRESS);
if (VM_MAX_KERNEL_ADDRESS < ~(uintptr_t)0)
func(VM_MAX_KERNEL_ADDRESS + 1, ~(uintptr_t)0);
}
int
dtrace_arm_condition_true(int cond, int cpsr)
{
int taken = 0;
int zf = (cpsr & PSR_ZF) ? 1 : 0,
nf = (cpsr & PSR_NF) ? 1 : 0,
cf = (cpsr & PSR_CF) ? 1 : 0,
vf = (cpsr & PSR_VF) ? 1 : 0;
switch(cond) {
case 0: taken = zf; break;
case 1: taken = !zf; break;
case 2: taken = cf; break;
case 3: taken = !cf; break;
case 4: taken = nf; break;
case 5: taken = !nf; break;
case 6: taken = vf; break;
case 7: taken = !vf; break;
case 8: taken = (cf && !zf); break;
case 9: taken = (!cf || zf); break;
case 10: taken = (nf == vf); break;
case 11: taken = (nf != vf); break;
case 12: taken = (!zf && (nf == vf)); break;
case 13: taken = (zf || (nf != vf)); break;
case 14: taken = 1; break;
case 15: taken = 1; break; /* always "true" for ARM, unpredictable for THUMB. */
}
return taken;
}
void dtrace_flush_caches(void)
{
/* TODO There were some problems with flushing just the cache line that had been modified.
* For now, we'll flush the entire cache, until we figure out how to flush just the patched block.
*/
FlushPoU_Dcache();
InvalidatePoU_Icache();
}
| {
"pile_set_name": "Github"
} |
/*
JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine
Copyright (C) 2012-2013 Ian Preston
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU 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.
Details (including contact information) can be found at:
jpc.sourceforge.net
or the developer website
sourceforge.net/projects/jpc/
End of licence header
*/
package org.jpc.emulator.execution.opcodes.pm;
import org.jpc.emulator.execution.*;
import org.jpc.emulator.execution.decoder.*;
import org.jpc.emulator.processor.*;
import org.jpc.emulator.processor.fpu64.*;
import static org.jpc.emulator.processor.Processor.*;
public class btc_Ed_Ib_mem extends Executable
{
final Pointer op1;
final int immb;
public btc_Ed_Ib_mem(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
int modrm = input.readU8();
op1 = Modrm.getPointer(prefices, modrm, input);
immb = Modrm.Ib(input);
}
public Branch execute(Processor cpu)
{
int bit = 1 << (immb & (32-1));
int offset = ((immb & ~(32-1))/8);
cpu.cf = (0 != (op1.get32(cpu, offset) & bit));
cpu.flagStatus &= NCF;
op1.set32(cpu, offset, (op1.get32(cpu, offset)^bit));
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
} | {
"pile_set_name": "Github"
} |
import { Scene } from "../../scene";
import { Vector3, Vector2, Vector4 } from "../../Maths/math.vector";
import { Color4 } from '../../Maths/math.color';
import { Mesh, _CreationDataStorage } from "../mesh";
import { VertexData } from "../mesh.vertexData";
import { PolygonMeshBuilder } from "../polygonMesh";
import { FloatArray, IndicesArray, Nullable } from "../../types";
import { VertexBuffer } from "../../Meshes/buffer";
import { EngineStore } from '../../Engines/engineStore';
declare var earcut: any;
VertexData.CreatePolygon = function(polygon: Mesh, sideOrientation: number, fUV?: Vector4[], fColors?: Color4[], frontUVs?: Vector4, backUVs?: Vector4, wrp?: boolean) {
var faceUV: Vector4[] = fUV || new Array<Vector4>(3);
var faceColors = fColors;
var colors = [];
var wrap: boolean = wrp || false;
// default face colors and UV if undefined
for (var f = 0; f < 3; f++) {
if (faceUV[f] === undefined) {
faceUV[f] = new Vector4(0, 0, 1, 1);
}
if (faceColors && faceColors[f] === undefined) {
faceColors[f] = new Color4(1, 1, 1, 1);
}
}
var positions = <FloatArray>polygon.getVerticesData(VertexBuffer.PositionKind);
var normals = <FloatArray>polygon.getVerticesData(VertexBuffer.NormalKind);
var uvs = <FloatArray>polygon.getVerticesData(VertexBuffer.UVKind);
var indices = <IndicesArray>polygon.getIndices();
var startIndex = positions.length / 9;
var disp = 0;
var distX = 0;
var distZ = 0;
var dist = 0;
var totalLen = 0;
var cumulate = [0];
if (wrap) {
for (var idx = startIndex; idx < positions.length / 3; idx += 4) {
distX = positions[3 * (idx + 2)] - positions[3 * idx];
distZ = positions[3 * (idx + 2) + 2] - positions[3 * idx + 2];
dist = Math.sqrt(distX * distX + distZ * distZ);
totalLen += dist;
cumulate.push(totalLen);
}
}
// set face colours and textures
var idx: number = 0;
var face: number = 0;
for (var index = 0; index < normals.length; index += 3) {
//Edge Face no. 1
if (Math.abs(normals[index + 1]) < 0.001) {
face = 1;
}
//Top Face no. 0
if (Math.abs(normals[index + 1] - 1) < 0.001) {
face = 0;
}
//Bottom Face no. 2
if (Math.abs(normals[index + 1] + 1) < 0.001) {
face = 2;
}
idx = index / 3;
if (face === 1) {
disp = idx - startIndex;
if (disp % 4 < 1.5) {
if (wrap) {
uvs[2 * idx] = faceUV[face].x + (faceUV[face].z - faceUV[face].x) * cumulate[Math.floor(disp / 4)] / totalLen;
}
else {
uvs[2 * idx] = faceUV[face].x;
}
}
else {
if (wrap) {
uvs[2 * idx] = faceUV[face].x + (faceUV[face].z - faceUV[face].x) * cumulate[Math.floor(disp / 4) + 1] / totalLen;
}
else {
uvs[2 * idx] = faceUV[face].z;
}
}
if (disp % 2 === 0) {
uvs[2 * idx + 1] = faceUV[face].w;
}
else {
uvs[2 * idx + 1] = faceUV[face].y;
}
}
else {
uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
}
if (faceColors) {
colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
}
}
// sides
VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
// Result
var vertexData = new VertexData();
vertexData.indices = indices;
vertexData.positions = positions;
vertexData.normals = normals;
vertexData.uvs = uvs;
if (faceColors) {
var totalColors = (sideOrientation === VertexData.DOUBLESIDE) ? colors.concat(colors) : colors;
vertexData.colors = totalColors;
}
return vertexData;
};
Mesh.CreatePolygon = (name: string, shape: Vector3[], scene: Scene, holes?: Vector3[][], updatable?: boolean, sideOrientation?: number, earcutInjection = earcut): Mesh => {
var options = {
shape: shape,
holes: holes,
updatable: updatable,
sideOrientation: sideOrientation
};
return PolygonBuilder.CreatePolygon(name, options, scene, earcutInjection);
};
Mesh.ExtrudePolygon = (name: string, shape: Vector3[], depth: number, scene: Scene, holes?: Vector3[][], updatable?: boolean, sideOrientation?: number, earcutInjection = earcut): Mesh => {
var options = {
shape: shape,
holes: holes,
depth: depth,
updatable: updatable,
sideOrientation: sideOrientation
};
return PolygonBuilder.ExtrudePolygon(name, options, scene, earcutInjection);
};
/**
* Class containing static functions to help procedurally build meshes
*/
export class PolygonBuilder {
/**
* Creates a polygon mesh
* The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
* * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors
* * You can set the mesh side orientation with the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE
* * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
* * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4)
* * Remember you can only change the shape positions, not their number when updating a polygon
* @param name defines the name of the mesh
* @param options defines the options used to create the mesh
* @param scene defines the hosting scene
* @param earcutInjection can be used to inject your own earcut reference
* @returns the polygon mesh
*/
public static CreatePolygon(name: string, options: { shape: Vector3[], holes?: Vector3[][], depth?: number, faceUV?: Vector4[], faceColors?: Color4[], updatable?: boolean, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4, wrap?: boolean}, scene: Nullable<Scene> = null, earcutInjection = earcut): Mesh {
options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);
var shape = options.shape;
var holes = options.holes || [];
var depth = options.depth || 0;
var contours: Array<Vector2> = [];
var hole: Array<Vector2> = [];
for (var i = 0; i < shape.length; i++) {
contours[i] = new Vector2(shape[i].x, shape[i].z);
}
var epsilon = 0.00000001;
if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
contours.pop();
}
var polygonTriangulation = new PolygonMeshBuilder(name, contours, scene || EngineStore.LastCreatedScene!, earcutInjection);
for (var hNb = 0; hNb < holes.length; hNb++) {
hole = [];
for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
hole.push(new Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
}
polygonTriangulation.addHole(hole);
}
var polygon = polygonTriangulation.build(options.updatable, depth);
polygon._originalBuilderSideOrientation = options.sideOrientation;
var vertexData = VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs, options.wrap);
vertexData.applyToMesh(polygon, options.updatable);
return polygon;
}
/**
* Creates an extruded polygon mesh, with depth in the Y direction.
* * You can set different colors and different images to the top, bottom and extruded side by using the parameters `faceColors` (an array of 3 Color3 elements) and `faceUV` (an array of 3 Vector4 elements)
* @see https://doc.babylonjs.com/how_to/createbox_per_face_textures_and_colors
* @param name defines the name of the mesh
* @param options defines the options used to create the mesh
* @param scene defines the hosting scene
* @param earcutInjection can be used to inject your own earcut reference
* @returns the polygon mesh
*/
public static ExtrudePolygon(name: string, options: { shape: Vector3[], holes?: Vector3[][], depth?: number, faceUV?: Vector4[], faceColors?: Color4[], updatable?: boolean, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4, wrap?: boolean }, scene: Nullable<Scene> = null, earcutInjection = earcut): Mesh {
return PolygonBuilder.CreatePolygon(name, options, scene, earcutInjection);
}
} | {
"pile_set_name": "Github"
} |
/*
* Skin: Purple
* ------------
*/
@import "../../bootstrap-less/mixins.less";
@import "../../bootstrap-less/variables.less";
@import "../variables.less";
@import "../mixins.less";
.skin-purple-light {
//Navbar
.main-header {
.navbar {
.navbar-variant(@purple; #fff);
.sidebar-toggle {
color: #fff;
&:hover {
background-color: darken(@purple, 5%);
}
}
@media (max-width: @screen-header-collapse) {
.dropdown-menu {
li {
&.divider {
background-color: rgba(255, 255, 255, 0.1);
}
a {
color: #fff;
&:hover {
background: darken(@purple, 5%);
}
}
}
}
}
}
//Logo
.logo {
.logo-variant(@purple);
}
li.user-header {
background-color: @purple;
}
}
//Content Header
.content-header {
background: transparent;
}
//Create the sidebar skin
.skin-light-sidebar(@purple);
}
| {
"pile_set_name": "Github"
} |
/*!
* merkle.js - merkle trees for bcrypto
* Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2019, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcrypto
*
* Parts of this software are based on bitcoin/bitcoin:
* Copyright (c) 2009-2019, The Bitcoin Core Developers (MIT License).
* Copyright (c) 2009-2019, The Bitcoin Developers (MIT License).
* https://github.com/bitcoin/bitcoin
*/
const assert = require('./bsert');
// Notes about unbalanced merkle trees:
//
// Bitcoin hashes odd nodes with themselves,
// allowing an attacker to add a duplicate
// TXID, creating an even number of leaves
// and computing the same root (CVE-2012-2459).
// In contrast, RFC 6962 simply propagates
// odd nodes up.
//
// RFC 6962:
//
// R
// / \
// / \
// / \
// / \
// / \
// k j <-- same as below
// / \ |
// / \ |
// / \ |
// h i j
// / \ / \ / \
// a b c d e f
//
// Bitcoin Behavior:
//
// R
// / \
// / \
// / \
// / \
// / \
// k l <-- HASH(j || j)
// / \ |
// / \ |
// / \ |
// h i j
// / \ / \ / \
// a b c d e f
//
// This creates a situation where these leaves:
//
// R
// / \
// / \
// / \
// d e <-- HASH(c || c)
// / \ / \
// a b c c
//
// Compute the same root as:
//
// R
// / \
// / \
// d e <-- HASH(c || c)
// / \ |
// a b c
//
// Why does this matter? Duplicate TXIDs are
// invalid right? They're spending the same
// inputs! The problem arises in certain
// implementation optimizations which may
// mark a block hash invalid. In other words,
// an invalid block shares the same block
// hash as a valid one!
//
// See:
// https://tools.ietf.org/html/rfc6962#section-2.1
// https://nvd.nist.gov/vuln/detail/CVE-2012-2459
// https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-2459
// https://bitcointalk.org/?topic=81749
/**
* Build a merkle tree from leaves.
* @param {Object} alg
* @param {Buffer[]} leaves
* @returns {Array} [nodes, malleated]
*/
function createTree(alg, leaves) {
assert(alg && typeof alg.root === 'function');
assert(Array.isArray(leaves));
const nodes = new Array(leaves.length);
for (let i = 0; i < leaves.length; i++) { nodes[i] = leaves[i]; }
let size = nodes.length;
let malleated = false;
let i = 0;
if (size === 0) {
nodes.push(alg.zero);
return [nodes, malleated];
}
while (size > 1) {
for (let j = 0; j < size; j += 2) {
const k = Math.min(j + 1, size - 1);
const left = nodes[i + j];
const right = nodes[i + k];
if (k === j + 1 && k + 1 === size
&& left.equals(right)) {
malleated = true;
}
const hash = alg.root(left, right);
nodes.push(hash);
}
i += size;
size = (size + 1) >>> 1;
}
return [nodes, malleated];
}
/**
* Calculate merkle root from leaves.
* @param {Object} alg
* @param {Buffer[]} leaves
* @returns {Array} [root, malleated]
*/
function createRoot(alg, leaves) {
assert(alg && typeof alg.root === 'function');
assert(Array.isArray(leaves));
const [nodes, malleated] = createTree(alg, leaves);
const root = nodes[nodes.length - 1];
return [root, malleated];
}
/**
* Collect a merkle branch from vector index.
* @param {Object} alg
* @param {Number} index
* @param {Buffer[]} leaves
* @returns {Buffer[]} branch
*/
function createBranch(alg, index, leaves) {
assert(alg && typeof alg.root === 'function');
assert((index >>> 0) === index);
assert(Array.isArray(leaves));
assert(index < leaves.length);
let size = leaves.length;
const [nodes] = createTree(alg, leaves);
const branch = [];
let i = 0;
while (size > 1) {
const j = Math.min(index ^ 1, size - 1);
branch.push(nodes[i + j]);
index >>>= 1;
i += size;
size = (size + 1) >>> 1;
}
return branch;
}
/**
* Derive merkle root from branch.
* @param {Object} alg
* @param {Buffer} hash
* @param {Buffer[]} branch
* @param {Number} index
* @returns {Buffer} root
*/
function deriveRoot(alg, hash, branch, index) {
assert(alg && typeof alg.root === 'function');
assert(Buffer.isBuffer(hash));
assert(Array.isArray(branch));
assert((index >>> 0) === index);
let root = hash;
for (const hash of branch) {
if ((index & 1) && hash.equals(root)) { return alg.zero; }
if (index & 1) { root = alg.root(hash, root); } else { root = alg.root(root, hash); }
index >>>= 1;
}
return root;
}
/*
* Expose
*/
exports.createTree = createTree;
exports.createRoot = createRoot;
exports.createBranch = createBranch;
exports.deriveRoot = deriveRoot;
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Gallery xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gallery"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:spacing="1dip" />
| {
"pile_set_name": "Github"
} |
/**
* @file methods/emst/union_find.hpp
* @author Bill March ([email protected])
*
* Implements a union-find data structure. This structure tracks the components
* of a graph. Each point in the graph is initially in its own component.
* Calling unionfind.Union(x, y) unites the components indexed by x and y.
* unionfind.Find(x) returns the index of the component containing point x.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_METHODS_EMST_UNION_FIND_HPP
#define MLPACK_METHODS_EMST_UNION_FIND_HPP
#include <mlpack/prereqs.hpp>
namespace mlpack {
namespace emst {
/**
* A Union-Find data structure. See Cormen, Rivest, & Stein for details. The
* structure tracks the components of a graph. Each point in the graph is
* initially in its own component. Calling Union(x, y) unites the components
* indexed by x and y. Find(x) returns the index of the component containing
* point x.
*/
class UnionFind
{
private:
arma::Col<size_t> parent;
arma::ivec rank;
public:
//! Construct the object with the given size.
UnionFind(const size_t size) : parent(size), rank(size)
{
for (size_t i = 0; i < size; ++i)
{
parent[i] = i;
rank[i] = 0;
}
}
//! Destroy the object (nothing to do).
~UnionFind() { }
/**
* Returns the component containing an element.
*
* @param x the component to be found
* @return The index of the component containing x
*/
size_t Find(const size_t x)
{
if (parent[x] == x)
{
return x;
}
else
{
// This ensures that the tree has a small depth.
parent[x] = Find(parent[x]);
return parent[x];
}
}
/**
* Union the components containing x and y.
*
* @param x one component
* @param y the other component
*/
void Union(const size_t x, const size_t y)
{
const size_t xRoot = Find(x);
const size_t yRoot = Find(y);
if (xRoot == yRoot)
{
return;
}
else if (rank[xRoot] == rank[yRoot])
{
parent[yRoot] = parent[xRoot];
rank[xRoot] = rank[xRoot] + 1;
}
else if (rank[xRoot] > rank[yRoot])
{
parent[yRoot] = xRoot;
}
else
{
parent[xRoot] = yRoot;
}
}
}; // class UnionFind
} // namespace emst
} // namespace mlpack
#endif // MLPACK_METHODS_EMST_UNION_FIND_HPP
| {
"pile_set_name": "Github"
} |
====== ارسال گذرواژهی جدید ======
خواهشمندیم نام کاربری خود را در فرم زیر بنویسید تا گذرواژهی جدید برایتان ارسال شود. یک پیوند تاییدیه برای ایمیل ثبت شده ارسال میشود.
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python3
#
# Copyright (c) Bo Peng and the University of Texas MD Anderson Cancer Center
# Distributed under the terms of the 3-clause BSD License.
import keyword
import re
from typing import Callable, List
SOS_TARGETS_OPTIONS = [
'group_by', 'paired_with', 'pattern', 'group_with', 'for_each',
'remove_empty_groups'
]
SOS_INPUT_OPTIONS = ['concurrent']
SOS_OUTPUT_OPTIONS = []
SOS_DEPENDS_OPTIONS: List = []
SOS_RUNTIME_OPTIONS = [
'workdir', 'walltime', 'nodes', 'cores', 'mem',
'shared', 'env', 'prepend_path', 'queue', 'to_host', 'from_host',
'trunk_size', 'trunk_workers', 'tags', 'logfile',
# deprecated
'concurrent', 'name', 'active'
]
SOS_ACTION_OPTIONS = [
'workdir', 'container', 'engine', 'docker_image', 'docker_file', 'active',
'input', 'output', 'allow_error', 'tracked', 'stdout', 'stderr',
'default_env', 'env'
]
SOS_DIRECTIVES = ['input', 'output', 'depends', 'task', 'parameter']
SOS_SECTION_OPTIONS = ['provides', 'shared', 'workdir']
SOS_KEYWORDS = SOS_INPUT_OPTIONS + SOS_OUTPUT_OPTIONS + SOS_DEPENDS_OPTIONS + SOS_RUNTIME_OPTIONS \
+ SOS_ACTION_OPTIONS + SOS_DIRECTIVES + SOS_SECTION_OPTIONS
SOS_USAGES = {
'input':
'''
input: filename, filename, ... [group_by=GROUP] [filetype=FILETYPE]
[paired_with=PAIRS] [for_each=VARS] [pattern=PATTEN]
Specify input targets of a SoS step.
See online documentation for details of variables.
''',
'output':
'''
output: target, target, ...
Specify output targets of a SoS step.
See online documentation for details of variables.
''',
'depends':
'''
depends: target, target, ...
Specify dependent targets of a SoS step.
See online documentation for details of variables.
'''
}
#
# This code is copied from Bazzar to compile regular expressions only when they
# are needed, to avoid compiling all regular expressions up front even when they
# are not used
#
class LazyRegex(object):
"""A proxy around a real regex, which won't be compiled until accessed."""
# These are the parameters on a real _sre.SRE_Pattern object, which we
# will map to local members so that we don't have the proxy overhead.
_regex_attributes_to_copy = [
'__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner',
'search', 'split', 'sub', 'subn'
]
# We use slots to keep the overhead low. But we need a slot entry for
# all of the attributes we will copy
__slots__ = [
'_real_regex',
'_regex_args',
'_regex_kwargs',
] + _regex_attributes_to_copy
def __init__(self, *args, **kwargs) -> None:
"""Create a new proxy object, passing in the args to pass to re.compile
:param args: The `*args` to pass to re.compile
:param kwargs: The `**kwargs` to pass to re.compile
"""
self._real_regex = None
self._regex_args = args
self._regex_kwargs = kwargs
def _compile_and_collapse(self) -> None:
"""Actually compile the requested regex"""
self._real_regex = self._real_re_compile(*self._regex_args,
**self._regex_kwargs)
for attr in self._regex_attributes_to_copy:
setattr(self, attr, getattr(self._real_regex, attr))
def _real_re_compile(self, *args, **kwargs):
"""Thunk over to the original re.compile"""
try:
return re.compile(*args, **kwargs)
except re.error as e:
# raise ValueError instead of re.error as this gives a
# cleaner message to the user.
raise ValueError('"' + args[0] + '" ' + str(e))
def __getstate__(self):
"""Return the state to use when pickling."""
return {
"args": self._regex_args,
"kwargs": self._regex_kwargs,
}
def __setstate__(self, sdict):
"""Restore from a pickled state."""
self._real_regex = None
setattr(self, "_regex_args", sdict["args"])
setattr(self, "_regex_kwargs", sdict["kwargs"])
def __getattr__(self, attr: str) -> Callable:
"""Return a member from the proxied regex object.
If the regex hasn't been compiled yet, compile it
"""
if self._real_regex is None:
self._compile_and_collapse()
# Once we have compiled, the only time we should come here
# is actually if the attribute is missing.
return getattr(self._real_regex, attr)
# Regular expressions for parsing section headers and options
_SECTION_HEADER_TMPL = r'''
^\[\s* # [
(?P<section_name>
[a-zA-Z*0-9_-]+ # name,
\s*(\([^)]*\))? # optional alias
(\s*,\s* # ,
[a-zA-Z*0-9_]+ # another name
\s*(\([^)]*\))? # alias
)* # optional second or more
) # section names
(:\s* # :
(?P<section_option>.*) # section options
)? # optional
\]\s*$ # ]
'''
_GLOBAL_SECTION_HEADER_TMPL = r'''
^\[\s* # [
global\s* # global
\]\s*$ # ]
'''
_SECTION_NAME_TMPL = r'''
^\s* # start
(?P<name> # optional name
[a-zA-Z*] # alphabet or '*'
([-\w\d_*]*? # followed by alpha numeric, '-' or '*'
[-a-zA-Z\d*])?? # but last character cannot be _
)? # name is optional
(?(name) # if there is name
(_(?P<index>\d+))? # optional _index
|(?P<default_index>\d+)) # no name, then index
\s*(\(\s*
(?P<alias>[^)]+) # optional alias
\s*\))?
\s*$
'''
_SUBWORKFLOW_TMPL = r'''
^\s* # leading space
(?P<name> # name
([a-zA-Z]+\.)* # optional name
([a-zA-Z*] # cannot start with _ etc
([-\w\d_]*?))?) # can - have _ and digit
(:(?P<steps> # index start from :
[\d\s-]+))? # with - and digit
\s*$ # end
'''
_SECTION_OPTION_TMPL = r'''
^\s* # start
(?P<name>{}) # one of the option names
(\s*=\s* # =
(?P<value>.+) # value
)? # value is optional
\s*$
'''.format('|'.join(SOS_SECTION_OPTIONS))
_FORMAT_LINE_TMPL = r'''
^ # from first column
\#fileformat\s*=\s* # starts with #fileformat=SOS
(?P<format_name>\S*) # format name
\s*$ # till end of line
'''
_FORMAT_VERSION_TMPL = r'''
^ # from first column
(?P<format_name>[a-zA-Z]+) # format name
(?P<format_version>[\d\.]+) # any number and .
\s*$ # till end of line
'''
_DIRECTIVE_TMPL = r'''
^ # from start of line
(?P<directive_name> #
(?!({})\s*:) # not a python keyword followed by : (can be input)
({} # name of directive
|[a-zA-Z][\w\d_]*)) # or action
\s*:\s* # followed by :
(?P<directive_value> # and values that can be
([^:.|=&@$^<>].*)?$) # name followed by and values, which can be
# constant 'a', "b", variable or function call
# a(), or arbitrary expression (['a'...], dictionary, set
# etc) which is difficult to match, so we use negative
# pattern to exclude expressions starting with :, | etc
'''.format('|'.join(keyword.kwlist), '|'.join(SOS_DIRECTIVES))
_INDENTED_ACTION_TMPL = r'''
^ # from start of line but allow space
(?P<action_name> #
(?!\s+({}|{})\s*:) # not a python keyword or SoS directive followed by :
(\s+[a-zA-Z][\w\d_]*)) # or action
\s*:\s* # followed by :
(?P<action_value> # and values that can be
([^:.|=&@$^<>].*)?$) # name followed by and values, which can be
# constant 'a', "b", variable or function call
# a(), or arbitrary expression (['a'...], dictionary, set
# etc) which is difficult to match, so we use negative
# pattern to exclude expressions starting with :, | etc
'''.format('|'.join(keyword.kwlist), '|'.join(SOS_DIRECTIVES))
_ASSIGNMENT_TMPL = r'''
^ # from start of line
(?P<var_name>[\w_][\d\w_]*) # variable name
\s*=(?!=)\s* # assignment
(?P<var_value>.*) # variable content
'''
_CONFIG_NAME = r'''
^
[a-zA-Z] # first letter must be
[a-zA-Z0-9_]*
(\.[a-zA-Z] # followed by more names separated with '.'
[a-zA-Z0-9_]*)*
$
'''
_SOS_MAGIC_TMPL = r''' # SOS magic
^%(dict # %dict
|run # %run
|paste # %paste
|set # %set
|get # %get
|preview # %preview
|with # %with
|use # %use
|shutdown # %shutdown
)(\s+.*)?
$
'''
_SOS_CELL_TMPL = r''' # %cell
^%cell(\s+.*)?
'''
_SOS_CELL_LINE_TMPL = r'''
^
%cell(\s+ # %cell
(?P<cell_type>
(markdown|code) # markdown or code
)?
(\s+
(?P<cell_count>
[0-9]+
))?
(?P<metainfo>
.* # arbitrary stuff
)?)?
$
'''
_INDENTED_TMPL = r'''
^ # start from beginning of string
(
\s*\n # empty lines are ignored
)*
(\s*)\S # match a line with a non-space character
'''
_SOS_WILDCARD_TMPL = r'''
\{
\s*
(?P<name>\w+?)
(\s*,\s*
(?P<constraint>
([^\{\}]+|\{\d+(,\d+)?\})
*)
)?
\s*
\}
'''
_SOS_TAG_TMPL = r'''
^[\w_.-]+$ # - is allowed in between
'''
_SOS_LOGLINE = r'''
^ # 2017-11-01 14:26:16,145:
\d\d\d\d\-\d\d\-\d\d\s+\d\d:\d\d:\d\d,\d\d\d:
'''
SOS_SECTION_HEADER = LazyRegex(_SECTION_HEADER_TMPL, re.VERBOSE)
SOS_GLOBAL_SECTION_HEADER = LazyRegex(_GLOBAL_SECTION_HEADER_TMPL, re.VERBOSE)
SOS_SECTION_NAME = LazyRegex(_SECTION_NAME_TMPL, re.VERBOSE)
SOS_SUBWORKFLOW = LazyRegex(_SUBWORKFLOW_TMPL, re.VERBOSE)
SOS_SECTION_OPTION = LazyRegex(_SECTION_OPTION_TMPL, re.VERBOSE)
SOS_FORMAT_LINE = LazyRegex(_FORMAT_LINE_TMPL, re.VERBOSE)
SOS_FORMAT_VERSION = LazyRegex(_FORMAT_VERSION_TMPL, re.VERBOSE)
SOS_DIRECTIVE = LazyRegex(_DIRECTIVE_TMPL, re.VERBOSE)
SOS_INDENTED_ACTION = LazyRegex(_INDENTED_ACTION_TMPL, re.VERBOSE)
SOS_ASSIGNMENT = LazyRegex(_ASSIGNMENT_TMPL, re.VERBOSE)
CONFIG_NAME = LazyRegex(_CONFIG_NAME, re.VERBOSE)
SOS_MAGIC = LazyRegex(_SOS_MAGIC_TMPL, re.VERBOSE)
SOS_CELL = LazyRegex(_SOS_CELL_TMPL, re.VERBOSE)
SOS_CELL_LINE = LazyRegex(_SOS_CELL_LINE_TMPL, re.VERBOSE)
INDENTED = LazyRegex(_INDENTED_TMPL, re.VERBOSE)
SOS_WILDCARD = LazyRegex(_SOS_WILDCARD_TMPL, re.VERBOSE)
SOS_TAG = LazyRegex(_SOS_TAG_TMPL, re.VERBOSE)
SOS_LOGLINE = LazyRegex(_SOS_LOGLINE, re.VERBOSE)
| {
"pile_set_name": "Github"
} |
/*
* fs/cifs/cifs_fs_sb.h
*
* Copyright (c) International Business Machines Corp., 2002,2004
* Author(s): Steve French ([email protected])
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU Lesser General Public License for more details.
*
*/
#include <linux/rbtree.h>
#ifndef _CIFS_FS_SB_H
#define _CIFS_FS_SB_H
#include <linux/backing-dev.h>
#define CIFS_MOUNT_NO_PERM 1 /* do not do client vfs_perm check */
#define CIFS_MOUNT_SET_UID 2 /* set current's euid in create etc. */
#define CIFS_MOUNT_SERVER_INUM 4 /* inode numbers from uniqueid from server */
#define CIFS_MOUNT_DIRECT_IO 8 /* do not write nor read through page cache */
#define CIFS_MOUNT_NO_XATTR 0x10 /* if set - disable xattr support */
#define CIFS_MOUNT_MAP_SPECIAL_CHR 0x20 /* remap illegal chars in filenames */
#define CIFS_MOUNT_POSIX_PATHS 0x40 /* Negotiate posix pathnames if possible*/
#define CIFS_MOUNT_UNX_EMUL 0x80 /* Network compat with SFUnix emulation */
#define CIFS_MOUNT_NO_BRL 0x100 /* No sending byte range locks to srv */
#define CIFS_MOUNT_CIFS_ACL 0x200 /* send ACL requests to non-POSIX srv */
#define CIFS_MOUNT_OVERR_UID 0x400 /* override uid returned from server */
#define CIFS_MOUNT_OVERR_GID 0x800 /* override gid returned from server */
#define CIFS_MOUNT_DYNPERM 0x1000 /* allow in-memory only mode setting */
#define CIFS_MOUNT_NOPOSIXBRL 0x2000 /* mandatory not posix byte range lock */
#define CIFS_MOUNT_NOSSYNC 0x4000 /* don't do slow SMBflush on every sync*/
#define CIFS_MOUNT_FSCACHE 0x8000 /* local caching enabled */
#define CIFS_MOUNT_MF_SYMLINKS 0x10000 /* Minshall+French Symlinks enabled */
#define CIFS_MOUNT_MULTIUSER 0x20000 /* multiuser mount */
#define CIFS_MOUNT_STRICT_IO 0x40000 /* strict cache mode */
#define CIFS_MOUNT_RWPIDFORWARD 0x80000 /* use pid forwarding for rw */
#define CIFS_MOUNT_POSIXACL 0x100000 /* mirror of MS_POSIXACL in mnt_cifs_flags */
#define CIFS_MOUNT_CIFS_BACKUPUID 0x200000 /* backup intent bit for a user */
#define CIFS_MOUNT_CIFS_BACKUPGID 0x400000 /* backup intent bit for a group */
#define CIFS_MOUNT_MAP_SFM_CHR 0x800000 /* SFM/MAC mapping for illegal chars */
#define CIFS_MOUNT_USE_PREFIX_PATH 0x1000000 /* make subpath with unaccessible
* root mountable
*/
struct cifs_sb_info {
struct rb_root tlink_tree;
spinlock_t tlink_tree_lock;
struct tcon_link *master_tlink;
struct nls_table *local_nls;
unsigned int rsize;
unsigned int wsize;
unsigned long actimeo; /* attribute cache timeout (jiffies) */
atomic_t active;
kuid_t mnt_uid;
kgid_t mnt_gid;
kuid_t mnt_backupuid;
kgid_t mnt_backupgid;
umode_t mnt_file_mode;
umode_t mnt_dir_mode;
unsigned int mnt_cifs_flags;
char *mountdata; /* options received at mount time or via DFS refs */
struct backing_dev_info bdi;
struct delayed_work prune_tlinks;
struct rcu_head rcu;
char *prepath;
};
#endif /* _CIFS_FS_SB_H */
| {
"pile_set_name": "Github"
} |
.sidebar-menu {
display: table-cell;
position: relative;
width: @sidebar-width;
background: @sidebar-background;
z-index: 1;
.logo-env {
padding: @default-padding (@double-margin + @sidebar-horizontal-link-padding);
border-bottom: 1px solid @sidebar-menu-border;
&:extend(.clearfix all);
.logo {
float: left;
.logo-collapsed {
display: none;
}
}
.settings-icon {
float: right;
position: relative;
top: 1px;
a {
@s: 18px;
color: @main-text-color;
line-height: 1;
i {
line-height: 1;
font-size: @s;
}
&:hover {
color: @main-text-active-color;
}
}
}
}
// Main Menu
.main-menu {
padding-left: @double-margin;
padding-right: @double-margin;
margin-top: @base-margin;
margin-bottom: @base-margin;
list-style: none;
@media screen and (max-width: @screen-sm){
margin-top: @base-padding;
margin-bottom: @base-padding;
}
// Links
a {
color: @main-text-color;
text-decoration: none;
display: block;
padding: @sidebar-vertical-link-padding @sidebar-horizontal-link-padding;
border-bottom: 1px solid @sidebar-menu-border;
&:extend(.transall);
> i {
display: inline-block;
margin-right: @base-padding;
+ span {
padding-right: @base-padding;
}
}
> span {
display: inline-block;
}
> .label {
margin-top: 1px;
}
> .badge {
font-size: 75%;
line-height: 1.2;
}
&:hover {
color: @main-text-active-color;
}
}
// Active
li.active > a {
color: @main-text-active-color;
}
// With Subs
li.has-sub {
> a {
&:before {
position: relative;
display: inline-block;
font-family: 'FontAwesome';
content: '\f107';
float: right;
color: lighten(@sidebar-menu-border, 25%);
margin-left: @base-padding;
.rotate(-90deg);
.transition(~"all 150ms ease-in-out");
}
}
&.opened, &.expanded {
> a:before {
.rotate(0deg);
}
}
}
// First Level
> li {
&.opened {
> ul {
display: block;
}
.opened {
> ul {
display: block;
}
}
}
}
// Subs
ul {
@sub-spacing: 25px;
display: none;
margin: 0;
padding: 0;
overflow: hidden;
list-style: none;
li {
@show-delay: 80ms;
position: relative;
&.is-hidden {
@media screen and (min-width: @screen-sm){
left: -@base-margin;
.opacity(0);
}
}
&.is-shown {
left: 0;
.opacity(1);
.transition(~"all 200ms ease-in-out");
+ .is-shown { .transition-delay(@show-delay * 1); }
+ .is-shown + .is-shown { .transition-delay(@show-delay * 1.5); }
+ .is-shown + .is-shown + .is-shown { .transition-delay(@show-delay * 2); }
+ .is-shown + .is-shown + .is-shown + .is-shown { .transition-delay(@show-delay * 2.5); }
+ .is-shown + .is-shown + .is-shown + .is-shown + .is-shown { .transition-delay(@show-delay * 3); }
+ .is-shown + .is-shown + .is-shown + .is-shown + .is-shown + .is-shown { .transition-delay(@show-delay * 3.5); }
+ .is-shown + .is-shown + .is-shown + .is-shown + .is-shown + .is-shown + .is-shown { .transition-delay(@show-delay * 4); }
+ .is-shown + .is-shown + .is-shown + .is-shown + .is-shown + .is-shown + .is-shown + .is-shown { .transition-delay(@show-delay * 4.5); }
+ .is-shown + .is-shown + .is-shown + .is-shown + .is-shown + .is-shown + .is-shown + .is-shown + .is-shown { .transition-delay(@show-delay * 5); }
+ .is-shown + .is-shown + .is-shown + .is-shown + .is-shown + .is-shown + .is-shown + .is-shown + .is-shown + .is-shown { .transition-delay(@show-delay * 5.5); }
}
&.hidden-item {
visibility: hidden;
.opacity(0);
.transition(~"all 250ms ease-in-out");
}
}
// Second Level
li a { padding-left: @base-padding + @sub-spacing * 1; }
// Third Level
li ul li a { padding-left: @base-padding + @sub-spacing * 2; }
// Fourth Level
li ul li ul li a { padding-left: @base-padding + @sub-spacing * 3; }
// Fifth Level
li ul li ul li ul li a { padding-left: @base-padding + @sub-spacing * 4; }
}
}
// Scrollbar
.ps-scrollbar-x-rail .ps-scrollbar-x,
.ps-scrollbar-y-rail .ps-scrollbar-y {
background-color: fade(#fff, 60%);
}
// Fixed sidebar
&.fixed {
//position: fixed;
height: 100%;
.sidebar-menu-inner {
position: fixed;
left: 0;
top: 0;
bottom: 0;
width: inherit;
overflow: hidden;
.page-body.right-sidebar & {
left: auto;
right: 0;
}
}
}
// Collapsed sidebar
@media screen and (min-width: @screen-sm) {
&.collapsed {
width: @sidebar-collapsed-width;
z-index: 10;
overflow: visible;
.hidden-collapsed {
display: none !important;
}
+ .main-content {
.user-info-navbar {
.user-info-menu {
a[data-toggle="sidebar"] {
color: @userinfo-link-active-color;
}
}
}
.main-footer {
left: @sidebar-collapsed-width;
}
}
&.fixed {
}
.sidebar-menu-inner {
overflow: visible;
position: relative;
}
.logo-env {
@vpadd: 18px;
padding: @vpadd 0;
.logo-collapsed {
display: block;
text-align: center;
img {
display: inline-block;
}
}
.logo-expanded, .settings-icon {
display: none;
}
.logo {
float: none;
}
}
.main-menu {
padding-left: 0;
padding-right: 0;
> li {
text-align: center;
position: relative;
&.active, li.active {
background-color: darken(@sidebar-background, 3%);
}
> a {
> i {
margin-right: 0;
font-size: 16px;
}
> span {
display: none;
&.label {
display: block;
position: absolute;
right: 0;
top: 0;
}
}
}
&.has-sub {
> a:before {
display: none;
}
}
&.opened {
> ul {
display: none;
}
}
> ul {
position: absolute;
background: @sidebar-background;
width: @sidebar-collapsed-submenu-width;
top: 0;
left: 100%;
text-align: left;
//display: block;
.page-body.right-sidebar & {
left: auto;
right: 100%;
}
// First level
> li > a {
padding-left: @base-margin;
}
> li > ul > li > a {
padding-left: @base-margin + 15 * 1;
}
> li > ul > li > ul > li > a {
padding-left: @base-margin + 15 * 2;
}
> li > ul > li > ul > li > ul > li > a {
padding-left: @base-margin + 15 * 3;
}
> li > ul > li > ul > li > ul > li > ul > li > a {
padding-left: @base-margin + 15 * 4;
}
li.has-sub {
> a {
&:before {
margin-right: @base-padding;
}
}
}
}
&:hover > ul {
display: block;
}
}
}
}
}
}
// Right sidebar
.page-body.right-sidebar {
.page-container {
direction: rtl;
> * {
direction: ltr;
}
}
} | {
"pile_set_name": "Github"
} |
Moves up and down the hierarchy of imported layers
| {
"pile_set_name": "Github"
} |
use failure::Error;
mod nosuchcall;
mod nosuchstream;
pub use self::{nosuchcall::NoSuchCall, nosuchstream::NoSuchStream};
pub type Result<T> = std::result::Result<T, Error>;
| {
"pile_set_name": "Github"
} |
// closedir.hh
// -----------
//
// Maintained by Joshua Juran
// Part of the Nitrogen project.
//
// Written 2007 by Joshua Juran.
//
// This code was written entirely by the above contributor, who places it
// in the public domain.
#ifndef POSEVEN_FUNCTIONS_CLOSEDIR_HH
#define POSEVEN_FUNCTIONS_CLOSEDIR_HH
// POSIX
#ifdef __APPLE__
// Include <sys/types.h> before <dirent.h> to compile with Mac OS X 10.2's SDK.
#include <sys/types.h>
#endif
#include <dirent.h>
// nucleus
#ifndef NUCLEUS_OWNED_HH
#include "nucleus/owned.hh"
#endif
// poseven
#ifndef POSEVEN_TYPES_DIR_T_HH
#include "poseven/types/dir_t.hh"
#endif
#ifndef POSEVEN_TYPES_ERRNO_T_HH
#include "poseven/types/errno_t.hh"
#endif
namespace nucleus
{
template <>
struct disposer< poseven::dir_t >
{
typedef poseven::dir_t argument_type;
typedef void result_type;
void operator()( poseven::dir_t dir ) const
{
poseven::handle_destruction_posix_result( ::closedir( dir ) );
}
};
}
namespace poseven
{
void closedir( nucleus::owned< dir_t > dir );
}
#endif
| {
"pile_set_name": "Github"
} |
var ImageDialog = {
preInit : function() {
var url;
tinyMCEPopup.requireLangPack();
if (url = tinyMCEPopup.getParam("external_image_list_url"))
document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>');
},
init : function() {
var f = document.forms[0], ed = tinyMCEPopup.editor;
// Setup browse button
document.getElementById('srcbrowsercontainer').innerHTML = getBrowserHTML('srcbrowser','src','image','theme_advanced_image');
if (isVisible('srcbrowser'))
document.getElementById('src').style.width = '180px';
e = ed.selection.getNode();
this.fillFileList('image_list', 'tinyMCEImageList');
if (e.nodeName == 'IMG') {
f.src.value = ed.dom.getAttrib(e, 'src');
f.alt.value = ed.dom.getAttrib(e, 'alt');
f.border.value = this.getAttrib(e, 'border');
f.vspace.value = this.getAttrib(e, 'vspace');
f.hspace.value = this.getAttrib(e, 'hspace');
f.width.value = ed.dom.getAttrib(e, 'width');
f.height.value = ed.dom.getAttrib(e, 'height');
f.insert.value = ed.getLang('update');
this.styleVal = ed.dom.getAttrib(e, 'style');
selectByValue(f, 'image_list', f.src.value);
selectByValue(f, 'align', this.getAttrib(e, 'align'));
this.updateStyle();
}
},
fillFileList : function(id, l) {
var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl;
l = window[l];
if (l && l.length > 0) {
lst.options[lst.options.length] = new Option('', '');
tinymce.each(l, function(o) {
lst.options[lst.options.length] = new Option(o[0], o[1]);
});
} else
dom.remove(dom.getParent(id, 'tr'));
},
update : function() {
var f = document.forms[0], nl = f.elements, ed = tinyMCEPopup.editor, args = {}, el;
tinyMCEPopup.restoreSelection();
if (f.src.value === '') {
if (ed.selection.getNode().nodeName == 'IMG') {
ed.dom.remove(ed.selection.getNode());
ed.execCommand('mceRepaint');
}
tinyMCEPopup.close();
return;
}
if (!ed.settings.inline_styles) {
args = tinymce.extend(args, {
vspace : nl.vspace.value,
hspace : nl.hspace.value,
border : nl.border.value,
align : getSelectValue(f, 'align')
});
} else
args.style = this.styleVal;
tinymce.extend(args, {
src : f.src.value,
alt : f.alt.value,
width : f.width.value,
height : f.height.value
});
el = ed.selection.getNode();
if (el && el.nodeName == 'IMG') {
ed.dom.setAttribs(el, args);
} else {
ed.execCommand('mceInsertContent', false, '<img id="__mce_tmp" />', {skip_undo : 1});
ed.dom.setAttribs('__mce_tmp', args);
ed.dom.setAttrib('__mce_tmp', 'id', '');
ed.undoManager.add();
}
tinyMCEPopup.close();
},
updateStyle : function() {
var dom = tinyMCEPopup.dom, st, v, f = document.forms[0];
if (tinyMCEPopup.editor.settings.inline_styles) {
st = tinyMCEPopup.dom.parseStyle(this.styleVal);
// Handle align
v = getSelectValue(f, 'align');
if (v) {
if (v == 'left' || v == 'right') {
st['float'] = v;
delete st['vertical-align'];
} else {
st['vertical-align'] = v;
delete st['float'];
}
} else {
delete st['float'];
delete st['vertical-align'];
}
// Handle border
v = f.border.value;
if (v || v == '0') {
if (v == '0')
st['border'] = '0';
else
st['border'] = v + 'px solid black';
} else
delete st['border'];
// Handle hspace
v = f.hspace.value;
if (v) {
delete st['margin'];
st['margin-left'] = v + 'px';
st['margin-right'] = v + 'px';
} else {
delete st['margin-left'];
delete st['margin-right'];
}
// Handle vspace
v = f.vspace.value;
if (v) {
delete st['margin'];
st['margin-top'] = v + 'px';
st['margin-bottom'] = v + 'px';
} else {
delete st['margin-top'];
delete st['margin-bottom'];
}
// Merge
st = tinyMCEPopup.dom.parseStyle(dom.serializeStyle(st));
this.styleVal = dom.serializeStyle(st);
}
},
getAttrib : function(e, at) {
var ed = tinyMCEPopup.editor, dom = ed.dom, v, v2;
if (ed.settings.inline_styles) {
switch (at) {
case 'align':
if (v = dom.getStyle(e, 'float'))
return v;
if (v = dom.getStyle(e, 'vertical-align'))
return v;
break;
case 'hspace':
v = dom.getStyle(e, 'margin-left')
v2 = dom.getStyle(e, 'margin-right');
if (v && v == v2)
return parseInt(v.replace(/[^0-9]/g, ''));
break;
case 'vspace':
v = dom.getStyle(e, 'margin-top')
v2 = dom.getStyle(e, 'margin-bottom');
if (v && v == v2)
return parseInt(v.replace(/[^0-9]/g, ''));
break;
case 'border':
v = 0;
tinymce.each(['top', 'right', 'bottom', 'left'], function(sv) {
sv = dom.getStyle(e, 'border-' + sv + '-width');
// False or not the same as prev
if (!sv || (sv != v && v !== 0)) {
v = 0;
return false;
}
if (sv)
v = sv;
});
if (v)
return parseInt(v.replace(/[^0-9]/g, ''));
break;
}
}
if (v = dom.getAttrib(e, at))
return v;
return '';
},
resetImageData : function() {
var f = document.forms[0];
f.width.value = f.height.value = "";
},
updateImageData : function() {
var f = document.forms[0], t = ImageDialog;
if (f.width.value == "")
f.width.value = t.preloadImg.width;
if (f.height.value == "")
f.height.value = t.preloadImg.height;
},
getImageData : function() {
var f = document.forms[0];
this.preloadImg = new Image();
this.preloadImg.onload = this.updateImageData;
this.preloadImg.onerror = this.resetImageData;
this.preloadImg.src = tinyMCEPopup.editor.documentBaseURI.toAbsolute(f.src.value);
}
};
ImageDialog.preInit();
tinyMCEPopup.onInit.add(ImageDialog.init, ImageDialog);
| {
"pile_set_name": "Github"
} |
/*
Fast Artificial Neural Network Library (fann)
Copyright (C) 2003-2016 Steffen Nissen ([email protected])
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <stdio.h>
#include "fann.h"
int main()
{
struct fann *ann;
struct fann_train_data *train_data, *test_data;
const float desired_error = (const float)0.0;
unsigned int max_neurons = 30;
unsigned int neurons_between_reports = 1;
unsigned int bit_fail_train, bit_fail_test;
float mse_train, mse_test;
unsigned int i = 0;
fann_type *output;
fann_type steepness;
int multi = 0;
enum fann_activationfunc_enum activation;
enum fann_train_enum training_algorithm = FANN_TRAIN_RPROP;
printf("Reading data.\n");
train_data = fann_read_train_from_file("../datasets/parity8.train");
test_data = fann_read_train_from_file("../datasets/parity8.test");
fann_scale_train_data(train_data, -1, 1);
fann_scale_train_data(test_data, -1, 1);
printf("Creating network.\n");
ann = fann_create_shortcut(2, fann_num_input_train_data(train_data), fann_num_output_train_data(train_data));
fann_set_training_algorithm(ann, training_algorithm);
fann_set_activation_function_hidden(ann, FANN_SIGMOID_SYMMETRIC);
fann_set_activation_function_output(ann, FANN_LINEAR);
fann_set_train_error_function(ann, FANN_ERRORFUNC_LINEAR);
if(!multi)
{
/*steepness = 0.5;*/
steepness = 1;
fann_set_cascade_activation_steepnesses(ann, &steepness, 1);
/*activation = FANN_SIN_SYMMETRIC;*/
activation = FANN_SIGMOID_SYMMETRIC;
fann_set_cascade_activation_functions(ann, &activation, 1);
fann_set_cascade_num_candidate_groups(ann, 8);
}
if(training_algorithm == FANN_TRAIN_QUICKPROP)
{
fann_set_learning_rate(ann, 0.35f);
fann_randomize_weights(ann, -2.0f, 2.0f);
}
fann_set_bit_fail_limit(ann, (fann_type)0.9);
fann_set_train_stop_function(ann, FANN_STOPFUNC_BIT);
fann_print_parameters(ann);
fann_save(ann, "cascade_train2.net");
printf("Training network.\n");
fann_cascadetrain_on_data(ann, train_data, max_neurons, neurons_between_reports, desired_error);
fann_print_connections(ann);
mse_train = fann_test_data(ann, train_data);
bit_fail_train = fann_get_bit_fail(ann);
mse_test = fann_test_data(ann, test_data);
bit_fail_test = fann_get_bit_fail(ann);
printf("\nTrain error: %f, Train bit-fail: %d, Test error: %f, Test bit-fail: %d\n\n",
mse_train, bit_fail_train, mse_test, bit_fail_test);
for(i = 0; i < train_data->num_data; i++)
{
output = fann_run(ann, train_data->input[i]);
if((train_data->output[i][0] >= 0 && output[0] <= 0) ||
(train_data->output[i][0] <= 0 && output[0] >= 0))
{
printf("ERROR: %f does not match %f\n", train_data->output[i][0], output[0]);
}
}
printf("Saving network.\n");
fann_save(ann, "cascade_train.net");
printf("Cleaning up.\n");
fann_destroy_train(train_data);
fann_destroy_train(test_data);
fann_destroy(ann);
return 0;
}
| {
"pile_set_name": "Github"
} |
//===--- FindTarget.cpp - What does an AST node refer to? -----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "FindTarget.h"
#include "AST.h"
#include "support/Logger.h"
#include "clang/AST/ASTTypeTraits.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/AST/DeclarationName.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprConcepts.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/NestedNameSpecifier.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/AST/TemplateBase.h"
#include "clang/AST/Type.h"
#include "clang/AST/TypeLoc.h"
#include "clang/AST/TypeLocVisitor.h"
#include "clang/AST/TypeVisitor.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/OperatorKinds.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/Specifiers.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/raw_ostream.h"
#include <iterator>
#include <utility>
#include <vector>
namespace clang {
namespace clangd {
namespace {
using ast_type_traits::DynTypedNode;
LLVM_ATTRIBUTE_UNUSED std::string
nodeToString(const ast_type_traits::DynTypedNode &N) {
std::string S = std::string(N.getNodeKind().asStringRef());
{
llvm::raw_string_ostream OS(S);
OS << ": ";
N.print(OS, PrintingPolicy(LangOptions()));
}
std::replace(S.begin(), S.end(), '\n', ' ');
return S;
}
// Helper function for getMembersReferencedViaDependentName()
// which takes a possibly-dependent type `T` and heuristically
// resolves it to a CXXRecordDecl in which we can try name lookup.
CXXRecordDecl *resolveTypeToRecordDecl(const Type *T) {
assert(T);
if (const auto *RT = T->getAs<RecordType>())
return dyn_cast<CXXRecordDecl>(RT->getDecl());
if (const auto *ICNT = T->getAs<InjectedClassNameType>())
T = ICNT->getInjectedSpecializationType().getTypePtrOrNull();
if (!T)
return nullptr;
const auto *TST = T->getAs<TemplateSpecializationType>();
if (!TST)
return nullptr;
const ClassTemplateDecl *TD = dyn_cast_or_null<ClassTemplateDecl>(
TST->getTemplateName().getAsTemplateDecl());
if (!TD)
return nullptr;
return TD->getTemplatedDecl();
}
// Given a tag-decl type and a member name, heuristically resolve the
// name to one or more declarations.
// The current heuristic is simply to look up the name in the primary
// template. This is a heuristic because the template could potentially
// have specializations that declare different members.
// Multiple declarations could be returned if the name is overloaded
// (e.g. an overloaded method in the primary template).
// This heuristic will give the desired answer in many cases, e.g.
// for a call to vector<T>::size().
// The name to look up is provided in the form of a factory that takes
// an ASTContext, because an ASTContext may be needed to obtain the
// name (e.g. if it's an operator name), but the caller may not have
// access to an ASTContext.
std::vector<const NamedDecl *> getMembersReferencedViaDependentName(
const Type *T,
llvm::function_ref<DeclarationName(ASTContext &)> NameFactory,
llvm::function_ref<bool(const NamedDecl *ND)> Filter) {
if (!T)
return {};
if (auto *ET = T->getAs<EnumType>()) {
auto Result =
ET->getDecl()->lookup(NameFactory(ET->getDecl()->getASTContext()));
return {Result.begin(), Result.end()};
}
if (auto *RD = resolveTypeToRecordDecl(T)) {
if (!RD->hasDefinition())
return {};
RD = RD->getDefinition();
DeclarationName Name = NameFactory(RD->getASTContext());
return RD->lookupDependentName(Name, Filter);
}
return {};
}
const auto NonStaticFilter = [](const NamedDecl *D) {
return D->isCXXInstanceMember();
};
const auto StaticFilter = [](const NamedDecl *D) {
return !D->isCXXInstanceMember();
};
const auto ValueFilter = [](const NamedDecl *D) { return isa<ValueDecl>(D); };
// Given the type T of a dependent expression that appears of the LHS of a
// "->", heuristically find a corresponding pointee type in whose scope we
// could look up the name appearing on the RHS.
const Type *getPointeeType(const Type *T) {
if (!T)
return nullptr;
if (T->isPointerType()) {
return T->getAs<PointerType>()->getPointeeType().getTypePtrOrNull();
}
// Try to handle smart pointer types.
// Look up operator-> in the primary template. If we find one, it's probably a
// smart pointer type.
auto ArrowOps = getMembersReferencedViaDependentName(
T,
[](ASTContext &Ctx) {
return Ctx.DeclarationNames.getCXXOperatorName(OO_Arrow);
},
NonStaticFilter);
if (ArrowOps.empty())
return nullptr;
// Getting the return type of the found operator-> method decl isn't useful,
// because we discarded template arguments to perform lookup in the primary
// template scope, so the return type would just have the form U* where U is a
// template parameter type.
// Instead, just handle the common case where the smart pointer type has the
// form of SmartPtr<X, ...>, and assume X is the pointee type.
auto *TST = T->getAs<TemplateSpecializationType>();
if (!TST)
return nullptr;
if (TST->getNumArgs() == 0)
return nullptr;
const TemplateArgument &FirstArg = TST->getArg(0);
if (FirstArg.getKind() != TemplateArgument::Type)
return nullptr;
return FirstArg.getAsType().getTypePtrOrNull();
}
// Forward declaration, needed as this function is mutually recursive
// with resolveExprToDecls.
const Type *resolveExprToType(const Expr *E);
// Try to heuristically resolve a possibly-dependent expression `E` to one
// or more declarations that it likely references.
std::vector<const NamedDecl *> resolveExprToDecls(const Expr *E) {
if (const auto *ME = dyn_cast<CXXDependentScopeMemberExpr>(E)) {
const Type *BaseType = ME->getBaseType().getTypePtrOrNull();
if (ME->isArrow()) {
BaseType = getPointeeType(BaseType);
}
if (!BaseType)
return {};
if (const auto *BT = BaseType->getAs<BuiltinType>()) {
// If BaseType is the type of a dependent expression, it's just
// represented as BultinType::Dependent which gives us no information. We
// can get further by analyzing the depedent expression.
Expr *Base = ME->isImplicitAccess() ? nullptr : ME->getBase();
if (Base && BT->getKind() == BuiltinType::Dependent) {
BaseType = resolveExprToType(Base);
}
}
return getMembersReferencedViaDependentName(
BaseType, [ME](ASTContext &) { return ME->getMember(); },
NonStaticFilter);
}
if (const auto *RE = dyn_cast<DependentScopeDeclRefExpr>(E)) {
return getMembersReferencedViaDependentName(
RE->getQualifier()->getAsType(),
[RE](ASTContext &) { return RE->getDeclName(); }, StaticFilter);
}
if (const auto *CE = dyn_cast<CallExpr>(E)) {
const auto *CalleeType = resolveExprToType(CE->getCallee());
if (!CalleeType)
return {};
if (const auto *FnTypePtr = CalleeType->getAs<PointerType>())
CalleeType = FnTypePtr->getPointeeType().getTypePtr();
if (const FunctionType *FnType = CalleeType->getAs<FunctionType>()) {
if (const auto *D =
resolveTypeToRecordDecl(FnType->getReturnType().getTypePtr())) {
return {D};
}
}
}
if (const auto *ME = dyn_cast<MemberExpr>(E))
return {ME->getMemberDecl()};
if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
return {DRE->getFoundDecl()};
return {};
}
// Try to heuristically resolve the type of a possibly-dependent expression `E`.
const Type *resolveExprToType(const Expr *E) {
std::vector<const NamedDecl *> Decls = resolveExprToDecls(E);
if (Decls.size() != 1) // Names an overload set -- just bail.
return nullptr;
if (const auto *TD = dyn_cast<TypeDecl>(Decls[0])) {
return TD->getTypeForDecl();
} else if (const auto *VD = dyn_cast<ValueDecl>(Decls[0])) {
return VD->getType().getTypePtrOrNull();
}
return nullptr;
}
const NamedDecl *getTemplatePattern(const NamedDecl *D) {
if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
if (const auto *Result = CRD->getTemplateInstantiationPattern())
return Result;
// getTemplateInstantiationPattern returns null if the Specialization is
// incomplete (e.g. the type didn't need to be complete), fall back to the
// primary template.
if (CRD->getTemplateSpecializationKind() == TSK_Undeclared)
if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(CRD))
return Spec->getSpecializedTemplate()->getTemplatedDecl();
} else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
return FD->getTemplateInstantiationPattern();
} else if (auto *VD = dyn_cast<VarDecl>(D)) {
// Hmm: getTIP returns its arg if it's not an instantiation?!
VarDecl *T = VD->getTemplateInstantiationPattern();
return (T == D) ? nullptr : T;
} else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
return ED->getInstantiatedFromMemberEnum();
} else if (isa<FieldDecl>(D) || isa<TypedefNameDecl>(D)) {
if (const auto *Parent = llvm::dyn_cast<NamedDecl>(D->getDeclContext()))
if (const DeclContext *ParentPat =
dyn_cast_or_null<DeclContext>(getTemplatePattern(Parent)))
for (const NamedDecl *BaseND : ParentPat->lookup(D->getDeclName()))
if (!BaseND->isImplicit() && BaseND->getKind() == D->getKind())
return BaseND;
} else if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
if (const auto *ED = dyn_cast<EnumDecl>(ECD->getDeclContext())) {
if (const EnumDecl *Pattern = ED->getInstantiatedFromMemberEnum()) {
for (const NamedDecl *BaseECD : Pattern->lookup(ECD->getDeclName()))
return BaseECD;
}
}
}
return nullptr;
}
// TargetFinder locates the entities that an AST node refers to.
//
// Typically this is (possibly) one declaration and (possibly) one type, but
// may be more:
// - for ambiguous nodes like OverloadExpr
// - if we want to include e.g. both typedefs and the underlying type
//
// This is organized as a set of mutually recursive helpers for particular node
// types, but for most nodes this is a short walk rather than a deep traversal.
//
// It's tempting to do e.g. typedef resolution as a second normalization step,
// after finding the 'primary' decl etc. But we do this monolithically instead
// because:
// - normalization may require these traversals again (e.g. unwrapping a
// typedef reveals a decltype which must be traversed)
// - it doesn't simplify that much, e.g. the first stage must still be able
// to yield multiple decls to handle OverloadExpr
// - there are cases where it's required for correctness. e.g:
// template<class X> using pvec = vector<x*>; pvec<int> x;
// There's no Decl `pvec<int>`, we must choose `pvec<X>` or `vector<int*>`
// and both are lossy. We must know upfront what the caller ultimately wants.
//
// FIXME: improve common dependent scope using name lookup in primary templates.
// We currently handle DependentScopeDeclRefExpr and
// CXXDependentScopeMemberExpr, but some other constructs remain to be handled:
// - DependentTemplateSpecializationType,
// - DependentNameType
// - UnresolvedUsingTypenameDecl
struct TargetFinder {
using RelSet = DeclRelationSet;
using Rel = DeclRelation;
private:
llvm::SmallDenseMap<const NamedDecl *,
std::pair<RelSet, /*InsertionOrder*/ size_t>>
Decls;
RelSet Flags;
template <typename T> void debug(T &Node, RelSet Flags) {
dlog("visit [{0}] {1}", Flags,
nodeToString(ast_type_traits::DynTypedNode::create(Node)));
}
void report(const NamedDecl *D, RelSet Flags) {
dlog("--> [{0}] {1}", Flags,
nodeToString(ast_type_traits::DynTypedNode::create(*D)));
auto It = Decls.try_emplace(D, std::make_pair(Flags, Decls.size()));
// If already exists, update the flags.
if (!It.second)
It.first->second.first |= Flags;
}
public:
llvm::SmallVector<std::pair<const NamedDecl *, RelSet>, 1> takeDecls() const {
using ValTy = std::pair<const NamedDecl *, RelSet>;
llvm::SmallVector<ValTy, 1> Result;
Result.resize(Decls.size());
for (const auto &Elem : Decls)
Result[Elem.second.second] = {Elem.first, Elem.second.first};
return Result;
}
void add(const Decl *Dcl, RelSet Flags) {
const NamedDecl *D = llvm::dyn_cast_or_null<NamedDecl>(Dcl);
if (!D)
return;
debug(*D, Flags);
if (const UsingDirectiveDecl *UDD = llvm::dyn_cast<UsingDirectiveDecl>(D))
D = UDD->getNominatedNamespaceAsWritten();
if (const TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(D)) {
add(TND->getUnderlyingType(), Flags | Rel::Underlying);
Flags |= Rel::Alias; // continue with the alias.
} else if (const UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
for (const UsingShadowDecl *S : UD->shadows())
add(S->getUnderlyingDecl(), Flags | Rel::Underlying);
Flags |= Rel::Alias; // continue with the alias.
} else if (const auto *NAD = dyn_cast<NamespaceAliasDecl>(D)) {
add(NAD->getUnderlyingDecl(), Flags | Rel::Underlying);
Flags |= Rel::Alias; // continue with the alias
} else if (const UnresolvedUsingValueDecl *UUVD =
dyn_cast<UnresolvedUsingValueDecl>(D)) {
for (const NamedDecl *Target : getMembersReferencedViaDependentName(
UUVD->getQualifier()->getAsType(),
[UUVD](ASTContext &) { return UUVD->getNameInfo().getName(); },
ValueFilter)) {
add(Target, Flags | Rel::Underlying);
}
Flags |= Rel::Alias; // continue with the alias
} else if (const UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D)) {
// Include the using decl, but don't traverse it. This may end up
// including *all* shadows, which we don't want.
report(USD->getUsingDecl(), Flags | Rel::Alias);
// Shadow decls are synthetic and not themselves interesting.
// Record the underlying decl instead, if allowed.
D = USD->getTargetDecl();
Flags |= Rel::Underlying; // continue with the underlying decl.
} else if (const auto *DG = dyn_cast<CXXDeductionGuideDecl>(D)) {
D = DG->getDeducedTemplate();
} else if (const ObjCImplementationDecl *IID =
dyn_cast<ObjCImplementationDecl>(D)) {
// Treat ObjC{Interface,Implementation}Decl as if they were a decl/def
// pair as long as the interface isn't implicit.
if (const auto *CID = IID->getClassInterface())
if (const auto *DD = CID->getDefinition())
if (!DD->isImplicitInterfaceDecl())
D = DD;
} else if (const ObjCCategoryImplDecl *CID =
dyn_cast<ObjCCategoryImplDecl>(D)) {
// Treat ObjC{Category,CategoryImpl}Decl as if they were a decl/def pair.
D = CID->getCategoryDecl();
}
if (!D)
return;
if (const Decl *Pat = getTemplatePattern(D)) {
assert(Pat != D);
add(Pat, Flags | Rel::TemplatePattern);
// Now continue with the instantiation.
Flags |= Rel::TemplateInstantiation;
}
report(D, Flags);
}
void add(const Stmt *S, RelSet Flags) {
if (!S)
return;
debug(*S, Flags);
struct Visitor : public ConstStmtVisitor<Visitor> {
TargetFinder &Outer;
RelSet Flags;
Visitor(TargetFinder &Outer, RelSet Flags) : Outer(Outer), Flags(Flags) {}
void VisitCallExpr(const CallExpr *CE) {
Outer.add(CE->getCalleeDecl(), Flags);
}
void VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E) {
Outer.add(E->getNamedConcept(), Flags);
}
void VisitDeclRefExpr(const DeclRefExpr *DRE) {
const Decl *D = DRE->getDecl();
// UsingShadowDecl allows us to record the UsingDecl.
// getFoundDecl() returns the wrong thing in other cases (templates).
if (auto *USD = llvm::dyn_cast<UsingShadowDecl>(DRE->getFoundDecl()))
D = USD;
Outer.add(D, Flags);
}
void VisitMemberExpr(const MemberExpr *ME) {
const Decl *D = ME->getMemberDecl();
if (auto *USD =
llvm::dyn_cast<UsingShadowDecl>(ME->getFoundDecl().getDecl()))
D = USD;
Outer.add(D, Flags);
}
void VisitOverloadExpr(const OverloadExpr *OE) {
for (auto *D : OE->decls())
Outer.add(D, Flags);
}
void VisitSizeOfPackExpr(const SizeOfPackExpr *SE) {
Outer.add(SE->getPack(), Flags);
}
void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
Outer.add(CCE->getConstructor(), Flags);
}
void VisitDesignatedInitExpr(const DesignatedInitExpr *DIE) {
for (const DesignatedInitExpr::Designator &D :
llvm::reverse(DIE->designators()))
if (D.isFieldDesignator()) {
Outer.add(D.getField(), Flags);
// We don't know which designator was intended, we assume the outer.
break;
}
}
void VisitGotoStmt(const GotoStmt *Goto) {
if (auto *LabelDecl = Goto->getLabel())
Outer.add(LabelDecl, Flags);
}
void VisitLabelStmt(const LabelStmt *Label) {
if (auto *LabelDecl = Label->getDecl())
Outer.add(LabelDecl, Flags);
}
void
VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
for (const NamedDecl *D : resolveExprToDecls(E)) {
Outer.add(D, Flags);
}
}
void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E) {
for (const NamedDecl *D : resolveExprToDecls(E)) {
Outer.add(D, Flags);
}
}
void VisitObjCIvarRefExpr(const ObjCIvarRefExpr *OIRE) {
Outer.add(OIRE->getDecl(), Flags);
}
void VisitObjCMessageExpr(const ObjCMessageExpr *OME) {
Outer.add(OME->getMethodDecl(), Flags);
}
void VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *OPRE) {
if (OPRE->isExplicitProperty())
Outer.add(OPRE->getExplicitProperty(), Flags);
else {
if (OPRE->isMessagingGetter())
Outer.add(OPRE->getImplicitPropertyGetter(), Flags);
if (OPRE->isMessagingSetter())
Outer.add(OPRE->getImplicitPropertySetter(), Flags);
}
}
void VisitObjCProtocolExpr(const ObjCProtocolExpr *OPE) {
Outer.add(OPE->getProtocol(), Flags);
}
void VisitOpaqueValueExpr(const OpaqueValueExpr *OVE) {
Outer.add(OVE->getSourceExpr(), Flags);
}
void VisitPseudoObjectExpr(const PseudoObjectExpr *POE) {
Outer.add(POE->getSyntacticForm(), Flags);
}
void VisitCXXNewExpr(const CXXNewExpr *CNE) {
Outer.add(CNE->getOperatorNew(), Flags);
}
void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE) {
Outer.add(CDE->getOperatorDelete(), Flags);
}
};
Visitor(*this, Flags).Visit(S);
}
void add(QualType T, RelSet Flags) {
if (T.isNull())
return;
debug(T, Flags);
struct Visitor : public TypeVisitor<Visitor> {
TargetFinder &Outer;
RelSet Flags;
Visitor(TargetFinder &Outer, RelSet Flags) : Outer(Outer), Flags(Flags) {}
void VisitTagType(const TagType *TT) {
Outer.add(TT->getAsTagDecl(), Flags);
}
void VisitElaboratedType(const ElaboratedType *ET) {
Outer.add(ET->desugar(), Flags);
}
void VisitInjectedClassNameType(const InjectedClassNameType *ICNT) {
Outer.add(ICNT->getDecl(), Flags);
}
void VisitDecltypeType(const DecltypeType *DTT) {
Outer.add(DTT->getUnderlyingType(), Flags | Rel::Underlying);
}
void VisitDeducedType(const DeducedType *DT) {
// FIXME: In practice this doesn't work: the AutoType you find inside
// TypeLoc never has a deduced type. https://llvm.org/PR42914
Outer.add(DT->getDeducedType(), Flags | Rel::Underlying);
}
void VisitDeducedTemplateSpecializationType(
const DeducedTemplateSpecializationType *DTST) {
// FIXME: This is a workaround for https://llvm.org/PR42914,
// which is causing DTST->getDeducedType() to be empty. We
// fall back to the template pattern and miss the instantiation
// even when it's known in principle. Once that bug is fixed,
// this method can be removed (the existing handling in
// VisitDeducedType() is sufficient).
if (auto *TD = DTST->getTemplateName().getAsTemplateDecl())
Outer.add(TD->getTemplatedDecl(), Flags | Rel::TemplatePattern);
}
void VisitTypedefType(const TypedefType *TT) {
Outer.add(TT->getDecl(), Flags);
}
void
VisitTemplateSpecializationType(const TemplateSpecializationType *TST) {
// Have to handle these case-by-case.
// templated type aliases: there's no specialized/instantiated using
// decl to point to. So try to find a decl for the underlying type
// (after substitution), and failing that point to the (templated) using
// decl.
if (TST->isTypeAlias()) {
Outer.add(TST->getAliasedType(), Flags | Rel::Underlying);
// Don't *traverse* the alias, which would result in traversing the
// template of the underlying type.
Outer.report(
TST->getTemplateName().getAsTemplateDecl()->getTemplatedDecl(),
Flags | Rel::Alias | Rel::TemplatePattern);
}
// specializations of template template parameters aren't instantiated
// into decls, so they must refer to the parameter itself.
else if (const auto *Parm =
llvm::dyn_cast_or_null<TemplateTemplateParmDecl>(
TST->getTemplateName().getAsTemplateDecl()))
Outer.add(Parm, Flags);
// class template specializations have a (specialized) CXXRecordDecl.
else if (const CXXRecordDecl *RD = TST->getAsCXXRecordDecl())
Outer.add(RD, Flags); // add(Decl) will despecialize if needed.
else {
// fallback: the (un-specialized) declaration from primary template.
if (auto *TD = TST->getTemplateName().getAsTemplateDecl())
Outer.add(TD->getTemplatedDecl(), Flags | Rel::TemplatePattern);
}
}
void VisitTemplateTypeParmType(const TemplateTypeParmType *TTPT) {
Outer.add(TTPT->getDecl(), Flags);
}
void VisitObjCInterfaceType(const ObjCInterfaceType *OIT) {
Outer.add(OIT->getDecl(), Flags);
}
void VisitObjCObjectType(const ObjCObjectType *OOT) {
// FIXME: ObjCObjectTypeLoc has no children for the protocol list, so
// there is no node in id<Foo> that refers to ObjCProtocolDecl Foo.
if (OOT->isObjCQualifiedId() && OOT->getNumProtocols() == 1)
Outer.add(OOT->getProtocol(0), Flags);
}
};
Visitor(*this, Flags).Visit(T.getTypePtr());
}
void add(const NestedNameSpecifier *NNS, RelSet Flags) {
if (!NNS)
return;
debug(*NNS, Flags);
switch (NNS->getKind()) {
case NestedNameSpecifier::Identifier:
return;
case NestedNameSpecifier::Namespace:
add(NNS->getAsNamespace(), Flags);
return;
case NestedNameSpecifier::NamespaceAlias:
add(NNS->getAsNamespaceAlias(), Flags);
return;
case NestedNameSpecifier::TypeSpec:
case NestedNameSpecifier::TypeSpecWithTemplate:
add(QualType(NNS->getAsType(), 0), Flags);
return;
case NestedNameSpecifier::Global:
// This should be TUDecl, but we can't get a pointer to it!
return;
case NestedNameSpecifier::Super:
add(NNS->getAsRecordDecl(), Flags);
return;
}
llvm_unreachable("unhandled NestedNameSpecifier::SpecifierKind");
}
void add(const CXXCtorInitializer *CCI, RelSet Flags) {
if (!CCI)
return;
debug(*CCI, Flags);
if (CCI->isAnyMemberInitializer())
add(CCI->getAnyMember(), Flags);
// Constructor calls contain a TypeLoc node, so we don't handle them here.
}
void add(const TemplateArgument &Arg, RelSet Flags) {
// Only used for template template arguments.
// For type and non-type template arguments, SelectionTree
// will hit a more specific node (e.g. a TypeLoc or a
// DeclRefExpr).
if (Arg.getKind() == TemplateArgument::Template ||
Arg.getKind() == TemplateArgument::TemplateExpansion) {
if (TemplateDecl *TD = Arg.getAsTemplate().getAsTemplateDecl()) {
report(TD, Flags);
}
}
}
};
} // namespace
llvm::SmallVector<std::pair<const NamedDecl *, DeclRelationSet>, 1>
allTargetDecls(const ast_type_traits::DynTypedNode &N) {
dlog("allTargetDecls({0})", nodeToString(N));
TargetFinder Finder;
DeclRelationSet Flags;
if (const Decl *D = N.get<Decl>())
Finder.add(D, Flags);
else if (const Stmt *S = N.get<Stmt>())
Finder.add(S, Flags);
else if (const NestedNameSpecifierLoc *NNSL = N.get<NestedNameSpecifierLoc>())
Finder.add(NNSL->getNestedNameSpecifier(), Flags);
else if (const NestedNameSpecifier *NNS = N.get<NestedNameSpecifier>())
Finder.add(NNS, Flags);
else if (const TypeLoc *TL = N.get<TypeLoc>())
Finder.add(TL->getType(), Flags);
else if (const QualType *QT = N.get<QualType>())
Finder.add(*QT, Flags);
else if (const CXXCtorInitializer *CCI = N.get<CXXCtorInitializer>())
Finder.add(CCI, Flags);
else if (const TemplateArgumentLoc *TAL = N.get<TemplateArgumentLoc>())
Finder.add(TAL->getArgument(), Flags);
return Finder.takeDecls();
}
llvm::SmallVector<const NamedDecl *, 1>
targetDecl(const ast_type_traits::DynTypedNode &N, DeclRelationSet Mask) {
llvm::SmallVector<const NamedDecl *, 1> Result;
for (const auto &Entry : allTargetDecls(N)) {
if (!(Entry.second & ~Mask))
Result.push_back(Entry.first);
}
return Result;
}
llvm::SmallVector<const NamedDecl *, 1>
explicitReferenceTargets(DynTypedNode N, DeclRelationSet Mask) {
assert(!(Mask & (DeclRelation::TemplatePattern |
DeclRelation::TemplateInstantiation)) &&
"explicitReferenceTargets handles templates on its own");
auto Decls = allTargetDecls(N);
// We prefer to return template instantiation, but fallback to template
// pattern if instantiation is not available.
Mask |= DeclRelation::TemplatePattern | DeclRelation::TemplateInstantiation;
llvm::SmallVector<const NamedDecl *, 1> TemplatePatterns;
llvm::SmallVector<const NamedDecl *, 1> Targets;
bool SeenTemplateInstantiations = false;
for (auto &D : Decls) {
if (D.second & ~Mask)
continue;
if (D.second & DeclRelation::TemplatePattern) {
TemplatePatterns.push_back(D.first);
continue;
}
if (D.second & DeclRelation::TemplateInstantiation)
SeenTemplateInstantiations = true;
Targets.push_back(D.first);
}
if (!SeenTemplateInstantiations)
Targets.insert(Targets.end(), TemplatePatterns.begin(),
TemplatePatterns.end());
return Targets;
}
namespace {
llvm::SmallVector<ReferenceLoc, 2> refInDecl(const Decl *D) {
struct Visitor : ConstDeclVisitor<Visitor> {
llvm::SmallVector<ReferenceLoc, 2> Refs;
void VisitUsingDirectiveDecl(const UsingDirectiveDecl *D) {
// We want to keep it as non-declaration references, as the
// "using namespace" declaration doesn't have a name.
Refs.push_back(ReferenceLoc{D->getQualifierLoc(),
D->getIdentLocation(),
/*IsDecl=*/false,
{D->getNominatedNamespaceAsWritten()}});
}
void VisitUsingDecl(const UsingDecl *D) {
// "using ns::identifier;" is a non-declaration reference.
Refs.push_back(
ReferenceLoc{D->getQualifierLoc(), D->getLocation(), /*IsDecl=*/false,
explicitReferenceTargets(DynTypedNode::create(*D),
DeclRelation::Underlying)});
}
void VisitNamespaceAliasDecl(const NamespaceAliasDecl *D) {
// For namespace alias, "namespace Foo = Target;", we add two references.
// Add a declaration reference for Foo.
VisitNamedDecl(D);
// Add a non-declaration reference for Target.
Refs.push_back(ReferenceLoc{D->getQualifierLoc(),
D->getTargetNameLoc(),
/*IsDecl=*/false,
{D->getAliasedNamespace()}});
}
void VisitNamedDecl(const NamedDecl *ND) {
// We choose to ignore {Class, Function, Var, TypeAlias}TemplateDecls. As
// as their underlying decls, covering the same range, will be visited.
if (llvm::isa<ClassTemplateDecl>(ND) ||
llvm::isa<FunctionTemplateDecl>(ND) ||
llvm::isa<VarTemplateDecl>(ND) ||
llvm::isa<TypeAliasTemplateDecl>(ND))
return;
// FIXME: decide on how to surface destructors when we need them.
if (llvm::isa<CXXDestructorDecl>(ND))
return;
// Filter anonymous decls, name location will point outside the name token
// and the clients are not prepared to handle that.
if (ND->getDeclName().isIdentifier() &&
!ND->getDeclName().getAsIdentifierInfo())
return;
Refs.push_back(ReferenceLoc{getQualifierLoc(*ND),
ND->getLocation(),
/*IsDecl=*/true,
{ND}});
}
void VisitCXXDeductionGuideDecl(const CXXDeductionGuideDecl *DG) {
// The class template name in a deduction guide targets the class
// template.
Refs.push_back(ReferenceLoc{DG->getQualifierLoc(),
DG->getNameInfo().getLoc(),
/*IsDecl=*/false,
{DG->getDeducedTemplate()}});
}
};
Visitor V;
V.Visit(D);
return V.Refs;
}
llvm::SmallVector<ReferenceLoc, 2> refInStmt(const Stmt *S) {
struct Visitor : ConstStmtVisitor<Visitor> {
// FIXME: handle more complicated cases: more ObjC, designated initializers.
llvm::SmallVector<ReferenceLoc, 2> Refs;
void VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E) {
Refs.push_back(ReferenceLoc{E->getNestedNameSpecifierLoc(),
E->getConceptNameLoc(),
/*IsDecl=*/false,
{E->getNamedConcept()}});
}
void VisitDeclRefExpr(const DeclRefExpr *E) {
Refs.push_back(ReferenceLoc{E->getQualifierLoc(),
E->getNameInfo().getLoc(),
/*IsDecl=*/false,
{E->getFoundDecl()}});
}
void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E) {
Refs.push_back(ReferenceLoc{
E->getQualifierLoc(), E->getNameInfo().getLoc(), /*IsDecl=*/false,
explicitReferenceTargets(DynTypedNode::create(*E), {})});
}
void VisitMemberExpr(const MemberExpr *E) {
// Skip destructor calls to avoid duplication: TypeLoc within will be
// visited separately.
if (llvm::dyn_cast<CXXDestructorDecl>(E->getFoundDecl().getDecl()))
return;
Refs.push_back(ReferenceLoc{E->getQualifierLoc(),
E->getMemberNameInfo().getLoc(),
/*IsDecl=*/false,
{E->getFoundDecl()}});
}
void
VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
Refs.push_back(
ReferenceLoc{E->getQualifierLoc(), E->getMemberNameInfo().getLoc(),
/*IsDecl=*/false,
explicitReferenceTargets(DynTypedNode::create(*E), {})});
}
void VisitOverloadExpr(const OverloadExpr *E) {
Refs.push_back(ReferenceLoc{E->getQualifierLoc(),
E->getNameInfo().getLoc(),
/*IsDecl=*/false,
llvm::SmallVector<const NamedDecl *, 1>(
E->decls().begin(), E->decls().end())});
}
void VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
E->getPackLoc(),
/*IsDecl=*/false,
{E->getPack()}});
}
void VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *E) {
Refs.push_back(ReferenceLoc{
NestedNameSpecifierLoc(), E->getLocation(),
/*IsDecl=*/false,
// Select the getter, setter, or @property depending on the call.
explicitReferenceTargets(DynTypedNode::create(*E), {})});
}
void VisitDesignatedInitExpr(const DesignatedInitExpr *DIE) {
for (const DesignatedInitExpr::Designator &D : DIE->designators()) {
if (!D.isFieldDesignator())
continue;
llvm::SmallVector<const NamedDecl *, 1> Targets;
if (D.getField())
Targets.push_back(D.getField());
Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), D.getFieldLoc(),
/*IsDecl=*/false, std::move(Targets)});
}
}
void VisitGotoStmt(const GotoStmt *GS) {
llvm::SmallVector<const NamedDecl *, 1> Targets;
if (const auto *L = GS->getLabel())
Targets.push_back(L);
Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(), GS->getLabelLoc(),
/*IsDecl=*/false, std::move(Targets)});
}
void VisitLabelStmt(const LabelStmt *LS) {
Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
LS->getIdentLoc(),
/*IsDecl=*/true,
{LS->getDecl()}});
}
};
Visitor V;
V.Visit(S);
return V.Refs;
}
llvm::SmallVector<ReferenceLoc, 2> refInTypeLoc(TypeLoc L) {
struct Visitor : TypeLocVisitor<Visitor> {
llvm::Optional<ReferenceLoc> Ref;
void VisitElaboratedTypeLoc(ElaboratedTypeLoc L) {
// We only know about qualifier, rest if filled by inner locations.
Visit(L.getNamedTypeLoc().getUnqualifiedLoc());
// Fill in the qualifier.
if (!Ref)
return;
assert(!Ref->Qualifier.hasQualifier() && "qualifier already set");
Ref->Qualifier = L.getQualifierLoc();
}
void VisitTagTypeLoc(TagTypeLoc L) {
Ref = ReferenceLoc{NestedNameSpecifierLoc(),
L.getNameLoc(),
/*IsDecl=*/false,
{L.getDecl()}};
}
void VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc L) {
Ref = ReferenceLoc{NestedNameSpecifierLoc(),
L.getNameLoc(),
/*IsDecl=*/false,
{L.getDecl()}};
}
void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc L) {
// We must ensure template type aliases are included in results if they
// were written in the source code, e.g. in
// template <class T> using valias = vector<T>;
// ^valias<int> x;
// 'explicitReferenceTargets' will return:
// 1. valias with mask 'Alias'.
// 2. 'vector<int>' with mask 'Underlying'.
// we want to return only #1 in this case.
Ref = ReferenceLoc{
NestedNameSpecifierLoc(), L.getTemplateNameLoc(), /*IsDecl=*/false,
explicitReferenceTargets(DynTypedNode::create(L.getType()),
DeclRelation::Alias)};
}
void VisitDeducedTemplateSpecializationTypeLoc(
DeducedTemplateSpecializationTypeLoc L) {
Ref = ReferenceLoc{
NestedNameSpecifierLoc(), L.getNameLoc(), /*IsDecl=*/false,
explicitReferenceTargets(DynTypedNode::create(L.getType()),
DeclRelation::Alias)};
}
void VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
Ref = ReferenceLoc{NestedNameSpecifierLoc(),
TL.getNameLoc(),
/*IsDecl=*/false,
{TL.getDecl()}};
}
void VisitDependentTemplateSpecializationTypeLoc(
DependentTemplateSpecializationTypeLoc L) {
Ref = ReferenceLoc{
L.getQualifierLoc(), L.getTemplateNameLoc(), /*IsDecl=*/false,
explicitReferenceTargets(DynTypedNode::create(L.getType()), {})};
}
void VisitDependentNameTypeLoc(DependentNameTypeLoc L) {
Ref = ReferenceLoc{
L.getQualifierLoc(), L.getNameLoc(), /*IsDecl=*/false,
explicitReferenceTargets(DynTypedNode::create(L.getType()), {})};
}
void VisitTypedefTypeLoc(TypedefTypeLoc L) {
Ref = ReferenceLoc{NestedNameSpecifierLoc(),
L.getNameLoc(),
/*IsDecl=*/false,
{L.getTypedefNameDecl()}};
}
};
Visitor V;
V.Visit(L.getUnqualifiedLoc());
if (!V.Ref)
return {};
return {*V.Ref};
}
class ExplicitReferenceCollector
: public RecursiveASTVisitor<ExplicitReferenceCollector> {
public:
ExplicitReferenceCollector(llvm::function_ref<void(ReferenceLoc)> Out)
: Out(Out) {
assert(Out);
}
bool VisitTypeLoc(TypeLoc TTL) {
if (TypeLocsToSkip.count(TTL.getBeginLoc().getRawEncoding()))
return true;
visitNode(DynTypedNode::create(TTL));
return true;
}
bool TraverseElaboratedTypeLoc(ElaboratedTypeLoc L) {
// ElaboratedTypeLoc will reports information for its inner type loc.
// Otherwise we loose information about inner types loc's qualifier.
TypeLoc Inner = L.getNamedTypeLoc().getUnqualifiedLoc();
TypeLocsToSkip.insert(Inner.getBeginLoc().getRawEncoding());
return RecursiveASTVisitor::TraverseElaboratedTypeLoc(L);
}
bool VisitStmt(Stmt *S) {
visitNode(DynTypedNode::create(*S));
return true;
}
bool TraverseOpaqueValueExpr(OpaqueValueExpr *OVE) {
visitNode(DynTypedNode::create(*OVE));
// Not clear why the source expression is skipped by default...
// FIXME: can we just make RecursiveASTVisitor do this?
return RecursiveASTVisitor::TraverseStmt(OVE->getSourceExpr());
}
bool TraversePseudoObjectExpr(PseudoObjectExpr *POE) {
visitNode(DynTypedNode::create(*POE));
// Traverse only the syntactic form to find the *written* references.
// (The semantic form also contains lots of duplication)
return RecursiveASTVisitor::TraverseStmt(POE->getSyntacticForm());
}
// We re-define Traverse*, since there's no corresponding Visit*.
// TemplateArgumentLoc is the only way to get locations for references to
// template template parameters.
bool TraverseTemplateArgumentLoc(TemplateArgumentLoc A) {
llvm::SmallVector<const NamedDecl *, 1> Targets;
switch (A.getArgument().getKind()) {
case TemplateArgument::Template:
case TemplateArgument::TemplateExpansion:
if (const auto *D = A.getArgument()
.getAsTemplateOrTemplatePattern()
.getAsTemplateDecl())
Targets.push_back(D);
reportReference(ReferenceLoc{A.getTemplateQualifierLoc(),
A.getTemplateNameLoc(),
/*IsDecl=*/false, Targets},
DynTypedNode::create(A.getArgument()));
break;
case TemplateArgument::Declaration:
break; // FIXME: can this actually happen in TemplateArgumentLoc?
case TemplateArgument::Integral:
case TemplateArgument::Null:
case TemplateArgument::NullPtr:
break; // no references.
case TemplateArgument::Pack:
case TemplateArgument::Type:
case TemplateArgument::Expression:
break; // Handled by VisitType and VisitExpression.
};
return RecursiveASTVisitor::TraverseTemplateArgumentLoc(A);
}
bool VisitDecl(Decl *D) {
visitNode(DynTypedNode::create(*D));
return true;
}
// We have to use Traverse* because there is no corresponding Visit*.
bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc L) {
if (!L.getNestedNameSpecifier())
return true;
visitNode(DynTypedNode::create(L));
// Inner type is missing information about its qualifier, skip it.
if (auto TL = L.getTypeLoc())
TypeLocsToSkip.insert(TL.getBeginLoc().getRawEncoding());
return RecursiveASTVisitor::TraverseNestedNameSpecifierLoc(L);
}
bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
visitNode(DynTypedNode::create(*Init));
return RecursiveASTVisitor::TraverseConstructorInitializer(Init);
}
private:
/// Obtain information about a reference directly defined in \p N. Does not
/// recurse into child nodes, e.g. do not expect references for constructor
/// initializers
///
/// Any of the fields in the returned structure can be empty, but not all of
/// them, e.g.
/// - for implicitly generated nodes (e.g. MemberExpr from range-based-for),
/// source location information may be missing,
/// - for dependent code, targets may be empty.
///
/// (!) For the purposes of this function declarations are not considered to
/// be references. However, declarations can have references inside them,
/// e.g. 'namespace foo = std' references namespace 'std' and this
/// function will return the corresponding reference.
llvm::SmallVector<ReferenceLoc, 2> explicitReference(DynTypedNode N) {
if (auto *D = N.get<Decl>())
return refInDecl(D);
if (auto *S = N.get<Stmt>())
return refInStmt(S);
if (auto *NNSL = N.get<NestedNameSpecifierLoc>()) {
// (!) 'DeclRelation::Alias' ensures we do not loose namespace aliases.
return {ReferenceLoc{
NNSL->getPrefix(), NNSL->getLocalBeginLoc(), false,
explicitReferenceTargets(
DynTypedNode::create(*NNSL->getNestedNameSpecifier()),
DeclRelation::Alias)}};
}
if (const TypeLoc *TL = N.get<TypeLoc>())
return refInTypeLoc(*TL);
if (const CXXCtorInitializer *CCI = N.get<CXXCtorInitializer>()) {
// Other type initializers (e.g. base initializer) are handled by visiting
// the typeLoc.
if (CCI->isAnyMemberInitializer()) {
return {ReferenceLoc{NestedNameSpecifierLoc(),
CCI->getMemberLocation(),
/*IsDecl=*/false,
{CCI->getAnyMember()}}};
}
}
// We do not have location information for other nodes (QualType, etc)
return {};
}
void visitNode(DynTypedNode N) {
for (const auto &R : explicitReference(N))
reportReference(R, N);
}
void reportReference(const ReferenceLoc &Ref, DynTypedNode N) {
// Our promise is to return only references from the source code. If we lack
// location information, skip these nodes.
// Normally this should not happen in practice, unless there are bugs in the
// traversals or users started the traversal at an implicit node.
if (Ref.NameLoc.isInvalid()) {
dlog("invalid location at node {0}", nodeToString(N));
return;
}
Out(Ref);
}
llvm::function_ref<void(ReferenceLoc)> Out;
/// TypeLocs starting at these locations must be skipped, see
/// TraverseElaboratedTypeSpecifierLoc for details.
llvm::DenseSet</*SourceLocation*/ unsigned> TypeLocsToSkip;
};
} // namespace
void findExplicitReferences(const Stmt *S,
llvm::function_ref<void(ReferenceLoc)> Out) {
assert(S);
ExplicitReferenceCollector(Out).TraverseStmt(const_cast<Stmt *>(S));
}
void findExplicitReferences(const Decl *D,
llvm::function_ref<void(ReferenceLoc)> Out) {
assert(D);
ExplicitReferenceCollector(Out).TraverseDecl(const_cast<Decl *>(D));
}
void findExplicitReferences(const ASTContext &AST,
llvm::function_ref<void(ReferenceLoc)> Out) {
ExplicitReferenceCollector(Out).TraverseAST(const_cast<ASTContext &>(AST));
}
llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, DeclRelation R) {
switch (R) {
#define REL_CASE(X) \
case DeclRelation::X: \
return OS << #X;
REL_CASE(Alias);
REL_CASE(Underlying);
REL_CASE(TemplateInstantiation);
REL_CASE(TemplatePattern);
#undef REL_CASE
}
llvm_unreachable("Unhandled DeclRelation enum");
}
llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, DeclRelationSet RS) {
const char *Sep = "";
for (unsigned I = 0; I < RS.S.size(); ++I) {
if (RS.S.test(I)) {
OS << Sep << static_cast<DeclRelation>(I);
Sep = "|";
}
}
return OS;
}
llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, ReferenceLoc R) {
// note we cannot print R.NameLoc without a source manager.
OS << "targets = {";
bool First = true;
for (const NamedDecl *T : R.Targets) {
if (!First)
OS << ", ";
else
First = false;
OS << printQualifiedName(*T) << printTemplateSpecializationArgs(*T);
}
OS << "}";
if (R.Qualifier) {
OS << ", qualifier = '";
R.Qualifier.getNestedNameSpecifier()->print(OS,
PrintingPolicy(LangOptions()));
OS << "'";
}
if (R.IsDecl)
OS << ", decl";
return OS;
}
} // namespace clangd
} // namespace clang
| {
"pile_set_name": "Github"
} |
'use strict'
const { describe, it } = require('mocha')
const { expect } = require('chai')
const createProxyAclPage = require('../../../../add-on/src/pages/proxy-acl/page')
const { objToAcl } = require('../../../helpers/acl')
const createMockI18n = require('../../../helpers/mock-i18n')
describe('pages/proxy-acl/page', () => {
it('should render with empty ACL', async () => {
const i18n = createMockI18n()
const state = { acl: objToAcl({}) }
let res
expect(() => { res = createProxyAclPage(i18n)(state) }).to.not.throw()
expect(res.toString()).to.have.string('page_proxyAcl_no_perms')
})
it('should render with single scope ACL and single allowed permission', async () => {
const i18n = createMockI18n()
const state = {
acl: objToAcl({
'https://ipfs.io/': {
'ipfs.files.add': true
}
})
}
let res
expect(() => { res = createProxyAclPage(i18n)(state).toString() }).to.not.throw()
expect(res).to.have.string('https://ipfs.io')
expect(res).to.have.string('page_proxyAcl_toggle_to_deny_button_title')
expect(res).to.have.string('ipfs.files.add')
})
it('should render with single scope ACL and single denied permission', async () => {
const i18n = createMockI18n()
const state = {
acl: objToAcl({
'https://ipfs.io/': {
'ipfs.files.add': false
}
})
}
let res
expect(() => { res = createProxyAclPage(i18n)(state).toString() }).to.not.throw()
expect(res).to.have.string('https://ipfs.io')
expect(res).to.have.string('page_proxyAcl_toggle_to_allow_button_title')
expect(res).to.have.string('ipfs.files.add')
})
it('should render with single scope ACL and multiple permissions', async () => {
const i18n = createMockI18n()
const state = {
acl: objToAcl({
'https://ipfs.io/': {
'ipfs.files.add': true,
'ipfs.object.new': false
}
})
}
let res
expect(() => { res = createProxyAclPage(i18n)(state).toString() }).to.not.throw()
expect(res).to.have.string('https://ipfs.io')
expect(res).to.have.string('page_proxyAcl_toggle_to_deny_button_title')
expect(res).to.have.string('page_proxyAcl_toggle_to_allow_button_title')
expect(res).to.have.string('ipfs.files.add')
expect(res).to.have.string('ipfs.object.new')
})
it('should render with multiple scopes and multiple permissions', async () => {
const i18n = createMockI18n()
const state = {
acl: objToAcl({
'https://ipfs.io/': {
'ipfs.files.add': false,
'ipfs.object.new': true
},
'https://ipld.io/': {
'ipfs.block.put': true
}
})
}
let res
expect(() => { res = createProxyAclPage(i18n)(state).toString() }).to.not.throw()
expect(res).to.have.string('https://ipfs.io/')
expect(res).to.have.string('https://ipld.io/')
expect(res).to.have.string('page_proxyAcl_toggle_to_allow_button_title')
expect(res).to.have.string('page_proxyAcl_toggle_to_deny_button_title')
expect(res).to.have.string('ipfs.files.add')
expect(res).to.have.string('ipfs.object.new')
expect(res).to.have.string('ipfs.block.put')
})
})
| {
"pile_set_name": "Github"
} |
package gitter
import (
"github.com/oklahomer/go-sarah/v3/retry"
"time"
)
// Config contains some configuration variables for gitter Adapter.
type Config struct {
Token string `json:"token" yaml:"token"`
RetryPolicy *retry.Policy `json:"retry_policy" yaml:"retry_policy"`
}
// NewConfig returns initialized Config struct with default settings.
// Token is empty at this point. Token can be set by feeding this instance to json.Unmarshal/yaml.Unmarshal,
// or direct assignment.
func NewConfig() *Config {
return &Config{
Token: "",
RetryPolicy: &retry.Policy{
Trial: 10,
Interval: 500 * time.Millisecond,
},
}
}
| {
"pile_set_name": "Github"
} |
新华网 消息
法国 费加罗 日前 报道 阵风 战斗机 阵风 战斗机 接受 真正 战火 洗礼 战斗机 至少 空军 接受 检验 海军 阵风 战斗机 戴高乐 航空母舰 经受 考验 阵风 战斗机 法国 达索 航空 公司 制造 国防部 介绍 阵风 计划 证实 飞机 批量 生产 投入 使用 期限 得到 遵守
军备 总工程师 帕特里克·迪富尔 计划 带动 法国 其他部门 发展 名副其实 技术 火车头 去年 进入 真正 生产 阶段 军队 提供 阵风 战斗机 出厂 军队 需求量 已确定 空军 海军 迄今 订购
法国 空军 建立 阵风 战斗机 大队 飞机 驻扎 法国 圣迪济 武器 系统 达到 F2 标准 能够 发射 Scalp 空对地 巡航导弹 目前 法国 海军 服役 阵风 战斗机 达到 能够 执行 空防 任务 F1 标准 阵风 战斗机 达到 F3 多用途 标准 发射 ASMPA 空对地 导弹 执行 侦察 攻击 任务 目前 空军 订购 阵风 战斗机 可在 组成 新的 战斗机 大队
海军 空军 同意 下述 看法 阵风 战斗机 多用途 一次 真正 革命 使用 维修 阵风 战斗机 最终 取代 以下 飞机 幻影 IV 战斗机 美洲 战斗机 幻影 F1 战斗机 幻影 战斗机 十字军 战士 战斗机 超军 战斗机 军旗 IVP 战斗机 法国 蒙德马桑 空军 试验 中心 主任 埃里克·鲁佐 将军 阵风 战斗机 执行 任务 能力 部署 战场 飞机 数量 大大 减少 节省 维修 方面 人力 物力 阵风 战斗机 需要 机械 维修 人员 一代 战机 20% 25%
另 飞跃 技术 方面 进步 阵风 战斗机 装备 多种 高性能 传感器 先进 数据 通讯 系统 具有 盟军 飞机 协同 作战 能力 阵风 战斗机 友好 对抗 演习 表现 赞赏 军官 沙特阿拉伯 战斗机 比利时 战斗机 一起 进行 军事 演习 看出 阵风 战斗机 具有 非同寻常 应变 能力 飞行员 演习 往往 占优势 | {
"pile_set_name": "Github"
} |
//this example starts discovery on adapter
//after discovery process GetDevices method
//returns list of discovered devices
//then with the help of mac address
//connectivity starts
//once sensors are connected it will
//fetch sensor name,manufacturer detail,
//firmware version, hardware version, model
//and sensor data...
package obex_push_example
import (
"sync"
"time"
"github.com/muka/go-bluetooth/api"
"github.com/muka/go-bluetooth/bluez/profile/obex"
log "github.com/sirupsen/logrus"
)
var wg sync.WaitGroup
func Run(targetAddress, filePath, adapterID string) error {
a, err := api.GetAdapter(adapterID)
if err != nil {
return err
}
dev, err := a.GetDeviceByAddress(targetAddress)
if err != nil {
return err
}
log.Debugf("device %s (%s)", dev.Properties.Name, dev.Properties.Address)
if dev == nil {
return err
}
props, err := dev.GetProperties()
if err != nil {
return err
}
if !props.Paired {
log.Debug("not paired")
err = dev.Pair()
if err != nil {
return err
}
} else {
log.Debug("already paired")
}
sessionArgs := map[string]interface{}{}
sessionArgs["Target"] = "opp"
obexClient := obex.NewObexClient1()
tries := 1
maxRetry := 20
var sessionPath string
for tries < maxRetry {
log.Debug("Create Session...")
sessionPath, err = obexClient.CreateSession(targetAddress, sessionArgs)
if err == nil {
break
}
tries++
if err != nil {
return err
}
}
if tries >= maxRetry {
log.Fatal("Max tries reached")
}
log.Debug("Session created: ", sessionPath)
obexSession := obex.NewObexSession1(sessionPath)
sessionProps, err := obexSession.GetProperties()
if err != nil {
return err
}
log.Debug("Source : ", sessionProps.Source)
log.Debug("Destination : ", sessionProps.Destination)
log.Debug("Channel : ", sessionProps.Channel)
log.Debug("Target : ", sessionProps.Target)
log.Debug("Root : ", sessionProps.Root)
log.Debug("Init transmission on ", sessionPath)
obexObjectPush := obex.NewObjectPush1(sessionPath)
log.Debug("Send File: ", filePath)
transPath, transProps, err := obexObjectPush.SendFile(filePath)
if err != nil {
return err
}
log.Debug("Transmission initiated: ", transPath)
log.Debug("Status : ", transProps.Status)
log.Debug("Session : ", transProps.Session)
log.Debug("Name : ", transProps.Name)
log.Debug("Type : ", transProps.Type)
log.Debug("Time : ", transProps.Time)
log.Debug("Size : ", transProps.Size)
log.Debug("Transferred : ", transProps.Transferred)
log.Debug("Filename : ", transProps.Filename)
for transProps.Transferred < transProps.Size {
time.Sleep(1 * time.Second)
obexTransfer := obex.NewObexTransfer1(transPath)
transProps, err = obexTransfer.GetProperties()
if err != nil {
return err
}
transferedPercent := (100 / float64(transProps.Size)) * float64(transProps.Transferred)
log.Debug("Progress : ", transferedPercent)
}
obexClient.RemoveSession(sessionPath)
log.Debug(sessionPath)
return nil
}
| {
"pile_set_name": "Github"
} |
Issuer services help companies from around the world to join the London equity market in order to gain access to capital.
The LSE allows companies to raise money, increase their profile and obtain a market valuation through a variety of routes, thus following the firms throughout the whole IPO process.
The London Stock Exchange runs several markets for listing, giving an opportunity for different sized companies to list.
International companies can list a number of products in London including shares, depositary receipts and debt, offering different and cost-effective ways to raise capital.
In 2004 the Exchange opened a Hong Kong office and has attracted more than 200 companies from the Asia-Pacific region.
For the biggest companies exists the Premium Listed Main Market.
This operates a Super Equivalence method where conditions of both the UK Listing Authority as well as London Stock Exchange’s own criteria have to be met.
The largest IPO on the Exchange was completed in May 2011 by Glencore International plc.
The company raised $10 billion at admission, making it one of the largest IPOs ever. | {
"pile_set_name": "Github"
} |
/* ChadoTransaction
*
* created: July 2006
*
* This file is part of Artemis
*
* Copyright (C) 2006 Genome Research Limited
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
package uk.ac.sanger.artemis.chado;
import java.sql.Timestamp;
import uk.ac.sanger.artemis.io.GFFStreamFeature;
import uk.ac.sanger.artemis.util.DatabaseDocument;
/**
* Store information about a SQL transaction <i>e.g</i> UPDATE, INSERT, DELETE
* a feature, featureloc, featureprop, feature_dbxref, feature_synonym.
**/
public class ChadoTransaction
{
//
// FEATURE TRANSACTIONS
/** update statement */
public static final int UPDATE = 1;
/** insert statement */
public static final int INSERT = 2;
/** delete statement */
public static final int DELETE = 3;
/** type of statement <i>e.g.</i> UPDATE, INSERT, DELETE, ... */
protected int type;
/** feature unique name */
protected String old_uniquename;
private String uniquename;
/** last time feature was modified */
private Timestamp lastmodified;
/** the feature object */
private Object feature_obj;
/** the feature key */
private String featureKey;
private GFFStreamFeature gff_feature;
private String logComment;
/**
* Create a transaction to represent a single insert, delete or
* update.
* @param type the type of transcation, e.g. insert, delete, update.
* @param feature_obj the <code>Feature</code>, <code>FeatureLoc</code>,
* <code>FeatureProp</code>, <code>FeatureRelationship</code>, <code>FeatureDbxref</code>,
* or <code>FeatureSynonym</code>.
* @param lastmodified the last modified timestamp
* @param gff_feature the artemis GFF feature effected
*/
public ChadoTransaction(final int type,
final Object feature_obj,
final Timestamp lastmodified,
final GFFStreamFeature gff_feature,
final String featureKey,
final String logComment)
{
this.type = type;
this.lastmodified = lastmodified;
this.feature_obj = feature_obj;
this.gff_feature = gff_feature;
this.logComment = logComment;
if(featureKey != null &&
featureKey.equals(DatabaseDocument.EXONMODEL))
this.featureKey = "exon";
else
this.featureKey = featureKey;
}
/**
* Copy this transaction
* @return
*/
public ChadoTransaction copy()
{
final ChadoTransaction tsn = new ChadoTransaction(getType(), getFeatureObject(),
getLastModified(), getGff_feature(),
getFeatureKey(), logComment);
if(uniquename != null)
tsn.setUniquename(uniquename);
tsn.setOldUniquename(old_uniquename);
return tsn;
}
/**
* The type of SQL transaction
* @return the transaction type
*/
public int getType()
{
return type;
}
public String getTypeAsString()
{
if(type == UPDATE)
return "UPDATE";
else if(type == INSERT)
return "INSERT";
else if(type == DELETE)
return "DELETE";
return "";
}
/**
* Set the old uniquename, used when updating the uniquename
* @param uniquename
*/
public void setOldUniquename(final String old_uniquename)
{
this.old_uniquename = old_uniquename;
}
/**
* Get the unique names of features to change.
*/
public String getOldUniquename()
{
return old_uniquename;
}
/**
* Set a uniquename, e.g. to be used when changing a featureprop
* @param uniquename
*/
public void setUniquename(final String uniquename)
{
this.uniquename = uniquename;
}
public String getUniquename()
{
if(uniquename != null)
return uniquename;
if(getGff_feature() == null)
return null;
return (String)
getGff_feature().getQualifierByName("ID").getValues().get(0);
}
/**
* Get the last time modified time stamp.
* @return the <code>Timestamp</code>
*/
public Timestamp getLastModified()
{
return this.lastmodified;
}
public Object getFeatureObject()
{
return feature_obj;
}
public GFFStreamFeature getGff_feature()
{
return gff_feature;
}
public String getFeatureKey()
{
return featureKey;
}
public String getLogComment()
{
String key = "";
if(getFeatureKey() != null)
key = " KEY=" + getFeatureKey();
return "["+getTypeAsString()+"] "+logComment+key;
}
}
| {
"pile_set_name": "Github"
} |
saute procfs lyonnais
procfs supports two levels of directory. the filesystem root
directory contains a representation of the system process table.
this consists of an entry for each active and zombie process, and
an additional entry "curproc" which always represents the process
making the lookup request.
each of the sub-directories contains several files. these files
are used to control and interrogate processes. the files implemented
are:
file - xxx. the exec'ed file.
status - r/o. returns process status.
ctl - w/o. sends a control message to the process.
for example:
echo hup > /proc/curproc/note
will send a SIGHUP to the shell.
whereas
echo attach > /proc/1293/ctl
would set up process 1293 for debugging.
see below for more details.
mem - r/w. virtual memory image of the process.
parts of the address space are readable
only if they exist in the target process.
a more reasonable alternative might be
to return zero pages instead of an error.
comments?
note - w/o. writing a string here sends the
equivalent note to the process.
[ not implemented. ]
notepg - w/o. the same as note, but sends to all
members of the process group.
[ not implemented. ]
regs - r/w. process register set. this can be read
or written any time even if the process
is not stopped. since the bsd kernel
is single-processor, this implementation
will get the "right" register values.
a multi-proc kernel would need to do some
synchronisation.
this then looks like:
% ls -li /proc
total 0
9 dr-xr-xr-x 2 root wheel 0 Sep 21 15:06 0
17 dr-xr-xr-x 2 root wheel 0 Sep 21 15:06 1
89 dr-xr-xr-x 2 root wheel 0 Sep 21 15:06 10
25 dr-xr-xr-x 2 root wheel 0 Sep 21 15:06 2
2065 dr-xr-xr-x 2 root wheel 0 Sep 21 15:06 257
2481 dr-xr-xr-x 2 jsp staff 0 Sep 21 15:06 309
265 dr-xr-xr-x 2 root wheel 0 Sep 21 15:06 32
3129 dr-xr-xr-x 2 jsp staff 0 Sep 21 15:06 390
3209 dr-xr-xr-x 2 jsp staff 0 Sep 21 15:06 400
3217 dr-xr-xr-x 2 jsp staff 0 Sep 21 15:06 401
3273 dr-xr-xr-x 2 jsp staff 0 Sep 21 15:06 408
393 dr-xr-xr-x 2 root wheel 0 Sep 21 15:06 48
409 dr-xr-xr-x 2 root wheel 0 Sep 21 15:06 50
465 dr-xr-xr-x 2 root wheel 0 Sep 21 15:06 57
481 dr-xr-xr-x 2 root wheel 0 Sep 21 15:06 59
537 dr-xr-xr-x 2 root kmem 0 Sep 21 15:06 66
545 dr-xr-xr-x 2 root wheel 0 Sep 21 15:06 67
657 dr-xr-xr-x 2 jsp staff 0 Sep 21 15:06 81
665 dr-xr-xr-x 2 jsp staff 0 Sep 21 15:06 82
673 dr-xr-xr-x 2 jsp staff 0 Sep 21 15:06 83
681 dr-xr-xr-x 2 root wheel 0 Sep 21 15:06 84
3273 dr-xr-xr-x 2 jsp staff 0 Sep 21 15:06 curproc
% ls -li /proc/curproc
total 408
3341 --w------- 1 jsp staff 0 Sep 21 15:06 ctl
1554 -r-xr-xr-x 1 bin bin 90112 Mar 29 04:52 file
3339 -rw------- 1 jsp staff 118784 Sep 21 15:06 mem
3343 --w------- 1 jsp staff 0 Sep 21 15:06 note
3344 --w------- 1 jsp staff 0 Sep 21 15:06 notepg
3340 -rw------- 1 jsp staff 0 Sep 21 15:06 regs
3342 -r--r--r-- 1 jsp staff 0 Sep 21 15:06 status
% df /proc/curproc /proc/curproc/file
Filesystem 512-blocks Used Avail Capacity Mounted on
proc 2 2 0 100% /proc
/dev/wd0a 16186 13548 1018 93% /
% cat /proc/curproc/status
cat 446 439 400 81 12,0 ctty 748620684 270000 0 0 0 20000 nochan 11 20 20 20 0 21 117
the basic sequence of commands written to "ctl" would be
attach - this stops the target process and
arranges for the sending process
to become the debug control process
wait - wait for the target process to come to
a steady state ready for debugging.
step - single step, with no signal delivery.
run - continue running, with no signal delivery,
until next trap or breakpoint.
<signame> - deliver signal <signame> and continue running.
detach - continue execution of the target process
and remove it from control by the debug process
in a normal debugging environment, where the target is fork/exec'd by
the debugger, the debugger should fork and the child should stop itself
(with a self-inflicted SIGSTOP). the parent should do a "wait" then an
"attach". as before, the child will hit a breakpoint on the first
instruction in any newly exec'd image.
$Id: README,v 3.1 1993/12/15 09:40:17 jsp Exp $
| {
"pile_set_name": "Github"
} |
package com.example.moviedb.ui.screen.profile
import com.example.moviedb.R
import com.example.moviedb.databinding.FragmentProfileBinding
import com.example.moviedb.ui.base.BaseFragment
import org.koin.androidx.viewmodel.ext.android.viewModel
class ProfileFragment: BaseFragment<FragmentProfileBinding, ProfileViewModel>() {
override val layoutId: Int
get() = R.layout.fragment_profile
override val viewModel: ProfileViewModel by viewModel()
} | {
"pile_set_name": "Github"
} |
:020000021000EC
:10FC000001C0F3C0112484B790E890936100109272
:10FC10006100882369F0982F9A70923049F081FF33
:10FC200002C097EF94BF282E80E002D10C94000010
:10FC300085E08093810082E08093C00088E180931A
:10FC4000C10087E08093C40086E08093C2008EE00C
:10FC5000EFD0259A84E02FE13FEF91E030938500CB
:10FC60002093840096BBB09BFECF1D9AA89540912F
:10FC7000C00047FD02C0815089F7CED0813479F4AD
:10FC8000CBD0C82FDBD0C23811F480E004C088E0AC
:10FC9000C13809F083E0B9D080E1B7D0EECF82342B
:10FCA00019F484E1D3D0F8CF853411F485E0FACF8C
:10FCB000853581F4B1D0E82EAFD0F82E87FF07C08C
:10FCC0008BB781608BBFEE0CFF1CB8D0E5CF8BB734
:10FCD0008E7FF8CF863579F49FD08D3451F49CD047
:10FCE000CBB79AD0C170880F8C2B8BBF81E0AED080
:10FCF000CCCF83E0FCCF843609F046C08DD0C82F2E
:10FD0000D0E0DC2FCC2788D0C82B86D0D82E5E013F
:10FD10008EEFB81A00E012E04801EFEF8E1A9E0A4B
:10FD20007BD0F801808384018A149B04A9F786D0D4
:10FD3000F5E410E000E0DF1609F150E040E063E098
:10FD4000C70153D08701C12C92E0D92EF601419111
:10FD500051916F0161E0C80148D00E5F1F4F22979B
:10FD6000A9F750E040E065E0C7013FD095CF608142
:10FD7000C8018E0D9F1D79D00F5F1F4FF801FE5FE8
:10FD8000C017D107A1F788CF843701F545D0C82F18
:10FD9000D0E0DC2FCC2740D0C82B3ED0D82E4ED080
:10FDA0008701F5E4DF120BC0CE0DDF1DC80155D071
:10FDB0002CD00F5F1F4FC017D107C1F76DCFF801CF
:10FDC00087918F0122D02197D1F766CF853739F4FB
:10FDD00035D08EE11AD087E918D084E05CCF813528
:10FDE00009F073CF88E024D070CFFC010A0167BF0F
:10FDF000E895112407B600FCFDCF667029F0452B6D
:10FE000019F481E187BFE89508959091C00095FFAE
:10FE1000FCCF8093C60008958091C00087FFFCCF7F
:10FE20008091C00084FD01C0A8958091C60008950E
:10FE3000E0E6F0E098E1908380830895EDDF803282
:10FE400019F088E0F5DFFFCF84E1DFCFCF93C82F33
:10FE5000E3DFC150E9F7CF91F1CFF999FECF92BD21
:10FE600081BDF89A992780B50895262FF999FECF7C
:10FE70001FBA92BD81BD20BD0FB6F894FA9AF99AC7
:06FE80000FBE019608957B
:02FFFE000008F9
:040000031000FC00ED
:00000001FF
| {
"pile_set_name": "Github"
} |
<?xml version="1.0"?>
<block>
<name>Burst Type Filter</name>
<key>gsm_burst_type_filter</key>
<import>import grgsm</import>
<make>grgsm.burst_type_filter($selected_burst_types)</make>
<param>
<name>Selected burst types</name>
<key>selected_burst_types</key>
<value>[0,1,2,3,4,5,6,7]</value>
<type>int_vector</type>
</param>
<sink>
<name>bursts_in</name>
<type>message</type>
<optional>1</optional>
</sink>
<source>
<name>bursts_out</name>
<type>message</type>
<optional>1</optional>
</source>
<doc>
This block filters bursts based on their type.
For more information on burst types, see GSM 05.02.
</doc>
</block>
| {
"pile_set_name": "Github"
} |
Fix stripping when cross-compiling
Probably-Signed-off-by: Dave Bender <[email protected]>
[[email protected]: patch was made by Dave, but he
forgot his SoB line, so I added it]
Signed-off-by: "Yann E. MORIN" <[email protected]>
diff -rupN openldap-2.4.40/build/shtool openldap-2.4.40-br/build/shtool
--- openldap-2.4.40/build/shtool 2014-09-18 21:48:49.000000000 -0400
+++ openldap-2.4.40-br/build/shtool 2015-01-21 13:21:35.689829372 -0500
@@ -981,7 +981,7 @@ install )
if [ ".$opt_t" = .yes ]; then
echo "strip $dsttmp" 1>&2
fi
- strip $dsttmp || shtool_exit $?
+ $STRIP $dsttmp || shtool_exit $?
fi
if [ ".$opt_o" != . ]; then
if [ ".$opt_t" = .yes ]; then
diff -rupN openldap-2.4.40/build/top.mk openldap-2.4.40-br/build/top.mk
--- openldap-2.4.40/build/top.mk 2014-09-18 21:48:49.000000000 -0400
+++ openldap-2.4.40-br/build/top.mk 2015-01-21 13:23:41.027810097 -0500
@@ -59,7 +59,7 @@ INSTALL_PROGRAM = $(INSTALL)
INSTALL_DATA = $(INSTALL) -m 644
INSTALL_SCRIPT = $(INSTALL)
-STRIP = -s
+STRIP_OPTS = -s
LINT = lint
5LINT = 5lint
diff -rupN openldap-2.4.40/clients/tools/Makefile.in openldap-2.4.40-br/clients/tools/Makefile.in
--- openldap-2.4.40/clients/tools/Makefile.in 2014-09-18 21:48:49.000000000 -0400
+++ openldap-2.4.40-br/clients/tools/Makefile.in 2015-01-21 13:23:35.827727946 -0500
@@ -120,7 +120,7 @@ install-local: FORCE
-$(MKDIR) $(DESTDIR)$(bindir)
@( \
for prg in $(PROGRAMS); do \
- $(LTINSTALL) $(INSTALLFLAGS) $(STRIP) -m 755 $$prg$(EXEEXT) \
+ $(LTINSTALL) $(INSTALLFLAGS) $(STRIP_OPTS) -m 755 $$prg$(EXEEXT) \
$(DESTDIR)$(bindir); \
done \
)
diff -rupN openldap-2.4.40/configure.in openldap-2.4.40-br/configure.in
--- openldap-2.4.40/configure.in 2014-09-18 21:48:49.000000000 -0400
+++ openldap-2.4.40-br/configure.in 2015-01-16 15:50:48.874816786 -0500
@@ -669,6 +669,15 @@ if test -z "${AR}"; then
fi
fi
+if test -z "${STRIP}"; then
+ AC_CHECK_PROGS(STRIP,strip,missing)
+
+ if test "${STRIP}" = "missing" ; then
+ AC_MSG_ERROR([Unable to locate strip(1) or suitable replacement. Check PATH or set STRIP.])
+ fi
+fi
+
+
AC_LIBTOOL_WIN32_DLL
AC_LIBTOOL_DLOPEN
AC_PROG_LIBTOOL
diff -rupN openldap-2.4.40/servers/slapd/Makefile.in openldap-2.4.40-br/servers/slapd/Makefile.in
--- openldap-2.4.40/servers/slapd/Makefile.in 2015-01-16 15:04:52.507473256 -0500
+++ openldap-2.4.40-br/servers/slapd/Makefile.in 2015-01-16 15:05:02.299627229 -0500
@@ -378,7 +378,7 @@ install-local-srv: install-slapd install
install-slapd: FORCE
-$(MKDIR) $(DESTDIR)$(libexecdir)
-$(MKDIR) $(DESTDIR)$(localstatedir)/run
- $(LTINSTALL) $(INSTALLFLAGS) $(STRIP) -m 755 \
+ $(LTINSTALL) $(INSTALLFLAGS) $(STRIP_OPTS) -m 755 \
slapd$(EXEEXT) $(DESTDIR)$(libexecdir)
@for i in $(SUBDIRS); do \
if test -d $$i && test -f $$i/Makefile ; then \
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python
# coding=utf-8
import random
def randomized_quicksort(items, p, r):
if p < r:
q = randomized_partition(items, p, r)
randomized_quicksort(items, p, q-1)
randomized_quicksort(items, q+1, r)
def randomized_partition(items, p, r):
i = random.randint(p, r)
items[i],items[r] = items[r],items[i]
return partition(items, p, r)
def partition(items, p, r):
x = items[r]
i = p-1
for j in range(p, r):
if items[j] <= x:
i = i + 1
items[i],items[j] = items[j],items[i]
items[i+1],items[r] = items[r],items[i+1]
return i+1
items = [2,5,9,3,7,0,-1]
randomized_quicksort(items, 0, len(items)-1)
print items
| {
"pile_set_name": "Github"
} |
msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2019-11-19T10:49:23+00:00\n"
"PO-Revision-Date: 2020-07-30 07:47+0000\n"
"Last-Translator: Paul Heckler <[email protected]>\n"
"Language-Team: French <http://translate.pkp.sfu.ca/projects/ojs/default/fr/>"
"\n"
"Language: fr_FR\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=n > 1;\n"
"X-Generator: Weblate 3.9.1\n"
msgid "default.contextSettings.checklist.notPreviouslyPublished"
msgstr "La soumission n'a pas déjà été publiée et n'est pas considérée actuellement par une autre revue. Si ce n'est pas le cas, fournir une explication dans le champ \"Commentaires au rédacteur\"."
msgid "default.contextSettings.checklist.fileFormat"
msgstr "Le fichier de la soumission est dans un des formats de fichier suivants : OpenOffice, Microsoft Word, RTF ou WordPerfect."
msgid "default.contextSettings.checklist.submissionAppearance"
msgstr "Le texte est à simple interligne, utilise une police de 12 points, emploie l'italique plutôt que le souligné (sauf pour les adresses URL) et place toutes les illustrations, figures et tableaux aux endroits appropriés dans le texte plutôt qu'à la fin."
msgid "default.contextSettings.checklist.bibliographicRequirements"
msgstr "Le texte se conforme aux exigences stylistiques et bibliographiques décrites dans les <a href=\"{$indexUrl}{$contextPath}/about/submissions#authorGuidelines\">Directives aux auteurs</a>, qui se trouvent dans la section « À propos de la revue »."
msgid "default.contextSettings.privacyStatement"
msgstr "<p>Les noms et courriels saisis dans le site de cette revue seront utilisés exclusivement aux fins indiquées par cette revue et ne serviront à aucune autre fin, ni à toute autre partie.</p>"
msgid "default.contextSettings.openAccessPolicy"
msgstr "Cette revue fournit l'accès libre immédiat à son contenu se basant sur le principe que rendre la recherche disponible au public gratuitement facilite un plus grand échange du savoir, à l'échelle de la planète."
msgid "default.contextSettings.emailSignature"
msgstr ""
"<br/>\n"
"________________________________________________________________________<br/>\n"
"<a href=\"{$contextUrl}\">{$contextName}</a>"
msgid "default.contextSettings.forReaders"
msgstr "Nous invitons les lecteurs à s'inscrire pour recevoir les avis de publication de cette revue. Utiliser le lien <a href=\"{$indexUrl}{$contextPath}/user/register\">S'inscrire</a> en haut de la page d'accueil de la revue. Cette inscription permettra au lecteur de recevoir par courriel la table des matières de chaque nouveau numéro de la revue. Cette liste permet aussi à la revue de revendiquer un certain niveau de soutien ou de lectorat. Voir la <a href=\"{$indexUrl}{$contextPath}/about/submissions#privacyStatement\">Déclaration de confidentialité</a> de la revue qui certifie aux lecteurs que leur nom et leur courriel ne seront pas utilisés à d'autres fins."
msgid "default.contextSettings.forAuthors"
msgstr ""
"Intéressé pour soumettre dans cette revue ? Nous vous recommandons de "
"consulter les politiques de rubrique de la revue à la page <a href=\""
"{$indexUrl}{$contextPath}/about\">À propos de la revue</a> ainsi que les <a "
"href=\"{$indexUrl}{$contextPath}/about/submissions#authorGuidelines\">"
"Directives aux auteurs</a>. Les auteurs doivent <a href=\""
"{$indexUrl}{$contextPath}/user/register\">S'inscrire</a> auprès de la revue "
"avant de présenter une soumission, ou s'ils sont déjà inscrits, simplement <"
"a href=\"{$indexUrl}{$contextPath}/login\">ouvrir une session</a> et accéder "
"au tableau de bord pour commencer les 5 étapes du processus."
msgid "default.contextSettings.forLibrarians"
msgstr "Nous incitons les bibliothécaires à lister cette revue dans leur fonds de revues numériques. Aussi, il peut être pertinent de mentionner que ce système de publication en accès libre est conçu pour être hébergé par les bibliothèques de recherche pour que les membres de leurs facultés l'utilisent avec les revues dans lesquelles ils sont impliqués (voir <a href=\"http://pkp.sfu.ca/ojs\">Open Journal Systems</a>)."
msgid "default.contextSettings.lockssLicense"
msgstr "Cette revue utilise le système LOCKSS pour créer un système de distribution des archives parmi les bibliothèques participantes et afin de permettre à ces bibliothèques de créer des archives permanentes pour fins de préservation et de restauration. <a href=\"http://lockss.org/\">En savoir plus...</a>"
msgid "default.contextSettings.checklist.addressesLinked"
msgstr "Lorsque possible, les URLs des références ont été fournies."
msgid "section.default.title"
msgstr "Articles"
msgid "section.default.abbrev"
msgstr "ART"
msgid "section.default.policy"
msgstr "Politique par défaut de la rubrique"
msgid "default.journalSettings.purchaseIssueFee"
msgstr "Acheter un numéro"
msgid "default.journalSettings.emailHeader"
msgstr ""
"Le message suivant est délivré au nom de {$journalName}.\n"
"________________________________________________________________________"
msgid "default.genres.article"
msgstr "Texte de l'article"
msgid "default.contextSettings.clockssLicense"
msgstr "Cette revue utilise le système CLOCKSS pour créer un système d'archivage distribué parmi les bibliothèques participantes et permet à ces bibliothèques de créer des archives permanentes de la revue à des fins de conservation et de reconstitution. <a href=\"http://clockss.org/\"> Plus ... </a>"
msgid "default.groups.name.manager"
msgstr "Directeur de la revue"
msgid "default.groups.plural.manager"
msgstr "Directeurs de la revue"
msgid "default.groups.abbrev.manager"
msgstr "DIR"
msgid "default.groups.name.editor"
msgstr "Rédacteur"
msgid "default.groups.plural.editor"
msgstr "Rédacteurs"
msgid "default.groups.abbrev.editor"
msgstr "RÉD"
msgid "default.groups.name.guestEditor"
msgstr "Rédacteur invité"
msgid "default.groups.plural.guestEditor"
msgstr "Rédacteurs invités"
msgid "default.groups.abbrev.guestEditor"
msgstr "RÉDINV"
msgid "default.groups.name.sectionEditor"
msgstr "Rédacteur de rubrique"
msgid "default.groups.plural.sectionEditor"
msgstr "Rédacteurs de rubrique"
msgid "default.groups.abbrev.sectionEditor"
msgstr "RÉDRUB"
msgid "default.groups.name.subscriptionManager"
msgstr "Responsable des abonnements"
msgid "default.groups.plural.subscriptionManager"
msgstr "Responsablesdes abonnements"
msgid "default.groups.abbrev.subscriptionManager"
msgstr "RespAB"
msgid "default.genres.researchInstrument"
msgstr "Instruments de recherche"
msgid "default.genres.researchMaterials"
msgstr "Matériels de recherche"
msgid "default.genres.researchResults"
msgstr "Résultats de recherche"
msgid "default.genres.transcripts"
msgstr "Transcriptions"
msgid "default.genres.dataAnalysis"
msgstr "Analyse de données"
msgid "default.genres.dataSet"
msgstr "Ensemble de données"
msgid "default.genres.sourceTexts"
msgstr "Sources textuelles"
msgid "default.groups.name.externalReviewer"
msgstr "Rapporteur"
msgid "default.groups.plural.externalReviewer"
msgstr "Rapporteurs"
msgid "default.groups.abbrev.externalReviewer"
msgstr "ÉVAL"
msgid "default.groups.name.committeemember"
msgstr "Membre du Comité de Rédaction"
msgid "default.groups.plural.committeemembers"
msgstr "Membres du Comité de Rédaction"
msgid "default.groups.abbrev.committeemembers"
msgstr "Membres du Comité"
msgid "default.journalSettings.membershipFee"
msgstr "Adhésion à l'association"
| {
"pile_set_name": "Github"
} |
import macros, strformat
import undoredostack
export undoredostack
type GapBuffer*[T] = object
buffer: seq[T]
size: int # 意味のあるデータが実際に格納されているサイズ
capacity: int # Amount of secured memory
gapBegin, gapEnd: int # 半開区間[gapBegin,gapEnd)を隙間とする
undoRedoStack: UndoRedoStack[T]
proc gapLen(gapBuffer: GapBuffer): int {.inline.} = gapBuffer.gapEnd - gapBuffer.gapBegin
proc makeGap(gapBuffer: var GapBuffer, gapBegin: int) =
## Create a gap starting with gapBegin
doAssert(0 <= gapBegin and gapBuffer.capacity - gapBegin >= gapBuffer.gapLen,
"Gapbuffer: Invalid position.")
if gapBegin < gapBuffer.gapBegin:
let
len = gapBuffer.gapBegin-gapBegin
index = gapBegin + gapBuffer.gapLen .. gapBegin+gapBuffer.gapLen+len - 1
gapBuffer.buffer[index] = gapBuffer.buffer[gapBegin .. gapBegin + len - 1]
else:
let
gapEnd = gapBegin + (gapBuffer.gapEnd-gapBuffer.gapBegin)
len = gapEnd - gapBuffer.gapEnd
gapBuffer.buffer[gapBuffer.gapBegin .. gapBuffer.gapBegin + len - 1] =
gapBuffer.buffer[gapBuffer.gapEnd .. gapBuffer.gapEnd + len - 1]
gapBuffer.gapEnd = gapBegin+gapBuffer.gapLen
gapBuffer.gapBegin = gapBegin
proc reserve(gapBuffer: var GapBuffer, capacity: int) =
doAssert(1 <= capacity and gapBuffer.size <= capacity,
"Gapbuffer: New buffer capacity is too small.")
gapBuffer.makeGap(gapBuffer.capacity-gapBuffer.gapLen)
gapBuffer.buffer.setLen(capacity)
gapBuffer.gapBegin = gapBuffer.size
gapBuffer.gapEnd = capacity
gapBuffer.capacity = capacity
proc insert*[T](gapBuffer: var GapBuffer,
element: T,
position: int,
pushToStack: bool = true) =
## positionの直前に要素を挿入する.末尾に追加したい場合はpositionにバッファの要素数を渡す.
## ex.空のバッファに要素を追加する場合はpositionに0を渡す.
doAssert(0 <= position and position <= gapBuffer.size,
"Gapbuffer: Invalid position.")
if pushToStack:
gapBuffer.undoRedoStack.push(newInsertCommand[T](element, position))
if gapBuffer.size == gapBuffer.capacity:
gapBuffer.reserve(gapBuffer.capacity*2)
if gapBuffer.gapBegin != position: gapBuffer.makeGap(position)
gapBuffer.buffer[gapBuffer.gapBegin] = element
inc(gapBuffer.gapBegin)
inc(gapBuffer.size)
proc add*[T](gapBuffer: var GapBuffer[T], val: T, pushToStack: bool = true) {.inline.} =
gapBuffer.insert(val, gapBuffer.len, pushToStack)
proc initGapBuffer*[T](): GapBuffer[T] =
result.buffer = newSeq[T](1)
result.capacity = 1
result.gapEnd = 1
result.undoRedoStack = initUndoRedoStack[T]()
proc initGapBuffer*[T](elements: seq[T]): GapBuffer[T] =
result = initGapBuffer[T]()
for e in elements: result.add(e, false)
proc deleteInterval(gapBuffer: var GapBuffer, first, last: int) =
## Delete [first, last] elements
let
delBegin = first
delEnd = last+1
doAssert(0 <= delBegin and delBegin <= delEnd and delEnd <= gapBuffer.size,
"Gapbuffer: Invalid interval.")
let
trueBegin = if gapBuffer.gapBegin > delBegin: delBegin
else: gapBuffer.gapEnd + (delBegin - gapBuffer.gapBegin)
trueEnd = if gapBuffer.gapBegin > delEnd: delEnd
else: gapBuffer.gapEnd + (delEnd - gapBuffer.gapBegin)
if trueBegin <= gapBuffer.gapBegin and gapBuffer.gapEnd <= trueEnd:
gapBuffer.gapBegin = trueBegin
gapBuffer.gapEnd = trueEnd
elif trueEnd <= gapBuffer.gapBegin:
gapBuffer.makeGap(trueEnd)
gapBuffer.gapBegin = trueBegin
else:
let len = trueBegin - gapBuffer.gapEnd
gapBuffer.buffer[gapBuffer.gapBegin .. gapBuffer.gapBegin + len - 1] =
gapBuffer.buffer[gapBuffer.gapEnd .. gapBuffer.gapEnd+len - 1]
gapBuffer.gapBegin = gapBuffer.gapBegin + trueBegin - gapBuffer.gapEnd
gapBuffer.gapEnd = trueEnd
gapBuffer.size -= delEnd - delBegin
while gapBuffer.size > 0 and gapBuffer.size * 4 <= gapBuffer.capacity:
gapBuffer.reserve(gapBuffer.capacity div 2)
proc delete*[T](gapBuffer: var GapBuffer[T],
index: int,
pushToStack: bool = true) =
## Delete the i-th element
if pushToStack:
gapBuffer.undoRedoStack.push(newDeleteCommand[T](gapBuffer[index], index))
gapBuffer.deleteInterval(index, index)
proc delete*[T](gapBuffer: var GapBuffer[T],
first, last: int,
pushToStack: bool = true) =
## Delete [first, last] elements
for i in countdown(last, first): gapBuffer.delete(i)
proc assign*[T](gapBuffer: var GapBuffer,
val: T,
index: int,
pushToStack: bool = true) =
doAssert(0<=index and index<gapBuffer.size, "Gapbuffer: Invalid index.")
if pushToStack:
gapBuffer.undoRedoStack.push(newAssignCommand[T](gapBuffer[index],
val,
index))
if index < gapBuffer.gapBegin: gapBuffer.buffer[index] = val
else: gapBuffer.buffer[gapBuffer.gapEnd+(index-gapBuffer.gapBegin)] = val
proc `[]=`*[T](gapBuffer: var GapBuffer, index: int, val: T) =
gapBuffer.assign(val, index)
proc `[]`*[T](gapBuffer: GapBuffer[T], index: int): T =
let size = gapBuffer.size
doAssert(0<=index and index<gapBuffer.size,
"Gapbuffer: Invalid index. index = "&($index)&", gapBuffer.size = "&($size))
if index < gapBuffer.gapBegin: return gapBuffer.buffer[index]
return gapBuffer.buffer[gapBuffer.gapEnd+(index-gapBuffer.gapBegin)]
proc lastSuitId*(gapBuffer: GapBuffer): int {.inline.} = gapBuffer.undoRedoStack.lastSuitId
proc beginNewSuitIfNeeded*(gapBuffer: var GapBuffer) {.inline.} =
gapBuffer.undoRedoStack.beginNewSuitIfNeeded
proc canUndo*(gapBuffer: GapBuffer): bool {.inline.} = gapBuffer.undoRedoStack.canUndo
proc canRedo*(gapBuffer: GapBuffer): bool {.inline.} = gapBuffer.undoRedoStack.canRedo
proc undo*(gapBuffer: var GapBuffer) {.inline.} = gapBuffer.undoRedoStack.undo(gapBuffer)
proc redo*(gapBuffer: var GapBuffer) {.inline.} = gapBuffer.undoRedoStack.redo(gapBuffer)
proc len*(gapBuffer: GapBuffer): int {.inline.} = gapBuffer.size
proc high*(gapBuffer: GapBuffer): int {.inline.} = gapBuffer.len-1
proc empty*(gapBuffer: GapBuffer): bool {.inline.} = return gapBuffer.len == 0
proc `$`*(gapBuffer: GapBuffer): string =
result = ""
for i in 0 ..< gapBuffer.len: result &= $gapBuffer[i] & "\n"
proc next*(gapBuffer: GapBuffer, line, column: int): (int, int) =
result = (line, column)
if line == gapBuffer.size-1 and column >= gapBuffer[gapBuffer.len-1].len-1:
return result
inc(result[1])
if result[1] >= gapBuffer[line].len:
inc(result[0])
result[1] = 0
proc prev*(gapBuffer: GapBuffer, line, column: int): (int, int) =
result = (line, column)
if line == 0 and column == 0: return result
dec(result[1])
if result[1] == -1:
dec(result[0])
result[1] = max(gapBuffer[result[0]].len-1, 0)
proc isFirst*(gapBuffer: GapBuffer, line, column: int): bool {.inline.} =
line == 0 and column == 0
proc isLast*(gapBuffer: GapBuffer, line, column: int): bool {.inline.} =
line == gapBuffer.len-1 and column >= gapBuffer[gapBuffer.len-1].len-1
proc calcIndexInEntireBuffer*[T: array | seq | string](
gapBuffer: GapBuffer[T],
line, column: int,
containNewline: bool): int =
block:
let mess = fmt"GapBuffer: The line is less than 0 or exceeds the length of the buffer. line = {line}, gapBuffer.len = {gapBuffer.len}."
doAssert(0 <= line and line < gapBuffer.len, mess)
block:
let mess = fmt"GapBuffer: The column is less than 0 or exceeds the length of the buffer[line]. column = {column}, gapBuffer[line].len = {gapBuffer[line].len}."
doAssert(0 <= column and column < gapBuffer[line].len, mess)
for i in 0 ..< line:
result += gapBuffer[i].len
if containNewline: inc(result)
result += column
| {
"pile_set_name": "Github"
} |
/*
*
* Copyright 2014 gRPC 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 naming defines the naming API and related data structures for gRPC.
// The interface is EXPERIMENTAL and may be suject to change.
package naming
// Operation defines the corresponding operations for a name resolution change.
type Operation uint8
const (
// Add indicates a new address is added.
Add Operation = iota
// Delete indicates an exisiting address is deleted.
Delete
)
// Update defines a name resolution update. Notice that it is not valid having both
// empty string Addr and nil Metadata in an Update.
type Update struct {
// Op indicates the operation of the update.
Op Operation
// Addr is the updated address. It is empty string if there is no address update.
Addr string
// Metadata is the updated metadata. It is nil if there is no metadata update.
// Metadata is not required for a custom naming implementation.
Metadata interface{}
}
// Resolver creates a Watcher for a target to track its resolution changes.
type Resolver interface {
// Resolve creates a Watcher for target.
Resolve(target string) (Watcher, error)
}
// Watcher watches for the updates on the specified target.
type Watcher interface {
// Next blocks until an update or error happens. It may return one or more
// updates. The first call should get the full set of the results. It should
// return an error if and only if Watcher cannot recover.
Next() ([]*Update, error)
// Close closes the Watcher.
Close()
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* 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 org.kie.server.api.model.cases;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.kie.server.api.model.ItemList;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "case-milestone-list")
public class CaseMilestoneList implements ItemList<CaseMilestone> {
@XmlElement(name = "milestones")
private CaseMilestone[] milestones;
public CaseMilestoneList() {
}
public CaseMilestoneList(CaseMilestone[] milestones) {
this.milestones = milestones;
}
public CaseMilestoneList(List<CaseMilestone> milestones) {
this.milestones = milestones.toArray(new CaseMilestone[milestones.size()]);
}
public CaseMilestone[] getMilestones() {
return milestones;
}
public void setMilestones(CaseMilestone[] milestones) {
this.milestones = milestones;
}
@Override
public List<CaseMilestone> getItems() {
if (milestones == null) {
return Collections.emptyList();
}
return Arrays.asList(milestones);
}
}
| {
"pile_set_name": "Github"
} |
/*
* Another question which belongs to the category of questions which are intentionally stated vaguely.
Expectation is that you will ask for correct clarification or you will state your assumptions before you start coding.
Implement strStr().
strstr - locate a substring ( needle ) in a string ( haystack ).
Try not to use standard library string functions for this question.
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
NOTE:
Good clarification questions:
What should be the return value if the needle is empty ?
What if both haystack and needle are empty ?
For the purpose of this problem, assume that the return value should be -1 in both cases.
*/
public class StrStr{
public static int strStr(final String haystack, final String needle) {
if(haystack.isEmpty() || needle.isEmpty())
return -1;
if(haystack == null || needle == null)
return -1;
int N = haystack.length();
int M = needle.length();
for(int i = 0; i <= N-M; i++){
int j;
for(j = 0; j < M; j++){
if(haystack.charAt(i+j) != needle.charAt(j))
break;
}
if(j == M) return i;
}
return -1;
}
//better approachExplicit backup
public static int strStrBetter(final String haystack, final String needle) {
if(haystack.isEmpty() || needle.isEmpty())
return -1;
if(haystack == null || needle == null)
return -1;
int i, j;
int M = needle.length();
int N = haystack.length();
for(i = 0, j = 0; i < N && j < M; i++){
if(haystack.charAt(i) == needle.charAt(j))
j++;
else{
i = i - j;
j = 0;
}
}
if(j == M)
return i - M;
else
return -1;
}
public static void main(String[] args){
String haystack = args[0];
String needle = args[1];
System.out.println(strStrBetter(haystack, needle));
}
} | {
"pile_set_name": "Github"
} |
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace StyledTriggers.Droid
{
[Activity(Label = "StyledTriggers", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
}
}
}
| {
"pile_set_name": "Github"
} |
/*
* tm6000-i2c.c - driver for TM5600/TM6000/TM6010 USB video capture devices
*
* Copyright (C) 2006-2007 Mauro Carvalho Chehab <[email protected]>
*
* Copyright (C) 2007 Michel Ludwig <[email protected]>
* - Fix SMBus Read Byte command
*
* 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 version 2
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/usb.h>
#include <linux/i2c.h>
#include "tm6000.h"
#include "tm6000-regs.h"
#include <media/v4l2-common.h>
#include <media/tuner.h>
#include "tuner-xc2028.h"
/* ----------------------------------------------------------- */
static unsigned int i2c_debug;
module_param(i2c_debug, int, 0644);
MODULE_PARM_DESC(i2c_debug, "enable debug messages [i2c]");
#define i2c_dprintk(lvl, fmt, args...) if (i2c_debug >= lvl) do { \
printk(KERN_DEBUG "%s at %s: " fmt, \
dev->name, __func__, ##args); } while (0)
static int tm6000_i2c_send_regs(struct tm6000_core *dev, unsigned char addr,
__u8 reg, char *buf, int len)
{
int rc;
unsigned int i2c_packet_limit = 16;
if (dev->dev_type == TM6010)
i2c_packet_limit = 80;
if (!buf)
return -1;
if (len < 1 || len > i2c_packet_limit) {
printk(KERN_ERR "Incorrect length of i2c packet = %d, limit set to %d\n",
len, i2c_packet_limit);
return -1;
}
/* capture mutex */
rc = tm6000_read_write_usb(dev, USB_DIR_OUT | USB_TYPE_VENDOR |
USB_RECIP_DEVICE, REQ_16_SET_GET_I2C_WR1_RDN,
addr | reg << 8, 0, buf, len);
if (rc < 0) {
/* release mutex */
return rc;
}
/* release mutex */
return rc;
}
/* Generic read - doesn't work fine with 16bit registers */
static int tm6000_i2c_recv_regs(struct tm6000_core *dev, unsigned char addr,
__u8 reg, char *buf, int len)
{
int rc;
u8 b[2];
unsigned int i2c_packet_limit = 16;
if (dev->dev_type == TM6010)
i2c_packet_limit = 64;
if (!buf)
return -1;
if (len < 1 || len > i2c_packet_limit) {
printk(KERN_ERR "Incorrect length of i2c packet = %d, limit set to %d\n",
len, i2c_packet_limit);
return -1;
}
/* capture mutex */
if ((dev->caps.has_zl10353) && (dev->demod_addr << 1 == addr) && (reg % 2 == 0)) {
/*
* Workaround an I2C bug when reading from zl10353
*/
reg -= 1;
len += 1;
rc = tm6000_read_write_usb(dev, USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
REQ_16_SET_GET_I2C_WR1_RDN, addr | reg << 8, 0, b, len);
*buf = b[1];
} else {
rc = tm6000_read_write_usb(dev, USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
REQ_16_SET_GET_I2C_WR1_RDN, addr | reg << 8, 0, buf, len);
}
/* release mutex */
return rc;
}
/*
* read from a 16bit register
* for example xc2028, xc3028 or xc3028L
*/
static int tm6000_i2c_recv_regs16(struct tm6000_core *dev, unsigned char addr,
__u16 reg, char *buf, int len)
{
int rc;
unsigned char ureg;
if (!buf || len != 2)
return -1;
/* capture mutex */
if (dev->dev_type == TM6010) {
ureg = reg & 0xFF;
rc = tm6000_read_write_usb(dev, USB_DIR_OUT | USB_TYPE_VENDOR |
USB_RECIP_DEVICE, REQ_16_SET_GET_I2C_WR1_RDN,
addr | (reg & 0xFF00), 0, &ureg, 1);
if (rc < 0) {
/* release mutex */
return rc;
}
rc = tm6000_read_write_usb(dev, USB_DIR_IN | USB_TYPE_VENDOR |
USB_RECIP_DEVICE, REQ_35_AFTEK_TUNER_READ,
reg, 0, buf, len);
} else {
rc = tm6000_read_write_usb(dev, USB_DIR_IN | USB_TYPE_VENDOR |
USB_RECIP_DEVICE, REQ_14_SET_GET_I2C_WR2_RDN,
addr, reg, buf, len);
}
/* release mutex */
return rc;
}
static int tm6000_i2c_xfer(struct i2c_adapter *i2c_adap,
struct i2c_msg msgs[], int num)
{
struct tm6000_core *dev = i2c_adap->algo_data;
int addr, rc, i, byte;
if (num <= 0)
return 0;
for (i = 0; i < num; i++) {
addr = (msgs[i].addr << 1) & 0xff;
i2c_dprintk(2, "%s %s addr=0x%x len=%d:",
(msgs[i].flags & I2C_M_RD) ? "read" : "write",
i == num - 1 ? "stop" : "nonstop", addr, msgs[i].len);
if (msgs[i].flags & I2C_M_RD) {
/* read request without preceding register selection */
/*
* The TM6000 only supports a read transaction
* immediately after a 1 or 2 byte write to select
* a register. We cannot fulfil this request.
*/
i2c_dprintk(2, " read without preceding write not"
" supported");
rc = -EOPNOTSUPP;
goto err;
} else if (i + 1 < num && msgs[i].len <= 2 &&
(msgs[i + 1].flags & I2C_M_RD) &&
msgs[i].addr == msgs[i + 1].addr) {
/* 1 or 2 byte write followed by a read */
if (i2c_debug >= 2)
for (byte = 0; byte < msgs[i].len; byte++)
printk(KERN_CONT " %02x", msgs[i].buf[byte]);
i2c_dprintk(2, "; joined to read %s len=%d:",
i == num - 2 ? "stop" : "nonstop",
msgs[i + 1].len);
if (msgs[i].len == 2) {
rc = tm6000_i2c_recv_regs16(dev, addr,
msgs[i].buf[0] << 8 | msgs[i].buf[1],
msgs[i + 1].buf, msgs[i + 1].len);
} else {
rc = tm6000_i2c_recv_regs(dev, addr, msgs[i].buf[0],
msgs[i + 1].buf, msgs[i + 1].len);
}
i++;
if (addr == dev->tuner_addr << 1) {
tm6000_set_reg(dev, REQ_50_SET_START, 0, 0);
tm6000_set_reg(dev, REQ_51_SET_STOP, 0, 0);
}
if (i2c_debug >= 2)
for (byte = 0; byte < msgs[i].len; byte++)
printk(KERN_CONT " %02x", msgs[i].buf[byte]);
} else {
/* write bytes */
if (i2c_debug >= 2)
for (byte = 0; byte < msgs[i].len; byte++)
printk(KERN_CONT " %02x", msgs[i].buf[byte]);
rc = tm6000_i2c_send_regs(dev, addr, msgs[i].buf[0],
msgs[i].buf + 1, msgs[i].len - 1);
}
if (i2c_debug >= 2)
printk(KERN_CONT "\n");
if (rc < 0)
goto err;
}
return num;
err:
i2c_dprintk(2, " ERROR: %i\n", rc);
return rc;
}
static int tm6000_i2c_eeprom(struct tm6000_core *dev)
{
int i, rc;
unsigned char *p = dev->eedata;
unsigned char bytes[17];
dev->i2c_client.addr = 0xa0 >> 1;
dev->eedata_size = 0;
bytes[16] = '\0';
for (i = 0; i < sizeof(dev->eedata); ) {
*p = i;
rc = tm6000_i2c_recv_regs(dev, 0xa0, i, p, 1);
if (rc < 1) {
if (p == dev->eedata)
goto noeeprom;
else {
printk(KERN_WARNING
"%s: i2c eeprom read error (err=%d)\n",
dev->name, rc);
}
return -EINVAL;
}
dev->eedata_size++;
p++;
if (0 == (i % 16))
printk(KERN_INFO "%s: i2c eeprom %02x:", dev->name, i);
printk(KERN_CONT " %02x", dev->eedata[i]);
if ((dev->eedata[i] >= ' ') && (dev->eedata[i] <= 'z'))
bytes[i%16] = dev->eedata[i];
else
bytes[i%16] = '.';
i++;
if (0 == (i % 16)) {
bytes[16] = '\0';
printk(KERN_CONT " %s\n", bytes);
}
}
if (0 != (i%16)) {
bytes[i%16] = '\0';
for (i %= 16; i < 16; i++)
printk(KERN_CONT " ");
printk(KERN_CONT " %s\n", bytes);
}
return 0;
noeeprom:
printk(KERN_INFO "%s: Huh, no eeprom present (err=%d)?\n",
dev->name, rc);
return -EINVAL;
}
/* ----------------------------------------------------------- */
/*
* functionality()
*/
static u32 functionality(struct i2c_adapter *adap)
{
return I2C_FUNC_SMBUS_EMUL;
}
static const struct i2c_algorithm tm6000_algo = {
.master_xfer = tm6000_i2c_xfer,
.functionality = functionality,
};
/* ----------------------------------------------------------- */
/*
* tm6000_i2c_register()
* register i2c bus
*/
int tm6000_i2c_register(struct tm6000_core *dev)
{
int rc;
dev->i2c_adap.owner = THIS_MODULE;
dev->i2c_adap.algo = &tm6000_algo;
dev->i2c_adap.dev.parent = &dev->udev->dev;
strlcpy(dev->i2c_adap.name, dev->name, sizeof(dev->i2c_adap.name));
dev->i2c_adap.algo_data = dev;
i2c_set_adapdata(&dev->i2c_adap, &dev->v4l2_dev);
rc = i2c_add_adapter(&dev->i2c_adap);
if (rc)
return rc;
dev->i2c_client.adapter = &dev->i2c_adap;
strlcpy(dev->i2c_client.name, "tm6000 internal", I2C_NAME_SIZE);
tm6000_i2c_eeprom(dev);
return 0;
}
/*
* tm6000_i2c_unregister()
* unregister i2c_bus
*/
int tm6000_i2c_unregister(struct tm6000_core *dev)
{
i2c_del_adapter(&dev->i2c_adap);
return 0;
}
| {
"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(FUSION_ERASE_10022005_1835)
#define FUSION_ERASE_10022005_1835
#include <boost/fusion/support/config.hpp>
#include <boost/mpl/erase.hpp>
#include <boost/fusion/support/tag_of.hpp>
#include <boost/fusion/algorithm/transformation/erase.hpp>
#include <boost/fusion/sequence/convert.hpp>
namespace boost { namespace mpl
{
template <typename Tag>
struct erase_impl;
template <>
struct erase_impl<fusion::fusion_sequence_tag>
{
template <typename Sequence, typename First, typename Last>
struct apply
{
typedef typename
fusion::result_of::erase<Sequence, First, Last>::type
result;
typedef typename
fusion::result_of::convert<
typename fusion::detail::tag_of<Sequence>::type, result>::type
type;
};
};
}}
#endif
| {
"pile_set_name": "Github"
} |
const fs = require('fs');
fs.rmdir(__dirname, (error) => {
console.error(error.message); // <1>
});
| {
"pile_set_name": "Github"
} |
package s3crypto
import (
"bytes"
"encoding/hex"
"fmt"
"io"
"testing"
)
func TestAESCBCEncryptDecrypt(t *testing.T) {
var testCases = []struct {
key string
iv string
plaintext string
ciphertext string
decodeHex bool
padder Padder
}{
// Test vectors from RFC 3602: https://tools.ietf.org/html/rfc3602
{
"06a9214036b8a15b512e03d534120006",
"3dafba429d9eb430b422da802c9fac41",
"Single block msg",
"e353779c1079aeb82708942dbe77181a",
false,
NoPadder,
},
{
"c286696d887c9aa0611bbb3e2025a45a",
"562e17996d093d28ddb3ba695a2e6f58",
"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
"d296cd94c2cccf8a3a863028b5e1dc0a7586602d253cfff91b8266bea6d61ab1",
true,
NoPadder,
},
{
"6c3ea0477630ce21a2ce334aa746c2cd",
"c782dc4c098c66cbd9cd27d825682c81",
"This is a 48-byte message (exactly 3 AES blocks)",
"d0a02b3836451753d493665d33f0e8862dea54cdb293abc7506939276772f8d5021c19216bad525c8579695d83ba2684",
false,
NoPadder,
},
{
"56e47a38c5598974bc46903dba290349",
"8ce82eefbea0da3c44699ed7db51b7d9",
"a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedf",
"c30e32ffedc0774e6aff6af0869f71aa0f3af07a9a31a9c684db207eb0ef8e4e35907aa632c3ffdf868bb7b29d3d46ad83ce9f9a102ee99d49a53e87f4c3da55",
true,
NoPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"",
"B012949BA07D1A6DCE9DEE67274D41AB",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"41",
"8A11ABA68A566132FFE04DB336621D41",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"4141",
"97D0896E41DFDB5CEA4A9EB70A938CFD",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"414141",
"8464EAD45FA2D8790E8741E32C28083F",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"41414141",
"1E656D6E2745BA9F154FAF136B2BC73D",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"4141414141",
"0B6031C4B230DAC6BD6D3F195645B287",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"414141414141",
"5D09FEB6462BB489489A7E18FD341D9D",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"41414141414141",
"85745E398F2FD1050C2CE8F8614DA369",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"4141414141414141",
"7BE52933970BA7B0FC6FB3FC37648205",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"414141414141414141",
"ED3A1E134EF36CCFE60C8123B4272F89",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"41414141414141414141",
"C3B7C9E177E1052FC736F65FC1E74209",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"4141414141414141414141",
"C3A8B53F7F57F0B9D346FA99810A3C28",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"414141414141414141414141",
"D16B1ECE5BF00AF919E139E99775FF06",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"41414141414141414141414141",
"B258F4DF57FFCA1EFCF8D76140F05139",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"4141414141414141414141414141",
"3CD2282DE24A2CF9E23326CC3DC9077A",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"414141414141414141414141414141",
"3010232E7C752A3B4C9EE428B4C4FE88",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"41414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217A22BC4E6D03BFD2418DD412D1ED1B31AF",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"4141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217A5427BBD4A4D50776989441370E3B5B16",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217A7FF985F55567D1B25EA40E23BB4CB1FE",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"41414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217A0835E548C7370D8F8D9925C0E6B54727",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"4141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217ADC0CF1436399E67BC1122B31CB596649",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217A3D096F0DEAFF91938B82E5D404B0B065",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"41414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217AD56ABA897A355CF307CCB74226243192",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"4141414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217A151284F950B1B1DBCAD6D9E7900DF4E6",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"414141414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217AEF85A612514121C299A1D87116C4A182",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"41414141414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217A67F157569BFB4013EA3AD16DB8C69AD6",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"4141414141414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217AF8520D191F6ACBD88B2140588B91C697",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"414141414141414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217ADD8BBAA71745669B96F2683E2F5AEC35",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"41414141414141414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217AFB2D4282817D7EC6B33EFAD7AA14A3C5",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"4141414141414141414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217A459B89E7E0DAF3DA654576B60B2DA7CE",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"414141414141414141414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217A65759F23F9789D05B23D5DBAA9E32036",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"41414141414141414141414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217A03C78FBD5E2CB08B3B6D181E23FBDE79",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"4141414141414141414141414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217ACEF79EE1163A2F52888F87A3979EB3CA013D941FBBDE56C106C482CD022F290F",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"414141414141414141414141414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217ACEF79EE1163A2F52888F87A3979EB3CA0645D313AC3C29B79DB1AA2E00A5B393",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"41414141414141414141414141414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217ACEF79EE1163A2F52888F87A3979EB3CA2ED0FD8048053BF22EBE501D82C4B3F1",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"4141414141414141414141414141414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217ACEF79EE1163A2F52888F87A3979EB3CAC57D706C7866A01D6E913F98AE57EE54",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"414141414141414141414141414141414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217ACEF79EE1163A2F52888F87A3979EB3CAB7FC1241FAFDFE45C4FF982D5DC1DAEF",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"41414141414141414141414141414141414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217ACEF79EE1163A2F52888F87A3979EB3CA7063EA296922DE8BDFD3B29D786C5F91",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"4141414141414141414141414141414141414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217ACEF79EE1163A2F52888F87A3979EB3CA3A4603475F4AFDBFADC6E7FA908188B1",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"414141414141414141414141414141414141414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217ACEF79EE1163A2F52888F87A3979EB3CA3365C63C2AF2A6C8FB4D0E9ED3C6FDA3",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"41414141414141414141414141414141414141414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217ACEF79EE1163A2F52888F87A3979EB3CA78BCC1874C0B7EB52645FC8F03B9C9CF",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"4141414141414141414141414141414141414141414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217ACEF79EE1163A2F52888F87A3979EB3CA9B7A31397718EECB89B9E9CCCD729326",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"414141414141414141414141414141414141414141414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217ACEF79EE1163A2F52888F87A3979EB3CAB15EA8A67E9E9FADB4249710277F3D4F",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"41414141414141414141414141414141414141414141414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217ACEF79EE1163A2F52888F87A3979EB3CA94641D6A076193C660632CEA3F9CB02C",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"4141414141414141414141414141414141414141414141414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217ACEF79EE1163A2F52888F87A3979EB3CAB2170A08417BE77F0EAA9110F4790E12",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217ACEF79EE1163A2F52888F87A3979EB3CA4E30F1CD7B2256ABD57DC3DAB05376C9",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"41414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217ACEF79EE1163A2F52888F87A3979EB3CA9909B7B93D01BDAAC22D15AF34DF1EEF",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"4141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217ACEF79EE1163A2F52888F87A3979EB3CAD97F5D1206F00E5C7225CAD81CCD4027",
true,
AESCBCPadder,
},
{
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141",
"C3304FA46097CBBA59085416764A217ACEF79EE1163A2F52888F87A3979EB3CA570CBB001A0C87558906B60C884AB5F41DA97CEF2A9401BC6DD0D22A54DBAD6D",
true,
AESCBCPadder,
},
}
for i, testCase := range testCases {
key, _ := hex.DecodeString(testCase.key)
iv, _ := hex.DecodeString(testCase.iv)
cd := CipherData{
Key: key,
IV: iv,
}
cbc, err := newAESCBC(cd, testCase.padder)
if err != nil {
t.Fatal(fmt.Sprintf("Case %d: Expected no error for cipher creation, but received: %v", i, err.Error()))
}
plaintext := []byte(testCase.plaintext)
if testCase.decodeHex {
plaintext, _ = hex.DecodeString(testCase.plaintext)
}
cipherdata := cbc.Encrypt(bytes.NewReader(plaintext))
ciphertext := []byte{}
b := make([]byte, 19)
err = nil
n := 0
for err != io.EOF {
n, err = cipherdata.Read(b)
ciphertext = append(ciphertext, b[:n]...)
}
if err != io.EOF {
t.Fatal(fmt.Sprintf("Case %d: Expected no error during io reading, but received: %v", i, err.Error()))
}
expectedData, _ := hex.DecodeString(testCase.ciphertext)
if bytes.Compare(expectedData, ciphertext) != 0 {
t.Log("\n", ciphertext, "\n", expectedData)
t.Fatal(fmt.Sprintf("Case %d: AES CBC encryption fails. Data is not the same", i))
}
plaindata := cbc.Decrypt(bytes.NewReader(ciphertext))
plaintextDecrypted := []byte{}
err = nil
for err != io.EOF {
n, err = plaindata.Read(b)
plaintextDecrypted = append(plaintextDecrypted, b[:n]...)
}
if err != io.EOF {
t.Fatal(fmt.Sprintf("Case %d: Expected no error during io reading, but received: %v", i, err.Error()))
}
if bytes.Compare(plaintext, plaintextDecrypted) != 0 {
t.Log("\n", plaintext, "\n", plaintextDecrypted)
t.Fatal(fmt.Sprintf("Case %d: AES CBC decryption fails. Data is not the same", i))
}
}
}
| {
"pile_set_name": "Github"
} |
{
"images" : [
{
"idiom" : "universal",
"filename" : "icon_read.png",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "[email protected]",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
} | {
"pile_set_name": "Github"
} |
[
{ "mask": "+247-####", "cc": "AC", "name_en": "Ascension", "desc_en": "", "name_ru": "Остров Вознесения", "desc_ru": "" },
{ "mask": "+376-###-###", "cc": "AD", "name_en": "Andorra", "desc_en": "", "name_ru": "Андорра", "desc_ru": "" },
{ "mask": "+971-5#-###-####", "cc": "AE", "name_en": "United Arab Emirates", "desc_en": "mobile", "name_ru": "Объединенные Арабские Эмираты", "desc_ru": "мобильные" },
{ "mask": "+971-#-###-####", "cc": "AE", "name_en": "United Arab Emirates", "desc_en": "", "name_ru": "Объединенные Арабские Эмираты", "desc_ru": "" },
{ "mask": "+93-##-###-####", "cc": "AF", "name_en": "Afghanistan", "desc_en": "", "name_ru": "Афганистан", "desc_ru": "" },
{ "mask": "+1(268)###-####", "cc": "AG", "name_en": "Antigua & Barbuda", "desc_en": "", "name_ru": "Антигуа и Барбуда", "desc_ru": "" },
{ "mask": "+1(264)###-####", "cc": "AI", "name_en": "Anguilla", "desc_en": "", "name_ru": "Ангилья", "desc_ru": "" },
{ "mask": "+355(###)###-###", "cc": "AL", "name_en": "Albania", "desc_en": "", "name_ru": "Албания", "desc_ru": "" },
{ "mask": "+374-##-###-###", "cc": "AM", "name_en": "Armenia", "desc_en": "", "name_ru": "Армения", "desc_ru": "" },
{ "mask": "+599-###-####", "cc": "AN", "name_en": "Caribbean Netherlands", "desc_en": "", "name_ru": "Карибские Нидерланды", "desc_ru": "" },
{ "mask": "+599-###-####", "cc": "AN", "name_en": "Netherlands Antilles", "desc_en": "", "name_ru": "Нидерландские Антильские острова", "desc_ru": "" },
{ "mask": "+599-9###-####", "cc": "AN", "name_en": "Netherlands Antilles", "desc_en": "Curacao", "name_ru": "Нидерландские Антильские острова", "desc_ru": "Кюрасао" },
{ "mask": "+244(###)###-###", "cc": "AO", "name_en": "Angola", "desc_en": "", "name_ru": "Ангола", "desc_ru": "" },
{ "mask": "+672-1##-###", "cc": "AQ", "name_en": "Australian bases in Antarctica", "desc_en": "", "name_ru": "Австралийская антарктическая база", "desc_ru": "" },
{ "mask": "+54(###)###-####", "cc": "AR", "name_en": "Argentina", "desc_en": "", "name_ru": "Аргентина", "desc_ru": "" },
{ "mask": "+1(684)###-####", "cc": "AS", "name_en": "American Samoa", "desc_en": "", "name_ru": "Американское Самоа", "desc_ru": "" },
{ "mask": "+43(###)###-####", "cc": "AT", "name_en": "Austria", "desc_en": "", "name_ru": "Австрия", "desc_ru": "" },
{ "mask": "+61-#-####-####", "cc": "AU", "name_en": "Australia", "desc_en": "", "name_ru": "Австралия", "desc_ru": "" },
{ "mask": "+297-###-####", "cc": "AW", "name_en": "Aruba", "desc_en": "", "name_ru": "Аруба", "desc_ru": "" },
{ "mask": "+994-##-###-##-##", "cc": "AZ", "name_en": "Azerbaijan", "desc_en": "", "name_ru": "Азербайджан", "desc_ru": "" },
{ "mask": "+387-##-#####", "cc": "BA", "name_en": "Bosnia and Herzegovina", "desc_en": "", "name_ru": "Босния и Герцеговина", "desc_ru": "" },
{ "mask": "+387-##-####", "cc": "BA", "name_en": "Bosnia and Herzegovina", "desc_en": "", "name_ru": "Босния и Герцеговина", "desc_ru": "" },
{ "mask": "+1(246)###-####", "cc": "BB", "name_en": "Barbados", "desc_en": "", "name_ru": "Барбадос", "desc_ru": "" },
{ "mask": "+880-##-###-###", "cc": "BD", "name_en": "Bangladesh", "desc_en": "", "name_ru": "Бангладеш", "desc_ru": "" },
{ "mask": "+32(###)###-###", "cc": "BE", "name_en": "Belgium", "desc_en": "", "name_ru": "Бельгия", "desc_ru": "" },
{ "mask": "+226-##-##-####", "cc": "BF", "name_en": "Burkina Faso", "desc_en": "", "name_ru": "Буркина Фасо", "desc_ru": "" },
{ "mask": "+359(###)###-###", "cc": "BG", "name_en": "Bulgaria", "desc_en": "", "name_ru": "Болгария", "desc_ru": "" },
{ "mask": "+973-####-####", "cc": "BH", "name_en": "Bahrain", "desc_en": "", "name_ru": "Бахрейн", "desc_ru": "" },
{ "mask": "+257-##-##-####", "cc": "BI", "name_en": "Burundi", "desc_en": "", "name_ru": "Бурунди", "desc_ru": "" },
{ "mask": "+229-##-##-####", "cc": "BJ", "name_en": "Benin", "desc_en": "", "name_ru": "Бенин", "desc_ru": "" },
{ "mask": "+1(441)###-####", "cc": "BM", "name_en": "Bermuda", "desc_en": "", "name_ru": "Бермудские острова", "desc_ru": "" },
{ "mask": "+673-###-####", "cc": "BN", "name_en": "Brunei Darussalam", "desc_en": "", "name_ru": "Бруней-Даруссалам", "desc_ru": "" },
{ "mask": "+591-#-###-####", "cc": "BO", "name_en": "Bolivia", "desc_en": "", "name_ru": "Боливия", "desc_ru": "" },
{ "mask": "+55-##-####[#]-####", "cc": "BR", "name_en": "Brazil", "desc_en": "", "name_ru": "Бразилия", "desc_ru": "" },
{ "mask": "+1(242)###-####", "cc": "BS", "name_en": "Bahamas", "desc_en": "", "name_ru": "Багамские Острова", "desc_ru": "" },
{ "mask": "+975-17-###-###", "cc": "BT", "name_en": "Bhutan", "desc_en": "", "name_ru": "Бутан", "desc_ru": "" },
{ "mask": "+975-#-###-###", "cc": "BT", "name_en": "Bhutan", "desc_en": "", "name_ru": "Бутан", "desc_ru": "" },
{ "mask": "+267-##-###-###", "cc": "BW", "name_en": "Botswana", "desc_en": "", "name_ru": "Ботсвана", "desc_ru": "" },
{ "mask": "+375(##)###-##-##", "cc": "BY", "name_en": "Belarus", "desc_en": "", "name_ru": "Беларусь (Белоруссия)", "desc_ru": "" },
{ "mask": "+501-###-####", "cc": "BZ", "name_en": "Belize", "desc_en": "", "name_ru": "Белиз", "desc_ru": "" },
{ "mask": "+243(###)###-###", "cc": "CD", "name_en": "Dem. Rep. Congo", "desc_en": "", "name_ru": "Дем. Респ. Конго (Киншаса)", "desc_ru": "" },
{ "mask": "+236-##-##-####", "cc": "CF", "name_en": "Central African Republic", "desc_en": "", "name_ru": "Центральноафриканская Республика", "desc_ru": "" },
{ "mask": "+242-##-###-####", "cc": "CG", "name_en": "Congo (Brazzaville)", "desc_en": "", "name_ru": "Конго (Браззавиль)", "desc_ru": "" },
{ "mask": "+41-##-###-####", "cc": "CH", "name_en": "Switzerland", "desc_en": "", "name_ru": "Швейцария", "desc_ru": "" },
{ "mask": "+225-##-###-###", "cc": "CI", "name_en": "Cote d’Ivoire (Ivory Coast)", "desc_en": "", "name_ru": "Кот-д’Ивуар", "desc_ru": "" },
{ "mask": "+682-##-###", "cc": "CK", "name_en": "Cook Islands", "desc_en": "", "name_ru": "Острова Кука", "desc_ru": "" },
{ "mask": "+56-#-####-####", "cc": "CL", "name_en": "Chile", "desc_en": "", "name_ru": "Чили", "desc_ru": "" },
{ "mask": "+237-####-####", "cc": "CM", "name_en": "Cameroon", "desc_en": "", "name_ru": "Камерун", "desc_ru": "" },
{ "mask": "+86(###)####-####", "cc": "CN", "name_en": "China (PRC)", "desc_en": "", "name_ru": "Китайская Н.Р.", "desc_ru": "" },
{ "mask": "+86(###)####-###", "cc": "CN", "name_en": "China (PRC)", "desc_en": "", "name_ru": "Китайская Н.Р.", "desc_ru": "" },
{ "mask": "+86-##-#####-#####", "cc": "CN", "name_en": "China (PRC)", "desc_en": "", "name_ru": "Китайская Н.Р.", "desc_ru": "" },
{ "mask": "+57(###)###-####", "cc": "CO", "name_en": "Colombia", "desc_en": "", "name_ru": "Колумбия", "desc_ru": "" },
{ "mask": "+506-####-####", "cc": "CR", "name_en": "Costa Rica", "desc_en": "", "name_ru": "Коста-Рика", "desc_ru": "" },
{ "mask": "+53-#-###-####", "cc": "CU", "name_en": "Cuba", "desc_en": "", "name_ru": "Куба", "desc_ru": "" },
{ "mask": "+238(###)##-##", "cc": "CV", "name_en": "Cape Verde", "desc_en": "", "name_ru": "Кабо-Верде", "desc_ru": "" },
{ "mask": "+599-###-####", "cc": "CW", "name_en": "Curacao", "desc_en": "", "name_ru": "Кюрасао", "desc_ru": "" },
{ "mask": "+357-##-###-###", "cc": "CY", "name_en": "Cyprus", "desc_en": "", "name_ru": "Кипр", "desc_ru": "" },
{ "mask": "+420(###)###-###", "cc": "CZ", "name_en": "Czech Republic", "desc_en": "", "name_ru": "Чехия", "desc_ru": "" },
{ "mask": "+49(####)###-####", "cc": "DE", "name_en": "Germany", "desc_en": "", "name_ru": "Германия", "desc_ru": "" },
{ "mask": "+49(###)###-####", "cc": "DE", "name_en": "Germany", "desc_en": "", "name_ru": "Германия", "desc_ru": "" },
{ "mask": "+49(###)##-####", "cc": "DE", "name_en": "Germany", "desc_en": "", "name_ru": "Германия", "desc_ru": "" },
{ "mask": "+49(###)##-###", "cc": "DE", "name_en": "Germany", "desc_en": "", "name_ru": "Германия", "desc_ru": "" },
{ "mask": "+49(###)##-##", "cc": "DE", "name_en": "Germany", "desc_en": "", "name_ru": "Германия", "desc_ru": "" },
{ "mask": "+49-###-###", "cc": "DE", "name_en": "Germany", "desc_en": "", "name_ru": "Германия", "desc_ru": "" },
{ "mask": "+253-##-##-##-##", "cc": "DJ", "name_en": "Djibouti", "desc_en": "", "name_ru": "Джибути", "desc_ru": "" },
{ "mask": "+45-##-##-##-##", "cc": "DK", "name_en": "Denmark", "desc_en": "", "name_ru": "Дания", "desc_ru": "" },
{ "mask": "+1(767)###-####", "cc": "DM", "name_en": "Dominica", "desc_en": "", "name_ru": "Доминика", "desc_ru": "" },
{ "mask": "+1(809)###-####", "cc": "DO", "name_en": "Dominican Republic", "desc_en": "", "name_ru": "Доминиканская Республика", "desc_ru": "" },
{ "mask": "+1(829)###-####", "cc": "DO", "name_en": "Dominican Republic", "desc_en": "", "name_ru": "Доминиканская Республика", "desc_ru": "" },
{ "mask": "+1(849)###-####", "cc": "DO", "name_en": "Dominican Republic", "desc_en": "", "name_ru": "Доминиканская Республика", "desc_ru": "" },
{ "mask": "+213-##-###-####", "cc": "DZ", "name_en": "Algeria", "desc_en": "", "name_ru": "Алжир", "desc_ru": "" },
{ "mask": "+593-##-###-####", "cc": "EC", "name_en": "Ecuador ", "desc_en": "mobile", "name_ru": "Эквадор ", "desc_ru": "мобильные" },
{ "mask": "+593-#-###-####", "cc": "EC", "name_en": "Ecuador", "desc_en": "", "name_ru": "Эквадор", "desc_ru": "" },
{ "mask": "+372-####-####", "cc": "EE", "name_en": "Estonia ", "desc_en": "mobile", "name_ru": "Эстония ", "desc_ru": "мобильные" },
{ "mask": "+372-###-####", "cc": "EE", "name_en": "Estonia", "desc_en": "", "name_ru": "Эстония", "desc_ru": "" },
{ "mask": "+20(###)###-####", "cc": "EG", "name_en": "Egypt", "desc_en": "", "name_ru": "Египет", "desc_ru": "" },
{ "mask": "+291-#-###-###", "cc": "ER", "name_en": "Eritrea", "desc_en": "", "name_ru": "Эритрея", "desc_ru": "" },
{ "mask": "+34(###)###-###", "cc": "ES", "name_en": "Spain", "desc_en": "", "name_ru": "Испания", "desc_ru": "" },
{ "mask": "+251-##-###-####", "cc": "ET", "name_en": "Ethiopia", "desc_en": "", "name_ru": "Эфиопия", "desc_ru": "" },
{ "mask": "+358(###)###-##-##", "cc": "FI", "name_en": "Finland", "desc_en": "", "name_ru": "Финляндия", "desc_ru": "" },
{ "mask": "+679-##-#####", "cc": "FJ", "name_en": "Fiji", "desc_en": "", "name_ru": "Фиджи", "desc_ru": "" },
{ "mask": "+500-#####", "cc": "FK", "name_en": "Falkland Islands", "desc_en": "", "name_ru": "Фолклендские острова", "desc_ru": "" },
{ "mask": "+691-###-####", "cc": "FM", "name_en": "F.S. Micronesia", "desc_en": "", "name_ru": "Ф.Ш. Микронезии", "desc_ru": "" },
{ "mask": "+298-###-###", "cc": "FO", "name_en": "Faroe Islands", "desc_en": "", "name_ru": "Фарерские острова", "desc_ru": "" },
{ "mask": "+262-#####-####", "cc": "FR", "name_en": "Mayotte", "desc_en": "", "name_ru": "Майотта", "desc_ru": "" },
{ "mask": "+33(###)###-###", "cc": "FR", "name_en": "France", "desc_en": "", "name_ru": "Франция", "desc_ru": "" },
{ "mask": "+508-##-####", "cc": "FR", "name_en": "St Pierre & Miquelon", "desc_en": "", "name_ru": "Сен-Пьер и Микелон", "desc_ru": "" },
{ "mask": "+590(###)###-###", "cc": "FR", "name_en": "Guadeloupe", "desc_en": "", "name_ru": "Гваделупа", "desc_ru": "" },
{ "mask": "+241-#-##-##-##", "cc": "GA", "name_en": "Gabon", "desc_en": "", "name_ru": "Габон", "desc_ru": "" },
{ "mask": "+1(473)###-####", "cc": "GD", "name_en": "Grenada", "desc_en": "", "name_ru": "Гренада", "desc_ru": "" },
{ "mask": "+995(###)###-###", "cc": "GE", "name_en": "Rep. of Georgia", "desc_en": "", "name_ru": "Грузия", "desc_ru": "" },
{ "mask": "+594-#####-####", "cc": "GF", "name_en": "Guiana (French)", "desc_en": "", "name_ru": "Фр. Гвиана", "desc_ru": "" },
{ "mask": "+233(###)###-###", "cc": "GH", "name_en": "Ghana", "desc_en": "", "name_ru": "Гана", "desc_ru": "" },
{ "mask": "+350-###-#####", "cc": "GI", "name_en": "Gibraltar", "desc_en": "", "name_ru": "Гибралтар", "desc_ru": "" },
{ "mask": "+299-##-##-##", "cc": "GL", "name_en": "Greenland", "desc_en": "", "name_ru": "Гренландия", "desc_ru": "" },
{ "mask": "+220(###)##-##", "cc": "GM", "name_en": "Gambia", "desc_en": "", "name_ru": "Гамбия", "desc_ru": "" },
{ "mask": "+224-##-###-###", "cc": "GN", "name_en": "Guinea", "desc_en": "", "name_ru": "Гвинея", "desc_ru": "" },
{ "mask": "+240-##-###-####", "cc": "GQ", "name_en": "Equatorial Guinea", "desc_en": "", "name_ru": "Экваториальная Гвинея", "desc_ru": "" },
{ "mask": "+30(###)###-####", "cc": "GR", "name_en": "Greece", "desc_en": "", "name_ru": "Греция", "desc_ru": "" },
{ "mask": "+502-#-###-####", "cc": "GT", "name_en": "Guatemala", "desc_en": "", "name_ru": "Гватемала", "desc_ru": "" },
{ "mask": "+1(671)###-####", "cc": "GU", "name_en": "Guam", "desc_en": "", "name_ru": "Гуам", "desc_ru": "" },
{ "mask": "+245-#-######", "cc": "GW", "name_en": "Guinea-Bissau", "desc_en": "", "name_ru": "Гвинея-Бисау", "desc_ru": "" },
{ "mask": "+592-###-####", "cc": "GY", "name_en": "Guyana", "desc_en": "", "name_ru": "Гайана", "desc_ru": "" },
{ "mask": "+852-####-####", "cc": "HK", "name_en": "Hong Kong", "desc_en": "", "name_ru": "Гонконг", "desc_ru": "" },
{ "mask": "+504-####-####", "cc": "HN", "name_en": "Honduras", "desc_en": "", "name_ru": "Гондурас", "desc_ru": "" },
{ "mask": "+385-##-###-###", "cc": "HR", "name_en": "Croatia", "desc_en": "", "name_ru": "Хорватия", "desc_ru": "" },
{ "mask": "+509-##-##-####", "cc": "HT", "name_en": "Haiti", "desc_en": "", "name_ru": "Гаити", "desc_ru": "" },
{ "mask": "+36(###)###-###", "cc": "HU", "name_en": "Hungary", "desc_en": "", "name_ru": "Венгрия", "desc_ru": "" },
{ "mask": "+62(8##)###-####", "cc": "ID", "name_en": "Indonesia ", "desc_en": "mobile", "name_ru": "Индонезия ", "desc_ru": "мобильные" },
{ "mask": "+62-##-###-##", "cc": "ID", "name_en": "Indonesia", "desc_en": "", "name_ru": "Индонезия", "desc_ru": "" },
{ "mask": "+62-##-###-###", "cc": "ID", "name_en": "Indonesia", "desc_en": "", "name_ru": "Индонезия", "desc_ru": "" },
{ "mask": "+62-##-###-####", "cc": "ID", "name_en": "Indonesia", "desc_en": "", "name_ru": "Индонезия", "desc_ru": "" },
{ "mask": "+62(8##)###-###", "cc": "ID", "name_en": "Indonesia ", "desc_en": "mobile", "name_ru": "Индонезия ", "desc_ru": "мобильные" },
{ "mask": "+62(8##)###-##-###", "cc": "ID", "name_en": "Indonesia ", "desc_en": "mobile", "name_ru": "Индонезия ", "desc_ru": "мобильные" },
{ "mask": "+353(###)###-###", "cc": "IE", "name_en": "Ireland", "desc_en": "", "name_ru": "Ирландия", "desc_ru": "" },
{ "mask": "+972-5#-###-####", "cc": "IL", "name_en": "Israel ", "desc_en": "mobile", "name_ru": "Израиль ", "desc_ru": "мобильные" },
{ "mask": "+972-#-###-####", "cc": "IL", "name_en": "Israel", "desc_en": "", "name_ru": "Израиль", "desc_ru": "" },
{ "mask": "+91(####)###-###", "cc": "IN", "name_en": "India", "desc_en": "", "name_ru": "Индия", "desc_ru": "" },
{ "mask": "+246-###-####", "cc": "IO", "name_en": "Diego Garcia", "desc_en": "", "name_ru": "Диего-Гарсия", "desc_ru": "" },
{ "mask": "+964(###)###-####", "cc": "IQ", "name_en": "Iraq", "desc_en": "", "name_ru": "Ирак", "desc_ru": "" },
{ "mask": "+98(###)###-####", "cc": "IR", "name_en": "Iran", "desc_en": "", "name_ru": "Иран", "desc_ru": "" },
{ "mask": "+354-###-####", "cc": "IS", "name_en": "Iceland", "desc_en": "", "name_ru": "Исландия", "desc_ru": "" },
{ "mask": "+39(###)####-###", "cc": "IT", "name_en": "Italy", "desc_en": "", "name_ru": "Италия", "desc_ru": "" },
{ "mask": "+1(876)###-####", "cc": "JM", "name_en": "Jamaica", "desc_en": "", "name_ru": "Ямайка", "desc_ru": "" },
{ "mask": "+962-#-####-####", "cc": "JO", "name_en": "Jordan", "desc_en": "", "name_ru": "Иордания", "desc_ru": "" },
{ "mask": "+81-##-####-####", "cc": "JP", "name_en": "Japan ", "desc_en": "mobile", "name_ru": "Япония ", "desc_ru": "мобильные" },
{ "mask": "+81(###)###-###", "cc": "JP", "name_en": "Japan", "desc_en": "", "name_ru": "Япония", "desc_ru": "" },
{ "mask": "+254-###-######", "cc": "KE", "name_en": "Kenya", "desc_en": "", "name_ru": "Кения", "desc_ru": "" },
{ "mask": "+996(###)###-###", "cc": "KG", "name_en": "Kyrgyzstan", "desc_en": "", "name_ru": "Киргизия", "desc_ru": "" },
{ "mask": "+855-##-###-###", "cc": "KH", "name_en": "Cambodia", "desc_en": "", "name_ru": "Камбоджа", "desc_ru": "" },
{ "mask": "+686-##-###", "cc": "KI", "name_en": "Kiribati", "desc_en": "", "name_ru": "Кирибати", "desc_ru": "" },
{ "mask": "+269-##-#####", "cc": "KM", "name_en": "Comoros", "desc_en": "", "name_ru": "Коморы", "desc_ru": "" },
{ "mask": "+1(869)###-####", "cc": "KN", "name_en": "Saint Kitts & Nevis", "desc_en": "", "name_ru": "Сент-Китс и Невис", "desc_ru": "" },
{ "mask": "+850-191-###-####", "cc": "KP", "name_en": "DPR Korea (North) ", "desc_en": "mobile", "name_ru": "Корейская НДР ", "desc_ru": "мобильные" },
{ "mask": "+850-##-###-###", "cc": "KP", "name_en": "DPR Korea (North)", "desc_en": "", "name_ru": "Корейская НДР", "desc_ru": "" },
{ "mask": "+850-###-####-###", "cc": "KP", "name_en": "DPR Korea (North)", "desc_en": "", "name_ru": "Корейская НДР", "desc_ru": "" },
{ "mask": "+850-###-###", "cc": "KP", "name_en": "DPR Korea (North)", "desc_en": "", "name_ru": "Корейская НДР", "desc_ru": "" },
{ "mask": "+850-####-####", "cc": "KP", "name_en": "DPR Korea (North)", "desc_en": "", "name_ru": "Корейская НДР", "desc_ru": "" },
{ "mask": "+850-####-#############", "cc": "KP", "name_en": "DPR Korea (North)", "desc_en": "", "name_ru": "Корейская НДР", "desc_ru": "" },
{ "mask": "+82-##-###-####", "cc": "KR", "name_en": "Korea (South)", "desc_en": "", "name_ru": "Респ. Корея", "desc_ru": "" },
{ "mask": "+965-####-####", "cc": "KW", "name_en": "Kuwait", "desc_en": "", "name_ru": "Кувейт", "desc_ru": "" },
{ "mask": "+1(345)###-####", "cc": "KY", "name_en": "Cayman Islands", "desc_en": "", "name_ru": "Каймановы острова", "desc_ru": "" },
{ "mask": "+7(6##)###-##-##", "cc": "KZ", "name_en": "Kazakhstan", "desc_en": "", "name_ru": "Казахстан", "desc_ru": "" },
{ "mask": "+7(7##)###-##-##", "cc": "KZ", "name_en": "Kazakhstan", "desc_en": "", "name_ru": "Казахстан", "desc_ru": "" },
{ "mask": "+856(20##)###-###", "cc": "LA", "name_en": "Laos ", "desc_en": "mobile", "name_ru": "Лаос ", "desc_ru": "мобильные" },
{ "mask": "+856-##-###-###", "cc": "LA", "name_en": "Laos", "desc_en": "", "name_ru": "Лаос", "desc_ru": "" },
{ "mask": "+961-##-###-###", "cc": "LB", "name_en": "Lebanon ", "desc_en": "mobile", "name_ru": "Ливан ", "desc_ru": "мобильные" },
{ "mask": "+961-#-###-###", "cc": "LB", "name_en": "Lebanon", "desc_en": "", "name_ru": "Ливан", "desc_ru": "" },
{ "mask": "+1(758)###-####", "cc": "LC", "name_en": "Saint Lucia", "desc_en": "", "name_ru": "Сент-Люсия", "desc_ru": "" },
{ "mask": "+423(###)###-####", "cc": "LI", "name_en": "Liechtenstein", "desc_en": "", "name_ru": "Лихтенштейн", "desc_ru": "" },
{ "mask": "+94-##-###-####", "cc": "LK", "name_en": "Sri Lanka", "desc_en": "", "name_ru": "Шри-Ланка", "desc_ru": "" },
{ "mask": "+231-##-###-###", "cc": "LR", "name_en": "Liberia", "desc_en": "", "name_ru": "Либерия", "desc_ru": "" },
{ "mask": "+266-#-###-####", "cc": "LS", "name_en": "Lesotho", "desc_en": "", "name_ru": "Лесото", "desc_ru": "" },
{ "mask": "+370(###)##-###", "cc": "LT", "name_en": "Lithuania", "desc_en": "", "name_ru": "Литва", "desc_ru": "" },
{ "mask": "+352(###)###-###", "cc": "LU", "name_en": "Luxembourg", "desc_en": "", "name_ru": "Люксембург", "desc_ru": "" },
{ "mask": "+371-##-###-###", "cc": "LV", "name_en": "Latvia", "desc_en": "", "name_ru": "Латвия", "desc_ru": "" },
{ "mask": "+218-##-###-###", "cc": "LY", "name_en": "Libya", "desc_en": "", "name_ru": "Ливия", "desc_ru": "" },
{ "mask": "+218-21-###-####", "cc": "LY", "name_en": "Libya", "desc_en": "Tripoli", "name_ru": "Ливия", "desc_ru": "Триполи" },
{ "mask": "+212-##-####-###", "cc": "MA", "name_en": "Morocco", "desc_en": "", "name_ru": "Марокко", "desc_ru": "" },
{ "mask": "+377(###)###-###", "cc": "MC", "name_en": "Monaco", "desc_en": "", "name_ru": "Монако", "desc_ru": "" },
{ "mask": "+377-##-###-###", "cc": "MC", "name_en": "Monaco", "desc_en": "", "name_ru": "Монако", "desc_ru": "" },
{ "mask": "+373-####-####", "cc": "MD", "name_en": "Moldova", "desc_en": "", "name_ru": "Молдова", "desc_ru": "" },
{ "mask": "+382-##-###-###", "cc": "ME", "name_en": "Montenegro", "desc_en": "", "name_ru": "Черногория", "desc_ru": "" },
{ "mask": "+261-##-##-#####", "cc": "MG", "name_en": "Madagascar", "desc_en": "", "name_ru": "Мадагаскар", "desc_ru": "" },
{ "mask": "+692-###-####", "cc": "MH", "name_en": "Marshall Islands", "desc_en": "", "name_ru": "Маршалловы Острова", "desc_ru": "" },
{ "mask": "+389-##-###-###", "cc": "MK", "name_en": "Republic of Macedonia", "desc_en": "", "name_ru": "Респ. Македония", "desc_ru": "" },
{ "mask": "+223-##-##-####", "cc": "ML", "name_en": "Mali", "desc_en": "", "name_ru": "Мали", "desc_ru": "" },
{ "mask": "+95-##-###-###", "cc": "MM", "name_en": "Burma (Myanmar)", "desc_en": "", "name_ru": "Бирма (Мьянма)", "desc_ru": "" },
{ "mask": "+95-#-###-###", "cc": "MM", "name_en": "Burma (Myanmar)", "desc_en": "", "name_ru": "Бирма (Мьянма)", "desc_ru": "" },
{ "mask": "+95-###-###", "cc": "MM", "name_en": "Burma (Myanmar)", "desc_en": "", "name_ru": "Бирма (Мьянма)", "desc_ru": "" },
{ "mask": "+976-##-##-####", "cc": "MN", "name_en": "Mongolia", "desc_en": "", "name_ru": "Монголия", "desc_ru": "" },
{ "mask": "+853-####-####", "cc": "MO", "name_en": "Macau", "desc_en": "", "name_ru": "Макао", "desc_ru": "" },
{ "mask": "+1(670)###-####", "cc": "MP", "name_en": "Northern Mariana Islands", "desc_en": "", "name_ru": "Северные Марианские острова Сайпан", "desc_ru": "" },
{ "mask": "+596(###)##-##-##", "cc": "MQ", "name_en": "Martinique", "desc_en": "", "name_ru": "Мартиника", "desc_ru": "" },
{ "mask": "+222-##-##-####", "cc": "MR", "name_en": "Mauritania", "desc_en": "", "name_ru": "Мавритания", "desc_ru": "" },
{ "mask": "+1(664)###-####", "cc": "MS", "name_en": "Montserrat", "desc_en": "", "name_ru": "Монтсеррат", "desc_ru": "" },
{ "mask": "+356-####-####", "cc": "MT", "name_en": "Malta", "desc_en": "", "name_ru": "Мальта", "desc_ru": "" },
{ "mask": "+230-###-####", "cc": "MU", "name_en": "Mauritius", "desc_en": "", "name_ru": "Маврикий", "desc_ru": "" },
{ "mask": "+960-###-####", "cc": "MV", "name_en": "Maldives", "desc_en": "", "name_ru": "Мальдивские острова", "desc_ru": "" },
{ "mask": "+265-1-###-###", "cc": "MW", "name_en": "Malawi", "desc_en": "Telecom Ltd", "name_ru": "Малави", "desc_ru": "Telecom Ltd" },
{ "mask": "+265-#-####-####", "cc": "MW", "name_en": "Malawi", "desc_en": "", "name_ru": "Малави", "desc_ru": "" },
{ "mask": "+52(###)###-####", "cc": "MX", "name_en": "Mexico", "desc_en": "", "name_ru": "Мексика", "desc_ru": "" },
{ "mask": "+52-##-##-####", "cc": "MX", "name_en": "Mexico", "desc_en": "", "name_ru": "Мексика", "desc_ru": "" },
{ "mask": "+60-##-###-####", "cc": "MY", "name_en": "Malaysia ", "desc_en": "mobile", "name_ru": "Малайзия ", "desc_ru": "мобильные" },
{ "mask": "+60(###)###-###", "cc": "MY", "name_en": "Malaysia", "desc_en": "", "name_ru": "Малайзия", "desc_ru": "" },
{ "mask": "+60-##-###-###", "cc": "MY", "name_en": "Malaysia", "desc_en": "", "name_ru": "Малайзия", "desc_ru": "" },
{ "mask": "+60-#-###-###", "cc": "MY", "name_en": "Malaysia", "desc_en": "", "name_ru": "Малайзия", "desc_ru": "" },
{ "mask": "+258-##-###-###", "cc": "MZ", "name_en": "Mozambique", "desc_en": "", "name_ru": "Мозамбик", "desc_ru": "" },
{ "mask": "+264-##-###-####", "cc": "NA", "name_en": "Namibia", "desc_en": "", "name_ru": "Намибия", "desc_ru": "" },
{ "mask": "+687-##-####", "cc": "NC", "name_en": "New Caledonia", "desc_en": "", "name_ru": "Новая Каледония", "desc_ru": "" },
{ "mask": "+227-##-##-####", "cc": "NE", "name_en": "Niger", "desc_en": "", "name_ru": "Нигер", "desc_ru": "" },
{ "mask": "+672-3##-###", "cc": "NF", "name_en": "Norfolk Island", "desc_en": "", "name_ru": "Норфолк (остров)", "desc_ru": "" },
{ "mask": "+234(###)###-####", "cc": "NG", "name_en": "Nigeria", "desc_en": "", "name_ru": "Нигерия", "desc_ru": "" },
{ "mask": "+234-##-###-###", "cc": "NG", "name_en": "Nigeria", "desc_en": "", "name_ru": "Нигерия", "desc_ru": "" },
{ "mask": "+234-##-###-##", "cc": "NG", "name_en": "Nigeria", "desc_en": "", "name_ru": "Нигерия", "desc_ru": "" },
{ "mask": "+234(###)###-####", "cc": "NG", "name_en": "Nigeria ", "desc_en": "mobile", "name_ru": "Нигерия ", "desc_ru": "мобильные" },
{ "mask": "+505-####-####", "cc": "NI", "name_en": "Nicaragua", "desc_en": "", "name_ru": "Никарагуа", "desc_ru": "" },
{ "mask": "+31-##-###-####", "cc": "NL", "name_en": "Netherlands", "desc_en": "", "name_ru": "Нидерланды", "desc_ru": "" },
{ "mask": "+47(###)##-###", "cc": "NO", "name_en": "Norway", "desc_en": "", "name_ru": "Норвегия", "desc_ru": "" },
{ "mask": "+977-##-###-###", "cc": "NP", "name_en": "Nepal", "desc_en": "", "name_ru": "Непал", "desc_ru": "" },
{ "mask": "+674-###-####", "cc": "NR", "name_en": "Nauru", "desc_en": "", "name_ru": "Науру", "desc_ru": "" },
{ "mask": "+683-####", "cc": "NU", "name_en": "Niue", "desc_en": "", "name_ru": "Ниуэ", "desc_ru": "" },
{ "mask": "+64(###)###-###", "cc": "NZ", "name_en": "New Zealand", "desc_en": "", "name_ru": "Новая Зеландия", "desc_ru": "" },
{ "mask": "+64-##-###-###", "cc": "NZ", "name_en": "New Zealand", "desc_en": "", "name_ru": "Новая Зеландия", "desc_ru": "" },
{ "mask": "+64(###)###-####", "cc": "NZ", "name_en": "New Zealand", "desc_en": "", "name_ru": "Новая Зеландия", "desc_ru": "" },
{ "mask": "+968-##-###-###", "cc": "OM", "name_en": "Oman", "desc_en": "", "name_ru": "Оман", "desc_ru": "" },
{ "mask": "+507-###-####", "cc": "PA", "name_en": "Panama", "desc_en": "", "name_ru": "Панама", "desc_ru": "" },
{ "mask": "+51(###)###-###", "cc": "PE", "name_en": "Peru", "desc_en": "", "name_ru": "Перу", "desc_ru": "" },
{ "mask": "+689-##-##-##", "cc": "PF", "name_en": "French Polynesia", "desc_en": "", "name_ru": "Французская Полинезия (Таити)", "desc_ru": "" },
{ "mask": "+675(###)##-###", "cc": "PG", "name_en": "Papua New Guinea", "desc_en": "", "name_ru": "Папуа-Новая Гвинея", "desc_ru": "" },
{ "mask": "+63(###)###-####", "cc": "PH", "name_en": "Philippines", "desc_en": "", "name_ru": "Филиппины", "desc_ru": "" },
{ "mask": "+92(###)###-####", "cc": "PK", "name_en": "Pakistan", "desc_en": "", "name_ru": "Пакистан", "desc_ru": "" },
{ "mask": "+48(###)###-###", "cc": "PL", "name_en": "Poland", "desc_en": "", "name_ru": "Польша", "desc_ru": "" },
{ "mask": "+970-##-###-####", "cc": "PS", "name_en": "Palestine", "desc_en": "", "name_ru": "Палестина", "desc_ru": "" },
{ "mask": "+351-##-###-####", "cc": "PT", "name_en": "Portugal", "desc_en": "", "name_ru": "Португалия", "desc_ru": "" },
{ "mask": "+680-###-####", "cc": "PW", "name_en": "Palau", "desc_en": "", "name_ru": "Палау", "desc_ru": "" },
{ "mask": "+595(###)###-###", "cc": "PY", "name_en": "Paraguay", "desc_en": "", "name_ru": "Парагвай", "desc_ru": "" },
{ "mask": "+974-####-####", "cc": "QA", "name_en": "Qatar", "desc_en": "", "name_ru": "Катар", "desc_ru": "" },
{ "mask": "+262-#####-####", "cc": "RE", "name_en": "Reunion", "desc_en": "", "name_ru": "Реюньон", "desc_ru": "" },
{ "mask": "+40-##-###-####", "cc": "RO", "name_en": "Romania", "desc_en": "", "name_ru": "Румыния", "desc_ru": "" },
{ "mask": "+381-##-###-####", "cc": "RS", "name_en": "Serbia", "desc_en": "", "name_ru": "Сербия", "desc_ru": "" },
{ "mask": "+7(###)###-##-##", "cc": "RU", "name_en": "Russia", "desc_en": "", "name_ru": "Россия", "desc_ru": "" },
{ "mask": "+250(###)###-###", "cc": "RW", "name_en": "Rwanda", "desc_en": "", "name_ru": "Руанда", "desc_ru": "" },
{ "mask": "+966-5-####-####", "cc": "SA", "name_en": "Saudi Arabia ", "desc_en": "mobile", "name_ru": "Саудовская Аравия ", "desc_ru": "мобильные" },
{ "mask": "+966-#-###-####", "cc": "SA", "name_en": "Saudi Arabia", "desc_en": "", "name_ru": "Саудовская Аравия", "desc_ru": "" },
{ "mask": "+677-###-####", "cc": "SB", "name_en": "Solomon Islands ", "desc_en": "mobile", "name_ru": "Соломоновы Острова ", "desc_ru": "мобильные" },
{ "mask": "+677-#####", "cc": "SB", "name_en": "Solomon Islands", "desc_en": "", "name_ru": "Соломоновы Острова", "desc_ru": "" },
{ "mask": "+248-#-###-###", "cc": "SC", "name_en": "Seychelles", "desc_en": "", "name_ru": "Сейшелы", "desc_ru": "" },
{ "mask": "+249-##-###-####", "cc": "SD", "name_en": "Sudan", "desc_en": "", "name_ru": "Судан", "desc_ru": "" },
{ "mask": "+46-##-###-####", "cc": "SE", "name_en": "Sweden", "desc_en": "", "name_ru": "Швеция", "desc_ru": "" },
{ "mask": "+65-####-####", "cc": "SG", "name_en": "Singapore", "desc_en": "", "name_ru": "Сингапур", "desc_ru": "" },
{ "mask": "+290-####", "cc": "SH", "name_en": "Saint Helena", "desc_en": "", "name_ru": "Остров Святой Елены", "desc_ru": "" },
{ "mask": "+290-####", "cc": "SH", "name_en": "Tristan da Cunha", "desc_en": "", "name_ru": "Тристан-да-Кунья", "desc_ru": "" },
{ "mask": "+386-##-###-###", "cc": "SI", "name_en": "Slovenia", "desc_en": "", "name_ru": "Словения", "desc_ru": "" },
{ "mask": "+421(###)###-###", "cc": "SK", "name_en": "Slovakia", "desc_en": "", "name_ru": "Словакия", "desc_ru": "" },
{ "mask": "+232-##-######", "cc": "SL", "name_en": "Sierra Leone", "desc_en": "", "name_ru": "Сьерра-Леоне", "desc_ru": "" },
{ "mask": "+378-####-######", "cc": "SM", "name_en": "San Marino", "desc_en": "", "name_ru": "Сан-Марино", "desc_ru": "" },
{ "mask": "+221-##-###-####", "cc": "SN", "name_en": "Senegal", "desc_en": "", "name_ru": "Сенегал", "desc_ru": "" },
{ "mask": "+252-##-###-###", "cc": "SO", "name_en": "Somalia", "desc_en": "", "name_ru": "Сомали", "desc_ru": "" },
{ "mask": "+252-#-###-###", "cc": "SO", "name_en": "Somalia", "desc_en": "", "name_ru": "Сомали", "desc_ru": "" },
{ "mask": "+252-#-###-###", "cc": "SO", "name_en": "Somalia ", "desc_en": "mobile", "name_ru": "Сомали ", "desc_ru": "мобильные" },
{ "mask": "+597-###-####", "cc": "SR", "name_en": "Suriname ", "desc_en": "mobile", "name_ru": "Суринам ", "desc_ru": "мобильные" },
{ "mask": "+597-###-###", "cc": "SR", "name_en": "Suriname", "desc_en": "", "name_ru": "Суринам", "desc_ru": "" },
{ "mask": "+211-##-###-####", "cc": "SS", "name_en": "South Sudan", "desc_en": "", "name_ru": "Южный Судан", "desc_ru": "" },
{ "mask": "+239-##-#####", "cc": "ST", "name_en": "Sao Tome and Principe", "desc_en": "", "name_ru": "Сан-Томе и Принсипи", "desc_ru": "" },
{ "mask": "+503-##-##-####", "cc": "SV", "name_en": "El Salvador", "desc_en": "", "name_ru": "Сальвадор", "desc_ru": "" },
{ "mask": "+1(721)###-####", "cc": "SX", "name_en": "Sint Maarten", "desc_en": "", "name_ru": "Синт-Маартен", "desc_ru": "" },
{ "mask": "+963-##-####-###", "cc": "SY", "name_en": "Syrian Arab Republic", "desc_en": "", "name_ru": "Сирийская арабская республика", "desc_ru": "" },
{ "mask": "+268-##-##-####", "cc": "SZ", "name_en": "Swaziland", "desc_en": "", "name_ru": "Свазиленд", "desc_ru": "" },
{ "mask": "+1(649)###-####", "cc": "TC", "name_en": "Turks & Caicos", "desc_en": "", "name_ru": "Тёркс и Кайкос", "desc_ru": "" },
{ "mask": "+235-##-##-##-##", "cc": "TD", "name_en": "Chad", "desc_en": "", "name_ru": "Чад", "desc_ru": "" },
{ "mask": "+228-##-###-###", "cc": "TG", "name_en": "Togo", "desc_en": "", "name_ru": "Того", "desc_ru": "" },
{ "mask": "+66-##-###-####", "cc": "TH", "name_en": "Thailand ", "desc_en": "mobile", "name_ru": "Таиланд ", "desc_ru": "мобильные" },
{ "mask": "+66-##-###-###", "cc": "TH", "name_en": "Thailand", "desc_en": "", "name_ru": "Таиланд", "desc_ru": "" },
{ "mask": "+992-##-###-####", "cc": "TJ", "name_en": "Tajikistan", "desc_en": "", "name_ru": "Таджикистан", "desc_ru": "" },
{ "mask": "+690-####", "cc": "TK", "name_en": "Tokelau", "desc_en": "", "name_ru": "Токелау", "desc_ru": "" },
{ "mask": "+670-###-####", "cc": "TL", "name_en": "East Timor", "desc_en": "", "name_ru": "Восточный Тимор", "desc_ru": "" },
{ "mask": "+670-77#-#####", "cc": "TL", "name_en": "East Timor", "desc_en": "Timor Telecom", "name_ru": "Восточный Тимор", "desc_ru": "Timor Telecom" },
{ "mask": "+670-78#-#####", "cc": "TL", "name_en": "East Timor", "desc_en": "Timor Telecom", "name_ru": "Восточный Тимор", "desc_ru": "Timor Telecom" },
{ "mask": "+993-#-###-####", "cc": "TM", "name_en": "Turkmenistan", "desc_en": "", "name_ru": "Туркменистан", "desc_ru": "" },
{ "mask": "+216-##-###-###", "cc": "TN", "name_en": "Tunisia", "desc_en": "", "name_ru": "Тунис", "desc_ru": "" },
{ "mask": "+676-#####", "cc": "TO", "name_en": "Tonga", "desc_en": "", "name_ru": "Тонга", "desc_ru": "" },
{ "mask": "+90(###)###-####", "cc": "TR", "name_en": "Turkey", "desc_en": "", "name_ru": "Турция", "desc_ru": "" },
{ "mask": "+1(868)###-####", "cc": "TT", "name_en": "Trinidad & Tobago", "desc_en": "", "name_ru": "Тринидад и Тобаго", "desc_ru": "" },
{ "mask": "+688-90####", "cc": "TV", "name_en": "Tuvalu ", "desc_en": "mobile", "name_ru": "Тувалу ", "desc_ru": "мобильные" },
{ "mask": "+688-2####", "cc": "TV", "name_en": "Tuvalu", "desc_en": "", "name_ru": "Тувалу", "desc_ru": "" },
{ "mask": "+886-#-####-####", "cc": "TW", "name_en": "Taiwan", "desc_en": "", "name_ru": "Тайвань", "desc_ru": "" },
{ "mask": "+886-####-####", "cc": "TW", "name_en": "Taiwan", "desc_en": "", "name_ru": "Тайвань", "desc_ru": "" },
{ "mask": "+255-##-###-####", "cc": "TZ", "name_en": "Tanzania", "desc_en": "", "name_ru": "Танзания", "desc_ru": "" },
{ "mask": "+380(##)###-##-##", "cc": "UA", "name_en": "Ukraine", "desc_en": "", "name_ru": "Украина", "desc_ru": "" },
{ "mask": "+256(###)###-###", "cc": "UG", "name_en": "Uganda", "desc_en": "", "name_ru": "Уганда", "desc_ru": "" },
{ "mask": "+44-##-####-####", "cc": "UK", "name_en": "United Kingdom", "desc_en": "", "name_ru": "Великобритания", "desc_ru": "" },
{ "mask": "+598-#-###-##-##", "cc": "UY", "name_en": "Uruguay", "desc_en": "", "name_ru": "Уругвай", "desc_ru": "" },
{ "mask": "+998-##-###-####", "cc": "UZ", "name_en": "Uzbekistan", "desc_en": "", "name_ru": "Узбекистан", "desc_ru": "" },
{ "mask": "+39-6-698-#####", "cc": "VA", "name_en": "Vatican City", "desc_en": "", "name_ru": "Ватикан", "desc_ru": "" },
{ "mask": "+1(784)###-####", "cc": "VC", "name_en": "Saint Vincent & the Grenadines", "desc_en": "", "name_ru": "Сент-Винсент и Гренадины", "desc_ru": "" },
{ "mask": "+58(###)###-####", "cc": "VE", "name_en": "Venezuela", "desc_en": "", "name_ru": "Венесуэла", "desc_ru": "" },
{ "mask": "+1(284)###-####", "cc": "VG", "name_en": "British Virgin Islands", "desc_en": "", "name_ru": "Британские Виргинские острова", "desc_ru": "" },
{ "mask": "+1(340)###-####", "cc": "VI", "name_en": "US Virgin Islands", "desc_en": "", "name_ru": "Американские Виргинские острова", "desc_ru": "" },
{ "mask": "+84-##-####-###", "cc": "VN", "name_en": "Vietnam", "desc_en": "", "name_ru": "Вьетнам", "desc_ru": "" },
{ "mask": "+84(###)####-###", "cc": "VN", "name_en": "Vietnam", "desc_en": "", "name_ru": "Вьетнам", "desc_ru": "" },
{ "mask": "+678-##-#####", "cc": "VU", "name_en": "Vanuatu ", "desc_en": "mobile", "name_ru": "Вануату ", "desc_ru": "мобильные" },
{ "mask": "+678-#####", "cc": "VU", "name_en": "Vanuatu", "desc_en": "", "name_ru": "Вануату", "desc_ru": "" },
{ "mask": "+681-##-####", "cc": "WF", "name_en": "Wallis and Futuna", "desc_en": "", "name_ru": "Уоллис и Футуна", "desc_ru": "" },
{ "mask": "+685-##-####", "cc": "WS", "name_en": "Samoa", "desc_en": "", "name_ru": "Самоа", "desc_ru": "" },
{ "mask": "+967-###-###-###", "cc": "YE", "name_en": "Yemen ", "desc_en": "mobile", "name_ru": "Йемен ", "desc_ru": "мобильные" },
{ "mask": "+967-#-###-###", "cc": "YE", "name_en": "Yemen", "desc_en": "", "name_ru": "Йемен", "desc_ru": "" },
{ "mask": "+967-##-###-###", "cc": "YE", "name_en": "Yemen", "desc_en": "", "name_ru": "Йемен", "desc_ru": "" },
{ "mask": "+27-##-###-####", "cc": "ZA", "name_en": "South Africa", "desc_en": "", "name_ru": "Южно-Африканская Респ.", "desc_ru": "" },
{ "mask": "+260-##-###-####", "cc": "ZM", "name_en": "Zambia", "desc_en": "", "name_ru": "Замбия", "desc_ru": "" },
{ "mask": "+263-#-######", "cc": "ZW", "name_en": "Zimbabwe", "desc_en": "", "name_ru": "Зимбабве", "desc_ru": "" },
{ "mask": "+1(###)###-####", "cc": ["US", "CA"], "name_en": "USA and Canada", "desc_en": "", "name_ru": "США и Канада", "desc_ru": "" }
]
| {
"pile_set_name": "Github"
} |
var convert = require('./convert'),
func = convert('flatten', require('../flatten'), require('./_falseOptions'));
func.placeholder = require('./placeholder');
module.exports = func;
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2013 Mellanox Technologies, Inc.
* All rights reserved.
* Copyright (c) 2013 Cisco Systems, Inc. All rights reserved.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*/
#include "oshmem_config.h"
#include "oshmem/shmem/fortran/bindings.h"
#include "oshmem/include/shmem.h"
#include "oshmem/shmem/shmem_api_logger.h"
#include "oshmem/runtime/runtime.h"
#include "oshmem/mca/spml/spml.h"
#include "ompi/datatype/ompi_datatype.h"
#include "stdio.h"
#if OSHMEM_PROFILING
#include "oshmem/shmem/fortran/profile/pbindings.h"
SHMEM_GENERATE_WEAK_BINDINGS(SHMEM_IGET32, shmem_iget32)
#include "oshmem/shmem/fortran/profile/defines.h"
#endif
SHMEM_GENERATE_FORTRAN_BINDINGS_SUB (void,
SHMEM_IGET32,
shmem_iget32_,
shmem_iget32__,
shmem_iget32_f,
(FORTRAN_POINTER_T target, FORTRAN_POINTER_T source, MPI_Fint *tst, MPI_Fint *sst, MPI_Fint *len, MPI_Fint *pe),
(target,source,tst,sst,len,pe) )
void shmem_iget32_f(FORTRAN_POINTER_T target, FORTRAN_POINTER_T source, MPI_Fint *tst, MPI_Fint *sst, MPI_Fint *len, MPI_Fint *pe)
{
int i;
int length = OMPI_FINT_2_INT(*len);
int tst_c = OMPI_FINT_2_INT(*tst);
int sst_c = OMPI_FINT_2_INT(*sst);
for (i=0; i<length; i++)
{
MCA_SPML_CALL(get(oshmem_ctx_default, (uint8_t *)FPTR_2_VOID_PTR(source) + i * sst_c * 4,
4,
(uint8_t *)FPTR_2_VOID_PTR(target) + i * tst_c * 4,
OMPI_FINT_2_INT(*pe)));
}
}
| {
"pile_set_name": "Github"
} |
"Space" = "Κενό";
"Use old shortcut" = "Χρήση παλιάς συντόμευσης";
"Type shortcut" = "Εισαγωγή συντόμευσης";
"Click to record shortcut" = "Κλίκ για εισαγωγή συντόμευσης";
"Pad %@" = "Numpad %@";
"The key combination %@ can't be used!" = "Ο συνδιασμός πλήκτρων \"%@\" δεν μπορεί να χρησιμοποιηθεί!";
"The key combination \"%@\" can't be used because %@." = "Ο συνδιασμός πλήκτρων \"%@\" δεν μπορεί να χρησιμοποιηθεί λόγω %@.";
"The key combination \"%@\" can't be used because it's already used by a system-wide keyboard shortcut. (If you really want to use this key combination, most shortcuts can be changed in the Keyboard & Mouse panel in System Preferences.)" = "Ο συνδιασμός πλήκτρων \"%@\" δεν μπορεί να χρησιμοποιηθεί γιατί χρησιμοποιείται ήδη από μια συντόμευση συστήματος. (Αν θέλετε οπωσδήποτε να χρησιμοποιήσετε αυτό τον συνδιασμό, οι περισσότερες συντομεύσεις μπορούν να αλλαχθούν στο πάνελ Keyboard & Mouse στο System Preferences.)";
"The key combination \"%@\" can't be used because it's already used by the menu item \"%@\"." = "Ο συνδιασμός πλήκτρων \"%@\" δεν μπορεί να χρησιμοποιηθεί γιατί χρησιμοποιείται ήδη από το μενού \"%@\".";
"Command + " = "Command + ";
"Option + " = "Option + ";
"Shift + " = "Shift + ";
"Control + " = "Control + "; | {
"pile_set_name": "Github"
} |
// It is expected that, when .add() returns false, the consumer
// of the DirWriter will pause until a "drain" event occurs. Note
// that this is *almost always going to be the case*, unless the
// thing being written is some sort of unsupported type, and thus
// skipped over.
module.exports = DirWriter
var fs = require("../../graceful-fs/graceful-fs.js")
, fstream = require("../fstream.js")
, Writer = require("./writer.js")
, inherits = require("../../inherits/inherits.js")
, mkdir = require("../../mkdirp")
, path = require("path")
, collect = require("./collect.js")
inherits(DirWriter, Writer)
function DirWriter (props) {
var me = this
if (!(me instanceof DirWriter)) me.error(
"DirWriter must be called as constructor.", null, true)
// should already be established as a Directory type
if (props.type !== "Directory" || !props.Directory) {
me.error("Non-directory type "+ props.type + " " +
JSON.stringify(props), null, true)
}
Writer.call(this, props)
}
DirWriter.prototype._create = function () {
var me = this
mkdir(me._path, Writer.dirmode, function (er) {
if (er) return me.error(er)
// ready to start getting entries!
me.ready = true
me.emit("ready")
me._process()
})
}
// a DirWriter has an add(entry) method, but its .write() doesn't
// do anything. Why a no-op rather than a throw? Because this
// leaves open the door for writing directory metadata for
// gnu/solaris style dumpdirs.
DirWriter.prototype.write = function () {
return true
}
DirWriter.prototype.end = function () {
this._ended = true
this._process()
}
DirWriter.prototype.add = function (entry) {
var me = this
// console.error("\tadd", entry._path, "->", me._path)
collect(entry)
if (!me.ready || me._currentEntry) {
me._buffer.push(entry)
return false
}
// create a new writer, and pipe the incoming entry into it.
if (me._ended) {
return me.error("add after end")
}
me._buffer.push(entry)
me._process()
return 0 === this._buffer.length
}
DirWriter.prototype._process = function () {
var me = this
// console.error("DW Process p=%j", me._processing, me.basename)
if (me._processing) return
var entry = me._buffer.shift()
if (!entry) {
// console.error("DW Drain")
me.emit("drain")
if (me._ended) me._finish()
return
}
me._processing = true
// console.error("DW Entry", entry._path)
me.emit("entry", entry)
// ok, add this entry
//
// don't allow recursive copying
var p = entry
do {
var pp = p._path || p.path
if (pp === me.root._path || pp === me._path ||
(pp && pp.indexOf(me._path) === 0)) {
// console.error("DW Exit (recursive)", entry.basename, me._path)
me._processing = false
if (entry._collected) entry.pipe()
return me._process()
}
} while (p = p.parent)
// console.error("DW not recursive")
// chop off the entry's root dir, replace with ours
var props = { parent: me
, root: me.root || me
, type: entry.type
, depth: me.depth + 1 }
var p = entry._path || entry.path || entry.props.path
if (entry.parent) {
p = p.substr(entry.parent._path.length + 1)
}
// get rid of any ../../ shenanigans
props.path = path.join(me.path, path.join("/", p))
// if i have a filter, the child should inherit it.
props.filter = me.filter
// all the rest of the stuff, copy over from the source.
Object.keys(entry.props).forEach(function (k) {
if (!props.hasOwnProperty(k)) {
props[k] = entry.props[k]
}
})
// not sure at this point what kind of writer this is.
var child = me._currentChild = new Writer(props)
child.on("ready", function () {
// console.error("DW Child Ready", child.type, child._path)
// console.error(" resuming", entry._path)
entry.pipe(child)
entry.resume()
})
// XXX Make this work in node.
// Long filenames should not break stuff.
child.on("error", function (er) {
if (child._swallowErrors) {
me.warn(er)
child.emit("end")
child.emit("close")
} else {
me.emit("error", er)
}
})
// we fire _end internally *after* end, so that we don't move on
// until any "end" listeners have had their chance to do stuff.
child.on("close", onend)
var ended = false
function onend () {
if (ended) return
ended = true
// console.error("* DW Child end", child.basename)
me._currentChild = null
me._processing = false
me._process()
}
}
| {
"pile_set_name": "Github"
} |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u043f\u0440\u0435 \u043f\u043e\u0434\u043d\u0435",
"\u043f\u043e\u043f\u043e\u0434\u043d\u0435"
],
"DAY": [
"\u043d\u0435\u0434\u0435\u0459\u0430",
"\u043f\u043e\u043d\u0435\u0434\u0435\u0459\u0430\u043a",
"\u0443\u0442\u043e\u0440\u0430\u043a",
"\u0441\u0440\u0438\u0458\u0435\u0434\u0430",
"\u0447\u0435\u0442\u0432\u0440\u0442\u0430\u043a",
"\u043f\u0435\u0442\u0430\u043a",
"\u0441\u0443\u0431\u043e\u0442\u0430"
],
"ERANAMES": [
"\u041f\u0440\u0435 \u043d\u043e\u0432\u0435 \u0435\u0440\u0435",
"\u041d\u043e\u0432\u0435 \u0435\u0440\u0435"
],
"ERAS": [
"\u043f. \u043d. \u0435.",
"\u043d. \u0435."
],
"MONTH": [
"\u0458\u0430\u043d\u0443\u0430\u0440",
"\u0444\u0435\u0431\u0440\u0443\u0430\u0440",
"\u043c\u0430\u0440\u0442",
"\u0430\u043f\u0440\u0438\u043b",
"\u043c\u0430\u0458",
"\u0458\u0443\u043d\u0438",
"\u0458\u0443\u043b\u0438",
"\u0430\u0432\u0433\u0443\u0441\u0442",
"\u0441\u0435\u043f\u0442\u0435\u043c\u0431\u0430\u0440",
"\u043e\u043a\u0442\u043e\u0431\u0430\u0440",
"\u043d\u043e\u0432\u0435\u043c\u0431\u0430\u0440",
"\u0434\u0435\u0446\u0435\u043c\u0431\u0430\u0440"
],
"SHORTDAY": [
"\u043d\u0435\u0434",
"\u043f\u043e\u043d",
"\u0443\u0442\u043e",
"\u0441\u0440\u0438",
"\u0447\u0435\u0442",
"\u043f\u0435\u0442",
"\u0441\u0443\u0431"
],
"SHORTMONTH": [
"\u0458\u0430\u043d",
"\u0444\u0435\u0431",
"\u043c\u0430\u0440",
"\u0430\u043f\u0440",
"\u043c\u0430\u0458",
"\u0458\u0443\u043d",
"\u0458\u0443\u043b",
"\u0430\u0432\u0433",
"\u0441\u0435\u043f",
"\u043e\u043a\u0442",
"\u043d\u043e\u0432",
"\u0434\u0435\u0446"
],
"fullDate": "EEEE, dd. MMMM y.",
"longDate": "dd. MMMM y.",
"medium": "dd.MM.y. HH:mm:ss",
"mediumDate": "dd.MM.y.",
"mediumTime": "HH:mm:ss",
"short": "d.M.yy. HH:mm",
"shortDate": "d.M.yy.",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": ".",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "bs-cyrl",
"pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
| {
"pile_set_name": "Github"
} |
<?php
namespace Imi\Cron;
use Imi\Cron\Message\IMessage;
class Client
{
/**
* socket 文件路径
*
* 不支持 samba 文件共享
*
* @var string
*/
private $socketFile;
/**
* socket 资源
*
* @var resource
*/
private $socket;
/**
* 是否已连接
*
* @var boolean
*/
private $connected;
/**
* 构造方法
*
* @param array $options
*/
public function __construct($options = [])
{
$this->options = $options;
if(!isset($options['socketFile']))
{
throw new \InvalidArgumentException('If you want to use Swoole Shared Memory, you must set the "socketFile" option');
}
$this->socketFile = $options['socketFile'];
}
/**
* 连接
*
* @return boolean
*/
public function connect(): bool
{
if($this->connected)
{
return true;
}
$this->socket = $socket = stream_socket_client('unix://' . $this->socketFile, $errno, $errstr, 10);
if(false === $socket)
{
$this->connected = false;
return false;
}
stream_set_timeout($socket, 10);
$this->connected = true;
return true;
}
/**
* 关闭连接
*
* @return void
*/
public function close()
{
if($this->connected)
{
fclose($this->socket);
$this->socket = null;
}
}
/**
* 是否已连接
*
* @return boolean
*/
public function isConnected(): bool
{
return $this->connected;
}
/**
* 发送操作
*
* @param IMessage $message
* @return boolean
*/
public function send(IMessage $message): bool
{
if(!$this->connected || !$this->connect())
{
return false;
}
$data = serialize($message);
$length = strlen($data);
$data = pack('N', $length) . $data;
$length += 4;
$result = fwrite($this->socket, $data, $length);
if(false === $result)
{
$this->close();
}
return $length === $result;
}
/**
* 接收结果
*
* @return \Imi\Cron\Message\IMessage|boolean
*/
public function recv()
{
if(!$this->connected || !$this->connect())
{
return false;
}
$meta = fread($this->socket, 4);
if('' === $meta || false === $meta)
{
$this->close();
return false;
}
$length = unpack('N', $meta)[1];
$data = fread($this->socket, $length);
if(false === $data || !isset($data[$length - 1]))
{
$this->close();
return false;
}
$result = unserialize($data);
if($result instanceof IMessage)
{
return $result;
}
else
{
return false;
}
}
} | {
"pile_set_name": "Github"
} |
<?php
/**
* Bitrix Framework
* @package bitrix
* @subpackage iblock
*/
namespace Bitrix\Iblock\PropertyIndex;
class Storage
{
protected $iblockId = 0;
protected static $exists = array();
const PRICE = 1;
const DICTIONARY = 2;
const STRING = 3;
const NUMERIC = 4;
const DATETIME = 5;
/**
* @param integer $iblockId Information block identifier.
*/
public function __construct($iblockId)
{
$this->iblockId = intval($iblockId);
}
/**
* Returns information block identifier.
*
* @return integer
*/
/**
* <p>Метод возвращает идентификатор инфоблока. Нестатический метод.</p> <p>Без параметров</p> <a name="example"></a>
*
*
* @return integer
*
* @static
* @link http://dev.1c-bitrix.ru/api_d7/bitrix/iblock/propertyindex/storage/getiblockid.php
* @author Bitrix
*/
public function getIblockId()
{
return $this->iblockId;
}
/**
* Internal method to get database table name for storing property index.
*
* @return string
*/
/**
* <p>Метод возвращает название таблицы базы данных для хранения индекса свойств. Нестатический внутренний метод.</p> <p>Без параметров</p> <a name="example"></a>
*
*
* @return string
*
* @static
* @link http://dev.1c-bitrix.ru/api_d7/bitrix/iblock/propertyindex/storage/gettablename.php
* @author Bitrix
*/
public function getTableName()
{
return "b_iblock_".$this->iblockId."_index";
}
/**
* Checks if property index exists in the database.
* Returns true on success.
*
* @return boolean
*/
/**
* <p>Метод проверяет существование в базе данных индекса для свойства. Нестатический метод.</p> <p>Без параметров</p> <a name="example"></a>
*
*
* @return boolean
*
* @static
* @link http://dev.1c-bitrix.ru/api_d7/bitrix/iblock/propertyindex/storage/isexists.php
* @author Bitrix
*/
public function isExists()
{
if (!array_key_exists($this->iblockId, self::$exists))
{
$connection = \Bitrix\Main\Application::getConnection();
self::$exists[$this->iblockId] = $connection->isTableExists($this->getTableName());
}
return self::$exists[$this->iblockId];
}
/**
* Creates new property values index for information block.
* You have to be sure that index does not exists.
*
* @return void
*/
/**
* <p>Метод создает новый индекс значений свойства информационного блока. Перед вызовом метода необходимо убедиться, что такой индекс еще не существует. Нестатический метод.</p> <p>Без параметров</p> <a name="example"></a>
*
*
* @return void
*
* @static
* @link http://dev.1c-bitrix.ru/api_d7/bitrix/iblock/propertyindex/storage/create.php
* @author Bitrix
*/
public function create()
{
$connection = \Bitrix\Main\Application::getConnection();
$connection->createTable($this->getTableName(), array(
"SECTION_ID" => new \Bitrix\Main\Entity\IntegerField("SECTION_ID", array(
'required' => true,
)),
"ELEMENT_ID" => new \Bitrix\Main\Entity\IntegerField("ELEMENT_ID", array(
'required' => true,
)),
"FACET_ID" => new \Bitrix\Main\Entity\IntegerField("FACET_ID", array(
'required' => true,
)),
"VALUE" => new \Bitrix\Main\Entity\IntegerField("VALUE", array(
'required' => true,
)),
"VALUE_NUM" => new \Bitrix\Main\Entity\FloatField("VALUE_NUM", array(
'required' => true,
)),
"INCLUDE_SUBSECTIONS" => new \Bitrix\Main\Entity\BooleanField("INCLUDE_SUBSECTIONS", array(
'required' => true,
'values' => array(0, 1),
)),
), array("SECTION_ID", "FACET_ID", "VALUE", "VALUE_NUM", "ELEMENT_ID"));
$connection->createIndex($this->getTableName(), 'IX_'.$this->getTableName().'_0', array("SECTION_ID", "FACET_ID", "VALUE_NUM", "VALUE", "ELEMENT_ID"));
$connection->createIndex($this->getTableName(), 'IX_'.$this->getTableName().'_1', array("ELEMENT_ID", "SECTION_ID", "FACET_ID"));
self::$exists[$this->iblockId] = true;
}
/**
* Deletes existing index from the database.
* You have to check that index exists before calling this method.
*
* @return void
*/
/**
* <p>Метод удаляет существующий индекс из базы данных. Перед вызовом метода необходимо убедиться в том, что индекс существует. Нестатический метод.</p> <p>Без параметров</p> <a name="example"></a>
*
*
* @return void
*
* @static
* @link http://dev.1c-bitrix.ru/api_d7/bitrix/iblock/propertyindex/storage/drop.php
* @author Bitrix
*/
public function drop()
{
$connection = \Bitrix\Main\Application::getConnection();
$connection->dropTable($this->getTableName());
self::$exists[$this->iblockId] = false;
}
/**
* Returns maximum stored element identifier.
*
* @return int
*/
/**
* <p>Метод возвращает максимальный идентификатор хранящегося элемента. Нестатический метод.</p> <p>Без параметров</p> <a name="example"></a>
*
*
* @return integer
*
* @static
* @link http://dev.1c-bitrix.ru/api_d7/bitrix/iblock/propertyindex/storage/getlaststoredelementid.php
* @author Bitrix
*/
public function getLastStoredElementId()
{
$connection = \Bitrix\Main\Application::getConnection();
$max = $connection->queryScalar("select max(ELEMENT_ID) ELEMENT_MAX from ".$this->getTableName());
return $max > 0? $max: 0;
}
/**
* Adds new index entry.
*
* @param integer $sectionId Identifier of the element section.
* @param integer $elementId Identifier of the element.
* @param integer $facetId Identifier of the property/price.
* @param integer $value Dictionary value or 0.
* @param float $valueNum Value of an numeric property or price.
* @param boolean $includeSubsections If section has parent or direct element connection.
*
* @return boolean
*/
/**
* <p>Метод добавляет новую запись индекса. Нестатический метод.</p>
*
*
* @param integer $sectionId Идентификатор секции элемента.
*
* @param integer $elementId Идентификатор элемента.
*
* @param integer $facetId Идентификатор свойства/цены.
*
* @param integer $value Значение словаря или 0.
*
* @param float $valueNum Значение числового свойства или цены.
*
* @param boolean $includeSubsections Параметр принимает <i>true</i>, если секция имеет родителя, в
* противном случае указывается <i>false</i>.
*
* @return boolean
*
* @static
* @link http://dev.1c-bitrix.ru/api_d7/bitrix/iblock/propertyindex/storage/addindexentry.php
* @author Bitrix
*/
public function addIndexEntry($sectionId, $elementId, $facetId, $value, $valueNum, $includeSubsections)
{
$connection = \Bitrix\Main\Application::getConnection();
try
{
$connection->query("
INSERT INTO ".$this->getTableName()." (
SECTION_ID
,ELEMENT_ID
,FACET_ID
,VALUE
,VALUE_NUM
,INCLUDE_SUBSECTIONS
) VALUES (
".intval($sectionId)."
,".intval($elementId)."
,".intval($facetId)."
,".intval($value)."
,".doubleval($valueNum)."
,".($includeSubsections > 0? 1: 0)."
)
");
}
catch (\Bitrix\Main\DB\SqlException $e)
{
return false;
}
return true;
}
/**
* Deletes all element entries from the index.
*
* @param integer $elementId Identifier of the element to be deleted.
*
* @return boolean
*/
/**
* <p>Метод удаляет все записи для элемента из индекса. Нестатический метод.</p>
*
*
* @param integer $elementId Идентификатор элемента, записи которого необходимо удалить.
*
* @return boolean
*
* @static
* @link http://dev.1c-bitrix.ru/api_d7/bitrix/iblock/propertyindex/storage/deleteindexelement.php
* @author Bitrix
*/
public function deleteIndexElement($elementId)
{
$connection = \Bitrix\Main\Application::getConnection();
$connection->query("DELETE from ".$this->getTableName()." WHERE ELEMENT_ID = ".intval($elementId));
return true;
}
/**
* Converts iblock property identifier into internal storage facet identifier.
*
* @param integer $propertyId Property identifier.
* @return integer
*/
/**
* <p>Метод преобразует идентификатор свойства инфоблока во внутренний идентификатор фасеты. Метод статический.</p>
*
*
* @param integer $propertyId Идентификатор свойства инфоблока.
*
* @return integer
*
* @static
* @link http://dev.1c-bitrix.ru/api_d7/bitrix/iblock/propertyindex/storage/propertyidtofacetid.php
* @author Bitrix
*/
public static function propertyIdToFacetId($propertyId)
{
return intval($propertyId * 2);
}
/**
* Converts catalog price identifier into internal storage facet identifier.
*
* @param integer $priceId Price identifier.
* @return integer
*/
/**
* <p>Метод преобразует идентификатор цены во внутренний идентификатор фасеты. Метод статический.</p>
*
*
* @param integer $priceId Идентификатор цены.
*
* @return integer
*
* @static
* @link http://dev.1c-bitrix.ru/api_d7/bitrix/iblock/propertyindex/storage/priceidtofacetid.php
* @author Bitrix
*/
public static function priceIdToFacetId($priceId)
{
return intval($priceId * 2 + 1);
}
/**
* Returns true if given identifier is catalog price one.
*
* @param integer $facetId Internal storage facet identifier.
*
* @return boolean
*/
/**
* <p>Метод возвращает <i>true</i>, если заданный идентификатор является идентификатором цены каталога. Метод статический.</p>
*
*
* @param integer $facetId Внутренний идентификатор фасеты.
*
* @return boolean
*
* @static
* @link http://dev.1c-bitrix.ru/api_d7/bitrix/iblock/propertyindex/storage/ispriceid.php
* @author Bitrix
*/
public static function isPriceId($facetId)
{
return ($facetId % 2) != 0;
}
/**
* Returns true if given identifier is iblock property one.
*
* @param integer $facetId Internal storage facet identifier.
*
* @return boolean
*/
/**
* <p>Метод возвращает <i>true</i>, если заданный идентификатор является идентификатором свойства инфоблока. Метод статический.</p>
*
*
* @param integer $facetId Внутренний идентификатор фасеты.
*
* @return boolean
*
* @static
* @link http://dev.1c-bitrix.ru/api_d7/bitrix/iblock/propertyindex/storage/ispropertyid.php
* @author Bitrix
*/
public static function isPropertyId($facetId)
{
return ($facetId % 2) == 0;
}
/**
* Converts internal storage facet identifier into iblock property identifier.
*
* @param integer $facetId Internal storage facet identifier.
*
* @return integer
*/
/**
* <p>Метод преобразует внутренний идентификатор фасеты в идентификатор свойства инфоблока. Метод статический.</p>
*
*
* @param integer $facetId Внутренний идентификатор фасеты.
*
* @return integer
*
* @static
* @link http://dev.1c-bitrix.ru/api_d7/bitrix/iblock/propertyindex/storage/facetidtopropertyid.php
* @author Bitrix
*/
public static function facetIdToPropertyId($facetId)
{
return intval($facetId / 2);
}
/**
* Converts internal storage facet identifier into catalog price identifier.
*
* @param integer $facetId Internal storage facet identifier.
*
* @return integer
*/
/**
* <p>Метод преобразует внутренний идентификатор фасеты в идентификатор цены каталога. Метод статический.</p>
*
*
* @param integer $facetId Внутренний идентификатор фасеты.
*
* @return integer
*
* @static
* @link http://dev.1c-bitrix.ru/api_d7/bitrix/iblock/propertyindex/storage/facetidtopriceid.php
* @author Bitrix
*/
public static function facetIdToPriceId($facetId)
{
return intval(($facetId - 1) / 2);
}
}
| {
"pile_set_name": "Github"
} |
/**
* Copyright (C) 2001-2020 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.visualization;
import com.rapidminer.example.Attribute;
import com.rapidminer.example.ExampleSet;
import com.rapidminer.operator.Operator;
import com.rapidminer.operator.OperatorDescription;
import com.rapidminer.operator.OperatorException;
import com.rapidminer.operator.ports.InputPort;
import com.rapidminer.operator.ports.OutputPort;
import com.rapidminer.operator.ports.metadata.GenerateNewMDRule;
import java.util.Iterator;
/**
* This operators calculates some very simple statistics about the given example set. These are the
* ranges of the attributes and the average or mode values for numerical or nominal attributes
* respectively. These informations are automatically calculated and displayed by the graphical user
* interface of RapidMiner. Since they cannot be displayed with the command line version of
* RapidMiner this operator can be used as a workaround in cases where the graphical user interface
* cannot be used.
*
* @author Ingo Mierswa ingomierswa Exp $
*/
public class DataStatisticsOperator extends Operator {
private InputPort exampleSetInput = getInputPorts().createPort("example set");
private OutputPort statisticsOutput = getOutputPorts().createPort("statistics");
private OutputPort exampleSetOutput = getOutputPorts().createPort("example set");
/** Creates a new data statistics operator. */
public DataStatisticsOperator(OperatorDescription description) {
super(description);
getTransformer().addPassThroughRule(exampleSetInput, exampleSetOutput);
getTransformer().addRule(new GenerateNewMDRule(statisticsOutput, DataStatistics.class));
}
/** Creates and delivers the simple statistics object. */
@Override
public void doWork() throws OperatorException {
ExampleSet eSet = exampleSetInput.getData(ExampleSet.class);
eSet.recalculateAllAttributeStatistics();
DataStatistics statistics = new DataStatistics();
Iterator<Attribute> i = eSet.getAttributes().allAttributes();
while (i.hasNext()) {
statistics.addInfo(eSet, i.next());
}
exampleSetOutput.deliver(eSet);
statisticsOutput.deliver(statistics);
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2003-2012 Apple Inc. All rights reserved.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. The rights granted to you under the License
* may not be used to create, or enable the creation or redistribution of,
* unlawful or unlicensed copies of an Apple operating system, or to
* circumvent, violate, or enable the circumvention or violation of, any
* terms of an Apple operating system software license agreement.
*
* Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_END@
*/
#ifndef _GID_T
#define _GID_T
typedef __darwin_gid_t gid_t;
#endif
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
<property name="hibernate.connection.password">111111</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/jshoper</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
</session-factory>
</hibernate-configuration>
| {
"pile_set_name": "Github"
} |
// Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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 NCNN_MODELBIN_H
#define NCNN_MODELBIN_H
#include "mat.h"
namespace ncnn {
class DataReader;
class ModelBin
{
public:
virtual ~ModelBin();
// element type
// 0 = auto
// 1 = float32
// 2 = float16
// 3 = int8
// load vec
virtual Mat load(int w, int type) const = 0;
// load image
virtual Mat load(int w, int h, int type) const;
// load dim
virtual Mat load(int w, int h, int c, int type) const;
};
class ModelBinFromDataReader : public ModelBin
{
public:
ModelBinFromDataReader(const DataReader& dr);
virtual Mat load(int w, int type) const;
protected:
const DataReader& dr;
};
class ModelBinFromMatArray : public ModelBin
{
public:
// construct from weight blob array
ModelBinFromMatArray(const Mat* weights);
virtual Mat load(int w, int type) const;
protected:
mutable const Mat* weights;
};
} // namespace ncnn
#endif // NCNN_MODELBIN_H
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<!--
* t
****************************************************************************
* Copyright (c) 1998-2006,2010 Free Software Foundation, Inc. *
* *
* 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, distribute with modifications, 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 ABOVE 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. *
* *
* Except as contained in this notice, the name(s) of the above copyright *
* holders shall not be used in advertising or otherwise to promote the *
* sale, use or other dealings in this Software without prior written *
* authorization. *
****************************************************************************
* @Id: form_page.3x,v 1.12 2010/12/04 18:40:45 tom Exp @
-->
<HTML>
<HEAD>
<TITLE>form_page 3x</TITLE>
<link rev=made href="mailto:[email protected]">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</HEAD>
<BODY>
<H1>form_page 3x</H1>
<HR>
<PRE>
<!-- Manpage converted by man2html 3.0.1 -->
<STRONG><A HREF="form_page.3x.html">form_page(3x)</A></STRONG> <STRONG><A HREF="form_page.3x.html">form_page(3x)</A></STRONG>
</PRE>
<H2>NAME</H2><PRE>
<STRONG>form_page</STRONG> - set and get form page number
</PRE>
<H2>SYNOPSIS</H2><PRE>
<STRONG>#include</STRONG> <STRONG><form.h></STRONG>
int set_current_field(FORM *form, FIELD *field);
FIELD *current_field(const FORM *);
int set_form_page(FORM *form, int n);
int form_page(const FORM *form);
int field_index(const FIELD *field);
</PRE>
<H2>DESCRIPTION</H2><PRE>
The function <STRONG>set_current</STRONG> <STRONG>field</STRONG> sets the current field of
the given form; <STRONG>current_field</STRONG> returns the current field of
the given form.
The function <STRONG>set_form_page</STRONG> sets the form's page number
(goes to page <EM>n</EM> of the form).
The function <STRONG>form_page</STRONG> returns the form's current page
number.
The function <STRONG>field_index</STRONG> returns the index of the field in
the field array of the form it is connected to. It returns
<STRONG>ERR</STRONG> if the argument is the null pointer or the field is
not connected.
</PRE>
<H2>RETURN VALUE</H2><PRE>
Except for <STRONG>form_page</STRONG>, each routine returns one of the fol-
lowing:
<STRONG>E_OK</STRONG> The routine succeeded.
<STRONG>E_BAD_ARGUMENT</STRONG>
Routine detected an incorrect or out-of-range argu-
ment.
<STRONG>E_BAD_STATE</STRONG>
Routine was called from an initialization or termina-
tion function.
<STRONG>E_INVALID_FIELD</STRONG>
Contents of a field are not valid.
<STRONG>E_REQUEST_DENIED</STRONG>
The form driver could not process the request.
<STRONG>E_SYSTEM_ERROR</STRONG>
System error occurred (see <STRONG>errno</STRONG>).
</PRE>
<H2>SEE ALSO</H2><PRE>
<STRONG><A HREF="ncurses.3x.html">curses(3x)</A></STRONG>, <STRONG><A HREF="form.3x.html">form(3x)</A></STRONG>.
</PRE>
<H2>NOTES</H2><PRE>
The header file <STRONG><form.h></STRONG> automatically includes the header
file <STRONG><curses.h></STRONG>.
</PRE>
<H2>PORTABILITY</H2><PRE>
These routines emulate the System V forms library. They
were not supported on Version 7 or BSD versions.
</PRE>
<H2>AUTHORS</H2><PRE>
Juergen Pfeifer. Manual pages and adaptation for new
curses by Eric S. Raymond.
<STRONG><A HREF="form_page.3x.html">form_page(3x)</A></STRONG>
</PRE>
<HR>
<ADDRESS>
Man(1) output converted with
<a href="http://www.oac.uci.edu/indiv/ehood/man2html.html">man2html</a>
</ADDRESS>
</BODY>
</HTML>
| {
"pile_set_name": "Github"
} |
(ns musical-creativity.pretty
(:require [quil.core :refer :all]))
(def cells (atom ["0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "*" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0"]))
(defn setup []
(smooth)
(frame-rate 50)
(background 200))
(defn draw []
(stroke 255)
(stroke-weight 2)
(doall
(map (fn [[cell index]]
(let [c (if (= cell "*") 0 255)
diam 15
x (* (inc index) 21)
y 20]
(fill c)
(ellipse x y diam diam)))
(map vector @cells (range)))))
(defsketch pretty-music
:title "Cellullar Automata"
:setup setup
:draw draw
:size [580 50])
| {
"pile_set_name": "Github"
} |
@mixin gz-make-unit ($width: 100%) {
// Required for offset/push/pull
position: relative;
// By default, all columns should be 100% wide (mobile-first).
@include gz-unit-width($width);
// border-box forces the browser to include padding and borders when calculating the width.
box-sizing: border-box;
}
@mixin gz-unit-width ($count, $total: null) {
$value: gz-percentage($count, $total);
flex: 0 0 $value;
width: $value;
}
@mixin gz-unit-push ($count, $total: null) {
$value: gz-percentage($count, $total);
left: $value;
}
@mixin gz-unit-pull ($count, $total: null) {
$value: gz-percentage($count, $total);
left: -$value;
}
@mixin gz-unit-offset ($count, $total: null) {
$value: gz-percentage($count, $total);
margin-left: $value;
}
@mixin gz-unit-equal-width {
flex: 1 1 0%;
width: auto;
}
@mixin gz-unit-first {
order: -1;
}
@mixin gz-unit-last {
order: 9999;
}
@mixin gz-unit-fit-content {
flex: none;
width: auto;
}
@mixin gz-unit-vertical-align ($align) {
$map: (
top : flex-start,
middle : center,
bottom : flex-end,
);
align-self: map-get($map, $align);
}
@mixin gz-unit-stretch {
align-self: stretch;
}
| {
"pile_set_name": "Github"
} |
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-alpha.6): button.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Button = function ($) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'button';
var VERSION = '4.0.0-alpha.6';
var DATA_KEY = 'bs.button';
var EVENT_KEY = '.' + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var ClassName = {
ACTIVE: 'active',
BUTTON: 'btn',
FOCUS: 'focus'
};
var Selector = {
DATA_TOGGLE_CARROT: '[data-toggle^="button"]',
DATA_TOGGLE: '[data-toggle="buttons"]',
INPUT: 'input',
ACTIVE: '.active',
BUTTON: '.btn'
};
var Event = {
CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY,
FOCUS_BLUR_DATA_API: 'focus' + EVENT_KEY + DATA_API_KEY + ' ' + ('blur' + EVENT_KEY + DATA_API_KEY)
};
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
var Button = function () {
function Button(element) {
_classCallCheck(this, Button);
this._element = element;
}
// getters
// public
Button.prototype.toggle = function toggle() {
var triggerChangeEvent = true;
var rootElement = $(this._element).closest(Selector.DATA_TOGGLE)[0];
if (rootElement) {
var input = $(this._element).find(Selector.INPUT)[0];
if (input) {
if (input.type === 'radio') {
if (input.checked && $(this._element).hasClass(ClassName.ACTIVE)) {
triggerChangeEvent = false;
} else {
var activeElement = $(rootElement).find(Selector.ACTIVE)[0];
if (activeElement) {
$(activeElement).removeClass(ClassName.ACTIVE);
}
}
}
if (triggerChangeEvent) {
input.checked = !$(this._element).hasClass(ClassName.ACTIVE);
$(input).trigger('change');
}
input.focus();
}
}
this._element.setAttribute('aria-pressed', !$(this._element).hasClass(ClassName.ACTIVE));
if (triggerChangeEvent) {
$(this._element).toggleClass(ClassName.ACTIVE);
}
};
Button.prototype.dispose = function dispose() {
$.removeData(this._element, DATA_KEY);
this._element = null;
};
// static
Button._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var data = $(this).data(DATA_KEY);
if (!data) {
data = new Button(this);
$(this).data(DATA_KEY, data);
}
if (config === 'toggle') {
data[config]();
}
});
};
_createClass(Button, null, [{
key: 'VERSION',
get: function get() {
return VERSION;
}
}]);
return Button;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$(document).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE_CARROT, function (event) {
event.preventDefault();
var button = event.target;
if (!$(button).hasClass(ClassName.BUTTON)) {
button = $(button).closest(Selector.BUTTON);
}
Button._jQueryInterface.call($(button), 'toggle');
}).on(Event.FOCUS_BLUR_DATA_API, Selector.DATA_TOGGLE_CARROT, function (event) {
var button = $(event.target).closest(Selector.BUTTON)[0];
$(button).toggleClass(ClassName.FOCUS, /^focus(in)?$/.test(event.type));
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Button._jQueryInterface;
$.fn[NAME].Constructor = Button;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Button._jQueryInterface;
};
return Button;
}(jQuery);
//# sourceMappingURL=button.js.map
| {
"pile_set_name": "Github"
} |
#!/bin/bash
set -e
set -u
set -o pipefail
train_set="train_reduced"
valid_set="dev5"
test_sets="dev5 test_set_iwslt2019"
asr_config=conf/train_asr_rnn.yaml
inference_config=conf/decode.yaml
feats_type=extracted
token_type=bpe
nlsyms=data/nlsyms
nbpe=1000
bpe_nlsyms="[hes]"
use_lm=false
./asr.sh \
--lang en \
--feats_type ${feats_type} \
--token_type ${token_type} \
--nbpe ${nbpe} \
--nlsyms_txt ${nlsyms} \
--bpe_nlsyms ${bpe_nlsyms} \
--use_lm ${use_lm} \
--asr_config "${asr_config}" \
--inference_config "${inference_config}" \
--train_set "${train_set}" \
--valid_set "${valid_set}" \
--test_sets "${test_sets}" \
--srctexts "data/${train_set}/text" "$@"
| {
"pile_set_name": "Github"
} |
import holodeck
import numpy as np
from tests.utils.equality import almost_equal
import uuid
base_cfg = {
"name": "test_rotation_sensor",
"world": "TestWorld",
"main_agent": "sphere0",
"agents": [
{
"agent_name": "sphere0",
"agent_type": "SphereAgent",
"sensors": [
{
"sensor_type": "RotationSensor",
}
],
"control_scheme": 0,
"location": [.95, -1.75, .5]
}
]
}
def test_rotation_sensor_after_teleport():
"""Make sure that the rotation sensor correctly updates after using a teleport command to
rotate the agent
"""
binary_path = holodeck.packagemanager.get_binary_path_for_package("DefaultWorlds")
with holodeck.environments.HolodeckEnvironment(scenario=base_cfg,
binary_path=binary_path,
show_viewport=False,
uuid=str(uuid.uuid4())) as env:
for _ in range(10):
env.tick()
loc = [123, 3740, 1030]
rot_deg = np.array([0, 90, 0])
env.agents['sphere0'].teleport(loc, rot_deg)
rotation = env.tick()["RotationSensor"]
assert almost_equal(rot_deg, rotation), "The agent rotated in an unexpected manner!"
| {
"pile_set_name": "Github"
} |
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// +k8s:deepcopy-gen=package
// +k8s:openapi-gen=true
// +groupName=certificates.k8s.io
package v1beta1 // import "k8s.io/api/certificates/v1beta1"
| {
"pile_set_name": "Github"
} |
//******************************************************************************
// SCICHART® Copyright SciChart Ltd. 2011-2019. All rights reserved.
//
// Web: http://www.scichart.com
// Support: [email protected]
// Sales: [email protected]
//
// LegendChartView.swift is part of the SCICHART® Examples. Permission is hereby granted
// to modify, create derivative works, distribute and publish any part of this source
// code whether for commercial, private or personal use.
//
// The SCICHART® examples are distributed in the hope that they will be useful, but
// without any warranty. It is provided "AS IS" without warranty of any kind, either
// expressed or implied.
//******************************************************************************
import SciChart.Protected.SCIStyleBase
class CustomSeriesStyle: SCIStyleBase<ISCIRenderableSeries> {
let Stroke = "Stroke"
init() {
super.init(styleableType: SCIRenderableSeriesBase.self)
}
override func applyStyleInternal(to styleableObject: ISCIRenderableSeries!) {
let currentPenStyle = styleableObject.strokeStyle
putProperty(Stroke, value: currentPenStyle, intoObject: styleableObject)
styleableObject.strokeStyle = SCISolidPenStyle(color: currentPenStyle!.color, thickness: 4)
}
override func discardStyleInternal(from styleableObject: ISCIRenderableSeries!) {
let penStyle = getValueFromProperty(Stroke, ofType: SCISolidPenStyle.self, fromObject: styleableObject)
styleableObject.strokeStyle = penStyle as? SCIPenStyle
}
}
class LegendChartView: SCDLegendChartViewControllerBase {
override func initExample() {
let xAxis = SCINumericAxis()
let yAxis = SCINumericAxis()
let dataSeries1 = SCIXyDataSeries(xType: .double, yType: .double)
dataSeries1.seriesName = "Curve A"
let dataSeries2 = SCIXyDataSeries(xType: .double, yType: .double)
dataSeries2.seriesName = "Curve B"
let dataSeries3 = SCIXyDataSeries(xType: .double, yType: .double)
dataSeries3.seriesName = "Curve C"
let dataSeries4 = SCIXyDataSeries(xType: .double, yType: .double)
dataSeries4.seriesName = "Curve D"
let SCDDoubleSeries1 = SCDDataManager.getStraightLines(withGradient: 4000, yIntercept: 1.0, pointCount: 10)
let SCDDoubleSeries2 = SCDDataManager.getStraightLines(withGradient: 3000, yIntercept: 1.0, pointCount: 10)
let SCDDoubleSeries3 = SCDDataManager.getStraightLines(withGradient: 2000, yIntercept: 1.0, pointCount: 10)
let SCDDoubleSeries4 = SCDDataManager.getStraightLines(withGradient: 1000, yIntercept: 1.0, pointCount: 10)
dataSeries1.append(x: SCDDoubleSeries1.xValues, y: SCDDoubleSeries1.yValues)
dataSeries2.append(x: SCDDoubleSeries2.xValues, y: SCDDoubleSeries2.yValues)
dataSeries3.append(x: SCDDoubleSeries3.xValues, y: SCDDoubleSeries3.yValues)
dataSeries4.append(x: SCDDoubleSeries4.xValues, y: SCDDoubleSeries4.yValues)
let line1 = SCIFastLineRenderableSeries()
line1.strokeStyle = SCISolidPenStyle(colorCode: 0xFFFFFF00, thickness: 1)
line1.dataSeries = dataSeries1
let line2 = SCIFastLineRenderableSeries()
line2.strokeStyle = SCISolidPenStyle(colorCode: 0xFF279B27, thickness: 1)
line2.dataSeries = dataSeries2
let line3 = SCIFastLineRenderableSeries()
line3.strokeStyle = SCISolidPenStyle(colorCode: 0xFFFF1919, thickness: 1)
line3.dataSeries = dataSeries3
let line4 = SCIFastLineRenderableSeries()
line3.strokeStyle = SCISolidPenStyle(colorCode: 0xFF1964FF, thickness: 1)
line4.dataSeries = dataSeries4
line4.isVisible = false
legendModifier = SCILegendModifier()
legendModifier.position = [.left, .top]
legendModifier.margins = SCIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
let seriesSelectionModifier = SCISeriesSelectionModifier()
seriesSelectionModifier.selectedSeriesStyle = CustomSeriesStyle()
legendModifier.orientation = orientation;
legendModifier.showLegend = showLegend;
legendModifier.showCheckBoxes = showCheckBoxes;
legendModifier.showSeriesMarkers = showSeriesMarkers;
legendModifier.sourceMode = sourceMode;
SCIUpdateSuspender.usingWith(surface) {
self.surface.xAxes.add(xAxis)
self.surface.yAxes.add(yAxis)
self.surface.renderableSeries.add(line1)
self.surface.renderableSeries.add(line2)
self.surface.renderableSeries.add(line3)
self.surface.renderableSeries.add(line4)
self.surface.chartModifiers.add(self.legendModifier)
self.surface.chartModifiers.add(seriesSelectionModifier)
SCIAnimations.sweep(line1, duration: 3.0, easingFunction: SCICubicEase())
SCIAnimations.sweep(line2, duration: 3.0, easingFunction: SCICubicEase())
SCIAnimations.sweep(line3, duration: 3.0, easingFunction: SCICubicEase())
SCIAnimations.sweep(line4, duration: 3.0, easingFunction: SCICubicEase())
}
}
}
| {
"pile_set_name": "Github"
} |
let _ =
Foo.func 1 2
let () =
let _ = Foo.func 2 3 in
()
| {
"pile_set_name": "Github"
} |
---
title: “TryCast”操作数必须是引用类型,但“<typename>”是值类型
ms.date: 07/20/2015
f1_keywords:
- BC30792
- vbc30792
helpviewer_keywords:
- BC30792
ms.assetid: 3325fce5-dbc0-4d1d-9530-31f4720bfe6e
ms.openlocfilehash: 66ffa48a4828d980aefe7e1ede4d5c84ac78f5f5
ms.sourcegitcommit: bf5c5850654187705bc94cc40ebfb62fe346ab02
ms.translationtype: MT
ms.contentlocale: zh-CN
ms.lasthandoff: 09/23/2020
ms.locfileid: "91063677"
---
# <a name="trycast-operand-must-be-reference-type-but-typename-is-a-value-type"></a>“TryCast”操作数必须是引用类型,但“\<typename>”是值类型
`TryCast` 运算符被用于至少一个参数的值类型。
`TryCast` 检测两个参数之间的继承关系或实现关系。 因此,它只能用于参数的引用类型。 有关详细信息,请参阅 [值类型和引用类型](../programming-guide/language-features/data-types/value-types-and-reference-types.md)。
**错误 ID:** BC30792
## <a name="to-correct-this-error"></a>更正此错误
- 使用 `DirectCast` 或 `CType` 执行转换。 它们都可用于值类型。
## <a name="see-also"></a>请参阅
- [TryCast 运算符](../language-reference/operators/trycast-operator.md)
- [DirectCast 运算符](../language-reference/operators/directcast-operator.md)
- [CType Function](../language-reference/functions/ctype-function.md)
- [Value Types and Reference Types](../programming-guide/language-features/data-types/value-types-and-reference-types.md)
| {
"pile_set_name": "Github"
} |
// RUN: %clang_cc1 %s -E -verify -fms-extensions
// expected-no-diagnostics
#pragma clang diagnostic ignored "-Wkeyword-macro"
bool f() {
// Check that operators still work before redefining them.
#if compl 0 bitand 1
return true and false;
#endif
}
#ifdef and
#endif
// The second 'and' is a valid C++ operator name for '&&'.
#if defined and and defined(and)
#endif
// All c++ keywords should be #define-able in ms mode.
// (operators like "and" aren't normally, the rest always is.)
#define and
#define and_eq
#define alignas
#define alignof
#define asm
#define auto
#define bitand
#define bitor
#define bool
#define break
#define case
#define catch
#define char
#define char16_t
#define char32_t
#define class
#define compl
#define const
#define constexpr
#define const_cast
#define continue
#define decltype
#define default
#define delete
#define double
#define dynamic_cast
#define else
#define enum
#define explicit
#define export
#define extern
#define false
#define float
#define for
#define friend
#define goto
#define if
#define inline
#define int
#define long
#define mutable
#define namespace
#define new
#define noexcept
#define not
#define not_eq
#define nullptr
#define operator
#define or
#define or_eq
#define private
#define protected
#define public
#define register
#define reinterpret_cast
#define return
#define short
#define signed
#define sizeof
#define static
#define static_assert
#define static_cast
#define struct
#define switch
#define template
#define this
#define thread_local
#define throw
#define true
#define try
#define typedef
#define typeid
#define typename
#define union
#define unsigned
#define using
#define virtual
#define void
#define volatile
#define wchar_t
#define while
#define xor
#define xor_eq
// Check this is all properly defined away.
and
and_eq
alignas
alignof
asm
auto
bitand
bitor
bool
break
case
catch
char
char16_t
char32_t
class
compl
const
constexpr
const_cast
continue
decltype
default
delete
double
dynamic_cast
else
enum
explicit
export
extern
false
float
for
friend
goto
if
inline
int
long
mutable
namespace
new
noexcept
not
not_eq
nullptr
operator
or
or_eq
private
protected
public
register
reinterpret_cast
return
short
signed
sizeof
static
static_assert
static_cast
struct
switch
template
this
thread_local
throw
true
try
typedef
typeid
typename
union
unsigned
using
virtual
void
volatile
wchar_t
while
xor
xor_eq
| {
"pile_set_name": "Github"
} |
{
"nome": "Corio",
"codice": "001094",
"zona": {
"codice": "1",
"nome": "Nord-ovest"
},
"regione": {
"codice": "01",
"nome": "Piemonte"
},
"provincia": {
"codice": "001",
"nome": "Torino"
},
"sigla": "TO",
"codiceCatastale": "D008",
"cap": [
"10070"
],
"popolazione": 3330
}
| {
"pile_set_name": "Github"
} |
#include <vector>
#include "gtest/gtest.h"
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/filler.hpp"
#include "caffe/layers/tile_layer.hpp"
#include "caffe/test/test_caffe_main.hpp"
#include "caffe/test/test_gradient_check_util.hpp"
namespace caffe {
template <typename TypeParam>
class TileLayerTest : public MultiDeviceTest<TypeParam> {
typedef typename TypeParam::Dtype Dtype;
protected:
TileLayerTest()
: blob_bottom_(new Blob<Dtype>(2, 3, 4, 5)),
blob_top_(new Blob<Dtype>()) {}
virtual void SetUp() {
blob_bottom_vec_.push_back(blob_bottom_);
blob_top_vec_.push_back(blob_top_);
FillerParameter filler_param;
filler_param.set_mean(0.0);
filler_param.set_std(1.0);
GaussianFiller<Dtype> filler(filler_param);
filler.Fill(blob_bottom_);
}
virtual ~TileLayerTest() {
delete blob_bottom_;
delete blob_top_;
}
Blob<Dtype>* const blob_bottom_;
Blob<Dtype>* const blob_top_;
vector<Blob<Dtype>*> blob_bottom_vec_;
vector<Blob<Dtype>*> blob_top_vec_;
};
TYPED_TEST_CASE(TileLayerTest, TestDtypesAndDevices);
TYPED_TEST(TileLayerTest, TestTrivialSetup) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
const int kNumTiles = 1;
layer_param.mutable_tile_param()->set_tiles(kNumTiles);
for (int i = 0; i < this->blob_bottom_->num_axes(); ++i) {
layer_param.mutable_tile_param()->set_axis(i);
TileLayer<Dtype> layer(layer_param);
layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
ASSERT_EQ(this->blob_top_->num_axes(), this->blob_bottom_->num_axes());
for (int j = 0; j < this->blob_bottom_->num_axes(); ++j) {
EXPECT_EQ(this->blob_top_->shape(j), this->blob_bottom_->shape(j));
}
}
}
TYPED_TEST(TileLayerTest, TestSetup) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
const int kNumTiles = 3;
layer_param.mutable_tile_param()->set_tiles(kNumTiles);
for (int i = 0; i < this->blob_bottom_->num_axes(); ++i) {
layer_param.mutable_tile_param()->set_axis(i);
TileLayer<Dtype> layer(layer_param);
layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
ASSERT_EQ(this->blob_top_->num_axes(), this->blob_bottom_->num_axes());
for (int j = 0; j < this->blob_bottom_->num_axes(); ++j) {
const int top_dim =
((i == j) ? kNumTiles : 1) * this->blob_bottom_->shape(j);
EXPECT_EQ(top_dim, this->blob_top_->shape(j));
}
}
}
TYPED_TEST(TileLayerTest, TestForwardNum) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
const int kTileAxis = 0;
const int kNumTiles = 3;
layer_param.mutable_tile_param()->set_axis(kTileAxis);
layer_param.mutable_tile_param()->set_tiles(kNumTiles);
TileLayer<Dtype> layer(layer_param);
layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_);
for (int n = 0; n < this->blob_top_->num(); ++n) {
for (int c = 0; c < this->blob_top_->channels(); ++c) {
for (int h = 0; h < this->blob_top_->height(); ++h) {
for (int w = 0; w < this->blob_top_->width(); ++w) {
const int bottom_n = n % this->blob_bottom_->num();
EXPECT_EQ(this->blob_bottom_->data_at(bottom_n, c, h, w),
this->blob_top_->data_at(n, c, h, w));
}
}
}
}
}
TYPED_TEST(TileLayerTest, TestForwardChannels) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
const int kNumTiles = 3;
layer_param.mutable_tile_param()->set_tiles(kNumTiles);
TileLayer<Dtype> layer(layer_param);
layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_);
for (int n = 0; n < this->blob_top_->num(); ++n) {
for (int c = 0; c < this->blob_top_->channels(); ++c) {
for (int h = 0; h < this->blob_top_->height(); ++h) {
for (int w = 0; w < this->blob_top_->width(); ++w) {
const int bottom_c = c % this->blob_bottom_->channels();
EXPECT_EQ(this->blob_bottom_->data_at(n, bottom_c, h, w),
this->blob_top_->data_at(n, c, h, w));
}
}
}
}
}
TYPED_TEST(TileLayerTest, TestTrivialGradient) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
const int kNumTiles = 1;
layer_param.mutable_tile_param()->set_tiles(kNumTiles);
TileLayer<Dtype> layer(layer_param);
GradientChecker<Dtype> checker(1e-2, 1e-2);
checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_,
this->blob_top_vec_);
}
TYPED_TEST(TileLayerTest, TestGradientNum) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
const int kTileAxis = 0;
const int kNumTiles = 3;
layer_param.mutable_tile_param()->set_axis(kTileAxis);
layer_param.mutable_tile_param()->set_tiles(kNumTiles);
TileLayer<Dtype> layer(layer_param);
GradientChecker<Dtype> checker(1e-2, 1e-2);
checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_,
this->blob_top_vec_);
}
TYPED_TEST(TileLayerTest, TestGradientChannels) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
const int kTileAxis = 1;
const int kNumTiles = 3;
layer_param.mutable_tile_param()->set_axis(kTileAxis);
layer_param.mutable_tile_param()->set_tiles(kNumTiles);
TileLayer<Dtype> layer(layer_param);
GradientChecker<Dtype> checker(1e-2, 1e-2);
checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_,
this->blob_top_vec_);
}
} // namespace caffe
| {
"pile_set_name": "Github"
} |
using System;
using Pathoschild.Stardew.Common;
using StardewValley;
namespace Pathoschild.Stardew.Automate
{
/// <summary>An item stack which notifies callbacks when it's reduced.</summary>
public class TrackedItem : ITrackedStack
{
/*********
** Fields
*********/
/// <summary>The item stack.</summary>
private readonly Item Item;
/// <summary>The callback invoked when the stack size is reduced (including reduced to zero).</summary>
protected readonly Action<Item> OnReduced;
/// <summary>The callback invoked when the stack is empty.</summary>
protected readonly Action<Item> OnEmpty;
/// <summary>The last stack size handlers were notified of.</summary>
private int LastCount;
/*********
** Accessors
*********/
/// <summary>A sample item for comparison.</summary>
/// <remarks>This should be equivalent to the underlying item (except in stack size), but *not* a reference to it.</remarks>
public Item Sample { get; }
/// <summary>The underlying item type.</summary>
public ItemType Type { get; }
/// <summary>The number of items in the stack.</summary>
public int Count { get; private set; }
/*********
** Public methods
*********/
/// <summary>Construct an instance.</summary>
/// <param name="item">The item stack.</param>
/// <param name="onReduced">The callback invoked when the stack size is reduced (including reduced to zero).</param>
/// <param name="onEmpty">The callback invoked when the stack is empty.</param>
public TrackedItem(Item item, Action<Item> onReduced = null, Action<Item> onEmpty = null)
{
this.Item = item ?? throw new InvalidOperationException("Can't track a null item stack.");
this.Type = (ItemType)item.GetItemType();
this.Sample = this.GetNewStack(item);
this.OnReduced = onReduced;
this.OnEmpty = onEmpty;
this.Count = item.Stack; // we can't trust Item.Stack to reduce correctly (e.g. Hat.Stack always return 1), so we need to track it ourselves
this.LastCount = this.Count;
}
/// <summary>Remove the specified number of this item from the stack.</summary>
/// <param name="count">The number to consume.</param>
public void Reduce(int count)
{
if (count <= 0)
return;
this.Item.Stack -= count;
this.Count -= count;
this.Delegate();
}
/// <summary>Remove the specified number of this item from the stack and return a new stack matching the count.</summary>
/// <param name="count">The number to get.</param>
public Item Take(int count)
{
if (count <= 0)
return null;
this.Reduce(count);
return this.GetNewStack(this.Item, count);
}
/*********
** Private methods
*********/
/// <summary>Notify handlers.</summary>
private void Delegate()
{
// skip if not reduced
if (this.Count >= this.LastCount)
return;
this.LastCount = this.Count;
// notify handlers
this.OnReduced?.Invoke(this.Item);
if (this.Count <= 0)
this.OnEmpty?.Invoke(this.Item);
}
/// <summary>Create a new stack of the given item.</summary>
/// <param name="original">The item stack to clone.</param>
/// <param name="stackSize">The new stack size.</param>
private Item GetNewStack(Item original, int stackSize = 1)
{
if (original == null)
return null;
Item stack = original.getOne();
stack.Stack = stackSize;
return stack;
}
}
}
| {
"pile_set_name": "Github"
} |
Submitted By: Douglas R. Reno <renodr at linuxfromscratch dot org>
Date: 2019-04-09
Initial Package Version: 2.60.1
Upstream Status: Committed
Origin: Upstream
Description: Adapts glib-networking to API changes in GnuTLS-3.6.7,
which broke TLS/SSL support due to a new error
declaration being added that was unexpected.
diff -Naurp glib-networking-2.60.1.orig/tls/gnutls/gtlsconnection-gnutls.c glib-networking-2.60.1/tls/gnutls/gtlsconnection-gnutls.c
--- glib-networking-2.60.1.orig/tls/gnutls/gtlsconnection-gnutls.c 2019-04-01 21:55:21.000000000 -0500
+++ glib-networking-2.60.1/tls/gnutls/gtlsconnection-gnutls.c 2019-04-09 22:30:32.253268948 -0500
@@ -1062,7 +1062,11 @@ end_gnutls_io (GTlsConnectionGnutls *gn
else
return 0;
}
- else if (status == GNUTLS_E_NO_CERTIFICATE_FOUND)
+ else if (status == GNUTLS_E_NO_CERTIFICATE_FOUND
+#ifdef GNUTLS_E_CERTIFICATE_REQUIRED
+ || status == GNUTLS_E_CERTIFICATE_REQUIRED /* Added in GnuTLS 3.6.7 */
+#endif
+ )
{
g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_CERTIFICATE_REQUIRED,
_("TLS connection peer did not send a certificate"));
diff -Naurp glib-networking-2.60.1.orig/tls/tests/connection.c glib-networking-2.60.1/tls/tests/connection.c
--- glib-networking-2.60.1.orig/tls/tests/connection.c 2019-04-01 21:55:21.000000000 -0500
+++ glib-networking-2.60.1/tls/tests/connection.c 2019-04-09 22:28:11.339078304 -0500
@@ -1685,17 +1685,6 @@ test_simultaneous_async (TestConnection
g_assert_cmpstr (test->buf, ==, TEST_DATA);
}
-#ifdef BACKEND_IS_GNUTLS
-static gboolean
-check_gnutls_has_rehandshaking_bug (void)
-{
- const char *version = gnutls_check_version (NULL);
-
- return !strcmp (version, "3.6.1") ||
- !strcmp (version, "3.6.2");
-}
-#endif
-
static void
test_simultaneous_async_rehandshake (TestConnection *test,
gconstpointer data)
@@ -1703,12 +1692,6 @@ test_simultaneous_async_rehandshake (Tes
#ifdef BACKEND_IS_OPENSSL
g_test_skip ("this needs more research on openssl");
return;
-#elif defined(BACKEND_IS_GNUTLS)
- if (check_gnutls_has_rehandshaking_bug ())
- {
- g_test_skip ("test would fail due to https://gitlab.com/gnutls/gnutls/issues/426");
- return;
- }
#endif
test->rehandshake = TRUE;
@@ -1808,12 +1791,6 @@ test_simultaneous_sync_rehandshake (Test
#ifdef BACKEND_IS_OPENSSL
g_test_skip ("this needs more research on openssl");
return;
-#elif defined(BACKEND_IS_GNUTLS)
- if (check_gnutls_has_rehandshaking_bug ())
- {
- g_test_skip ("test would fail due to https://gitlab.com/gnutls/gnutls/issues/426");
- return;
- }
#endif
test->rehandshake = TRUE;
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "fboss/agent/hw/sai/fake/FakeSaiWred.h"
#include "fboss/agent/hw/sai/fake/FakeSai.h"
#include <folly/logging/xlog.h>
using facebook::fboss::FakeSai;
sai_status_t set_wred_attribute_fn(
sai_object_id_t wred_id,
const sai_attribute_t* attr) {
auto fs = FakeSai::getInstance();
auto& wred = fs->wredManager.get(wred_id);
sai_status_t res;
if (!attr) {
return SAI_STATUS_INVALID_PARAMETER;
}
res = SAI_STATUS_SUCCESS;
switch (attr->id) {
case SAI_WRED_ATTR_GREEN_ENABLE:
wred.setGreenEnable(attr->value.booldata);
break;
case SAI_WRED_ATTR_GREEN_MIN_THRESHOLD:
wred.setGreenMinThreshold(attr->value.u32);
break;
case SAI_WRED_ATTR_GREEN_MAX_THRESHOLD:
wred.setGreenMaxThreshold(attr->value.u32);
break;
case SAI_WRED_ATTR_ECN_MARK_MODE:
wred.setEcnMarkMode(attr->value.s32);
break;
case SAI_WRED_ATTR_ECN_GREEN_MIN_THRESHOLD:
wred.setEcnGreenMinThreshold(attr->value.u32);
break;
case SAI_WRED_ATTR_ECN_GREEN_MAX_THRESHOLD:
wred.setEcnGreenMaxThreshold(attr->value.u32);
break;
default:
res = SAI_STATUS_INVALID_PARAMETER;
break;
}
return res;
}
sai_status_t create_wred_fn(
sai_object_id_t* wred_id,
sai_object_id_t /*switch_id */,
uint32_t attr_count,
const sai_attribute_t* attr_list) {
auto fs = FakeSai::getInstance();
std::optional<bool> greenEnable;
std::optional<sai_uint32_t> greenMinThreshold;
std::optional<sai_uint32_t> greenMaxThreshold;
std::optional<sai_int32_t> ecnMarkMode;
std::optional<sai_uint32_t> ecnGreenMinThreshold;
std::optional<sai_uint32_t> ecnGreenMaxThreshold;
for (int i = 0; i < attr_count; ++i) {
switch (attr_list[i].id) {
case SAI_WRED_ATTR_GREEN_ENABLE:
greenEnable = attr_list[i].value.booldata;
break;
case SAI_WRED_ATTR_GREEN_MIN_THRESHOLD:
greenMinThreshold = attr_list[i].value.u32;
break;
case SAI_WRED_ATTR_GREEN_MAX_THRESHOLD:
greenMaxThreshold = attr_list[i].value.u32;
break;
case SAI_WRED_ATTR_ECN_MARK_MODE:
ecnMarkMode = attr_list[i].value.s32;
break;
case SAI_WRED_ATTR_ECN_GREEN_MIN_THRESHOLD:
ecnGreenMinThreshold = attr_list[i].value.u32;
break;
case SAI_WRED_ATTR_ECN_GREEN_MAX_THRESHOLD:
ecnGreenMaxThreshold = attr_list[i].value.u32;
break;
default:
return SAI_STATUS_INVALID_PARAMETER;
break;
}
}
if (!greenEnable || !greenMinThreshold || !ecnGreenMaxThreshold ||
!ecnMarkMode || !ecnGreenMinThreshold || !ecnGreenMaxThreshold) {
return SAI_STATUS_INVALID_PARAMETER;
}
*wred_id = fs->wredManager.create(
greenEnable.value(),
greenMinThreshold.value(),
greenMaxThreshold.value(),
ecnMarkMode.value(),
ecnGreenMinThreshold.value(),
ecnGreenMaxThreshold.value());
return SAI_STATUS_SUCCESS;
}
sai_status_t remove_wred_fn(sai_object_id_t wred_id) {
auto fs = FakeSai::getInstance();
fs->wredManager.remove(wred_id);
return SAI_STATUS_SUCCESS;
}
sai_status_t get_wred_attribute_fn(
sai_object_id_t wred_id,
uint32_t attr_count,
sai_attribute_t* attr_list) {
auto fs = FakeSai::getInstance();
auto& wred = fs->wredManager.get(wred_id);
for (int i = 0; i < attr_count; ++i) {
switch (attr_list[i].id) {
case SAI_WRED_ATTR_GREEN_ENABLE:
attr_list[i].value.booldata = wred.getGreenEnable();
break;
case SAI_WRED_ATTR_GREEN_MIN_THRESHOLD:
attr_list[i].value.u32 = wred.getGreenMinThreshold();
break;
case SAI_WRED_ATTR_GREEN_MAX_THRESHOLD:
attr_list[i].value.u32 = wred.getGreenMaxThreshold();
break;
case SAI_WRED_ATTR_ECN_MARK_MODE:
attr_list[i].value.s32 = wred.getEcnMarkMode();
break;
case SAI_WRED_ATTR_ECN_GREEN_MIN_THRESHOLD:
attr_list[i].value.u32 = wred.getEcnGreenMinThreshold();
break;
case SAI_WRED_ATTR_ECN_GREEN_MAX_THRESHOLD:
attr_list[i].value.u32 = wred.getEcnGreenMaxThreshold();
break;
default:
return SAI_STATUS_NOT_SUPPORTED;
}
}
return SAI_STATUS_SUCCESS;
}
namespace facebook::fboss {
static sai_wred_api_t _wred_api;
void populate_wred_api(sai_wred_api_t** wred_api) {
_wred_api.create_wred = &create_wred_fn;
_wred_api.remove_wred = &remove_wred_fn;
_wred_api.set_wred_attribute = &set_wred_attribute_fn;
_wred_api.get_wred_attribute = &get_wred_attribute_fn;
*wred_api = &_wred_api;
}
} // namespace facebook::fboss
| {
"pile_set_name": "Github"
} |
{
"os": {
"discovery": {
"devices": [
{
"sysName": "",
"sysObjectID": ".1.3.6.1.4.1.2509.11.1.1.8",
"sysDescr": null,
"sysContact": null,
"version": "2.7.0.11.4349-WTM4100",
"hardware": "W42-11H2-WPX",
"features": null,
"os": "aviat-wtm",
"type": "wireless",
"serial": "AAA9999A999",
"icon": "aviat.png",
"location": null
}
]
},
"poller": "matches discovery"
},
"ports": {
"discovery": {
"ports": [
{
"port_descr_type": null,
"port_descr_descr": null,
"port_descr_circuit": null,
"port_descr_speed": null,
"port_descr_notes": null,
"ifDescr": "Primary",
"ifName": "Radio1",
"portName": null,
"ifIndex": 1537,
"ifSpeed": null,
"ifSpeed_prev": null,
"ifConnectorPresent": null,
"ifPromiscuousMode": null,
"ifHighSpeed": null,
"ifHighSpeed_prev": null,
"ifOperStatus": "up",
"ifOperStatus_prev": null,
"ifAdminStatus": null,
"ifAdminStatus_prev": null,
"ifDuplex": null,
"ifMtu": null,
"ifType": "radioMAC",
"ifAlias": "Primary",
"ifPhysAddress": null,
"ifHardType": null,
"ifLastChange": 0,
"ifVlan": "",
"ifTrunk": null,
"counter_in": null,
"counter_out": null,
"ignore": 0,
"disabled": 0,
"detailed": 0,
"deleted": 0,
"pagpOperationMode": null,
"pagpPortState": null,
"pagpPartnerDeviceId": null,
"pagpPartnerLearnMethod": null,
"pagpPartnerIfIndex": null,
"pagpPartnerGroupIfIndex": null,
"pagpPartnerDeviceName": null,
"pagpEthcOperationMode": null,
"pagpDeviceId": null,
"pagpGroupIfIndex": null,
"ifInUcastPkts": null,
"ifInUcastPkts_prev": null,
"ifInUcastPkts_delta": null,
"ifInUcastPkts_rate": null,
"ifOutUcastPkts": null,
"ifOutUcastPkts_prev": null,
"ifOutUcastPkts_delta": null,
"ifOutUcastPkts_rate": null,
"ifInErrors": null,
"ifInErrors_prev": null,
"ifInErrors_delta": null,
"ifInErrors_rate": null,
"ifOutErrors": null,
"ifOutErrors_prev": null,
"ifOutErrors_delta": null,
"ifOutErrors_rate": null,
"ifInOctets": null,
"ifInOctets_prev": null,
"ifInOctets_delta": null,
"ifInOctets_rate": null,
"ifOutOctets": null,
"ifOutOctets_prev": null,
"ifOutOctets_delta": null,
"ifOutOctets_rate": null,
"poll_prev": null,
"ifInNUcastPkts": null,
"ifInNUcastPkts_prev": null,
"ifInNUcastPkts_delta": null,
"ifInNUcastPkts_rate": null,
"ifOutNUcastPkts": null,
"ifOutNUcastPkts_prev": null,
"ifOutNUcastPkts_delta": null,
"ifOutNUcastPkts_rate": null,
"ifInDiscards": null,
"ifInDiscards_prev": null,
"ifInDiscards_delta": null,
"ifInDiscards_rate": null,
"ifOutDiscards": null,
"ifOutDiscards_prev": null,
"ifOutDiscards_delta": null,
"ifOutDiscards_rate": null,
"ifInUnknownProtos": null,
"ifInUnknownProtos_prev": null,
"ifInUnknownProtos_delta": null,
"ifInUnknownProtos_rate": null,
"ifInBroadcastPkts": null,
"ifInBroadcastPkts_prev": null,
"ifInBroadcastPkts_delta": null,
"ifInBroadcastPkts_rate": null,
"ifOutBroadcastPkts": null,
"ifOutBroadcastPkts_prev": null,
"ifOutBroadcastPkts_delta": null,
"ifOutBroadcastPkts_rate": null,
"ifInMulticastPkts": null,
"ifInMulticastPkts_prev": null,
"ifInMulticastPkts_delta": null,
"ifInMulticastPkts_rate": null,
"ifOutMulticastPkts": null,
"ifOutMulticastPkts_prev": null,
"ifOutMulticastPkts_delta": null,
"ifOutMulticastPkts_rate": null
}
]
},
"poller": {
"ports": [
{
"port_descr_type": null,
"port_descr_descr": null,
"port_descr_circuit": null,
"port_descr_speed": null,
"port_descr_notes": null,
"ifDescr": "Primary",
"ifName": "Radio1",
"portName": null,
"ifIndex": 1537,
"ifSpeed": null,
"ifSpeed_prev": 0,
"ifConnectorPresent": null,
"ifPromiscuousMode": null,
"ifHighSpeed": null,
"ifHighSpeed_prev": null,
"ifOperStatus": "up",
"ifOperStatus_prev": "up",
"ifAdminStatus": null,
"ifAdminStatus_prev": null,
"ifDuplex": null,
"ifMtu": null,
"ifType": "radioMAC",
"ifAlias": "Primary",
"ifPhysAddress": null,
"ifHardType": null,
"ifLastChange": 0,
"ifVlan": "",
"ifTrunk": null,
"counter_in": null,
"counter_out": null,
"ignore": 0,
"disabled": 0,
"detailed": 0,
"deleted": 0,
"pagpOperationMode": null,
"pagpPortState": null,
"pagpPartnerDeviceId": null,
"pagpPartnerLearnMethod": null,
"pagpPartnerIfIndex": null,
"pagpPartnerGroupIfIndex": null,
"pagpPartnerDeviceName": null,
"pagpEthcOperationMode": null,
"pagpDeviceId": null,
"pagpGroupIfIndex": null,
"ifInUcastPkts": 0,
"ifInUcastPkts_prev": 0,
"ifInUcastPkts_delta": null,
"ifInUcastPkts_rate": null,
"ifOutUcastPkts": 0,
"ifOutUcastPkts_prev": 0,
"ifOutUcastPkts_delta": null,
"ifOutUcastPkts_rate": null,
"ifInErrors": 0,
"ifInErrors_prev": 0,
"ifInErrors_delta": null,
"ifInErrors_rate": null,
"ifOutErrors": 0,
"ifOutErrors_prev": 0,
"ifOutErrors_delta": null,
"ifOutErrors_rate": null,
"ifInOctets": 0,
"ifInOctets_prev": 0,
"ifInOctets_delta": null,
"ifInOctets_rate": null,
"ifOutOctets": 0,
"ifOutOctets_prev": 0,
"ifOutOctets_delta": null,
"ifOutOctets_rate": null,
"poll_prev": null,
"ifInNUcastPkts": 0,
"ifInNUcastPkts_prev": 0,
"ifInNUcastPkts_delta": null,
"ifInNUcastPkts_rate": null,
"ifOutNUcastPkts": 0,
"ifOutNUcastPkts_prev": 0,
"ifOutNUcastPkts_delta": null,
"ifOutNUcastPkts_rate": null,
"ifInDiscards": 0,
"ifInDiscards_prev": 0,
"ifInDiscards_delta": null,
"ifInDiscards_rate": null,
"ifOutDiscards": 0,
"ifOutDiscards_prev": 0,
"ifOutDiscards_delta": null,
"ifOutDiscards_rate": null,
"ifInUnknownProtos": 0,
"ifInUnknownProtos_prev": 0,
"ifInUnknownProtos_delta": null,
"ifInUnknownProtos_rate": null,
"ifInBroadcastPkts": 0,
"ifInBroadcastPkts_prev": 0,
"ifInBroadcastPkts_delta": null,
"ifInBroadcastPkts_rate": null,
"ifOutBroadcastPkts": 0,
"ifOutBroadcastPkts_prev": 0,
"ifOutBroadcastPkts_delta": null,
"ifOutBroadcastPkts_rate": null,
"ifInMulticastPkts": 0,
"ifInMulticastPkts_prev": 0,
"ifInMulticastPkts_delta": null,
"ifInMulticastPkts_rate": null,
"ifOutMulticastPkts": 0,
"ifOutMulticastPkts_prev": 0,
"ifOutMulticastPkts_delta": null,
"ifOutMulticastPkts_rate": null
}
]
}
},
"sensors": {
"discovery": {
"sensors": [
{
"sensor_deleted": 0,
"sensor_class": "state",
"poller_type": "snmp",
"sensor_oid": ".1.3.6.1.4.1.2509.9.3.2.1.1.13.59",
"sensor_index": "59",
"sensor_type": "aviatModemCurModulationRx",
"sensor_descr": "Tx Mod Rate (Carrier1/59)",
"group": null,
"sensor_divisor": 1,
"sensor_multiplier": 1,
"sensor_current": 14,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_prev": null,
"user_func": null,
"state_name": "aviatModemCurModulationRx"
},
{
"sensor_deleted": 0,
"sensor_class": "state",
"poller_type": "snmp",
"sensor_oid": ".1.3.6.1.4.1.2509.9.3.2.1.1.13.60",
"sensor_index": "60",
"sensor_type": "aviatModemCurModulationRx",
"sensor_descr": "Tx Mod Rate (Carrier1/60)",
"group": null,
"sensor_divisor": 1,
"sensor_multiplier": 1,
"sensor_current": 14,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_prev": null,
"user_func": null,
"state_name": "aviatModemCurModulationRx"
},
{
"sensor_deleted": 0,
"sensor_class": "temperature",
"poller_type": "snmp",
"sensor_oid": ".1.3.6.1.2.1.99.1.1.1.4.5",
"sensor_index": "5",
"sensor_type": "entity-sensor",
"sensor_descr": "InternalTemp1/1",
"group": null,
"sensor_divisor": 1000,
"sensor_multiplier": 1,
"sensor_current": 42.562,
"sensor_limit": 62.562,
"sensor_limit_warn": null,
"sensor_limit_low": 32.562,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": "5",
"entPhysicalIndex_measured": null,
"sensor_prev": null,
"user_func": null,
"state_name": null
},
{
"sensor_deleted": 0,
"sensor_class": "temperature",
"poller_type": "snmp",
"sensor_oid": ".1.3.6.1.2.1.99.1.1.1.4.6",
"sensor_index": "6",
"sensor_type": "entity-sensor",
"sensor_descr": "InternalTemp1/2",
"group": null,
"sensor_divisor": 1000,
"sensor_multiplier": 1,
"sensor_current": 40.375,
"sensor_limit": 60.375,
"sensor_limit_warn": null,
"sensor_limit_low": 30.375,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": "6",
"entPhysicalIndex_measured": null,
"sensor_prev": null,
"user_func": null,
"state_name": null
},
{
"sensor_deleted": 0,
"sensor_class": "temperature",
"poller_type": "snmp",
"sensor_oid": ".1.3.6.1.2.1.99.1.1.1.4.7",
"sensor_index": "7",
"sensor_type": "entity-sensor",
"sensor_descr": "InternalTemp1/3",
"group": null,
"sensor_divisor": 1000,
"sensor_multiplier": 1,
"sensor_current": 52,
"sensor_limit": 72,
"sensor_limit_warn": null,
"sensor_limit_low": 42,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": "7",
"entPhysicalIndex_measured": null,
"sensor_prev": null,
"user_func": null,
"state_name": null
},
{
"sensor_deleted": 0,
"sensor_class": "temperature",
"poller_type": "snmp",
"sensor_oid": ".1.3.6.1.2.1.99.1.1.1.4.8",
"sensor_index": "8",
"sensor_type": "entity-sensor",
"sensor_descr": "InternalTemp1/4",
"group": null,
"sensor_divisor": 1000,
"sensor_multiplier": 1,
"sensor_current": 51.187,
"sensor_limit": 71.187,
"sensor_limit_warn": null,
"sensor_limit_low": 41.187,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": "8",
"entPhysicalIndex_measured": null,
"sensor_prev": null,
"user_func": null,
"state_name": null
},
{
"sensor_deleted": 0,
"sensor_class": "temperature",
"poller_type": "snmp",
"sensor_oid": ".1.3.6.1.2.1.99.1.1.1.4.9",
"sensor_index": "9",
"sensor_type": "entity-sensor",
"sensor_descr": "InternalTemp1/5",
"group": null,
"sensor_divisor": 1000,
"sensor_multiplier": 1,
"sensor_current": 48.724,
"sensor_limit": 68.724,
"sensor_limit_warn": null,
"sensor_limit_low": 38.724,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": "9",
"entPhysicalIndex_measured": null,
"sensor_prev": null,
"user_func": null,
"state_name": null
},
{
"sensor_deleted": 0,
"sensor_class": "voltage",
"poller_type": "snmp",
"sensor_oid": ".1.3.6.1.2.1.99.1.1.1.4.3",
"sensor_index": "3",
"sensor_type": "entity-sensor",
"sensor_descr": "Voltage1/1",
"group": null,
"sensor_divisor": 1000,
"sensor_multiplier": 1,
"sensor_current": 47.058,
"sensor_limit": 54.1167,
"sensor_limit_warn": null,
"sensor_limit_low": 39.9993,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": "3",
"entPhysicalIndex_measured": null,
"sensor_prev": null,
"user_func": null,
"state_name": null
}
],
"state_indexes": [
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "N/A",
"state_draw_graph": 1,
"state_value": 1,
"state_generic_value": 1
},
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "QPSK",
"state_draw_graph": 1,
"state_value": 2,
"state_generic_value": 0
},
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "16-QAM",
"state_draw_graph": 1,
"state_value": 3,
"state_generic_value": 0
},
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "32-QAM",
"state_draw_graph": 1,
"state_value": 4,
"state_generic_value": 0
},
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "64-QAM",
"state_draw_graph": 1,
"state_value": 5,
"state_generic_value": 0
},
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "128-QAM",
"state_draw_graph": 1,
"state_value": 6,
"state_generic_value": 0
},
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "256-QAM",
"state_draw_graph": 1,
"state_value": 7,
"state_generic_value": 0
},
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "512-QAM",
"state_draw_graph": 1,
"state_value": 8,
"state_generic_value": 0
},
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "1024-QAM",
"state_draw_graph": 1,
"state_value": 9,
"state_generic_value": 0
},
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "256-QAM-HG",
"state_draw_graph": 1,
"state_value": 10,
"state_generic_value": 0
},
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "512-QAM-HD",
"state_draw_graph": 1,
"state_value": 11,
"state_generic_value": 0
},
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "1024-QAM-HD",
"state_draw_graph": 1,
"state_value": 12,
"state_generic_value": 0
},
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "2048-QAM",
"state_draw_graph": 1,
"state_value": 13,
"state_generic_value": 0
},
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "4096-QAM",
"state_draw_graph": 1,
"state_value": 14,
"state_generic_value": 0
}
]
},
"poller": {
"sensors": [
{
"sensor_deleted": 0,
"sensor_class": "state",
"poller_type": "snmp",
"sensor_oid": ".1.3.6.1.4.1.2509.9.3.2.1.1.13.59",
"sensor_index": "59",
"sensor_type": "aviatModemCurModulationRx",
"sensor_descr": "Tx Mod Rate (Carrier1/59)",
"group": null,
"sensor_divisor": 1,
"sensor_multiplier": 1,
"sensor_current": 0,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_prev": 14,
"user_func": null,
"state_name": "aviatModemCurModulationRx"
},
{
"sensor_deleted": 0,
"sensor_class": "state",
"poller_type": "snmp",
"sensor_oid": ".1.3.6.1.4.1.2509.9.3.2.1.1.13.60",
"sensor_index": "60",
"sensor_type": "aviatModemCurModulationRx",
"sensor_descr": "Tx Mod Rate (Carrier1/60)",
"group": null,
"sensor_divisor": 1,
"sensor_multiplier": 1,
"sensor_current": 0,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_prev": 14,
"user_func": null,
"state_name": "aviatModemCurModulationRx"
},
{
"sensor_deleted": 0,
"sensor_class": "temperature",
"poller_type": "snmp",
"sensor_oid": ".1.3.6.1.2.1.99.1.1.1.4.5",
"sensor_index": "5",
"sensor_type": "entity-sensor",
"sensor_descr": "InternalTemp1/1",
"group": null,
"sensor_divisor": 1000,
"sensor_multiplier": 1,
"sensor_current": 42.562,
"sensor_limit": 62.562,
"sensor_limit_warn": null,
"sensor_limit_low": 32.562,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": "5",
"entPhysicalIndex_measured": null,
"sensor_prev": null,
"user_func": null,
"state_name": null
},
{
"sensor_deleted": 0,
"sensor_class": "temperature",
"poller_type": "snmp",
"sensor_oid": ".1.3.6.1.2.1.99.1.1.1.4.6",
"sensor_index": "6",
"sensor_type": "entity-sensor",
"sensor_descr": "InternalTemp1/2",
"group": null,
"sensor_divisor": 1000,
"sensor_multiplier": 1,
"sensor_current": 40.375,
"sensor_limit": 60.375,
"sensor_limit_warn": null,
"sensor_limit_low": 30.375,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": "6",
"entPhysicalIndex_measured": null,
"sensor_prev": null,
"user_func": null,
"state_name": null
},
{
"sensor_deleted": 0,
"sensor_class": "temperature",
"poller_type": "snmp",
"sensor_oid": ".1.3.6.1.2.1.99.1.1.1.4.7",
"sensor_index": "7",
"sensor_type": "entity-sensor",
"sensor_descr": "InternalTemp1/3",
"group": null,
"sensor_divisor": 1000,
"sensor_multiplier": 1,
"sensor_current": 52,
"sensor_limit": 72,
"sensor_limit_warn": null,
"sensor_limit_low": 42,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": "7",
"entPhysicalIndex_measured": null,
"sensor_prev": null,
"user_func": null,
"state_name": null
},
{
"sensor_deleted": 0,
"sensor_class": "temperature",
"poller_type": "snmp",
"sensor_oid": ".1.3.6.1.2.1.99.1.1.1.4.8",
"sensor_index": "8",
"sensor_type": "entity-sensor",
"sensor_descr": "InternalTemp1/4",
"group": null,
"sensor_divisor": 1000,
"sensor_multiplier": 1,
"sensor_current": 51.187,
"sensor_limit": 71.187,
"sensor_limit_warn": null,
"sensor_limit_low": 41.187,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": "8",
"entPhysicalIndex_measured": null,
"sensor_prev": null,
"user_func": null,
"state_name": null
},
{
"sensor_deleted": 0,
"sensor_class": "temperature",
"poller_type": "snmp",
"sensor_oid": ".1.3.6.1.2.1.99.1.1.1.4.9",
"sensor_index": "9",
"sensor_type": "entity-sensor",
"sensor_descr": "InternalTemp1/5",
"group": null,
"sensor_divisor": 1000,
"sensor_multiplier": 1,
"sensor_current": 48.724,
"sensor_limit": 68.724,
"sensor_limit_warn": null,
"sensor_limit_low": 38.724,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": "9",
"entPhysicalIndex_measured": null,
"sensor_prev": null,
"user_func": null,
"state_name": null
},
{
"sensor_deleted": 0,
"sensor_class": "voltage",
"poller_type": "snmp",
"sensor_oid": ".1.3.6.1.2.1.99.1.1.1.4.3",
"sensor_index": "3",
"sensor_type": "entity-sensor",
"sensor_descr": "Voltage1/1",
"group": null,
"sensor_divisor": 1000,
"sensor_multiplier": 1,
"sensor_current": 47.058,
"sensor_limit": 54.1167,
"sensor_limit_warn": null,
"sensor_limit_low": 39.9993,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": "3",
"entPhysicalIndex_measured": null,
"sensor_prev": null,
"user_func": null,
"state_name": null
}
],
"state_indexes": [
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "N/A",
"state_draw_graph": 1,
"state_value": 1,
"state_generic_value": 1
},
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "QPSK",
"state_draw_graph": 1,
"state_value": 2,
"state_generic_value": 0
},
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "16-QAM",
"state_draw_graph": 1,
"state_value": 3,
"state_generic_value": 0
},
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "32-QAM",
"state_draw_graph": 1,
"state_value": 4,
"state_generic_value": 0
},
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "64-QAM",
"state_draw_graph": 1,
"state_value": 5,
"state_generic_value": 0
},
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "128-QAM",
"state_draw_graph": 1,
"state_value": 6,
"state_generic_value": 0
},
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "256-QAM",
"state_draw_graph": 1,
"state_value": 7,
"state_generic_value": 0
},
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "512-QAM",
"state_draw_graph": 1,
"state_value": 8,
"state_generic_value": 0
},
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "1024-QAM",
"state_draw_graph": 1,
"state_value": 9,
"state_generic_value": 0
},
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "256-QAM-HG",
"state_draw_graph": 1,
"state_value": 10,
"state_generic_value": 0
},
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "512-QAM-HD",
"state_draw_graph": 1,
"state_value": 11,
"state_generic_value": 0
},
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "1024-QAM-HD",
"state_draw_graph": 1,
"state_value": 12,
"state_generic_value": 0
},
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "2048-QAM",
"state_draw_graph": 1,
"state_value": 13,
"state_generic_value": 0
},
{
"state_name": "aviatModemCurModulationRx",
"state_descr": "4096-QAM",
"state_draw_graph": 1,
"state_value": 14,
"state_generic_value": 0
}
]
}
},
"wireless": {
"discovery": {
"wireless_sensors": [
{
"sensor_deleted": 0,
"sensor_class": "rate",
"sensor_index": "59",
"sensor_type": "aviat-wtm-carrier-tx-rate",
"sensor_descr": "TX Capacity (Carrier1/1)",
"sensor_divisor": 1,
"sensor_multiplier": 1000,
"sensor_aggregator": "sum",
"sensor_current": 730947,
"sensor_prev": null,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_oids": "[\".1.3.6.1.4.1.2509.9.3.2.1.1.11.59\"]"
},
{
"sensor_deleted": 0,
"sensor_class": "rate",
"sensor_index": "60",
"sensor_type": "aviat-wtm-carrier-tx-rate",
"sensor_descr": "TX Capacity (Carrier1/2)",
"sensor_divisor": 1,
"sensor_multiplier": 1000,
"sensor_aggregator": "sum",
"sensor_current": 730947,
"sensor_prev": null,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_oids": "[\".1.3.6.1.4.1.2509.9.3.2.1.1.11.60\"]"
},
{
"sensor_deleted": 0,
"sensor_class": "rate",
"sensor_index": "59",
"sensor_type": "aviat-wtm-carrier-rx-rate",
"sensor_descr": "TX Capacity (Carrier1/1)",
"sensor_divisor": 1,
"sensor_multiplier": 1000,
"sensor_aggregator": "sum",
"sensor_current": 730947,
"sensor_prev": null,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_oids": "[\".1.3.6.1.4.1.2509.9.3.2.1.1.12.59\"]"
},
{
"sensor_deleted": 0,
"sensor_class": "rate",
"sensor_index": "60",
"sensor_type": "aviat-wtm-carrier-rx-rate",
"sensor_descr": "TX Capacity (Carrier1/2)",
"sensor_divisor": 1,
"sensor_multiplier": 1000,
"sensor_aggregator": "sum",
"sensor_current": 730947,
"sensor_prev": null,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_oids": "[\".1.3.6.1.4.1.2509.9.3.2.1.1.12.60\"]"
},
{
"sensor_deleted": 0,
"sensor_class": "snr",
"sensor_index": "59",
"sensor_type": "aviat-wtm-carrier-snr",
"sensor_descr": "SNR (Carrier1/1)",
"sensor_divisor": 10,
"sensor_multiplier": 1,
"sensor_aggregator": "sum",
"sensor_current": 45,
"sensor_prev": null,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_oids": "[\".1.3.6.1.4.1.2509.9.33.2.2.1.3.59\"]"
},
{
"sensor_deleted": 0,
"sensor_class": "snr",
"sensor_index": "60",
"sensor_type": "aviat-wtm-carrier-snr",
"sensor_descr": "SNR (Carrier1/2)",
"sensor_divisor": 10,
"sensor_multiplier": 1,
"sensor_aggregator": "sum",
"sensor_current": 45,
"sensor_prev": null,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_oids": "[\".1.3.6.1.4.1.2509.9.33.2.2.1.3.60\"]"
},
{
"sensor_deleted": 0,
"sensor_class": "rssi",
"sensor_index": "59",
"sensor_type": "aviat-wtm-carrier-rsl",
"sensor_descr": "RSL (Carrier1/1)",
"sensor_divisor": 10,
"sensor_multiplier": 1,
"sensor_aggregator": "sum",
"sensor_current": -36.7,
"sensor_prev": null,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_oids": "[\".1.3.6.1.4.1.2509.9.15.2.2.1.4.59\"]"
},
{
"sensor_deleted": 0,
"sensor_class": "rssi",
"sensor_index": "60",
"sensor_type": "aviat-wtm-carrier-rsl",
"sensor_descr": "RSL (Carrier1/2)",
"sensor_divisor": 10,
"sensor_multiplier": 1,
"sensor_aggregator": "sum",
"sensor_current": -37,
"sensor_prev": null,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_oids": "[\".1.3.6.1.4.1.2509.9.15.2.2.1.4.60\"]"
},
{
"sensor_deleted": 0,
"sensor_class": "power",
"sensor_index": "59",
"sensor_type": "aviat-wtm-carrier-txpower",
"sensor_descr": "TX Power (Carrier1/1)",
"sensor_divisor": 10,
"sensor_multiplier": 1,
"sensor_aggregator": "sum",
"sensor_current": 22.4,
"sensor_prev": null,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_oids": "[\".1.3.6.1.4.1.2509.9.33.2.2.1.7.59\"]"
},
{
"sensor_deleted": 0,
"sensor_class": "power",
"sensor_index": "60",
"sensor_type": "aviat-wtm-carrier-txpower",
"sensor_descr": "TX Power (Carrier1/2)",
"sensor_divisor": 10,
"sensor_multiplier": 1,
"sensor_aggregator": "sum",
"sensor_current": 22.5,
"sensor_prev": null,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_oids": "[\".1.3.6.1.4.1.2509.9.33.2.2.1.7.60\"]"
},
{
"sensor_deleted": 0,
"sensor_class": "frequency",
"sensor_index": "59",
"sensor_type": "aviat-wtm-carrier-tx-freq",
"sensor_descr": "TX Frequency (Carrier1/1)",
"sensor_divisor": 1000,
"sensor_multiplier": 1,
"sensor_aggregator": "sum",
"sensor_current": 11565000,
"sensor_prev": null,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_oids": "[\".1.3.6.1.4.1.2509.9.5.2.1.1.1.59\"]"
},
{
"sensor_deleted": 0,
"sensor_class": "frequency",
"sensor_index": "60",
"sensor_type": "aviat-wtm-carrier-tx-freq",
"sensor_descr": "TX Frequency (Carrier1/2)",
"sensor_divisor": 1000,
"sensor_multiplier": 1,
"sensor_aggregator": "sum",
"sensor_current": 11565000,
"sensor_prev": null,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_oids": "[\".1.3.6.1.4.1.2509.9.5.2.1.1.1.60\"]"
}
]
},
"poller": {
"wireless_sensors": [
{
"sensor_deleted": 0,
"sensor_class": "rate",
"sensor_index": "59",
"sensor_type": "aviat-wtm-carrier-tx-rate",
"sensor_descr": "TX Capacity (Carrier1/1)",
"sensor_divisor": 1,
"sensor_multiplier": 1000,
"sensor_aggregator": "sum",
"sensor_current": 730947000,
"sensor_prev": 730947,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_oids": "[\".1.3.6.1.4.1.2509.9.3.2.1.1.11.59\"]"
},
{
"sensor_deleted": 0,
"sensor_class": "rate",
"sensor_index": "60",
"sensor_type": "aviat-wtm-carrier-tx-rate",
"sensor_descr": "TX Capacity (Carrier1/2)",
"sensor_divisor": 1,
"sensor_multiplier": 1000,
"sensor_aggregator": "sum",
"sensor_current": 730947000,
"sensor_prev": 730947,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_oids": "[\".1.3.6.1.4.1.2509.9.3.2.1.1.11.60\"]"
},
{
"sensor_deleted": 0,
"sensor_class": "rate",
"sensor_index": "59",
"sensor_type": "aviat-wtm-carrier-rx-rate",
"sensor_descr": "TX Capacity (Carrier1/1)",
"sensor_divisor": 1,
"sensor_multiplier": 1000,
"sensor_aggregator": "sum",
"sensor_current": 730947000,
"sensor_prev": 730947,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_oids": "[\".1.3.6.1.4.1.2509.9.3.2.1.1.12.59\"]"
},
{
"sensor_deleted": 0,
"sensor_class": "rate",
"sensor_index": "60",
"sensor_type": "aviat-wtm-carrier-rx-rate",
"sensor_descr": "TX Capacity (Carrier1/2)",
"sensor_divisor": 1,
"sensor_multiplier": 1000,
"sensor_aggregator": "sum",
"sensor_current": 730947000,
"sensor_prev": 730947,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_oids": "[\".1.3.6.1.4.1.2509.9.3.2.1.1.12.60\"]"
},
{
"sensor_deleted": 0,
"sensor_class": "snr",
"sensor_index": "59",
"sensor_type": "aviat-wtm-carrier-snr",
"sensor_descr": "SNR (Carrier1/1)",
"sensor_divisor": 10,
"sensor_multiplier": 1,
"sensor_aggregator": "sum",
"sensor_current": 45,
"sensor_prev": 45,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_oids": "[\".1.3.6.1.4.1.2509.9.33.2.2.1.3.59\"]"
},
{
"sensor_deleted": 0,
"sensor_class": "snr",
"sensor_index": "60",
"sensor_type": "aviat-wtm-carrier-snr",
"sensor_descr": "SNR (Carrier1/2)",
"sensor_divisor": 10,
"sensor_multiplier": 1,
"sensor_aggregator": "sum",
"sensor_current": 45,
"sensor_prev": 45,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_oids": "[\".1.3.6.1.4.1.2509.9.33.2.2.1.3.60\"]"
},
{
"sensor_deleted": 0,
"sensor_class": "rssi",
"sensor_index": "59",
"sensor_type": "aviat-wtm-carrier-rsl",
"sensor_descr": "RSL (Carrier1/1)",
"sensor_divisor": 10,
"sensor_multiplier": 1,
"sensor_aggregator": "sum",
"sensor_current": -36.7,
"sensor_prev": -36.7,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_oids": "[\".1.3.6.1.4.1.2509.9.15.2.2.1.4.59\"]"
},
{
"sensor_deleted": 0,
"sensor_class": "rssi",
"sensor_index": "60",
"sensor_type": "aviat-wtm-carrier-rsl",
"sensor_descr": "RSL (Carrier1/2)",
"sensor_divisor": 10,
"sensor_multiplier": 1,
"sensor_aggregator": "sum",
"sensor_current": -37,
"sensor_prev": -37,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_oids": "[\".1.3.6.1.4.1.2509.9.15.2.2.1.4.60\"]"
},
{
"sensor_deleted": 0,
"sensor_class": "power",
"sensor_index": "59",
"sensor_type": "aviat-wtm-carrier-txpower",
"sensor_descr": "TX Power (Carrier1/1)",
"sensor_divisor": 10,
"sensor_multiplier": 1,
"sensor_aggregator": "sum",
"sensor_current": 22.4,
"sensor_prev": 22.4,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_oids": "[\".1.3.6.1.4.1.2509.9.33.2.2.1.7.59\"]"
},
{
"sensor_deleted": 0,
"sensor_class": "power",
"sensor_index": "60",
"sensor_type": "aviat-wtm-carrier-txpower",
"sensor_descr": "TX Power (Carrier1/2)",
"sensor_divisor": 10,
"sensor_multiplier": 1,
"sensor_aggregator": "sum",
"sensor_current": 22.5,
"sensor_prev": 22.5,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_oids": "[\".1.3.6.1.4.1.2509.9.33.2.2.1.7.60\"]"
},
{
"sensor_deleted": 0,
"sensor_class": "frequency",
"sensor_index": "59",
"sensor_type": "aviat-wtm-carrier-tx-freq",
"sensor_descr": "TX Frequency (Carrier1/1)",
"sensor_divisor": 1000,
"sensor_multiplier": 1,
"sensor_aggregator": "sum",
"sensor_current": 11565,
"sensor_prev": 11565000,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_oids": "[\".1.3.6.1.4.1.2509.9.5.2.1.1.1.59\"]"
},
{
"sensor_deleted": 0,
"sensor_class": "frequency",
"sensor_index": "60",
"sensor_type": "aviat-wtm-carrier-tx-freq",
"sensor_descr": "TX Frequency (Carrier1/2)",
"sensor_divisor": 1000,
"sensor_multiplier": 1,
"sensor_aggregator": "sum",
"sensor_current": 11565,
"sensor_prev": 11565000,
"sensor_limit": null,
"sensor_limit_warn": null,
"sensor_limit_low": null,
"sensor_limit_low_warn": null,
"sensor_alert": 1,
"sensor_custom": "No",
"entPhysicalIndex": null,
"entPhysicalIndex_measured": null,
"sensor_oids": "[\".1.3.6.1.4.1.2509.9.5.2.1.1.1.60\"]"
}
]
}
}
}
| {
"pile_set_name": "Github"
} |
<div style="max-width: 450px; padding-bottom: 50px">
<h4 class="table-example-popin-title">Mobile Mode</h4>
<table fd-table [popIn]="true" [noBorderX]="true" [noBorderY]="true">
<thead fd-table-header>
<tr fd-table-row>
<th fd-table-cell>Fruit Description</th>
<th fd-table-cell>Price</th>
<th fd-table-cell></th>
</tr>
</thead>
<tbody fd-table-body>
<ng-container *ngFor="let fruit of fruits">
<tr fd-table-row [main]="true" [activable]="true">
<td fd-table-cell>
<p fd-table-text [title]="true">{{fruit.name}}</p>
<p fd-table-text>{{fruit.country}}</p>
</td>
<td fd-table-cell [fitContent]="true">
{{fruit.price}}
</td>
<td fd-table-cell [fitContent]="true" [noPadding]="true">
<span fd-table-icon [glyph]="navigationArrow$ | async" [navigation]="true"></span>
</td>
</tr>
<tr fd-table-row [secondary]="true">
<td fd-table-cell colspan="100%">
<p fd-table-text>
<label fd-form-label>Status:</label>
<span fd-object-status [status]="fruit.status">{{fruit.statusName}}</span>
</p>
<p fd-table-text>
<label fd-form-label>Date Of Expire:</label>
{{fruit.dateOfExpire}}
</p>
<p fd-table-text>
<label fd-form-label>Description:</label>
{{fruit.description}}
</p>
</td>
</tr>
</ng-container>
</tbody>
</table>
</div>
<div style="max-width: 768px; padding-bottom: 50px;">
<h4 class="table-example-popin-title">Tablet Mode</h4>
<table fd-table [popIn]="true" [noBorderX]="true" [noBorderY]="true">
<thead fd-table-header>
<tr fd-table-row>
<th fd-table-cell>Fruit Description</th>
<th fd-table-cell>Price</th>
<th fd-table-cell>Status</th>
<th fd-table-cell>Date Of Expire</th>
<th fd-table-cell></th>
</tr>
</thead>
<tbody fd-table-body>
<ng-container *ngFor="let fruit of fruits">
<tr fd-table-row [main]="true" [activable]="true">
<td fd-table-cell>
<p fd-table-text [title]="true">{{fruit.name}}</p>
<p fd-table-text>{{fruit.country}}</p>
</td>
<td fd-table-cell [fitContent]="true">
{{fruit.price}}
</td>
<td fd-table-cell [fitContent]="true">
<span fd-object-status [status]="fruit.status">{{fruit.statusName}}</span>
</td>
<td fd-table-cell [fitContent]="true">
{{fruit.dateOfExpire}}
</td>
<td fd-table-cell [fitContent]="true" [noPadding]="true">
<span fd-table-icon [glyph]="navigationArrow$ | async" [navigation]="true"></span>
</td>
</tr>
<tr fd-table-row [secondary]="true">
<td fd-table-cell colspan="100%">
<p fd-table-text>
<label fd-form-label>Description: </label>
{{fruit.description}}
</p>
</td>
</tr>
</ng-container>
</tbody>
</table>
</div>
<div style="max-width: 1200px; padding-bottom: 50px">
<h4 class="table-example-popin-title">Desktop Mode</h4>
<table fd-table [noBorderX]="true">
<thead fd-table-header>
<tr fd-table-row>
<th fd-table-cell>Name</th>
<th fd-table-cell>Price</th>
<th fd-table-cell>Country</th>
<th fd-table-cell>Status</th>
<th fd-table-cell>Date Of Expire</th>
<th fd-table-cell>Description</th>
<th fd-table-cell></th>
</tr>
</thead>
<tbody fd-table-body>
<ng-container *ngFor="let fruit of fruits">
<tr fd-table-row [main]="true" [activable]="true">
<td fd-table-cell>
{{fruit.name}}
</td>
<td fd-table-cell>
{{fruit.country}}
</td>
<td fd-table-cell>
{{fruit.price}}
</td>
<td fd-table-cell>
<span fd-object-status [status]="fruit.status">{{fruit.statusName}}</span>
</td>
<td fd-table-cell>
{{fruit.dateOfExpire}}
</td>
<td fd-table-cell>
{{fruit.description}}
</td>
<td fd-table-cell [fitContent]="true" [noPadding]="true">
<span fd-table-icon [glyph]="navigationArrow$ | async" [navigation]="true"></span>
</td>
</tr>
</ng-container>
</tbody>
</table>
</div>
<div style="max-width: 450px; padding-bottom: 50px">
<h4 class="table-example-popin-title">Popin Mobile Mode with Checkboxes</h4>
<table fd-table [popIn]="true" [noBorderX]="true" [noBorderY]="true">
<thead fd-table-header>
<tr fd-table-row>
<th fd-table-cell>
<fd-checkbox name="allCheckbox"
[ngModel]="masterCheckbox"
(ngModelChange)="selectMaster($event)"
></fd-checkbox>
</th>
<th fd-table-cell>Fruit Description</th>
<th fd-table-cell>Price</th>
<th fd-table-cell></th>
</tr>
</thead>
<tbody fd-table-body>
<ng-container *ngFor="let fruit of fruits; let ind = index">
<tr fd-table-row [main]="true" [attr.aria-selected]="fruit.checked">
<td fd-table-cell>
<fd-checkbox name="firstCheckbox{{fruit.name}}" [ngModel]="fruit.checked" (ngModelChange)="select(ind, $event)"></fd-checkbox>
</td>
<td fd-table-cell>
<p fd-table-text [title]="true">{{fruit.name}}</p>
<p fd-table-text>{{fruit.country}}</p>
</td>
<td fd-table-cell [fitContent]="true">
{{fruit.price}}
</td>
<td fd-table-cell [fitContent]="true" [noPadding]="true">
<span fd-table-icon [glyph]="navigationArrow$ | async" [navigation]="true"></span>
</td>
</tr>
<tr fd-table-row [secondary]="true" [attr.aria-selected]="fruit.checked">
<td fd-table-cell></td>
<td fd-table-cell colspan="100%">
<p fd-table-text>
<label fd-form-label>Status:</label>
<span fd-object-status [status]="fruit.status">{{fruit.statusName}}</span>
</p>
<p fd-table-text>
<label fd-form-label>Date Of Expire:</label>
{{fruit.dateOfExpire}}
</p>
<p fd-table-text>
<label fd-form-label>Description:</label>
{{fruit.description}}
</p>
</td>
</tr>
</ng-container>
</tbody>
</table>
</div>
| {
"pile_set_name": "Github"
} |
timestamp <- Sys.time()
library(caret)
library(plyr)
library(recipes)
library(dplyr)
model <- "rpartCost"
#########################################################################
set.seed(2)
training <- twoClassSim(500, linearVars = 2)
testing <- twoClassSim(500, linearVars = 2)
trainX <- training[, -ncol(training)]
trainY <- training$Class
rec_cls <- recipe(Class ~ ., data = training) %>%
step_center(all_predictors()) %>%
step_scale(all_predictors())
grid <- expand.grid(Cost = 1:3, cp = c(0.1, .01))
seeds <- vector(mode = "list", length = nrow(training) + 1)
seeds <- lapply(seeds, function(x) 1:20)
cctrl1 <- trainControl(method = "cv", number = 3,
returnResamp = "all", seeds = seeds)
cctrl2 <- trainControl(method = "LOOCV", seeds = seeds)
cctrl3 <- trainControl(method = "none", seeds = seeds)
cctrlR <- trainControl(method = "cv", number = 3,
returnResamp = "all", search = "random",
seeds = seeds)
set.seed(849)
test_class_cv_model <- train(trainX, trainY,
method = "rpartCost",
trControl = cctrl1,
preProc = c("center", "scale"),
tuneGrid = grid)
set.seed(849)
test_class_cv_form <- train(Class ~ ., data = training,
method = "rpartCost",
trControl = cctrl1,
preProc = c("center", "scale"))
test_class_pred <- predict(test_class_cv_model, testing[, -ncol(testing)])
test_class_pred_form <- predict(test_class_cv_form, testing[, -ncol(testing)])
set.seed(849)
test_class_rand <- train(trainX, trainY,
method = "rpartCost",
trControl = cctrlR,
tuneLength = 4)
set.seed(849)
test_class_loo_model <- train(trainX, trainY,
method = "rpartCost",
trControl = cctrl2,
preProc = c("center", "scale"))
set.seed(849)
test_class_none_model <- train(trainX, trainY,
method = "rpartCost",
trControl = cctrl3,
tuneGrid = test_class_cv_model$bestTune,
preProc = c("center", "scale"))
test_class_none_pred <- predict(test_class_none_model, testing[, -ncol(testing)])
set.seed(849)
test_class_rec <- train(x = rec_cls,
data = training,
method = "rpartCost",
trControl = cctrl1,
tuneGrid = grid)
if(
!isTRUE(
all.equal(test_class_cv_model$results,
test_class_rec$results))
)
stop("CV weights not giving the same results")
test_class_imp_rec <- varImp(test_class_rec)
test_class_pred_rec <- predict(test_class_rec, testing[, -ncol(testing)])
test_levels <- levels(test_class_cv_model)
if(!all(levels(trainY) %in% test_levels))
cat("wrong levels")
#########################################################################
test_class_imp <- varImp(test_class_cv_model)
#########################################################################
tests <- grep("test_", ls(), fixed = TRUE, value = TRUE)
sInfo <- sessionInfo()
timestamp_end <- Sys.time()
save(list = c(tests, "sInfo", "timestamp", "timestamp_end"),
file = file.path(getwd(), paste(model, ".RData", sep = "")))
if(!interactive())
q("no")
| {
"pile_set_name": "Github"
} |
<?xml version='1.0' encoding='utf-8'?>
<section xmlns="https://code.dccouncil.us/schemas/dc-library" xmlns:codified="https://code.dccouncil.us/schemas/codified" xmlns:codify="https://code.dccouncil.us/schemas/codify" xmlns:xi="http://www.w3.org/2001/XInclude" containing-doc="D.C. Code">
<num>29A-101.04</num>
<reason>Repealed</reason>
<heading>General powers.</heading>
<text>Repealed.</text>
<annotations>
<annotation type="History">June 8, 1954, 68 Stat. 180, ch. 269, § 4</annotation>
<annotation doc="Pub. L. 88-111" type="History">Sept. 3, 1963, 77 Stat. 136, Pub. L. 88-111, § 1(1)</annotation>
<annotation doc="D.C. Law 18-378" type="History">July 2, 2011, D.C. Law 18-378, § 3(j), 58 DCR 1720</annotation>
<annotation type="Prior Codifications">1973 Ed., § 29-904.</annotation>
<annotation type="Prior Codifications">1981 Ed., § 29-304.</annotation>
<annotation type="Prior Codifications">2001 Ed., § 29-101.04.</annotation>
</annotations>
</section>
| {
"pile_set_name": "Github"
} |
/***********************************************************************
*
* Copyright (C) 2014-2019 wereturtle
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
***********************************************************************/
#ifndef MAIN_WINDOW_H
#define MAIN_WINDOW_H
#include <QObject>
#include <QMainWindow>
#include <QWidget>
#include <QMenu>
#include <QAction>
#include <QLabel>
#include <QGraphicsColorizeEffect>
#include <QGraphicsDropShadowEffect>
#include "MarkdownEditor.h"
#include "HtmlPreview.h"
#include "ThemeFactory.h"
#include "HtmlPreview.h"
#include "AppSettings.h"
#include "TimeLabel.h"
#include "find_dialog.h"
#include "spelling/dictionary_manager.h"
#define MAX_RECENT_FILES 10
class HudWindow;
class QSettings;
class QFileSystemWatcher;
class QTextBrowser;
class QCheckBox;
class QListWidget;
class DocumentManager;
class Outline;
class DocumentStatistics;
class DocumentStatisticsWidget;
class SessionStatistics;
class SessionStatisticsWidget;
/**
* Main window for the application.
*/
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(const QString& filePath = QString(), QWidget* parent = 0);
virtual ~MainWindow();
protected:
QSize sizeHint() const;
void resizeEvent(QResizeEvent* event);
void moveEvent(QMoveEvent* event);
void keyPressEvent(QKeyEvent* e);
bool eventFilter(QObject* obj, QEvent* event);
void paintEvent(QPaintEvent* event);
void closeEvent(QCloseEvent* event);
private slots:
void quitApplication();
void changeTheme();
void showFindReplaceDialog();
void openPreferencesDialog();
void toggleHtmlPreview(bool checked);
void toggleHemingwayMode(bool checked);
void toggleFocusMode(bool checked);
void toggleFullScreen(bool checked);
void toggleHideMenuBarInFullScreen(bool checked);
void toggleOutlineAlternateRowColors(bool checked);
void toggleFileHistoryEnabled(bool checked);
void toggleDisplayTimeInFullScreen(bool checked);
void toggleDesktopCompositingEffects(bool checked);
void toggleOpenHudsVisibility();
void toggleOpenHudsVisibility(bool checked);
void changeHudButtonLayout(HudWindowButtonLayout layout);
void changeEditorWidth(EditorWidth editorWidth);
void changeInterfaceStyle(InterfaceStyle style);
void insertImage();
void showStyleSheetManager();
void showQuickReferenceGuide();
void showWikiPage();
void showOutlineHud();
void showCheatSheetHud();
void showDocumentStatisticsHud();
void showSessionStatisticsHud();
void onHideHudsOnPreviewChanged(bool enabled);
void onHudClosed();
void onTypingPaused();
void onTypingResumed();
void showAbout();
void updateWordCount(int newWordCount);
void changeFocusMode(FocusMode focusMode);
void applyTheme(const Theme& theme);
void openRecentFile();
void refreshRecentFiles();
void clearRecentFileHistory();
void changeDocumentDisplayName(const QString& displayName);
void onOperationStarted(const QString& description);
void onOperationFinished();
void changeFont();
void onFontSizeChanged(int size);
void onSetLocale();
void changeHudOpacity(int value);
void copyHtml();
void showPreviewOptions();
void onAboutToHideMenuBarMenu();
void onAboutToShowMenuBarMenu();
private:
MarkdownEditor* editor;
QSplitter* splitter;
DocumentManager* documentManager;
ThemeFactory* themeFactory;
Theme theme;
QString language;
QLabel* wordCountLabel;
QLabel* statusLabel;
TimeLabel* timeLabel;
QPushButton* previewOptionsButton;
QPushButton* exportButton;
QPushButton* copyHtmlButton;
QPushButton* hemingwayModeButton;
QPushButton* focusModeButton;
QPushButton* htmlPreviewButton;
QPushButton* hideOpenHudsButton;
FindDialog* findReplaceDialog;
HtmlPreview* htmlPreview;
QWebEngineView* quickReferenceGuideViewer;
QAction* htmlPreviewMenuAction;
QAction* fullScreenMenuAction;
QPushButton* fullScreenButton;
QGraphicsColorizeEffect* fullScreenButtonColorEffect;
HudWindow* outlineHud;
Outline* outlineWidget;
HudWindow* cheatSheetHud;
HudWindow* documentStatsHud;
HudWindow* sessionStatsHud;
QVector<HudWindow*> huds;
QVector<HudWindow*> openHuds;
QVector<QString> hudGeometryKeys;
QVector<QString> hudOpenKeys;
bool openHudsVisible;
QAction* hideOpenHudsAction;
DocumentStatistics* documentStats;
DocumentStatisticsWidget* documentStatsWidget;
SessionStatistics* sessionStats;
SessionStatisticsWidget* sessionStatsWidget;
QListWidget* cheatSheetWidget;
QPixmap originalBackgroundImage;
QPixmap adjustedBackgroundImage;
QFileSystemWatcher* fileWatcher;
QAction* recentFilesActions[MAX_RECENT_FILES];
int menuBarHeight;
QPoint lastMousePos;
bool menuBarMenuActivated;
QList<QWidget*> statusBarButtons;
QList<QWidget*> statusBarWidgets;
Exporter* exporter;
QThread* exporterThread;
AppSettings* appSettings;
QAction* addMenuAction
(
QMenu* menu,
const QString& name,
const QString& shortcut = 0,
bool checkable = false,
bool checked = false,
QActionGroup* actionGroup = 0
);
HudWindow* createHudWindow
(
const QString& title,
QWidget* centralWidget,
const QString& geometrySettingsKey,
const QString& openSettingsKey
);
void buildMenuBar();
void buildStatusBar();
void showHud(HudWindow* hud);
void adjustEditorWidth(int width);
void applyStatusBarStyle();
void applyTheme();
void predrawBackgroundImage();
void showMenuBar();
void hideMenuBar();
bool isMenuBarVisible() const;
void setOpenHudsVisibility(bool visible);
};
#endif
| {
"pile_set_name": "Github"
} |
### 一桩案件揭中共军方利用美大学进行秘密研究
------------------------
#### [首页](https://github.com/gfw-breaker/banned-news/blob/master/README.md) | [手把手翻墙教程](https://github.com/gfw-breaker/guides/wiki) | [禁闻聚合安卓版](https://github.com/gfw-breaker/bn-android) | [网门安卓版](https://github.com/oGate2/oGate) | [神州正道安卓版](https://github.com/SzzdOgate/update)
<div><img alt="" class="aligncenter wp-post-image" src="https://i.epochtimes.com/assets/uploads/2013/10/1310161022522320-600x400.jpg"/>
<div class="red16 caption">
从美国国防部到美国国立卫生研究院等一系列美国机构,已经对北京企图利用美国大学专业知识,来增强中共军事和技术竞争力的举动感到震惊。(Feng Li/Getty Images)
</div>
</div><hr/>
#### [翻墙必看视频(文昭、江峰、法轮功、八九六四、香港反送中...)](https://github.com/gfw-breaker/banned-news/blob/master/pages/link3.md)
<div><p>
【大纪元2020年02月24日讯】(大纪元记者苏静好综合报导)美国波士顿大学一名中国访问学者被美国司法部起诉的案件,再次引发各界关注中共军方利用美国大学和研究机构,获取先进技术进行秘密研究的事实。
</p>
<p>
在中国学者委员会的资助下,中共军方中尉叶燕青(Yanqing Ye,音译)申请到波士顿大学高分子研究所的物理、化学和生物医学工程中心进行深造。她被指控在申请美国签证时,对美国政府隐瞒其军方身份,同时利用J-1访问学者身份在美从事外国代理人事务,将敏感军事信息发给她在中国国内的军方同伙。
</p>
<p>
《华尔街日报》2月23日报导,这个案件表明美国大学对尖端研究的国际合作持开放态度,使它们成为中共潜在的目标。
</p>
<p>
叶燕青向波士顿大学注明物理学家尤金‧斯坦利(Eugene Stanley)申请深造机会。斯坦利的广泛研究包括使用人工智能对金融市场进行解码,并运用统计物理学来预防疾病。他说:“我对政治一点都不感兴趣。我是一位科学家。”
</p>
<p>
从美国国防部到美国国立卫生研究院等一系列美国机构,已经对北京企图利用美国大学专业知识,来增强中共军事和技术竞争力的举动感到震惊。
</p>
<h4>
中共军方研究人员隐瞒身份 进入美国实验室
</h4>
<p>
美国官员指责中共以学术界为目标,包括将中共军事研究人员派往美国实验室,并使用人才招聘计划吸引顶尖科学家、企业家和专家窃取美国知识产权。
</p>
<p>
波士顿联邦检察官上个月提起迄今为止最引人注目的中共招聘案,检察官指控哈佛大学化学系主任通过中共“千人计划”获得数百万美元资金。根据起诉书,尚未认罪的查尔斯‧利伯(Charles Lieber)教授签署了一项为期五年的协议,就电动汽车电池技术进行研究,而中共希望在这个领域成为全球主导。
</p>
<p>
德克萨斯农工大学系统官员进行的一项审查发现,学校中有一百多名教师参与了中共人才招聘计划,只有五名透露了自己参与的信息。
</p>
<p>
澳大利亚政府支持的无党派智囊机构澳大利亚战略政策研究所(Australian Strategic Policy Institute)2018年的一份报告表示,尽管有开放交流的承诺,但大学在与中共军方(PLA)合作方面需要慎重。
</p>
<p>
研究人员亚历克斯‧约斯克(Alex Joske)在报告中说:“帮助竞争对手发展其专业知识和技术并不符合国家利益。”他发现,在过去十年中,中共军方赞助了2500多名科学家和工程师前往国外学习,而他们深造的学校不了解这些人与中共军方的隶属关系。
</p>
<h4>
<ok href="https://www.epochtimes.com/gb/tag/%E5%9B%BD%E9%98%B2%E7%A7%91%E5%A4%A7.html">
国防科大
</ok>
上美黑名单 叶燕青案是冰山一角
</h4>
<p>
美国调查人员发现,今年29岁的叶燕青是中共军方中尉,也是中国共产党党员。起诉书称,在申请用于学术交流的J-1签证时,她说自己是中国国防科技大学的学生,没有透露自己是中共中尉。在2017年到2019年在波士顿大学深造时,叶还执行她的中共军方同事分配的任务。
</p>
<p>
美国联邦调查局1月底对叶燕青发布了“通缉令”海报,称她很可能回到中国。
</p>
<p>
《华日》报导,斯坦利说,他对叶的指控“完全不知所措”。他说他不太记得叶,但在他的档案中发现了2016年一篇关于机器学习的论文,是斯坦利和叶燕青,以及叶在波士顿实验室工作之前的同事合著的。其中一合著者是叶在
<ok href="https://www.epochtimes.com/gb/tag/%E5%9B%BD%E9%98%B2%E7%A7%91%E5%A4%A7.html">
国防科大
</ok>
的同事杨科伟(Kewei Yang,音译),杨是中共军方上校。
</p>
<p>
机器学习具有一系列民用和军事应用。
</p>
<p>
杨上校在起诉书中被标志为“同谋A”,他被指控在叶燕青在波士顿大学期间指导她。他没有回应《华日》置评请求。在论文中,他与叶和斯坦利先生合写了书,他们的隶属关系都列为国防科技大学。
</p>
<p>
2015年,美国商务部将中国国防科技大学(NUDT,简称国防科大)列入“实体名单”,“因为它使用美国原产的多核电路板,以及(辅助)处理器,研发超级计算机,这些超级计算机是为了支持核爆炸模拟和军事模拟活动。”
</p>
<p>
在2018年一份追加起诉书中,马萨诸塞州检察官指控一名非法出口美国海洋技术的被告,而国防大学是被告的最大客户。
</p>
<p>
澳大利亚战略政策研究所报告显示,中共军方科学家与国外学者共同发表论文的数量大幅度增加,由2007年的95篇增加到2017年的734篇。这份调查报告的作者乔斯克(Alex Joske)2018年发表报告时表示,在过去10年中,美国大学接收了大约500名来自隶属于与中共军队相关大学的访问学者。
</p>
<h4>
美国会和政府已警觉 大学和研究机构也要承担责任
</h4>
<p>
司法部官员去年4月表示,多家大学和公司拥有敏感的知识产权,“波士顿是
<ok href="https://www.epochtimes.com/gb/tag/%E4%B8%AD%E5%85%B1%E9%97%B4%E8%B0%8D.html">
中共间谍
</ok>
活动的重点目标”。
</p>
<p>
《华日》报导,波士顿学校数据显示,在截至2019年6月30日财年中,波士顿大学接待了来自96个国家/地区的1,294名国际学者,其中中国为第一大来源。该校发言人说,在过去一年中,学校管理人员已经对教师进行了有关美国政府对外国影响关注的教育,政策审查委员会也提出建议,这些建议正在得到执行。
</p>
<p>
美国国务院发言人拒绝讨论具体案件,但表示《移民和国籍法》对拒绝签证的授权有限。发言人说,目前,如果领事馆官员认为申请人可能打算出口美国政府控制清单上的技术,他们可能会出于国家安全原因拒绝签证。
</p>
<p>
从2018年6月11日起,美国国务院将把在某些敏感研究领域学习的中国研究生的签证时效缩短至1年,中国留美研究生需要每年重新申请签证。被列入签证紧缩的留学领域,都属于“中国制造2025”计划中的重要产业。
</p>
<p>
美国官员表示,此举目的是降低在美国国家安全至关重要的领域发生间谍活动和盗窃知识产权的风险。
</p>
<p>
去年12月,参议院常驻调查小组委员会主席、俄亥俄州共和党参议员罗伯‧波特曼(Rob Portman)在一份声明中说:“中国(中共)获利两次,首先,美国纳税人为中国的研究与发展提供资金;其次,中共利用这些研究来提高其经济和军事地位。”
</p>
<p>
参议院还在去年11月发布一份调查报告时指出,美国大学和研究机构必须对此问题承担一些责任。他表示,大学可以对员工进行严格的科学审查或偷窃指控,也可以对财务利益冲突和外国资金来源进行审查。
</p>
<p>
他还表示计划与白宫、国家研究机构、大学和国务院合作制定立法解决方案,以保护用美国纳税人的钱所支持的研究。
</p>
<p>
责任编辑:叶紫微 #
</p>
</div>
<hr/>
手机上长按并复制下列链接或二维码分享本文章:<br/>
https://github.com/gfw-breaker/banned-news/blob/master/pages/nf4514/n11891206.md <br/>
<a href='https://github.com/gfw-breaker/banned-news/blob/master/pages/nf4514/n11891206.md'><img src='https://github.com/gfw-breaker/banned-news/blob/master/pages/nf4514/n11891206.md.png'/></a> <br/>
原文地址(需翻墙访问):https://www.epochtimes.com/gb/20/2/24/n11891206.htm
------------------------
#### [首页](https://github.com/gfw-breaker/banned-news/blob/master/README.md) | [一键翻墙软件](https://github.com/gfw-breaker/nogfw/blob/master/README.md) | [《九评共产党》](https://github.com/gfw-breaker/9ping.md/blob/master/README.md#九评之一评共产党是什么) | [《解体党文化》](https://github.com/gfw-breaker/jtdwh.md/blob/master/README.md) | [《共产主义的终极目的》](https://github.com/gfw-breaker/gczydzjmd.md/blob/master/README.md)
<img src='http://gfw-breaker.win/banned-news/pages/nf4514/n11891206.md' width='0px' height='0px'/> | {
"pile_set_name": "Github"
} |
-- boundary4.test
--
-- db eval {
-- SELECT rowid, a, x FROM t1 ORDER BY x
-- }
SELECT rowid, a, x FROM t1 ORDER BY x | {
"pile_set_name": "Github"
} |
{
"Format" : "EPS",
"Orientaion" : "Top, left side (Horizontal / normal)",
"DPIWidth" : "101",
"DPIHeight" : "101",
"PixelWidth" : "275",
"PixelHeight" : "207",
"BitsPerPixel" : "24",
"ColorMode" : "RGB",
"HasAlpha" : "false",
"Duration" : "00:00:00",
"VideoCodec" : "Unknown",
"FrameRate" : "0",
"AudioCodec" : "Unknown",
"AudioSampleSize" : "0",
"AudioSampleRate" : "0",
"FileType" : {
"DetectedFileTypeName" : "EPS",
"DetectedFileTypeLongName" : "Encapsulated PostScript",
"DetectedMIMEType" : "application/postscript",
"ExpectedFileNameExtension" : "eps"
},
"ExifIFD0" : {
"ImageWidth" : "275 pixels",
"ImageHeight" : "207 pixels",
"BitsPerSample" : "8 8 8 bits/component/pixel",
"PhotometricInterpretation" : "RGB",
"Orientation" : "Top, left side (Horizontal / normal)",
"SamplesPerPixel" : "3 samples/pixel",
"XResolution" : "101 dots per inch",
"YResolution" : "101 dots per inch",
"ResolutionUnit" : "Inch",
"Software" : "Adobe Photoshop CC 2017 (Macintosh)",
"DateTime" : "2017:08:16 12:24:54",
"Copyright" : "1999 Lars Borg"
},
"ExifSubIFD" : {
"ExifVersion" : "2.21",
"ColorSpace" : "Undefined",
"ExifImageWidth" : "275 pixels",
"ExifImageHeight" : "207 pixels"
},
"ExifThumbnail" : {
"Compression" : "JPEG (old-style)",
"XResolution" : "72 dots per inch",
"YResolution" : "72 dots per inch",
"ResolutionUnit" : "Inch",
"ThumbnailOffset" : "414 bytes",
"ThumbnailLength" : "0 bytes"
},
"ICCProfile" : {
"ProfileSize" : "532",
"CMMType" : "ADBE",
"Version" : "2.1.0",
"Class" : "Display Device",
"ColorSpace" : "RGB ",
"ProfileConnectionSpace" : "XYZ ",
"ProfileDateTime" : "1999:04:05 15:08:05",
"Signature" : "acsp",
"PrimaryPlatform" : "Apple Computer, Inc.",
"DeviceManufacturer" : "none",
"RenderingIntent" : "Media-Relative Colorimetric",
"XYZValues" : "0.964 1 0.825",
"TagCount" : "10",
"Copyright" : "(c) 1999 Adobe Systems Inc.",
"ProfileDescription" : "GBR",
"MediaWhitePoint" : "(0.9505, 1, 1.0891)",
"MediaBlackPoint" : "(0, 0, 0)",
"RedTRC" : "0.0085908",
"GreenTRC" : "0.0085908",
"BlueTRC" : "0.0085908",
"RedColorant" : "(0.3851, 0.7169, 0.0971)",
"GreenColorant" : "(0.1431, 0.0606, 0.7139)",
"BlueColorant" : "(0.436, 0.2225, 0.0139)"
},
"IPTC": {
"CodedCharacterSet" : "UTF-8",
"ApplicationRecordVersion" : "2",
"CopyrightNotice" : "1999 Lars Borg"
},
"Photoshop" : {
"CaptionDigest" : "218 119 165 163 16 30 63 186 160 177 8 58 1 54 252 149",
"PrintInfo2" : "[229 values]",
"PrintStyle" : "[557 values]",
"ResolutionInfo" : "101x101 DPI",
"PrintScale" : "Centered, Scale 1.0",
"GlobalAngle" : "30",
"GlobalAltitude" : "30",
"PrintFlags" : "0 0 0 0 0 0 0 0 1",
"CopyrightFlag" : "Yes",
"PrintFlagsInformation" : "0 1 0 0 0 0 0 0 0 1",
"ColorHalftoningInformation" : "[72 values]",
"ColorTransferFunctions" : "[112 values]",
"GridAndGuidesInformation" : "0 0 0 1 0 0 2 64 0 0 2 64 0 0 0 0",
"URLList" : "0",
"Slices" : " (0,0,207,275) 1 Slices",
"PixelAspectRatio" : "1.0",
"SeedNumber" : "1",
"ThumbnailData" : "JpegRGB, 159x120, Decomp 57600 bytes, 1572865 bpp, 8151 bytes",
"VersionInfo" : "1 (Adobe Photoshop, Adobe Photoshop CC 2017) 1",
"EPSOptions" : "1 1 0 0 0 0 0 0"
},
"EPS" : {
"TIFFPreviewSize" : "41802 bytes",
"TIFFPreviewOffset" : "30 bytes",
"Creator" : "Adobe Photoshop Version 2017.1.1 20170425.r.252 2017/04/25:23:00:00 CL 1113967",
"Title" : "adobeJpeg1.eps",
"CreationDate" : "8/16/17 12:24 PM",
"BoundingBox" : "0 0 196 148",
"ImageData" : "275 207 8 3 0 1 3 \"beginimage\"",
"ImageWidth" : "275 pixels",
"ImageHeight" : "207 pixels",
"ColorType" : "RGB",
"RamSize" : "170775"
}
}
| {
"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.
*/
package org.apache.camel.component.log;
import java.util.Locale;
import java.util.Map;
import org.apache.camel.Endpoint;
import org.apache.camel.LoggingLevel;
import org.apache.camel.spi.CamelLogger;
import org.apache.camel.spi.ExchangeFormatter;
import org.apache.camel.spi.Metadata;
import org.apache.camel.support.DefaultComponent;
import org.apache.camel.support.processor.DefaultExchangeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The <a href="http://camel.apache.org/log.html">Log Component</a> is for logging message exchanges via the underlying
* logging mechanism.
*/
@org.apache.camel.spi.annotations.Component("log")
public class LogComponent extends DefaultComponent {
private static final Logger LOG = LoggerFactory.getLogger(LogComponent.class);
@Metadata(label = "advanced")
private ExchangeFormatter exchangeFormatter;
public LogComponent() {
}
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
LoggingLevel level = getLoggingLevel(parameters);
Logger providedLogger = getLogger(parameters);
if (providedLogger == null) {
// try to look up the logger in registry
Map<String, Logger> availableLoggers = getCamelContext().getRegistry().findByTypeWithName(Logger.class);
if (availableLoggers.size() == 1) {
providedLogger = availableLoggers.values().iterator().next();
LOG.info("Using custom Logger: {}", providedLogger);
} else if (availableLoggers.size() > 1) {
LOG.info("More than one {} instance found in the registry. Falling back to creating logger from URI {}.",
Logger.class.getName(), uri);
}
}
// first, try to pick up the ExchangeFormatter from the registry
ExchangeFormatter logFormatter
= getCamelContext().getRegistry().lookupByNameAndType("logFormatter", ExchangeFormatter.class);
if (logFormatter != null) {
setProperties(logFormatter, parameters);
} else if (exchangeFormatter != null) {
// do not set properties, the exchangeFormatter is explicitly set, therefore the
// user would have set its properties explicitly too
logFormatter = exchangeFormatter;
}
LogEndpoint endpoint = new LogEndpoint(uri, this);
endpoint.setLevel(level.name());
endpoint.setExchangeFormatter(logFormatter);
if (providedLogger == null) {
endpoint.setLoggerName(remaining);
} else {
endpoint.setProvidedLogger(providedLogger);
}
setProperties(endpoint, parameters);
return endpoint;
}
/**
* Gets the logging level, will default to use INFO if no level parameter provided.
*/
protected LoggingLevel getLoggingLevel(Map<String, Object> parameters) {
String levelText = getAndRemoveParameter(parameters, "level", String.class, "INFO");
return LoggingLevel.valueOf(levelText.toUpperCase(Locale.ENGLISH));
}
/**
* Gets optional {@link Logger} instance from parameters. If non-null, the provided instance will be used as
* {@link Logger} in {@link CamelLogger}
*
* @param parameters the parameters
* @return the Logger object from the parameter
*/
protected Logger getLogger(Map<String, Object> parameters) {
return getAndRemoveOrResolveReferenceParameter(parameters, "logger", Logger.class);
}
public ExchangeFormatter getExchangeFormatter() {
return exchangeFormatter;
}
/**
* Sets a custom {@link ExchangeFormatter} to convert the Exchange to a String suitable for logging. If not
* specified, we default to {@link DefaultExchangeFormatter}.
*/
public void setExchangeFormatter(ExchangeFormatter exchangeFormatter) {
this.exchangeFormatter = exchangeFormatter;
}
}
| {
"pile_set_name": "Github"
} |
#ifndef CROPRPC
#define CROPRPC
#include <QWidget>
#include <QMenuBar>
#include <QLineEdit>
#include <QLayout>
#include <QToolBar>
#include <QFormLayout>
#include <QDockWidget>
#include <QTextEdit>
#include <QListWidget>
#include <QLabel>
#include <QTreeWidget>
#include <QTreeWidgetItem>
#include <QFileSystemModel>
#include <iostream>
#include <QModelIndex>
#include <QStringListModel>
#include <stdio.h>
#include <dirent.h>
#include <regex.h>
#include <string>
#include <QDebug>
#include <QDirModel>
#include <QLCDNumber>
#include <QSlider>
#include <QDockWidget>
#include <QPushButton>
#include <QMainWindow>
#include <QButtonGroup>
#include <QProcess>
#include "MainWindow.h"
#include "NewProject.h"
#include "CropRPC.h"
#include "Console.h"
class CropRPC : public QWidget
{
Q_OBJECT
public:
CropRPC(QList <QString>, QList <QString>, QString);
QList<QString> listImages;
QMessageBox msgBox2;
QString msg1();
QDialog qDi;
signals:
void signal_a();
public slots:
void mm3d();
void stopped();
void oriSearch();
void oriSearch1();
QString getTxt();
void msg();
void readyReadStandardOutput();
private:
QButtonGroup *modeGroupBox;
QCheckBox* imagesCheckBox;
QList<QCheckBox*> listeCasesImages;
Console cons;
QString sendCons;
QTextEdit *rPC;
QFileInfo fichier;
QTextEdit *Qtr ;
QRadioButton *mulScale;
QRadioButton *all;
QRadioButton *line;
QRadioButton *file;
QRadioButton *graph;
QRadioButton *georeph;
QMessageBox msgBox;
QTextEdit *qtt ;
std::string mode;
std::string images;
QTextEdit *regularE;
QVBoxLayout *boxLayoutV ;
QVBoxLayout *boxLayoutVOp ;
QLabel *ql;
QLabel *oriFileCrop;
QLabel *directoryOutput;
QLabel *labelOptions;
QTextEdit *oriFileCropTxt;
QTextEdit *directoryOutputTxt;
QTextEdit *patternTxt;
std::string oriFileCropTxt_str;
std::string directoryOutputTxt_str;
std::string patternTxt_str;
QCheckBox* boxTxt;
std::string txt;
std::string cmd;
std::string path_s;
QString p_stdout;
QProcess p;
std::string recup;
QString aPath;
QTextEdit *SzQt;
QTextEdit *SzQt2;
QTextEdit *OrgQt;
QTextEdit *OrgQt2;
std::string SzVar;
std::string OrgVar;
};
#endif // CROPRPC
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2002-2020 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* 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 org.neo4j.ogm.persistence.types.nativetypes;
import static org.assertj.core.api.Assertions.*;
import java.util.Arrays;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.neo4j.ogm.session.Session;
import org.neo4j.ogm.session.SessionFactory;
import org.neo4j.ogm.testutil.TestContainersTestBase;
import org.neo4j.ogm.types.spatial.CartesianPoint2d;
import org.neo4j.ogm.types.spatial.CartesianPoint3d;
import org.neo4j.ogm.types.spatial.GeographicPoint2d;
import org.neo4j.ogm.types.spatial.GeographicPoint3d;
/**
* @author Gerrit Meier
* @author Michael J. Simons
*/
public abstract class SpatialTestBase extends TestContainersTestBase {
static SessionFactory sessionFactory;
@Before
public void clearDatabase() {
sessionFactory.openSession().purgeDatabase();
}
@AfterClass
public static void shutDown() {
if (sessionFactory != null) {
sessionFactory.close();
}
}
@Test
public void convertPersistAndLoadGeographicPoint2d() {
Session session = sessionFactory.openSession();
SomethingSpatial spatial = new SomethingSpatial();
GeographicPoint2d point = new GeographicPoint2d(1, 2);
spatial.setGeographicPoint2d(point);
session.save(spatial);
session.clear();
SomethingSpatial loaded = session.load(SomethingSpatial.class, spatial.getId());
assertThat(loaded.getGeographicPoint2d()).isEqualTo(point);
}
@Test
public void convertPersistAndLoadGeographicPoint3d() {
Session session = sessionFactory.openSession();
SomethingSpatial spatial = new SomethingSpatial();
GeographicPoint3d point = new GeographicPoint3d(1, 2, 3);
spatial.setGeographicPoint3d(point);
session.save(spatial);
session.clear();
SomethingSpatial loaded = session.load(SomethingSpatial.class, spatial.getId());
assertThat(loaded.getGeographicPoint3d()).isEqualTo(point);
}
@Test
public void convertPersistAndLoadCartesianPoint2d() {
Session session = sessionFactory.openSession();
SomethingSpatial spatial = new SomethingSpatial();
CartesianPoint2d point = new CartesianPoint2d(1, 2);
spatial.setCartesianPoint2d(point);
session.save(spatial);
session.clear();
SomethingSpatial loaded = session.load(SomethingSpatial.class, spatial.getId());
assertThat(loaded.getCartesianPoint2d()).isEqualTo(point);
}
@Test
public void convertPersistAndLoadCartesianPoint3d() {
Session session = sessionFactory.openSession();
SomethingSpatial spatial = new SomethingSpatial();
CartesianPoint3d point = new CartesianPoint3d(1, 2, 3);
spatial.setCartesianPoint3d(point);
session.save(spatial);
session.clear();
SomethingSpatial loaded = session.load(SomethingSpatial.class, spatial.getId());
assertThat(loaded.getCartesianPoint3d()).isEqualTo(point);
}
@Test
public void convertPersistAndLoadGeographicPoint2dForRelationship() {
Session session = sessionFactory.openSession();
SomethingRelationship somethingRelated = new SomethingRelationship();
GeographicPoint2d point = new GeographicPoint2d(1, 2);
somethingRelated.setGeographicPoint2d(point);
session.save(somethingRelated);
session.clear();
SomethingRelationship loaded = session.load(SomethingRelationship.class, somethingRelated.getId());
assertThat(loaded.getGeographicPoint2d()).isEqualTo(point);
}
@Test
public void convertPersistAndLoadGeographicPoint3dForRelationship() {
Session session = sessionFactory.openSession();
SomethingRelationship somethingRelated = new SomethingRelationship();
GeographicPoint3d point = new GeographicPoint3d(1, 2, 3);
somethingRelated.setGeographicPoint3d(point);
session.save(somethingRelated);
session.clear();
SomethingRelationship loaded = session.load(SomethingRelationship.class, somethingRelated.getId());
assertThat(loaded.getGeographicPoint3d()).isEqualTo(point);
}
@Test
public void convertPersistAndLoadCartesianPoint2dForRelationship() {
Session session = sessionFactory.openSession();
SomethingRelationship somethingRelated = new SomethingRelationship();
CartesianPoint2d point = new CartesianPoint2d(1, 2);
somethingRelated.setCartesianPoint2d(point);
session.save(somethingRelated);
session.clear();
SomethingRelationship loaded = session.load(SomethingRelationship.class, somethingRelated.getId());
assertThat(loaded.getCartesianPoint2d()).isEqualTo(point);
}
@Test
public void convertPersistAndLoadCartesianPoint3dForRelationship() {
Session session = sessionFactory.openSession();
SomethingRelationship somethingRelated = new SomethingRelationship();
CartesianPoint3d point = new CartesianPoint3d(1, 2, 3);
somethingRelated.setCartesianPoint3d(point);
session.save(somethingRelated);
session.clear();
SomethingRelationship loaded = session.load(SomethingRelationship.class, somethingRelated.getId());
assertThat(loaded.getCartesianPoint3d()).isEqualTo(point);
}
@Test
public void collectionsOfPointsShouldWork() {
Session session = sessionFactory.openSession();
SomethingSpatial spatial = new SomethingSpatial();
spatial.setArrayOfPoints(
new GeographicPoint2d[] { new GeographicPoint2d(55.0, 13), new GeographicPoint2d(56.0, 14.0) });
spatial.setListOfPoints(Arrays.asList(new GeographicPoint2d(50.0, 6.0), new GeographicPoint2d(51, 7.0)));
session.save(spatial);
session.clear();
SomethingSpatial loaded = session.load(SomethingSpatial.class, spatial.getId());
assertThat(loaded.getArrayOfPoints()).hasSize(2).extracting(GeographicPoint2d::getLatitude)
.containsExactlyInAnyOrder(55.0, 56.0);
assertThat(loaded.getListOfPoints()).hasSize(2).extracting(GeographicPoint2d::getLatitude)
.containsExactlyInAnyOrder(50.0, 51.0);
}
@Test
public void spatialObjectsInMapsShouldWork() {
Session session = sessionFactory.openSession();
SomethingSpatial spatial = new SomethingSpatial();
GeographicPoint2d geographicPoint2d = new GeographicPoint2d(1, 2);
GeographicPoint3d geographicPoint3d = new GeographicPoint3d(1, 2, 3);
CartesianPoint2d cartesianPoint2d = new CartesianPoint2d(1, 2);
CartesianPoint3d cartesianPoint3d = new CartesianPoint3d(1, 2, 3);
spatial.addProperty("geographicPoint2d", geographicPoint2d);
spatial.addProperty("geographicPoint3d", geographicPoint3d);
spatial.addProperty("cartesianPoint2d", cartesianPoint2d);
spatial.addProperty("cartesianPoint3d", cartesianPoint3d);
session.save(spatial);
session.clear();
SomethingSpatial loaded = session.load(SomethingSpatial.class, spatial.getId());
assertThat(loaded.getProperties()).containsEntry("geographicPoint2d", geographicPoint2d);
assertThat(loaded.getProperties()).containsEntry("geographicPoint3d", geographicPoint3d);
assertThat(loaded.getProperties()).containsEntry("cartesianPoint2d", cartesianPoint2d);
assertThat(loaded.getProperties()).containsEntry("cartesianPoint3d", cartesianPoint3d);
}
}
| {
"pile_set_name": "Github"
} |
tinyMCEPopup.requireLangPack();
var detail = 50, strhex = "0123456789abcdef", i, isMouseDown = false, isMouseOver = false;
var colors = [
"#000000","#000033","#000066","#000099","#0000cc","#0000ff","#330000","#330033",
"#330066","#330099","#3300cc","#3300ff","#660000","#660033","#660066","#660099",
"#6600cc","#6600ff","#990000","#990033","#990066","#990099","#9900cc","#9900ff",
"#cc0000","#cc0033","#cc0066","#cc0099","#cc00cc","#cc00ff","#ff0000","#ff0033",
"#ff0066","#ff0099","#ff00cc","#ff00ff","#003300","#003333","#003366","#003399",
"#0033cc","#0033ff","#333300","#333333","#333366","#333399","#3333cc","#3333ff",
"#663300","#663333","#663366","#663399","#6633cc","#6633ff","#993300","#993333",
"#993366","#993399","#9933cc","#9933ff","#cc3300","#cc3333","#cc3366","#cc3399",
"#cc33cc","#cc33ff","#ff3300","#ff3333","#ff3366","#ff3399","#ff33cc","#ff33ff",
"#006600","#006633","#006666","#006699","#0066cc","#0066ff","#336600","#336633",
"#336666","#336699","#3366cc","#3366ff","#666600","#666633","#666666","#666699",
"#6666cc","#6666ff","#996600","#996633","#996666","#996699","#9966cc","#9966ff",
"#cc6600","#cc6633","#cc6666","#cc6699","#cc66cc","#cc66ff","#ff6600","#ff6633",
"#ff6666","#ff6699","#ff66cc","#ff66ff","#009900","#009933","#009966","#009999",
"#0099cc","#0099ff","#339900","#339933","#339966","#339999","#3399cc","#3399ff",
"#669900","#669933","#669966","#669999","#6699cc","#6699ff","#999900","#999933",
"#999966","#999999","#9999cc","#9999ff","#cc9900","#cc9933","#cc9966","#cc9999",
"#cc99cc","#cc99ff","#ff9900","#ff9933","#ff9966","#ff9999","#ff99cc","#ff99ff",
"#00cc00","#00cc33","#00cc66","#00cc99","#00cccc","#00ccff","#33cc00","#33cc33",
"#33cc66","#33cc99","#33cccc","#33ccff","#66cc00","#66cc33","#66cc66","#66cc99",
"#66cccc","#66ccff","#99cc00","#99cc33","#99cc66","#99cc99","#99cccc","#99ccff",
"#cccc00","#cccc33","#cccc66","#cccc99","#cccccc","#ccccff","#ffcc00","#ffcc33",
"#ffcc66","#ffcc99","#ffcccc","#ffccff","#00ff00","#00ff33","#00ff66","#00ff99",
"#00ffcc","#00ffff","#33ff00","#33ff33","#33ff66","#33ff99","#33ffcc","#33ffff",
"#66ff00","#66ff33","#66ff66","#66ff99","#66ffcc","#66ffff","#99ff00","#99ff33",
"#99ff66","#99ff99","#99ffcc","#99ffff","#ccff00","#ccff33","#ccff66","#ccff99",
"#ccffcc","#ccffff","#ffff00","#ffff33","#ffff66","#ffff99","#ffffcc","#ffffff"
];
var named = {
'#F0F8FF':'Alice Blue','#FAEBD7':'Antique White','#00FFFF':'Aqua','#7FFFD4':'Aquamarine','#F0FFFF':'Azure','#F5F5DC':'Beige',
'#FFE4C4':'Bisque','#000000':'Black','#FFEBCD':'Blanched Almond','#0000FF':'Blue','#8A2BE2':'Blue Violet','#A52A2A':'Brown',
'#DEB887':'Burly Wood','#5F9EA0':'Cadet Blue','#7FFF00':'Chartreuse','#D2691E':'Chocolate','#FF7F50':'Coral','#6495ED':'Cornflower Blue',
'#FFF8DC':'Cornsilk','#DC143C':'Crimson','#00FFFF':'Cyan','#00008B':'Dark Blue','#008B8B':'Dark Cyan','#B8860B':'Dark Golden Rod',
'#A9A9A9':'Dark Gray','#A9A9A9':'Dark Grey','#006400':'Dark Green','#BDB76B':'Dark Khaki','#8B008B':'Dark Magenta','#556B2F':'Dark Olive Green',
'#FF8C00':'Darkorange','#9932CC':'Dark Orchid','#8B0000':'Dark Red','#E9967A':'Dark Salmon','#8FBC8F':'Dark Sea Green','#483D8B':'Dark Slate Blue',
'#2F4F4F':'Dark Slate Gray','#2F4F4F':'Dark Slate Grey','#00CED1':'Dark Turquoise','#9400D3':'Dark Violet','#FF1493':'Deep Pink','#00BFFF':'Deep Sky Blue',
'#696969':'Dim Gray','#696969':'Dim Grey','#1E90FF':'Dodger Blue','#B22222':'Fire Brick','#FFFAF0':'Floral White','#228B22':'Forest Green',
'#FF00FF':'Fuchsia','#DCDCDC':'Gainsboro','#F8F8FF':'Ghost White','#FFD700':'Gold','#DAA520':'Golden Rod','#808080':'Gray','#808080':'Grey',
'#008000':'Green','#ADFF2F':'Green Yellow','#F0FFF0':'Honey Dew','#FF69B4':'Hot Pink','#CD5C5C':'Indian Red','#4B0082':'Indigo','#FFFFF0':'Ivory',
'#F0E68C':'Khaki','#E6E6FA':'Lavender','#FFF0F5':'Lavender Blush','#7CFC00':'Lawn Green','#FFFACD':'Lemon Chiffon','#ADD8E6':'Light Blue',
'#F08080':'Light Coral','#E0FFFF':'Light Cyan','#FAFAD2':'Light Golden Rod Yellow','#D3D3D3':'Light Gray','#D3D3D3':'Light Grey','#90EE90':'Light Green',
'#FFB6C1':'Light Pink','#FFA07A':'Light Salmon','#20B2AA':'Light Sea Green','#87CEFA':'Light Sky Blue','#778899':'Light Slate Gray','#778899':'Light Slate Grey',
'#B0C4DE':'Light Steel Blue','#FFFFE0':'Light Yellow','#00FF00':'Lime','#32CD32':'Lime Green','#FAF0E6':'Linen','#FF00FF':'Magenta','#800000':'Maroon',
'#66CDAA':'Medium Aqua Marine','#0000CD':'Medium Blue','#BA55D3':'Medium Orchid','#9370D8':'Medium Purple','#3CB371':'Medium Sea Green','#7B68EE':'Medium Slate Blue',
'#00FA9A':'Medium Spring Green','#48D1CC':'Medium Turquoise','#C71585':'Medium Violet Red','#191970':'Midnight Blue','#F5FFFA':'Mint Cream','#FFE4E1':'Misty Rose','#FFE4B5':'Moccasin',
'#FFDEAD':'Navajo White','#000080':'Navy','#FDF5E6':'Old Lace','#808000':'Olive','#6B8E23':'Olive Drab','#FFA500':'Orange','#FF4500':'Orange Red','#DA70D6':'Orchid',
'#EEE8AA':'Pale Golden Rod','#98FB98':'Pale Green','#AFEEEE':'Pale Turquoise','#D87093':'Pale Violet Red','#FFEFD5':'Papaya Whip','#FFDAB9':'Peach Puff',
'#CD853F':'Peru','#FFC0CB':'Pink','#DDA0DD':'Plum','#B0E0E6':'Powder Blue','#800080':'Purple','#FF0000':'Red','#BC8F8F':'Rosy Brown','#4169E1':'Royal Blue',
'#8B4513':'Saddle Brown','#FA8072':'Salmon','#F4A460':'Sandy Brown','#2E8B57':'Sea Green','#FFF5EE':'Sea Shell','#A0522D':'Sienna','#C0C0C0':'Silver',
'#87CEEB':'Sky Blue','#6A5ACD':'Slate Blue','#708090':'Slate Gray','#708090':'Slate Grey','#FFFAFA':'Snow','#00FF7F':'Spring Green',
'#4682B4':'Steel Blue','#D2B48C':'Tan','#008080':'Teal','#D8BFD8':'Thistle','#FF6347':'Tomato','#40E0D0':'Turquoise','#EE82EE':'Violet',
'#F5DEB3':'Wheat','#FFFFFF':'White','#F5F5F5':'White Smoke','#FFFF00':'Yellow','#9ACD32':'Yellow Green'
};
var namedLookup = {};
function init() {
var inputColor = convertRGBToHex(tinyMCEPopup.getWindowArg('input_color')), key, value;
tinyMCEPopup.resizeToInnerSize();
generatePicker();
generateWebColors();
generateNamedColors();
if (inputColor) {
changeFinalColor(inputColor);
col = convertHexToRGB(inputColor);
if (col)
updateLight(col.r, col.g, col.b);
}
for (key in named) {
value = named[key];
namedLookup[value.replace(/\s+/, '').toLowerCase()] = key.replace(/#/, '').toLowerCase();
}
}
function toHexColor(color) {
var matches, red, green, blue, toInt = parseInt;
function hex(value) {
value = parseInt(value).toString(16);
return value.length > 1 ? value : '0' + value; // Padd with leading zero
};
color = tinymce.trim(color);
color = color.replace(/^[#]/, '').toLowerCase(); // remove leading '#'
color = namedLookup[color] || color;
matches = /^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/.exec(color);
if (matches) {
red = toInt(matches[1]);
green = toInt(matches[2]);
blue = toInt(matches[3]);
} else {
matches = /^([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/.exec(color);
if (matches) {
red = toInt(matches[1], 16);
green = toInt(matches[2], 16);
blue = toInt(matches[3], 16);
} else {
matches = /^([0-9a-f])([0-9a-f])([0-9a-f])$/.exec(color);
if (matches) {
red = toInt(matches[1] + matches[1], 16);
green = toInt(matches[2] + matches[2], 16);
blue = toInt(matches[3] + matches[3], 16);
} else {
return '';
}
}
}
return '#' + hex(red) + hex(green) + hex(blue);
}
function insertAction() {
var color = document.getElementById("color").value, f = tinyMCEPopup.getWindowArg('func');
var hexColor = toHexColor(color);
if (hexColor === '') {
var text = tinyMCEPopup.editor.getLang('advanced_dlg.invalid_color_value');
tinyMCEPopup.alert(text + ': ' + color);
}
else {
tinyMCEPopup.restoreSelection();
if (f)
f(hexColor);
tinyMCEPopup.close();
}
}
function showColor(color, name) {
if (name)
document.getElementById("colorname").innerHTML = name;
document.getElementById("preview").style.backgroundColor = color;
document.getElementById("color").value = color.toUpperCase();
}
function convertRGBToHex(col) {
var re = new RegExp("rgb\\s*\\(\\s*([0-9]+).*,\\s*([0-9]+).*,\\s*([0-9]+).*\\)", "gi");
if (!col)
return col;
var rgb = col.replace(re, "$1,$2,$3").split(',');
if (rgb.length == 3) {
r = parseInt(rgb[0]).toString(16);
g = parseInt(rgb[1]).toString(16);
b = parseInt(rgb[2]).toString(16);
r = r.length == 1 ? '0' + r : r;
g = g.length == 1 ? '0' + g : g;
b = b.length == 1 ? '0' + b : b;
return "#" + r + g + b;
}
return col;
}
function convertHexToRGB(col) {
if (col.indexOf('#') != -1) {
col = col.replace(new RegExp('[^0-9A-F]', 'gi'), '');
r = parseInt(col.substring(0, 2), 16);
g = parseInt(col.substring(2, 4), 16);
b = parseInt(col.substring(4, 6), 16);
return {r : r, g : g, b : b};
}
return null;
}
function generatePicker() {
var el = document.getElementById('light'), h = '', i;
for (i = 0; i < detail; i++){
h += '<div id="gs'+i+'" style="background-color:#000000; width:15px; height:3px; border-style:none; border-width:0px;"'
+ ' onclick="changeFinalColor(this.style.backgroundColor)"'
+ ' onmousedown="isMouseDown = true; return false;"'
+ ' onmouseup="isMouseDown = false;"'
+ ' onmousemove="if (isMouseDown && isMouseOver) changeFinalColor(this.style.backgroundColor); return false;"'
+ ' onmouseover="isMouseOver = true;"'
+ ' onmouseout="isMouseOver = false;"'
+ '></div>';
}
el.innerHTML = h;
}
function generateWebColors() {
var el = document.getElementById('webcolors'), h = '', i;
if (el.className == 'generated')
return;
// TODO: VoiceOver doesn't seem to support legend as a label referenced by labelledby.
h += '<div role="listbox" aria-labelledby="webcolors_title" tabindex="0"><table role="presentation" border="0" cellspacing="1" cellpadding="0">'
+ '<tr>';
for (i=0; i<colors.length; i++) {
h += '<td bgcolor="' + colors[i] + '" width="10" height="10">'
+ '<a href="javascript:insertAction();" role="option" tabindex="-1" aria-labelledby="web_colors_' + i + '" onfocus="showColor(\'' + colors[i] + '\');" onmouseover="showColor(\'' + colors[i] + '\');" style="display:block;width:10px;height:10px;overflow:hidden;">';
if (tinyMCEPopup.editor.forcedHighContrastMode) {
h += '<canvas class="mceColorSwatch" height="10" width="10" data-color="' + colors[i] + '"></canvas>';
}
h += '<span class="mceVoiceLabel" style="display:none;" id="web_colors_' + i + '">' + colors[i].toUpperCase() + '</span>';
h += '</a></td>';
if ((i+1) % 18 == 0)
h += '</tr><tr>';
}
h += '</table></div>';
el.innerHTML = h;
el.className = 'generated';
paintCanvas(el);
enableKeyboardNavigation(el.firstChild);
}
function paintCanvas(el) {
tinyMCEPopup.getWin().tinymce.each(tinyMCEPopup.dom.select('canvas.mceColorSwatch', el), function(canvas) {
var context;
if (canvas.getContext && (context = canvas.getContext("2d"))) {
context.fillStyle = canvas.getAttribute('data-color');
context.fillRect(0, 0, 10, 10);
}
});
}
function generateNamedColors() {
var el = document.getElementById('namedcolors'), h = '', n, v, i = 0;
if (el.className == 'generated')
return;
for (n in named) {
v = named[n];
h += '<a href="javascript:insertAction();" role="option" tabindex="-1" aria-labelledby="named_colors_' + i + '" onfocus="showColor(\'' + n + '\',\'' + v + '\');" onmouseover="showColor(\'' + n + '\',\'' + v + '\');" style="background-color: ' + n + '">';
if (tinyMCEPopup.editor.forcedHighContrastMode) {
h += '<canvas class="mceColorSwatch" height="10" width="10" data-color="' + colors[i] + '"></canvas>';
}
h += '<span class="mceVoiceLabel" style="display:none;" id="named_colors_' + i + '">' + v + '</span>';
h += '</a>';
i++;
}
el.innerHTML = h;
el.className = 'generated';
paintCanvas(el);
enableKeyboardNavigation(el);
}
function enableKeyboardNavigation(el) {
tinyMCEPopup.editor.windowManager.createInstance('tinymce.ui.KeyboardNavigation', {
root: el,
items: tinyMCEPopup.dom.select('a', el)
}, tinyMCEPopup.dom);
}
function dechex(n) {
return strhex.charAt(Math.floor(n / 16)) + strhex.charAt(n % 16);
}
function computeColor(e) {
var x, y, partWidth, partDetail, imHeight, r, g, b, coef, i, finalCoef, finalR, finalG, finalB, pos = tinyMCEPopup.dom.getPos(e.target);
x = e.offsetX ? e.offsetX : (e.target ? e.clientX - pos.x : 0);
y = e.offsetY ? e.offsetY : (e.target ? e.clientY - pos.y : 0);
partWidth = document.getElementById('colors').width / 6;
partDetail = detail / 2;
imHeight = document.getElementById('colors').height;
r = (x >= 0)*(x < partWidth)*255 + (x >= partWidth)*(x < 2*partWidth)*(2*255 - x * 255 / partWidth) + (x >= 4*partWidth)*(x < 5*partWidth)*(-4*255 + x * 255 / partWidth) + (x >= 5*partWidth)*(x < 6*partWidth)*255;
g = (x >= 0)*(x < partWidth)*(x * 255 / partWidth) + (x >= partWidth)*(x < 3*partWidth)*255 + (x >= 3*partWidth)*(x < 4*partWidth)*(4*255 - x * 255 / partWidth);
b = (x >= 2*partWidth)*(x < 3*partWidth)*(-2*255 + x * 255 / partWidth) + (x >= 3*partWidth)*(x < 5*partWidth)*255 + (x >= 5*partWidth)*(x < 6*partWidth)*(6*255 - x * 255 / partWidth);
coef = (imHeight - y) / imHeight;
r = 128 + (r - 128) * coef;
g = 128 + (g - 128) * coef;
b = 128 + (b - 128) * coef;
changeFinalColor('#' + dechex(r) + dechex(g) + dechex(b));
updateLight(r, g, b);
}
function updateLight(r, g, b) {
var i, partDetail = detail / 2, finalCoef, finalR, finalG, finalB, color;
for (i=0; i<detail; i++) {
if ((i>=0) && (i<partDetail)) {
finalCoef = i / partDetail;
finalR = dechex(255 - (255 - r) * finalCoef);
finalG = dechex(255 - (255 - g) * finalCoef);
finalB = dechex(255 - (255 - b) * finalCoef);
} else {
finalCoef = 2 - i / partDetail;
finalR = dechex(r * finalCoef);
finalG = dechex(g * finalCoef);
finalB = dechex(b * finalCoef);
}
color = finalR + finalG + finalB;
setCol('gs' + i, '#'+color);
}
}
function changeFinalColor(color) {
if (color.indexOf('#') == -1)
color = convertRGBToHex(color);
setCol('preview', color);
document.getElementById('color').value = color;
}
function setCol(e, c) {
try {
document.getElementById(e).style.backgroundColor = c;
} catch (ex) {
// Ignore IE warning
}
}
tinyMCEPopup.onInit.add(init);
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>angle</key>
<real>90</real>
<key>angleVariance</key>
<real>360</real>
<key>blendFuncDestination</key>
<integer>1</integer>
<key>blendFuncSource</key>
<integer>770</integer>
<key>duration</key>
<real>-1</real>
<key>emitterType</key>
<real>0.0</real>
<key>finishColorAlpha</key>
<real>1</real>
<key>finishColorBlue</key>
<real>0.0</real>
<key>finishColorGreen</key>
<real>0.0</real>
<key>finishColorRed</key>
<real>0.0</real>
<key>finishColorVarianceAlpha</key>
<real>0.0</real>
<key>finishColorVarianceBlue</key>
<real>0.0</real>
<key>finishColorVarianceGreen</key>
<real>0.0</real>
<key>finishColorVarianceRed</key>
<real>0.0</real>
<key>finishParticleSize</key>
<real>37</real>
<key>finishParticleSizeVariance</key>
<real>0.0</real>
<key>gravityx</key>
<real>0.0</real>
<key>gravityy</key>
<real>0.0</real>
<key>maxParticles</key>
<real>934</real>
<key>maxRadius</key>
<real>276.20999145507812</real>
<key>maxRadiusVariance</key>
<real>154.94999694824219</real>
<key>minRadius</key>
<real>0.0</real>
<key>particleLifespan</key>
<real>4</real>
<key>particleLifespanVariance</key>
<real>1</real>
<key>radialAccelVariance</key>
<real>0.0</real>
<key>radialAcceleration</key>
<real>-20</real>
<key>rotatePerSecond</key>
<real>35.529998779296875</real>
<key>rotatePerSecondVariance</key>
<real>0.0</real>
<key>sourcePositionVariancex</key>
<real>0.0</real>
<key>sourcePositionVariancey</key>
<real>0.0</real>
<key>sourcePositionx</key>
<real>169.91000366210938</real>
<key>sourcePositiony</key>
<real>228.71000671386719</real>
<key>speed</key>
<real>59.209999084472656</real>
<key>speedVariance</key>
<real>10</real>
<key>startColorAlpha</key>
<real>1</real>
<key>startColorBlue</key>
<real>0.75999999046325684</real>
<key>startColorGreen</key>
<real>0.25</real>
<key>startColorRed</key>
<real>0.11999999731779099</real>
<key>startColorVarianceAlpha</key>
<real>0.0</real>
<key>startColorVarianceBlue</key>
<real>0.0</real>
<key>startColorVarianceGreen</key>
<real>0.0</real>
<key>startColorVarianceRed</key>
<real>0.0</real>
<key>startParticleSize</key>
<real>37</real>
<key>startParticleSizeVariance</key>
<real>10</real>
<key>tangentialAccelVariance</key>
<real>50</real>
<key>tangentialAcceleration</key>
<real>50</real>
<key>textureFileName</key>
<string>Galaxy.png</string>
<key>textureImageData</key>
<string>H4sIAAAAAAAAAwFmA5n8iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADLUlEQVRYCcXX51JbQRCEUeOc/f6v6ZzxHKFPLAoI84epmrp7985294QVxcXl5eWjh7Sn9yB/MWcej19sXQb87/iP8f+yiztWAOmzcYL5k/F9AX9m7/fWf83zTmLOVeD5AHECWieiKpR95D8nlhPcepbH7TYBL+dI/mrWRCRkrQIBZY9Q5vzb+PdxQj2P2ikBCPnrxb0TRMQpAYiRIa9lVcregR0TgATZm/G3W7cmxn5VaA6qQNkjEkNAMbPcDOpBJfYF6DMByJC/H3+3XSfC97IziATov8FD8HUcDmzZs+bETSF0Z+cEICeCE0TYOQFlHznSZoTQkwIc5PW+FqwC7NUGVagCXTvlXzNHXnXE5LsrulYAYFduX4Ts11b4LlaWlbXBWzNH2GxojzN4jgogJgENYreganyYGELsq1YCAOp9CZX5eivEwy9mltcvPvqwirBHSGKIQE6Eitg35forO5mxSo5cDJyVHIf3TRVSIxNgiUgIUO5Abel2qII4hLJnSk5M7XC2rMPGU5s2APO++11PiKBVUECEyAq5athHyvS6TO2vhOHB72/ILK+VtHnb0+EEAkeiLZGV2UpyG94cvRbgh+KcGyzenZb5l3FPbbBfzDks3zcmE9aBCIBF1FCt16meO98M6L3BEpeohIUHP65ZXvXJM2IH8oCAATZYiJWc+a7swJF/HvddnHjnuLgwE4RvY1XAAVMuwAHvHPA61cUDNnD6DUws8k/j2kJEZ8NahdjbWIBeVvJIgSISh4yJ8931SgBwpMhVwtPZKiIeaSJmeWWrgMolENh6pSKXrTjftcKU66m9ziViFSI+AWJ3tgoQADTwrtdKLvvinE2AfcAylTXyj9tn1UiE8ztbBdhUIiD2u9ez3PS5LP0QJe6UgKpgJhpOuPBv2DEBMubAmbI3H0BqDYEJcBOAy06mqpCI/xIw5zYViFx/gZc98IZyX0DtITIR+4M4n27afgX6CgB52dffsq9FawWqkipUCWLyWR7aKQEiHVwFuHbrX7batApNRO3wPOj77O3swf8zuquAneJZaEPZ14KqcOOKrYdOre8j4BTWvfZl8qD2D7ghcomuE8XXAAAAAElFTkSuQmCCksg8PmYDAAA=</string>
</dict>
</plist>
| {
"pile_set_name": "Github"
} |
/*******************************************************************
// *** COPYRIGHT NOTICE ****
//
// Copyright 2001. Wes Jones ([email protected])
//
// This code is free for use under the following conditions:
//
// You may not claim authorship of this code.
// You may not sell or distrubute this code without author's permission.
// *Author's permission has been obtained to distribute this code with BumpTop's source code.
// You are not permitted to sell this code in it's compiled, non-compiled, executable, or any other form.
// Executable code excepted in the case that it is not sold separately from an application which
// uses this it. This means you can use this code for your applications as you see fit, but this code may not be sold in any form
// to others for use in their applications.
// This copyright notice may not be removed.
//
//
// If this code was NOT obtained by downloading it from www.codeproject.com,
// or given to you by a friend or coworker, please tell me, & let me know how you got it. There a plenty of lazy bastards that
// collect source code from the internet, and then sell it as part of
// a 'Programmer's Library'. Using this code for such a purpose is stricly prohibited.
//
// If you'd like to pay me to turn this into an ActiveX/COM object so you
// can use it in a Visual Basic application, feel free to contact me with an offer,
// and I will create it for you. Otherwise, here is the source code, and you may make your own
// ActiveX/COM object, providing that it is not sold separately.
//
// No guarantees or warranties are expressed or implied.
// This code may contain bugs.
// Warning: May contain matter. If this should come into contact with anti-matter, a violent explosion may occur.
*******************************************************************/
// DirectoryChanges.cpp: implementation of the CDirectoryChangeWatcher and CDirectoryChangeHandler classes.
//
///////////////////////////////////////////////////////////////////
///
/***********************************************************
Author: Wes Jones [email protected]
File: DirectoryChanges.cpp
Latest Changes:
11/22/2001 -- Fixed bug causing file name's to be truncated if
longer than 130 characters. Fixed CFileNotifyInformation::GetFileName()
Thanks to Edric([email protected]) for pointing this out.
Added code to enable process privileges when CDirectoryChangeWatcher::WatchDirectory()
is first called. See docuementation API for ReadDirectoryChangesW() for more information of required privileges.
Currently enables these privileges: (11/22/2001)
SE_BACKUP_NAME
SE_CHANGE_NOTIFY_NAME
SE_RESTORE_NAME(02/09/2002)
Implemented w/ helper class CPrivilegeEnabler.
11/23/2001 Added classes so that all notifications are handled by the
same thread that called CDirectoryChangeWatcher::WatchDirectory(),
ie: the main thread.
CDirectoryChangeHandler::onFilexxxx() functions are now called in the
context of the main thread instead of the worker thread.
This is good for two reasons:
1: The worker thread spends less time handling each notification.
The worker thread simply passes the notification to the main thread,
which does the processing.
This means that each file change notification is handled as fast as possible
and ReadDirectoryChangesW() can be called again to receive more notifications
faster.
2: This makes it easier to make an ActiveX or ATL object with this class
because the events that are fired, fire in the context of the main thread.
The fact that I'm using a worker thread w/ this class is totally
transparent to a client user.
If I decide to turn this app into an ActiveX or ATL object
I don't have to worry about wierd COM rules and multithreading issues,
and neither does the client, be the client a VB app, C++ app, Delphi app, or whatever.
Implemented with CDelayedDirectoryChangeHandler in DirectoryChangeHandler.h/.cpp
02/06/2002 Fixed a bug that would cause an application to hang.
If ReadDirectoryChangesW was to fail during normal operation,
the short story is that the application would hang
when it called CDirectoryChangeWatcher::UnwatchDirectory(const CString &)
One way to reproduce this behavior on the old code
is to watch a directory using a UNC path, and then change the IP
address of that machine while the watch was running. Exitting
the app after this would cause it to hang.
Steps to reproduce it:
1) Assume that the computer running the code is
named 'ThisComputer' and there is a shared folder named 'FolderName'
2) Start a watch on a folder using a UNC path: ie: \\ThisComputer\FolderName
eg: CDirectoryChangeWatcher watcher;
watcher.WatchDirectory(_T("\\\\ThisComputer\\FolderName",/ * other parameters * /)
3) Change the IP address of 'ThisComputer'
** ReadDirectoryChangesW() will fail some point after this.
4) Exit the application... it may hang.
Anyways, that's what the bug fix is for.
02/06/2002 New side effects for CDirectoryChangeHandler::onReadDirectoryChangeError()
If CDirectoryChangeHandler::onReadDirectoryChangeError() is ever executed
the directory that you are watching will have been unwatched automatically due
to the error condition.
A call to CDirectoryChangeWatcher::IsWatchingDirectory() will fail because the directory
is no longer being watched. You'll need to re-watch that directory.
02/09/2002 Added a parameter to CDirectoryChangeHandler::onReadDirectoryChangeError()
Added the parameter: const CString & strDirectoryName
The new signature is now:
VRTUAL void CDirectoryChangeHandler::onReadDirectoryChangeError(DWORD dwError, const CString & strDirectoryName);
This new parameter gives you the name of the directory that the error occurred on.
04/25/2002 Provided a way to get around the requirement of a message pump.
A console app can now use this w/out problems by passing false
to the constructor of CDirectoryChangeWatcher.
An app w/ a message pump can also pass false if it so desires w/out problems.
04/25/2002 Added two new VRTUAL functions to CDirectoryChangeHandler
Added:
onWatchStarted(DWORD dwError, const CString & strDirectoryName)
onWatchStopped(const CString & strDirectoryName);
See header file for details.
04/27/2002 Added new function to CDirectoryChangeHandler:
Added VRTUAL bool onFilterNotification(DWORD dwNotifyAction, LPCTSTR szFileName, LPCTSTR szNewFileName)
This function is called before any notification function, and allows the
CDirectoryChangeHandler derived class to ignore file notifications
by performing a programmer defined test.
By ignore, i mean that
onFileAdded(), onFileRemoved(), onFileModified(), or onFileNameChanged()
will NOT be called if this function returns false.
The default implementation always returns true, signifying that ALL notifications
are to be called.
04/27/2002 Added new Parameters to CDirectoryChangeWatcher::WatchDirectory()
The new parameters are:
LPCTSTR szIncludeFilter
LPCTSTR szExcludeFilter
Both parameters are defaulted to NULL.
Signature is now:
CDirectoryChangeWatcher::WatchDirectory(const CString & strDirToWatch,
DWORD dwChangesToWatchFor,
CDirectoryChangeHandler * pChangeHandler,
BOOL bWatchSubDirs = FALSE,
LPCTSTR szIncludeFilter = NULL,
LPCTSTR szExcludeFilter = NULL)
04/27/2002 Added support for include and exclude filters.
These filters allow you to receive notifications for just the files you
want... ie: you can specify that you only want to receive notifications
for changes to "*.txt" files or some other such file filter.
NOTE: This feature is implemented w/ the PathMatchSpec() api function
which is only available on NT4.0 if Internet Explorer 4.0 or above is installed.
See MSDN for PathMatchSpec(). Win2000, and XP do not have to worry about it.
Filter specifications:
Accepts wild card characters * and ?, just as you're used to for the DOS dir command.
It is possible to specify multiple extenstions in the filter by separating each filter spec
with a semi-colon.
eg: "*.txt;*.tmp;*.log" <-- this filter specifies all .txt, .tmp, & .log files
Filters are passed as parameters to CDirectoryChangeWatcher::WatchDirectory()
NOTE: The filters you specify take precedence over CDirectoryChangeHandler::onFilterNotification().
This means that if the file name does not pass the filters that you specify
when the watch is started, onFilterNotification() will not be called.
Filter specifications are case insensitive, ie: ".tmp" and ".TMP" are the same
FILTER TYPES:
Include Filter:
If you specify an include filter, you are specifying that you
only want to receive notifications for specific file types.
eg: "*.log" means that you only want notifications for changes
to files w/ an exention of ".log".
Changes to ALL OTHER other file types are ignored.
An empty, or not specified include filter means that you want
notifications for changes of ALL file types.
Exclude filter:
If you specify an exclude filter, you are specifying that
you do not wish to receive notifications for a specific type of file or files.
eg: "*.tmp" would mean that you do not want any notifications
regarding files that end w/ ".tmp"
An empty, or not specified exclude filter means that
you do not wish to exclude any file notifications.
************************************************************/
#include "stdafx.h"
#include "afxdisp.h"
#include "DirectoryChanges.h"
#include "DelayedDirectoryChangeHandler.h"
#ifdef BTDEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//
//
// Fwd Declares & #define's
//
//
//
// Helper classes
class CPrivilegeEnabler; //for use w/ enabling process priveledges when this code is first used. It's a singleton.
class CFileNotifyInformation;//helps CDirectoryChangeWatcher class notify CDirectoryChangeHandler class of changes to files.
class CDelayedDirectoryChangeHandler; // Helps all notifications become handled by the main
// thread, or a worker thread depending upon a value passed to the
// constructor of CDirectoryChangeWatcher.
//
// For notifications to fire in the main thread, your app must have a message pump.
//
// The 'main' thread is the one that called CDirectoryChangeWatcher::WatchDirectory()
// Helper functions
static BOOL EnablePrivilege(LPCTSTR pszPrivName, BOOL fEnable = TRUE);
static bool IsDirectory(const CString & strPath);
/////////////////////////////////////////////////////////////////////
// Helper functions.
BOOL EnablePrivilege(LPCTSTR pszPrivName, BOOL fEnable /*= TRUE*/)
//
// I think this code is from a Jeffrey Richter book...
//
// Enables user priviledges to be set for this process.
//
// Process needs to have access to certain priviledges in order
// to use the ReadDirectoryChangesW() API. See documentation.
{
BOOL fOk = FALSE;
// Assume function fails
HANDLE hToken;
// Try to open this process's access token
if (OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES, &hToken))
{
// privilege
TOKEN_PRIVILEGES tp = { 1 };
if(LookupPrivilegeValue(NULL, pszPrivName, &tp.Privileges[0].Luid))
{
tp.Privileges[0].Attributes = fEnable ? SE_PRIVILEGE_ENABLED : 0;
AdjustTokenPrivileges(hToken, FALSE, &tp,
sizeof(tp), NULL, NULL);
fOk = (GetLastError() == ERROR_SUCCESS);
}
CloseHandle(hToken);
}
return(fOk);
}
static bool IsDirectory(const CString & strPath)
//
// Returns: bool
// true if strPath is a path to a directory
// false otherwise.
//
{
DWORD dwAttrib = GetFileAttributes(strPath);
return static_cast<bool>((dwAttrib != 0xffffffff
&& (dwAttrib & FILE_ATTRIBUTE_DIRECTORY)));
}
///////////////////////////////////////////////
//Helper class:
class CFileNotifyInformation
/*******************************
A Class to more easily traverse the FILE_NOTIFY_INFORMATION records returned
by ReadDirectoryChangesW().
FILE_NOTIFY_INFORMATION is defined in Winnt.h as:
typedef struct _FILE_NOTIFY_INFORMATION {
DWORD NextEntryOffset;
DWORD Action;
DWORD FileNameLength;
WCHAR FileName[1];
} FILE_NOTIFY_INFORMATION, *PFILE_NOTIFY_INFORMATION;
ReadDirectoryChangesW basically puts x amount of these records in a
buffer that you specify.
The FILE_NOTIFY_INFORMATION structure is a 'dynamically sized' structure (size depends on length
of the file name (+ sizeof the DWORDs in the struct))
Because each structure contains an offset to the 'next' file notification
it is basically a singly linked list. This class treats the structure in that way.
Sample Usage:
BYTE Read_Buffer[ 4096 ];
...
ReadDirectoryChangesW(...Read_Buffer, 4096,...);
...
CFileNotifyInformation notify_info(Read_Buffer, 4096);
do{
switch(notify_info.GetAction())
{
case xx:
notify_info.GetFileName();
}
while(notify_info.GetNextNotifyInformation());
********************************/
{
public:
CFileNotifyInformation(BYTE * lpFileNotifyInfoBuffer, DWORD dwBuffSize)
: m_pBuffer(lpFileNotifyInfoBuffer),
m_dwBufferSize(dwBuffSize)
{
ASSERT(lpFileNotifyInfoBuffer && dwBuffSize);
m_pCurrentRecord = (PFILE_NOTIFY_INFORMATION) m_pBuffer;
}
BOOL GetNextNotifyInformation();
BOOL CopyCurrentRecordToBeginningOfBuffer(OUT DWORD & ref_dwSizeOfCurrentRecord);
DWORD GetAction() const;//gets the type of file change notifiation
CString GetFileName()const;//gets the file name from the FILE_NOTIFY_INFORMATION record
CString GetFileNameWithPath(const CString & strRootPath) const;//same as GetFileName() only it prefixes the strRootPath into the file name
protected:
BYTE * m_pBuffer;//<--all of the FILE_NOTIFY_INFORMATION records 'live' in the buffer this points to...
DWORD m_dwBufferSize;
PFILE_NOTIFY_INFORMATION m_pCurrentRecord;//this points to the current FILE_NOTIFY_INFORMATION record in m_pBuffer
};
BOOL CFileNotifyInformation::GetNextNotifyInformation()
/***************
Sets the m_pCurrentRecord to the next FILE_NOTIFY_INFORMATION record.
Even if this return FALSE, (unless m_pCurrentRecord is NULL)
m_pCurrentRecord will still point to the last record in the buffer.
****************/
{
if(m_pCurrentRecord
&& m_pCurrentRecord->NextEntryOffset != 0UL)//is there another record after this one?
{
//set the current record to point to the 'next' record
PFILE_NOTIFY_INFORMATION pOld = m_pCurrentRecord;
m_pCurrentRecord = (PFILE_NOTIFY_INFORMATION) ((LPBYTE)m_pCurrentRecord + m_pCurrentRecord->NextEntryOffset);
ASSERT((DWORD)((BYTE*)m_pCurrentRecord - m_pBuffer) < m_dwBufferSize);//make sure we haven't gone too far
if((DWORD)((BYTE*)m_pCurrentRecord - m_pBuffer) > m_dwBufferSize)
{
//we've gone too far.... this data is hosed.
//
// This sometimes happens if the watched directory becomes deleted... remove the FILE_SHARE_DELETE flag when using CreateFile() to get the handle to the directory...
m_pCurrentRecord = pOld;
}
return (BOOL)(m_pCurrentRecord != pOld);
}
return FALSE;
}
BOOL CFileNotifyInformation::CopyCurrentRecordToBeginningOfBuffer(OUT DWORD & ref_dwSizeOfCurrentRecord)
/*****************************************
Copies the FILE_NOTIFY_INFORMATION record to the beginning of the buffer
specified in the constructor.
The size of the current record is returned in DWORD & dwSizeOfCurrentRecord.
*****************************************/
{
ASSERT(m_pBuffer && m_pCurrentRecord);
if(!m_pCurrentRecord) return FALSE;
BOOL bRetVal = TRUE;
//determine the size of the current record.
ref_dwSizeOfCurrentRecord = sizeof(FILE_NOTIFY_INFORMATION);
//subtract out sizeof FILE_NOTIFY_INFORMATION::FileName[1]
WCHAR FileName[1];//same as is defined for FILE_NOTIFY_INFORMATION::FileName
UNREFERENCED_PARAMETER(FileName);
ref_dwSizeOfCurrentRecord -= sizeof(FileName);
//and replace it w/ value of FILE_NOTIFY_INFORMATION::FileNameLength
ref_dwSizeOfCurrentRecord += m_pCurrentRecord->FileNameLength;
ASSERT((DWORD)((LPBYTE)m_pCurrentRecord + ref_dwSizeOfCurrentRecord) <= m_dwBufferSize);
ASSERT((void*)m_pBuffer != (void*)m_pCurrentRecord);//if this is the case, your buffer is way too small
if((void*)m_pBuffer != (void*) m_pCurrentRecord)
{//copy the m_pCurrentRecord to the beginning of m_pBuffer
ASSERT((DWORD)m_pCurrentRecord > (DWORD)m_pBuffer + ref_dwSizeOfCurrentRecord);//will it overlap?
__try{
memcpy(m_pBuffer, m_pCurrentRecord, ref_dwSizeOfCurrentRecord);
bRetVal = TRUE;
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
TRACE(_T("EXCEPTION! CFileNotifyInformation::CopyCurrentRecordToBeginningOfBuffer() -- probably because bytes overlapped in a call to memcpy()"));
bRetVal = FALSE;
}
}
//else
//there was only one record in this buffer, and m_pCurrentRecord is already at the beginning of the buffer
return bRetVal;
}
DWORD CFileNotifyInformation::GetAction() const
{
ASSERT(m_pCurrentRecord);
if(m_pCurrentRecord)
return m_pCurrentRecord->Action;
return 0UL;
}
CString CFileNotifyInformation::GetFileName() const
{
DWORD fsz;
//
//BUG FIX:
// File Name's longer than 130 characters are truncated
//
// Thanks Edric @ [email protected] for pointing this out.
if(m_pCurrentRecord)
{
WCHAR wcFileName[ MAX_PATH + 1] = {0};//L"";
if (m_pCurrentRecord->FileNameLength < (MAX_PATH * sizeof(WCHAR)))
fsz = m_pCurrentRecord->FileNameLength;
else
fsz = (MAX_PATH * sizeof(WCHAR));
memcpy( wcFileName,
m_pCurrentRecord->FileName,
//min(MAX_PATH, m_pCurrentRecord->FileNameLength) <-- buggy line
fsz);
return CString(wcFileName);
}
return CString();
}
static inline bool HasTrailingBackslash(const CString & str)
{
if(str.GetLength() > 0
&& str[ str.GetLength() - 1 ] == _T('\\'))
return true;
return false;
}
CString CFileNotifyInformation::GetFileNameWithPath(const CString & strRootPath) const
{
CString strFileName(strRootPath);
//if(strFileName.Right(1) != _T("\\"))
if(!HasTrailingBackslash(strRootPath))
strFileName += _T("\\");
strFileName += GetFileName();
return strFileName;
}
/////////////////////////////////////////////////////////////////////////////////
class CPrivilegeEnabler
//
// Enables privileges for this process
// first time CDirectoryChangeWatcher::WatchDirectory() is called.
//
// It's a singleton.
//
{
private:
CPrivilegeEnabler();//ctor
public:
~CPrivilegeEnabler(){};
static CPrivilegeEnabler & Instance();
//friend static CPrivilegeEnabler & Instance();
};
CPrivilegeEnabler::CPrivilegeEnabler()
{
LPCTSTR arPrivelegeNames[] = {
SE_BACKUP_NAME, // these two are required for the FILE_FLAG_BACKUP_SEMANTICS flag used in the call to
SE_RESTORE_NAME,// CreateFile() to open the directory handle for ReadDirectoryChangesW
SE_CHANGE_NOTIFY_NAME //just to make sure...it's on by default for all users.
//<others here as needed>
};
for(int i = 0; i < sizeof(arPrivelegeNames) / sizeof(arPrivelegeNames[0]); ++i)
{
if(!EnablePrivilege(arPrivelegeNames[i], TRUE))
{
TRACE(_T("Unable to enable privilege: %s -- GetLastError(): %d\n"), arPrivelegeNames[i], GetLastError());
TRACE(_T("CDirectoryChangeWatcher notifications may not work as intended due to insufficient access rights/process privileges.\n"));
TRACE(_T("File: %s Line: %d\n"), _T(__FILE__), __LINE__);
}
}
}
CPrivilegeEnabler & CPrivilegeEnabler::Instance()
{
static CPrivilegeEnabler theInstance;//constructs this first time it's called.
return theInstance;
}
//
//
//
///////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CDirectoryChangeHandler::CDirectoryChangeHandler()
: m_nRefCnt(1),
m_pDirChangeWatcher(NULL),
m_nWatcherRefCnt(0L),
m_csWatcher(new CCriticalSection())
{
}
CDirectoryChangeHandler::~CDirectoryChangeHandler()
{
UnwatchDirectory();
delete m_csWatcher;
}
long CDirectoryChangeHandler::AddRef()
{
return InterlockedIncrement(&m_nRefCnt);
}
long CDirectoryChangeHandler::Release()
{
long nRefCnt = -1;
if((nRefCnt = InterlockedDecrement(&m_nRefCnt)) == 0)
delete this;
return nRefCnt;
}
long CDirectoryChangeHandler::CurRefCnt()const
{
return m_nRefCnt;
}
BOOL CDirectoryChangeHandler::UnwatchDirectory()
{
CSingleLock lock(m_csWatcher, TRUE);
ASSERT(lock.IsLocked());
if(m_pDirChangeWatcher)
return m_pDirChangeWatcher->UnwatchDirectory(this);
return TRUE;
}
long CDirectoryChangeHandler::ReferencesWatcher(CDirectoryChangeWatcher * pDirChangeWatcher)
{
ASSERT(pDirChangeWatcher);
CSingleLock lock(m_csWatcher, TRUE);
if(m_pDirChangeWatcher
&& m_pDirChangeWatcher != pDirChangeWatcher)
{
TRACE(_T("CDirectoryChangeHandler...is becoming used by a different CDirectoryChangeWatcher!\n"));
TRACE(_T("Directories being handled by this object will now be unwatched.\nThis object is now being used to ")
_T("handle changes to a directory watched by different CDirectoryChangeWatcher object, probably on a different directory"));
if(UnwatchDirectory())
{
m_pDirChangeWatcher = pDirChangeWatcher;
m_nWatcherRefCnt = 1; //when this reaches 0, set m_pDirChangeWatcher to NULL
return m_nWatcherRefCnt;
}
else
{
ASSERT(FALSE);//shouldn't get here!
}
}
else
{
ASSERT(!m_pDirChangeWatcher || m_pDirChangeWatcher == pDirChangeWatcher);
m_pDirChangeWatcher = pDirChangeWatcher;
if(m_pDirChangeWatcher)
return InterlockedIncrement(&m_nWatcherRefCnt);
}
return m_nWatcherRefCnt;
}
long CDirectoryChangeHandler::ReleaseReferenceToWatcher(CDirectoryChangeWatcher * pDirChangeWatcher)
{
ASSERT(m_pDirChangeWatcher == pDirChangeWatcher);
CSingleLock lock(m_csWatcher, TRUE);
long nRef;
if((nRef = InterlockedDecrement(&m_nWatcherRefCnt)) <= 0L)
{
m_pDirChangeWatcher = NULL; //Setting this to NULL so that this->UnwatchDirectory() which is called in the dtor
//won't call m_pDirChangeWatcher->UnwatchDirecotry(this).
//m_pDirChangeWatcher may point to a destructed object depending on how
//these classes are being used.
m_nWatcherRefCnt = 0L;
}
return nRef;
}
//
//
// Default implmentations for CDirectoryChangeHandler's VRTUAL functions.
//
//
void CDirectoryChangeHandler::onFileAdded(LPCTSTR strFileName)
{
TRACE(_T("The following file was added: %s\n"), strFileName);
}
void CDirectoryChangeHandler::onFileRemoved(LPCTSTR strFileName)
{
TRACE(_T("The following file was removed: %s\n"), strFileName);
}
void CDirectoryChangeHandler::onFileModified(LPCTSTR strFileName)
{
TRACE(_T("The following file was modified: %s\n"), strFileName);
}
void CDirectoryChangeHandler::onFileNameChanged(LPCTSTR strOldFileName, LPCTSTR strNewFileName)
{
TRACE(_T("The file %s was RENAMED to %s\n"), strOldFileName, strNewFileName);
}
void CDirectoryChangeHandler::onReadDirectoryChangesError(DWORD dwError, const TCHAR * strDirectoryName)
{
TRACE(_T("WARNING!!!!!\n"));
TRACE(_T("An error has occurred on a watched directory!\n"));
TRACE(_T("This directory has become unwatched! -- %s \n"), strDirectoryName);
TRACE(_T("ReadDirectoryChangesW has failed! %d"), dwError);
ASSERT(FALSE);//you should override this function no matter what. an error will occur someday.
}
void CDirectoryChangeHandler::onWatchStarted(DWORD dwError, const TCHAR * strDirectoryName)
{
if(dwError == 0)
TRACE(_T("A watch has begun on the following directory: %s\n"), strDirectoryName);
else
TRACE(_T("A watch failed to start on the following directory: (Error: %d) %s\n"),dwError, strDirectoryName);
}
void CDirectoryChangeHandler::onWatchStopped(const TCHAR * strDirectoryName)
{
TRACE(_T("The watch on the following directory has stopped: %s\n"), strDirectoryName);
}
bool CDirectoryChangeHandler::onFilterNotification(DWORD /*dwNotifyAction*/, LPCTSTR /*szFileName*/, LPCTSTR /*szNewFileName*/)
//
// bool onFilterNotification(DWORD dwNotifyAction, LPCTSTR szFileName, LPCTSTR szNewFileName);
//
// This function gives your class a chance to filter unwanted notifications.
//
// PARAMETERS:
// DWORD dwNotifyAction -- specifies the event to filter
// LPCTSTR szFileName -- specifies the name of the file for the event.
// LPCTSTR szNewFileName -- specifies the new file name of a file that has been renamed.
//
// RETURN VALUE:
// return true from this function, and you will receive the notification.
// return false from this function, and your class will NOT receive the notification.
//
// Valid values of dwNotifyAction:
// FILE_ACTION_ADDED -- onFileAdded() is about to be called.
// FILE_ACTION_REMOVED -- onFileRemoved() is about to be called.
// FILE_ACTION_MODIFIED -- onFileModified() is about to be called.
// FILE_ACTION_RENAMED_OLD_NAME-- onFileNameChanged() is about to be call.
//
//
// NOTE: When the value of dwNotifyAction is FILE_ACTION_RENAMED_OLD_NAME,
// szFileName will be the old name of the file, and szNewFileName will
// be the new name of the renamed file.
//
// The default implementation always returns true, indicating that all notifications will
// be sent.
//
{
return true;
}
void CDirectoryChangeHandler::SetChangedDirectoryName(const TCHAR * strChangedDirName)
{
m_strChangedDirectoryName = strChangedDirName;
}
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
CDirectoryChangeWatcher::CDirectoryChangeWatcher(bool bAppHasGUI /*= true*/, DWORD dwFilterFlags/*=FILTERS_CHECK_FILE_NAME_ONLY*/)
: m_hCompPort(NULL)
,m_hThread(NULL)
,m_dwThreadID(0UL)
,m_bAppHasGUI(bAppHasGUI)
,m_dwFilterFlags(dwFilterFlags == 0? FILTERS_DEFAULT_BEHAVIOR : dwFilterFlags)
{
//NOTE:
// The bAppHasGUI variable indicates that you have a message pump associated
// with the main thread(or the thread that first calls CDirectoryChangeWatcher::WatchDirectory()).
// Directory change notifications are dispatched to your main thread.
//
// If your app doesn't have a gui, then pass false. Doing so causes a worker thread
// to be created that implements a message pump where it dispatches/executes the notifications.
// It's ok to pass false even if your app does have a GUI.
// Passing false is required for Console applications, or applications without a message pump.
// Note that notifications are fired in a worker thread.
//
//NOTE:
//
//
AfxOleInit();
AfxInitRichEdit2();
}
CDirectoryChangeWatcher::~CDirectoryChangeWatcher()
{
UnwatchAllDirectories();
if(m_hCompPort)
{
CloseHandle(m_hCompPort);
m_hCompPort = NULL;
}
}
DWORD CDirectoryChangeWatcher::SetFilterFlags(DWORD dwFilterFlags)
//
// SetFilterFlags()
//
// sets filter behavior for directories watched AFTER this function has been called.
//
//
//
{
DWORD dwOld = m_dwFilterFlags;
m_dwFilterFlags = dwFilterFlags;
if(m_dwFilterFlags == 0)
m_dwFilterFlags = FILTERS_DEFAULT_BEHAVIOR;//the default.
return dwOld;
}
BOOL CDirectoryChangeWatcher::IsWatchingDirectory(const CString & strDirName)const
/*********************************************
Determines whether or not a directory is being watched
be carefull that you have the same name path name, including the backslash
as was used in the call to WatchDirectory().
ie:
"C:\\Temp"
is different than
"C:\\Temp\\"
**********************************************/
{
CSingleLock lock(const_cast<CCriticalSection*>(&m_csDirWatchInfo), TRUE);
ASSERT(lock.IsLocked());
int i;
if(GetDirWatchInfo(strDirName, i))
return TRUE;
return FALSE;
}
int CDirectoryChangeWatcher::NumWatchedDirectories()const
{
CSingleLock lock(const_cast<CCriticalSection*>(&m_csDirWatchInfo), TRUE);
ASSERT(lock.IsLocked());
int nCnt(0),max = m_DirectoriesToWatch.GetSize();
for(int i(0); i < max; ++i)
{
if(m_DirectoriesToWatch[i] != NULL)//array may contain NULL elements.
nCnt++;
}
return nCnt;
}
DWORD CDirectoryChangeWatcher::WatchDirectory(const CString & strDirToWatch,
DWORD dwChangesToWatchFor,
CDirectoryChangeHandler * pChangeHandler,
BOOL bWatchSubDirs /*=FALSE*/,
LPCTSTR szIncludeFilter /*=NULL*/,
LPCTSTR szExcludeFilter /*=NULL*/
)
/*************************************************************
FUNCTION: WatchDirectory(const CString & strDirToWatch, --the name of the directory to watch
DWORD dwChangesToWatchFor, --the changes to watch for see dsk docs..for ReadDirectoryChangesW
CDirectoryChangeHandler * pChangeHandler -- handles changes in specified directory
BOOL bWatchSubDirs --specified to watch sub directories of the directory that you want to watch
)
PARAMETERS:
const CString & strDirToWatch -- specifies the path of the directory to watch.
DWORD dwChangesToWatchFor -- specifies flags to be passed to ReadDirectoryChangesW()
CDirectoryChangeHandler * -- ptr to an object which will handle notifications of file changes.
BOOL bWatchSubDirs -- specifies to watch subdirectories.
LPCTSTR szIncludeFilter -- A file pattern string for files that you wish to receive notifications
for. See Remarks.
LPCTSTR szExcludeFilter -- A file pattern string for files that you do not wish to receive notifications for. See Remarks
Starts watching the specified directory(and optionally subdirectories) for the specified changes
When specified changes take place the appropriate CDirectoryChangeHandler::onFilexxx() function is called.
dwChangesToWatchFor can be a combination of the following flags, and changes map out to the
following functions:
FILE_NOTIFY_CHANGE_FILE_NAME -- CDirectoryChangeHandler::onFileAdded()
CDirectoryChangeHandler::onFileNameChanged,
CDirectoryChangeHandler::onFileRemoved
FILE_NOTIFY_CHANGE_DIR_NAME -- CDirectoryChangeHandler::onFileNameAdded(),
CDirectoryChangeHandler::onFileRemoved
FILE_NOTIFY_CHANGE_ATTRIBUTES -- CDirectoryChangeHandler::onFileModified
FILE_NOTIFY_CHANGE_SIZE -- CDirectoryChangeHandler::onFileModified
FILE_NOTIFY_CHANGE_LAST_WRITE -- CDirectoryChangeHandler::onFileModified
FILE_NOTIFY_CHANGE_LAST_ACCESS -- CDirectoryChangeHandler::onFileModified
FILE_NOTIFY_CHANGE_CREATION -- CDirectoryChangeHandler::onFileModified
FILE_NOTIFY_CHANGE_SECURITY -- CDirectoryChangeHandler::onFileModified?
Returns ERROR_SUCCESS if the directory will be watched,
or a windows error code if the directory couldn't be watched.
The error code will most likely be related to a call to CreateFile(), or
from the initial call to ReadDirectoryChangesW(). It's also possible to get an
error code related to being unable to create an io completion port or being unable
to start the worker thread.
This function will fail if the directory to be watched resides on a
computer that is not a Windows NT/2000/XP machine.
You can only have one watch specified at a time for any particular directory.
Calling this function with the same directory name will cause the directory to be
unwatched, and then watched again(w/ the new parameters that have been passed in).
**************************************************************/
{
ASSERT(dwChangesToWatchFor != 0);
if(strDirToWatch.IsEmpty()
|| dwChangesToWatchFor == 0
|| pChangeHandler == NULL)
{
TRACE(_T("ERROR: You've passed invalid parameters to CDirectoryChangeWatcher::WatchDirectory()\n"));
::SetLastError(ERROR_INVALID_PARAMETER);
return ERROR_INVALID_PARAMETER;
}
//double check that it's really a directory
if(!IsDirectory(strDirToWatch))
{
TRACE(_T("ERROR: CDirectoryChangeWatcher::WatchDirectory() -- %s is not a directory!\n"), strDirToWatch);
::SetLastError(ERROR_BAD_PATHNAME);
return ERROR_BAD_PATHNAME;
}
//double check that this directory is not already being watched....
//if it is, then unwatch it before restarting it...
if(IsWatchingDirectory(strDirToWatch))
{
VERIFY(
UnwatchDirectory(strDirToWatch)
);
}
//
//
// Reference this singleton so that privileges for this process are enabled
// so that it has required permissions to use the ReadDirectoryChangesW API, etc.
//
CPrivilegeEnabler::Instance();
//
//open the directory to watch....
HANDLE hDir = CreateFile(strDirToWatch,
FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_WRITE ,//| FILE_SHARE_DELETE, <-- removing FILE_SHARE_DELETE prevents the user or someone else from renaming or deleting the watched directory. This is a good thing to prevent.
NULL, //security attributes
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | //<- the required priviliges for this flag are: SE_BACKUP_NAME and SE_RESTORE_NAME. CPrivilegeEnabler takes care of that.
FILE_FLAG_OVERLAPPED, //OVERLAPPED!
NULL);
if(hDir == INVALID_HANDLE_VALUE)
{
DWORD dwError = GetLastError();
TRACE(_T("CDirectoryChangeWatcher::WatchDirectory() -- Couldn't open directory for monitoring. %d\n"), dwError);
::SetLastError(dwError);//who knows if TRACE will cause GetLastError() to return success...probably won't, but set it manually just for fun.
return dwError;
}
//opened the dir!
CDirWatchInfo * pDirInfo = new CDirWatchInfo(hDir, strDirToWatch, pChangeHandler, dwChangesToWatchFor, bWatchSubDirs, m_bAppHasGUI, szIncludeFilter, szExcludeFilter, m_dwFilterFlags);
if(!pDirInfo)
{
TRACE(_T("WARNING: Couldn't allocate a new CDirWatchInfo() object --- File: %s Line: %d\n"), _T(__FILE__), __LINE__);
CloseHandle(hDir);
::SetLastError(ERROR_OUTOFMEMORY);
return ERROR_OUTOFMEMORY;
}
//create a IO completion port/or associate this key with
//the existing IO completion port
m_hCompPort = CreateIoCompletionPort(hDir,
m_hCompPort, //if m_hCompPort is NULL, hDir is associated with a NEW completion port,
//if m_hCompPort is NON-NULL, hDir is associated with the existing completion port that the handle m_hCompPort references
(DWORD)pDirInfo, //the completion 'key'... this ptr is returned from GetQueuedCompletionStatus() when one of the events in the dwChangesToWatchFor filter takes place
0);
if(m_hCompPort == NULL)
{
TRACE(_T("ERROR -- Unable to create I/O Completion port! GetLastError(): %d File: %s Line: %d"), GetLastError(), _T(__FILE__), __LINE__);
DWORD dwError = GetLastError();
pDirInfo->DeleteSelf(NULL);
::SetLastError(dwError);//who knows what the last error will be after i call pDirInfo->DeleteSelf(), so set it just to make sure
return dwError;
}
else
{//completion port created/directory associated w/ it successfully
//if the thread isn't running start it....
//when the thread starts, it will call ReadDirectoryChangesW and wait
//for changes to take place
if(m_hThread == NULL)
{
//start the thread
CWinThread * pThread = AfxBeginThread((AFX_THREADPROC)MonitorDirectoryChanges, this);
if(!pThread)
{//couldn't create the thread!
TRACE(_T("CDirectoryChangeWatcher::WatchDirectory()-- AfxBeginThread failed!\n"));
pDirInfo->DeleteSelf(NULL);
return (GetLastError() == ERROR_SUCCESS)? ERROR_MAX_THRDS_REACHED : GetLastError();
}
else
{
m_hThread = pThread->m_hThread;
m_dwThreadID = pThread->m_nThreadID;
pThread->m_bAutoDelete = TRUE;//pThread is deleted when thread ends....it's TRUE by default(for CWinThread ptrs returned by AfxBeginThread(threadproc, void*)), but just makin sure.
}
}
if(m_hThread != NULL)
{//thread is running,
//signal the thread to issue the initial call to
//ReadDirectoryChangesW()
DWORD dwStarted = pDirInfo->StartMonitor(m_hCompPort);
if(dwStarted != ERROR_SUCCESS)
{//there was a problem!
TRACE(_T("Unable to watch directory: %s -- GetLastError(): %d\n"), dwStarted);
pDirInfo->DeleteSelf(NULL);
::SetLastError(dwStarted);//I think this'll set the Err object in a VB app.....
return dwStarted;
}
else
{//ReadDirectoryChangesW was successfull!
//add the directory info to the first empty slot in the array
//associate the pChangeHandler with this object
pChangeHandler->ReferencesWatcher(this);//reference is removed when directory is unwatched.
//CDirWatchInfo::DeleteSelf() must now be called w/ this CDirectoryChangeWatcher pointer becuse
//of a reference count
//save the CDirWatchInfo* so I'll be able to use it later.
VERIFY(AddToWatchInfo(pDirInfo));
SetLastError(dwStarted);
return dwStarted;
}
}
else
{
ASSERT(FALSE);//control path shouldn't get here
::SetLastError(ERROR_MAX_THRDS_REACHED);
return ERROR_MAX_THRDS_REACHED;
}
}
ASSERT(FALSE);//shouldn't get here.
}
BOOL CDirectoryChangeWatcher::UnwatchAllDirectories()
{
//unwatch all of the watched directories
//delete all of the CDirWatchInfo objects,
//kill off the worker thread
if(m_hThread != NULL)
{
ASSERT(m_hCompPort != NULL);
CSingleLock lock(&m_csDirWatchInfo, TRUE);
ASSERT(lock.IsLocked());
CDirWatchInfo * pDirInfo;
//Unwatch each of the watched directories
//and delete the CDirWatchInfo associated w/ that directory...
int max = m_DirectoriesToWatch.GetSize();
for(int i = 0; i < max; ++i)
{
if((pDirInfo = m_DirectoriesToWatch[i]) != NULL)
{
VERIFY(pDirInfo->UnwatchDirectory(m_hCompPort));
m_DirectoriesToWatch.SetAt(i, NULL) ;
pDirInfo->DeleteSelf(this);
}
}
m_DirectoriesToWatch.RemoveAll();
//kill off the thread
PostQueuedCompletionStatus(m_hCompPort, 0, 0, NULL);//The thread will catch this and exit the thread
//wait for it to exit
WaitForSingleObject(m_hThread, INFINITE);
//CloseHandle(m_hThread);//Since thread was started w/ AfxBeginThread() this handle is closed automatically, closing it again will raise an exception
m_hThread = NULL;
m_dwThreadID = 0UL;
//close the completion port...
CloseHandle(m_hCompPort);
m_hCompPort = NULL;
return TRUE;
}
else
{
#ifdef BTDEBUG
//make sure that there aren't any
//CDirWatchInfo objects laying around... they should have all been destroyed
//and removed from the array m_DirectoriesToWatch
if(m_DirectoriesToWatch.GetSize() > 0)
{
for(int i = 0; i < m_DirectoriesToWatch.GetSize(); ++i)
{
ASSERT(m_DirectoriesToWatch[i] == NULL);
}
}
#endif
}
return FALSE;
}
BOOL CDirectoryChangeWatcher::UnwatchDirectory(const CString & strDirToStopWatching)
/***************************************************************
FUNCTION: UnwatchDirectory(const CString & strDirToStopWatching -- if this directory is being watched, the watch is stopped
****************************************************************/
{
BOOL bRetVal = FALSE;
if(m_hCompPort != NULL)//The io completion port must be open
{
ASSERT(!strDirToStopWatching.IsEmpty());
CSingleLock lock(&m_csDirWatchInfo, TRUE);
ASSERT(lock.IsLocked());
int nIdx = -1;
CDirWatchInfo * pDirInfo = GetDirWatchInfo(strDirToStopWatching, nIdx);
if(pDirInfo != NULL
&& nIdx != -1)
{
//stop watching this directory
VERIFY(pDirInfo->UnwatchDirectory(m_hCompPort));
//cleanup the object used to watch the directory
m_DirectoriesToWatch.SetAt(nIdx, NULL);
pDirInfo->DeleteSelf(this);
bRetVal = TRUE;
}
}
return bRetVal;
}
BOOL CDirectoryChangeWatcher::UnwatchDirectory(CDirectoryChangeHandler * pChangeHandler)
/************************************
This function is called from the dtor of CDirectoryChangeHandler automatically,
but may also be called by a programmer because it's public...
A single CDirectoryChangeHandler may be used for any number of watched directories.
Unwatch any directories that may be using this
CDirectoryChangeHandler * pChangeHandler to handle changes to a watched directory...
The CDirWatchInfo::m_pChangeHandler member of objects in the m_DirectoriesToWatch
array will == pChangeHandler if that handler is being used to handle changes to a directory....
************************************/
{
ASSERT(pChangeHandler);
CSingleLock lock(&m_csDirWatchInfo, TRUE);
ASSERT(lock.IsLocked());
int nUnwatched = 0;
int nIdx = -1;
CDirWatchInfo * pDirInfo;
//
// go through and unwatch any directory that is
// that is using this pChangeHandler as it's file change notification handler.
//
while((pDirInfo = GetDirWatchInfo(pChangeHandler, nIdx)) != NULL)
{
VERIFY(pDirInfo->UnwatchDirectory(m_hCompPort));
nUnwatched++;
m_DirectoriesToWatch.SetAt(nIdx, NULL);
pDirInfo->DeleteSelf(this);
}
return (BOOL)(nUnwatched != 0);
}
BOOL CDirectoryChangeWatcher::UnwatchDirectoryBecauseOfError(CDirWatchInfo * pWatchInfo)
//
// Called in the worker thread in the case that ReadDirectoryChangesW() fails
// during normal operation. One way to force this to happen is to watch a folder
// using a UNC path and changing that computer's IP address.
//
{
ASSERT(pWatchInfo);
ASSERT(m_dwThreadID == GetCurrentThreadId());//this should be called from the worker thread only.
BOOL bRetVal = FALSE;
if(pWatchInfo)
{
CSingleLock lock(&m_csDirWatchInfo, TRUE);
ASSERT(lock.IsLocked());
int nIdx = -1;
if(GetDirWatchInfo(pWatchInfo, nIdx) == pWatchInfo)
{
// we are actually watching this....
//
// Remove this CDirWatchInfo object from the list of watched directories.
//
m_DirectoriesToWatch.SetAt(nIdx, NULL);//mark the space as free for the next watch...
//
// and delete it...
//
pWatchInfo->DeleteSelf(this);
}
}
return bRetVal;
}
int CDirectoryChangeWatcher::AddToWatchInfo(CDirectoryChangeWatcher::CDirWatchInfo * pWatchInfo)
//
//
// To add the CDirWatchInfo * to an array.
// The array is used to keep track of which directories
// are being watched.
//
// Add the ptr to the first non-null slot in the array.
{
CSingleLock lock(&m_csDirWatchInfo, TRUE);
ASSERT(lock.IsLocked());
int i;
//first try to add it to the first empty slot in m_DirectoriesToWatch
int max = m_DirectoriesToWatch.GetSize();
for(i = 0; i < max; ++i)
{
if(m_DirectoriesToWatch[i] == NULL)
{
m_DirectoriesToWatch[i] = pWatchInfo;
break;
}
}
if(i == max)
{
// there where no empty slots, add it to the end of the array
try{
i = m_DirectoriesToWatch.Add(pWatchInfo);
}
catch(CMemoryException * e){
e->ReportError();
e->Delete();//??? delete this? I thought CMemoryException objects where pre allocated in mfc? -- sample code in msdn does, so will i
i = -1;
}
}
return (BOOL)(i != -1);
}
//
// functions for retrieving the directory watch info based on different parameters
//
CDirectoryChangeWatcher::CDirWatchInfo * CDirectoryChangeWatcher::GetDirWatchInfo(const CString & strDirName, int & ref_nIdx)const
{
if(strDirName.IsEmpty())// can't be watching a directory if it's you don't pass in the name of it...
return FALSE; //
CSingleLock lock(const_cast<CCriticalSection*>(&m_csDirWatchInfo), TRUE);
int max = m_DirectoriesToWatch.GetSize();
CDirWatchInfo * p = NULL;
for(int i = 0; i < max; ++i)
{
if((p = m_DirectoriesToWatch[i]) != NULL
&& p->m_strDirName.CompareNoCase(strDirName) == 0)
{
ref_nIdx = i;
return p;
}
}
return NULL;//NOT FOUND
}
CDirectoryChangeWatcher::CDirWatchInfo * CDirectoryChangeWatcher::GetDirWatchInfo(CDirectoryChangeWatcher::CDirWatchInfo * pWatchInfo, int & ref_nIdx)const
{
ASSERT(pWatchInfo != NULL);
CSingleLock lock(const_cast<CCriticalSection*>(&m_csDirWatchInfo), TRUE);
int i(0), max = m_DirectoriesToWatch.GetSize();
CDirWatchInfo * p;
for(; i < max; ++i)
{
if((p = m_DirectoriesToWatch[i]) != NULL
&& p == pWatchInfo)
{
ref_nIdx = i;
return p;
}
}
return NULL;//NOT FOUND
}
CDirectoryChangeWatcher::CDirWatchInfo * CDirectoryChangeWatcher::GetDirWatchInfo(CDirectoryChangeHandler * pChangeHandler, int & ref_nIdx)const
{
ASSERT(pChangeHandler != NULL);
CSingleLock lock(const_cast<CCriticalSection*>(&m_csDirWatchInfo), TRUE);
int i(0),max = m_DirectoriesToWatch.GetSize();
CDirWatchInfo * p;
for(; i < max; ++i)
{
if((p = m_DirectoriesToWatch[i]) != NULL
&& p->GetRealChangeHandler() == pChangeHandler)
{
ref_nIdx = i;
return p;
}
}
return NULL;//NOT FOUND
}
long CDirectoryChangeWatcher::ReleaseReferenceToWatcher(CDirectoryChangeHandler * pChangeHandler)
{
ASSERT(pChangeHandler);
return pChangeHandler->ReleaseReferenceToWatcher(this);
}
CDirectoryChangeWatcher::CDirWatchInfo::CDirWatchInfo(HANDLE hDir,
const CString & strDirectoryName,
CDirectoryChangeHandler * pChangeHandler,
DWORD dwChangeFilter,
BOOL bWatchSubDir,
bool bAppHasGUI,
LPCTSTR szIncludeFilter,
LPCTSTR szExcludeFilter,
DWORD dwFilterFlags)
: m_pChangeHandler(NULL),
m_hDir(hDir),
m_dwChangeFilter(dwChangeFilter),
m_bWatchSubDir(bWatchSubDir),
m_strDirName(strDirectoryName),
m_dwBufLength(0),
m_dwReadDirError(ERROR_SUCCESS),
m_StartStopEvent(FALSE, TRUE), //NOT SIGNALLED, MANUAL RESET
m_RunningState(RUNNING_STATE_NOT_SET)
{
ASSERT(hDir != INVALID_HANDLE_VALUE
&& !strDirectoryName.IsEmpty());
//
// This object 'decorates' the pChangeHandler passed in
// so that notifications fire in the context a thread other than
// CDirectoryChangeWatcher::MonitorDirectoryChanges()
//
// Supports the include and exclude filters
//
//
m_pChangeHandler = new CDelayedDirectoryChangeHandler(pChangeHandler, bAppHasGUI, szIncludeFilter, szExcludeFilter, dwFilterFlags);
if(m_pChangeHandler)
m_pChangeHandler->SetPartialPathOffset(m_strDirName);//to support FILTERS_CHECK_PARTIAL_PATH..this won't change for the duration of the watch, so set it once... HERE!
ASSERT(m_pChangeHandler);
ASSERT(GetChangeHandler());
ASSERT(GetRealChangeHandler());
if(GetRealChangeHandler())
GetRealChangeHandler()->AddRef();
memset(&m_Overlapped, 0, sizeof(m_Overlapped));
//memset(m_Buffer, 0, sizeof(m_Buffer));
}
CDirectoryChangeWatcher::CDirWatchInfo::~CDirWatchInfo()
{
if(GetChangeHandler())
{//If this call to CDirectoryChangeHandler::Release() causes m_pChangeHandler to delete itself,
//the dtor for CDirectoryChangeHandler will call CDirectoryChangeWatcher::UnwatchDirectory(CDirectoryChangeHandler *),
//which will make try to delete this object again.
//if m_pChangeHandler is NULL, it won't try to delete this object again...
CDirectoryChangeHandler * pTmp = SetRealDirectoryChangeHandler(NULL);
if(pTmp)
pTmp->Release();
else{
ASSERT(FALSE);
}
}
CloseDirectoryHandle();
delete m_pChangeHandler;
m_pChangeHandler = NULL;
}
void CDirectoryChangeWatcher::CDirWatchInfo::DeleteSelf(CDirectoryChangeWatcher * pWatcher)
//
// There's a reason for this function!
//
// the dtor is private to enforce that it is used.
//
//
// pWatcher can be NULL only if CDirecotryChangeHandler::ReferencesWatcher() has NOT been called.
// ie: in certain sections of WatchDirectory() it's ok to pass this w/ NULL, but no where else.
//
{
//ASSERT(pWatcher != NULL);
ASSERT(GetRealChangeHandler());
if(pWatcher)
{
//
//
// Before this object is deleted, the CDirectoryChangeHandler object
// needs to release it's reference count to the CDirectoryChangeWatcher object.
// I might forget to do this since I getting rid of CDirWatchInfo objects
// in more than one place...hence the reason for this function.
//
pWatcher->ReleaseReferenceToWatcher(GetRealChangeHandler());
}
delete this;
}
CDelayedDirectoryChangeHandler* CDirectoryChangeWatcher::CDirWatchInfo::GetChangeHandler() const
{
return m_pChangeHandler;
}
CDirectoryChangeHandler * CDirectoryChangeWatcher::CDirWatchInfo::GetRealChangeHandler() const
//
// The 'real' change handler is the CDirectoryChangeHandler object
// passed to CDirectoryChangeWatcher::WatchDirectory() -- this is the object
// that really handles the changes.
//
{
ASSERT(m_pChangeHandler);
return m_pChangeHandler->GetRealChangeHandler();
}
CDirectoryChangeHandler * CDirectoryChangeWatcher::CDirWatchInfo::SetRealDirectoryChangeHandler(CDirectoryChangeHandler * pChangeHandler)
//
// Allows you to switch out, at run time, which object really handles the change notifications.
//
{
CDirectoryChangeHandler * pOld = GetRealChangeHandler();
m_pChangeHandler->GetRealChangeHandler() = pChangeHandler;
return pOld;
}
BOOL CDirectoryChangeWatcher::CDirWatchInfo::CloseDirectoryHandle()
//
// Closes the directory handle that was opened in CDirectoryChangeWatcher::WatchDirecotry()
//
//
{
BOOL b = TRUE;
if(m_hDir != INVALID_HANDLE_VALUE)
{
b = CloseHandle(m_hDir);
m_hDir = INVALID_HANDLE_VALUE;
}
return b;
}
DWORD CDirectoryChangeWatcher::CDirWatchInfo::StartMonitor(HANDLE hCompPort)
/*********************************************
Sets the running state of the object to perform the initial call to ReadDirectoryChangesW()
, wakes up the thread waiting on GetQueuedCompletionStatus()
and waits for an event to be set before returning....
The return value is either ERROR_SUCCESS if ReadDirectoryChangesW is successfull,
or is the value of GetLastError() for when ReadDirectoryChangesW() failed.
**********************************************/
{
ASSERT(hCompPort);
//Guard the properties of this object
VERIFY(LockProperties());
m_RunningState = RUNNING_STATE_START_MONITORING;//set the state member to indicate that the object is to START monitoring the specified directory
PostQueuedCompletionStatus(hCompPort, sizeof(this), (DWORD)this, &m_Overlapped);//make the thread waiting on GetQueuedCompletionStatus() wake up
VERIFY(UnlockProperties());//unlock this object so that the thread can get at them...
//wait for signal that the initial call
//to ReadDirectoryChanges has been made
DWORD dwWait = 0;
do{
dwWait = WaitForSingleObject(m_StartStopEvent, 10 * 1000);
if(dwWait != WAIT_OBJECT_0)
{
//
// shouldn't ever see this one....but just in case you do, notify me of the problem [email protected].
//
TRACE(_T("WARNING! Possible lockup detected. FILE: %s Line: %d\n"), _T(__FILE__), __LINE__);
}
} while(dwWait != WAIT_OBJECT_0);
ASSERT(dwWait == WAIT_OBJECT_0);
m_StartStopEvent.ResetEvent();
return m_dwReadDirError;//This value is set in the worker thread when it first calls ReadDirectoryChangesW().
}
BOOL CDirectoryChangeWatcher::CDirWatchInfo::UnwatchDirectory(HANDLE hCompPort)
/*******************************************
Sets the running state of the object to stop monitoring a directory,
Causes the worker thread to wake up and to stop monitoring the dierctory
********************************************/
{
ASSERT(hCompPort);
//
// Signal that the worker thread is to stop watching the directory
//
if(SignalShutdown(hCompPort))
{
//and wait for the thread to signal that it has shutdown
return WaitForShutdown();
}
return FALSE;
}
BOOL CDirectoryChangeWatcher::CDirWatchInfo::SignalShutdown(HANDLE hCompPort)
//added to fix a bug -- this will be called normally by UnwatchDirectory(HANDLE)
// and abnormally by the worker thread in the case that ReadDirectoryChangesW fails -- see code.
//
// Signals the worker thread(via the I/O completion port) that it is to stop watching the
// directory for this object, and then returns.
//
{
BOOL bRetVal = FALSE;
ASSERT(hCompPort);
ASSERT(m_hDir != INVALID_HANDLE_VALUE);
//Lock the properties so that they aren't modified by another thread
VERIFY(LockProperties()); //unlikey to fail...
//set the state member to indicate that the object is to stop monitoring the
//directory that this CDirWatchInfo is responsible for...
m_RunningState = CDirectoryChangeWatcher::CDirWatchInfo::RUNNING_STATE_STOP;
//put this object in the I/O completion port... GetQueuedCompletionStatus() will return it inside the worker thread.
bRetVal = PostQueuedCompletionStatus(hCompPort, sizeof(CDirWatchInfo*), (DWORD)this, &m_Overlapped);
if(!bRetVal)
{
TRACE(_T("PostQueuedCompletionStatus() failed! GetLastError(): %d\n"), GetLastError());
}
VERIFY(UnlockProperties());
return bRetVal;
}
BOOL CDirectoryChangeWatcher::CDirWatchInfo::WaitForShutdown()
//
// This is to be called some time after SignalShutdown().
//
//
{
ASSERT_VALID(&m_StartStopEvent);
//Wait for the Worker thread to indicate that the watch has been stopped
DWORD dwWait;
bool bWMQuitReceived = false;
do{
dwWait = MsgWaitForMultipleObjects(1, &m_StartStopEvent.m_hObject, FALSE, 5000, QS_ALLINPUT);//wait five seconds
switch(dwWait)
{
case WAIT_OBJECT_0:
//handle became signalled!
break;
case WAIT_OBJECT_0 + 1:
{
//This thread awoke due to sent/posted message
//process the message Q
//
// There is a message in this thread's queue, so
// MsgWaitForMultipleObjects returned.
// Process those messages, and wait again.
MSG msg;
while(PeekMessage(&msg, NULL, 0,0, PM_REMOVE))
{
if(msg.message != WM_QUIT)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
/****
This appears to be causing quite a lot of pain, to quote Mustafa.
//it's the WM_QUIT message, put it back in the Q and
// exit this function
PostMessage(msg.hwnd, msg.message, msg.wParam, msg.lParam);
bWMQuitReceived = true;
****/
break;
}
}
}break;
case WAIT_TIMEOUT:
{
TRACE(_T("WARNING: Possible Deadlock detected! ThreadID: %d File: %s Line: %d\n"), GetCurrentThreadId(), _T(__FILE__), __LINE__);
}break;
}//end switch(dwWait)
}while(dwWait != WAIT_OBJECT_0 && !bWMQuitReceived);
ASSERT(dwWait == WAIT_OBJECT_0 || bWMQuitReceived);
m_StartStopEvent.ResetEvent();
return (BOOL) (dwWait == WAIT_OBJECT_0 || bWMQuitReceived);
}
void CDirectoryChangeWatcher::MonitorDirectoryChanges(LPVOID lpvThis)
/********************************************
The worker thread function which monitors directory changes....
********************************************/
{
DWORD numBytes;
CDirWatchInfo * pdi;
LPOVERLAPPED lpOverlapped;
CDirectoryChangeWatcher * pThis = reinterpret_cast<CDirectoryChangeWatcher*>(lpvThis);
ASSERT(pThis);
pThis->On_ThreadInitialize();
do
{
// Retrieve the directory info for this directory
// through the io port's completion key
if(!GetQueuedCompletionStatus(pThis->m_hCompPort,
&numBytes,
(LPDWORD) &pdi,//<-- completion Key
&lpOverlapped,
INFINITE))
{//The io completion request failed...
//probably because the handle to the directory that
//was used in a call to ReadDirectoryChangesW has been closed.
//
// calling pdi->CloseDirectoryHandle() will cause GetQueuedCompletionStatus() to return false.
//
//
if(!pdi
|| (pdi && AfxIsValidAddress(pdi, sizeof(CDirectoryChangeWatcher::CDirWatchInfo)))
&& pdi->m_hDir != INVALID_HANDLE_VALUE //the directory handle is still open! (we expect this when after we close the directory handle)
)
{
#ifdef BTDEBUG
TRACE(_T("GetQueuedCompletionStatus() returned FALSE\nGetLastError(): %d Completion Key: %p lpOverlapped: %p\n"), GetLastError(), pdi, lpOverlapped);
MessageBeep(static_cast<UINT>(-1));
#endif
}
}
if (pdi)//pdi will be null if I call PostQueuedCompletionStatus(m_hCompPort, 0,0,NULL);
{
//
// The following check to AfxIsValidAddress() should go off in the case
// that I have deleted this CDirWatchInfo object, but it was still in
// "in the Queue" of the i/o completion port from a previous overlapped operation.
//
ASSERT(AfxIsValidAddress(pdi,
sizeof(CDirectoryChangeWatcher::CDirWatchInfo)));
/***********************************
The CDirWatchInfo::m_RunningState is pretty much the only member
of CDirWatchInfo that can be modified from the other thread.
The functions StartMonitor() and UnwatchDirecotry() are the functions that
can modify that variable.
So that I'm sure that I'm getting the right value,
I'm using a critical section to guard against another thread modyfying it when I want
to read it...
************************************/
bool bObjectShouldBeOk = true;
try{
VERIFY(pdi->LockProperties());//don't give the main thread a chance to change this object
}
catch(...){
//any sort of exception here indicates I've
//got a hosed object.
TRACE(_T("CDirectoryChangeWatcher::MonitorDirectoryChanges() -- pdi->LockProperties() raised an exception!\n"));
bObjectShouldBeOk = false;
}
if(bObjectShouldBeOk)
{
//while we're working with this object...
CDirWatchInfo::eRunningState Run_State = pdi->m_RunningState ;
VERIFY(pdi->UnlockProperties());//let another thread back at the properties...
/***********************************
Unlock it so that there isn't a DEADLOCK if
somebody tries to call a function which will
cause CDirWatchInfo::UnwatchDirectory() to be called
from within the context of this thread (eg: a function called because of
the handler for one of the CDirectoryChangeHandler::onFilexxx() functions)
************************************/
ASSERT(pdi->GetChangeHandler());
switch(Run_State)
{
case CDirWatchInfo::RUNNING_STATE_START_MONITORING:
{
//Issue the initial call to ReadDirectoryChangesW()
if(!ReadDirectoryChangesW(pdi->m_hDir,
pdi->m_Buffer,//<--FILE_NOTIFY_INFORMATION records are put into this buffer
READ_DIR_CHANGE_BUFFER_SIZE,
pdi->m_bWatchSubDir,
pdi->m_dwChangeFilter,
&pdi->m_dwBufLength,//this var not set when using asynchronous mechanisms...
&pdi->m_Overlapped,
NULL))//no completion routine!
{
pdi->m_dwReadDirError = GetLastError();
if(pdi->GetChangeHandler())
pdi->GetChangeHandler()->onWatchStarted(pdi->m_dwReadDirError, pdi->m_strDirName);
}
else
{//read directory changes was successful!
//allow it to run normally
pdi->m_RunningState = CDirWatchInfo::RUNNING_STATE_NORMAL;
pdi->m_dwReadDirError = ERROR_SUCCESS;
if(pdi->GetChangeHandler())
pdi->GetChangeHandler()->onWatchStarted(ERROR_SUCCESS, pdi->m_strDirName);
}
pdi->m_StartStopEvent.SetEvent();//signall that the ReadDirectoryChangesW has been called
//check CDirWatchInfo::m_dwReadDirError to see whether or not ReadDirectoryChangesW succeeded...
//
// note that pdi->m_dwReadDirError is the value returned by WatchDirectory()
//
}break;
case CDirWatchInfo::RUNNING_STATE_STOP:
{
//We want to shut down the monitoring of the directory
//that pdi is managing...
if(pdi->m_hDir != INVALID_HANDLE_VALUE)
{
//Since I've previously called ReadDirectoryChangesW() asynchronously, I am waiting
//for it to return via GetQueuedCompletionStatus(). When I close the
//handle that ReadDirectoryChangesW() is waiting on, it will
//cause GetQueuedCompletionStatus() to return again with this pdi object....
// Close the handle, and then wait for the call to GetQueuedCompletionStatus()
//to return again by breaking out of the switch, and letting GetQueuedCompletionStatus()
//get called again
pdi->CloseDirectoryHandle();
pdi->m_RunningState = CDirWatchInfo::RUNNING_STATE_STOP_STEP2;//back up step...GetQueuedCompletionStatus() will still need to return from the last time that ReadDirectoryChangesW() was called.....
//
// The watch has been stopped, tell the client about it
// if(pdi->GetChangeHandler())
pdi->GetChangeHandler()->onWatchStopped(pdi->m_strDirName);
}
else
{
//either we weren't watching this direcotry in the first place,
//or we've already stopped monitoring it....
pdi->m_StartStopEvent.SetEvent();//set the event that ReadDirectoryChangesW has returned and no further calls to it will be made...
}
}break;
case CDirWatchInfo::RUNNING_STATE_STOP_STEP2:
{
//GetQueuedCompletionStatus() has returned from the last
//time that ReadDirectoryChangesW was called...
//Using CloseHandle() on the directory handle used by
//ReadDirectoryChangesW will cause it to return via GetQueuedCompletionStatus()....
if(pdi->m_hDir == INVALID_HANDLE_VALUE)
pdi->m_StartStopEvent.SetEvent();//signal that no further calls to ReadDirectoryChangesW will be made
//and this pdi can be deleted
else
{//for some reason, the handle is still open..
pdi->CloseDirectoryHandle();
//wait for GetQueuedCompletionStatus() to return this pdi object again
}
}break;
case CDirWatchInfo::RUNNING_STATE_NORMAL:
{
if(pdi->GetChangeHandler())
pdi->GetChangeHandler()->SetChangedDirectoryName(pdi->m_strDirName);
DWORD dwReadBuffer_Offset = 0UL;
//process the FILE_NOTIFY_INFORMATION records:
CFileNotifyInformation notify_info((LPBYTE)pdi->m_Buffer, READ_DIR_CHANGE_BUFFER_SIZE);
pThis->ProcessChangeNotifications(notify_info, pdi, dwReadBuffer_Offset);
// Changes have been processed,
// Reissue the watch command
//
if(!ReadDirectoryChangesW(pdi->m_hDir,
pdi->m_Buffer + dwReadBuffer_Offset,//<--FILE_NOTIFY_INFORMATION records are put into this buffer
READ_DIR_CHANGE_BUFFER_SIZE - dwReadBuffer_Offset,
pdi->m_bWatchSubDir,
pdi->m_dwChangeFilter,
&pdi->m_dwBufLength,//this var not set when using asynchronous mechanisms...
&pdi->m_Overlapped,
NULL))//no completion routine!
{
//
// NOTE:
// In this case the thread will not wake up for
// this pdi object because it is no longer associated w/
// the I/O completion port...there will be no more outstanding calls to ReadDirectoryChangesW
// so I have to skip the normal shutdown routines(normal being what happens when CDirectoryChangeWatcher::UnwatchDirectory() is called.
// and close this up, & cause it to be freed.
//
TRACE(_T("WARNING: ReadDirectoryChangesW has failed during normal operations...failed on directory: %s\n"), pdi->m_strDirName);
ASSERT(pThis);
//
// To help insure that this has been unwatched by the time
// the main thread processes the onReadDirectoryChangesError() notification
// bump the thread priority up temporarily. The reason this works is because the notification
// is really posted to another thread's message queue,...by setting this thread's priority
// to highest, this thread will get to shutdown the watch by the time the other thread has a chance
// to handle it. *note* not technically guaranteed 100% to be the case, but in practice it'll work.
int nOldThreadPriority = GetThreadPriority(GetCurrentThread());
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
//
// Notify the client object....(a CDirectoryChangeHandler derived class)
//
try{
pdi->m_dwReadDirError = GetLastError();
pdi->GetChangeHandler()->onReadDirectoryChangesError(pdi->m_dwReadDirError, pdi->m_strDirName);
//Do the shutdown
pThis->UnwatchDirectoryBecauseOfError(pdi);
//pdi = NULL; <-- DO NOT set this to NULL, it will cause this worker thread to exit.
//pdi is INVALID at this point!!
}
catch(...)
{
//just in case of exception, this thread will be set back to
//normal priority.
}
//
// Set the thread priority back to normal.
//
SetThreadPriority(GetCurrentThread(), nOldThreadPriority);
}
else
{//success, continue as normal
pdi->m_dwReadDirError = ERROR_SUCCESS;
}
}break;
default:
TRACE(_T("MonitorDirectoryChanges() -- how did I get here?\n"));
break;//how did I get here?
}//end switch(pdi->m_RunningState)
}//end if(bObjectShouldBeOk)
}//end if(pdi)
} while(pdi);
pThis->On_ThreadExit();
}
void CDirectoryChangeWatcher::ProcessChangeNotifications(IN CFileNotifyInformation & notify_info,
IN CDirectoryChangeWatcher::CDirWatchInfo * pdi,
OUT DWORD & ref_dwReadBuffer_Offset//used in case ...see case for FILE_ACTION_RENAMED_OLD_NAME
)
/////////////////////////////////////////////////////////////
//
// Processes the change notifications and dispatches the handling of the
// notifications to the CDirectoryChangeHandler object passed to WatchDirectory()
//
/////////////////////////////////////////////////////////////
{
//
// Sanity check...
// this function should only be called by the worker thread.
//
ASSERT(m_dwThreadID == GetCurrentThreadId());
// Validate parameters...
//
ASSERT(pdi);
ASSERT(AfxIsValidAddress(pdi, sizeof(CDirectoryChangeWatcher::CDirWatchInfo)));
if(!pdi || !AfxIsValidAddress(pdi, sizeof(CDirectoryChangeWatcher::CDirWatchInfo)))
{
TRACE(_T("Invalid arguments to CDirectoryChangeWatcher::ProcessChangeNotifications() -- pdi is invalid!\n"));
TRACE(_T("File: %s Line: %d"), _T(__FILE__), __LINE__);
return;
}
DWORD dwLastAction = 0;
ref_dwReadBuffer_Offset = 0UL;
CDirectoryChangeHandler * pChangeHandler = pdi->GetChangeHandler();
//CDelayedDirectoryChangeHandler * pChangeHandler = pdi->GetChangeHandler();
ASSERT(pChangeHandler);
ASSERT(AfxIsValidAddress(pChangeHandler, sizeof(CDirectoryChangeHandler)));
//ASSERT(AfxIsValidAddress(pChangeHandler, sizeof(CDelayedDirectoryChangeHandler)));
if(!pChangeHandler)
{
TRACE(_T("CDirectoryChangeWatcher::ProcessChangeNotifications() Unable to continue, pdi->GetChangeHandler() returned NULL!\n"));
TRACE(_T("File: %s Line: %d\n"), _T(__FILE__), __LINE__);
return;
}
//
// go through and process the notifications contained in the
// CFileChangeNotification object(CFileChangeNotification is a wrapper for the FILE_NOTIFY_INFORMATION structure
// returned by ReadDirectoryChangesW)
//
do
{
//The FileName member of the FILE_NOTIFY_INFORMATION
//structure contains the NAME of the file RELATIVE to the
//directory that is being watched...
//ie, if watching C:\Temp and the file C:\Temp\MyFile.txt is changed,
//the file name will be "MyFile.txt"
//If watching C:\Temp, AND you're also watching subdirectories
//and the file C:\Temp\OtherFolder\MyOtherFile.txt is modified,
//the file name will be "OtherFolder\MyOtherFile.txt
//The CDirectoryChangeHandler::onFilexxx() functions will receive the name of the file
//which includes the full path to the directory being watched
//
// See what the change was
//
switch(notify_info.GetAction())
{
case FILE_ACTION_ADDED: // a file was added!
pChangeHandler->onFileAdded(notify_info.GetFileNameWithPath(pdi->m_strDirName)); break;
case FILE_ACTION_REMOVED: //a file was removed
pChangeHandler->onFileRemoved(notify_info.GetFileNameWithPath(pdi->m_strDirName)); break;
case FILE_ACTION_MODIFIED:
//a file was changed
//pdi->m_pChangeHandler->onFileModified(strLastFileName); break;
pChangeHandler->onFileModified(notify_info.GetFileNameWithPath(pdi->m_strDirName)); break;
case FILE_ACTION_RENAMED_OLD_NAME:
{//a file name has changed, and this is the OLD name
//This record is followed by another one w/
//the action set to FILE_ACTION_RENAMED_NEW_NAME (contains the new name of the file
CString strOldFileName = notify_info.GetFileNameWithPath(pdi->m_strDirName);
if(notify_info.GetNextNotifyInformation())
{//there is another PFILE_NOTIFY_INFORMATION record following the one we're working on now...
//it will be the record for the FILE_ACTION_RENAMED_NEW_NAME record
ASSERT(notify_info.GetAction() == FILE_ACTION_RENAMED_NEW_NAME);//making sure that the next record after the OLD_NAME record is the NEW_NAME record
//get the new file name
CString strNewFileName = notify_info.GetFileNameWithPath(pdi->m_strDirName);
pChangeHandler->onFileNameChanged(strOldFileName, strNewFileName);
}
else
{
//this OLD_NAME was the last record returned by ReadDirectoryChangesW
//I will have to call ReadDirectoryChangesW again so that I will get
//the record for FILE_ACTION_RENAMED_NEW_NAME
//Adjust an offset so that when I call ReadDirectoryChangesW again,
//the FILE_NOTIFY_INFORMATION will be placed after
//the record that we are currently working on.
/***************
Let's say that 200 files all had their names changed at about the same time
There will be 400 FILE_NOTIFY_INFORMATION records (one for OLD_NAME and one for NEW_NAME for EACH file which had it's name changed)
that ReadDirectoryChangesW will have to report to
me. There might not be enough room in the buffer
and the last record that we DID get was an OLD_NAME record,
I will need to call ReadDirectoryChangesW again so that I will get the NEW_NAME
record. This way I'll always have to strOldFileName and strNewFileName to pass
to CDirectoryChangeHandler::onFileRenamed().
After ReadDirecotryChangesW has filled out our buffer with
FILE_NOTIFY_INFORMATION records,
our read buffer would look something like this:
End Of Buffer
|
\-/
|_________________________________________________________________________
| |
|file1 OLD name record|file1 NEW name record|...|fileX+1 OLD_name record| |(the record we want would be here, but we've ran out of room, so we adjust an offset and call ReadDirecotryChangesW again to get it)
|_________________________________________________________________________|
Since the record I need is still waiting to be returned to me,
and I need the current 'OLD_NAME' record,
I'm copying the current FILE_NOTIFY_INFORMATION record
to the beginning of the buffer used by ReadDirectoryChangesW()
and I adjust the offset into the read buffer so the the NEW_NAME record
will be placed into the buffer after the OLD_NAME record now at the beginning of the buffer.
Before we call ReadDirecotryChangesW again,
modify the buffer to contain the current OLD_NAME record...
|_______________________________________________________
| |
|fileX old name record(saved)|<this is now garbage>.....|
|_______________________________________________________|
/-\
|
Offset for Read
Re-issue the watch command to get the rest of the records...
ReadDirectoryChangesW(..., pBuffer + (an Offset),
After GetQueuedCompletionStatus() returns,
our buffer will look like this:
|__________________________________________________________________________________________________________
| |
|fileX old name record(saved)|fileX new name record(the record we've been waiting for)| <other records>... |
|__________________________________________________________________________________________________________|
Then I'll be able to know that a file name was changed
and I will have the OLD and the NEW name of the file to pass to CDirectoryChangeHandler::onFileNameChanged
****************/
//NOTE that this case has never happened to me in my testing
//so I can only hope that the code works correctly.
//It would be a good idea to set a breakpoint on this line of code:
VERIFY(notify_info.CopyCurrentRecordToBeginningOfBuffer(ref_dwReadBuffer_Offset));
}
break;
}
case FILE_ACTION_RENAMED_NEW_NAME:
{
//This should have been handled in FILE_ACTION_RENAMED_OLD_NAME
ASSERT(dwLastAction == FILE_ACTION_RENAMED_OLD_NAME);
ASSERT(FALSE);//this shouldn't get here
}
default:
TRACE(_T("CDirectoryChangeWatcher::ProcessChangeNotifications() -- unknown FILE_ACTION_ value! : %d\n"), notify_info.GetAction());
break;//unknown action
}
dwLastAction = notify_info.GetAction();
} while(notify_info.GetNextNotifyInformation());
}
DirectoryChangeWatcher::DirectoryChangeWatcher() : watcher(new CDirectoryChangeWatcher()) { }
DirectoryChangeWatcher::~DirectoryChangeWatcher() { delete watcher; }
DWORD DirectoryChangeWatcher::WatchDirectory(const TCHAR * strDirToWatch,
DWORD dwChangesToWatchFor, CDirectoryChangeHandler * pChangeHandler,
BOOL bWatchSubDirs, LPCTSTR szIncludeFilter, LPCTSTR szExcludeFilter)
{
return watcher->WatchDirectory(strDirToWatch, dwChangesToWatchFor, pChangeHandler, bWatchSubDirs,
szIncludeFilter, szExcludeFilter);
}
BOOL DirectoryChangeWatcher::UnwatchDirectory(const TCHAR * strDirToStopWatching)
{
return watcher->UnwatchDirectory(strDirToStopWatching);
} | {
"pile_set_name": "Github"
} |
<?php
/**
* 2007-2016 [PagSeguro Internet Ltda.]
*
* NOTICE OF LICENSE
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author PagSeguro Internet Ltda.
* @copyright 2007-2016 PagSeguro Internet Ltda.
* @license http://www.apache.org/licenses/LICENSE-2.0
*
*/
namespace PagSeguro\Helpers;
class Crypto
{
private static $list = [
"senderPhone" => array("phone", \PagSeguro\Enum\Mask::PHONE),
"senderCPF" => array("cpf", \PagSeguro\Enum\Mask::CPF)
];
public static function encrypt($parameters)
{
foreach (self::$list as $param => $value) {
if (array_key_exists($param, $parameters)) {
$parameters[$param] = Mask::{current($value)}($parameters[$param], ["type" => end($value)]);
}
}
return $parameters;
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package runtime
const (
_AT_NULL = 0
_AT_RANDOM = 25
)
| {
"pile_set_name": "Github"
} |
/// Copyright (c) 2012 Ecma International. All rights reserved.
/**
* @path ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-138.js
* @description Object.getOwnPropertyDescriptor returns data desc for functions on built-ins (Date.prototype.setFullYear)
*/
function testcase() {
var desc = Object.getOwnPropertyDescriptor(Date.prototype, "setFullYear");
if (desc.value === Date.prototype.setFullYear &&
desc.writable === true &&
desc.enumerable === false &&
desc.configurable === true) {
return true;
}
}
runTestCase(testcase);
| {
"pile_set_name": "Github"
} |
/***********************************************************************
Copyright (c) 2006-2011, Skype Limited. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of Internet Society, IETF or IETF Trust, nor the
names of specific 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.
***********************************************************************/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "main_FLP.h"
/* Apply sine window to signal vector */
/* Window types: */
/* 1 -> sine window from 0 to pi/2 */
/* 2 -> sine window from pi/2 to pi */
void silk_apply_sine_window_FLP(
silk_float px_win[], /* O Pointer to windowed signal */
const silk_float px[], /* I Pointer to input signal */
const opus_int win_type, /* I Selects a window type */
const opus_int length /* I Window length, multiple of 4 */
)
{
opus_int k;
silk_float freq, c, S0, S1;
silk_assert( win_type == 1 || win_type == 2 );
/* Length must be multiple of 4 */
silk_assert( ( length & 3 ) == 0 );
freq = PI / ( length + 1 );
/* Approximation of 2 * cos(f) */
c = 2.0f - freq * freq;
/* Initialize state */
if( win_type < 2 ) {
/* Start from 0 */
S0 = 0.0f;
/* Approximation of sin(f) */
S1 = freq;
} else {
/* Start from 1 */
S0 = 1.0f;
/* Approximation of cos(f) */
S1 = 0.5f * c;
}
/* Uses the recursive equation: sin(n*f) = 2 * cos(f) * sin((n-1)*f) - sin((n-2)*f) */
/* 4 samples at a time */
for( k = 0; k < length; k += 4 ) {
px_win[ k + 0 ] = px[ k + 0 ] * 0.5f * ( S0 + S1 );
px_win[ k + 1 ] = px[ k + 1 ] * S1;
S0 = c * S1 - S0;
px_win[ k + 2 ] = px[ k + 2 ] * 0.5f * ( S1 + S0 );
px_win[ k + 3 ] = px[ k + 3 ] * S0;
S1 = c * S0 - S1;
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfDVBTTuning xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<DVBTTuning>
<Frequency>562000</Frequency>
<BandWidth>8</BandWidth>
<Offset>125</Offset>
</DVBTTuning>
<DVBTTuning>
<Frequency>658000</Frequency>
<BandWidth>8</BandWidth>
<Offset>125</Offset>
</DVBTTuning>
<DVBTTuning>
<Frequency>674000</Frequency>
<BandWidth>8</BandWidth>
<Offset>125</Offset>
</DVBTTuning>
</ArrayOfDVBTTuning> | {
"pile_set_name": "Github"
} |
/*
* DialogConnectionList1.java
*
* $Id$
*
* URL picklist
*
* This file is part of the OpenLink Software Virtuoso Open-Source (VOS)
* project.
*
* Copyright (C) 1998-2020 OpenLink Software
*
* This project 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; only version 2 of the License, dated June 1991.
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*
*
*/
import java.awt.*;
import java.awt.event.*;
class DialogConnectionList1 extends Dialog implements ActionListener
{
List urlList;
Panel panel1, panel2, panel3;
Label label1, label2, label3, label4;
Button buttonOK;
Button buttonCancel;
TextField textUser, textPass, textDb;
boolean OK = false;
String Database;
String User;
String Password;
String SelectedItem;
public DialogConnectionList1(Frame parent, boolean modal, String paramList[])
{
super(parent, modal);
this.enableEvents(AWTEvent.WINDOW_EVENT_MASK);
setSize(getInsets().left + getInsets().right + 400,getInsets().top + getInsets().bottom +250);
setBackground(new Color(12632256));
GridBagLayout gbl = new GridBagLayout();
setLayout(gbl);
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(2,2,2,2);
gbc.fill = GridBagConstraints.VERTICAL;
gbc.anchor = GridBagConstraints.WEST;
gbc.weightx = 1;
label1 = new java.awt.Label("Choose URL:");
gbl.setConstraints(label1,gbc);
add(label1);
panel1 = new java.awt.Panel();
gbc.gridwidth=GridBagConstraints.REMAINDER ;
gbl.setConstraints(panel1,gbc);
add(panel1);
urlList = new java.awt.List();
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.CENTER;
gbl.setConstraints(urlList,gbc);
add(urlList);
panel2 = new java.awt.Panel();
gbc.weighty = 0;
gbc.gridwidth=1;
gbc.fill = GridBagConstraints.BOTH;
gbl.setConstraints(panel2,gbc);
add(panel2);
label4 = new java.awt.Label("Database:");
gbc.gridwidth=1;
gbl.setConstraints(label4,gbc);
add(label4);
textDb = new java.awt.TextField();
gbc.gridwidth=GridBagConstraints.REMAINDER ;
gbl.setConstraints(textDb,gbc);
add(textDb);
label2 = new java.awt.Label("Username:");
gbc.gridwidth=1;
gbl.setConstraints(label2,gbc);
add(label2);
textUser = new java.awt.TextField();
gbc.gridwidth=GridBagConstraints.REMAINDER ;
gbl.setConstraints(textUser,gbc);
add(textUser);
label3 = new java.awt.Label("Password:");
gbc.gridwidth=1;
gbl.setConstraints(label3,gbc);
add(label3);
textPass = new java.awt.TextField();
textPass.setEchoChar('*');
gbc.gridwidth=GridBagConstraints.REMAINDER ;
gbl.setConstraints(textPass,gbc);
add(textPass);
panel3 = new java.awt.Panel();
gbc.gridwidth=1;
gbc.fill = GridBagConstraints.BOTH;
gbl.setConstraints(panel2,gbc);
add(panel2);
buttonOK = new java.awt.Button("OK");
buttonOK.addActionListener(this);
gbl.setConstraints(buttonOK,gbc);
add(buttonOK);
buttonCancel = new java.awt.Button("Cancel");
buttonCancel.addActionListener(this);
gbl.setConstraints(buttonCancel,gbc);
add(buttonCancel);
setTitle("Pick Connection URL");
if (paramList != null && paramList.length >0)
{
for (int i = 0; i < paramList.length; i++)
urlList.add(paramList[i]);
}
}
public void show()
{
Rectangle bounds = getParent().getBounds();
Rectangle abounds = getBounds();
setLocation(bounds.x + (bounds.width - abounds.width)/ 2,
bounds.y + (bounds.height - abounds.height)/2);
super.show();
}
/**Overridden so we can exit when window is closed*/
protected void processWindowEvent(WindowEvent e) {
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
hide();
}
super.processWindowEvent(e);
}
public void actionPerformed(ActionEvent e) {
Object c = e.getSource();
if (c == buttonOK) {
OK = true;
SelectedItem = urlList.getSelectedItem();
Database = textDb.getText();
User = textUser.getText();
Password = textPass.getText();
hide();
}
else
if (c == buttonCancel) {
hide();
}
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2019 Google LLC. 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.
*/
// [START maps_layer_data_event]
let map: google.maps.Map;
function initMap(): void {
map = new google.maps.Map(document.getElementById("map") as HTMLElement, {
zoom: 4,
center: { lat: -28, lng: 137 },
});
// Load GeoJSON.
map.data.loadGeoJson(
"https://storage.googleapis.com/maps-devrel/google.json"
);
// Add some style.
map.data.setStyle((feature) => {
return /** @type {google.maps.Data.StyleOptions} */ {
fillColor: feature.getProperty("color"),
strokeWeight: 1,
};
});
// [START maps_layer_data_event_snippet]
// Set mouseover event for each feature.
map.data.addListener("mouseover", (event) => {
(document.getElementById(
"info-box"
) as HTMLElement).textContent = event.feature.getProperty("letter");
});
// [END maps_layer_data_event_snippet]
}
// [END maps_layer_data_event]
export { initMap };
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS};
/// https://url.spec.whatwg.org/#fragment-percent-encode-set
const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`');
/// https://url.spec.whatwg.org/#path-percent-encode-set
const PATH: &AsciiSet = &FRAGMENT.add(b'#').add(b'?').add(b'{').add(b'}');
const USERINFO: &AsciiSet = &PATH
.add(b'/')
.add(b':')
.add(b';')
.add(b'=')
.add(b'@')
.add(b'[')
.add(b'\\')
.add(b']')
.add(b'^')
.add(b'|');
pub const HG_ENCODE_SET: &AsciiSet = &USERINFO.add(b',');
pub fn percent_encode(input: &str) -> String {
// This encode set doesn't exactly match what Python's urllib does, but it's
// close enough and importantly it encodes '=' which is the only important
// one.
utf8_percent_encode(input, HG_ENCODE_SET).collect::<String>()
}
| {
"pile_set_name": "Github"
} |
/**
Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
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
FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import IGListKit
protocol SearchSectionControllerDelegate: class {
func searchSectionController(_ sectionController: SearchSectionController, didChangeText text: String)
}
final class SearchSectionController: ListSectionController, UISearchBarDelegate, ListScrollDelegate {
weak var delegate: SearchSectionControllerDelegate?
override init() {
super.init()
scrollDelegate = self
}
override func sizeForItem(at index: Int) -> CGSize {
return CGSize(width: collectionContext!.containerSize.width, height: 44)
}
override func cellForItem(at index: Int) -> UICollectionViewCell {
guard let cell = collectionContext?.dequeueReusableCell(of: SearchCell.self, for: self, at: index) as? SearchCell else {
fatalError()
}
cell.searchBar.delegate = self
return cell
}
// MARK: UISearchBarDelegate
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
delegate?.searchSectionController(self, didChangeText: searchText)
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
delegate?.searchSectionController(self, didChangeText: searchBar.text!)
}
// MARK: ListScrollDelegate
func listAdapter(_ listAdapter: ListAdapter, didScroll sectionController: ListSectionController) {
if let searchBar = (collectionContext?.cellForItem(at: 0, sectionController: self) as? SearchCell)?.searchBar {
searchBar.resignFirstResponder()
}
}
func listAdapter(_ listAdapter: ListAdapter, willBeginDragging sectionController: ListSectionController) {}
func listAdapter(_ listAdapter: ListAdapter,
didEndDragging sectionController: ListSectionController,
willDecelerate decelerate: Bool) {}
}
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.